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.yml b/.github/workflows/build.yml index c3b3f50cf6..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,23 +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: @@ -685,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: 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 a1094c8d14..71024514c4 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - 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. 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`. diff --git a/app/build.gradle b/app/build.gradle index 634a41eec0..f2cb40169b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -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" @@ -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/PreviewSupport.kt b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt index fc83727e11..96a958e719 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt @@ -61,7 +61,7 @@ internal val sampleActions: FrontEndActions = FrontEndActions( onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) /** The in-game menu's actions with settled sample values; its switches do nothing. */ diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 38c13055be..461a0d6798 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -737,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) @@ -894,6 +899,7 @@ 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; @@ -949,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) { @@ -1025,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))) { @@ -1050,9 +1058,12 @@ 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++; 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(); } } diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index a843500c95..74cd5d6b45 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -163,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; @@ -487,7 +488,8 @@ 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, @@ -560,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; } diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 7184ff644f..61b2765c5b 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -1494,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; } diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 4dc2f2c08c..308332f9b1 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -63,6 +63,7 @@ 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; @@ -84,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; } @@ -154,6 +156,13 @@ 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; diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index be2deadbed..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) 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/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index af3eddf8e7..a26bb5d81e 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -53,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 @@ -215,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()) @@ -254,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) } @@ -375,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) + } } } @@ -627,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)) } } @@ -642,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() @@ -652,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() } @@ -707,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) @@ -883,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) @@ -909,12 +924,24 @@ 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) { @@ -925,7 +952,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet 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 } @@ -938,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 @@ -951,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) @@ -959,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() } } @@ -973,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) { @@ -1048,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 } @@ -1208,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() @@ -1231,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) { @@ -1243,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) @@ -1345,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, @@ -1392,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( @@ -1412,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() @@ -1666,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 -> @@ -1763,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) } @@ -1804,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 }, @@ -1911,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() @@ -1952,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 @@ -1965,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)) { @@ -1995,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") @@ -2143,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()) @@ -2166,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 @@ -2217,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) } @@ -2233,21 +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() { + // 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() - gameLaunchRequest.incrementAndGet() + launchCoordinator.cancelAll() cancelCompatLaunch() updates.unregister() runCatching { unregisterReceiver(shortcutsInstallStatus) } @@ -2267,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) @@ -2308,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) @@ -2323,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() } } @@ -2664,6 +2772,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet 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, @@ -3086,10 +3195,12 @@ 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 @@ -3111,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() } @@ -3209,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) @@ -3334,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() @@ -3346,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 } @@ -3355,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( @@ -3368,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) } @@ -3414,7 +3585,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet 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() } @@ -3430,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 @@ -3450,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() } @@ -3461,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) } } @@ -3480,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 a209bac123..7deb31a83e 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -850,8 +850,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde 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) @@ -875,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 @@ -936,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 @@ -1550,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 @@ -2996,16 +2996,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this) - private fun followScale(): Float { - val mode = displayMode() - val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait()) - return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f - } - - 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), followPortrait())) + 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) { @@ -3019,6 +3013,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionService.setActivityDisplay(this, sessionActivityDisplayId) } cancelTouchGestures() + applyFollowChoice() applyFollowOrientation(newConfig) applyNotchInset() applyUnfoldedControls() @@ -3553,6 +3548,15 @@ 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 -> { @@ -4410,6 +4414,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde 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) 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/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/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/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/DualScreen.kt b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt index a4de922ca7..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") @@ -99,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/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/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, canonical: (String) -> String): List = + 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() 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, - kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), + kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), glIcd: Boolean = false, ): List? { - 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, socket: String): List? { + 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, socket: String, glIcd: Boolean): List? { 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() @@ -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 = + 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/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? = 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/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 = emptyList()): Map = linkedMapOf( + fun environment(root: File, program: String, preload: List = emptyList()): Map = 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): List { + fun command(root: File, program: String, args: List, libraryPath: String = libraryPath(root)): List { 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, hostname: String? = null): Map { + fun sessionEnvironment(root: File, binds: List, program: String, hostname: String? = null): Map { 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, env: Map, preload: List = 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/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/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/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 { + internal class Link 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? = 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? = 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/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>(emptyMap()) + val failed = MutableStateFlow>(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, failed: Map, facts: Facts): List = 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): 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): Int { + val measured = measure(rows) + if (!pending(rows)) { + highWater = 0 + return measured + } + highWater = maxOf(highWater, measured) + return highWater + } + + internal fun measure(rows: List): 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/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? = 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(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( + private val queue: QueuedLaunch, + 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, 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) { + 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? = runCatching { - File(dir, LOG_MARKS).readLines().mapNotNull { line -> + private fun logMarks(dir: File, marks: String): List? = 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 = 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 = copySessionLogsResult(logs, dir, out, openWriter) { false }.files + ): List = 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() 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/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 1645851229..177774a4ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -95,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) @@ -126,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", @@ -258,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('/') 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 422db659f6..8889ccb261 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -502,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() } @@ -807,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") @@ -1336,6 +1348,10 @@ object SessionPrefs { SessionDisplay.effectiveChoice( resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait) + fun followScales(context: Context, mode: String, panel: Pair): Pair = + SessionDisplay.followScale(resolutionChoice(context, mode, panel, false)) to + SessionDisplay.followScale(resolutionChoice(context, mode, panel, true)) + fun resolutionStored(context: Context, mode: String, panel: Pair, portrait: Boolean): String { if (!portrait) return landscapeResolutionStored(context, mode, panel) val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE @@ -1546,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 } 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 15d2844d34..f7af8ff9ae 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -784,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 @@ -1070,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") @@ -2705,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 e695f8b932..92255febec 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -148,6 +148,9 @@ object SessionState { @Volatile var outputSize: Pair = Pair(1920, 1080) + @Volatile + var followScales: Pair = null to null + @Volatile var followScreen = false var followScale = 1f 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? { + 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, 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/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, remote: Map, baseline: Map?): Plan { + fun up(local: Map, remote: Map, baseline: Map?, deleted: Set = emptySet()): Plan { if (baseline == null) return Plan(emptyList(), emptyList(), emptyList(), refused = "no-baseline") val transfer = ArrayList(); val conflicts = ArrayList(); val same = ArrayList() 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 { + private class Listing(val live: Map, val deleted: Set) + + 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 fun details(file: CloudFile) {} fun get(file: CloudFile): Pair @@ -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 { 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/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() 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/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(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(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/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(1) } + val moves = remember { intArrayOf(0) } + val move = remember { arrayOfNulls(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, grid: LazyGridState, leadItems: Int, modifier: Modifier) { val colors = MaterialTheme.colorScheme 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/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 = - 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): List { + 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/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index c2f49c2ef2..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 = emptyList(), val secondScreenDisplays: List = emptyList(), + val ownScreen: SecondScreenDisplay? = null, val dualScreen: Boolean = false, val dualScreenDevice: Boolean = false, val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO, @@ -313,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(), ) @@ -508,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(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 @@ -526,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 @@ -542,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) { @@ -802,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, ) } @@ -823,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, @@ -838,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, @@ -846,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, ) } } @@ -906,6 +894,10 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } } +internal object ChildProcessSetup { + @Volatile var request: (() -> Unit)? = null +} + internal object MainTabSteps { @Volatile var handler: ((Int) -> Unit)? = null } 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 70c49a5518..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 -> @@ -540,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), @@ -1096,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 @@ -1147,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)) } } } @@ -1273,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 faa4667306..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,10 +205,12 @@ 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 @@ -234,6 +236,11 @@ 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) 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 79ee2d8491..f06c43851c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -38,8 +38,10 @@ 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 @@ -581,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) @@ -663,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 @@ -678,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) { @@ -699,6 +718,7 @@ class InputSurfaceView( override fun onDetachedFromWindow() { setClick(false) if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f) + redraw.cancel() super.onDetachedFromWindow() } } @@ -766,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/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index e931c7ec7a..3f561cae09 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -78,6 +78,7 @@ class ModeSettings( val mic: Boolean?, val gameStorage: String? = null, val storageOptions: List = emptyList(), + val storageFat32: Boolean = false, val steamLibraries: List = emptyList(), val foundSteamLibraries: List = emptyList(), val allFilesAccessMissing: Boolean = false, @@ -455,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) { 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 99785c488a..c9c469dad0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -27,7 +27,7 @@ internal object DeveloperTools { internal object NavTabs { const val MORE = "more" val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent") - val DEFAULT_SHELVED = setOf("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", "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") 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/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index b84a27be75..ae1dd01b77 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -283,6 +283,7 @@ class DrawerActions( val secondScreenDisplays: List, val selectedSecondScreenDisplay: Int, val onHud: (Boolean) -> Unit, + val onHudOnlyDuringGame: (Boolean) -> Unit = {}, val onHudSetting: (String, String) -> Unit = { _, _ -> }, val onGpuClockPin: (Boolean) -> Unit = {}, val onHudOrder: (Map, List) -> Unit = { _, _ -> }, @@ -1519,6 +1520,7 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) 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, 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 f9c81f4e42..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 @@ -153,27 +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), ) { - Wordmark(30.dp) + mark() runtimeStatus() } else Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - 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/StoragePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt index 34ebbbf9f8..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, 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 c2e79b9c86..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt +++ /dev/null @@ -1,631 +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(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, - focusAtTap: Int? = null, - onBack: (() -> Unit)? = null, -) { - val context = LocalContext.current - val onBackLatest = rememberUpdatedState(onBack) - val focusAsked = remember { booleanArrayOf(false) } - val focusTapAsked = remember { arrayOfNulls(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(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)) - } - }, - ) - } - } -} - -@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 8d43d09c7b..d9d2eb111f 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -84,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 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 81543e6d1c..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; diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 018c08995c..59188caba6 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1304,8 +1304,6 @@ فتح خيارات المطوّرين لا يحتوي إصدار Android هذا على مفتاح لذلك، لذا يغيّره DroidDeck عبر تصحيح الأخطاء اللاسلكي. يستغرق نحو دقيقة، ولا يحتاج إلى جهاز كمبيوتر. يحتاج تصحيح الأخطاء اللاسلكي إلى Wi-Fi. تعمل أي شبكة؛ فهو لا يحتاج إلى اتصال بالإنترنت. - يظهر رمز الإقران في إشعار. فعِّل الإشعارات لـ DroidDeck، أو استخدم «طرق أخرى». - السماح بالإشعارات افتح الإعدادات ← خيارات المطوّرين ← تصحيح الأخطاء اللاسلكي وفعِّله اضغط على «إقران جهاز برمز إقران» أدخل الرمز في إشعار DroidDeck @@ -1322,48 +1320,13 @@ الحالة يتم التحقّق كل ثانيتين. تُغلَق هذه الصفحة عند إيقافه. طرق أخرى - تصحيح الأخطاء اللاسلكي، عنوان يدوي، ADB من كمبيوتر - عنوان يدوي، ADB من كمبيوتر، خيارات المطوّرين استخدام تصحيح الأخطاء اللاسلكي بدلًا من ذلك تضيف بعض إصدارات ROM هذا المفتاح رغم ذلك. ابحث عن «العمليات الفرعية» في خيارات المطوّرين. - إذا لم ينجح الإشعار، أدخل عنوان النافذة المنبثقة ورمزها بنفسك. - إدخال العنوان يدويًا من جهاز كمبيوتر يحتوي على ADB: نسخ الأمر وصّل النظارة بالكمبيوتر وافتح SideQuest. اختر “Run ADB Command” ثم “Custom Command”، واكتب الأمر الظاهر أدناه، ثم اختر “Run Command”. اختر الشاشة التي ستُفتَح فيها إعدادات Android. الشاشة الرئيسية - تم الإقران. جارٍ البحث عن منفذ تصحيح الأخطاء اللاسلكي… - تم الإقران. أدخل المنفذ من الإعدادات. - تم العثور على الجهاز. جارٍ تطبيق الإعداد… - تعذّر التطبيق تلقائيًا. تحقّق من العنوان أدناه وأعد المحاولة. %1$s - تصحيح الأخطاء اللاسلكي - تم تحديث حد العمليات الفرعية - تغيير حد العمليات الفرعية - إذا كان هذا الخيار غير متاح، فأقرن عبر تصحيح الأخطاء اللاسلكي. - تم الإقران. تحقّق من عنوان IP والمنفذ في تصحيح الأخطاء اللاسلكي. - تم تحديث حد العمليات الفرعية. - استخدم الخطوة 2 إذا لم يكن في خيارات المطوّرين إعداد للعمليات الفرعية. افتح خيارات المطوّرين ← تصحيح الأخطاء اللاسلكي ← إقران جهاز برمز إقران. - تم الإقران. استخدم العنوان أدناه، أو حدِّثه من تصحيح الأخطاء اللاسلكي ← عنوان IP والمنفذ. - تم تحديث حد العمليات الفرعية عبر تصحيح الأخطاء اللاسلكي. - أكّد Android أن الحد مفعّل. - أكّد Android أن الحد معطّل. - 2 · إقران تصحيح الأخطاء اللاسلكي - عنوان IP ومنفذ النافذة المنبثقة للإقران - رمز الإقران (PIN) - 6 أرقام - إقران - 2 · التطبيق عبر تصحيح الأخطاء اللاسلكي - عنوان IP ومنفذ الاتصال - إقران مرة أخرى - إيقاف الحد - طرق أخرى لتغييره - 1 · خيارات المطوّرين (جرّب هذا أولًا) - عطِّل «إيقاف القيود المفروضة على العمليات الثانوية». - فعِّل «إيقاف القيود المفروضة على العمليات الثانوية». - 3 · ADB من كمبيوتر (كخيار أخير) - فقط إذا كان تصحيح الأخطاء اللاسلكي غير متاح. - 3 · ADB من كمبيوتر (كخيار أخير) اللون مخصّص العتامة @@ -1675,8 +1638,6 @@ تم محو %1$d مجلدًا لسجلات الجلسات. تم محو %1$d مجلد لسجلات الجلسات. - فشل الإقران عبر تصحيح الأخطاء اللاسلكي - فشل أمر تصحيح الأخطاء اللاسلكي تصحيح الأخطاء اللاسلكي غير متاح تم نسخ أمر ADB اختر مجلد ROMs @@ -2857,6 +2818,7 @@ الاتصال بصفحة تسجيل الدخول غير آمن. تعذّر التحقّق من تسجيل الدخول. حاوِل مرة أخرى. فشل تسجيل الدخول. حاوِل مرة أخرى. + يحتاج %1$s إلى خطوة أخرى. أكملها في المتصفح الذي فُتح، ثم حاول مرة أخرى. إغلاق رجوع تعديل @@ -3257,7 +3219,7 @@ تم في انتظار اتصال USB Ethernet الخاص بالنظارة. قد لا يتيحه هذا الهاتف للتطبيقات. انقطع اتصال XREAL أو أعاد استجابة غير مدعومة. جارٍ إعادة المحاولة… - دعم تجريبي لـ 1S. استخدم وضع Follow وعطّل تثبيت الصورة من قائمة النظارة. لا تزال اتجاهات التتبّع وأوضاع العرض بحاجة إلى اختبار على الجهاز. + دعم تجريبي لـ XREAL 1S وOne وOne Pro وOne Pro+ وAura. استخدم وضع Follow وأوقف تثبيت الصورة في قائمة النظارة؛ وعلى Aura، أوقف Spatial Anchor أيضًا. تم اختبار تتبع الرأس والتبديل بين 2D/3D على Aura وOne Pro+. تتبّع تجريبي لحركة الرأس لنظارة Pro 2. لا يُدعم بعد ضبط السطوع ومستوى الصوت أو تبديل وضع العرض. Cardboard VR وضع Cardboard @@ -4276,4 +4238,6 @@ الإبرازات نجاح خطأ + عرض HUD أثناء اللعب فقط + إخفاء HUD عند عدم اكتشاف إطارات اللعبة. 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 2f30d0ba67..c1314a8bd6 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1310,8 +1310,6 @@ Abrir Opciones de desarrollador 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. La Depuración inalámbrica necesita Wi-Fi. Sirve cualquier red; no necesita internet. - El código de vinculación aparece en una notificación. Permite las notificaciones de DroidDeck o usa Otras formas. - Permitir notificaciones Abre Ajustes → Opciones de desarrollador → Depuración inalámbrica y actívala Toca “Vincular dispositivo con código de vinculación” Escribe el código en la notificación de DroidDeck @@ -1328,48 +1326,13 @@ Estado Se comprueba cada 2 segundos. Esta página se cierra cuando esté desactivado. Otras formas - Depuración inalámbrica, dirección manual, ADB desde una computadora - Dirección manual, ADB desde una computadora, Opciones de desarrollador Usar Depuración inalámbrica en su lugar Algunas ROM agregan el interruptor de todos modos. Busca “procesos secundarios” en Opciones de desarrollador. - Si la notificación no funciona, ingresa manualmente la dirección y el código de la ventana. - Ingresar dirección manualmente Desde una computadora con ADB: Copiar comando 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”. Elige en qué pantalla abrir los Ajustes de Android. Pantalla principal - Vinculado. Buscando el puerto de la Depuración inalámbrica… - Vinculado. Ingresa el puerto de Ajustes. - Dispositivo encontrado. Aplicando el ajuste… - No se pudo aplicar automáticamente. Revisa la dirección de abajo y reintenta. %1$s - Depuración inalámbrica - Límite de procesos secundarios actualizado - Cambiar el límite de procesos secundarios - Si falta la opción, vincula mediante la Depuración inalámbrica. - Vinculado. Revisa la dirección IP y el puerto en Depuración inalámbrica. - El límite de procesos secundarios se actualizó. - 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. - Vinculado. Usa la dirección de abajo o actualízala desde Depuración inalámbrica → Dirección IP y puerto. - El límite de procesos secundarios se actualizó mediante la Depuración inalámbrica. - Android confirmó que el límite está activado. - Android confirmó que el límite está desactivado. - 2 · Vincular Depuración inalámbrica - Dirección IP y puerto de la ventana de vinculación - Código de vinculación (PIN) - 6 dígitos - Vincular - 2 · Aplicar mediante Depuración inalámbrica - Dirección IP y puerto de conexión - Vincular de nuevo - Desactivar límite - Otras formas de cambiarlo - 1 · Opciones de desarrollador (pruébalo primero) - Desactiva “Inhabilitar restricciones de procesos secundarios”. - Activa “Inhabilitar restricciones de procesos secundarios”. - 3 · ADB desde una computadora (último recurso) - Solo si la Depuración inalámbrica no está disponible. - 3 · ADB desde una computadora (último recurso) Color Personalizado Opacidad @@ -1424,7 +1387,7 @@ Hecho Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps. La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando… - 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. + 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+. 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. Animaciones Avisar cuando queda poco almacenamiento @@ -1706,8 +1669,6 @@ Se borraron %1$d carpetas de registros de sesión. Se borraron %1$d carpetas de registros de sesión. - Falló la vinculación de la Depuración inalámbrica - Falló el comando de la Depuración inalámbrica La Depuración inalámbrica no está disponible Comando ADB copiado Elige la carpeta de ROMs @@ -2823,6 +2784,7 @@ La conexión con la página de inicio de sesión no es segura. No se pudo verificar el inicio de sesión. Inténtalo de nuevo. No se pudo iniciar sesión. Inténtalo de nuevo. + %1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo. Cerrar Atrás Editar @@ -4156,4 +4118,6 @@ Destacados Éxito Error + Mostrar el HUD solo durante una partida + Ocultar el HUD cuando no se detecten fotogramas del juego. diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 3a2428fbfb..2ab13542e9 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -1276,8 +1276,6 @@ Отваряне на Опции за програмисти Тази версия на Android няма превключвател за това, затова DroidDeck го променя чрез безжично отстраняване на грешки. Отнема около минута, не е нужен компютър. Безжичното отстраняване на грешки изисква Wi-Fi. Работи с всяка мрежа; не е необходим интернет. - Кодът за сдвояване се показва в известие. Разрешете известията за DroidDeck или използвайте „Други начини“. - Разрешаване на известията Отворете Настройки → Опции за програмисти → Безжично отстраняване на грешки и го включете Докоснете „Сдвояване на устройство с код за сдвояване“ Въведете кода в известието на DroidDeck @@ -1294,48 +1292,13 @@ Състояние Проверява се на всеки 2 секунди. Тази страница се затваря, когато е изключено. Други начини - Безжично отстраняване на грешки, ръчен адрес, ADB от компютър - Ръчен адрес, ADB от компютър, Опции за програмисти Използване на безжично отстраняване на грешки вместо това Някои ROM-и добавят превключвателя въпреки това. Потърсете „child process“ в Опции за програмисти. - Ако известието не работи, въведете сами адреса и кода от изскачащия прозорец. - Ръчно въвеждане на адреса От компютър с ADB: Копиране на командата Свържете шлема с компютър и отворете SideQuest. Изберете „Run ADB Command“, после „Custom Command“, въведете командата, показана по-долу, и изберете „Run Command“. Изберете на кой екран да се отворят настройките на Android. Основен екран - Сдвоено. Търсене на порта за безжично отстраняване на грешки… - Сдвоено. Въведете порта от Настройки. - Устройството е намерено. Прилагане на настройката… - Не можа да се приложи автоматично. Проверете адреса по-долу и опитайте отново. %1$s - Безжично отстраняване на грешки - Ограничението на дъщерните процеси е актуализирано - Промяна на ограничението на дъщерните процеси - Ако опцията липсва, сдвоете чрез безжично отстраняване на грешки. - Сдвоено. Проверете IP адреса и порта в безжичното отстраняване на грешки. - Ограничението на дъщерните процеси беше актуализирано. - Използвайте стъпка 2, ако Опции за програмисти нямат настройка за дъщерни процеси. Отворете Опции за програмисти → Безжично отстраняване на грешки → Сдвояване на устройство с код за сдвояване. - Сдвоено. Използвайте адреса по-долу или го обновете от Безжично отстраняване на грешки → IP адрес и порт. - Ограничението на дъщерните процеси беше актуализирано чрез безжично отстраняване на грешки. - Android потвърди, че ограничението е включено. - Android потвърди, че ограничението е изключено. - 2 · Сдвояване на безжично отстраняване на грешки - IP адрес и порт на изскачащия прозорец за сдвояване - Код за сдвояване (PIN) - 6 цифри - Сдвояване - 2 · Прилагане чрез безжично отстраняване на грешки - IP адрес и порт за връзка - Сдвояване отново - Изключване на ограничението - Други начини за промяна - 1 · Опции за програмисти (пробвайте първо) - Изключете „Деактивиране на ограниченията за дъщерните процеси“. - Включете „Деактивиране на ограниченията за дъщерните процеси“. - 3 · ADB от компютър (последна възможност) - Само ако безжичното отстраняване на грешки не е достъпно. - 3 · ADB от компютър (последна възможност) Цвят Персонализиран Прозрачност @@ -1623,8 +1586,6 @@ Изчистена %1$d папка с логове от сесия. Изчистени %1$d папки с логове от сесии. - Чифтосването за безжично отстраняване на грешки се провали - Командата за безжично отстраняване на грешки се провали Безжичното отстраняване на грешки не е достъпно Командата за ADB е копирана Избор на папката ROMs @@ -2753,6 +2714,7 @@ Връзката със страницата за вход не е защитена. Входът не можа да бъде потвърден. Опитай отново. Входът се провали. Опитай отново. + %1$s изисква още една стъпка. Завърши я в браузъра, който се отвори, и опитай отново. Затвори Назад Редактирай @@ -3137,7 +3099,7 @@ Готово Изчаква се USB Ethernet връзката на очилата. Този телефон може да не я предоставя на приложенията. Връзката с XREAL беше прекъсната или върна неподдържан отговор. Нов опит… - Експериментална поддръжка на 1S. Използвайте режим Follow и изключете стабилизацията в менюто на очилата. Посоките на проследяване и режимите на показване все още трябва да се тестват на устройство. + Експериментална поддръжка на XREAL 1S, One, One Pro, One Pro+ и Aura. Използвайте режим Follow и изключете стабилизацията в менюто на очилата; при Aura изключете и Spatial Anchor. Проследяването на главата и превключването между 2D/3D са тествани на Aura и One Pro+. Експериментално проследяване на движенията на главата за Pro 2. Регулирането на яркостта и силата на звука и превключването на режима на показване все още не се поддържат. Cardboard VR Режим Cardboard @@ -4116,4 +4078,6 @@ Акценти Успех Грешка + Показвай HUD само по време на игра + Скривай HUD, когато не се засичат кадри от играта. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 4c920c1cf0..04231de374 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1290,8 +1290,6 @@ Otevřít Možnosti pro vývojáře 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. Bezdrátové ladění potřebuje Wi-Fi. Funguje jakákoli síť, internet není nutný. - Párovací kód se zobrazí v oznámení. Povolte oznámení pro DroidDeck, nebo použijte Jiné způsoby. - Povolit oznámení Otevřete Nastavení → Možnosti pro vývojáře → Bezdrátové ladění a zapněte ho Klepněte na „Spárovat zařízení pomocí párovacího kódu“ Zadejte kód do oznámení DroidDecku @@ -1308,48 +1306,13 @@ Stav Kontroluje se každé 2 sekundy. Tato stránka se zavře, až bude vypnuto. Jiné způsoby - Bezdrátové ladění, ruční adresa, ADB z počítače - Ruční adresa, ADB z počítače, Možnosti pro vývojáře Použít místo toho Bezdrátové ladění Některé ROM přepínač přidávají i tak. Hledejte v Možnostech pro vývojáře „child process“. - Pokud oznámení nefunguje, zadejte adresu a kód z okna sami. - Zadat adresu ručně Z počítače s ADB: Kopírovat příkaz 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“. Vyberte, na kterém displeji se má otevřít Nastavení Androidu. Hlavní obrazovka - Spárováno. Hledání portu Bezdrátového ladění… - Spárováno. Zadejte port z Nastavení. - Zařízení nalezeno. Používá se nastavení… - Nepodařilo se použít automaticky. Zkontrolujte adresu níže a zkuste to znovu. %1$s - Bezdrátové ladění - Omezení pro dětské procesy aktualizováno - Změnit omezení pro dětské procesy - Pokud volba chybí, spárujte přes Bezdrátové ladění. - Spárováno. Zkontrolujte IP adresu a port v Bezdrátovém ladění. - Omezení pro dětské procesy bylo aktualizováno. - 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. - Spárováno. Použijte adresu níže, nebo ji aktualizujte z Bezdrátové ladění → IP adresa a port. - Omezení pro dětské procesy bylo aktualizováno přes Bezdrátové ladění. - Android potvrdil, že omezení je zapnuto. - Android potvrdil, že omezení je vypnuto. - 2 · Spárovat Bezdrátové ladění - IP adresa a port párovacího okna - Párovací kód (PIN) - 6 číslic - Spárovat - 2 · Použít přes Bezdrátové ladění - IP adresa a port pro připojení - Spárovat znovu - Vypnout omezení - Jiné způsoby změny - 1 · Možnosti pro vývojáře (zkusit nejdřív) - Vypněte „Deaktivace omezení podřízených procesů“. - Zapněte „Deaktivace omezení podřízených procesů“. - 3 · ADB z počítače (poslední možnost) - Jen pokud Bezdrátové ladění není k dispozici. - 3 · ADB z počítače (poslední možnost) Barva Vlastní Průhlednost @@ -1649,8 +1612,6 @@ Vyčištěno %1$d složek s logy relace. Vyčištěno %1$d složek s logy relace. - Párování bezdrátového ladění se nezdařilo - Příkaz bezdrátového ladění se nezdařil Bezdrátové ladění není k dispozici Příkaz ADB zkopírován Vybrat složku ROMs @@ -2805,6 +2766,7 @@ Spojení s přihlašovací stránkou není zabezpečené. Přihlášení se nepodařilo ověřit. Zkuste to znovu. Přihlášení se nezdařilo. Zkuste to znovu. + %1$s vyžaduje ještě jeden krok. Dokončete ho v prohlížeči, který se otevřel, a zkuste to znovu. Zavřít Zpět Upravit @@ -3197,7 +3159,7 @@ Hotovo Čeká se na připojení USB Ethernet brýlí. Tento telefon ho možná aplikacím nezpřístupňuje. Připojení XREAL bylo přerušeno nebo vrátilo nepodporovanou odpověď. Zkouší se to znovu… - 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í. + 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+. 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. Cardboard VR Režim Cardboard @@ -4196,4 +4158,6 @@ Zvýraznění Úspěch Chyba + Zobrazovat HUD pouze během hry + Skrýt HUD, když nejsou detekovány snímky hry. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index c34b855e74..609965ad7f 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1276,8 +1276,6 @@ Åbn Udviklerindstillinger 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. Trådløs fejlretning kræver Wi-Fi. Alle netværk fungerer; det kræver ikke internet. - Parringskoden kommer i en notifikation. Tillad notifikationer for DroidDeck, eller brug Andre måder. - Tillad notifikationer Åbn Indstillinger → Udviklerindstillinger → Trådløs fejlretning, og slå den til Tryk på “Par enhed med parringskode” Indtast koden i DroidDeck-notifikationen @@ -1294,48 +1292,13 @@ Status Kontrollerer hvert 2. sekund. Denne side lukker, når den er fra. Andre måder - Trådløs fejlretning, manuel adresse, computer-ADB - Manuel adresse, computer-ADB, Udviklerindstillinger Brug Trådløs fejlretning i stedet Nogle ROM’er tilføjer kontakten alligevel. Kig efter “underprocesser” i Udviklerindstillinger. - Hvis notifikationen ikke virker, kan du selv indtaste vinduets adresse og kode. - Indtast adresse manuelt Fra en computer med ADB: Kopier kommando 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”. Vælg, hvilken skærm Android-indstillinger skal åbnes på. Hovedskærm - Parret. Finder porten for Trådløs fejlretning… - Parret. Indtast porten fra Indstillinger. - Enhed fundet. Anvender indstillingen… - Kunne ikke anvendes automatisk. Kontroller adressen nedenfor, og prøv igen. %1$s - Trådløs fejlretning - Grænsen for underprocesser opdateret - Ændr grænsen for underprocesser - Hvis indstillingen mangler, skal du parre via Trådløs fejlretning. - Parret. Kontroller IP-adressen og porten i Trådløs fejlretning. - Grænsen for underprocesser blev opdateret. - Brug trin 2, hvis Udviklerindstillinger ikke har en indstilling for underprocesser. Åbn Udviklerindstillinger → Trådløs fejlretning → Par enhed med parringskode. - Parret. Brug adressen nedenfor, eller opdater den fra Trådløs fejlretning → IP-adresse og port. - Grænsen for underprocesser blev opdateret via Trådløs fejlretning. - Android bekræftede, at grænsen er til. - Android bekræftede, at grænsen er fra. - 2 · Par Trådløs fejlretning - Parringsvinduets IP-adresse og port - Parringskode (PIN) - 6 cifre - Par - 2 · Anvend via Trådløs fejlretning - Forbindelsens IP-adresse og port - Par igen - Slå grænsen fra - Andre måder at ændre det - 1 · Udviklerindstillinger (prøv først) - Slå “Deaktiver begrænsningerne for underprocesser” fra. - Slå “Deaktiver begrænsningerne for underprocesser” til. - 3 · Computer-ADB (sidste udvej) - Kun hvis Trådløs fejlretning ikke er tilgængelig. - 3 · Computer-ADB (sidste udvej) Farve Brugerdefineret Gennemsigtighed @@ -1623,8 +1586,6 @@ Ryddede %1$d sessionslogmappe. Ryddede %1$d sessionslogmapper. - Parring til trådløs fejlretning mislykkedes - Kommando til trådløs fejlretning mislykkedes Trådløs fejlretning er ikke tilgængelig ADB-kommando kopieret Vælg ROMs-mappen @@ -2753,6 +2714,7 @@ Forbindelsen til loginsiden er ikke sikker. Login kunne ikke bekræftes. Forsøg igen. Login mislykkedes. Forsøg igen. + %1$s kræver et trin mere. Fuldfør det i browseren, der blev åbnet, og prøv igen. Luk Tilbage Rediger @@ -3137,7 +3099,7 @@ Udført Venter på brillens USB-Ethernet-forbindelse. Denne telefon gør den muligvis ikke tilgængelig for apps. XREAL-forbindelsen blev afbrudt eller returnerede et svar, der ikke understøttes. Prøver igen… - Eksperimentel understøttelse af 1S. Brug Follow-tilstand, og slå stabilisering fra i brillens menu. Sporingsretninger og visningstilstande mangler stadig test på enheden. + 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+. Eksperimentel hovedsporing til Pro 2. Justering af lysstyrke og lydstyrke samt skift af visningstilstand understøttes endnu ikke. Cardboard VR Cardboard-tilstand @@ -4116,4 +4078,6 @@ Fremhævninger Succes Fejl + Vis kun HUD under spil + Skjul HUD, når der ikke registreres spilbilleder. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 8715f4b3a3..f803d555bd 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1268,8 +1268,6 @@ Entwickleroptionen öffnen Diese Android-Version hat dafür keinen Schalter, deshalb ändert DroidDeck es über „Debugging über WLAN“. Dauert etwa eine Minute, kein Computer nötig. „Debugging über WLAN“ braucht eine Wi-Fi-Verbindung. Jedes Netzwerk geht; Internet ist nicht nötig. - Der Kopplungscode wird in eine Benachrichtigung eingegeben. Erlaube Benachrichtigungen für DroidDeck oder nutze „Andere Wege“. - Benachrichtigungen erlauben Öffne Einstellungen → Entwickleroptionen → Debugging über WLAN und aktiviere es Tippe auf „Gerät über einen Kopplungscode koppeln“ Gib den Code in die DroidDeck-Benachrichtigung ein @@ -1286,48 +1284,13 @@ Status Prüft alle 2 Sekunden. Diese Seite schließt sich, sobald es aus ist. Andere Wege - Debugging über WLAN, manuelle Adresse, ADB am Computer - Manuelle Adresse, ADB am Computer, Entwickleroptionen Stattdessen „Debugging über WLAN“ verwenden Manche ROMs haben den Schalter trotzdem. Suche in den Entwickleroptionen nach „untergeordnete Prozesse“. - Falls die Benachrichtigung nicht funktioniert, gib Adresse und Code des Pop-ups selbst ein. - Adresse manuell eingeben Von einem Computer mit ADB: Befehl kopieren 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“. Wähle, auf welchem Display die Android-Einstellungen geöffnet werden. Hauptbildschirm - Gekoppelt. Suche den Port für Debugging über WLAN… - Gekoppelt. Gib den Port aus den Einstellungen ein. - Gerät gefunden. Einstellung wird angewendet… - Automatisches Anwenden fehlgeschlagen. Prüfe die Adresse unten und versuch es erneut. %1$s - Debugging über WLAN - Limit für untergeordnete Prozesse aktualisiert - Limit für untergeordnete Prozesse ändern - Fehlt die Option, kopple über „Debugging über WLAN“. - Gekoppelt. Prüfe IP-Adresse und Port unter „Debugging über WLAN“. - Das Limit für untergeordnete Prozesse wurde aktualisiert. - Nutze Schritt 2, wenn die Entwickleroptionen keine Einstellung für untergeordnete Prozesse haben. Öffne Entwickleroptionen → Debugging über WLAN → Gerät über einen Kopplungscode koppeln. - Gekoppelt. Nutze die Adresse unten oder aktualisiere sie über Debugging über WLAN → IP-Adresse und Port. - Das Limit für untergeordnete Prozesse wurde über „Debugging über WLAN“ aktualisiert. - Android hat bestätigt, dass das Limit aktiv ist. - Android hat bestätigt, dass das Limit aus ist. - 2 · Für Debugging über WLAN koppeln - IP-Adresse und Port aus dem Kopplungs-Pop-up - Kopplungscode (PIN) - 6 Ziffern - Koppeln - 2 · Per Debugging über WLAN anwenden - IP-Adresse und Port für die Verbindung - Erneut koppeln - Limit deaktivieren - Andere Wege, es zu ändern - 1 · Entwickleroptionen (zuerst versuchen) - Schalte „Beschränkungen für Unterprozesse deaktivieren“ aus. - Schalte „Beschränkungen für Unterprozesse deaktivieren“ ein. - 3 · ADB am Computer (letzter Ausweg) - Nur wenn „Debugging über WLAN“ nicht verfügbar ist. - 3 · ADB am Computer (letzter Ausweg) Farbe Benutzerdefiniert Deckkraft @@ -1615,8 +1578,6 @@ %1$d Ordner mit Sitzungsprotokollen gelöscht. %1$d Ordner mit Sitzungsprotokollen gelöscht. - Kopplung für Debugging über WLAN fehlgeschlagen - Befehl für Debugging über WLAN fehlgeschlagen Debugging über WLAN ist nicht verfügbar ADB-Befehl kopiert ROMs-Ordner auswählen @@ -2742,6 +2703,7 @@ Die Verbindung zur Anmeldeseite ist nicht sicher. Die Anmeldung konnte nicht bestätigt werden. Versuche es erneut. Anmeldung fehlgeschlagen. Versuche es erneut. + %1$s braucht noch einen Schritt. Schließe ihn im geöffneten Browser ab und versuche es dann erneut. Schließen Zurück Bearbeiten @@ -3126,7 +3088,7 @@ Fertig Warte auf die USB-Ethernet-Verbindung der Brille. Dieses Smartphone stellt sie Apps möglicherweise nicht bereit. Die XREAL-Verbindung wurde unterbrochen oder hat eine nicht unterstützte Antwort geliefert. Neuer Versuch … - 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. + 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. Experimentelles Kopftracking für Pro 2. Das Einstellen von Helligkeit und Lautstärke sowie das Umschalten des Anzeigemodus werden noch nicht unterstützt. Cardboard VR Cardboard-Modus @@ -4116,4 +4078,6 @@ Hervorhebungen Erfolg Fehler + HUD nur während eines Spiels anzeigen + HUD ausblenden, wenn keine Spielframes erkannt werden. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 93b0438ef5..08d647886a 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1276,8 +1276,6 @@ Άνοιγμα Επιλογών προγραμματιστή Αυτή η έκδοση Android δεν έχει διακόπτη για αυτό, οπότε το DroidDeck το αλλάζει μέσω Ασύρματου εντοπισμού σφαλμάτων. Διαρκεί περίπου ένα λεπτό, χωρίς υπολογιστή. Ο Ασύρματος εντοπισμός σφαλμάτων απαιτεί Wi-Fi. Οποιοδήποτε δίκτυο λειτουργεί· δεν απαιτείται σύνδεση στο διαδίκτυο. - Ο κωδικός σύζευξης εμφανίζεται σε ειδοποίηση. Επιτρέψτε ειδοποιήσεις για το DroidDeck, ή χρησιμοποιήστε Άλλοι τρόποι. - Αποδοχή ειδοποιήσεων Ανοίξτε Ρυθμίσεις → Επιλογές προγραμματιστή → Ασύρματος εντοπισμός σφαλμάτων και ενεργοποιήστε τον Πατήστε «Σύζευξη συσκευής με κωδικό σύζευξης» Πληκτρολογήστε τον κωδικό στην ειδοποίηση του DroidDeck @@ -1294,48 +1292,13 @@ Κατάσταση Έλεγχος κάθε 2 δευτερόλεπτα. Αυτή η σελίδα κλείνει όταν είναι απενεργοποιημένο. Άλλοι τρόποι - Ασύρματος εντοπισμός σφαλμάτων, μη αυτόματη διεύθυνση, ADB υπολογιστή - Μη αυτόματη διεύθυνση, ADB υπολογιστή, Επιλογές προγραμματιστή Χρήση Ασύρματου εντοπισμού σφαλμάτων αντ\' αυτού Ορισμένες ROM προσθέτουν τον διακόπτη ούτως ή άλλως. Αναζητήστε «θυγατρική διαδικασία» στις Επιλογές προγραμματιστή. - Αν η ειδοποίηση δεν λειτουργεί, εισαγάγετε τη διεύθυνση και τον κωδικό του αναδυόμενου παραθύρου εσείς. - Μη αυτόματη εισαγωγή διεύθυνσης Από υπολογιστή με ADB: Αντιγραφή εντολής Συνδέστε το headset σε υπολογιστή και ανοίξτε το SideQuest. Επιλέξτε «Run ADB Command», μετά «Custom Command», πληκτρολογήστε την εντολή που εμφανίζεται παρακάτω και επιλέξτε «Run Command». Επιλέξτε σε ποια οθόνη θα ανοίξουν οι Ρυθμίσεις Android. Κύρια οθόνη - Έγινε σύζευξη. Αναζήτηση θύρας Ασύρματου εντοπισμού σφαλμάτων… - Έγινε σύζευξη. Εισαγάγετε τη θύρα από τις Ρυθμίσεις. - Η συσκευή βρέθηκε. Εφαρμογή της ρύθμισης… - Δεν ήταν δυνατή η αυτόματη εφαρμογή. Ελέγξτε την παρακάτω διεύθυνση και δοκιμάστε ξανά. %1$s - Ασύρματος εντοπισμός σφαλμάτων - Το όριο θυγατρικών διαδικασιών ενημερώθηκε - Αλλαγή του ορίου θυγατρικών διαδικασιών - Αν η επιλογή λείπει, κάντε σύζευξη μέσω Ασύρματου εντοπισμού σφαλμάτων. - Έγινε σύζευξη. Ελέγξτε τη διεύθυνση IP και τη θύρα στον Ασύρματο εντοπισμό σφαλμάτων. - Το όριο θυγατρικών διαδικασιών ενημερώθηκε. - Χρησιμοποιήστε το βήμα 2 αν οι Επιλογές προγραμματιστή δεν έχουν ρύθμιση θυγατρικών διαδικασιών. Ανοίξτε Επιλογές προγραμματιστή → Ασύρματος εντοπισμός σφαλμάτων → Σύζευξη συσκευής με κωδικό σύζευξης. - Έγινε σύζευξη. Χρησιμοποιήστε την παρακάτω διεύθυνση, ή ενημερώστε την από Ασύρματος εντοπισμός σφαλμάτων → Διεύθυνση IP & θύρα. - Το όριο θυγατρικών διαδικασιών ενημερώθηκε μέσω Ασύρματου εντοπισμού σφαλμάτων. - Το Android επιβεβαίωσε ότι το όριο είναι ενεργό. - Το Android επιβεβαίωσε ότι το όριο είναι ανενεργό. - 2 · Σύζευξη Ασύρματου εντοπισμού σφαλμάτων - Διεύθυνση IP & θύρα αναδυόμενου παραθύρου σύζευξης - Κωδικός σύζευξης (PIN) - 6 ψηφία - Σύζευξη - 2 · Εφαρμογή μέσω Ασύρματου εντοπισμού σφαλμάτων - Διεύθυνση IP & θύρα σύνδεσης - Σύζευξη ξανά - Απενεργοποίηση ορίου - Άλλοι τρόποι αλλαγής - 1 · Επιλογές προγραμματιστή (δοκιμάστε πρώτα) - Απενεργοποιήστε «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες». - Ενεργοποιήστε «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες». - 3 · ADB υπολογιστή (τελευταία λύση) - Μόνο αν ο Ασύρματος εντοπισμός σφαλμάτων δεν είναι διαθέσιμος. - 3 · ADB υπολογιστή (τελευταία λύση) Χρώμα Προσαρμοσμένο Διαφάνεια @@ -1623,8 +1586,6 @@ Έγινε εκκαθάριση %1$d φακέλου αρχείων καταγραφής συνεδρίας. Έγινε εκκαθάριση %1$d φακέλων αρχείων καταγραφής συνεδρίας. - Η σύζευξη ασύρματου εντοπισμού σφαλμάτων απέτυχε - Η εντολή ασύρματου εντοπισμού σφαλμάτων απέτυχε Ο ασύρματος εντοπισμός σφαλμάτων δεν είναι διαθέσιμος Η εντολή ADB αντιγράφηκε Επιλέξτε τον φάκελο ROMs @@ -2753,6 +2714,7 @@ Η σύνδεση με τη σελίδα σύνδεσης δεν είναι ασφαλής. Δεν ήταν δυνατή η επαλήθευση της σύνδεσης. Δοκιμάστε ξανά. Η σύνδεση απέτυχε. Δοκιμάστε ξανά. + Το %1$s χρειάζεται ένα ακόμη βήμα. Ολοκληρώστε το στο πρόγραμμα περιήγησης που άνοιξε και δοκιμάστε ξανά. Κλείσιμο Πίσω Επεξεργασία @@ -3137,7 +3099,7 @@ Τέλος Αναμονή για τη σύνδεση USB Ethernet των γυαλιών. Αυτό το τηλέφωνο ίσως δεν τη διαθέτει στις εφαρμογές. Η σύνδεση XREAL διακόπηκε ή επέστρεψε μη υποστηριζόμενη απόκριση. Νέα προσπάθεια… - Πειραματική υποστήριξη για 1S. Χρησιμοποιήστε τη λειτουργία Follow και απενεργοποιήστε τη σταθεροποίηση στο μενού των γυαλιών. Οι κατευθύνσεις παρακολούθησης και οι λειτουργίες οθόνης χρειάζονται ακόμα δοκιμή σε συσκευή. + Πειραματική υποστήριξη για XREAL 1S, One, One Pro, One Pro+ και Aura. Χρησιμοποιήστε τη λειτουργία Follow και απενεργοποιήστε τη σταθεροποίηση στο μενού των γυαλιών· στα Aura απενεργοποιήστε επίσης το Spatial Anchor. Η παρακολούθηση κεφαλής και η εναλλαγή 2D/3D έχουν δοκιμαστεί στα Aura και One Pro+. Πειραματική παρακολούθηση κεφαλής για Pro 2. Η ρύθμιση της φωτεινότητας και της έντασης ήχου και η αλλαγή λειτουργίας οθόνης δεν υποστηρίζονται ακόμη. Cardboard VR Λειτουργία Cardboard @@ -4116,4 +4078,6 @@ Επισημάνσεις Επιτυχία Σφάλμα + Εμφάνιση HUD μόνο κατά τη διάρκεια παιχνιδιού + Απόκρυψη HUD όταν δεν ανιχνεύονται καρέ παιχνιδιού. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index a8a7525c87..d1859b029a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1283,8 +1283,6 @@ Abrir Opciones de desarrollador 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. La Depuración inalámbrica necesita Wi-Fi. Sirve cualquier red; no necesita internet. - El código de vinculación aparece en una notificación. Permite las notificaciones de DroidDeck o usa Otras formas. - Permitir notificaciones Abre Ajustes → Opciones de desarrollador → Depuración inalámbrica y actívala Toca “Vincular dispositivo con código de vinculación” Escribe el código en la notificación de DroidDeck @@ -1301,48 +1299,13 @@ Estado Se comprueba cada 2 segundos. Esta página se cierra cuando esté desactivado. Otras formas - Depuración inalámbrica, dirección manual, ADB desde ordenador - Dirección manual, ADB desde ordenador, Opciones de desarrollador Usar Depuración inalámbrica en su lugar Algunas ROM añaden el interruptor de todos modos. Busca “procesos secundarios” en Opciones de desarrollador. - Si la notificación no funciona, introduce manualmente la dirección y el código de la ventana. - Introducir dirección manualmente Desde un ordenador con ADB: Copiar comando 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». Elige en qué pantalla abrir los Ajustes de Android. Pantalla principal - Vinculado. Buscando el puerto de la Depuración inalámbrica… - Vinculado. Introduce el puerto de Ajustes. - Dispositivo encontrado. Aplicando el ajuste… - No se pudo aplicar automáticamente. Revisa la dirección de abajo y reintenta. %1$s - Depuración inalámbrica - Límite de procesos secundarios actualizado - Cambiar el límite de procesos secundarios - Si falta la opción, vincula mediante la Depuración inalámbrica. - Vinculado. Revisa la dirección IP y el puerto en Depuración inalámbrica. - El límite de procesos secundarios se actualizó. - 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. - Vinculado. Usa la dirección de abajo o actualízala desde Depuración inalámbrica → Dirección IP y puerto. - El límite de procesos secundarios se actualizó mediante la Depuración inalámbrica. - Android confirmó que el límite está activado. - Android confirmó que el límite está desactivado. - 2 · Vincular Depuración inalámbrica - Dirección IP y puerto de la ventana de vinculación - Código de vinculación (PIN) - 6 dígitos - Vincular - 2 · Aplicar mediante Depuración inalámbrica - Dirección IP y puerto de conexión - Vincular de nuevo - Desactivar límite - Otras formas de cambiarlo - 1 · Opciones de desarrollador (pruébalo primero) - Desactiva “Inhabilitar restricciones de procesos secundarios”. - Activa “Inhabilitar restricciones de procesos secundarios”. - 3 · ADB desde ordenador (último recurso) - Solo si la Depuración inalámbrica no está disponible. - 3 · ADB desde ordenador (último recurso) Color Personalizado Opacidad @@ -1636,8 +1599,6 @@ Se borraron %1$d carpetas de registros de sesión. Se borraron %1$d carpetas de registros de sesión. - Falló la vinculación de la Depuración inalámbrica - Falló el comando de la Depuración inalámbrica La Depuración inalámbrica no está disponible Comando ADB copiado Elige la carpeta de ROMs @@ -2776,6 +2737,7 @@ La conexión con la página de inicio de sesión no es segura. No se pudo verificar el inicio de sesión. Inténtalo de nuevo. No se pudo iniciar sesión. Inténtalo de nuevo. + %1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo. Cerrar Atrás Editar @@ -3153,7 +3115,7 @@ Hecho Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps. La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando… - 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. + 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+. 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. Desarrollador Distribuidor @@ -4156,4 +4118,6 @@ Destacados Éxito Error + Mostrar el HUD solo durante una partida + Ocultar el HUD cuando no se detecten fotogramas del juego. diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 084d781755..4cf72f1674 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1276,8 +1276,6 @@ Avaa Kehittäjäasetukset Tässä Android-versiossa ei ole kytkintä tälle, niin DroidDeck muuttaa sen Langattoman virheenkorjauksen kautta. Kestää noin minuutin, ei tarvita tietokonetta. Langaton virheenkorjaus vaatii Wi-Fi-yhteyden. Mikä tahansa verkko käy; internet-yhteyttä ei tarvita. - Pariutuskoodi tulee ilmoitukseen. Salli ilmoitukset DroidDeckille, tai käytä Muita tapoja. - Salli ilmoitukset Avaa Asetukset → Kehittäjäasetukset → Langaton virheenkorjaus ja kytke se päälle Napauta ”Pariuta laite pariutuskoodilla” Kirjoita koodi DroidDeckin ilmoitukseen @@ -1294,48 +1292,13 @@ Tila Tarkistetaan 2 sekunnin välein. Tämä sivu sulkeutuu, kun se on pois päältä. Muita tapoja - Langaton virheenkorjaus, manuaalinen osoite, tietokoneen ADB - Manuaalinen osoite, tietokoneen ADB, Kehittäjäasetukset Käytä sen sijaan Langatonta virheenkorjausta Jotkin ROM-versiot lisäävät kytkimen joka tapauksessa. Etsi ”child process” Kehittäjäasetuksista. - Jos ilmoitus ei toimi, syötä ponnahdusikkunan osoite ja koodi itse. - Syötä osoite manuaalisesti Tietokoneelta ADB:llä: Kopioi komento Liitä lasit tietokoneeseen ja avaa SideQuest. Valitse ”Run ADB Command” ja sitten ”Custom Command”, kirjoita alla näkyvä komento ja valitse ”Run Command”. Valitse, millä näytöllä Android-asetukset avataan. Päänäyttö - Pariutui. Etsitään Langattoman virheenkorjauksen porttia… - Pariutui. Syötä portti Asetuksista. - Laite löytyi. Otetaan asetus käyttöön… - Automaattinen käyttöönotto epäonnistui. Tarkista alla oleva osoite ja yritä uudelleen. %1$s - Langaton virheenkorjaus - Lapsiprosessien raja päivitetty - Muuta lapsiprosessien rajaa - Jos asetus puuttuu, pariuta Langattoman virheenkorjauksen kautta. - Pariutui. Tarkista IP-osoite ja portti Langattomasta virheenkorjauksesta. - Lapsiprosessien raja päivitettiin. - Käytä vaihetta 2, jos Kehittäjäasetuksissa ei ole lapsiprosessiasetusta. Avaa Kehittäjäasetukset → Langaton virheenkorjaus → Pariuta laite pariutuskoodilla. - Pariutui. Käytä alla olevaa osoitetta, tai päivitä se Langaton virheenkorjaus → IP-osoite ja portti -kohdasta. - Lapsiprosessien raja päivitettiin Langattoman virheenkorjauksen kautta. - Android vahvisti, että raja on päällä. - Android vahvisti, että raja on pois päältä. - 2 · Pariuta Langaton virheenkorjaus - Pariutuksen ponnahdusikkunan IP-osoite ja portti - Pariutuskoodi (PIN) - 6 numeroa - Pariuta - 2 · Ota käyttöön Langattoman virheenkorjauksen kautta - Yhteyden IP-osoite ja portti - Pariuta uudelleen - Kytke raja pois päältä - Muita tapoja muuttaa sitä - 1 · Kehittäjäasetukset (kokeile ensin) - Aseta ”Poista käytöstä alatason prosessirajoitukset” pois päältä. - Aseta ”Poista käytöstä alatason prosessirajoitukset” päälle. - 3 · Tietokoneen ADB (viimeinen keino) - Vain jos Langaton virheenkorjaus ei ole käytettävissä. - 3 · Tietokoneen ADB (viimeinen keino) Väri Mukautettu Peittävyys @@ -1623,8 +1586,6 @@ Tyhjennettiin %1$d istuntolokikansio. Tyhjennettiin %1$d istuntolokikansiota. - Langattoman virheenkorjauksen laitepariutus epäonnistui - Langattoman virheenkorjauksen komento epäonnistui Langaton virheenkorjaus ei ole käytettävissä ADB-komento kopioitu Valitse ROMs-kansio @@ -2753,6 +2714,7 @@ Yhteys kirjautumissivulle ei ole suojattu. Kirjautumista ei voitu vahvistaa. Yritä uudelleen. Kirjautuminen epäonnistui. Yritä uudelleen. + %1$s vaatii vielä yhden vaiheen. Viimeistele se avautuneessa selaimessa ja yritä sitten uudelleen. Sulje Takaisin Muokkaa @@ -3137,7 +3099,7 @@ Valmis Odotetaan lasien USB-Ethernet-yhteyttä. Tämä puhelin ei ehkä tarjoa sitä sovelluksille. XREAL-yhteys katkesi tai palautti vastauksen, jota ei tueta. Yritetään uudelleen… - 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. + 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. Kokeellinen päänliikkeiden seuranta Pro 2:lle. Kirkkauden ja äänenvoimakkuuden säätöä sekä näyttötilan vaihtamista ei vielä tueta. Cardboard VR Cardboard-tila @@ -4116,4 +4078,6 @@ Korostukset Onnistuminen Virhe + Näytä HUD vain pelin aikana + Piilota HUD, kun pelin ruutuja ei havaita. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index c12f0c8afe..c735507d40 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1282,8 +1282,6 @@ Ouvrir les options pour les développeurs 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. Le débogage sans fil nécessite un Wi-Fi. N\'importe quel réseau convient, Internet n\'est pas nécessaire. - Le code d\'appairage s\'affichera dans une notification. Veuillez autoriser DroidDeck à envoyer des notifications, ou utilisez « Autre méthode ». - Autoriser les notifications Ouvrez Paramètres → Options pour les développeurs → Débogage sans fil, et activez-le Appuyez sur « Associer l\'appareil avec un code d\'appairage » Saisissez le code d\'appairage dans la notification DroidDeck @@ -1300,48 +1298,13 @@ État Vérification toutes les 2 secondes. Cette page se fermera automatiquement une fois cet interrupteur désactivé. Autres méthodes - Débogage sans fil, saisie manuelle de l\'adresse, ADB sur PC - Saisie manuelle de l\'adresse, ADB sur PC, options pour les développeurs Utiliser plutôt le débogage sans fil Certaines ROM proposent encore cet interrupteur. Recherchez « processus enfants » dans les options pour les développeurs. - Si la méthode par notification ne fonctionne pas, saisissez manuellement l\'adresse et le code d\'appairage de la fenêtre. - Saisir l\'adresse manuellement Utiliser ADB depuis un ordinateur : Copier la commande 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 ». Choisissez l\'écran sur lequel ouvrir les paramètres Android. Écran principal - Appairé. Recherche du port de débogage sans fil… - Appairé. Veuillez saisir le port indiqué dans les paramètres. - Appareil trouvé. Application des paramètres… - Impossible d\'appliquer automatiquement. Veuillez vérifier l\'adresse ci-dessous et réessayer. %1$s - Débogage sans fil - Limite des processus enfants mise à jour - Modifier la limite des processus enfants - Si cette option n\'est pas disponible, appairez via le débogage sans fil. - Appairé. Veuillez vérifier l\'adresse IP et le port dans le débogage sans fil. - La limite des processus enfants a été mise à jour. - 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. - Appairé. Utilisez l\'adresse ci-dessous, ou mettez-la à jour dans Débogage sans fil → Adresse IP et port. - Limite des processus enfants mise à jour via le débogage sans fil. - Android a confirmé que la limite est activée. - Android a confirmé que la limite est désactivée. - 2 · Appairer le débogage sans fil - Adresse IP et port dans la fenêtre d\'appairage - Code d\'appairage (PIN) - 6 chiffres - Appairer - 2 · Appliquer via le débogage sans fil - Adresse IP et port de connexion - Réappairer - Désactiver la limite - Autres méthodes de modification - 1 · Options pour les développeurs (à essayer en premier) - Désactivez « Désactiver les limites pour les processus enfant ». - Activez « Désactiver les limites pour les processus enfant ». - 3 · ADB sur PC (en dernier recours) - À utiliser uniquement si le débogage sans fil n\'est pas disponible. - 3 · ADB sur PC (en dernier recours) Couleur Personnalisée Opacité @@ -1635,8 +1598,6 @@ %1$d dossiers de journaux de session effacés. %1$d dossiers de journaux de session effacés. - Échec de l\'appairage du débogage sans fil - Échec de la commande de débogage sans fil Le débogage sans fil n\'est pas disponible Commande ADB copiée Choisir le dossier ROM @@ -2775,6 +2736,7 @@ La liaison avec la page de connexion n\'est pas sécurisée. Impossible de vérifier la connexion. Réessayez. Échec de la connexion. Réessayez. + %1$s demande une étape de plus. Terminez-la dans le navigateur qui s\'est ouvert, puis réessayez. Fermer Retour Modifier @@ -3163,7 +3125,7 @@ Terminé En attente de la connexion Ethernet USB des lunettes. Ce téléphone ne la rend peut-être pas accessible aux applications. La connexion XREAL a été interrompue ou a renvoyé une réponse non prise en charge. Nouvelle tentative… - 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. + 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+. 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. Développeur Éditeur @@ -4155,4 +4117,6 @@ Mises en évidence Succès Erreur + Afficher le HUD uniquement pendant une partie + Masquer le HUD lorsqu’aucune image du jeu n’est détectée. diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index b2f2633475..c3b71210f6 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1276,8 +1276,6 @@ डेवलपर विकल्प खोलें इस Android वर्शन में इसके लिए कोई स्विच नहीं है, इसलिए DroidDeck इसे वायरलेस डीबगिंग के ज़रिए बदलता है। इसमें लगभग एक मिनट लगता है, किसी कंप्यूटर की ज़रूरत नहीं। वायरलेस डीबगिंग के लिए Wi-Fi चाहिए। कोई भी नेटवर्क काम करेगा; इंटरनेट की ज़रूरत नहीं है। - पेयरिंग कोड एक नोटिफ़िकेशन में आता है। DroidDeck के लिए नोटिफ़िकेशन की अनुमति दें, या अन्य तरीके इस्तेमाल करें। - नोटिफ़िकेशन की अनुमति दें Settings → डेवलपर विकल्प → वायरलेस डीबगिंग खोलें और उसे चालू करें “Pair device with pairing code” पर टैप करें DroidDeck नोटिफ़िकेशन में कोड टाइप करें @@ -1294,48 +1292,13 @@ स्थिति हर 2 सेकंड में जांच हो रही है। यह बंद होने पर यह पेज बंद हो जाता है। अन्य तरीके - वायरलेस डीबगिंग, मैनुअल एड्रेस, कंप्यूटर ADB - मैनुअल एड्रेस, कंप्यूटर ADB, डेवलपर विकल्प इसके बदले वायरलेस डीबगिंग इस्तेमाल करें कुछ ROM फिर भी यह स्विच जोड़ देते हैं। डेवलपर विकल्प में “child process” देखें। - अगर नोटिफ़िकेशन काम न करे, तो पॉप-अप का एड्रेस और कोड खुद डालें। - एड्रेस खुद डालें ADB वाले कंप्यूटर से: कमांड कॉपी करें हेडसेट को कंप्यूटर से जोड़ें और SideQuest खोलें। “Run ADB Command”, फिर “Custom Command” चुनें, नीचे दिखाया गया कमांड टाइप करें और “Run Command” चुनें। Android Settings किस डिस्प्ले पर खोलना है चुनें। मुख्य स्क्रीन - पेयर हो गया। वायरलेस डीबगिंग का पोर्ट खोजा जा रहा है… - पेयर हो गया। Settings से पोर्ट डालें। - डिवाइस मिल गया। सेटिंग लागू की जा रही है… - खुद लागू नहीं हो सका। नीचे दिया एड्रेस जांचें और फिर कोशिश करें। %1$s - वायरलेस डीबगिंग - चाइल्ड-प्रोसेस सीमा अपडेट हुई - चाइल्ड-प्रोसेस सीमा बदलें - अगर यह विकल्प न हो, तो वायरलेस डीबगिंग से पेयर करें। - पेयर हो गया। वायरलेस डीबगिंग में IP एड्रेस और पोर्ट जांचें। - चाइल्ड-प्रोसेस सीमा अपडेट हो गई। - अगर डेवलपर विकल्प में चाइल्ड-प्रोसेस सेटिंग न हो तो स्टेप 2 इस्तेमाल करें। डेवलपर विकल्प → वायरलेस डीबगिंग → Pair device with pairing code खोलें। - पेयर हो गया। नीचे दिया एड्रेस इस्तेमाल करें, या इसे वायरलेस डीबगिंग → IP address & Port से अपडेट करें। - चाइल्ड-प्रोसेस सीमा वायरलेस डीबगिंग के ज़रिए अपडेट हो गई। - Android ने पुष्टि की कि सीमा चालू है। - Android ने पुष्टि की कि सीमा बंद है। - 2 · वायरलेस डीबगिंग पेयर करें - पेयरिंग पॉप-अप का IP एड्रेस और पोर्ट - पेयरिंग कोड (PIN) - 6 अंक - पेयर करें - 2 · वायरलेस डीबगिंग के ज़रिए लागू करें - कनेक्शन का IP एड्रेस और पोर्ट - फिर से पेयर करें - सीमा बंद करें - इसे बदलने के अन्य तरीके - 1 · डेवलपर विकल्प (पहले आज़माएं) - “चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” बंद करें। - “चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” चालू करें। - 3 · कंप्यूटर ADB (आख़िरी विकल्प) - सिर्फ़ तब जब वायरलेस डीबगिंग उपलब्ध न हो। - 3 · कंप्यूटर ADB (आख़िरी विकल्प) रंग कस्टम ओपैसिटी @@ -1623,8 +1586,6 @@ %1$d सेशन लॉग फ़ोल्डर हटाया गया। %1$d सेशन लॉग फ़ोल्डर हटाए गए। - वायरलेस डीबगिंग पेयरिंग विफल रही - वायरलेस डीबगिंग कमांड विफल रहा वायरलेस डीबगिंग उपलब्ध नहीं है ADB कमांड कॉपी हो गया ROM फ़ोल्डर चुनें @@ -2753,6 +2714,7 @@ साइन-इन पेज से कनेक्शन सुरक्षित नहीं है। साइन-इन सत्यापित नहीं हो सका। फिर कोशिश करें। साइन-इन विफल रहा। फिर कोशिश करें। + %1$s को एक और चरण चाहिए। खुले हुए ब्राउज़र में इसे पूरा करें, फिर दोबारा कोशिश करें। बंद करें बैक संपादित करें @@ -3137,7 +3099,7 @@ हो गया चश्मे के USB Ethernet कनेक्शन का इंतज़ार है। हो सकता है यह फ़ोन इसे ऐप्स को उपलब्ध न कराए। XREAL कनेक्शन टूट गया या उसने ऐसा जवाब दिया जो समर्थित नहीं है। फिर से कोशिश हो रही है… - 1S के लिए प्रायोगिक सपोर्ट। चश्मे के मेनू में Follow मोड चुनें और स्टेबिलाइज़ेशन बंद करें। ट्रैकिंग की दिशाएं और डिस्प्ले मोड अभी डिवाइस पर टेस्ट होने बाकी हैं। + XREAL 1S, One, One Pro, One Pro+ और Aura के लिए प्रायोगिक सपोर्ट। चश्मे के मेनू में Follow मोड चुनें और स्टेबिलाइज़ेशन बंद करें; Aura पर Spatial Anchor भी बंद करें। Aura और One Pro+ पर हेड ट्रैकिंग और 2D/3D स्विचिंग का परीक्षण किया गया है। Pro 2 के लिए प्रायोगिक हेड ट्रैकिंग। चमक और वॉल्यूम बदलना और डिस्प्ले मोड स्विच करना अभी समर्थित नहीं है। Cardboard VR Cardboard मोड @@ -4116,4 +4078,6 @@ हाइलाइट सफलता त्रुटि + HUD केवल गेम के दौरान दिखाएँ + गेम के फ़्रेम का पता न चलने पर HUD छिपाएँ। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index b9d15f6725..8c51e3cf8a 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -1276,8 +1276,6 @@ Fejlesztői beállítások megnyitása 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. A vezeték nélküli hibakereséshez Wi-Fi szükséges. Bármelyik hálózat megfelel; internetkapcsolat nem szükséges. - 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. - Értesítések engedélyezése Nyissa meg: Beállítások → Fejlesztői beállítások → Vezeték nélküli hibakeresés, és kapcsolja be Koppintson az „Eszköz párosítása párosítási kóddal” lehetőségre Írja be a kódot a DroidDeck értesítésébe @@ -1294,48 +1292,13 @@ Állapot Ellenőrzés 2 másodpercenként. Ez az oldal bezárul, amikor kikapcsol. Egyéb módok - Vezeték nélküli hibakeresés, manuális cím, számítógépes ADB - Manuális cím, számítógépes ADB, Fejlesztői beállítások Vezeték nélküli hibakeresés használata helyette Néhány ROM mindenképpen hozzáadja a kapcsolót. Keresse a „gyermekfolyamat” kifejezést a Fejlesztői beállításokban. - 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. - Cím kézi megadása Egy ADB-vel rendelkező számítógépről: Parancs másolása 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. Válassza ki, melyik kijelzőn nyíljon meg az Android Beállítások. Fő képernyő - Párosítva. A vezeték nélküli hibakeresés portjának keresése… - Párosítva. Adja meg a portot a Beállításokból. - Eszköz megtalálva. A beállítás alkalmazása… - Nem sikerült automatikusan alkalmazni. Ellenőrizze az alábbi címet, és próbálja újra. %1$s - Vezeték nélküli hibakeresés - A gyermekfolyamat-korlát frissítve - A gyermekfolyamat-korlát módosítása - Ha a beállítás hiányzik, párosítson a vezeték nélküli hibakeresésen keresztül. - Párosítva. Ellenőrizze az IP-címet és a portot a vezeték nélküli hibakeresésben. - A gyermekfolyamat-korlát frissítve. - 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. - 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. - A gyermekfolyamat-korlát frissítve a vezeték nélküli hibakeresésen keresztül. - Az Android megerősítette, hogy a korlát be van kapcsolva. - Az Android megerősítette, hogy a korlát ki van kapcsolva. - 2 · Vezeték nélküli hibakeresés párosítása - A párosítási felugró ablak IP-címe és portja - Párosítási kód (PIN) - 6 számjegy - Párosítás - 2 · Alkalmazás vezeték nélküli hibakeresésen keresztül - Kapcsolat IP-címe és portja - Párosítás újra - Korlát kikapcsolása - Egyéb módok a módosítására - 1 · Fejlesztői beállítások (próbálja ezt először) - Kapcsolja ki az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget. - Kapcsolja be az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget. - 3 · Számítógépes ADB (végső megoldás) - Csak ha a vezeték nélküli hibakeresés nem elérhető. - 3 · Számítógépes ADB (végső megoldás) Szín Egyéni Átlátszatlanság @@ -1623,8 +1586,6 @@ %1$d munkamenet-naplómappa törölve. %1$d munkamenet-naplómappa törölve. - A vezeték nélküli hibakeresés párosítása sikertelen - A vezeték nélküli hibakeresés parancsa sikertelen A vezeték nélküli hibakeresés nem áll rendelkezésre ADB-parancs másolva ROMs mappa kiválasztása @@ -2753,6 +2714,7 @@ A kapcsolat a bejelentkezési oldalhoz nem biztonságos. A bejelentkezést nem sikerült ellenőrizni. Próbálja újra. A bejelentkezés sikertelen. Próbálja újra. + 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. Bezárás Vissza Szerkesztés @@ -3137,7 +3099,7 @@ Kész 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. Az XREAL-kapcsolat megszakadt, vagy nem támogatott választ adott. Újrapróbálkozás… - 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. + 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. 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. Cardboard VR Cardboard mód @@ -4116,4 +4078,6 @@ Kiemelések Siker Hiba + HUD megjelenítése csak játék közben + HUD elrejtése, ha nem észlelhetők játék képkockái. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 56dd216a98..d067290684 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -1270,8 +1270,6 @@ Buka Opsi pengembang Versi Android ini tidak memiliki sakelar untuk itu, sehingga DroidDeck mengubahnya melalui Debugging nirkabel. Membutuhkan waktu sekitar satu menit, tanpa komputer. Debugging nirkabel memerlukan Wi-Fi. Jaringan apa pun berfungsi; tidak perlu internet. - Kode pemasangan muncul di notifikasi. Izinkan notifikasi untuk DroidDeck, atau gunakan Cara lain. - Izinkan notifikasi Buka Setelan → Opsi pengembang → Debugging nirkabel dan aktifkan Ketuk “Pasangkan perangkat dengan kode pemasangan” Masukkan kode ke notifikasi DroidDeck @@ -1288,48 +1286,13 @@ Status Memeriksa setiap 2 detik. Halaman ini akan tertutup saat statusnya nonaktif. Cara lain - Debugging nirkabel, alamat manual, ADB komputer - Alamat manual, ADB komputer, Opsi pengembang Gunakan Debugging nirkabel sebagai gantinya Beberapa ROM menambahkan sakelar ini juga. Cari “child process” di Opsi pengembang. - Jika notifikasinya tidak berfungsi, masukkan sendiri alamat dan kode dari jendela pemasangan. - Masukkan alamat secara manual Dari komputer dengan ADB: Salin perintah Hubungkan headset ke komputer dan buka SideQuest. Pilih “Run ADB Command”, lalu “Custom Command”, ketik perintah yang ditampilkan di bawah, dan pilih “Run Command”. Pilih tampilan tempat membuka Setelan Android. Layar utama - Berhasil dipasangkan. Mencari port Debugging nirkabel… - Berhasil dipasangkan. Masukkan port dari Setelan. - Perangkat ditemukan. Menerapkan setelan… - Tidak dapat menerapkan secara otomatis. Periksa alamat di bawah dan coba lagi. %1$s - Debugging nirkabel - Batas proses turunan diperbarui - Ubah batas proses turunan - Jika opsinya tidak ada, pasangkan melalui Debugging nirkabel. - Berhasil dipasangkan. Periksa alamat IP dan port di Debugging nirkabel. - Batas proses turunan telah diperbarui. - Gunakan langkah 2 jika Opsi pengembang tidak memiliki setelan proses turunan. Buka Opsi pengembang → Debugging nirkabel → Pasangkan perangkat dengan kode pemasangan. - Berhasil dipasangkan. Gunakan alamat di bawah, atau perbarui dari Debugging nirkabel → Alamat IP & Port. - Batas proses turunan telah diperbarui melalui Debugging nirkabel. - Android mengonfirmasi batas ini aktif. - Android mengonfirmasi batas ini nonaktif. - 2 · Pasangkan Debugging nirkabel - Alamat IP & port jendela pemasangan - Kode pemasangan (PIN) - 6 digit - Pasangkan - 2 · Terapkan melalui Debugging nirkabel - Alamat IP & port koneksi - Pasangkan lagi - Nonaktifkan batas - Cara lain untuk mengubahnya - 1 · Opsi pengembang (coba dahulu) - Nonaktifkan “Nonaktifkan batasan proses turunan”. - Aktifkan “Nonaktifkan batasan proses turunan”. - 3 · ADB komputer (upaya terakhir) - Hanya jika Debugging nirkabel tidak tersedia. - 3 · ADB komputer (upaya terakhir) Warna Khusus Opasitas @@ -1611,8 +1574,6 @@ %1$d folder log sesi dihapus. - Penyambungan debugging nirkabel gagal - Perintah debugging nirkabel gagal Debugging nirkabel tidak tersedia Perintah ADB disalin Pilih folder ROMs @@ -2728,6 +2689,7 @@ Koneksi ke halaman masuk tidak aman. Proses masuk tidak dapat diverifikasi. Coba lagi. Proses masuk gagal. Coba lagi. + %1$s memerlukan satu langkah lagi. Selesaikan di browser yang terbuka, lalu coba lagi. Tutup Kembali Edit @@ -3108,7 +3070,7 @@ Selesai Menunggu koneksi Ethernet USB dari kacamata. Ponsel ini mungkin tidak menyediakannya untuk aplikasi. Koneksi XREAL terputus atau memberikan respons yang tidak didukung. Mencoba lagi… - Dukungan 1S eksperimental. Gunakan mode Follow dan nonaktifkan stabilisasi di menu kacamata. Arah pelacakan dan mode tampilan masih perlu diuji di perangkat. + 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+. Pelacakan kepala Pro 2 eksperimental. Pengaturan kecerahan, volume, dan pergantian mode tampilan belum didukung. Cardboard VR Mode Cardboard @@ -4086,4 +4048,6 @@ Sorotan Berhasil Kesalahan + Tampilkan HUD hanya saat bermain + Sembunyikan HUD saat tidak ada frame game yang terdeteksi. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 9d574d4ba4..2dfa1da981 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1274,8 +1274,6 @@ Apri Opzioni sviluppatore 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. Il Debug wireless richiede il Wi-Fi. Va bene qualsiasi rete; non serve l\'accesso a internet. - Il codice di accoppiamento arriva in una notifica. Consenti le notifiche per DroidDeck, oppure usa Altri modi. - Consenti notifiche Apri Impostazioni → Opzioni sviluppatore → Debug wireless e attivalo Tocca “Accoppia dispositivo con codice di accoppiamento” Digita il codice nella notifica di DroidDeck @@ -1292,48 +1290,13 @@ Stato Controllo ogni 2 secondi. Questa pagina si chiude quando è disattivato. Altri modi - Debug wireless, indirizzo manuale, ADB da computer - Indirizzo manuale, ADB da computer, Opzioni sviluppatore Usa invece il Debug wireless Alcune ROM aggiungono comunque l\'interruttore. Cerca “processi figlio” nelle Opzioni sviluppatore. - Se la notifica non funziona, inserisci tu l\'indirizzo e il codice del popup. - Inserisci l\'indirizzo manualmente Da un computer con ADB: Copia comando 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”. Scegli su quale schermo aprire le Impostazioni di Android. Schermo principale - Accoppiato. Ricerca della porta del Debug wireless… - Accoppiato. Inserisci la porta dalle Impostazioni. - Dispositivo trovato. Applicazione dell\'impostazione… - Impossibile applicare automaticamente. Controlla l\'indirizzo qui sotto e riprova. %1$s - Debug wireless - Limite dei processi figlio aggiornato - Cambia il limite dei processi figlio - Se l\'opzione non è presente, accoppia tramite il Debug wireless. - Accoppiato. Controlla l\'indirizzo IP e la porta nel Debug wireless. - Il limite dei processi figlio è stato aggiornato. - 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. - Accoppiato. Usa l\'indirizzo qui sotto, oppure aggiornalo da Debug wireless → Indirizzo IP e porta. - Il limite dei processi figlio è stato aggiornato tramite il Debug wireless. - Android ha confermato che il limite è attivo. - Android ha confermato che il limite è disattivato. - 2 · Accoppia il Debug wireless - Indirizzo IP e porta del popup di accoppiamento - Codice di accoppiamento (PIN) - 6 cifre - Accoppia - 2 · Applica tramite il Debug wireless - Indirizzo IP e porta di connessione - Accoppia di nuovo - Disattiva il limite - Altri modi per cambiarlo - 1 · Opzioni sviluppatore (da provare prima) - Disattiva “Disattiva limitazioni per i processi secondari”. - Attiva “Disattiva limitazioni per i processi secondari”. - 3 · ADB da computer (ultima risorsa) - Solo se il Debug wireless non è disponibile. - 3 · ADB da computer (ultima risorsa) Colore Personalizzato Opacità @@ -1627,8 +1590,6 @@ %1$d cartelle di log di sessione cancellate. %1$d cartelle di log di sessione cancellate. - Accoppiamento per il debug wireless non riuscito - Comando di debug wireless non riuscito Il debug wireless non è disponibile Comando ADB copiato Scegli la cartella delle ROM @@ -2767,6 +2728,7 @@ La connessione alla pagina di accesso non è sicura. Impossibile verificare l\'accesso. Riprova. Accesso non riuscito. Riprova. + %1$s richiede un altro passaggio. Completalo nel browser che si è aperto, poi riprova. Chiudi Indietro Modifica @@ -3155,7 +3117,7 @@ Fine In attesa della connessione USB Ethernet degli occhiali. Questo telefono potrebbe non renderla disponibile alle app. La connessione XREAL si è interrotta o ha restituito una risposta non supportata. Nuovo tentativo… - 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. + 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+. Tracciamento sperimentale della testa per Pro 2. La regolazione di luminosità e volume e il cambio della modalità di visualizzazione non sono ancora supportati. Cardboard VR Modalità Cardboard @@ -4155,4 +4117,6 @@ Evidenziazioni Successo Errore + Mostra l’HUD solo durante il gioco + Nascondi l’HUD quando non vengono rilevati fotogrammi del gioco. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index f09bbbff7a..b51efa75a8 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1270,8 +1270,6 @@ 開発者向けオプションを開く このAndroidバージョンにはこのスイッチがないため、DroidDeckはワイヤレスデバッグを介して変更します。約1分かかり、PCは不要です。 ワイヤレスデバッグにはWi-Fiが必要です。ネットワークは何でもよく、インターネットは不要です。 - ペアリングコードは通知に表示されます。DroidDeckに通知を許可するか、「他の方法」を使用してください。 - 通知を許可 設定 → 開発者向けオプション → ワイヤレスデバッグを開き、オンにする 「ペアリングコードでデバイスをペア設定」をタップ DroidDeckの通知にペアリングコードを入力 @@ -1288,48 +1286,13 @@ ステータス 2秒ごとに確認します。このスイッチをオフにすると、このページは自動的に閉じます。 他の方法 - ワイヤレスデバッグ、手動でアドレス入力、PC ADB - 手動でアドレス入力、PC ADB、開発者向けオプション 代わりにワイヤレスデバッグを使用 一部のROMではこのスイッチが提供されています。開発者向けオプションで「子プロセス」を検索してください。 - 通知方法が機能しない場合は、ポップアップのアドレスとペアリングコードを手動で入力してください。 - 手動でアドレスを入力 PCでADBを使用: コマンドをコピー ヘッドセットをパソコンにつないで SideQuest を開きます。「Run ADB Command」→「Custom Command」を選び、下に表示されたコマンドを入力して「Run Command」を選びます。 Android設定をどの画面で開くか選択してください。 メイン画面 - ペアリング済み。ワイヤレスデバッグのポートを検索中… - ペアリング済み。設定のポートを入力してください。 - デバイスが見つかりました。設定を適用中… - 自動適用できませんでした。以下のアドレスを確認して再試行してください。 %1$s - ワイヤレスデバッグ - 子プロセス制限を更新しました - 子プロセス制限の変更 - オプションがない場合は、ワイヤレスデバッグでペアリングしてください。 - ペアリング済み。ワイヤレスデバッグのIPアドレスとポートを確認してください。 - 子プロセス制限を更新しました。 - 開発者向けオプションに子プロセス設定がない場合は、手順2を使用してください。開発者向けオプション → ワイヤレスデバッグ → ペアリングコードでデバイスをペア設定を開きます。 - ペアリング済み。以下のアドレスを使用するか、ワイヤレスデバッグ → IPアドレスとポートで更新してください。 - ワイヤレスデバッグを介して子プロセス制限を更新しました。 - Androidは制限がオンであることを確認しました。 - Androidは制限がオフであることを確認しました。 - 2 · ワイヤレスデバッグのペアリング - ポップアップのIPアドレスとポート - ペアリングコード(PIN) - 6桁の数字 - ペアリング - 2 · ワイヤレスデバッグで適用 - 接続先のIPアドレスとポート - 再ペアリング - 制限をオフにする - その他の変更方法 - 1 · 開発者向けオプション(最初に試す) - 「子プロセスの制限を無効化」をオフにします。 - 「子プロセスの制限を無効化」をオンにします。 - 3 · PC ADB(最終手段) - ワイヤレスデバッグが利用できない場合にのみ使用してください。 - 3 · PC ADB(最終手段) 色 カスタム 不透明度 @@ -1611,8 +1574,6 @@ %1$d個のセッションログフォルダを消去しました。 - ワイヤレスデバッグのペアリングに失敗しました - ワイヤレスデバッグのコマンドに失敗しました ワイヤレスデバッグは利用できません ADBコマンドをコピーしました ROMフォルダを選択 @@ -2728,6 +2689,7 @@ ログインページへの接続は安全ではありません。 ログインを確認できませんでした。もう一度お試しください。 ログインに失敗しました。もう一度お試しください。 + %1$s で追加の手順が必要です。開いたブラウザーで完了してから、もう一度お試しください。 閉じる 戻る 編集 @@ -3108,7 +3070,7 @@ 完了 グラスの USB Ethernet 接続を待っています。このスマートフォンでは、アプリがこの接続を利用できない場合があります。 XREAL との接続が中断されたか、サポートされていない応答が返されました。再試行しています… - 1S のサポートは試験運用中です。グラスのメニューで Follow モードを使い、安定化をオフにしてください。トラッキングの方向と表示モードは、まだ実機でのテストが必要です。 + XREAL 1S、One、One Pro、One Pro+、Auraの試験的なサポートです。グラスのメニューでFollowモードを使用し、安定化をオフにしてください。AuraではSpatial Anchorもオフにしてください。ヘッドトラッキングと2D/3D切り替えは、AuraとOne Pro+でテスト済みです。 Pro 2 のヘッドトラッキングは試験運用中です。明るさと音量の調整、および表示モードの切り替えにはまだ対応していません。 開発元 パブリッシャー @@ -4086,4 +4048,6 @@ 強調表示 成功 エラー + ゲーム中のみHUDを表示 + ゲームのフレームが検出されないときはHUDを非表示にする。 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index d7b6c044a1..8b3f92a2a9 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1270,8 +1270,6 @@ 개발자 옵션 열기 이 Android 버전에는 해당 스위치가 없으므로 DroidDeck이 무선 디버깅을 통해 수정합니다. 약 1분이 걸리며 PC가 필요하지 않습니다. 무선 디버깅에는 Wi-Fi가 필요합니다. 네트워크는 아무거나 괜찮으며 인터넷은 필요하지 않습니다. - 페어링 코드가 알림에 표시됩니다. DroidDeck에 알림을 허용하거나 \"다른 방법\"을 사용하세요. - 알림 허용 설정 → 개발자 옵션 → 무선 디버깅을 열고 켜기 \"페어링 코드로 기기 페어링\" 탭 DroidDeck 알림에 페어링 코드 입력 @@ -1288,48 +1286,13 @@ 상태 2초마다 확인합니다. 이 스위치를 끄면 이 페이지가 자동으로 닫힙니다. 다른 방법 - 무선 디버깅, 수동 주소 입력, PC ADB - 수동 주소 입력, PC ADB, 개발자 옵션 대신 무선 디버깅 사용 일부 ROM에서는 이 스위치를 제공합니다. 개발자 옵션에서 \"하위 프로세스\"를 검색하세요. - 알림 방법이 작동하지 않으면 팝업의 주소와 페어링 코드를 수동으로 입력하세요. - 수동으로 주소 입력 PC에서 ADB 사용: 명령 복사 헤드셋을 컴퓨터에 연결하고 SideQuest를 엽니다. “Run ADB Command”, “Custom Command”를 차례로 선택하고 아래에 표시된 명령을 입력한 뒤 “Run Command”를 선택하세요. Android 설정을 어느 화면에서 열지 선택하세요. 메인 화면 - 페어링됨. 무선 디버깅 포트를 찾는 중… - 페어링됨. 설정의 포트를 입력하세요. - 기기를 찾았습니다. 설정을 적용하는 중… - 자동으로 적용할 수 없습니다. 아래 주소를 확인한 후 다시 시도하세요. %1$s - 무선 디버깅 - 하위 프로세스 제한 업데이트됨 - 하위 프로세스 제한 변경 - 옵션이 없으면 무선 디버깅으로 페어링하세요. - 페어링됨. 무선 디버깅의 IP 주소와 포트를 확인하세요. - 하위 프로세스 제한이 업데이트되었습니다. - 개발자 옵션에 하위 프로세스 설정이 없으면 2단계를 사용하세요. 개발자 옵션 → 무선 디버깅 → 페어링 코드로 기기 페어링을 엽니다. - 페어링됨. 아래 주소를 사용하거나 무선 디버깅 → IP 주소 및 포트에서 업데이트하세요. - 무선 디버깅을 통해 하위 프로세스 제한을 업데이트했습니다. - Android에서 제한이 켜져 있음을 확인했습니다. - Android에서 제한이 꺼져 있음을 확인했습니다. - 2 · 무선 디버깅 페어링 - 페어링 팝업의 IP 주소 및 포트 - 페어링 코드(PIN) - 6자리 숫자 - 페어링 - 2 · 무선 디버깅으로 적용 - 연결할 IP 주소 및 포트 - 다시 페어링 - 제한 끄기 - 기타 변경 방법 - 1 · 개발자 옵션(먼저 시도) - \"하위 프로세스 제한 사용 중지\"를 끕니다. - \"하위 프로세스 제한 사용 중지\"를 켭니다. - 3 · PC ADB(최후의 수단) - 무선 디버깅을 사용할 수 없을 때만 사용하세요. - 3 · PC ADB(최후의 수단) 색상 사용자 정의 불투명도 @@ -1611,8 +1574,6 @@ 세션 로그 폴더 %1$d개를 지웠습니다. - 무선 디버깅 페어링 실패 - 무선 디버깅 명령 실패 무선 디버깅을 사용할 수 없습니다 ADB 명령이 복사되었습니다 ROM 폴더 선택 @@ -2728,6 +2689,7 @@ 로그인 페이지 연결이 안전하지 않습니다. 로그인을 확인할 수 없습니다. 다시 시도하세요. 로그인에 실패했습니다. 다시 시도하세요. + %1$s에서 한 단계가 더 필요합니다. 열린 브라우저에서 완료한 다음 다시 시도하세요. 닫기 뒤로 편집 @@ -3108,7 +3070,7 @@ 완료 안경의 USB Ethernet 연결을 기다리는 중입니다. 이 휴대폰은 앱에 이 연결을 제공하지 않을 수 있습니다. XREAL 연결이 중단되었거나 지원되지 않는 응답을 받았습니다. 다시 시도하는 중… - 1S 지원은 실험 단계입니다. 안경 메뉴에서 Follow 모드를 사용하고 안정화를 끄세요. 트래킹 방향과 디스플레이 모드는 아직 기기에서 테스트가 필요합니다. + XREAL 1S, One, One Pro, One Pro+ 및 Aura의 실험적 지원입니다. 안경 메뉴에서 Follow 모드를 사용하고 안정화를 끄세요. Aura에서는 Spatial Anchor도 끄세요. 헤드 트래킹과 2D/3D 전환은 Aura와 One Pro+에서 테스트되었습니다. Pro 2 헤드 트래킹은 실험 단계입니다. 밝기와 음량 조절 및 디스플레이 모드 전환은 아직 지원되지 않습니다. 개발사 배급사 @@ -4086,4 +4048,6 @@ 강조 표시 성공 오류 + 게임 중에만 HUD 표시 + 게임 프레임이 감지되지 않으면 HUD 숨기기. diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index c4c67b0b6f..95364b21d1 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -1270,8 +1270,6 @@ Buka Pilihan pembangun Versi Android ini tidak mempunyai suis untuknya, jadi DroidDeck menukarnya melalui Debugging Wayarles. Mengambil masa kira-kira seminit, tanpa komputer diperlukan. Debugging Wayarles memerlukan Wi-Fi. Mana-mana rangkaian berfungsi; ia tidak memerlukan internet. - Kod gandingan dihantar dalam pemberitahuan. Benarkan pemberitahuan untuk DroidDeck, atau gunakan Cara lain. - Benarkan pemberitahuan Buka Tetapan → Pilihan pembangun → Debugging Wayarles dan hidupkannya Ketik “Gandingkan peranti dengan kod gandingan” Taip kod itu ke dalam pemberitahuan DroidDeck @@ -1288,48 +1286,13 @@ Status Menyemak setiap 2 saat. Halaman ini ditutup apabila ia mati. Cara lain - Debugging Wayarles, alamat manual, ADB komputer - Alamat manual, ADB komputer, Pilihan pembangun Gunakan Debugging Wayarles sebaliknya Sesetengah ROM turut menambah suis itu. Cari “proses anak” dalam Pilihan pembangun. - Jika pemberitahuan tidak berfungsi, masukkan alamat dan kod tetingkap timbul itu sendiri. - Masukkan alamat secara manual Daripada komputer dengan ADB: Salin arahan 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”. Pilih paparan mana untuk membuka Tetapan Android. Skrin utama - Digandingkan. Mencari port Debugging Wayarles… - Digandingkan. Masukkan port daripada Tetapan. - Peranti dijumpai. Menggunakan tetapan… - Tidak dapat digunakan secara automatik. Semak alamat di bawah dan cuba lagi. %1$s - Debugging Wayarles - Had proses anak dikemas kini - Tukar had proses anak - Jika pilihan itu tiada, gandingkan melalui Debugging Wayarles. - Digandingkan. Semak alamat IP dan port dalam Debugging Wayarles. - Had proses anak telah dikemas kini. - Gunakan langkah 2 jika Pilihan pembangun tidak mempunyai tetapan proses anak. Buka Pilihan pembangun → Debugging Wayarles → Gandingkan peranti dengan kod gandingan. - Digandingkan. Gunakan alamat di bawah, atau kemas kini daripada Debugging Wayarles → Alamat IP & Port. - Had proses anak telah dikemas kini melalui Debugging Wayarles. - Android mengesahkan had itu hidup. - Android mengesahkan had itu mati. - 2 · Gandingkan Debugging Wayarles - Alamat IP & port tetingkap timbul gandingan - Kod gandingan (PIN) - 6 digit - Gandingkan - 2 · Gunakan melalui Debugging Wayarles - Alamat IP & port sambungan - Gandingkan semula - Matikan had - Cara lain untuk menukarnya - 1 · Pilihan pembangun (cuba dahulu) - Tetapkan “Lumpuhkan sekatan proses anak” mati. - Tetapkan “Lumpuhkan sekatan proses anak” hidup. - 3 · ADB komputer (pilihan akhir) - Hanya jika Debugging Wayarles tidak tersedia. - 3 · ADB komputer (pilihan akhir) Warna Tersuai Kelegapan @@ -1611,8 +1574,6 @@ %1$d folder log sesi dikosongkan. - Gandingan Debugging Wayarles gagal - Arahan Debugging Wayarles gagal Debugging Wayarles tidak tersedia Arahan ADB disalin Pilih folder ROM @@ -2728,6 +2689,7 @@ Sambungan ke halaman log masuk tidak selamat. Log masuk tidak dapat disahkan. Cuba lagi. Log masuk gagal. Cuba lagi. + %1$s memerlukan satu langkah lagi. Selesaikannya dalam pelayar yang dibuka, kemudian cuba lagi. Tutup Kembali Sunting @@ -3108,7 +3070,7 @@ Selesai Menunggu sambungan USB Ethernet cermin mata. Telefon ini mungkin tidak mendedahkannya kepada apl. Sambungan XREAL terganggu atau memberikan respons yang tidak disokong. Mencuba semula… - Sokongan eksperimen untuk 1S. Gunakan mod Follow dan matikan penstabilan dalam menu cermin mata. Arah penjejakan dan mod paparan masih perlu diuji pada peranti. + 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+. Penjejakan kepala Pro 2 secara eksperimen. Pelarasan kecerahan, kelantangan dan pertukaran mod paparan belum disokong. Cardboard VR Mod Cardboard @@ -4086,4 +4048,6 @@ Sorotan Berjaya Ralat + Paparkan HUD hanya semasa bermain + Sembunyikan HUD apabila bingkai permainan tidak dikesan. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 633b16d02e..2fd355eec3 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -1276,8 +1276,6 @@ Åpne Utvikleralternativer 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. Trådløs feilsøking krever Wi-Fi. Hvilket nettverk som helst fungerer; det krever ikke internett. - Koblingskoden kommer i en varsling. Tillat varslinger for DroidDeck, eller bruk Andre måter. - Tillat varslinger Åpne Innstillinger → Utvikleralternativer → Trådløs feilsøking og slå det på Trykk på «Par enhet med koblingskode» Skriv koden inn i DroidDeck-varslingen @@ -1294,48 +1292,13 @@ Status Kontrollerer hvert 2. sekund. Denne siden lukkes når det er av. Andre måter - Trådløs feilsøking, manuell adresse, ADB fra datamaskin - Manuell adresse, ADB fra datamaskin, Utvikleralternativer Bruk trådløs feilsøking i stedet Noen ROM-er legger til bryteren likevel. Se etter «child process» i Utvikleralternativer. - Hvis varslingen ikke fungerer, skriv inn varselets adresse og kode selv. - Skriv inn adresse manuelt Fra en datamaskin med ADB: Kopier kommando Koble headsettet til en datamaskin og åpne SideQuest. Velg «Run ADB Command», deretter «Custom Command», skriv inn kommandoen vist nedenfor og velg «Run Command». Velg hvilken skjerm Android-innstillinger skal åpnes på. Hovedskjerm - Koblet sammen. Finner porten for trådløs feilsøking… - Koblet sammen. Skriv inn porten fra Innstillinger. - Enhet funnet. Bruker innstillingen… - Kunne ikke bruke den automatisk. Kontroller adressen under og prøv igjen. %1$s - Trådløs feilsøking - Grensen for underprosesser er oppdatert - Endre grensen for underprosesser - Hvis alternativet er borte, par over trådløs feilsøking. - Koblet sammen. Kontroller IP-adressen og porten i Trådløs feilsøking. - Grensen for underprosesser ble oppdatert. - Bruk steg 2 hvis Utvikleralternativer ikke har en innstilling for underprosesser. Åpne Utvikleralternativer → Trådløs feilsøking → Par enhet med koblingskode. - Koblet sammen. Bruk adressen under, eller oppdater den fra Trådløs feilsøking → IP-adresse og port. - Grensen for underprosesser ble oppdatert via trådløs feilsøking. - Android bekreftet at grensen er på. - Android bekreftet at grensen er av. - 2 · Koble sammen trådløs feilsøking - IP-adresse og port for koblingsvarsel - Koblingskode (PIN) - 6 tall - Koble sammen - 2 · Bruk via trådløs feilsøking - IP-adresse og port for tilkobling - Koble sammen igjen - Slå av grensen - Andre måter å endre det - 1 · Utvikleralternativer (prøv først) - Slå av «Slå av begrensninger for underordnede prosesser». - Slå på «Slå av begrensninger for underordnede prosesser». - 3 · ADB fra datamaskin (siste utvei) - Bare hvis trådløs feilsøking ikke er tilgjengelig. - 3 · ADB fra datamaskin (siste utvei) Farge Egendefinert Opasitet @@ -1623,8 +1586,6 @@ Tømte %1$d sesjonsloggmappe. Tømte %1$d sesjonsloggmapper. - Kobling for trådløs feilsøking mislyktes - Kommando for trådløs feilsøking mislyktes Trådløs feilsøking er ikke tilgjengelig ADB-kommando kopiert Velg ROM-mappen @@ -2753,6 +2714,7 @@ Tilkoblingen til innloggingssiden er ikke sikker. Innloggingen kunne ikke verifiseres. Prøv igjen. Innlogging mislyktes. Prøv igjen. + %1$s trenger ett trinn til. Fullfør det i nettleseren som ble åpnet, og prøv igjen. Lukk Tilbake Rediger @@ -3137,7 +3099,7 @@ Ferdig Venter på USB Ethernet-tilkoblingen til brillene. Denne telefonen gjør den kanskje ikke tilgjengelig for apper. XREAL-tilkoblingen ble avbrutt eller ga et svar som ikke støttes. Prøver igjen… - Eksperimentell støtte for 1S. Bruk Follow-modus og slå av stabilisering i brillemenyen. Sporingsretninger og visningsmoduser må fortsatt testes på enheten. + 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+. Eksperimentell hodesporing for Pro 2. Justering av lysstyrke og volum samt bytte av visningsmodus støttes ikke ennå. Cardboard VR Cardboard-modus @@ -4116,4 +4078,6 @@ Uthevinger Suksess Feil + Vis HUD bare mens du spiller + Skjul HUD når ingen spillbilder registreres. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 5f51dc1cd4..b788d41499 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1276,8 +1276,6 @@ Opties voor ontwikkelaars openen Deze Android-versie heeft hiervoor geen schakelaar, dus wijzigt DroidDeck dit via Draadloos debuggen. Duurt ongeveer een minuut, geen computer nodig. Draadloos debuggen heeft Wi-Fi nodig. Elk netwerk werkt; internet is niet vereist. - De koppelingscode komt in een melding. Sta meldingen toe voor DroidDeck, of gebruik Andere manieren. - Meldingen toestaan Open Instellingen → Opties voor ontwikkelaars → Draadloos debuggen en zet het aan Tik op “Apparaat koppelen met koppelingscode” Voer de code in bij de melding van DroidDeck @@ -1294,48 +1292,13 @@ Status Controleert elke 2 seconden. Deze pagina sluit zodra het uit staat. Andere manieren - Draadloos debuggen, handmatig adres, computer-ADB - Handmatig adres, computer-ADB, Opties voor ontwikkelaars Gebruik Draadloos debuggen in plaats daarvan Sommige ROMs voegen de schakelaar toch toe. Zoek naar “subproces” in Opties voor ontwikkelaars. - Als de melding niet werkt, voer je het adres en de code van de pop-up zelf in. - Adres handmatig invoeren Vanaf een computer met ADB: Opdracht kopiëren 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’. Kies op welk scherm Android-instellingen wordt geopend. Hoofdscherm - Gekoppeld. Poort van Draadloos debuggen zoeken… - Gekoppeld. Voer de poort uit Instellingen in. - Apparaat gevonden. Instelling toepassen… - Kan niet automatisch worden toegepast. Controleer het adres hieronder en probeer het opnieuw. %1$s - Draadloos debuggen - Limiet voor subprocessen bijgewerkt - De limiet voor subprocessen wijzigen - Als de optie ontbreekt, koppel dan via Draadloos debuggen. - Gekoppeld. Controleer het IP-adres en de poort in Draadloos debuggen. - De limiet voor subprocessen is bijgewerkt. - Gebruik stap 2 als Opties voor ontwikkelaars geen instelling voor subprocessen heeft. Open Opties voor ontwikkelaars → Draadloos debuggen → Apparaat koppelen met koppelingscode. - Gekoppeld. Gebruik het adres hieronder, of werk het bij via Draadloos debuggen → IP-adres & Poort. - De limiet voor subprocessen is bijgewerkt via Draadloos debuggen. - Android heeft bevestigd dat de limiet aan staat. - Android heeft bevestigd dat de limiet uit staat. - 2 · Draadloos debuggen koppelen - IP-adres & poort van de koppelingspop-up - Koppelingscode (pincode) - 6 cijfers - Koppelen - 2 · Toepassen via Draadloos debuggen - IP-adres & poort van de verbinding - Opnieuw koppelen - Limiet uitschakelen - Andere manieren om dit te wijzigen - 1 · Opties voor ontwikkelaars (probeer dit eerst) - Zet “Beperkingen voor onderliggende processen uitzetten” uit. - Zet “Beperkingen voor onderliggende processen uitzetten” aan. - 3 · Computer-ADB (laatste redmiddel) - Alleen als Draadloos debuggen niet beschikbaar is. - 3 · Computer-ADB (laatste redmiddel) Kleur Aangepast Transparantie @@ -1623,8 +1586,6 @@ %1$d map met sessielogs gewist. %1$d mappen met sessielogs gewist. - Koppelen voor draadloze foutopsporing mislukt - Opdracht voor draadloze foutopsporing mislukt Draadloze foutopsporing is niet beschikbaar ADB-opdracht gekopieerd Kies de ROM-map @@ -2753,6 +2714,7 @@ De verbinding met de aanmeldpagina is niet beveiligd. De aanmelding kon niet worden geverifieerd. Probeer het opnieuw. Aanmelden mislukt. Probeer het opnieuw. + %1$s vraagt nog één stap. Rond die af in de browser die is geopend en probeer het opnieuw. Sluiten Terug Bewerken @@ -3137,7 +3099,7 @@ Klaar Wachten op de USB Ethernet-verbinding van de bril. Deze telefoon maakt die mogelijk niet beschikbaar voor apps. De XREAL-verbinding is onderbroken of gaf een niet-ondersteund antwoord. Opnieuw proberen… - 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. + 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+. Experimentele hoofdtracking voor Pro 2. Het aanpassen van helderheid en volume en het wisselen van weergavemodus worden nog niet ondersteund. Cardboard VR Cardboard-modus @@ -4116,4 +4078,6 @@ Accenten Geslaagd Fout + HUD alleen tijdens een game weergeven + Verberg de HUD wanneer er geen gameframes worden gedetecteerd. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 65a0f62751..59fadab554 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1290,8 +1290,6 @@ Otwórz Opcje programisty 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. Debugowanie bezprzewodowe wymaga Wi-Fi. Działa każda sieć; nie musi mieć internetu. - Kod parowania pojawia się w powiadomieniu. Zezwól DroidDeck na powiadomienia albo użyj sekcji „Inne sposoby”. - Zezwól na powiadomienia Otwórz Ustawienia → Opcje programisty → Debugowanie bezprzewodowe i włącz je Dotknij „Sparuj urządzenie za pomocą kodu parowania” Wpisz kod w powiadomieniu DroidDeck @@ -1308,48 +1306,13 @@ Stan Sprawdzanie co 2 sekundy. Ta strona zamknie się, gdy przełącznik będzie wyłączony. Inne sposoby - Debugowanie bezprzewodowe, adres ręczny, komputer z ADB - Adres ręczny, komputer z ADB, Opcje programisty Użyj za to debugowania bezprzewodowego Niektóre ROM-y dodają ten przełącznik mimo to. Poszukaj „child process” w Opcjach programisty. - Jeśli powiadomienie nie działa, wpisz adres i kod z okienka samodzielnie. - Wpisz adres ręcznie Z komputera z ADB: Kopiuj polecenie 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”. Wybierz, na którym ekranie otworzyć Ustawienia Androida. Ekran główny - Sparowano. Wyszukiwanie portu debugowania bezprzewodowego… - Sparowano. Wpisz port z Ustawień. - Znaleziono urządzenie. Stosowanie ustawienia… - Nie udało się zastosować automatycznie. Sprawdź adres poniżej i spróbuj ponownie. %1$s - Debugowanie bezprzewodowe - Limit procesów podrzędnych zmieniony - Zmień limit procesów podrzędnych - Jeśli opcja jest niedostępna, sparuj przez debugowanie bezprzewodowe. - Sparowano. Sprawdź adres IP i port w Debugowaniu bezprzewodowym. - Limit procesów podrzędnych został zmieniony. - 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. - Sparowano. Użyj adresu poniżej lub zaktualizuj go z Debugowanie bezprzewodowe → Adres IP i port. - Limit procesów podrzędnych został zmieniony przez debugowanie bezprzewodowe. - Android potwierdził, że limit jest włączony. - Android potwierdził, że limit jest wyłączony. - 2 · Sparuj debugowanie bezprzewodowe - Adres IP i port okienka parowania - Kod parowania (PIN) - 6 cyfr - Sparuj - 2 · Zastosuj przez debugowanie bezprzewodowe - Adres IP i port połączenia - Sparuj ponownie - Wyłącz limit - Inne sposoby na zmianę tego - 1 · Opcje programisty (spróbuj najpierw) - Ustaw „Wyłącz ograniczenia procesów podrzędnych aplikacji” na wyłączone. - Ustaw „Wyłącz ograniczenia procesów podrzędnych aplikacji” na włączone. - 3 · Komputer z ADB (ostatnia opcja) - Tylko jeśli debugowanie bezprzewodowe jest niedostępne. - 3 · Komputer z ADB (ostatnia opcja) Kolor Własny Przezroczystość @@ -1649,8 +1612,6 @@ Wyczyszczono %1$d folderów logów sesji. Wyczyszczono %1$d folderu logów sesji. - Parowanie przez debugowanie bezprzewodowe nie powiodło się - Polecenie debugowania bezprzewodowego nie powiodło się Debugowanie bezprzewodowe jest niedostępne Skopiowano polecenie ADB Wybierz folder ROM-ów @@ -2805,6 +2766,7 @@ Połączenie ze stroną logowania nie jest bezpieczne. Nie udało się zweryfikować logowania. Spróbuj ponownie. Logowanie nie powiodło się. Spróbuj ponownie. + %1$s wymaga jeszcze jednego kroku. Dokończ go w otwartej przeglądarce, a potem spróbuj ponownie. Zamknij Wstecz Edytuj @@ -3197,7 +3159,7 @@ Gotowe Oczekiwanie na połączenie USB Ethernet okularów. Ten telefon może nie udostępniać go aplikacjom. Połączenie z XREAL zostało przerwane lub zwróciło nieobsługiwaną odpowiedź. Ponawianie… - 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. + 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+. 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. Cardboard VR Tryb Cardboard @@ -4196,4 +4158,6 @@ Wyróżnienia Sukces Błąd + Pokazuj HUD tylko podczas gry + Ukryj HUD, gdy nie wykryto klatek gry. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index df9839df35..5e1f62f5d1 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -1274,8 +1274,6 @@ Abrir Opções de programador 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. A Depuração sem fios requer Wi-Fi. Qualquer rede serve; não precisa de Internet. - O código de sincronização é introduzido numa notificação. Permita as notificações do DroidDeck ou utilize Outras formas. - Permitir notificações Abra Definições → Opções de programador → Depuração sem fios e ative-a Toque em “Sincronizar dispositivo com código de sincronização” Escreva o código na notificação do DroidDeck @@ -1292,48 +1290,13 @@ Estado A verificar a cada 2 segundos. Esta página fecha-se quando estiver desativado. Outras formas - Depuração sem fios, endereço manual, ADB num computador - Endereço manual, ADB num computador, Opções de programador Utilizar antes a Depuração sem fios Algumas ROMs adicionam o interruptor mesmo assim. Procure “processos secundários” nas Opções de programador. - Se a notificação não funcionar, introduza manualmente o endereço e o código da janela. - Introduzir endereço manualmente A partir de um computador com ADB: Copiar comando 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”. Escolha em que ecrã abrir as Definições do Android. Ecrã principal - Sincronizado. A procurar a porta da Depuração sem fios… - Sincronizado. Introduza a porta indicada nas Definições. - Dispositivo encontrado. A aplicar a definição… - Não foi possível aplicar automaticamente. Verifique o endereço abaixo e tente novamente. %1$s - Depuração sem fios - Limite de processos secundários atualizado - Alterar o limite de processos secundários - Se a opção não existir, sincronize através da Depuração sem fios. - Sincronizado. Verifique o endereço IP e a porta na Depuração sem fios. - O limite de processos secundários foi atualizado. - 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. - Sincronizado. Utilize o endereço abaixo ou atualize-o em Depuração sem fios → Endereço IP e porta. - O limite de processos secundários foi atualizado através da Depuração sem fios. - O Android confirmou que o limite está ativado. - O Android confirmou que o limite está desativado. - 2 · Sincronizar a Depuração sem fios - Endereço IP e porta da janela de sincronização - Código de sincronização (PIN) - 6 dígitos - Sincronizar - 2 · Aplicar através da Depuração sem fios - Endereço IP e porta de ligação - Sincronizar novamente - Desativar limite - Outras formas de o alterar - 1 · Opções de programador (tente primeiro) - Desative “Desativar restrições de processos secundários”. - Ative “Desativar restrições de processos secundários”. - 3 · ADB num computador (último recurso) - Apenas se a Depuração sem fios não estiver disponível. - 3 · ADB num computador (último recurso) Cor Personalizada Opacidade @@ -1627,8 +1590,6 @@ Foram limpas %1$d pastas de registos de sessão. Foram limpas %1$d pastas de registos de sessão. - Falha na sincronização da depuração sem fios - Falha no comando de depuração sem fios A depuração sem fios não está disponível Comando ADB copiado Escolha a pasta de ROMs @@ -2781,6 +2742,7 @@ A ligação à página de início de sessão não é segura. Não foi possível verificar o início de sessão. Tente novamente. Falha no início de sessão. Tente novamente. + %1$s precisa de mais um passo. Conclua-o no navegador que foi aberto e tente novamente. Fechar Voltar Editar @@ -3169,7 +3131,7 @@ Concluído A aguardar a ligação Ethernet por USB dos óculos. Este telemóvel pode não a disponibilizar às apps. A ligação aos óculos XREAL foi interrompida ou devolveu uma resposta não suportada. A tentar novamente… - 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. + 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+. 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. Cardboard VR Modo Cardboard @@ -4155,4 +4117,6 @@ Inteiro Ajustar Suavização de serrilhado + Mostrar o HUD apenas durante um jogo + Ocultar o HUD quando não forem detetados fotogramas do jogo. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 47b370a046..6372234699 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1282,8 +1282,6 @@ Abrir as Opções do desenvolvedor 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. A Depuração por Wi-Fi requer Wi-Fi. Qualquer rede serve; não precisa de internet. - O código de pareamento é digitado em uma notificação. Permita notificações do DroidDeck ou use Outras formas. - Permitir notificações Abra Configurações → Opções do desenvolvedor → Depuração por Wi-Fi e ative Toque em “Parear o dispositivo com um código de pareamento” Digite o código na notificação do DroidDeck @@ -1300,48 +1298,13 @@ Status Verificando a cada 2 segundos. Esta página fecha quando o limite for desativado. Outras formas - Depuração por Wi-Fi, endereço manual, ADB pelo computador - Endereço manual, ADB pelo computador, Opções do desenvolvedor Usar a Depuração por Wi-Fi Algumas ROMs adicionam a chave mesmo assim. Procure “processos filhos” nas Opções do desenvolvedor. - Se a notificação não funcionar, digite você mesmo o endereço e o código do pop-up. - Digitar endereço manualmente De um computador com ADB: Copiar comando 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”. Escolha em qual tela abrir as Configurações do Android. Tela principal - Pareado. Procurando a porta da Depuração por Wi-Fi… - Pareado. Digite a porta mostrada nas Configurações. - Dispositivo encontrado. Aplicando a configuração… - Não foi possível aplicar automaticamente. Verifique o endereço abaixo e tente de novo. %1$s - Depuração por Wi-Fi - Limite de processos filhos atualizado - Alterar o limite de processos filhos - Se a opção não existir, pareie pela Depuração por Wi-Fi. - Pareado. Verifique o endereço IP e a porta na Depuração por Wi-Fi. - O limite de processos filhos foi atualizado. - 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. - Pareado. Use o endereço abaixo ou atualize-o em Depuração por Wi-Fi → Endereço IP e porta. - O limite de processos filhos foi atualizado pela Depuração por Wi-Fi. - O Android confirmou que o limite está ativado. - O Android confirmou que o limite está desativado. - 2 · Parear pela Depuração por Wi-Fi - Endereço IP e porta do pop-up de pareamento - Código de pareamento (PIN) - 6 dígitos - Parear - 2 · Aplicar pela Depuração por Wi-Fi - Endereço IP e porta de conexão - Parear de novo - Desativar o limite - Outras formas de alterar - 1 · Opções do desenvolvedor (tente primeiro) - Desative “Desativar restrições de processos filhos”. - Ative “Desativar restrições de processos filhos”. - 3 · ADB pelo computador (último recurso) - Só se a Depuração por Wi-Fi não estiver disponível. - 3 · ADB pelo computador (último recurso) Cor Personalizada Opacidade @@ -1635,8 +1598,6 @@ %1$d pastas de logs de sessão limpas. %1$d pastas de logs de sessão limpas. - Falha no pareamento da depuração por Wi-Fi - Falha no comando de depuração por Wi-Fi A depuração por Wi-Fi não está disponível Comando ADB copiado Escolha a pasta de ROMs @@ -2789,6 +2750,7 @@ A conexão com a página de login não é segura. Não foi possível verificar o login. Tente de novo. Falha no login. Tente de novo. + %1$s precisa de mais uma etapa. Conclua no navegador que foi aberto e tente novamente. Fechar Voltar Editar @@ -3177,7 +3139,7 @@ Concluído Aguardando a conexão Ethernet por USB dos óculos. Este celular pode não disponibilizá-la para os apps. A conexão com os óculos XREAL foi interrompida ou retornou uma resposta incompatível. Tentando novamente… - 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. + 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+. 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. Cardboard VR Modo Cardboard @@ -4163,4 +4125,6 @@ Inteiro Ajustar Suavização de serrilhado + Mostrar o HUD somente durante o jogo + Ocultar o HUD quando nenhum quadro do jogo for detectado. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 69a16f1cf2..f25f8abbb2 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1283,8 +1283,6 @@ Deschide Opțiunile pentru dezvoltatori 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. Depanarea wireless are nevoie de Wi-Fi. Orice rețea funcționează; nu are nevoie de internet. - Codul de asociere apare într-o notificare. Permite notificările pentru DroidDeck, sau folosește Alte moduri. - Permite notificările Deschide Setări → Opțiuni pentru dezvoltatori → Depanare wireless și activează-o Apasă „Asociază dispozitivul cu un cod de asociere” Introdu codul în notificarea DroidDeck @@ -1301,48 +1299,13 @@ Stare Se verifică la fiecare 2 secunde. Această pagină se închide când este dezactivată. Alte moduri - Depanare wireless, adresă manuală, ADB pe computer - Adresă manuală, ADB pe computer, Opțiuni pentru dezvoltatori Folosește Depanarea wireless în schimb Unele ROM-uri adaugă comutatorul oricum. Caută „procese-copil” în Opțiuni pentru dezvoltatori. - Dacă notificarea nu funcționează, introdu tu adresa și codul din fereastră. - Introdu adresa manual De pe un computer cu ADB: Copiază comanda 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”. Alege pe care afișaj se deschid Setările Android. Ecranul principal - Asociat. Se caută portul de Depanare wireless… - Asociat. Introdu portul din Setări. - Dispozitiv găsit. Se aplică setarea… - Nu s-a putut aplica automat. Verifică adresa de mai jos și încearcă din nou. %1$s - Depanare wireless - Limita proceselor-copil a fost actualizată - Schimbă limita proceselor-copil - Dacă opțiunea lipsește, asociază-te prin Depanare wireless. - Asociat. Verifică adresa IP și portul în Depanare wireless. - Limita proceselor-copil a fost actualizată. - 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. - Asociat. Folosește adresa de mai jos, sau actualizeaz-o din Depanare wireless → Adresă IP și port. - Limita proceselor-copil a fost actualizată prin Depanarea wireless. - Android a confirmat că limita este activă. - Android a confirmat că limita este dezactivată. - 2 · Asociază Depanarea wireless - Adresa IP și portul ferestrei de asociere - Cod de asociere (PIN) - 6 cifre - Asociază - 2 · Aplică prin Depanarea wireless - Adresa IP și portul de conexiune - Asociază din nou - Dezactivează limita - Alte moduri de a o schimba - 1 · Opțiuni pentru dezvoltatori (încearcă mai întâi) - Dezactivează „Dezactivează restricțiile pentru procese secundare”. - Activează „Dezactivează restricțiile pentru procese secundare”. - 3 · ADB pe computer (ultima soluție) - Doar dacă Depanarea wireless nu este disponibilă. - 3 · ADB pe computer (ultima soluție) Culoare Personalizat Opacitate @@ -1636,8 +1599,6 @@ S-au șters %1$d foldere de jurnal de sesiune. S-au șters %1$d de foldere de jurnal de sesiune. - Asocierea Depanării wireless a eșuat - Comanda Depanării wireless a eșuat Depanarea wireless nu este disponibilă Comanda ADB copiată Alege folderul ROMs @@ -2779,6 +2740,7 @@ Conexiunea la pagina de autentificare nu este sigură. Autentificarea nu a putut fi verificată. Încearcă din nou. Autentificarea a eșuat. Încearcă din nou. + %1$s mai cere un pas. Finalizează-l în browserul care s-a deschis, apoi încearcă din nou. Închide Înapoi Editează @@ -3167,7 +3129,7 @@ Gata Se așteaptă conexiunea USB Ethernet a ochelarilor. Este posibil ca acest telefon să nu o expună aplicațiilor. Conexiunea XREAL a fost întreruptă sau a returnat un răspuns neacceptat. Se reîncearcă… - 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. + 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+. 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. Cardboard VR Mod Cardboard @@ -4156,4 +4118,6 @@ Evidențieri Succes Eroare + Afișează HUD-ul doar în timpul jocului + Ascunde HUD-ul când nu sunt detectate cadre ale jocului. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e45c8af9a0..956c3d5136 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1290,8 +1290,6 @@ Открыть «Для разработчиков» В этой версии Android нет такого переключателя, поэтому DroidDeck внесет изменения через отладку по Wi-Fi. Это займет около минуты, компьютер не нужен. Для отладки по Wi-Fi требуется Wi-Fi. Подойдет любая сеть, интернет не нужен. - Код сопряжения придет в уведомлении. Разрешите DroidDeck отправлять уведомления или используйте «Другие способы». - Разрешить уведомления Откройте Настройки → Для разработчиков → Отладка по Wi-Fi и включите ее Нажмите «Подключить устройство с помощью кода подключения» Введите код сопряжения в уведомлении DroidDeck @@ -1308,48 +1306,13 @@ Статус Проверка каждые 2 секунды. После отключения этого переключателя страница закроется автоматически. Другие способы - Отладка по Wi-Fi, ручной ввод адреса, ADB на ПК - Ручной ввод адреса, ADB на ПК, «Для разработчиков» Использовать отладку по Wi-Fi В некоторых прошивках переключатель все же есть. Поищите «дочерние процессы» в разделе «Для разработчиков». - Если способ с уведомлением не работает, введите адрес и код сопряжения из окна вручную. - Ввести адрес вручную С компьютера через ADB: Копировать команду Подключите шлем к компьютеру и откройте SideQuest. Выберите «Run ADB Command», затем «Custom Command», введите команду, показанную ниже, и нажмите «Run Command». Выберите экран для открытия настроек Android. Главный экран - Сопряжено. Поиск порта отладки по Wi-Fi… - Сопряжено. Введите порт из настроек. - Устройство найдено. Применение настроек… - Не удалось применить автоматически. Проверьте адрес ниже и повторите попытку. %1$s - Отладка по Wi-Fi - Ограничение дочерних процессов обновлено - Изменить ограничение дочерних процессов - Если опции нет, выполните сопряжение через отладку по Wi-Fi. - Сопряжено. Проверьте IP-адрес и порт в отладке по Wi-Fi. - Ограничение дочерних процессов обновлено. - Если в параметрах разработчика нет настройки дочерних процессов, используйте шаг 2. Откройте Для разработчиков → Отладка по Wi-Fi → Сопряжение устройства с помощью кода. - Сопряжено. Используйте адрес ниже или обновите его в разделе Отладка по Wi-Fi → IP-адрес и порт. - Ограничение дочерних процессов обновлено через отладку по Wi-Fi. - Android подтвердил, что ограничение включено. - Android подтвердил, что ограничение отключено. - 2 · Сопряжение отладки по Wi-Fi - IP-адрес и порт из окна сопряжения - Код сопряжения (PIN) - 6 цифр - Сопряжение - 2 · Применение через отладку по Wi-Fi - IP-адрес и порт подключения - Сопряжение заново - Отключить ограничение - Другие способы изменения - 1 · Для разработчиков (сначала попробуйте это) - Отключите «Отключить ограничения для дочерних процессов». - Включите «Отключить ограничения для дочерних процессов». - 3 · ADB на ПК (крайняя мера) - Используйте только если отладка по Wi-Fi недоступна. - 3 · ADB на ПК (крайняя мера) Цвет Пользовательский Непрозрачность @@ -1649,8 +1612,6 @@ Очищено %1$d папок журналов сессии. Очищено %1$d папки журналов сессии. - Ошибка сопряжения для отладки по Wi-Fi - Ошибка команды отладки по Wi-Fi Отладка по Wi-Fi недоступна Команда ADB скопирована Выберите папку ROM @@ -1687,6 +1648,7 @@ Выберите папку хранилища игр Выберите ZIP-файл плагина Decky Нельзя использовать: %1$s + FAT32 не поддерживает файлы больше 4 ГБ, поэтому часть игр не установится. Отформатируйте в exFAT. Программа Удаление среды выполнения Linux Не удалось открыть настройки на нижнем экране; они открыты на главном экране. @@ -2802,6 +2764,7 @@ Подключение к странице входа не защищено. Не удалось подтвердить вход. Повторите попытку. Ошибка входа. Повторите попытку. + %1$s требует ещё один шаг. Завершите его в открывшемся браузере и попробуйте снова. Закрыть Назад Изменить @@ -3194,7 +3157,7 @@ Готово Ожидание подключения очков по USB Ethernet. Этот телефон может не предоставлять его приложениям. Подключение к XREAL прервано или получен неподдерживаемый ответ. Повторная попытка… - Экспериментальная поддержка 1S. Включите режим Follow и отключите стабилизацию в меню очков. Направления отслеживания и режимы отображения ещё нужно проверить на устройстве. + Экспериментальная поддержка XREAL 1S, One, One Pro, One Pro+ и Aura. Используйте режим Follow и отключите стабилизацию в меню очков; на Aura также отключите Spatial Anchor. Отслеживание головы и переключение между 2D/3D проверены на Aura и One Pro+. Экспериментальное отслеживание движений головы для Pro 2. Настройка яркости и громкости и переключение режимов отображения пока не поддерживаются. Разработчик Издатель @@ -4196,4 +4159,6 @@ Выделения Успех Ошибка + Показывать HUD только во время игры + Скрывать HUD, когда кадры игры не обнаруживаются. diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index afa62b8e4a..9361bca121 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1276,8 +1276,6 @@ Öppna Utvecklaralternativ 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. Trådlös felsökning kräver Wi-Fi. Alla nätverk fungerar; det behöver inte internet. - Ihopkopplingskoden skickas i en avisering. Tillåt aviseringar för DroidDeck, eller använd Andra sätt. - Tillåt aviseringar Öppna Inställningar → Utvecklaralternativ → Trådlös felsökning och slå på det Tryck på ”Para ihop enhet med ihopkopplingskod” Skriv in koden i DroidDeck-aviseringen @@ -1294,48 +1292,13 @@ Status Kontrollerar var 2 sekunder. Den här sidan stängs när det är av. Andra sätt - Trådlös felsökning, manuell adress, dator-ADB - Manuell adress, dator-ADB, Utvecklaralternativ Använd Trådlös felsökning i stället Vissa ROM:ar lägger till omkopplaren trots allt. Leta efter ”underprocess” i Utvecklaralternativ. - Om aviseringen inte fungerar, ange popup-fönstrets adress och kod själv. - Ange adress manuellt Från en dator med ADB: Kopiera kommando 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”. Välj vilken skärm Android-inställningar ska öppnas på. Huvudskärm - Ihopkopplad. Letar efter porten för Trådlös felsökning… - Ihopkopplad. Ange porten från Inställningar. - Enhet hittad. Tillämpar inställningen… - Kunde inte tillämpas automatiskt. Kontrollera adressen nedan och försök igen. %1$s - Trådlös felsökning - Gränsen för underprocesser har uppdaterats - Ändra gränsen för underprocesser - Om alternativet saknas, para ihop via Trådlös felsökning. - Ihopkopplad. Kontrollera IP-adressen och porten i Trådlös felsökning. - Gränsen för underprocesser har uppdaterats. - 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. - Ihopkopplad. Använd adressen nedan, eller uppdatera den från Trådlös felsökning → IP-adress & port. - Gränsen för underprocesser uppdaterades via Trådlös felsökning. - Android bekräftade att gränsen är på. - Android bekräftade att gränsen är av. - 2 · Para ihop Trådlös felsökning - Ihopkopplingsrutans IP-adress & port - Ihopkopplingskod (PIN) - 6 siffror - Para ihop - 2 · Tillämpa via Trådlös felsökning - Anslutningens IP-adress & port - Para ihop igen - Stäng av gränsen - Andra sätt att ändra det - 1 · Utvecklaralternativ (prova först) - Slå av ”Inaktivera begränsningar på underordnade processer”. - Slå på ”Inaktivera begränsningar på underordnade processer”. - 3 · Dator-ADB (sista utväg) - Bara om Trådlös felsökning inte är tillgänglig. - 3 · Dator-ADB (sista utväg) Färg Anpassad Opacitet @@ -1623,8 +1586,6 @@ Rensade %1$d sessionsloggmapp. Rensade %1$d sessionsloggmappar. - Parkopplingen för trådlös felsökning misslyckades - Kommandot för trådlös felsökning misslyckades Trådlös felsökning är inte tillgänglig ADB-kommandot har kopierats Välj ROM-mappen @@ -2753,6 +2714,7 @@ Anslutningen till inloggningssidan är inte säker. Inloggningen kunde inte verifieras. Försök igen. Inloggningen misslyckades. Försök igen. + %1$s behöver ett steg till. Slutför det i webbläsaren som öppnades och försök sedan igen. Stäng Tillbaka Redigera @@ -3137,7 +3099,7 @@ Klar Väntar på glasögonens USB Ethernet-anslutning. Telefonen kanske inte gör den tillgänglig för appar. XREAL-anslutningen avbröts eller gav ett svar som inte stöds. Försöker igen… - 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. + 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+. Experimentell huvudspårning för Pro 2. Justering av ljusstyrka och volym samt byte av visningsläge stöds inte ännu. Cardboard VR Cardboard-läge @@ -4116,4 +4078,6 @@ Markeringar Lyckades Fel + Visa HUD endast under spel + Dölj HUD när inga spelbildrutor upptäcks. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 14a813ab5b..a7f07bbe93 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1270,8 +1270,6 @@ เปิดตัวเลือกสำหรับนักพัฒนา Android รุ่นนี้ไม่มีสวิตช์สำหรับสิ่งนี้ ดังนั้น DroidDeck จะเปลี่ยนค่าผ่าน Wireless debugging ใช้เวลาประมาณหนึ่งนาที ไม่ต้องใช้คอมพิวเตอร์ Wireless debugging ต้องใช้ Wi-Fi เครือข่ายใดก็ได้ ไม่จำเป็นต้องมีอินเทอร์เน็ต - รหัสจับคู่จะแสดงในการแจ้งเตือน อนุญาตการแจ้งเตือนสำหรับ DroidDeck หรือใช้วิธีอื่น - อนุญาตการแจ้งเตือน เปิดการตั้งค่า → ตัวเลือกสำหรับนักพัฒนา → Wireless debugging แล้วเปิดใช้งาน แตะ “Pair device with pairing code” พิมพ์รหัสลงในการแจ้งเตือนของ DroidDeck @@ -1288,48 +1286,13 @@ สถานะ กำลังตรวจสอบทุก 2 วินาที หน้านี้จะปิดเมื่อปิดใช้งานแล้ว วิธีอื่น - Wireless debugging, ที่อยู่แบบกำหนดเอง, ADB จากคอมพิวเตอร์ - ที่อยู่แบบกำหนดเอง, ADB จากคอมพิวเตอร์, ตัวเลือกสำหรับนักพัฒนา ใช้ Wireless debugging แทน บาง ROM เพิ่มสวิตช์นี้มาเองเลย ลองหา “child process” ในตัวเลือกสำหรับนักพัฒนา - หากการแจ้งเตือนไม่ทำงาน ให้กรอกที่อยู่และรหัสจากป๊อปอัปด้วยตัวเอง - กรอกที่อยู่ด้วยตัวเอง จากคอมพิวเตอร์ที่มี ADB: คัดลอกคำสั่ง เชื่อมต่อแว่นกับคอมพิวเตอร์แล้วเปิด SideQuest เลือก “Run ADB Command” จากนั้น “Custom Command” พิมพ์คำสั่งที่แสดงด้านล่างแล้วเลือก “Run Command” เลือกหน้าจอที่จะเปิดการตั้งค่า Android หน้าจอหลัก - จับคู่แล้ว กำลังค้นหาพอร์ตของ Wireless debugging… - จับคู่แล้ว กรอกพอร์ตจากการตั้งค่า - พบอุปกรณ์แล้ว กำลังปรับใช้การตั้งค่า… - ไม่สามารถปรับใช้โดยอัตโนมัติได้ ตรวจสอบที่อยู่ด้านล่างแล้วลองใหม่ %1$s - การแก้ไขข้อบกพร่องแบบไร้สาย - อัปเดตขีดจำกัดโพรเซสลูกแล้ว - เปลี่ยนขีดจำกัดโพรเซสลูก - หากไม่พบตัวเลือกนี้ ให้จับคู่ผ่าน Wireless debugging - จับคู่แล้ว ตรวจสอบที่อยู่ IP และพอร์ตใน Wireless debugging - อัปเดตขีดจำกัดโพรเซสลูกแล้ว - ใช้ขั้นตอนที่ 2 หากตัวเลือกสำหรับนักพัฒนาไม่มีการตั้งค่าโพรเซสลูก เปิดตัวเลือกสำหรับนักพัฒนา → Wireless debugging → Pair device with pairing code - จับคู่แล้ว ใช้ที่อยู่ด้านล่าง หรืออัปเดตจาก Wireless debugging → IP address & Port - อัปเดตขีดจำกัดโพรเซสลูกผ่าน Wireless debugging แล้ว - Android ยืนยันแล้วว่าขีดจำกัดเปิดอยู่ - Android ยืนยันแล้วว่าขีดจำกัดปิดอยู่ - 2 · จับคู่ Wireless debugging - ที่อยู่ IP และพอร์ตของป๊อปอัปการจับคู่ - รหัสจับคู่ (PIN) - 6 หลัก - จับคู่ - 2 · ปรับใช้ผ่าน Wireless debugging - ที่อยู่ IP และพอร์ตสำหรับเชื่อมต่อ - จับคู่อีกครั้ง - ปิดขีดจำกัด - วิธีอื่นในการเปลี่ยนค่านี้ - 1 · ตัวเลือกสำหรับนักพัฒนา (ลองก่อน) - ปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย” - เปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย” - 3 · ADB จากคอมพิวเตอร์ (ทางเลือกสุดท้าย) - ใช้เฉพาะเมื่อ Wireless debugging ใช้งานไม่ได้ - 3 · ADB จากคอมพิวเตอร์ (ทางเลือกสุดท้าย) สี กำหนดเอง ความโปร่งใส @@ -1611,8 +1574,6 @@ ล้างโฟลเดอร์ล็อกเซสชัน %1$d โฟลเดอร์แล้ว - การจับคู่ Wireless debugging ล้มเหลว - คำสั่ง Wireless debugging ล้มเหลว Wireless debugging ไม่พร้อมใช้งาน คัดลอกคำสั่ง ADB แล้ว เลือกโฟลเดอร์ ROM @@ -2728,6 +2689,7 @@ การเชื่อมต่อไปยังหน้าลงชื่อเข้าใช้ไม่ปลอดภัย ไม่สามารถยืนยันการลงชื่อเข้าใช้ได้ ลองใหม่ ลงชื่อเข้าใช้ล้มเหลว ลองใหม่ + %1$s ต้องการอีกหนึ่งขั้นตอน ทำให้เสร็จในเบราว์เซอร์ที่เปิดขึ้น แล้วลองอีกครั้ง ปิด กลับ แก้ไข @@ -3108,7 +3070,7 @@ เสร็จสิ้น กำลังรอการเชื่อมต่อ USB Ethernet ของแว่นตา โทรศัพท์นี้อาจไม่เปิดให้แอปเข้าถึงการเชื่อมต่อนี้ การเชื่อมต่อ XREAL ขาดหายหรือได้รับการตอบกลับที่ไม่รองรับ กำลังลองใหม่… - รองรับ 1S แบบทดลอง ใช้โหมด Follow และปิดการกันสั่นในเมนูของแว่นตา ทิศทางการติดตามและโหมดการแสดงผลยังต้องทดสอบกับอุปกรณ์จริง + รองรับ XREAL 1S, One, One Pro, One Pro+ และ Aura แบบทดลอง ใช้โหมด Follow และปิดการกันสั่นในเมนูของแว่นตา สำหรับ Aura ให้ปิด Spatial Anchor ด้วย การติดตามศีรษะและการสลับ 2D/3D ผ่านการทดสอบบน Aura และ One Pro+ แล้ว การติดตามศีรษะแบบทดลองสำหรับ Pro 2 ยังไม่รองรับการปรับความสว่าง ระดับเสียง และการสลับโหมดการแสดงผล Cardboard VR โหมด Cardboard @@ -4086,4 +4048,6 @@ จุดเน้น สำเร็จ ข้อผิดพลาด + แสดง HUD เฉพาะขณะเล่นเกม + ซ่อน HUD เมื่อไม่พบเฟรมของเกม diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 9e67af3366..581d4aecbb 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1268,8 +1268,6 @@ Geliştirici seçeneklerini aç 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. Kablosuz hata ayıklama Wi-Fi gerektirir. Herhangi bir ağ işe yarar; internet gerekmez. - Eşleştirme kodu bir bildirime gelir. DroidDeck için bildirimlere izin verin veya Diğer yollar\'ı kullanın. - Bildirimlere izin ver Ayarlar → Geliştirici seçenekleri → Kablosuz hata ayıklama\'yı açın “Eşleştirme koduyla cihaz eşle” seçeneğine dokunun Kodu DroidDeck bildirimine yazın @@ -1286,48 +1284,13 @@ Durum Her 2 saniyede bir kontrol ediliyor. Kapandığında bu sayfa kapanır. Diğer yollar - Kablosuz hata ayıklama, elle adres girme, bilgisayardan ADB - Elle adres girme, bilgisayardan ADB, Geliştirici seçenekleri Bunun yerine Kablosuz hata ayıklamayı kullan Bazı ROM\'lar bu anahtarı yine de ekler. Geliştirici seçenekleri\'nde “alt süreç” ifadesini arayın. - Bildirim işe yaramazsa açılır penceredeki adresi ve kodu kendiniz girin. - Adresi elle girin ADB\'li bir bilgisayardan: Komutu kopyala 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. Android Ayarları\'nın hangi ekranda açılacağını seçin. Ana ekran - Eşleşti. Kablosuz hata ayıklama bağlantı noktası bulunuyor… - Eşleşti. Bağlantı noktasını Ayarlar\'dan girin. - Cihaz bulundu. Ayar uygulanıyor… - Otomatik olarak uygulanamadı. Aşağıdaki adresi kontrol edip yeniden deneyin. %1$s - Kablosuz hata ayıklama - Alt süreç sınırı güncellendi - Alt süreç sınırını değiştir - Seçenek yoksa Kablosuz hata ayıklama üzerinden eşleyin. - Eşleşti. IP adresini ve bağlantı noktasını Kablosuz hata ayıklama\'da kontrol edin. - Alt süreç sınırı güncellendi. - 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. - Eşleşti. Aşağıdaki adresi kullanın veya Kablosuz hata ayıklama → IP adresi ve bağlantı noktası\'ndan güncelleyin. - Alt süreç sınırı Kablosuz hata ayıklama üzerinden güncellendi. - Android sınırın açık olduğunu onayladı. - Android sınırın kapalı olduğunu onayladı. - 2 · Kablosuz hata ayıklamayı eşle - Eşleştirme açılır penceresinin IP adresi ve bağlantı noktası - Eşleştirme kodu (PIN) - 6 hane - Eşle - 2 · Kablosuz hata ayıklama üzerinden uygula - Bağlantı IP adresi ve bağlantı noktası - Yeniden eşle - Sınırı kapat - Değiştirmenin diğer yolları - 1 · Geliştirici seçenekleri (önce bunu deneyin) - “Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini kapalı olarak ayarlayın. - “Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini açık olarak ayarlayın. - 3 · Bilgisayardan ADB (son yöntem) - Yalnızca Kablosuz hata ayıklama kullanılamıyorsa. - 3 · Bilgisayardan ADB (son yöntem) Renk Özel Opaklık @@ -1615,8 +1578,6 @@ %1$d oturum günlüğü klasörü temizlendi. %1$d oturum günlüğü klasörü temizlendi. - Kablosuz hata ayıklama eşlemesi başarısız oldu - Kablosuz hata ayıklama komutu başarısız oldu Kablosuz hata ayıklama kullanılamıyor ADB komutu kopyalandı ROM klasörünü seçin @@ -2742,6 +2703,7 @@ Oturum açma sayfasına bağlantı güvenli değil. Oturum açma doğrulanamadı. Yeniden deneyin. Oturum açma başarısız oldu. Yeniden deneyin. + %1$s bir adım daha istiyor. Açılan tarayıcıda tamamlayın, ardından yeniden deneyin. Kapat Geri Düzenle @@ -3126,7 +3088,7 @@ Bitti Gözlüğün USB Ethernet bağlantısı bekleniyor. Bu telefon bu bağlantıyı uygulamalara açmıyor olabilir. XREAL bağlantısı kesildi veya desteklenmeyen bir yanıt döndü. Yeniden deneniyor… - 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. + 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. Pro 2 için deneysel baş takibi. Parlaklık ve ses düzeyi ayarı ile ekran modu değiştirme henüz desteklenmiyor. Cardboard VR Cardboard modu @@ -4116,4 +4078,6 @@ Vurgular Başarılı Hata + HUD\'yi yalnızca oyun sırasında göster + Oyun kareleri algılanmadığında HUD\'yi gizle. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 8609b09b5d..8db1b46441 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1290,8 +1290,6 @@ Відкрити «Параметри розробника» У цій версії Android немає перемикача для цього, тож DroidDeck змінює налаштування через бездротове налагодження. Займає приблизно хвилину, комп’ютер не потрібен. Бездротове налагодження потребує Wi-Fi. Підійде будь-яка мережа; інтернет не потрібен. - Код поєднання приходить у сповіщенні. Дозвольте сповіщення для DroidDeck або скористайтеся розділом «Інші способи». - Дозволити сповіщення Відкрийте «Налаштування» → «Параметри розробника» → «Бездротове налагодження» і увімкніть його Натисніть «Поєднати пристрій за кодом» Введіть код у сповіщення DroidDeck @@ -1308,48 +1306,13 @@ Статус Перевірка кожні 2 секунди. Ця сторінка закриється, коли це вимкнено. Інші способи - Бездротове налагодження, адреса вручну, ADB з комп’ютера - Адреса вручну, ADB з комп’ютера, параметри розробника Використати бездротове налагодження замість цього Деякі прошивки все одно додають цей перемикач. Пошукайте «дочірній процес» у параметрах розробника. - Якщо сповіщення не працює, введіть адресу та код із вікна вручну. - Ввести адресу вручну З комп’ютера з ADB: Копіювати команду Підключіть шолом до комп’ютера й відкрийте SideQuest. Виберіть «Run ADB Command», потім «Custom Command», введіть команду, показану нижче, і виберіть «Run Command». Виберіть, на якому екрані відкрити налаштування Android. Головний екран - Поєднано. Пошук порту бездротового налагодження… - Поєднано. Введіть порт із налаштувань. - Пристрій знайдено. Застосування налаштування… - Не вдалося застосувати автоматично. Перевірте адресу нижче і повторіть спробу. %1$s - Бездротове налагодження - Обмеження дочірніх процесів оновлено - Змінити обмеження дочірніх процесів - Якщо цього параметра немає, поєднайтеся через бездротове налагодження. - Поєднано. Перевірте IP-адресу і порт у бездротовому налагодженні. - Обмеження дочірніх процесів оновлено. - Використайте крок 2, якщо в параметрах розробника немає налаштування дочірніх процесів. Відкрийте «Параметри розробника» → «Бездротове налагодження» → «Поєднати пристрій за кодом». - Поєднано. Використайте адресу нижче або оновіть її в розділі «Бездротове налагодження» → «IP-адреса та порт». - Обмеження дочірніх процесів оновлено через бездротове налагодження. - Android підтвердив, що обмеження увімкнено. - Android підтвердив, що обмеження вимкнено. - 2 · Поєднати бездротове налагодження - IP-адреса і порт із вікна поєднання - Код поєднання (PIN) - 6 цифр - Поєднати - 2 · Застосувати через бездротове налагодження - IP-адреса і порт з’єднання - Поєднати ще раз - Вимкнути обмеження - Інші способи змінити це - 1 · Параметри розробника (спробуйте спершу) - Вимкніть «Вимкнути обмеження для дочірніх процесів». - Увімкніть «Вимкнути обмеження для дочірніх процесів». - 3 · ADB з комп’ютера (останній варіант) - Лише якщо бездротове налагодження недоступне. - 3 · ADB з комп’ютера (останній варіант) Колір Власний Непрозорість @@ -1649,8 +1612,6 @@ Очищено %1$d папок журналів сеансів. Очищено %1$d папки журналів сеансів. - Не вдалося створити пару через бездротове налагодження - Помилка команди бездротового налагодження Бездротове налагодження недоступне Команду ADB скопійовано Виберіть папку ROMs @@ -2805,6 +2766,7 @@ З’єднання зі сторінкою входу не захищене. Не вдалося підтвердити вхід. Спробуйте ще раз. Вхід не вдався. Спробуйте ще раз. + %1$s потребує ще одного кроку. Завершіть його у відкритому браузері та спробуйте ще раз. Закрити Назад Редагувати @@ -3197,7 +3159,7 @@ Готово Очікування з’єднання USB Ethernet від окулярів. Цей телефон може не надавати його додаткам. З’єднання з XREAL перервалося або повернуло непідтримувану відповідь. Повторна спроба… - Експериментальна підтримка 1S. Увімкніть режим Follow і вимкніть стабілізацію в меню окулярів. Напрямки відстеження й режими відображення ще потрібно перевірити на пристрої. + Експериментальна підтримка XREAL 1S, One, One Pro, One Pro+ та Aura. Використовуйте режим Follow і вимкніть стабілізацію в меню окулярів; на Aura також вимкніть Spatial Anchor. Відстеження голови та перемикання між 2D/3D перевірено на Aura й One Pro+. Експериментальне відстеження рухів голови для Pro 2. Налаштування яскравості й гучності та перемикання режимів відображення ще не підтримуються. Cardboard VR Режим Cardboard @@ -4196,4 +4158,6 @@ Виділення Успіх Помилка + Показувати HUD лише під час гри + Приховувати HUD, коли кадри гри не виявляються. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index fd23d10b90..707c107c89 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1270,8 +1270,6 @@ Mở Tùy chọn cho nhà phát triển 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. 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. - 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. - Cho phép thông báo Mở Settings → Developer options → Wireless debugging và bật nó lên Nhấn “Pair device with pairing code” Nhập mã vào thông báo của DroidDeck @@ -1288,48 +1286,13 @@ Trạng thái Đang kiểm tra mỗi 2 giây. Trang này sẽ đóng khi nó tắt. Cách khác - Gỡ lỗi qua mạng không dây, địa chỉ thủ công, ADB từ máy tính - Địa chỉ thủ công, ADB từ máy tính, Tùy chọn cho nhà phát triển Dùng Gỡ lỗi qua mạng không dây thay vào đó 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. - 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. - Nhập địa chỉ thủ công Từ một máy tính có ADB: Sao chép lệnh 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”. Chọn màn hình để mở Android Settings. Màn hình chính - Đã ghép nối. Đang tìm cổng Gỡ lỗi qua mạng không dây… - Đã ghép nối. Nhập cổng từ Settings. - Đã tìm thấy thiết bị. Đang áp dụng thiết lập… - Không thể áp dụng tự động. Kiểm tra địa chỉ dưới đây và thử lại. %1$s - Gỡ lỗi qua mạng không dây - Đã cập nhật giới hạn tiến trình con - Đổi giới hạn tiến trình con - 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. - Đã ghép nối. Kiểm tra địa chỉ IP và cổng trong Gỡ lỗi qua mạng không dây. - Giới hạn tiến trình con đã được cập nhật. - 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. - Đã ghép nối. Dùng địa chỉ dưới đây, hoặc cập nhật nó từ Wireless debugging → IP address & Port. - 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. - Android xác nhận giới hạn đang bật. - Android xác nhận giới hạn đang tắt. - 2 · Ghép nối Gỡ lỗi qua mạng không dây - Địa chỉ IP & cổng của cửa sổ bật lên ghép nối - Mã ghép nối (PIN) - 6 số - Ghép nối - 2 · Áp dụng qua Gỡ lỗi qua mạng không dây - Địa chỉ IP & cổng kết nối - Ghép nối lại - Tắt giới hạn - Cách khác để đổi nó - 1 · Tùy chọn cho nhà phát triển (thử trước) - Đặt “Tắt các mục hạn chế đối với tiến trình con” thành tắt. - Đặt “Tắt các mục hạn chế đối với tiến trình con” thành bật. - 3 · ADB từ máy tính (phương án cuối) - Chỉ khi Gỡ lỗi qua mạng không dây không khả dụng. - 3 · ADB từ máy tính (phương án cuối) Màu Tùy chỉnh Độ mờ @@ -1611,8 +1574,6 @@ Đã xóa %1$d thư mục log phiên. - Ghép nối Gỡ lỗi qua mạng không dây thất bại - Lệnh Gỡ lỗi qua mạng không dây thất bại Gỡ lỗi qua mạng không dây không khả dụng Đã sao chép lệnh ADB Chọn thư mục ROM @@ -2728,6 +2689,7 @@ Kết nối đến trang đăng nhập không an toàn. Không thể xác minh đăng nhập. Hãy thử lại. Đăng nhập thất bại. Hãy thử lại. + %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. Đóng Quay lại Sửa @@ -3108,7 +3070,7 @@ Xong Đ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 đó. 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… - 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ị. + 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+. 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ị. Cardboard VR Chế độ Cardboard @@ -4086,4 +4048,6 @@ Điểm nhấn Thành công Lỗi + Chỉ hiển thị HUD khi đang chơi + Ẩn HUD khi không phát hiện khung hình trò chơi. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index aa46013f4a..e95780a79c 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1353,8 +1353,6 @@ 打开开发者选项 此 Android 版本没有该开关,因此 DroidDeck 通过无线调试来修改。大约需要一分钟,无需电脑。 无线调试需要 Wi-Fi。任何网络都可以,不需要互联网。 - 配对码会出现在通知中。请允许 DroidDeck 的通知,或使用“其他方式”。 - 允许通知 打开“设置”→“开发者选项”→“无线调试”,并将其开启 点按“使用配对码配对设备” 在 DroidDeck 通知中输入配对码 @@ -1371,48 +1369,13 @@ 状态 每 2 秒检查一次。该设置关闭后,本页面会自动关闭。 其他方式 - 无线调试、手动地址、电脑 ADB - 手动地址、电脑 ADB、开发者选项 改用无线调试 部分 Android ROM 仍会加入该开关。请在开发者选项中查找“子进程”。 - 若通知不起作用,请手动输入弹窗中的地址和配对码。 - 手动输入地址 通过装有 ADB 的电脑: 复制命令 将头显连接到电脑并打开 SideQuest。依次选择“Run ADB Command”和“Custom Command”,输入下方显示的命令,然后选择“Run Command”。 选择在哪个屏幕上打开 Android 设置。 主屏幕 - 已配对。正在查找无线调试端口… - 已配对。请输入设置中的端口。 - 已找到设备。正在应用设置… - 无法自动应用。请检查下方地址并重试。%1$s - 无线调试 - 子进程限制已更新 - 更改子进程限制 - 若缺少该选项,请通过无线调试配对。 - 已配对。请在无线调试中查看 IP 地址和端口。 - 子进程限制已更新。 - 若开发者选项中没有子进程设置,请使用第 2 步。打开开发者选项 → 无线调试 → 使用配对码配对设备。 - 已配对。请使用下方地址,或从无线调试 → IP 地址与端口更新它。 - 子进程限制已通过无线调试更新。 - Android 已确认限制处于开启状态。 - Android 已确认限制处于关闭状态。 - 2 · 配对无线调试 - 配对弹窗 IP 地址与端口 - 配对码(PIN) - 6 位数字 - 配对 - 2 · 通过无线调试应用更改 - 连接 IP 地址与端口 - 重新配对 - 关闭限制 - 其他修改方式 - 1 · 开发者选项(优先尝试) - 把“停止限制子进程”设为关。 - 把“停止限制子进程”设为开。 - 3 · 电脑 ADB(最后手段) - 仅在无线调试不可用时使用。 - 3 · 电脑 ADB(最后手段) 颜色 自定义 不透明度 @@ -1694,8 +1657,6 @@ 已清除 %1$d 个会话日志文件夹。 - 无线调试配对失败 - 无线调试命令执行失败 无线调试不可用 已复制 ADB 命令 选择 ROM 文件夹 @@ -2802,6 +2763,7 @@ 与登录页面的连接不安全。 无法验证登录。请重试。 登录失败。请重试。 + %1$s 还需要一个步骤。请在已打开的浏览器中完成,然后重试。 关闭 返回 编辑 @@ -3108,7 +3070,7 @@ 完成 正在等待眼镜的 USB Ethernet 连接。这部手机可能不向应用开放此连接。 XREAL 连接中断或返回了不受支持的响应。正在重试… - 实验性 1S 支持。请在眼镜菜单中使用跟随模式并关闭防抖。追踪方向和显示模式仍需在设备上测试。 + 实验性支持 XREAL 1S、One、One Pro、One Pro+ 和 Aura。请在眼镜菜单中使用 Follow 模式并关闭防抖;在 Aura 上还需关闭 Spatial Anchor。头部追踪和 2D/3D 切换已在 Aura 和 One Pro+ 上测试。 Pro 2 实验性头部追踪。暂不支持亮度、音量调节和显示模式切换。 开发商 发行商 @@ -4086,4 +4048,6 @@ 高亮 成功 错误 + 仅在游戏期间显示 HUD + 未检测到游戏帧时隐藏 HUD。 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 1bec44cc0a..28dcdcb49f 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1269,8 +1269,6 @@ 開啟開發人員選項 此 Android 版本沒有此開關,因此 DroidDeck 會透過無線偵錯更改。約需一分鐘,無需電腦。 無線偵錯需要 Wi-Fi。任何網絡都可以,無需連接互聯網。 - 配對碼需在通知中輸入。請允許 DroidDeck 發出通知,或使用「其他方式」。 - 允許通知 開啟「系統設定」→「開發人員選項」→「無線偵錯」,並將其開啟 輕按「使用配對碼配對裝置」 在 DroidDeck 通知中輸入配對碼 @@ -1287,48 +1285,13 @@ 狀態 每 2 秒檢查一次。關閉此開關後,本頁面會自動關閉。 其他方式 - 無線偵錯、手動輸入位址、電腦 ADB - 手動輸入位址、電腦 ADB、開發人員選項 改用無線偵錯 部分 ROM 仍會提供此開關。請在開發人員選項中尋找「子進程」。 - 如果通知無效,請自行輸入彈出式視窗中的位址和配對碼。 - 手動輸入位址 在已安裝 ADB 的電腦上: 複製指令 將頭戴裝置連接到電腦並開啟 SideQuest。依次選擇「Run ADB Command」和「Custom Command」,輸入下方顯示的指令,然後選擇「Run Command」。 選擇要在哪個螢幕開啟 Android 設定。 主螢幕 - 已配對,正在尋找無線偵錯連接埠… - 已配對,請輸入「系統設定」中顯示的連接埠。 - 已找到裝置,正在套用設定… - 無法自動套用。請檢查下方的位址,然後重試。%1$s - 無線偵錯 - 子進程限制已更新 - 更改子進程限制 - 如果沒有此選項,請透過無線偵錯配對。 - 已配對。請檢查無線偵錯中的 IP 位址和連接埠。 - 子進程限制已更新。 - 如果開發人員選項中沒有子進程設定,請使用步驟 2。開啟「開發人員選項」→「無線偵錯」→「使用配對碼配對裝置」。 - 已配對。請使用下方的位址,或在「無線偵錯」→「IP 位址和連接埠」中更新。 - 已透過無線偵錯更新子進程限制。 - Android 確認限制已開啟。 - Android 確認限制已關閉。 - 2 · 配對無線偵錯 - 配對彈出式視窗中的 IP 位址和連接埠 - 配對碼(PIN) - 6 位數字 - 配對 - 2 · 透過無線偵錯套用 - 連線 IP 位址和連接埠 - 重新配對 - 關閉限制 - 其他更改方式 - 1 · 開發人員選項(請先嘗試) - 關閉「停用對子處理過程的限制」。 - 開啟「停用對子處理過程的限制」。 - 3 · 電腦 ADB(最後手段) - 只在無法使用無線偵錯時使用。 - 3 · 電腦 ADB(最後手段) 顏色 自訂 不透明度 @@ -1610,8 +1573,6 @@ 已清除 %1$d 個會話記錄資料夾。 - 無線偵錯配對失敗 - 無線偵錯指令失敗 無法使用無線偵錯 已複製 ADB 指令 選擇 ROM 資料夾 @@ -2725,6 +2686,7 @@ 與登入頁面的連線不安全。 無法驗證登入,請再試一次。 登入失敗,請再試一次。 + %1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。 關閉 返回 編輯 @@ -3105,7 +3067,7 @@ 完成 正在等候眼鏡的 USB Ethernet 連線。這部手機可能不會向應用程式開放此連線。 XREAL 連線中斷或傳回不支援的回應。正在重試… - 實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在裝置上測試。 + 實驗性支援 XREAL 1S、One、One Pro、One Pro+ 和 Aura。請在眼鏡選單中使用 Follow 模式並關閉畫面穩定;在 Aura 上亦需關閉 Spatial Anchor。頭部追蹤和 2D/3D 切換已在 Aura 和 One Pro+ 上測試。 Pro 2 實驗性頭部追蹤。暫不支援亮度、音量調整及顯示模式切換。 開發商 發行商 @@ -4086,4 +4048,6 @@ 重點標示 成功 錯誤 + 只在遊戲期間顯示 HUD + 未偵測到遊戲畫面時隱藏 HUD。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index d484813b1e..a1f1534f67 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1269,8 +1269,6 @@ 開啟開發人員選項 此 Android 版本沒有該開關,因此 DroidDeck 會透過無線偵錯進行修改。大約需要一分鐘,無需電腦。 無線偵錯需要 Wi-Fi。任何網路都可以,不需要網際網路。 - 配對碼會顯示在通知中。請允許 DroidDeck 傳送通知,或使用「其他方式」。 - 允許通知 開啟「Android 設定」→「開發人員選項」→「無線偵錯」,並將其開啟 點擊「使用配對碼配對裝置」 將配對碼輸入 DroidDeck 通知中 @@ -1287,48 +1285,13 @@ 狀態 每 2 秒檢查一次。關閉此開關後此頁面會自動關閉。 其他方式 - 無線偵錯、手動輸入位址、電腦 ADB - 手動輸入位址、電腦 ADB、開發人員選項 改用無線偵錯 部分 ROM 仍會提供此開關。請在開發人員選項中搜尋「子處理程序」。 - 如果通知方式沒有作用,請手動輸入彈出視窗中的位址和配對碼。 - 手動輸入位址 使用電腦上的 ADB: 複製指令 將頭戴裝置連接到電腦並開啟 SideQuest。依序選擇「Run ADB Command」和「Custom Command」,輸入下方顯示的指令,然後選擇「Run Command」。 選擇在哪個螢幕上開啟 Android 設定。 主螢幕 - 已配對。正在尋找無線偵錯連接埠… - 已配對。請輸入設定中的連接埠。 - 已找到裝置。正在套用設定… - 無法自動套用。請檢查下方位址後重試。%1$s - 無線偵錯 - 子處理程序限制已更新 - 變更子處理程序限制 - 如果沒有該選項,請透過無線偵錯進行配對。 - 已配對。請檢查無線偵錯中的 IP 位址和連接埠。 - 子處理程序限制已更新。 - 如果開發人員選項中沒有子處理程序設定,請使用步驟 2。開啟開發人員選項 → 無線偵錯 → 使用配對碼配對裝置。 - 已配對。請使用下面的位址,或在無線偵錯 → IP 位址和連接埠 中更新它。 - 已透過無線偵錯更新子處理程序限制。 - Android 已確認限制處於開啟狀態。 - Android 已確認限制處於關閉狀態。 - 2 · 配對無線偵錯 - 配對彈出視窗中的 IP 位址和連接埠 - 配對碼(PIN) - 6 位數字 - 配對 - 2 · 透過無線偵錯套用 - 連線 IP 位址和連接埠 - 重新配對 - 關閉限制 - 其他變更方式 - 1 · 開發人員選項(優先嘗試) - 關閉「停止限制子程序」。 - 開啟「停止限制子程序」。 - 3 · 電腦 ADB(最後手段) - 僅在無線偵錯無法使用時使用。 - 3 · 電腦 ADB(最後手段) 顏色 自訂 不透明度 @@ -1610,8 +1573,6 @@ 已清除 %1$d 個工作階段日誌資料夾。 - 無線偵錯配對失敗 - 無線偵錯指令失敗 無法使用無線偵錯 已複製 ADB 指令 選擇 ROM 資料夾 @@ -2725,6 +2686,7 @@ 與登入頁面的連線不安全。 無法驗證登入。請再試一次。 登入失敗。請再試一次。 + %1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。 關閉 返回 編輯 @@ -3105,7 +3067,7 @@ 完成 正在等待眼鏡的 USB Ethernet 連線。這支手機可能不會向應用程式開放此連線。 XREAL 連線中斷或傳回不支援的回應。正在重試… - 實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在實機上測試。 + 實驗性支援 XREAL 1S、One、One Pro、One Pro+ 和 Aura。請在眼鏡選單中使用 Follow 模式並關閉畫面穩定;在 Aura 上還需關閉 Spatial Anchor。頭部追蹤和 2D/3D 切換已在 Aura 和 One Pro+ 上測試。 Pro 2 實驗性頭部追蹤。尚不支援亮度、音量調整及顯示模式切換。 開發商 發行商 @@ -4086,4 +4048,6 @@ 醒目標示 成功 錯誤 + 僅在遊戲期間顯示 HUD + 未偵測到遊戲畫面時隱藏 HUD。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1b57e5b281..69b03e75f6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -35,8 +35,9 @@ Frame rate (fps) Match screen Scroll speed + First launch also downloads Proton Experimental (about 400 MB) and sets Steam up. After this it starts much faster. - First run downloads Steam. This may take a few minutes. + DroidDeck downloads Steam in the background while you set up, so your first launch is quicker. 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. Hold Back on your controller to open Steam\'s Quick Access menu. Hold Back for Steam shortcuts must be on in the session settings. 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. @@ -1041,10 +1042,11 @@ Dual screen launcher 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. Dual screen sessions - 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. + 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. Automatic On Off + On, game on second screen Bottom screen controls in games Android keyboard for text fields 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. @@ -1420,13 +1422,12 @@ One Android setting to change Steam Android stops apps that start many background processes, and Steam starts dozens. Until this changes, games close without an error. + The pairing code goes in a notification. Turn on notifications for DroidDeck, then try again. Fix it for me Turn on “Disable child process restrictions”, then come back. Leave Developer options on, or the switch turns off again. Open Developer options This Android version has no switch for it, so DroidDeck changes it over Wireless debugging. Takes about a minute, no computer needed. Wireless debugging needs Wi-Fi. Any network works; it doesn\'t need internet. - The pairing code goes in a notification. Allow notifications for DroidDeck, or use Other ways. - Allow notifications Open Settings → Developer options → Wireless debugging and turn it on Tap “Pair device with pairing code” Type the code into the DroidDeck notification @@ -1443,49 +1444,16 @@ Status Checking every 2 seconds. This page closes when it\'s off. Other ways - Wireless debugging, manual address, computer ADB - Manual address, computer ADB, Developer options + Computer ADB + Computer ADB, Developer options Use Wireless debugging instead Some ROMs add the switch anyway. Look for “child process” in Developer options. - If the notification doesn\'t work, enter the pop-up\'s address and code yourself. - Enter address manually From a computer with ADB: Copy command SideQuest 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”. Choose which display to open Android Settings on. Main screen - Paired. Finding the Wireless debugging port… - Paired. Enter the port from Settings. - Device found. Applying the setting… - Couldn\'t apply automatically. Check the address below and retry. %1$s - Wireless debugging - Child-process limit updated - Change the child-process limit - If the option is missing, pair over Wireless debugging. - Paired. Check the IP address and port in Wireless debugging. - The child-process limit was updated. - Use step 2 if Developer options has no child-process setting. Open Developer options → Wireless debugging → Pair device with pairing code. - Paired. Use the address below, or update it from Wireless debugging → IP address & Port. - The child-process limit was updated over Wireless debugging. - Android confirmed the limit is on. - Android confirmed the limit is off. - 2 · Pair Wireless debugging - Pairing pop-up IP address & port - Pairing code (PIN) - 6 digits - Pair - 2 · Apply over Wireless debugging - Connection IP address & port - Pair again - Turn limit off - Other ways to change it - 1 · Developer options (try first) - Turn off “Disable child process restrictions”. - Turn on “Disable child process restrictions”. - 3 · Computer ADB (last resort) - Only if Wireless debugging is unavailable. - 3 · Computer ADB (last resort) Color Custom Opacity @@ -1837,8 +1805,6 @@ Cleared %1$d session log folder. Cleared %1$d session log folders. - Wireless debugging pairing failed - Wireless debugging command failed Wireless debugging is unavailable ADB command copied Choose the ROMs folder @@ -1875,6 +1841,7 @@ Choose the game storage folder Choose a Decky plugin ZIP Not usable: %1$s + FAT32 cannot hold files over 4 GB, so some games will fail to install. Reformat as exFAT. Program Removing Linux runtime Could not open Settings on the bottom screen; opened it on the main screen. @@ -3067,6 +3034,7 @@ The connection to the sign-in page is not secure. The sign-in could not be verified. Try again. Sign-in failed. Try again. + %1$s needs one more step. Finish it in the browser that opened, then try again. Close Back Edit @@ -3485,7 +3453,7 @@ Done Waiting for the glasses’ USB Ethernet connection. This phone may not expose it to apps. The XREAL connection was interrupted or returned an unsupported response. Retrying… - 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. + 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+. Experimental Pro 2 head tracking. Brightness, volume, and display switching are not supported yet. Picture position Top @@ -4152,6 +4120,8 @@ Location denied · allow it in App info Steam’s slider sets screen brightness Home opens the Steam menu in a session + Bluetooth controllers + Lets DroidDeck connect to Steam Controllers and other Bluetooth pads Alt+Tab, Win key and Home button stay in the session Greyed out in Android? App info → ⋮ → Allow restricted settings System keys didn\'t install @@ -4399,4 +4369,23 @@ Reset tabs Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More. Your tab order and what sits under More or is hidden go back to the defaults. + Getting DroidDeck ready + %1$d%% · you can keep using the app + Linux runtime + DroidDeck Proton + Steam client + Waiting + Ready + Will retry + Downloading the Steam client + Downloading the Steam client (%1$d MB) + The Steam client download will retry + Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish. + Do it for me + Set up while you wait + Getting ready · %1$d%% · %2$s + Show HUD only during a game + Hide the HUD when no game frames are detected. + Getting ready · %1$d%% + Finish setup · %1$d%% 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 + + @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(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/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("") + 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(), 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() + 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() @@ -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 02380b0f25..078b3e3fdc 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt @@ -187,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() + val menu = BackQamInput({}, taps::add) + val guest = mutableListOf>() + 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/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/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() + 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/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/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() + val first = coordinator.beginLaunch() + val second = coordinator.beginLaunch() + assertFalse(coordinator.isCurrent(first)) + assertTrue(coordinator.isCurrent(second)) + } + + @Test + fun anAllowedLaunchDropsThePendingLink() { + val coordinator = LaunchCoordinator() + coordinator.beginLink("link") + coordinator.beginLaunch() + assertFalse(coordinator.hasPending()) + } + + @Test + fun aLinkReadResolvesAndIsConsumed() { + val coordinator = LaunchCoordinator() + 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() + 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() + 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() + 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() + coordinator.beginLink("link") + val launch = coordinator.beginLaunch() + assertNull(coordinator.pendingLink()) + assertTrue(coordinator.isCurrent(launch)) + } + + @Test + fun aSecondLinkReplacesTheFirst() { + val coordinator = LaunchCoordinator() + 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() + val ticket = coordinator.beginLink("intent-a") + coordinator.resolve(ticket, "game") + assertSame("intent-a", coordinator.pendingLink()?.owner) + } + + @Test + fun aLinkIsOwnedOnlyByItsIntent() { + val coordinator = LaunchCoordinator() + 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() + 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/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/PortraitResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt index fb9199157b..f010e97a65 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -1,6 +1,7 @@ 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 @@ -74,6 +75,35 @@ class PortraitResolutionTest { 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)) 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() + 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, val state: State) { + class State { var blocked = true; var busy = false } + val started = mutableListOf() + 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(15 * minute).also { it.queue("steam", 0) }, Owner.State()) + owner.runner.poke() + clock.advance(5_000) + assertEquals(emptyList(), 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(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + clock.advance(7_000) + assertEquals(emptyList(), 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(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + clock.advance(16 * minute) + state.busy = false + clock.advance(10_000) + assertEquals(emptyList(), owner.started) + } + + @Test fun onlyTheRestoredOwnerStartsAfterTheFirstOneIsDestroyedMidRetry() { + val clock = Clock() + val state = Owner.State().apply { blocked = false; busy = true } + val firstQueue = QueuedLaunch(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(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(), 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(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + owner.runner.destroy() + clock.advance(10_000) + assertEquals(emptyList(), owner.started) + } + + @Test fun pokingTwiceBeforeTheFirstAttemptStartsTheLaunchOnce() { + val clock = Clock() + val state = Owner.State().apply { blocked = false } + val owner = Owner(clock, QueuedLaunch(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(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(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(15 * minute) + queue.restore("steam", queuedAt = 0, now = 20 * minute) + assertNull(queue.launch) + } + + @Test fun aLaunchRestoredWithoutAValidTimeIsDropped() { + val queue = QueuedLaunch(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(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/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 { + 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/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/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() 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() + 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, modifiedMs: Map): Map { val sent = LinkedHashMap() @@ -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 + 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/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 = 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/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt index 2811284d0e..a64e56383f 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -298,7 +298,7 @@ class CurseLinkTabTest { 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/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/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/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 8e9fcad74a..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", "decky", "boot-movies"), 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", "decky", "boot-movies"), 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() { @@ -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/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/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/development/game-environment.md b/docs/development/game-environment.md index 8d366151e6..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 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/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/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 d90a458d2c..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,101 +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 - 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 - github_repo=${DROIDDECK_GITHUB_REPOSITORY:-} if [[ -z "${github_repo}" ]]; then origin_url=$(git -C "${repo_root}" remote get-url origin) @@ -223,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}") @@ -273,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" @@ -384,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 @@ -419,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" 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/fex/patches/0013-path-syscalls-through-libc.patch b/tools/fex/patches/0013-path-syscalls-through-libc.patch index 122f7654d2..1aa641b311 100644 --- a/tools/fex/patches/0013-path-syscalls-through-libc.patch +++ b/tools/fex/patches/0013-path-syscalls-through-libc.patch @@ -1,5 +1,5 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp -index 11ff163..085a621 100644 +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, @@ -44,6 +44,20 @@ index 11ff163..085a621 100644 static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3); REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3); +@@ -220,11 +255,11 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(shmctl, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(getpid, SyscallPassthrough0); + REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(connect, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(bind, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3); @@ -238,9 +273,9 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { REGISTER_SYSCALL_IMPL(flock, SyscallPassthrough2); REGISTER_SYSCALL_IMPL(fsync, SyscallPassthrough1); 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 ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough0(FEXCore::Core::CpuStateFrame* Frame) { ++ uint64_t Result = ::syscall(syscall_num); ++ SYSCALL_ERRNO(); ++} ++ + template + 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); + REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(fchown, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(umask, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(getuid, SyscallPassthrough0); ++ REGISTER_SYSCALL_IMPL(getuid, SyscallPathPassthrough0); + REGISTER_SYSCALL_IMPL(syslog, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(getgid, SyscallPassthrough0); +- REGISTER_SYSCALL_IMPL(setuid, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(setgid, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(geteuid, SyscallPassthrough0); +- REGISTER_SYSCALL_IMPL(getegid, SyscallPassthrough0); ++ REGISTER_SYSCALL_IMPL(getgid, SyscallPathPassthrough0); ++ REGISTER_SYSCALL_IMPL(setuid, SyscallPathPassthrough1); ++ REGISTER_SYSCALL_IMPL(setgid, SyscallPathPassthrough1); ++ REGISTER_SYSCALL_IMPL(geteuid, SyscallPathPassthrough0); ++ REGISTER_SYSCALL_IMPL(getegid, SyscallPathPassthrough0); + REGISTER_SYSCALL_IMPL(setpgid, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(getppid, SyscallPassthrough0); + REGISTER_SYSCALL_IMPL(setsid, SyscallPassthrough0); +- REGISTER_SYSCALL_IMPL(setreuid, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(setregid, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(getgroups, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(setgroups, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(setresuid, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(getresuid, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(setresgid, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(getresgid, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(setreuid, SyscallPathPassthrough2); ++ REGISTER_SYSCALL_IMPL(setregid, SyscallPathPassthrough2); ++ REGISTER_SYSCALL_IMPL(getgroups, SyscallPathPassthrough2); ++ REGISTER_SYSCALL_IMPL(setgroups, SyscallPathPassthrough2); ++ REGISTER_SYSCALL_IMPL(setresuid, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(getresuid, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(setresgid, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(getresgid, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(getpgid, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(setfsuid, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(setfsgid, SyscallPassthrough1); ++ REGISTER_SYSCALL_IMPL(setfsuid, SyscallPathPassthrough1); ++ REGISTER_SYSCALL_IMPL(setfsgid, SyscallPathPassthrough1); + REGISTER_SYSCALL_IMPL(getsid, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(capget, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(capset, SyscallPassthrough2); +@@ -537,23 +544,23 @@ namespace x64 { + namespace x32 { + void RegisterPassthrough(FEX::HLE::SyscallHandler* Handler) { + RegisterCommon(Handler); +- REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPassthrough0); +- REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPassthrough0); +- REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPassthrough0); +- REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPassthrough0); +- REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPassthrough1); ++ REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPathPassthrough0); ++ REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPathPassthrough0); ++ REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPathPassthrough0); ++ REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPathPassthrough0); ++ REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPathPassthrough2); ++ REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPathPassthrough2); ++ REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPathPassthrough2); ++ REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPathPassthrough2); ++ REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPathPassthrough1); ++ REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPathPassthrough1); ++ REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPathPassthrough1); ++ REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPathPassthrough1); + REGISTER_SYSCALL_IMPL_X32(sendfile64, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X32(clock_gettime64, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X32(clock_settime64, SyscallPassthrough2); 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, ""); ++ FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, Program.ProgramPath); + FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, ""); + } + } 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); + REGISTER_SYSCALL_IMPL_X64(sendfile, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(accept, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X64(sendmsg, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL_X64(sendmsg, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL_X64(setsockopt, SyscallPassthrough5); +- REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPassthrough5); ++ REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPathPassthrough5); + REGISTER_SYSCALL_IMPL_X64(wait4, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(semop, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(getrlimit, SyscallPassthrough2); diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 214c9b75b8..e28e224cdd 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -418,3 +418,12 @@ changed focus. In a nested session with no other window the SDL window stayed hi 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/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/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index f715ad18d7..6a1cdc4d08 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -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-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-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 a465a93859..e1bee1c12a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -164,6 +164,12 @@ def ff7_rebirth_feature_level(game): 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": @@ -236,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" @@ -1406,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-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 61dbb5feda..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) ) & 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("> 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 @@ -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/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/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 4dd7d1f115..54aac381fa 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -1146,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 de3cfdaee7..388b92da6a 100644 --- a/tools/linuxfs/preload/net.c +++ b/tools/linuxfs/preload/net.c @@ -277,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); @@ -377,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/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/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/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/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 #include #include +#include #include #include #include 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 #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 8f3daf8086..fd6824d3b7 100644 --- a/tools/nativeguest/hook/env.c +++ b/tools/nativeguest/hook/env.c @@ -76,7 +76,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const 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, const 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; @@ -217,19 +215,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const 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 664b0beedf..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,15 +88,11 @@ 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); } @@ -407,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! @@ -476,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; @@ -712,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 *, @@ -829,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; @@ -959,7 +1012,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, int ret = -1; 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)); 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 " / "bl " 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 +} + +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 09a1074b86..d2a84c7a23 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -526,6 +526,12 @@ static long nested_path_syscall(long number, unsigned long dirfd, unsigned long 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); @@ -708,6 +714,31 @@ long syscall(long number, ...) { 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); @@ -867,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//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//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/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/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 89488e1ba5..4b2da89133 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -48,8 +48,19 @@ 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, builds = [], set() + skipped = set(copied(root)) for name in SOURCE_PATHS: path = root / name files.extend(path.rglob('*') if path.is_dir() else [path]) @@ -57,14 +68,18 @@ def sources(root): 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' + 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']: @@ -84,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']] @@ -178,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: @@ -195,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 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/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_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_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_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_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_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("&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_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, "");', 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, "");', 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 +#include +#include +#include +#include +#include +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)\);") +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 +#include +#include +#include +#include +#include + +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_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)\);") +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 +#include +#include +#include +#include +#include + +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_game_environment.py b/tools/tests/test_game_environment.py index e2a6d85385..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 @@ -1548,6 +1549,65 @@ class GameEnvironmentTest(unittest.TestCase): 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" @@ -1866,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 +#include +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_inputudev_preload.py b/tools/tests/test_inputudev_preload.py index 7cb96a91d5..68d55403fe 100644 --- a/tools/tests/test_inputudev_preload.py +++ b/tools/tests/test_inputudev_preload.py @@ -650,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_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 +#include +#include +#include +#include +#include +#include + +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 +#include +#include + +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 +#include + +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 +#include +#include +#include +#include + +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 +#include +#include +#include + +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 + +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 index 43b810344a..8d8b417f82 100644 --- a/tools/tests/test_native_hook_ldso_spawn.py +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -10,6 +10,9 @@ 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 @@ -24,6 +27,7 @@ static void show(const char *path, char *const argv[], char *const envp[]) { 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); } @@ -102,13 +106,33 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): 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): + 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}")] @@ -118,6 +142,7 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): 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) @@ -146,6 +171,14 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): 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): @@ -158,6 +191,42 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): 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 #include #include +#include #include #include +#include #include 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 +#include +#include +#include +#include +#include +#include + +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 +#include +int main(int argc, char **argv) { return sem_open(argv[1], O_CREAT | O_EXCL, 0640, 3) == SEM_FAILED; } +""" + +FORKER = r""" +#include +#include +#include +#include +#include +#include + +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 index ab69fc3c83..be0967cbb0 100644 --- a/tools/tests/test_native_hook_path_syscalls.py +++ b/tools/tests/test_native_hook_path_syscalls.py @@ -12,9 +12,12 @@ PROBE = r""" #define _GNU_SOURCE #include #include +#include #include #include +#include #include +#include #include static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); } @@ -40,6 +43,29 @@ int main(int argc, char **argv) { 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); @@ -88,7 +114,7 @@ __attribute__((constructor)) static void early(void) { free(malloc(1)); } """ CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat", - "chdir", "cwd", "unlinkat-file", "unlinkat-dir") + "bind", "connect", "bind-length", "connect-length", "chdir", "cwd", "unlinkat-file", "unlinkat-dir") class NativeHookPathSyscallsTest(unittest.TestCase): @@ -97,7 +123,7 @@ class NativeHookPathSyscallsTest(unittest.TestCase): cls.cc, cls.prefix = runner() if cls.cc is None: raise unittest.SkipTest("no aarch64 compiler and runner") - cls.tmp = tempfile.TemporaryDirectory() + 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) 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//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 +#include +#include +#include +#include +#include +#include + +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_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_runtime_inputs.py b/tools/tests/test_runtime_inputs.py index 92f2ae1c79..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') 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('> "$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_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("> (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 + +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 +#include +#include + +#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 +#include +#include +#include +#include + +#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_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/vk_terminal_callers_test.c b/tools/tests/vk_terminal_callers_test.c index ebf8fbf096..374c049a6f 100644 --- a/tools/tests/vk_terminal_callers_test.c +++ b/tools/tests/vk_terminal_callers_test.c @@ -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 #include @@ -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 a4e35e0a32..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); \ @@ -638,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; } @@ -665,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); } @@ -692,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), @@ -723,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), diff --git a/tools/venus/layer/mali_compat.h b/tools/venus/layer/mali_compat.h index eb171bb6f9..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) @@ -138,7 +142,9 @@ struct instance { X(CmdPushDescriptorSetWithTemplate) \ X(CmdBindVertexBuffers) \ X(CmdBindVertexBuffers2) \ - X(CmdSetColorBlendEquationEXT) + X(CmdSetColorBlendEquationEXT) \ + X(CmdSetDepthTestEnable) \ + X(CmdSetDepthCompareOp) struct staging_block; @@ -163,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; @@ -311,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 95c0ccd1ee..01236be5b7 100644 --- a/tools/venus/layer/pipeline.c +++ b/tools/venus/layer/pipeline.c @@ -143,6 +143,7 @@ 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]; @@ -401,6 +402,19 @@ 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) 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 = 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 { @@ -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), "").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), "").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), "").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");