diff --git a/.github/trusted-test-builds.txt b/.github/trusted-test-builds.txt new file mode 100644 index 0000000000..9b09f6132b --- /dev/null +++ b/.github/trusted-test-builds.txt @@ -0,0 +1,5 @@ +# GitHub PR openers trusted for automatic release-signed test builds. +FX192 +K11MCH1 +kingokksa +ovurrsl diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 146e7fe3bf..0dd6d06d16 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -494,6 +494,16 @@ jobs: - name: Build the add-on packs run: bash tools/packs/build.sh app/build/packs + - name: Note when the proot pack pin is behind this build + run: | + set -euo pipefail + # shellcheck disable=SC1091 + source tools/packs/proot/release.env + sha=$(sha256sum app/build/packs/proot.tar.zst | cut -d' ' -f1) + if [ "$sha" != "$PROOT_PACK_SHA256" ]; then + echo "::warning::built proot pack $sha does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256). This build publishes the pack it just built. Source builds keep downloading the pinned pack until release.env is updated." + fi + - name: Build id: build env: @@ -610,7 +620,6 @@ jobs: UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }} TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }} APK_OUTCOME: ${{ steps.apk-upload.outcome }} - SAME_REPO: ${{ github.event.pull_request.head.repo.full_name == github.repository }} run: bash tools/release/report-build.sh python-tests: diff --git a/.github/workflows/pr-release-publish.yml b/.github/workflows/pr-release-publish.yml index dab96e0154..85f972a1b4 100644 --- a/.github/workflows/pr-release-publish.yml +++ b/.github/workflows/pr-release-publish.yml @@ -8,6 +8,10 @@ on: description: Open pull request number required: true type: string + automatic_build_run_id: + description: Completed build run for automatic publishing + required: false + type: string pull_request_target: types: [labeled] branches: [main] @@ -27,16 +31,47 @@ concurrency: queue: max jobs: + dispatch-fork-builds: + if: >- + github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && + github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.head_repository.full_name != github.repository + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + actions: write + pull-requests: read + steps: + - name: Find fork PRs for the completed build + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ github.event.workflow_run.id }} + RUN_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_REPO: ${{ github.event.workflow_run.head_repository.full_name }} + RUN_BRANCH: ${{ github.event.workflow_run.head_branch }} + run: | + set -euo pipefail + owner=${RUN_REPO%%/*} + gh api --paginate --slurp -X GET "repos/$GITHUB_REPOSITORY/pulls" \ + -f state=open -f base=main -f "head=$owner:$RUN_BRANCH" -f per_page=100 | + jq -r --arg sha "$RUN_SHA" --arg repo "$RUN_REPO" --arg branch "$RUN_BRANCH" ' + .[][] | select(.head.sha == $sha and .head.repo.full_name == $repo and .head.ref == $branch) | .number' | + while IFS= read -r number; do + gh workflow run pr-release-publish.yml -R "$GITHUB_REPOSITORY" --ref main \ + -f "pr_number=$number" -f "automatic_build_run_id=$RUN_ID" + done + authorize: if: >- (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') || - (github.event_name == 'pull_request_target' && github.event.label.name == 'publish-test') || + (github.event_name == 'pull_request_target' && + (github.event.action != 'labeled' || github.event.label.name == 'publish-test')) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.pull_requests[0] != null) runs-on: ubuntu-24.04 - timeout-minutes: 45 + timeout-minutes: 150 outputs: pr_number: ${{ steps.gate.outputs.pr_number }} run_id: ${{ steps.gate.outputs.run_id }} @@ -50,6 +85,7 @@ jobs: steps: - uses: actions/checkout@v4 with: + fetch-depth: 0 persist-credentials: false - name: The packages a signed build ships as id: variants @@ -61,22 +97,14 @@ jobs: EVENT_NAME: ${{ github.event_name }} REQUESTER: ${{ github.actor }} PR_NUMBER: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }} + ACTION: ${{ github.event.action }} BUILT_SHA: ${{ github.event.workflow_run.head_sha }} + AUTO_RUN: ${{ inputs.automatic_build_run_id }} run: | set -euo pipefail [[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "::error::Invalid PR number '$PR_NUMBER'"; exit 1; } skip() { echo "::notice::Not publishing PR #$PR_NUMBER: $1"; echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0; } - if [ "$EVENT_NAME" = workflow_run ]; then - echo "automatic=true" >> "$GITHUB_OUTPUT" - pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") - [ "$(jq -r .state <<<"$pr")" = open ] || skip "it is not open" - [ "$(jq -r .draft <<<"$pr")" = false ] || skip "it is a draft" - [ "$(jq -r .base.ref <<<"$pr")" = main ] || skip "it does not target main" - [ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork" - jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build" - [ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building" - fi - if [ "$EVENT_NAME" = pull_request_target ]; then + if [ "$EVENT_NAME" = pull_request_target ] && [ "$ACTION" = labeled ]; then permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$REQUESTER/permission" --jq .permission) case "$permission" in admin|maintain|write) ;; @@ -85,29 +113,59 @@ jobs: fi pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null || - { echo "::error::PR #$PR_NUMBER must be open, ready for review, and target main"; exit 1; } + skip "it must be open, ready for review, and target main" + if [ "$EVENT_NAME" = workflow_run ]; then + [ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork" + [ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building" + jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build" + echo "automatic=true" >> "$GITHUB_OUTPUT" + elif [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; then + [[ "$AUTO_RUN" =~ ^[1-9][0-9]*$ ]] || { echo '::error::Invalid automatic build run ID'; exit 1; } + jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build" + git fetch --no-tags origin main + opener=$(jq -r .user.login <<<"$pr") + git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener" || skip "PR opener @$opener is not trusted for automatic signing" + echo "automatic=true" >> "$GITHUB_OUTPUT" + fi head=$(jq -r '.head.sha' <<<"$pr") base=$(jq -r '.base.sha' <<<"$pr") run_id= - for attempt in $(seq 1 60); do - latest=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml \ - --event pull_request --commit "$head" \ - --json databaseId,headSha,status,conclusion,createdAt,attempt -L 100 | - jq -c --arg head "$head" '[.[] | select(.headSha == $head)] | - sort_by([.createdAt, .attempt]) | last // empty') + for attempt in $(seq 1 240); do + latest=$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/build.yml/runs?event=pull_request&head_sha=$head&per_page=100" | + jq -c --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" ' + [.workflow_runs[] | select(.head_sha == $head and .head_repository.full_name == $repo and .head_branch == $ref)] | + sort_by([.created_at, .run_attempt]) | last // empty') + if [[ -z "$latest" && "$attempt" == 1 ]]; then + git fetch --no-tags origin main + git fetch --no-tags origin "refs/pull/$PR_NUMBER/head" + git diff --no-renames --name-only -z "$base...FETCH_HEAD" > "$RUNNER_TEMP/pr-changed-paths" + excluded=true + while IFS= read -r -d '' path; do + case "$path" in + *.md|LICENSE|.gitignore) ;; + *) excluded=false; break ;; + esac + done < "$RUNNER_TEMP/pr-changed-paths" + [ "$excluded" = false ] || skip "its changes do not trigger the APK build" + fi if [[ -n "$latest" && $(jq -r .status <<<"$latest") == completed ]]; then conclusion=$(jq -r .conclusion <<<"$latest") - [[ "$conclusion" == success ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; } - run_id=$(jq -r .databaseId <<<"$latest") - break + if [[ "$conclusion" == success ]]; then + run_id=$(jq -r .id <<<"$latest") + if [ -n "$AUTO_RUN" ] && [ "$run_id" != "$AUTO_RUN" ]; then + skip "a newer build exists" + fi + break + fi + [[ "$conclusion" == action_required ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; } fi status=not-started [[ -z "$latest" ]] || status=$(jq -r .status <<<"$latest") echo "Waiting for the PR build of ${head:0:7} to finish ($status)" sleep 30 done - [[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 30 minutes'; exit 1; } + [[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 120 minutes'; exit 1; } run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id") jq -e --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" ' .event == "pull_request" and .head_sha == $head and .conclusion == "success" and @@ -137,6 +195,13 @@ jobs: .head.sha == $head and .base.sha == $base ' <<<"$current" >/dev/null || { echo "::error::PR #$PR_NUMBER moved on while its build was checked; publish again"; exit 1; } + if [ "$EVENT_NAME" = workflow_run ] || { [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; }; then + jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$current" >/dev/null && skip "it is labelled no-test-build" + if [ "$EVENT_NAME" = workflow_dispatch ]; then + git fetch --no-tags origin main + git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$(jq -r .user.login <<<"$current")" || skip "the PR opener is no longer trusted" + fi + fi { echo "pr_number=$PR_NUMBER" echo "run_id=$run_id" @@ -271,17 +336,24 @@ jobs: echo "release=$release" >> "$GITHUB_OUTPUT" echo "apk=$GITHUB_SERVER_URL/$repo/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT" - - name: Whether the PR's branch is in this repo - id: same-repo + - name: Whether the PR opener is trusted + id: trusted-opener env: GH_TOKEN: ${{ github.token }} PR_NUMBER: ${{ needs.authorize.outputs.pr_number }} run: | - head_repo=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .head.repo.full_name) - echo "same=$([ "$head_repo" = "$GITHUB_REPOSITORY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT" + pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") + opener=$(jq -r .user.login <<<"$pr") + git fetch --no-tags origin main + if [ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || + git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener"; then + echo "trusted=true" >> "$GITHUB_OUTPUT" + else + echo "trusted=false" >> "$GITHUB_OUTPUT" + fi - name: Clear the publish request label - if: ${{ github.event_name == 'pull_request_target' && steps.publish.outcome == 'success' }} + if: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && steps.publish.outcome == 'success' }} env: GH_TOKEN: ${{ github.token }} PR_NUMBER: ${{ needs.authorize.outputs.pr_number }} @@ -295,12 +367,12 @@ jobs: HEAD_SHA: ${{ needs.authorize.outputs.head_sha }} RELEASE: ${{ steps.publish.outputs.release }} APK: ${{ steps.publish.outputs.apk }} - SAME_REPO: ${{ steps.same-repo.outputs.same }} + TRUSTED_OPENER: ${{ steps.trusted-opener.outputs.trusted }} run: | set -euo pipefail short=${HEAD_SHA:0:7} mark='' - if [ "$SAME_REPO" = true ]; then + if [ "$TRUSTED_OPENER" = true ]; then NEXT='Each green build of a new push is signed and published here on its own. Label the PR `no-test-build` to stop that.' else NEXT='Pushes to this PR do not re-sign automatically. After a new green build, a maintainer can add the `publish-test` label again.' diff --git a/README.md b/README.md index 653df9f720..8290b3ef6a 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,10 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big

Join the DroidDeck Discord

+

+ Star History Rank +

+

Droid-Deck%2FDroidDeck | Trendshift Droid-Deck%2FDroidDeck | Trendshift @@ -57,7 +61,7 @@ Compatibility and performance vary by device; hardware validation is limited. De ## Credits and licence -GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc//mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc//status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driver in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). Xbox games load the Windows modules of [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) runtime (LGPL-2.1-or-later), including its `wintypes.dll`, whose `ApiInformation` answer Minecraft for Windows needs to start; how Minecraft installs GameInput under Wine was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve. +GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader, without taking their code. The registry entries a GOG game's install script (`goggame-.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. x86 AppImages packed with [sharun](https://github.com/VHSgunzo/sharun) by VHSgunzo (MIT) start because DroidDeck's own [FEX](https://github.com/FEX-Emu/FEX) build (MIT) puts the platform name under `AT_PLATFORM`, which sharun's [userland-execve](https://crates.io/crates/userland-execve) loader (MIT) requires; FEX filed it under `AT_BASE_PLATFORM`. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc//mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc//status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driver in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). Xbox games load the Windows modules of [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) runtime (LGPL-2.1-or-later), including its `wintypes.dll`, whose `ApiInformation` answer Minecraft for Windows needs to start; how Minecraft installs GameInput under Wine was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). [ReSkate](https://github.com/Dingo-Shenanigans/ReSkate) (GPL-3.0) by Dingo Shenanigans is set up with the Steam launch option from its README and starts at D3D12 feature level 12_1, as its game crashes at 12_2 here. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve. XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them. @@ -67,4 +71,8 @@ Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead. +Remote Play from a PC to the arm64 Steam client goes through a stand-in for the V4L2 decoder and the libdrm dumb buffers that Steam's `streaming_client` expects: each frame is decoded by Android's MediaCodec through the app, or by the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) that ships in Steam's own runtime, into dma-heap buffers that its Vulkan renderer imports. The Qualcomm low-latency decoder settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0). + Steam's Browse buttons open a GTK 3 file chooser through PyGObject (LGPL-2.1-or-later). It runs under Steam's own `reaper` with Steam's app ID, which [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) reads from the process tree (`GetAppIdFromReaper` in `src/Utils/Process.cpp`) to show it over Steam. + +Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose fixes for them (`311210.py` sets ALSA audio, `570940.py` installs VC++ 2017) fail under ARM64 Proton. diff --git a/app/build.gradle b/app/build.gradle index 8ba8c8ea09..1c9b9bad8d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -87,10 +87,18 @@ def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines() def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines() .findAll { it.contains('=') && !it.startsWith('#') } .collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] } +def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines() + .findAll { it.contains('=') && !it.startsWith('#') } + .collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] } def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].collectEntries { name -> def pack = file("build/packs/${name}.tar.zst") if (!pack.isFile()) { if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") + // A source build that did not compile proot still pins a published pack, so the app + // downloads the patched binary instead of falling back to the rootfs copy. + if (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) { + return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]] + } return [(name): [sha256: '', size: 0L]] } def digest = java.security.MessageDigest.getInstance('SHA-256') @@ -262,6 +270,7 @@ def runtimeAssetsDir = layout.buildDirectory.dir('runtimeAssets') def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) { dependsOn(stageSessionScripts) from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' } + from(rootProject.file('tools/linuxfs/innoextract')) from(layout.buildDirectory.dir('prepared-assets')) into(runtimeAssetsDir) } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 29718e0879..091811b040 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,15 @@ + + + + + + + + + @@ -18,7 +27,10 @@ + + + @@ -47,6 +59,15 @@ + + + + + + + + @@ -116,7 +148,7 @@ android:excludeFromRecents="true" android:noHistory="true" android:taskAffinity="${applicationId}.home" - android:screenOrientation="sensorLandscape" + android:screenOrientation="user" android:theme="@android:style/Theme.Translucent.NoTitleBar"> @@ -126,6 +158,18 @@ + + + + + + + @@ -176,7 +220,7 @@ diff --git a/app/src/main/cpp/framegen/ddfg/framegen.cpp b/app/src/main/cpp/framegen/ddfg/framegen.cpp index 82d0a764b7..5200f6b094 100644 --- a/app/src/main/cpp/framegen/ddfg/framegen.cpp +++ b/app/src/main/cpp/framegen/ddfg/framegen.cpp @@ -184,8 +184,9 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) { VkExtent2D e = levelExtent(extent, l); if (!makeImage(pyrA_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false; if (!makeImage(pyrB_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false; - if (!makeImage(flowLvl_[l], e, VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false; } + for (int l = flowFinest_; l < kLevels; ++l) + if (!makeImage(flowLvl_[l], levelExtent(extent, l), VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false; pyrAs_.resize(kLevels); for (int l = flowFinest_; l < kLevels; ++l) if (!makeImage(pyrAs_[l], levelExtent(extent, l), VK_FORMAT_R32_SFLOAT, lumaUsage)) return false; diff --git a/app/src/main/cpp/framegen/ddfg/record_impl.inc b/app/src/main/cpp/framegen/ddfg/record_impl.inc index 554c05c7fc..734d94cdc9 100644 --- a/app/src/main/cpp/framegen/ddfg/record_impl.inc +++ b/app/src/main/cpp/framegen/ddfg/record_impl.inc @@ -439,7 +439,7 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr); if (S.flowRegUboPtr) { FlowRegUBO fu{cfg.frDt, cfg.frLambda, cfg.frEdge, cfg.frEps}; std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); } S.flowUbo.resize(kLevels); S.flowUboMem.resize(kLevels); S.flowUboPtr.resize(kLevels); - for (int l = 0; l < kLevels; ++l) { + for (int l = fg->flowFinest(); l < kLevels; ++l) { makeUbo(dd, dev, mp, sizeof(FlowUBO), S.flowUbo[l], S.flowUboMem[l], S.flowUboPtr[l]); if (S.flowUboPtr[l]) { FlowUBO u{cfg.flowScale, (uint32_t)l, 0.6f, 1.6f}; std::memcpy(S.flowUboPtr[l], &u, sizeof(u)); } } @@ -464,13 +464,12 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, } S.sFlow.resize(kLevels); - for (int l = 0; l < kLevels; ++l) { + for (int l = fg->flowFinest(); l < kLevels; ++l) { S.sFlow[l] = allocSet(dd, dev, pool, pFlow.setLayout); int pred = (l + 1 < kLevels) ? l + 1 : l; - VkImageView currLvl = (l >= fg->flowFinest()) ? pyrAs[l].view : pyrA[l].view; wUbo(dd, dev, S.sFlow[l], 0, S.flowUbo[l], sizeof(FlowUBO)); wImg(dd, dev, S.sFlow[l], 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[l].view, samp, GEN); - wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currLvl, samp, GEN); + wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrAs[l].view, samp, GEN); wImg(dd, dev, S.sFlow[l], 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[pred].view, samp, GEN); wImg(dd, dev, S.sFlow[l], 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowLvl[l].view, VK_NULL_HANDLE, GEN); } diff --git a/app/src/main/cpp/venc/venc_proto.h b/app/src/main/cpp/venc/venc_proto.h index 9622577119..47fb6ef241 100644 --- a/app/src/main/cpp/venc/venc_proto.h +++ b/app/src/main/cpp/venc/venc_proto.h @@ -9,7 +9,7 @@ #define VENC_MAX_BUFFERS 16 -enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5 }; +enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5, VDEC_CONFIG = 6, VDEC_CAPTURE = 7, VDEC_PACKET = 8, VDEC_RESULT = 9 }; enum venc_touch_action { VENC_TOUCH_DOWN = 0, VENC_TOUCH_MOVE = 1, VENC_TOUCH_UP = 2 }; enum venc_codec { VENC_H264 = 0, VENC_HEVC = 1 }; @@ -52,4 +52,30 @@ struct venc_touch { uint32_t x, y; }; +struct vdec_config { + uint32_t type; + uint32_t codec; + uint32_t width, height; + uint32_t stride, rows; + uint32_t bitstreams, bitstream_size; +}; + +struct vdec_capture { + uint32_t type; + uint32_t index; + uint32_t size; +}; + +struct vdec_packet { + uint32_t type; + uint32_t input, bytes, capture; + int64_t pts_us; +}; + +struct vdec_result { + uint32_t type; + int32_t status; + uint32_t frame; +}; + #endif diff --git a/app/src/main/cpp/venc/venc_server.cpp b/app/src/main/cpp/venc/venc_server.cpp index be484c898d..17a5d7eed1 100644 --- a/app/src/main/cpp/venc/venc_server.cpp +++ b/app/src/main/cpp/venc/venc_server.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -11,6 +12,7 @@ #include #include +#include #include #include #include @@ -45,6 +47,218 @@ int32_t avc_profile(int32_t v4l2) { } } +struct DmaBufSync { + uint64_t flags; +}; +constexpr unsigned long kDmaBufIoctlSync = _IOW('b', 0, DmaBufSync); +constexpr uint64_t kDmaBufSyncWrite = 2, kDmaBufSyncStart = 0, kDmaBufSyncEnd = 4; +constexpr int32_t kColorFormatYuv420Planar = 19; + +class Decoder { +public: + ~Decoder() { release(); } + + void release() { + if (codec_) { + AMediaCodec_stop(codec_); + AMediaCodec_delete(codec_); + codec_ = nullptr; + } + if (bitstream_) munmap((void *)bitstream_, bitstream_size_); + bitstream_ = nullptr; + for (auto &c : captures_) drop(c); + } + + bool configure(const vdec_config &c, int fd) { + release(); + if (c.width < 16 || c.height < 16 || c.stride < c.width || c.rows < c.height || c.bitstreams == 0 || + c.bitstreams > VENC_MAX_BUFFERS || c.bitstream_size == 0) { + LOG("bad decoder config: %ux%u stride %u rows %u, %u bitstreams", c.width, c.height, c.stride, c.rows, + c.bitstreams); + return false; + } + bitstream_size_ = (size_t)c.bitstreams * c.bitstream_size; + void *p = mmap(nullptr, bitstream_size_, PROT_READ, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) { + LOG("could not map the bitstream buffers: %s", strerror(errno)); + return false; + } + bitstream_ = (const uint8_t *)p; + config_ = c; + codec_ = create(c, true); + if (!codec_) codec_ = create(c, false); + if (!codec_) { + LOG("no %s decoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height); + release(); + return false; + } + src_stride_ = (int32_t)c.width; + src_rows_ = (int32_t)c.height; + src_width_ = (int32_t)c.width; + src_height_ = (int32_t)c.height; + src_planar_ = false; + shown_ = false; + using GetName = media_status_t (*)(AMediaCodec *, char **); + using ReleaseName = void (*)(AMediaCodec *, char *); + static auto get_name = (GetName)dlsym(RTLD_DEFAULT, "AMediaCodec_getName"); + static auto release_name = (ReleaseName)dlsym(RTLD_DEFAULT, "AMediaCodec_releaseName"); + char *name = nullptr; + if (get_name && get_name(codec_, &name) != AMEDIA_OK) name = nullptr; + LOG("decoding %s %ux%u with %s", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height, + name ? name : "MediaCodec"); + if (name && release_name) release_name(codec_, name); + return true; + } + + void capture(const vdec_capture &c, int fd) { + if (c.index >= VENC_MAX_BUFFERS) { + close(fd); + return; + } + Capture &cap = captures_[c.index]; + drop(cap); + void *p = mmap(nullptr, c.size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) { + LOG("could not map capture buffer %u: %s", c.index, strerror(errno)); + close(fd); + return; + } + cap = {fd, (uint8_t *)p, c.size}; + } + + bool decode(const vdec_packet &p, bool *frame) { + *frame = false; + if (!codec_ || p.capture >= VENC_MAX_BUFFERS || !captures_[p.capture].data || p.input >= config_.bitstreams || + p.bytes == 0 || p.bytes > config_.bitstream_size) + return false; + auto start = std::chrono::steady_clock::now(); + ssize_t in = AMediaCodec_dequeueInputBuffer(codec_, 20000); + if (in < 0) return false; + size_t capacity = 0; + uint8_t *dst = AMediaCodec_getInputBuffer(codec_, (size_t)in, &capacity); + if (!dst || capacity < p.bytes) { + AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, 0, 0, 0); + return false; + } + memcpy(dst, bitstream_ + (size_t)p.input * config_.bitstream_size, p.bytes); + if (AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, p.bytes, (uint64_t)std::max(p.pts_us, 0), 0) != + AMEDIA_OK) + return false; + auto wait = std::chrono::milliseconds(shown_ ? 25 : 250); + while (std::chrono::steady_clock::now() - start < wait) { + AMediaCodecBufferInfo info; + ssize_t o = AMediaCodec_dequeueOutputBuffer(codec_, &info, 2000); + if (o == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { + read_format(); + continue; + } + if (o < 0) continue; + size_t size = 0; + uint8_t *data = AMediaCodec_getOutputBuffer(codec_, (size_t)o, &size); + if (data && info.size > 0 && (size_t)info.offset + (size_t)info.size <= size) + *frame = copy(data + info.offset, (size_t)info.size, captures_[p.capture]) || *frame; + AMediaCodec_releaseOutputBuffer(codec_, (size_t)o, false); + if (info.presentationTimeUs >= p.pts_us) break; + } + shown_ = shown_ || *frame; + return true; + } + +private: + struct Capture { + int fd = -1; + uint8_t *data = nullptr; + size_t size = 0; + }; + + static void drop(Capture &c) { + if (c.data) munmap(c.data, c.size); + if (c.fd >= 0) close(c.fd); + c = Capture(); + } + + AMediaCodec *create(const vdec_config &c, bool low_latency) { + const char *mime = c.codec == VENC_HEVC ? "video/hevc" : "video/avc"; + AMediaCodec *codec = AMediaCodec_createDecoderByType(mime); + if (!codec) return nullptr; + AMediaFormat *f = AMediaFormat_new(); + AMediaFormat_setString(f, AMEDIAFORMAT_KEY_MIME, mime); + AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_WIDTH, (int32_t)c.width); + AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_HEIGHT, (int32_t)c.height); + AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatYuv420SemiPlanar); + AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, (int32_t)c.bitstream_size); + if (low_latency) { + AMediaFormat_setInt32(f, "low-latency", 1); + AMediaFormat_setInt32(f, "vendor.qti-ext-dec-low-latency.enable", 1); + AMediaFormat_setInt32(f, "vendor.qti-ext-dec-picture-order.enable", 1); + AMediaFormat_setInt32(f, "priority", 0); + AMediaFormat_setFloat(f, "operating-rate", 120.0f); + } + media_status_t s = AMediaCodec_configure(codec, f, nullptr, nullptr, 0); + AMediaFormat_delete(f); + if (s == AMEDIA_OK) s = AMediaCodec_start(codec); + if (s != AMEDIA_OK) { + AMediaCodec_delete(codec); + return nullptr; + } + return codec; + } + + void read_format() { + AMediaFormat *f = AMediaCodec_getOutputFormat(codec_); + if (!f) return; + int32_t v; + if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_WIDTH, &v) && v > 0) src_width_ = v; + if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_HEIGHT, &v) && v > 0) src_height_ = v; + src_stride_ = AMediaFormat_getInt32(f, "stride", &v) && v >= src_width_ ? v : src_width_; + src_rows_ = AMediaFormat_getInt32(f, "slice-height", &v) && v >= src_height_ ? v : src_height_; + src_planar_ = AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, &v) && v == kColorFormatYuv420Planar; + LOG("decoder output %dx%d stride %d rows %d %s", src_width_, src_height_, src_stride_, src_rows_, + src_planar_ ? "planar" : "semi-planar"); + AMediaFormat_delete(f); + } + + bool copy(const uint8_t *src, size_t size, const Capture &cap) { + size_t luma = (size_t)src_stride_ * src_rows_; + size_t chroma = src_planar_ ? 2 * (size_t)(src_stride_ / 2) * (src_rows_ / 2) : (size_t)src_stride_ * (src_rows_ / 2); + if (size < luma + chroma) return false; + uint32_t w = std::min((uint32_t)src_width_, config_.stride); + uint32_t h = std::min((uint32_t)src_height_, config_.rows); + if ((size_t)config_.stride * config_.rows * 3 / 2 > cap.size) return false; + DmaBufSync sync = {kDmaBufSyncStart | kDmaBufSyncWrite}; + ioctl(cap.fd, kDmaBufIoctlSync, &sync); + uint8_t *y = cap.data, *uv = cap.data + (size_t)config_.stride * config_.rows; + for (uint32_t row = 0; row < h; row++) + memcpy(y + (size_t)row * config_.stride, src + (size_t)row * src_stride_, w); + const uint8_t *su = src + luma; + for (uint32_t row = 0; row < h / 2; row++) { + uint8_t *d = uv + (size_t)row * config_.stride; + if (!src_planar_) { + memcpy(d, su + (size_t)row * src_stride_, w & ~1u); + continue; + } + const uint8_t *u = su + (size_t)row * (src_stride_ / 2); + const uint8_t *vv = su + (size_t)(src_stride_ / 2) * (src_rows_ / 2) + (size_t)row * (src_stride_ / 2); + for (uint32_t x = 0; x < w / 2; x++) { + d[2 * x] = u[x]; + d[2 * x + 1] = vv[x]; + } + } + sync.flags = kDmaBufSyncEnd | kDmaBufSyncWrite; + ioctl(cap.fd, kDmaBufIoctlSync, &sync); + return true; + } + + AMediaCodec *codec_ = nullptr; + vdec_config config_ = {}; + const uint8_t *bitstream_ = nullptr; + size_t bitstream_size_ = 0; + Capture captures_[VENC_MAX_BUFFERS]; + int32_t src_width_ = 0, src_height_ = 0, src_stride_ = 0, src_rows_ = 0; + bool src_planar_ = false; + bool shown_ = false; +}; + class Session { public: explicit Session(int fd) : fd_(fd) {} @@ -85,6 +299,24 @@ public: memcpy(&b, buf, sizeof b); set_bitrate(b.bitrate); for (int i = 0; i < nfds; i++) close(fds[i]); + } else if (type == VDEC_CONFIG && n == (ssize_t)sizeof(vdec_config)) { + vdec_config c; + memcpy(&c, buf, sizeof c); + bool ok = nfds == 1 && decoder_.configure(c, fds[0]); + for (int i = 0; i < nfds; i++) close(fds[i]); + decoded(ok ? 0 : -1, false); + } else if (type == VDEC_CAPTURE && n == (ssize_t)sizeof(vdec_capture)) { + vdec_capture c; + memcpy(&c, buf, sizeof c); + if (nfds == 1) decoder_.capture(c, fds[0]); + else for (int i = 0; i < nfds; i++) close(fds[i]); + } else if (type == VDEC_PACKET && n == (ssize_t)sizeof(vdec_packet)) { + vdec_packet p; + memcpy(&p, buf, sizeof p); + bool frame = false; + bool ok = decoder_.decode(p, &frame); + for (int i = 0; i < nfds; i++) close(fds[i]); + decoded(ok ? 0 : -1, frame); } else { LOG("unexpected message %u of %zd bytes; closing", type, n); for (int i = 0; i < nfds; i++) close(fds[i]); @@ -117,7 +349,13 @@ private: send(fd_, &d, sizeof d, MSG_NOSIGNAL); } + void decoded(int32_t status, bool frame) { + vdec_result r = {VDEC_RESULT, status, frame ? 1u : 0u}; + send(fd_, &r, sizeof r, MSG_NOSIGNAL); + } + void release() { + decoder_.release(); if (codec_) { AMediaCodec_stop(codec_); AMediaCodec_delete(codec_); @@ -292,6 +530,7 @@ private: int32_t dst_stride_ = 0, dst_rows_ = 0; std::vector inputs_, outputs_; std::vector header_; + Decoder decoder_; }; std::atomic g_listener{-1}; diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c index 6cf0c80373..cb44478354 100644 --- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c +++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c @@ -371,8 +371,8 @@ void ahb_swapchain_set_mode(int on, int live) { : "; gralloc frames still in flight stay on the layer (or take the copy path) until then"); else droiddeck_log("layer", "zero-copy: %s at launch (%s)", on ? "on" : "off", - on ? "DROIDDECK_WAYLAND_ZERO_COPY=1: games present their own gralloc buffers on the display layer" - : "the drawer's Zero-copy presentation switch turns it on live"); + on ? "HDR session: games present their own gralloc buffers on the display layer" + : "only HDR sessions turn it on"); if (live) wl_display_flush_clients(droiddeck_get_display()); droiddeck_request_redraw(); } diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 562a83a750..ff1a33ed2d 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -186,6 +186,9 @@ static void on_client_created(struct wl_listener *l, void *data) { enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP, ROLE_CURSOR }; +#define DAMAGE_RECTS 8 +struct damage_list { int32_t r[DAMAGE_RECTS][4]; int n; }; + struct surface { struct wl_resource *resource; struct wl_list link; @@ -204,9 +207,11 @@ struct surface { struct wl_resource *dmabuf; struct dmabuf_buffer *dmabuf_buf; struct wl_listener dmabuf_destroy; + const void *last_dmabuf; int buf_w, buf_h, has_content; int buf_alpha; int opaque[4], pending_opaque[4], pending_opaque_set; + struct damage_list damage_buf, pending_damage_buf, damage_local, pending_damage_local; int src_set, dst_set; float src[4]; int dst[2]; @@ -257,6 +262,21 @@ static struct wl_event_source *g_render_idle, *g_frame_timer; static int g_dirty; +static int64_t g_dirty_since_ns; +#define PACE_BUFFERS 32 +static struct { + unsigned ticks, ticks_late_2ms, renders, null_attaches, reattaches, presented, replaced, undrawn, distinct; + int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns; + const void *buffers[PACE_BUFFERS]; + uint64_t game_frames_seen; +} g_pace; + +static void pace_note_buffer(const void *buffer) { + for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++) + if (g_pace.buffers[i] == buffer) return; + if (g_pace.distinct < PACE_BUFFERS) g_pace.buffers[g_pace.distinct] = buffer; + g_pace.distinct++; +} static int64_t g_last_vsync_ns; static int64_t g_tick_vsync_ns; static int64_t g_refresh_ns = 16666667; @@ -264,6 +284,8 @@ static struct wl_event_source *g_fallback_timer; static int g_fallback_armed; volatile int g_fps_limit; +/* fps limit -1 (phone output, not mirrored): replaced buffers go back to the client at once instead of once per refresh. */ +volatile int g_release_unpaced; volatile int g_hide_shell; @@ -371,7 +393,7 @@ static int on_release_timer(int fd, uint32_t mask, void *data) { static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) { const int limit = g_fps_limit; const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns; - if (interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; } + if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; } int64_t now = now_ns(); int64_t at = s->next_release_ns + interval; int64_t latest = now + interval * (int64_t)(s->releases_pending + 1); @@ -622,6 +644,68 @@ static void fire_frames(struct wl_list *frames) { } } +static void scene_size(int *w, int *h); +static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h); +static struct surface *g_hud_surface, *g_hud_shm; +static int64_t g_hud_shm_ns; +static int64_t g_hud_last_ns, g_hud_alive_ns; +static int g_hud_fresh; +static int g_hud_new; +#define HUD_TIMES 256 +static pthread_mutex_t g_hud_times_lock = PTHREAD_MUTEX_INITIALIZER; +static float g_hud_times[HUD_TIMES]; +static int64_t g_hud_times_total, g_hud_shown_ns; + +static void hud_frame_shown(int64_t t) { + const int64_t previous = g_hud_shown_ns; + g_hud_shown_ns = t; + if (!previous || t <= previous) return; + pthread_mutex_lock(&g_hud_times_lock); + g_hud_times[g_hud_times_total % HUD_TIMES] = (float)((t - previous) / 1e6); + g_hud_times_total++; + pthread_mutex_unlock(&g_hud_times_lock); +} + +static int tree_rank(const struct surface *s, const struct surface *want, int *rank, int depth) { + const struct surface *c; + if (depth > 8) return 0; + wl_list_for_each(c, &s->children, child_link) + if (c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1; + if (s == want) return 1; + (*rank)++; + wl_list_for_each(c, &s->children, child_link) + if (!c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1; + return 0; +} + +static int render_rank(const struct surface *want) { + const struct surface *s; + int rank = 0; + if (g_desktop && tree_rank(g_desktop, want, &rank, 0)) return rank; + wl_list_for_each(s, &g_toplevels, toplevel_link) + if (tree_rank(s, want, &rank, 0)) return rank; + return -1; +} + +static int below_surface(const struct surface *s, const struct surface *other) { + const int a = render_rank(s), b = render_rank(other); + return a >= 0 && b >= 0 && a < b; +} + +int droiddeck_hud_frame_times(float *out, int len, int64_t *total) { + pthread_mutex_lock(&g_hud_times_lock); + *total = g_hud_times_total; + int64_t n = *total < len ? *total : len; + if (n > HUD_TIMES) n = HUD_TIMES; + for (int64_t i = 0; i < n; i++) out[i] = g_hud_times[(*total - n + i) % HUD_TIMES]; + pthread_mutex_unlock(&g_hud_times_lock); + return (int)n; +} +static uint64_t g_game_frames; +extern void droiddeck_on_game_surface(const char *window, const char *gpu); +extern void droiddeck_on_game_frame(void); +extern void droiddeck_on_game_program(int pid, const char *program); + static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) { int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm); int32_t stride = wl_shm_buffer_get_stride(shm); @@ -644,6 +728,33 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res g_stat_shm++; struct client_info *ci = client_info_of(wl_resource_get_client(s->resource)); if (ci && ci->asked_feedback) ci->shm_frames++; + int local_w, local_h; + surface_size(s, &local_w, &local_h); + const double region = s->src_set ? (double)s->src[2] * s->src[3] : (double)w * h; + const int64_t local_max = damage_area(&s->damage_local, local_w, local_h); + const int64_t local = local_w > 0 && local_h > 0 + ? (int64_t)((double)local_max * region / ((double)local_w * local_h)) : local_max; + const int64_t buffer_max = damage_area(&s->damage_buf, w, h); + const int64_t area = (int64_t)w * h; + int64_t damaged = buffer_max > local ? buffer_max : local; + if (damaged > area) damaged = area; + const int64_t now = now_ns(); + if (damaged * 16 >= area && (!g_hud_surface || now - g_hud_last_ns > 1000000000LL) && + (s == g_hud_shm || !g_hud_shm || now - g_hud_shm_ns > 1000000000LL)) { + const struct surface *top = s; + int scene_w, scene_h, top_w, top_h, depth = 0; + while (top->parent && depth++ < 8) top = top->parent; + scene_size(&scene_w, &scene_h); + surface_size(top, &top_w, &top_h); + int64_t shown = (int64_t)local_w * local_h; + if ((int64_t)top_w * top_h > shown) shown = (int64_t)top_w * top_h; + if (top->role == ROLE_TOPLEVEL && top->mapped && shown * 2 >= (int64_t)scene_w * scene_h) { + g_hud_shm = s; + g_hud_shm_ns = now; + g_hud_new = 1; + droiddeck_on_game_frame(); + } + } } static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) { @@ -660,17 +771,12 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou s->has_content = s->shm_img != NULL; } -static struct surface *g_hud_surface; -static int64_t g_hud_last_ns, g_hud_alive_ns; -static int g_hud_fresh; -static uint64_t g_game_frames; -extern void droiddeck_on_game_surface(const char *window, const char *gpu); -extern void droiddeck_on_game_frame(void); -extern void droiddeck_on_game_program(int pid, const char *program); - static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) { const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b; if (!repeat) { + if (!s->dmabuf && s->last_dmabuf == buffer) g_pace.reattaches++; + s->last_dmabuf = buffer; + pace_note_buffer(buffer); drop_dmabuf(s, 1); s->dmabuf = buffer; s->dmabuf_buf = b; @@ -722,8 +828,9 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re name, b->width, b->height, (unsigned long long)b->modifier); } if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) && - (!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || - (announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) { + (!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) || + (announced_now && !below_surface(g_hud_surface, s) && + (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) { char name[160]; describe(s, name, sizeof(name)); g_hud_surface = s; @@ -747,7 +854,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re } if (s == g_hud_surface) { g_hud_alive_ns = now_ns(); - if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_game_frames++; droiddeck_on_game_frame(); } + if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; droiddeck_on_game_frame(); } } } @@ -784,8 +891,45 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r, wl_resource_add_destroy_listener(buffer, &s->pending_buffer_destroy); } } +static int64_t rect_area(const int32_t *r, int bound_w, int bound_h) { + int64_t x0 = r[0], y0 = r[1], x1 = (int64_t)r[0] + r[2], y1 = (int64_t)r[1] + r[3]; + if (bound_w > 0 && bound_h > 0) { + if (x0 < 0) x0 = 0; + if (y0 < 0) y0 = 0; + if (x1 > bound_w) x1 = bound_w; + if (y1 > bound_h) y1 = bound_h; + } + if (x1 <= x0 || y1 <= y0) return 0; + const int64_t w = x1 - x0, h = y1 - y0; + return (w < 65536 ? w : 65536) * (h < 65536 ? h : 65536); +} +static void note_damage(struct damage_list *d, int32_t x, int32_t y, int32_t w, int32_t h) { + if (w <= 0 || h <= 0) return; + const int32_t rect[4] = { x, y, w, h }; + int slot = d->n; + if (slot == DAMAGE_RECTS) { + slot = 0; + for (int i = 1; i < DAMAGE_RECTS; i++) + if (rect_area(d->r[i], 0, 0) < rect_area(d->r[slot], 0, 0)) slot = i; + if (rect_area(rect, 0, 0) <= rect_area(d->r[slot], 0, 0)) return; + } else { + d->n++; + } + memcpy(d->r[slot], rect, sizeof(rect)); +} +static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h) { + int64_t max = 0; + for (int i = 0; i < d->n; i++) { + const int64_t area = rect_area(d->r[i], bound_w, bound_h); + if (area > max) max = area; + } + return max; +} static void surface_damage(struct wl_client *c, struct wl_resource *r, - int32_t x, int32_t y, int32_t w, int32_t h) {} + int32_t x, int32_t y, int32_t w, int32_t h) { + struct surface *s = wl_resource_get_user_data(r); + note_damage(&s->pending_damage_local, x, y, w, h); +} static void frame_callback_destroy(struct wl_resource *r) { wl_list_remove(wl_resource_get_link(r)); } @@ -794,12 +938,15 @@ static void feedback_resource_destroy(struct wl_resource *r) { wl_list_remove(wl_resource_get_link(r)); } -static void feedback_discard_all(struct wl_list *list) { +static unsigned feedback_discard_all(struct wl_list *list) { struct wl_resource *fb, *tmp; + unsigned n = 0; wl_resource_for_each_safe(fb, tmp, list) { wp_presentation_feedback_send_discarded(fb); wl_resource_destroy(fb); + n++; } + return n; } static uint32_t nominal_refresh_ns(void) { @@ -828,6 +975,7 @@ static void feedback_present_all(struct wl_list *list, int64_t t) { nominal_refresh_ns(), 0, 0, WP_PRESENTATION_FEEDBACK_KIND_VSYNC); wl_resource_destroy(fb); + g_pace.presented++; } } @@ -985,13 +1133,18 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { s->pending_opaque_set = 0; } + s->damage_buf = s->pending_damage_buf; + s->damage_local = s->pending_damage_local; + s->pending_damage_buf.n = s->pending_damage_local.n = 0; if (s->pending_attach) { struct wl_resource *buffer = s->pending_buffer; struct dmabuf_buffer *db = get_dmabuf(buffer); struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL; uint8_t pixel[4]; - feedback_discard_all(&s->feedback); + g_pace.replaced += feedback_discard_all(&s->feedback); + if (!buffer) g_pace.null_attaches++; + else if (!db) s->last_dmabuf = NULL; if (buffer) { wl_list_remove(&s->pending_buffer_destroy.link); @@ -1049,7 +1202,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {} static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {} static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r, - int32_t x, int32_t y, int32_t w, int32_t h) {} + int32_t x, int32_t y, int32_t w, int32_t h) { + struct surface *s = wl_resource_get_user_data(r); + note_damage(&s->pending_damage_buf, x, y, w, h); +} static void surface_offset(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y) {} static const struct wl_surface_interface surface_impl = { @@ -1092,6 +1248,7 @@ static void surface_resource_destroy(struct wl_resource *r) { droiddeck_text_input_surface_gone(r); if (g_desktop == s) { g_desktop = NULL; droiddeck_log("desktop", "the desktop closed"); } if (g_hud_surface == s) { g_hud_surface = NULL; droiddeck_on_game_surface(NULL, NULL); } + if (g_hud_shm == s) g_hud_shm = NULL; constraints_surface_gone(s); unmap_toplevel(s); @@ -1960,13 +2117,20 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) { unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); } static void render_scene(void) { - if (atomic_load(&g_stream_on)) { render_stream(); return; } + if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; } struct draw_list dl = {0}; struct surface *s; int w, h; const int64_t t_scene = now_ns(); int copy = 0; + if (g_dirty_since_ns) { + const int64_t wait = t_scene - g_dirty_since_ns; + g_pace.wait_ns += wait; + if (wait > g_pace.wait_max_ns) g_pace.wait_max_ns = wait; + g_pace.renders++; + g_dirty_since_ns = 0; + } g_dirty = 0; g_hud_fresh = 0; g_hdr_unimported = NULL; @@ -2101,9 +2265,13 @@ static void render_scene(void) { if (rendered) { int64_t t = presented_ns(t_scene); g_stat_frames++; + if (g_hud_new) { + g_hud_new = 0; + hud_frame_shown(t); + } wl_list_for_each(s, &g_surfaces, link) { if (s->drawn) feedback_present_all(&s->feedback, t); - else feedback_discard_all(&s->feedback); + else g_pace.undrawn += feedback_discard_all(&s->feedback); } fire_all_frames(); } else { @@ -2129,6 +2297,7 @@ static int on_fallback_timer(void *data) { } static void schedule_render(void) { + if (!g_dirty && !g_dirty_since_ns) g_dirty_since_ns = now_ns(); g_dirty = 1; if (!g_display) return; if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) return; @@ -2148,6 +2317,13 @@ static int scene_waits_for_game(int64_t now) { static void on_vsync(int64_t frame_time_ns) { int64_t now = now_ns(); g_perf.ticks++; + if (frame_time_ns > 0 && now >= frame_time_ns) { + const int64_t late = now - frame_time_ns; + g_pace.ticks++; + g_pace.tick_late_ns += late; + if (late > g_pace.tick_late_max_ns) g_pace.tick_late_max_ns = late; + if (late > 2000000LL) g_pace.ticks_late_2ms++; + } if (g_last_vsync_ns) { int64_t d = now - g_last_vsync_ns; if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8; @@ -3260,6 +3436,24 @@ static int on_stats_timer(void *data) { #undef PERF_MS memset(&g_perf, 0, sizeof(g_perf)); } + const uint64_t game = g_game_frames - g_pace.game_frames_seen; + if (g_pace.ticks || g_pace.renders || game || g_pace.reattaches || g_pace.null_attaches || g_pace.distinct || + g_pace.presented || g_pace.replaced || g_pace.undrawn) { + droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | " + "new frame waits %.2f/%.2f ms to be drawn (%u scenes) | %llu game frames, %u re-attached after an " + "empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, " + "%u not drawn", + g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6, + g_pace.ticks, g_pace.ticks_late_2ms, + g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6, + g_pace.renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct, + g_pace.presented, g_pace.replaced, g_pace.undrawn); + } + { + const uint64_t seen = g_game_frames; + memset(&g_pace, 0, sizeof(g_pace)); + g_pace.game_frames_seen = seen; + } g_stat_frames = g_stat_dmabuf = g_stat_shm = 0; droiddeck_color_stats_tick(); diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 16e42d1b5d..675d4ac2ce 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -25,6 +25,7 @@ extern void droiddeck_wayland_send_pointer(int action, int x, int y); extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y); extern int droiddeck_cursor_snapshot(int *out, int cap); extern int droiddeck_cursor_serial(void); +extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total); extern void droiddeck_wayland_send_key(int evdev, int state); extern void droiddeck_wayland_send_scene_input(int type, int a, int b); extern void droiddeck_wayland_vsync(int64_t frame_time_ns); @@ -34,6 +35,7 @@ extern unsigned droiddeck_stream_frames(void); extern void droiddeck_wayland_output_resized(void); extern void droiddeck_wayland_set_output_refresh_rate(int mhz); extern volatile int g_fps_limit; +extern volatile int g_release_unpaced; extern volatile int g_hide_shell; extern volatile int g_zero_copy; extern volatile unsigned g_zero_copy_last; @@ -267,6 +269,20 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot( return n; } +JNIEXPORT jlong JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHudFrameTimes(JNIEnv *env, jclass clazz, jfloatArray out) { + (void)clazz; + if (!out) return 0; + jint cap = (*env)->GetArrayLength(env, out); + float *buf = cap > 0 ? malloc(sizeof(float) * (size_t)cap) : NULL; + if (!buf) return 0; + int64_t total = 0; + int n = droiddeck_hud_frame_times(buf, cap, &total); + if (n > 0) (*env)->SetFloatArrayRegion(env, out, 0, n, buf); + free(buf); + return (jlong)total; +} + JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) { (void)env; (void)clazz; @@ -574,6 +590,7 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv * JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) { g_fps_limit = fps > 0 ? fps : 0; + g_release_unpaced = fps < 0; __android_log_print(ANDROID_LOG_INFO, TAG, "fps limit %d", fps); } diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 928d7caa8c..324941bd43 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -53,6 +53,7 @@ class App : Application() { com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend) + com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend) } /** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */ diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 3092aa187b..5a202591f5 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -52,6 +52,7 @@ import com.droiddeck.launcher.core.PhantomProcessLimit import com.droiddeck.launcher.core.PhantomProcessStatus import com.droiddeck.launcher.core.WirelessAdbFix import com.droiddeck.launcher.core.WifiDiscovery +import com.droiddeck.launcher.core.SteamIntegration import com.droiddeck.launcher.core.WirelessAdbPairingService import com.droiddeck.launcher.ui.CoreRow import com.droiddeck.launcher.ui.PerformancePage @@ -91,12 +92,17 @@ class FrontEndActivity : ComponentActivity() { private val components = ComponentsMenu(this, ui) private val decky = DeckyMenu(this, ui) private val updates = UpdatesMenu(this, ui) - private val protons = ProtonMenu(this, ui) { !busy && flood == null && pkgStage == null && components.compBusy == null } + private val protons = ProtonMenu(this, ui) { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null } private var installed by mutableStateOf(null) private var flood by mutableStateOf(null) private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f) private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent) + private class CompatLaunch(val intent: Intent, val loading: com.droiddeck.launcher.session.LoadingState, var menuInstall: Boolean) + private var compatLaunch by mutableStateOf(null) + private var compatFlood by mutableStateOf(null) + private var compatLaunchPoll: Runnable? = null + private var compatLaunchVisible = false private var returning by mutableStateOf(null) private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?) private var ready by mutableStateOf(false) @@ -134,11 +140,17 @@ class FrontEndActivity : ComponentActivity() { private var catalog by mutableStateOf?>(null) private var catalogLoading by mutableStateOf(false) private var packageRows by mutableStateOf?>(null) - private var pkgId by mutableStateOf(null) - private var pkgStage by mutableStateOf(null) - private var pkgPercent by mutableIntStateOf(-1) + private object PackageOperation { + val id = mutableStateOf(null) + val stage = mutableStateOf(null) + val percent = mutableIntStateOf(-1) + } + private var pkgId by PackageOperation.id + private var pkgStage by PackageOperation.stage + private var pkgPercent by PackageOperation.percent private var desktopInstalled by mutableStateOf(false) private var desktopPresent by mutableStateOf(false) + private var battleNetInstalled by mutableStateOf(false) private var offlineAccount by mutableStateOf(null) private var offline by mutableStateOf(false) private var showPerformance by mutableStateOf(false) @@ -152,6 +164,9 @@ class FrontEndActivity : ComponentActivity() { private var syncFallback by mutableStateOf(true) private var fsyncFirst by mutableStateOf(false) private var gamescopeRealtime by mutableStateOf(false) + private var ramCapMb by mutableStateOf(0) + private var zramClient by mutableStateOf(true) + private var vramCapMb by mutableStateOf(0) private var gpuClockPin by mutableStateOf(false) private var prootNoSeccomp by mutableStateOf(false) private var prootFastPath by mutableStateOf(true) @@ -164,10 +179,12 @@ class FrontEndActivity : ComponentActivity() { private var picturePosition by mutableStateOf("center") private var stretch16x9 by mutableStateOf(false) private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) + private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) private var launcherFullscreen by mutableStateOf(true) private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO) private var downloadMirror by mutableStateOf("") private var downloadPrefix by mutableStateOf("") + private var downloadProxy by mutableStateOf("") private var animationsEnabled by mutableStateOf(true) private var launcherIcon by mutableStateOf(LauncherIcon.DARK) private var gameStoresEnabled by mutableStateOf(true) @@ -182,6 +199,8 @@ class FrontEndActivity : ComponentActivity() { private var wifiDiscoveryLocation by mutableStateOf(false) private var wifiDiscoveryAsked by mutableStateOf(false) private var wifiDiscoveryBlocked by mutableStateOf(false) + private var integrationState by mutableStateOf(SteamIntegration.State()) + private var integrationFocus by mutableStateOf(null) private val wifiLocationReceiver = object : android.content.BroadcastReceiver() { override fun onReceive(context: android.content.Context?, intent: Intent?) { refreshWifiDiscovery() @@ -250,8 +269,65 @@ class FrontEndActivity : ComponentActivity() { SessionPrefs.setWifiDiscoveryEnabled(this, false) } wifiDiscovery = SessionPrefs.wifiDiscoveryEnabled(this) + integrationState = readIntegration() } + private var shortcutsTried = false + + private fun readIntegration() = SteamIntegration.read(this) + .copy(locationBlocked = wifiDiscoveryBlocked, shortcutsTried = shortcutsTried) + + private fun openIntegration(feature: SteamIntegration.Feature? = null) { + SteamIntegration.dismissSuggestion(this) + refreshWifiDiscovery() + integrationState = readIntegration() + integrationFocus = feature + navRequest = "setup:integration" + } + + private fun readIntegrationIntent(incoming: Intent) { + if (incoming.action != SteamIntegration.ACTION_SETUP) return + openIntegration(incoming.getStringExtra(SteamIntegration.EXTRA_FEATURE)?.let { + runCatching { SteamIntegration.Feature.valueOf(it) }.getOrNull() + }) + } + + private fun integrationSettings(intent: Intent, fallback: String = android.provider.Settings.ACTION_SETTINGS) { + try { startActivity(intent) } + catch (_: android.content.ActivityNotFoundException) { startActivity(Intent(fallback)) } + catch (_: SecurityException) { startActivity(Intent(fallback)) } + } + + private fun configureIntegration(feature: SteamIntegration.Feature) { + when (feature) { + SteamIntegration.Feature.WIFI -> { + if (wifiDiscovery && wifiDiscoveryPermission) { + SessionPrefs.setWifiDiscoveryEnabled(this, false) + } else if (wifiDiscoveryPermission) { + SessionPrefs.setWifiDiscoveryEnabled(this, true) + } else { + SessionPrefs.setWifiDiscoveryAsked(this) + wifiLocationPermission.launch(WifiDiscovery.permissions) + } + refreshWifiDiscovery() + } + SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this)) + SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else { + HomeApp.setHomeScreenEnabled(this, true) + refreshHomeAppState() + manageHomeApp() + } + SteamIntegration.Feature.SHORTCUTS -> { + if (!integrationState.shortcuts) shortcutsTried = true + if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME) + else integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS) + } + } + } + + private fun openAppInfo() = + integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))) + private fun openWifiDiscoverySettings() { if (!WifiDiscovery.permissionGranted(this)) { wifiPermissionSettings.launch(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, @@ -386,7 +462,6 @@ class FrontEndActivity : ComponentActivity() { private var theme by mutableStateOf("graphite") private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) private var hdrOn by mutableStateOf(false) - private var fpsLimit by mutableStateOf(0) private var upscaler by mutableStateOf(0) private var upscaleSharpness by mutableStateOf(75) private var hdrReason by mutableStateOf(null) @@ -411,11 +486,30 @@ class FrontEndActivity : ComponentActivity() { private var logsEnabled by mutableStateOf(true) private var vacDiagnostics by mutableStateOf(false) private var agentCommands by mutableStateOf(false) + private var clearCachedApps by mutableStateOf(false) + private var adbPaired by mutableStateOf(false) + private var memoryHud by mutableStateOf(SessionPrefs.MEMORY_HUD_OFF) + private var backgroundAppLimit by mutableStateOf(com.droiddeck.launcher.core.BackgroundAppLimit.OFF) private var showRoms by mutableStateOf(false) private var homeAppSelected by mutableStateOf(false) private var homeScreenEnabled by mutableStateOf(false) private var defaultHomeLabel by mutableStateOf(null) private var androidApps by mutableStateOf>(emptyList()) + private var androidAppsListing = 0 + private val packageCallback = object : android.content.pm.LauncherApps.Callback() { + private fun changed() { + refreshAndroidApps() + if (HomeWidgets.providers != null) HomeWidgets.refreshProviders(this@FrontEndActivity) + } + override fun onPackageRemoved(packageName: String, user: android.os.UserHandle) = changed() + override fun onPackageAdded(packageName: String, user: android.os.UserHandle) = changed() + override fun onPackageChanged(packageName: String, user: android.os.UserHandle) = changed() + override fun onPackagesAvailable(packageNames: Array, user: android.os.UserHandle, replacing: Boolean) = changed() + override fun onPackagesUnavailable(packageNames: Array, user: android.os.UserHandle, replacing: Boolean) = changed() + override fun onShortcutsChanged(packageName: String, shortcuts: MutableList, user: android.os.UserHandle) { + if (homeAppSelected) HomePins.refresh(this@FrontEndActivity) + } + } private var secondScreenDisplays by mutableStateOf>(emptyList()) private lateinit var displayManager: DisplayManager private val secondScreenDisplayListener = object : DisplayManager.DisplayListener { @@ -429,7 +523,9 @@ class FrontEndActivity : ComponentActivity() { } override fun startActivity(intent: Intent?) { + val compat = protons.protonBusyId != null || ProtonExtras.installInProgress if (intent?.component?.className == SessionActivity::class.java.name) { + if (compatLaunch != null) return when { busy || LinuxRuntimeInstaller.isBusy() -> { android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show() @@ -439,10 +535,7 @@ class FrontEndActivity : ComponentActivity() { android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() return } - protons.protonBusyId != null || ProtonExtras.installInProgress -> { - android.widget.Toast.makeText(this, R.string.main_wait_proton_install, android.widget.Toast.LENGTH_SHORT).show() - return - } + compat -> Unit pkgStage != null -> { android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() return @@ -457,17 +550,26 @@ class FrontEndActivity : ComponentActivity() { return } com.droiddeck.launcher.ui.LaunchOrigin.flooding = null + if (compat) { + waitForCompat(intent) + return + } } super.startActivity(intent) if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold) } private fun launchFlooded(f: PendingFlood) { - if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null || - ProtonExtras.installInProgress || pkgStage != null) { + if (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || + protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) { flood = null floodProgress = 0f com.droiddeck.launcher.ui.LaunchOrigin.flooding = null + if (!busy && !LinuxRuntimeInstaller.isBusy() && !(SessionState.installing != null && !SessionState.running) && + (protons.protonBusyId != null || ProtonExtras.installInProgress)) { + compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal + waitForCompat(f.intent) + } return } val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal @@ -475,6 +577,72 @@ class FrontEndActivity : ComponentActivity() { overridePendingTransition(0, 0) } + private fun waitForCompat(next: Intent, menuInstall: Boolean = protons.protonBusyId != null) { + if (compatLaunch != null) return + com.droiddeck.launcher.ui.LaunchOrigin.take() + com.droiddeck.launcher.ui.LaunchOrigin.flooding = null + val waiting = CompatLaunch(Intent(next), com.droiddeck.launcher.session.LoadingState(this), menuInstall) + compatLaunch = waiting + val poll = object : Runnable { + override fun run() { + if (isDestroyed || isFinishing || compatLaunch !== waiting) return + if (protons.protonBusyId != null || ProtonExtras.installInProgress) { + waiting.menuInstall = waiting.menuInstall || protons.protonBusyId != null + val percent = if (protons.protonBusyId != null) protons.protonPercent else -1 + val stage = protons.protonStage ?: getString(R.string.load_compat_wait) + waiting.loading.say(if (percent >= 0) getString(R.string.load_compat_progress, stage, percent) else stage, + com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true) + waiting.loading.percent = percent + waiting.loading.tick() + ui.postDelayed(this, 250) + return + } + if (!compatLaunchVisible) { ui.postDelayed(this, 250); return } + val problem = protons.protonProblem.takeIf { waiting.menuInstall } + if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || pkgStage != null)) { + waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime), + com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true) + waiting.loading.percent = if (pkgStage != null) pkgPercent else percent + waiting.loading.tick() + ui.postDelayed(this, 250) + return + } + compatLaunchPoll = null + if (problem != null) waiting.loading.showEnded(problem) + else { + compatLaunch = null + startActivity(waiting.intent) + } + } + } + compatLaunchPoll = poll + poll.run() + } + + private fun cancelCompatLaunch() { + compatLaunchPoll?.let(ui::removeCallbacks) + compatLaunchPoll = null + compatLaunch = null + compatFlood = null + } + + private fun restoreCompatLaunch(state: Bundle) { + savedIntent(state, KEY_COMPAT_LAUNCH)?.let { next -> + val problem = state.getString(KEY_COMPAT_PROBLEM) + if (problem == null) waitForCompat(next, state.getBoolean(KEY_COMPAT_MENU_INSTALL)) + else compatLaunch = CompatLaunch(next, + com.droiddeck.launcher.session.LoadingState(this).apply { showEnded(problem) }, false) + } + } + + private fun saveCompatLaunch(state: Bundle) { + compatLaunch?.let { + state.putParcelable(KEY_COMPAT_LAUNCH, it.intent) + state.putBoolean(KEY_COMPAT_MENU_INSTALL, it.menuInstall) + if (it.loading.ended) state.putString(KEY_COMPAT_PROBLEM, it.loading.step) + } + } + private var shortcutPicker by mutableStateOf(false) private var shortcutLibraryScanning by mutableStateOf(false) @Volatile private var libraryScanGeneration = 0 @@ -536,7 +704,7 @@ class FrontEndActivity : ComponentActivity() { } private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean { - if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) { + if (pkgStage != null) { android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() return false } @@ -592,9 +760,11 @@ class FrontEndActivity : ComponentActivity() { .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN) .putExtra(SessionService.EXTRA_PROGRAM, command.program) .putExtra(SessionService.EXTRA_PROGRAM_ARGS, command.args.toTypedArray()) + .putExtra(SessionService.EXTRA_GAME_ID, com.droiddeck.launcher.session.NoSteamLaunch.scope(game)) when { !SessionState.running -> startSessionOrWait(next) SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show() + command.program == com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET && handToBattleNet(command.args, returnHome) { pendingSwitch = next } -> {} SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args -> startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME) .returnTo(returnHome) @@ -646,7 +816,7 @@ class FrontEndActivity : ComponentActivity() { android.widget.Toast.makeText(this, R.string.epic_client_uninstalling, android.widget.Toast.LENGTH_SHORT).show() return false } - if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) { + if (pkgStage != null) { android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() return false } @@ -692,7 +862,8 @@ class FrontEndActivity : ComponentActivity() { } private fun startSessionOrWait(next: Intent): Boolean { - val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL)) + val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL) || + next.getStringExtra(SessionService.EXTRA_PROGRAM) in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET)) if (!started && (busy || LinuxRuntimeInstaller.isBusy())) android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() return started } @@ -753,10 +924,12 @@ class FrontEndActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + if (savedInstanceState == null) readIntegrationIntent(intent) readGameIntent(intent) gameSyncFolder = GameFileSync.folder(this) displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager refreshPhantomStatus() + if (!SessionState.running) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this) theme = SessionPrefs.theme(this) frameGenLabel = getString(R.string.frame_gen_off) appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this) @@ -765,11 +938,13 @@ class FrontEndActivity : ComponentActivity() { steamGamesX64 = cachedX64 backActionsInverted = SessionPrefs.backActionsInverted(this) orientation = SessionPrefs.orientation(this) - requestedOrientation = orientation + launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this) + requestedOrientation = launcherOrientation launcherFullscreen = SessionPrefs.launcherFullscreen(this) downloadSource = DownloadSource.mode(this) downloadMirror = DownloadSource.mirror(this) downloadPrefix = DownloadSource.custom(this) + downloadProxy = DownloadSource.proxyHostPort(this) DownloadSource.probe() animationsEnabled = SessionPrefs.animationsEnabled(this) LauncherIcon.repair(this, intent?.component) @@ -805,6 +980,7 @@ class FrontEndActivity : ComponentActivity() { offlineAccount = offlineAccount, offline = offline, frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, vacDiagnostics = vacDiagnostics, agentCommands = agentCommands, + clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit, steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel, frameGen = FrameGen.mode(this), lossless = lossless, @@ -815,6 +991,8 @@ class FrontEndActivity : ComponentActivity() { isHomeApp = homeAppSelected, homeScreenEnabled = homeScreenEnabled, defaultHomeLabel = defaultHomeLabel, + integration = integrationState, + integrationFocus = integrationFocus, androidApps = androidApps, secondScreenDisplays = secondScreenDisplays, packages = packageRows, @@ -823,6 +1001,7 @@ class FrontEndActivity : ComponentActivity() { packageStage = pkgStage, packagePercent = pkgPercent, sessionRunning = SessionState.running, + battleNetInstalled = battleNetInstalled, backActionsInverted = backActionsInverted, buildLabel = BuildConfig.BUILD_LABEL, oscMode = oscMode, @@ -831,10 +1010,12 @@ class FrontEndActivity : ComponentActivity() { phantomProcessStatus = phantomProcessStatus, showPhantomGate = showPhantomGate, orientation = orientation, + launcherOrientation = launcherOrientation, launcherFullscreen = launcherFullscreen, downloadSource = downloadSource, downloadMirror = downloadMirror, downloadPrefix = downloadPrefix, + downloadProxy = downloadProxy, animationsEnabled = animationsEnabled, launcherIcon = launcherIcon, gameStoresEnabled = gameStoresEnabled, @@ -910,6 +1091,7 @@ class FrontEndActivity : ComponentActivity() { .putExtra(SessionService.EXTRA_PROGRAM, app.program) .putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray())) }, + onBattleNet = { openBattleNet() }, onFlatpakApp = { id, name -> Library.flatpakNames[id] = name startActivity(Intent(this, SessionActivity::class.java) @@ -964,6 +1146,12 @@ class FrontEndActivity : ComponentActivity() { com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)) agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this) }, + onClearCachedApps = { on -> SessionPrefs.setClearCachedApps(this, on); clearCachedApps = on }, + onMemoryHud = { value -> SessionPrefs.setMemoryHud(this, value); memoryHud = value }, + onBackgroundAppLimit = { limit -> + SessionPrefs.setBackgroundAppLimit(this, limit); backgroundAppLimit = limit + if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this) + }, onShareLogs = { SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip -> if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show() @@ -1005,6 +1193,10 @@ class FrontEndActivity : ComponentActivity() { onOrientation = { value -> SessionPrefs.setOrientation(this, value) orientation = value + }, + onLauncherOrientation = { value -> + com.droiddeck.launcher.core.AppUiPrefs.setOrientation(this, value) + launcherOrientation = value requestedOrientation = value }, onLauncherFullscreen = { on -> @@ -1035,7 +1227,19 @@ class FrontEndActivity : ComponentActivity() { DownloadSource.setCustom(this, prefix) downloadPrefix = DownloadSource.custom(this) }, + onDownloadProxy = { value -> + DownloadSource.setProxy(this, value) + downloadProxy = DownloadSource.proxyHostPort(this) + }, onHomeApp = { manageHomeApp() }, + onSteamIntegration = ::openIntegration, + onIntegration = { integrationFocus = null; configureIntegration(it) }, + onIntegrationAppInfo = ::openAppInfo, + onIntegrationLocation = ::openWifiDiscoverySettings, + onDismissIntegration = { + SteamIntegration.dismissSuggestion(this) + integrationState = readIntegration() + }, onHomeScreen = { on -> HomeApp.setHomeScreenEnabled(this, on) refreshHomeAppState() @@ -1089,7 +1293,12 @@ class FrontEndActivity : ComponentActivity() { android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show() }, onDismissPhantomGate = { showPhantomGate = false }, + onShowPhantomGate = { + refreshPhantomStatus() + showPhantomGate = true + }, onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) }, + onStartPairingGuide = { displayId -> PairingGuideActivity.start(this, displayId) }, onOpenNotificationSettings = { startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS) .putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName) @@ -1185,12 +1394,23 @@ class FrontEndActivity : ComponentActivity() { com.droiddeck.launcher.ui.LaunchOrigin.flooding = null } } + androidx.activity.compose.BackHandler(compatLaunch != null) { cancelCompatLaunch() } + compatLaunch?.loading?.let { loading -> + if (!loading.ended) com.droiddeck.launcher.ui.VeilRing() + com.droiddeck.launcher.ui.LoadingOverlay( + loading.step, loading.percent, loading.elapsed, getString(R.string.load_compat_hint), loading.ended, + loading.topic, loading.readable, title = getString(R.string.load_compat_title), + onCancel = ::cancelCompatLaunch, onClose = ::cancelCompatLaunch, + flood = compatFlood, onFlooded = { compatFlood = null }, + ) + } } } } if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() } else { + restoreCompatLaunch(savedInstanceState) pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH) savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) } } @@ -1219,6 +1439,10 @@ class FrontEndActivity : ComponentActivity() { override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) + if (intent.action == SteamIntegration.ACTION_SETUP) { + readIntegrationIntent(intent) + return + } readGameIntent(intent) refresh() startSteamAtStartupIfEnabled() @@ -1277,6 +1501,14 @@ class FrontEndActivity : ComponentActivity() { } override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (compatLaunch != null) { + if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) { + if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch() + return true + } + if (!compatLaunch!!.loading.ended && event.keyCode !in listOf( + KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true + } if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { @@ -1293,13 +1525,27 @@ class FrontEndActivity : ComponentActivity() { } } + override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean { + if (compatLaunch != null && !compatLaunch!!.loading.ended && + com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true + return super.dispatchGenericMotionEvent(event) + } + + override fun onPause() { + compatLaunchVisible = false + super.onPause() + } + override fun onResume() { super.onResume() + compatLaunchVisible = true orientation = SessionPrefs.orientation(this) - requestedOrientation = orientation + launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this) + requestedOrientation = launcherOrientation 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.ui.Motion.refresh(this) com.droiddeck.launcher.ui.QuitFlood.take()?.let { c -> returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn()) @@ -1341,10 +1587,20 @@ class FrontEndActivity : ComponentActivity() { }) displayManager.registerDisplayListener(secondScreenDisplayListener, ui) refreshSecondScreenDisplays() + getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui) + HomeWidgets.startListening(this) + } + + @Suppress("OVERRIDE_DEPRECATION") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) return + @Suppress("DEPRECATION") + super.onActivityResult(requestCode, resultCode, data) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) + saveCompatLaunch(outState) pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) } switchingTo?.let { outState.putParcelable(KEY_SWITCHING_TO, it) @@ -1357,6 +1613,7 @@ class FrontEndActivity : ComponentActivity() { else @Suppress("DEPRECATION") state.getParcelable(key) override fun onDestroy() { + cancelCompatLaunch() updates.unregister() super.onDestroy() } @@ -1364,8 +1621,11 @@ class FrontEndActivity : ComponentActivity() { override fun onStop() { unregisterReceiver(wifiLocationReceiver) unregisterReceiver(mediaReceiver) + getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback) + HomeWidgets.stopListening(this) ui.removeCallbacks(mediaRefresh) com.droiddeck.launcher.stores.StoresState.libraryListener = null + com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null displayManager.unregisterDisplayListener(secondScreenDisplayListener) flood = null returning = null @@ -1378,7 +1638,22 @@ class FrontEndActivity : ComponentActivity() { homeScreenEnabled = HomeApp.isHomeScreenEnabled(this) homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this) defaultHomeLabel = HomeApp.defaultLabel(this) - androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList() + refreshAndroidApps() + integrationState = readIntegration() + } + + private fun refreshAndroidApps() { + if (!homeAppSelected) { + ++androidAppsListing + androidApps = emptyList() + return + } + val seq = ++androidAppsListing + HomePins.refresh(this) + Thread({ + val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList()) + ui.post { if (seq == androidAppsListing) androidApps = apps } + }, "home-apps").start() } private fun refreshSecondScreenDisplays() { @@ -1559,6 +1834,50 @@ class FrontEndActivity : ComponentActivity() { desktopPresent = DesktopCatalog.desktopPresent(this) } + private fun openBattleNet(args: List = emptyList()) { + if (pkgStage != null) { + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + return + } + val app = applicationContext + Thread({ + val full = if (args.firstOrNull() == "--library") args else com.droiddeck.launcher.stores.battlenet.BattleNetClient.library(app) + args + ui.post { + if (isDestroyed) return@post + val next = Intent(this, SessionActivity::class.java) + .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN) + .putExtra(SessionService.EXTRA_PROGRAM, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET) + .putExtra(SessionService.EXTRA_PROGRAM_ARGS, full.toTypedArray()) + when { + !SessionState.running -> startSessionOrWait(next) + SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show() + handToBattleNet(full) { pendingSwitch = next } -> {} + else -> pendingSwitch = next + } + } + }, "battlenet-open").start() + } + + private fun handToBattleNet(args: List, returnHome: Boolean = false, otherwise: () -> Unit): Boolean { + if (SessionState.mode != SessionService.MODE_RUN || SessionState.program != com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET) return false + val library = args.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1) + val sessionLibrary = SessionState.programArgs.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1) + if (library != null && sessionLibrary != null && library != sessionLibrary) return false + val request = if (library != null) args.drop(2) else args + val app = applicationContext + Thread({ + val handed = request.isEmpty() || com.droiddeck.launcher.stores.battlenet.BattleNetClient.request(LinuxRuntime.sessionRoot(app), request) + ui.post { + if (isDestroyed) return@post + if (!handed) otherwise() + else startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME) + .returnTo(returnHome) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)) + } + }, "battlenet-request").start() + return true + } + private fun launchProgram(path: String) { startActivity(Intent(this, SessionActivity::class.java) .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN) @@ -1624,7 +1943,7 @@ class FrontEndActivity : ComponentActivity() { ModeSettings( mode = mode, resolution = resolution, panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this), - hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit, + hdr = hdrOn, hdrReason = hdrReason, upscaler = upscaler, upscaleSharpness = upscaleSharpness, gpuDrivers = drivers.summary(), touchMode = touchMode, @@ -1632,8 +1951,7 @@ class FrontEndActivity : ComponentActivity() { steamDownloadsInBackground = steamDownloadsInBackground, pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this), pipAutoEnter = pipAutoEnter, - unfoldedControls = if (mode == SessionService.MODE_STEAM && - com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null, + unfoldedControls = if (mode == SessionService.MODE_STEAM) unfoldedControls else null, unfoldedControlsWithController = unfoldedControlsWithController, oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null, backActionsInverted = backActionsInverted, @@ -1659,11 +1977,7 @@ class FrontEndActivity : ComponentActivity() { bootMovieCustomName = bootMovieCustomName, bootMovieImporting = bootMovieImporting, bootMovieProgress = bootMovieProgress, - wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null, - wifiDiscoveryPermission = wifiDiscoveryPermission, - wifiDiscoveryLocation = wifiDiscoveryLocation, - wifiDiscoveryAsked = wifiDiscoveryAsked, - wifiDiscoveryBlocked = wifiDiscoveryBlocked, + integration = if (mode == SessionService.MODE_STEAM) integrationState else null, deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null, deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyLatest else null, deckyBranch = decky.deckyBranch, @@ -1672,25 +1986,12 @@ class FrontEndActivity : ComponentActivity() { deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running, ), ModeSettingsActions( - onWifiDiscovery = { on -> - if (!on) { - SessionPrefs.setWifiDiscoveryEnabled(this, false) - refreshWifiDiscovery() - } else if (WifiDiscovery.permissionGranted(this)) { - SessionPrefs.setWifiDiscoveryEnabled(this, true) - refreshWifiDiscovery() - } else if (wifiDiscoveryBlocked) { - openWifiDiscoverySettings() - } else { - SessionPrefs.setWifiDiscoveryAsked(this) - wifiLocationPermission.launch(WifiDiscovery.permissions) - } - }, - onWifiDiscoverySettings = { openWifiDiscoverySettings() }, + onIntegration = ::configureIntegration, + onIntegrationAppInfo = ::openAppInfo, + onIntegrationLocation = ::openWifiDiscoverySettings, onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value }, onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, - onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps }, onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m }, onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct }, onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t }, @@ -1785,6 +2086,10 @@ class FrontEndActivity : ComponentActivity() { fsyncFirst = fsyncFirst, gamescopeRealtime = gamescopeRealtime, gpuClockPin = gpuClockPin, + ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient, + deviceRamMb = (android.app.ActivityManager.MemoryInfo() + .also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(), + ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(), prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, cursorComposite = cursorComposite, guestHostname = guestHostname, phantomWarning = phantomWarning, onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on }, @@ -1798,6 +2103,9 @@ class FrontEndActivity : ComponentActivity() { onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on }, onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on }, onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on }, + onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb }, + onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on }, + onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb }, onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on }, onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on }, onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on }, @@ -1934,7 +2242,6 @@ class FrontEndActivity : ComponentActivity() { runSteamAtStartup = SessionPrefs.runSteamAtStartup(this) loadBootMovie() hdrOn = SessionPrefs.hdr(this, mode) - fpsLimit = SessionPrefs.fpsLimit(this, mode) upscaler = SessionPrefs.upscaler(this) upscaleSharpness = SessionPrefs.upscaleSharpness(this) hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason @@ -1993,6 +2300,9 @@ class FrontEndActivity : ComponentActivity() { syncFallback = SessionPrefs.syncFallback(this) fsyncFirst = SessionPrefs.fsyncFirst(this) gamescopeRealtime = SessionPrefs.gamescopeRealtime(this) + ramCapMb = SessionPrefs.ramCapMb(this) + zramClient = SessionPrefs.zramClient(this) + vramCapMb = SessionPrefs.vramCapMb(this) gpuClockPin = SessionPrefs.gpuClockPin(this) prootNoSeccomp = SessionPrefs.prootNoSeccomp(this) prootFastPath = SessionPrefs.prootFastPath(this) @@ -2013,6 +2323,7 @@ class FrontEndActivity : ComponentActivity() { addedGamesArt = SessionPrefs.addedGamesArt(this) desktopInstalled = DesktopCatalog.desktopInstalled(this) desktopPresent = DesktopCatalog.desktopPresent(this) + battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(this) offlineAccount = OfflineMode.account(this) offline = OfflineMode.enabled(this) installed = LinuxRuntimeInstaller.installedVersion(this) @@ -2023,6 +2334,10 @@ class FrontEndActivity : ComponentActivity() { logsEnabled = SessionPrefs.logsEnabled(this) vacDiagnostics = SessionPrefs.vacDiagnostics(this) agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this) + clearCachedApps = SessionPrefs.clearCachedApps(this) + adbPaired = WirelessAdbFix.hasSavedPairing(this) + memoryHud = SessionPrefs.memoryHud(this) + backgroundAppLimit = SessionPrefs.backgroundAppLimit(this) runningLabel = if (SessionState.running) when (SessionState.mode) { SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop) SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program) @@ -2032,7 +2347,7 @@ class FrontEndActivity : ComponentActivity() { val scanGeneration = ++libraryScanGeneration val artRefreshesAtStart = HashMap(steamArtRefreshes) if (shortcutPicker) shortcutLibraryScanning = true - if (SessionPrefs.steamClientArch(this) == "x86_64" && !OfflineMode.enabled(this)) { + if (!OfflineMode.enabled(this)) { Thread({ com.droiddeck.launcher.session.FexCatalog.refresh(this) }, "fex-catalog").start() } Thread({ @@ -2124,6 +2439,7 @@ class FrontEndActivity : ComponentActivity() { private fun refreshPhantomStatus() { phantomProcessStatus = PhantomProcessLimit.read(this) + adbPaired = WirelessAdbFix.hasSavedPairing(this) phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { getString( R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus), @@ -2227,6 +2543,9 @@ class FrontEndActivity : ComponentActivity() { private const val SESSION_SWITCH_WAIT_MS = 30_000L private const val SESSION_SWITCH_POLL_MS = 250L private const val KEY_PENDING_SWITCH = "pending_switch" + private const val KEY_COMPAT_LAUNCH = "compat_launch" + private const val KEY_COMPAT_MENU_INSTALL = "compat_menu_install" + private const val KEY_COMPAT_PROBLEM = "compat_problem" private const val KEY_SWITCHING_TO = "switching_to" private const val KEY_SWITCH_DEADLINE = "switch_deadline" private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED) diff --git a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt index 71304e8837..59e10c48e7 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt @@ -13,7 +13,7 @@ class HomeActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this) + requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this) routeHome() } diff --git a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt index 74b49821c5..9d0ae53c1c 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt @@ -6,20 +6,41 @@ import android.graphics.Bitmap import android.content.ComponentName import android.content.Context import android.content.Intent +import android.content.pm.ApplicationInfo +import android.content.pm.LauncherApps +import android.content.pm.ShortcutInfo +import android.graphics.Rect +import android.os.Process +import android.os.UserHandle +import android.os.UserManager import android.content.pm.PackageManager +import android.net.Uri import android.os.Build import android.provider.Settings import androidx.core.graphics.drawable.toBitmap import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState +import kotlin.math.roundToInt object HomeApp { + private const val ICON_DP = 72 + data class LaunchableApp( val label: String, val packageName: String, val className: String, val icon: Bitmap?, - ) + val system: Boolean = false, + val game: Boolean = false, + val installedAt: Long = 0L, + val updatedAt: Long = 0L, + val user: UserHandle? = null, + val userSerial: Long = 0L, + ) { + val component get() = ComponentName(packageName, className) + val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else "" + val work get() = userSerial != 0L + } fun isHomeScreenEnabled(context: Context): Boolean = context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) == @@ -69,33 +90,79 @@ object HomeApp { fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS) fun launchableApps(context: Context): List { + val launcher = context.getSystemService(LauncherApps::class.java) + val users = context.getSystemService(UserManager::class.java) val pm = context.packageManager - val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER) - val apps = pm.queryIntentActivities(launch, 0) - .asSequence() - .mapNotNull { result -> - val activity = result.activityInfo ?: return@mapNotNull null - if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null - val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName } - val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull() - LaunchableApp(label, activity.packageName, activity.name, icon) + val own = Process.myUserHandle() + val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt() + val apps = users.userProfiles.flatMap { user -> + val serial = if (user == own) 0L else users.getSerialNumberForUser(user) + runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info -> + val component = info.componentName + if (component.packageName == context.packageName && user == own) return@mapNotNull null + val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName } + val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull() + val app = info.applicationInfo + val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null + @Suppress("DEPRECATION") + val game = app.category == ApplicationInfo.CATEGORY_GAME || app.flags and ApplicationInfo.FLAG_IS_GAME != 0 + LaunchableApp( + label, component.packageName, component.className, icon, + system = app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0, + game = game, + installedAt = info.firstInstallTime, + updatedAt = updated ?: info.firstInstallTime, + user = user, + userSerial = serial, + ) } - .distinctBy { it.packageName } - .toList() - return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }) + } + return apps.distinctBy { it.key }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }) } - fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) { - val intent = Intent(Intent.ACTION_MAIN) - .addCategory(Intent.CATEGORY_LAUNCHER) - .setComponent(ComponentName(app.packageName, app.className)) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - if (displayId == null) { - context.startActivity(intent) - return - } - val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId) - context.startActivity(intent, options.toBundle()) + fun launch(context: Context, app: LaunchableApp, displayId: Int? = null, bounds: Rect? = null) { + val options = displayId?.let { ActivityOptions.makeBasic().setLaunchDisplayId(it).toBundle() } + val launcher = context.getSystemService(LauncherApps::class.java) + launcher.startMainActivity(app.component, app.user ?: Process.myUserHandle(), bounds, options) + } + + fun canUseShortcuts(context: Context): Boolean = + runCatching { context.getSystemService(LauncherApps::class.java).hasShortcutHostPermission() }.getOrDefault(false) + + fun shortcuts(context: Context, app: LaunchableApp): List { + if (!canUseShortcuts(context)) return emptyList() + val query = LauncherApps.ShortcutQuery() + .setPackage(app.packageName) + .setActivity(app.component) + .setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST) + return runCatching { context.getSystemService(LauncherApps::class.java).getShortcuts(query, app.user ?: Process.myUserHandle()) } + .getOrNull().orEmpty() + .filter { it.isEnabled } + .sortedWith(compareBy { if (it.isDeclaredInManifest) 0 else 1 }.thenBy { it.rank }) + .take(5) + } + + fun shortcutIcon(context: Context, info: ShortcutInfo, px: Int = (ICON_DP * context.resources.displayMetrics.density).roundToInt()): Bitmap? = runCatching { + context.getSystemService(LauncherApps::class.java) + .getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px) + }.getOrNull() + + fun startShortcut(context: Context, info: ShortcutInfo) { + context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null) + } + + fun openAppInfo(context: Context, app: LaunchableApp) { + context.getSystemService(LauncherApps::class.java) + .startAppDetailsActivity(app.component, app.user ?: Process.myUserHandle(), null, null) + } + + fun canUninstall(app: LaunchableApp): Boolean = !app.system && !app.work + + fun uninstall(context: Context, app: LaunchableApp) { + context.startActivity( + Intent(Intent.ACTION_DELETE, Uri.fromParts("package", app.packageName, null)) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) } fun isActiveSteamSession(): Boolean = diff --git a/app/src/main/java/com/droiddeck/launcher/HomeFolders.kt b/app/src/main/java/com/droiddeck/launcher/HomeFolders.kt new file mode 100644 index 0000000000..dc1f0bca47 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/HomeFolders.kt @@ -0,0 +1,65 @@ +package com.droiddeck.launcher + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import org.json.JSONArray +import org.json.JSONObject +import java.util.UUID + +object HomeFolders { + data class Folder(val id: String, val name: String, val apps: List) + + private const val PREFS = "home_launcher" + private const val KEY = "folders" + + var folders by mutableStateOf>(emptyList()) + private set + private var loaded = false + + fun load(context: Context) { + if (loaded) return + loaded = true + val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return + folders = runCatching { + val array = JSONArray(raw) + (0 until array.length()).map { i -> + val o = array.getJSONObject(i) + val apps = o.getJSONArray("apps") + Folder(o.getString("id"), o.getString("name"), (0 until apps.length()).map { apps.getString(it) }) + } + }.getOrDefault(emptyList()) + } + + fun create(context: Context, name: String, appKey: String): Folder { + val folder = Folder(UUID.randomUUID().toString(), name, listOf(appKey)) + update(context, without(appKey) + folder) + return folder + } + + fun add(context: Context, folderId: String, appKey: String) = + update(context, without(appKey).map { if (it.id == folderId) it.copy(apps = it.apps + appKey) else it }) + + fun remove(context: Context, appKey: String) = update(context, without(appKey)) + + fun rename(context: Context, folderId: String, name: String) = + update(context, folders.map { if (it.id == folderId) it.copy(name = name) else it }) + + fun delete(context: Context, folderId: String) = update(context, folders.filterNot { it.id == folderId }) + + fun migrateMembers(context: Context, keyFor: (String) -> String?) { + if (folders.none { f -> f.apps.any { '/' !in it } }) return + update(context, folders.map { f -> f.copy(apps = f.apps.map { if ('/' in it) it else keyFor(it) ?: it }.distinct()) }) + } + + private fun without(appKey: String): List = + folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() } + + private fun update(context: Context, next: List) { + folders = next + val array = JSONArray() + for (f in next) array.put(JSONObject().put("id", f.id).put("name", f.name).put("apps", JSONArray(f.apps))) + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/HomeHidden.kt b/app/src/main/java/com/droiddeck/launcher/HomeHidden.kt new file mode 100644 index 0000000000..70f98f4843 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/HomeHidden.kt @@ -0,0 +1,26 @@ +package com.droiddeck.launcher + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue + +object HomeHidden { + private const val PREFS = "home_launcher" + private const val KEY = "hidden" + + var keys by mutableStateOf>(emptySet()) + private set + private var loaded = false + + fun load(context: Context) { + if (loaded) return + loaded = true + keys = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, emptySet()).orEmpty().toSet() + } + + fun set(context: Context, key: String, hidden: Boolean) { + keys = if (hidden) keys + key else keys - key + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, keys).apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/HomePins.kt b/app/src/main/java/com/droiddeck/launcher/HomePins.kt new file mode 100644 index 0000000000..1040995e87 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/HomePins.kt @@ -0,0 +1,75 @@ +package com.droiddeck.launcher + +import android.content.Context +import android.content.pm.LauncherApps +import android.content.pm.ShortcutInfo +import android.graphics.Bitmap +import android.os.Handler +import android.os.Looper +import android.os.Process +import android.os.UserManager +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue + +/** Shortcuts other apps asked to put on the home screen. The system keeps the pinned set per launcher. */ +object HomePins { + class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) { + val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else "" + val label get() = info.shortLabel?.toString()?.trim().orEmpty().ifEmpty { appLabel } + val work get() = userSerial != 0L + } + + var pinned by mutableStateOf>(emptyList()) + private set + private val main = Handler(Looper.getMainLooper()) + private var listing = 0 + + fun refresh(context: Context) { + val app = context.applicationContext + val seq = ++listing + Thread({ + val list = runCatching { load(app) }.getOrDefault(emptyList()) + main.post { if (seq == listing) pinned = list } + }, "home-pins").start() + } + + private fun load(context: Context): List { + if (!HomeApp.canUseShortcuts(context)) return emptyList() + val launcher = context.getSystemService(LauncherApps::class.java) + val users = context.getSystemService(UserManager::class.java) + val pm = context.packageManager + val own = Process.myUserHandle() + val query = LauncherApps.ShortcutQuery().setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED) + return users.userProfiles.flatMap { user -> + val serial = if (user == own) 0L else users.getSerialNumberForUser(user) + runCatching { launcher.getShortcuts(query, user) }.getOrNull().orEmpty() + .filter { it.isEnabled && it.isPinned } + .map { info -> + val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.`package`, 0)).toString() } + .getOrDefault(info.`package`) + Pinned(info, HomeApp.shortcutIcon(context, info), appLabel, serial) + } + } + } + + fun accept(context: Context, request: LauncherApps.PinItemRequest): Boolean { + val ok = runCatching { request.isValid && request.accept() }.getOrDefault(false) + if (ok) refresh(context) + return ok + } + + fun unpin(context: Context, pinned: Pinned) { + val info = pinned.info + val launcher = context.getSystemService(LauncherApps::class.java) + val query = LauncherApps.ShortcutQuery().setPackage(info.`package`).setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED) + val unpinned = runCatching { + val current = checkNotNull(launcher.getShortcuts(query, info.userHandle)) + val keep = current.map { it.id } - info.id + launcher.pinShortcuts(info.`package`, keep, info.userHandle) + }.isSuccess + if (!unpinned) return + listing++ + this.pinned = this.pinned.filterNot { it.key == pinned.key } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt new file mode 100644 index 0000000000..8f79f4354b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt @@ -0,0 +1,317 @@ +package com.droiddeck.launcher + +import android.app.Activity +import android.appwidget.AppWidgetHost +import android.appwidget.AppWidgetHostView +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProviderInfo +import android.content.Context +import android.content.Intent +import android.content.pm.LauncherApps +import android.graphics.Bitmap +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.util.SizeF +import android.view.HapticFeedbackConstants +import android.view.MotionEvent +import android.view.ViewConfiguration +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.core.graphics.drawable.toBitmap +import org.json.JSONArray +import org.json.JSONObject +import kotlin.math.hypot +import kotlin.math.roundToInt + +object HomeWidgets { + data class Placed(val id: Int, val widthDp: Int, val heightDp: Int) + + data class Provider( + val info: AppWidgetProviderInfo, + val label: String, + val appLabel: String, + val preview: Bitmap?, + val widthDp: Int, + val heightDp: Int, + ) + + private const val HOST_ID = 0x0DDE + private const val PREFS = "home_launcher" + private const val KEY = "widgets" + private const val REQUEST_BIND = 0x0DD1 + private const val REQUEST_CONFIGURE = 0x0DD2 + private const val REQUEST_RECONFIGURE = 0x0DD3 + const val MIN_WIDTH_DP = 96 + const val MIN_HEIGHT_DP = 56 + + var widgets by mutableStateOf>(emptyList()) + private set + var providers by mutableStateOf?>(null) + private set + private var loaded = false + private var host: Host? = null + private var pending: AppWidgetProviderInfo? = null + private var pendingId = AppWidgetManager.INVALID_APPWIDGET_ID + private var pinRequest: LauncherApps.PinItemRequest? = null + private val main = Handler(Looper.getMainLooper()) + + private class Host(context: Context) : AppWidgetHost(context, HOST_ID) { + override fun onCreateView(context: Context, appWidgetId: Int, appWidget: AppWidgetProviderInfo?): AppWidgetHostView = + HomeWidgetView(context) + } + + class HomeWidgetView(context: Context) : AppWidgetHostView(context) { + var onLongPress: (() -> Unit)? = null + private var fired = false + private var downX = 0f + private var downY = 0f + private val slop = ViewConfiguration.get(context).scaledTouchSlop + private val longPress = Runnable { + fired = true + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) + onLongPress?.invoke() + } + + override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { + when (ev.actionMasked) { + MotionEvent.ACTION_DOWN -> { + fired = false + downX = ev.x + downY = ev.y + postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong()) + } + MotionEvent.ACTION_MOVE -> if (hypot(ev.x - downX, ev.y - downY) > slop) removeCallbacks(longPress) + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> removeCallbacks(longPress) + } + return fired + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (fired) { + if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) fired = false + return true + } + return super.onTouchEvent(event) + } + } + + private fun host(context: Context): Host = host ?: Host(context.applicationContext).also { host = it } + + fun load(context: Context) { + if (loaded) return + loaded = true + val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return + val manager = AppWidgetManager.getInstance(context) + val parsed = runCatching { + val array = JSONArray(raw) + (0 until array.length()).map { i -> + val o = array.getJSONObject(i) + Placed(o.getInt("id"), o.getInt("w"), o.getInt("h")) + } + }.getOrDefault(emptyList()) + val live = parsed.filter { manager.getAppWidgetInfo(it.id) != null } + parsed.filterNot { it in live }.forEach { host(context).deleteAppWidgetId(it.id) } + widgets = live + if (live.size != parsed.size) save(context) + } + + fun startListening(context: Context) { + load(context) + runCatching { host(context).startListening() } + } + + fun stopListening(context: Context) { + runCatching { host(context).stopListening() } + } + + fun info(context: Context, id: Int): AppWidgetProviderInfo? = AppWidgetManager.getInstance(context).getAppWidgetInfo(id) + + fun createView(context: Context, id: Int): HomeWidgetView? { + val info = info(context, id) ?: return null + return host(context).createView(context, id, info) as? HomeWidgetView + } + + fun applySize(view: AppWidgetHostView, widthDp: Int, heightDp: Int) { + if (Build.VERSION.SDK_INT >= 31) { + view.updateAppWidgetSize(Bundle(), listOf(SizeF(widthDp.toFloat(), heightDp.toFloat()))) + } else { + @Suppress("DEPRECATION") + view.updateAppWidgetSize(null, widthDp, heightDp, widthDp, heightDp) + } + } + + fun loadProviders(context: Context) { + if (providers != null) return + val app = context.applicationContext + Thread({ + val pm = app.packageManager + val manager = AppWidgetManager.getInstance(app) + val dpi = app.resources.displayMetrics.densityDpi + val list = manager.installedProviders.mapNotNull { info -> + runCatching { + val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.provider.packageName, 0)).toString() } + .getOrDefault(info.provider.packageName) + val drawable = info.loadPreviewImage(app, dpi) ?: info.loadIcon(app, dpi) + val preview = drawable?.let { d -> + val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192 + val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192 + val scale = minOf(1f, 360f / maxOf(w, h)) + d.toBitmap((w * scale).roundToInt().coerceAtLeast(1), (h * scale).roundToInt().coerceAtLeast(1)) + } + val (w, h) = defaultSize(app, info) + Provider(info, info.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { appLabel }, appLabel, preview, w, h) + }.getOrNull() + }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, Provider::appLabel).thenBy(String.CASE_INSENSITIVE_ORDER, Provider::label)) + main.post { providers = list } + }, "widget-providers").start() + } + + fun refreshProviders(context: Context) { + providers = null + loadProviders(context) + } + + private fun defaultSize(context: Context, info: AppWidgetProviderInfo): Pair { + val density = context.resources.displayMetrics.density + var w = (info.minWidth / density).roundToInt() + var h = (info.minHeight / density).roundToInt() + if (Build.VERSION.SDK_INT >= 31) { + if (info.targetCellWidth > 0) w = maxOf(w, info.targetCellWidth * 80) + if (info.targetCellHeight > 0) h = maxOf(h, info.targetCellHeight * 80) + } + return w.coerceIn(160, 560) to h.coerceIn(MIN_HEIGHT_DP, 360) + } + + fun minSize(context: Context, id: Int): Pair { + val info = info(context, id) ?: return MIN_WIDTH_DP to MIN_HEIGHT_DP + val density = context.resources.displayMetrics.density + val w = (if (info.minResizeWidth > 0) info.minResizeWidth else info.minWidth) / density + val h = (if (info.minResizeHeight > 0) info.minResizeHeight else info.minHeight) / density + return w.roundToInt().coerceAtLeast(MIN_WIDTH_DP) to h.roundToInt().coerceAtLeast(MIN_HEIGHT_DP) + } + + fun add(activity: Activity, provider: Provider) { + if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null) + } + + /** Places a widget another app asked for; its own app has already configured it. */ + fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean { + if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false + val info = request.getAppWidgetProviderInfo(activity) ?: return false + load(activity) + add(activity, info, request) + return pending != null + } + + private fun add(activity: Activity, info: AppWidgetProviderInfo, request: LauncherApps.PinItemRequest?) { + val h = host(activity) + val id = h.allocateAppWidgetId() + pending = info + pendingId = id + pinRequest = request + val manager = AppWidgetManager.getInstance(activity) + val bound = runCatching { manager.bindAppWidgetIdIfAllowed(id, info.profile, info.provider, null) }.getOrDefault(false) + if (bound) { + bound(activity, id, info) + return + } + val bind = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile) + @Suppress("DEPRECATION") + runCatching { activity.startActivityForResult(bind, REQUEST_BIND) }.onFailure { abandon(activity) } + } + + private fun bound(activity: Activity, id: Int, info: AppWidgetProviderInfo) { + val request = pinRequest + if (request == null) { + configure(activity, id, info) + return + } + val accepted = runCatching { request.isValid && request.accept(Bundle().apply { putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, id) }) } + .getOrDefault(false) + if (accepted) place(activity, id, info) else abandon(activity) + } + + private fun configure(activity: Activity, id: Int, info: AppWidgetProviderInfo) { + val optional = Build.VERSION.SDK_INT >= 31 && + info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0 + if (info.configure == null || optional) { + place(activity, id, info) + return + } + runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_CONFIGURE, null) } + .onFailure { place(activity, id, info) } + } + + fun canReconfigure(context: Context, id: Int): Boolean { + val info = info(context, id) ?: return false + if (info.configure == null) return false + return Build.VERSION.SDK_INT < 28 || info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE != 0 + } + + fun reconfigure(activity: Activity, id: Int) { + runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_RECONFIGURE, null) } + } + + fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int): Boolean { + when (requestCode) { + REQUEST_BIND -> { + val info = pending + if (resultCode == Activity.RESULT_OK && info != null) bound(activity, pendingId, info) else abandon(activity) + } + REQUEST_CONFIGURE -> { + val info = pending + if (resultCode == Activity.RESULT_OK && info != null) place(activity, pendingId, info) else abandon(activity) + } + REQUEST_RECONFIGURE -> Unit + else -> return false + } + return true + } + + private fun abandon(context: Context) { + if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) host(context).deleteAppWidgetId(pendingId) + pending = null + pinRequest = null + pendingId = AppWidgetManager.INVALID_APPWIDGET_ID + } + + private fun place(context: Context, id: Int, info: AppWidgetProviderInfo) { + val (w, h) = defaultSize(context, info) + pending = null + pinRequest = null + pendingId = AppWidgetManager.INVALID_APPWIDGET_ID + widgets = widgets + Placed(id, w, h) + save(context) + } + + fun resize(context: Context, id: Int, widthDp: Int, heightDp: Int) { + widgets = widgets.map { if (it.id == id) it.copy(widthDp = widthDp, heightDp = heightDp) else it } + save(context) + } + + fun move(context: Context, id: Int, by: Int) { + val i = widgets.indexOfFirst { it.id == id } + val j = i + by + if (i < 0 || j !in widgets.indices) return + widgets = widgets.toMutableList().apply { add(j, removeAt(i)) } + save(context) + } + + fun remove(context: Context, id: Int) { + host(context).deleteAppWidgetId(id) + widgets = widgets.filterNot { it.id == id } + save(context) + } + + private fun save(context: Context) { + val array = JSONArray() + for (w in widgets) array.put(JSONObject().put("id", w.id).put("w", w.widthDp).put("h", w.heightDp)) + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt new file mode 100644 index 0000000000..44fce026a9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt @@ -0,0 +1,328 @@ +package com.droiddeck.launcher + +import android.app.ActivityOptions +import android.app.AppOpsManager +import android.app.PictureInPictureParams +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.res.Configuration +import android.os.Build +import android.os.Bundle +import android.os.Process +import android.provider.Settings +import android.util.Rational +import androidx.activity.ComponentActivity +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.scale +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.core.AppLanguage +import com.droiddeck.launcher.core.GlobalSettings +import com.droiddeck.launcher.core.WirelessAdbPairingService +import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage +import com.droiddeck.launcher.ui.DroidDeckTheme +import com.droiddeck.launcher.ui.LocalPalette +import com.droiddeck.launcher.ui.PrimaryButton +import com.droiddeck.launcher.ui.SecondaryButton +import kotlinx.coroutines.delay + +class PairingGuideActivity : ComponentActivity() { + enum class Step { BUILD_NUMBER, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED } + + private var settingsDisplay: Int? = null + private var inPip by mutableStateOf(false) + private var launchPending = false + + override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase)) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 } + setContent { DroidDeckTheme { Guide() } } + launchPending = savedInstanceState == null + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 } + launchPending = true + } + + override fun onResume() { + super.onResume() + if (!launchPending) return + if (inPip || settingsDisplay != null) { + launchSettings() + return + } + enterPip() + if (!inPip) launchSettings() + } + + override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) { + super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) + inPip = isInPictureInPictureMode + if (isInPictureInPictureMode && launchPending) launchSettings() + } + + private fun launchSettings() { + launchPending = false + openSettings(stepFor(this, WirelessAdbPairingService.stage.value)) + } + + private fun enterPip() { + inPip = runCatching { + enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(4, 3)).build()) + }.getOrDefault(false) + } + + private fun openSettings(step: Step) { + val intent = if (step == Step.BUILD_NUMBER) { + Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number") + } else { + Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless") + }.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val display = settingsDisplay + runCatching { + if (display == null) startActivity(intent) + else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle()) + }.onFailure { + runCatching { startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } + } + } + + private fun returnToApp() { + startActivity(Intent(this, FrontEndActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) + finish() + } + + @Composable + private fun Guide() { + val stage by WirelessAdbPairingService.stage.collectAsState() + val settingsState by produceState(SettingsState.read(this)) { + while (true) { + value = SettingsState.read(this@PairingGuideActivity) + delay(500) + } + } + val step = stepFor(settingsState, stage) + var previous by remember { mutableStateOf(step) } + LaunchedEffect(step) { + if (previous == Step.BUILD_NUMBER && step == Step.WIRELESS_DEBUGGING) openSettings(step) + previous = step + when (step) { + Step.DONE -> { delay(1_500); returnToApp() } + Step.FAILED -> { delay(3_000); returnToApp() } + else -> Unit + } + } + LaunchedEffect(stage) { if (stage == Stage.Idle) finish() } + BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() } + + Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) { + if (inPip) CompactStep(step, stage) + else FullGuide(step, stage) + } + } + + @Composable + private fun CompactStep(step: Step, stage: Stage) { + Column(Modifier.fillMaxSize().padding(10.dp), verticalArrangement = Arrangement.SpaceBetween) { + Text( + instruction(step, stage), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onBackground, maxLines = 3, overflow = TextOverflow.Ellipsis, + ) + StepVisual(step, compact = true) + StepDots(step) + } + } + + @Composable + private fun FullGuide(step: Step, stage: Stage) { + Column( + Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Text(stringResource(R.string.gate_title), style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground) + Text(instruction(step, stage), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground) + StepVisual(step, compact = false) + StepDots(step) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + if (step == Step.DONE || step == Step.FAILED) { + PrimaryButton(stringResource(R.string.common_back), onClick = ::returnToApp) + } else { + PrimaryButton(stringResource(R.string.gate_open_dev), onClick = { + if (settingsDisplay == null) enterPip() + openSettings(step) + }) + SecondaryButton(stringResource(R.string.common_cancel), onClick = { + WirelessAdbPairingService.cancel(this@PairingGuideActivity) + returnToApp() + }) + } + } + } + } + + @Composable + private fun instruction(step: Step, stage: Stage): String = when (step) { + Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number) + Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless) + Step.PAIR -> stringResource(R.string.pairguide_pair) + Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3) + Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_working) + Step.DONE -> stringResource(R.string.adbpair_title_done) + Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed) + } + + @Composable + private fun StepVisual(step: Step, compact: Boolean) { + val colors = MaterialTheme.colorScheme + val accent = LocalPalette.current.signal + val pulse = rememberInfiniteTransition(label = "guidePulse") + val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat") + val label = when (step) { + Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number) + Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless) + Step.PAIR -> stringResource(R.string.pairguide_row_pair) + Step.CODE -> stringResource(R.string.adbpair_enter_code) + Step.WORKING, Step.DONE, Step.FAILED -> return + } + val rowHeight = if (compact) 34.dp else 56.dp + Row( + Modifier.fillMaxWidth().height(rowHeight).background(colors.surfaceVariant, RoundedCornerShape(10.dp)) + .border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(10.dp)).padding(horizontal = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge, + color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + when (step) { + Step.WIRELESS_DEBUGGING -> Toggle(on = beat > 0.5f, accent = accent, compact = compact) + else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent) + Box(contentAlignment = Alignment.Center) { + Box(Modifier.size(if (compact) 18.dp else 26.dp).scale(0.6f + beat * 0.8f).alpha(1f - beat) + .background(accent, CircleShape)) + Box(Modifier.size(if (compact) 8.dp else 12.dp).background(accent, CircleShape)) + } + } + } + } + } + + @Composable + private fun Toggle(on: Boolean, accent: Color, compact: Boolean) { + val width = if (compact) 26.dp else 40.dp + val knob = if (compact) 12.dp else 18.dp + Box( + Modifier.width(width).height(knob + 4.dp) + .background(if (on) accent.copy(alpha = 0.6f) else MaterialTheme.colorScheme.outline, CircleShape).padding(2.dp), + contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart, + ) { Box(Modifier.size(knob).background(Color.White, CircleShape)) } + } + + @Composable + private fun StepDots(step: Step) { + val accent = LocalPalette.current.signal + val shown = listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE) + val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size + Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) { + shown.forEachIndexed { index, _ -> + Box(Modifier.size(if (index == at) 8.dp else 6.dp) + .background(if (index <= at) accent else MaterialTheme.colorScheme.outline, CircleShape)) + } + Spacer(Modifier.width(2.dp)) + } + } + + private data class SettingsState(val developerOptions: Boolean, val wirelessDebugging: Boolean) { + companion object { + fun read(context: Context) = SettingsState( + GlobalSettings.developerOptionsOn(context), + GlobalSettings.wirelessDebuggingOn(context), + ) + } + } + + companion object { + private const val EXTRA_DISPLAY = "settingsDisplay" + private const val HIGHLIGHT_KEY = ":settings:fragment_args_key" + + private fun stepFor(context: Context, stage: Stage) = stepFor(SettingsState.read(context), stage) + + private fun stepFor(settings: SettingsState, stage: Stage): Step = when (stage) { + is Stage.Working -> Step.WORKING + Stage.Done -> Step.DONE + is Stage.Failed -> Step.FAILED + is Stage.CodeNeeded -> Step.CODE + else -> when { + !settings.developerOptions -> Step.BUILD_NUMBER + !settings.wirelessDebugging -> Step.WIRELESS_DEBUGGING + else -> Step.PAIR + } + } + + fun canFloat(context: Context): Boolean { + if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false + val ops = context.getSystemService(AppOpsManager::class.java) ?: return true + val mode = if (Build.VERSION.SDK_INT >= 29) { + ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName) + } else { + @Suppress("DEPRECATION") + ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName) + } + return mode == AppOpsManager.MODE_ALLOWED + } + + fun start(context: Context, settingsDisplay: Int?): Boolean { + if (settingsDisplay == null && !canFloat(context)) return false + context.startActivity(Intent(context, PairingGuideActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) }) + return true + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/PinRequestActivity.kt b/app/src/main/java/com/droiddeck/launcher/PinRequestActivity.kt new file mode 100644 index 0000000000..ca8d382fee --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/PinRequestActivity.kt @@ -0,0 +1,82 @@ +package com.droiddeck.launcher + +import android.content.Intent +import android.content.pm.LauncherApps +import android.graphics.Bitmap +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.core.graphics.drawable.toBitmap +import com.droiddeck.launcher.core.AppUiPrefs +import com.droiddeck.launcher.ui.DroidDeckTheme +import com.droiddeck.launcher.ui.PinRequestPrompt + +class PinRequestActivity : ComponentActivity() { + override fun attachBaseContext(newBase: android.content.Context) { + super.attachBaseContext(newBase) + com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val request = runCatching { getSystemService(LauncherApps::class.java).getPinItemRequest(intent) }.getOrNull() + if (request == null || !request.isValid) { + finish() + return + } + val prompt = when (request.requestType) { + LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT -> request.shortcutInfo?.let { info -> + val appLabel = appLabel(info.`package`) + Triple(info.shortLabel?.toString().orEmpty().ifEmpty { appLabel }, appLabel, HomeApp.shortcutIcon(this, info)) + } + LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET -> request.getAppWidgetProviderInfo(this)?.let { info -> + val appLabel = appLabel(info.provider.packageName) + val dpi = resources.displayMetrics.densityDpi + val icon = runCatching { (info.loadPreviewImage(this, dpi) ?: info.loadIcon(this, dpi))?.let(::scaled) }.getOrNull() + Triple(info.loadLabel(packageManager)?.toString().orEmpty().ifEmpty { appLabel }, appLabel, icon) + } + else -> null + } + if (prompt == null) { + finish() + return + } + val (label, appLabel, icon) = prompt + val widget = request.requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET + setContent { + DroidDeckTheme(appScale = AppUiPrefs.scale(this)) { + PinRequestPrompt( + label = label, appLabel = appLabel, icon = icon, wide = widget, + onAdd = { + if (!widget) { + HomePins.accept(this, request) + finish() + } else if (!HomeWidgets.addPinned(this, request)) finish() + }, + onCancel = { finish() }, + ) + } + } + } + + @Suppress("OVERRIDE_DEPRECATION") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) { + finish() + return + } + @Suppress("DEPRECATION") + super.onActivityResult(requestCode, resultCode, data) + } + + private fun appLabel(packageName: String): String = + runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() } + .getOrDefault(packageName) + + private fun scaled(d: android.graphics.drawable.Drawable): Bitmap { + val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192 + val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192 + val k = minOf(1f, 480f / maxOf(w, h)) + return d.toBitmap((w * k).toInt().coerceAtLeast(1), (h * k).toInt().coerceAtLeast(1)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt index 5e49b5cf5d..8e8efc80c2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt @@ -20,10 +20,19 @@ internal class ProtonMenu( private val ui: Handler, private val idle: () -> Boolean = { true }, ) { - var protonRows by mutableStateOf>(emptyList()) - var protonBusyId by mutableStateOf(null) - var protonStage by mutableStateOf(null) - var protonPercent by mutableIntStateOf(-1) + // Install workers and their results outlive the activity that starts them. + private object Operation { + val rows = mutableStateOf>(emptyList()) + val busyId = mutableStateOf(null) + val stage = mutableStateOf(null) + val percent = mutableIntStateOf(-1) + val problem = mutableStateOf(null) + } + var protonRows by Operation.rows + var protonBusyId by Operation.busyId + var protonStage by Operation.stage + var protonPercent by Operation.percent + var protonProblem by Operation.problem private val checking = java.util.concurrent.atomic.AtomicBoolean(false) @VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? = { tool, progress -> ProtonExtras.install(activity, tool, progress) } @@ -33,6 +42,7 @@ internal class ProtonMenu( if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return ProtonExtras.unqueue(activity, tool) protonBusyId = id + protonProblem = null protonStage = activity.getString(R.string.store_starting) protonPercent = -1 Thread({ @@ -41,7 +51,9 @@ internal class ProtonMenu( ui.post { protonStage = label; protonPercent = value } } }.getOrElse { it.message ?: it.javaClass.simpleName } + if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false) ui.post { + protonProblem = problem protonBusyId = null protonStage = null protonPercent = -1 @@ -59,10 +71,12 @@ internal class ProtonMenu( val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return if (protonBusyId != null || SessionState.running) return protonBusyId = id + protonProblem = null protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name) protonPercent = -1 Thread({ if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir) + if (tool.id == ProtonExtras.OWN && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true) ui.post { protonBusyId = null protonStage = null @@ -94,9 +108,23 @@ internal class ProtonMenu( ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() || SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return + if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) { + protonBusyId = ProtonExtras.OWN + protonProblem = null + Thread({ + ProtonExtras.tidy(activity) + val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1 + ui.post { + protonBusyId = null + refreshProtons() + if (tidied) ensureAutoUpdates() + } + }, "proton-tidy").start() + return + } val attempts = activity.getSharedPreferences("proton-auto-updates", android.content.Context.MODE_PRIVATE) val (tool, update) = ProtonExtras.tools.firstNotNullOfOrNull { tool -> - val update = ProtonExtras.update(activity, tool) ?: return@firstNotNullOfOrNull null + val update = ProtonExtras.update(activity, tool) ?: ProtonExtras.missing(activity, tool) ?: return@firstNotNullOfOrNull null val previous = attempts.getLong("${tool.id}.at", 0L) if (attempts.getString("${tool.id}.tag", null) != update || now - previous !in 0 until 15L * 60 * 1000) tool to update else null } ?: return diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index f149d93565..9ff4f2496d 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -9,6 +9,7 @@ import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Environment +import android.database.ContentObserver import android.os.Handler import android.os.Looper import android.os.SystemClock @@ -67,6 +68,7 @@ import com.droiddeck.launcher.gpu.ScreenEffects import com.droiddeck.launcher.gpu.Lossless import com.droiddeck.launcher.gpu.TurnipDriver import com.droiddeck.launcher.input.EvdevKeys +import com.droiddeck.launcher.input.HomeGuideInput import com.droiddeck.launcher.input.InputSpace import com.droiddeck.launcher.input.KeyboardHost import com.droiddeck.launcher.input.ControllerPrefs @@ -75,8 +77,10 @@ import com.droiddeck.launcher.input.OnScreenControls import com.droiddeck.launcher.input.PadBridge import com.droiddeck.launcher.input.PadMouse import com.droiddeck.launcher.input.PadState +import com.droiddeck.launcher.input.ScreenKeys import com.droiddeck.launcher.input.SteamControllerBle import com.droiddeck.launcher.input.DirectTouchHold +import com.droiddeck.launcher.input.GestureTouchStreamGate import com.droiddeck.launcher.input.PointerGestures import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenDisplays @@ -155,6 +159,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private lateinit var sessionOverlay: ComposeView private lateinit var loading: LoadingState private lateinit var hud: PerfHud + private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud private var padBridge: PadBridge? = null private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null @@ -198,10 +203,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig() private var gestureGame: String? = null private var gestureSettingsOpen by mutableStateOf(false) + private var screenKeyPickerOpen by mutableStateOf(false) + private var screenKeyBind: List? = null + private var screenKeyDir: Int? = null + private var screenKeyTextFocus = false + private var screenKeyEdit by mutableStateOf(null) + private var screenLayoutsOpen by mutableStateOf(false) + private var screenKeysShown by mutableStateOf(true) + private var screenLayoutNames by mutableStateOf(listOf()) + private var screenKeys: ScreenKeys? = null private var recognizedGesture by mutableStateOf(null) private var gesturePointerX = 0f private var gesturePointerY = 0f private var gesturePointerReady = false + private val gestureTouchStreamGate = GestureTouchStreamGate() private val clearRecognizedGesture = Runnable { recognizedGesture = null } private val gestureKeysDown = mutableSetOf() private lateinit var scrollTouch: ScrollTouchGestures @@ -244,6 +259,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false } private val uiHandler = Handler(Looper.getMainLooper()) private var pendingBackAction: Runnable? = null + private val backQamInput = com.droiddeck.launcher.input.BackQamInput( + setPressed = { padBridge?.setBackQamPressed(it) }, + onTap = { performBackAction(double = it) }, + doubleTapMs = { backDoubleTapMs.toLong() }, + onCancel = { padBridge?.cancelBackQam() }, + ) private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN private var drawerDirectionDownTime = 0L private var drawerDirectionDeviceId = -1 @@ -270,6 +291,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } private val resumeKeysDown = mutableSetOf>() + private val drawerShortcutKeysDown = mutableSetOf>() private var drawerOpen by mutableStateOf(false) private var quitFrom by mutableStateOf(null) @@ -280,6 +302,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var drawerDefaultProton by mutableStateOf(null) private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) } private var drawerGameProfileId by mutableStateOf(null) + + private fun noSteamSession(): Boolean = SessionState.mode == SessionService.MODE_RUN && + SessionState.program in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.EPIC) private val drawerGameInventory = GameProfileInventoryCache() private var drawerGameInventoryRevision = 0L private var drawerGameFexPresetSaving by mutableStateOf(false) @@ -301,8 +326,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER) private var drawerControllerActive by mutableStateOf(false) private var backActionsInverted by mutableStateOf(false) - private var lowLatencyController by mutableStateOf(false) - private var lowLatencyTouch by mutableStateOf(false) + private var backDoubleTapMs by mutableStateOf(500) + private var lowLatency by mutableStateOf(true) private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK) private var pcKeyboardOpen by mutableStateOf(false) private var achievementsInFront by mutableStateOf(null) @@ -409,6 +434,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } + // A higher refresh rate allowed in Android's settings does not change the display while this window + // still asks for a lower mode, so the mode is chosen again when the setting changes. + private val refreshSettingObserver = object : ContentObserver(Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean) { + applyOutputPacing() + } + } + private fun followPanelRefresh(displayId: Int) { if (!CompositorHost.isStarted) return val output = glassesScreen?.display @@ -430,6 +463,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onInputDeviceRemoved(deviceId: Int) { Log.i(TAG, "input device $deviceId disconnected") + backQamInput.onDeviceRemoved(deviceId) joyConVr?.refresh() padBridge?.onDeviceRemoved(deviceId) if (::padMouse.isInitialized) padMouse.reset() @@ -481,11 +515,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) - if (!SessionState.running) { - SessionState.fpsLimit = SessionPrefs.fpsLimit( - this, SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM), - ) - } applyOutputPacing() if (!SessionState.running) SessionState.followScreen = followChoice() applyFollowOrientation(resources.configuration) @@ -516,6 +545,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam) bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this)) padBridge = bridge + bridge.setOnChordInput(backQamInput::onChordInput) SessionState.padBridge = bridge if (Build.VERSION.SDK_INT >= 31) { val vr = com.droiddeck.launcher.input.JoyConVr(this, File(filesDir, ".wayland-rt/${com.droiddeck.launcher.input.JoyConVr.FILE}")) { taken, released -> @@ -540,7 +570,28 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { uiHandler.removeCallbacks(cursorHide) cursorVisible = false } - onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) } + onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { controls -> + controls.onTouchMiss = miss@{ event -> + if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss + event.offsetLocation(controls.left - surfaceView.left.toFloat(), controls.top - surfaceView.top.toFloat()) + onTouchEvent(event) + } + root.addView(controls) + } + screenKeysShown = com.droiddeck.launcher.input.ControllerPrefs.screenKeysShown(this) + screenKeys = ScreenKeys(this) { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) }.also { keys -> + keys.onTouchMiss = miss@{ event -> + if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss + event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat()) + onTouchEvent(event) + } + keys.onAdd = { screenKeyPickerOpen = true } + keys.onSelect = { codes -> screenKeyEdit = screenKeys?.stateOf(codes) } + keys.onEditingChanged = { if (!it) screenKeyEdit = null } + keys.steamStyle = { steamTouchControls?.style } + keys.visibility = if (screenKeysShown) View.VISIBLE else View.GONE + root.addView(keys) + } keyboard = KeyboardHost(this).also { root.addView(it) } touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener) directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener) { @@ -555,7 +606,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // game surface and on-screen buttons, in either finger-down order. root.isMotionEventSplittingEnabled = true surfaceView.setOnTouchListener { _, event -> - routedTouchMode == SessionPrefs.TOUCH_GESTURES && onTouchEvent(event) + if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) { + false + } else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) { + false + } else onTouchEvent(event) } padMouse = PadMouse(padMouseListener) bridge.setTouchRoute(object : PadBridge.TouchRoute { @@ -579,17 +634,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { val needResume = !needRuntime && com.droiddeck.launcher.runtime.DesktopCatalog.interrupted(this).isNotEmpty() val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP && (repair || !com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this)) - val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM && - com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this) + val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) + val protonUser = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM || + program == com.droiddeck.launcher.runtime.BattleNet.PROGRAM || program == com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN + val needProton = protonUser && com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this) if (needRuntime || needResume || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton, needResume) } hud = PerfHud(this) + memoryHud = com.droiddeck.launcher.session.MemoryHud(this) hud.onPresentingWindowChanged = { if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() } } if (SessionState.running && SessionState.firstFrameSeen) { loading.visible = false hud.start() + memoryHud.start() } readPrefs() @@ -684,7 +743,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density, cursorImage, cursorHotX, cursorHotY, cursorImageScale) - if (hud.text.isNotEmpty() || hud.graph.size >= 2) HudText(hud.text, hud.graph, hudColor, hudOpacity) + val hudLines = listOf(hud.text, memoryHud.text).filter { it.isNotEmpty() } + if (hudLines.isNotEmpty() || hud.graph.size >= 2) + HudText(hudLines.joinToString("\n"), hud.graph, hudColor, hudOpacity) val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking) if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) { @@ -739,7 +800,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) { if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) { + backQamInput.cancel() + com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity) cancelTouchGestures() + screenKeys?.stopEditing() } } com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture) @@ -748,6 +812,84 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onDismiss = { gestureSettingsOpen = false }, onSaved = { gestureSettingsOpen = false; refreshGestureConfig() }, ) + if (screenKeyPickerOpen) { + val dir = screenKeyDir + com.droiddeck.launcher.ui.ScreenKeyPicker( + initial = if (dir != null) { + listOfNotNull((screenKeyEdit?.codes?.getOrNull(dir) ?: 0).takeIf { it != 0 }) + } else { + screenKeyBind ?: emptyList() + }, + onDismiss = { screenKeyPickerOpen = false; screenKeyBind = null; screenKeyDir = null }, + onAdd = { codes -> + val bind = screenKeyBind + if (dir != null && bind != null) { + screenKeys?.setDirection(bind, dir, codes.lastOrNull() ?: 0)?.let { screenKeyEdit = it } + } else if (bind != null) { + screenKeys?.setCodes(bind, codes)?.let { screenKeyEdit = it } + } else { + screenKeys?.add(codes) + screenKeyEdit = screenKeys?.stateOf(codes) + } + screenKeyPickerOpen = false + screenKeyBind = null + screenKeyDir = null + }, + ) + } + screenKeyEdit?.let { key -> + com.droiddeck.launcher.ui.ScreenKeyEditor( + codes = key.codes, keyY = key.y, + size = key.size, opacity = key.opacity, shape = key.shape, toggle = key.toggle, + labels = key.labels, + text = key.text, hasImage = key.image.isNotEmpty(), + onResize = { screenKeys?.resize(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) }, + onOpacity = { screenKeys?.setOpacity(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) }, + onShape = { screenKeys?.setShape(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) }, + onToggle = { on -> screenKeys?.setToggle(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) }, + onLabels = { on -> screenKeys?.setLabels(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) }, + onDirection = { index -> screenKeyBind = key.codes; screenKeyDir = index; screenKeyPickerOpen = true }, + onText = { screenKeys?.setText(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) }, + onImage = { screenKeys?.setImage(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) }, + onClearImage = { screenKeys?.setImage(key.codes, ""); screenKeyEdit = screenKeys?.stateOf(key.codes) }, + onBind = { screenKeyBind = key.codes; screenKeyDir = null; screenKeyPickerOpen = true }, + onTextFocus = { screenKeyTextFocus = true; keyboard?.hide() }, + onTextBlur = { screenKeyTextFocus = false }, + onRemove = { screenKeys?.remove(key.codes); screenKeyEdit = null }, + onDismiss = { screenKeyEdit = null; screenKeyTextFocus = false; screenKeys?.deselect() }, + ) + } + if (screenLayoutsOpen) com.droiddeck.launcher.ui.ScreenLayoutPanel( + layouts = screenLayoutNames, + onSave = { name -> + screenKeys?.let { keys -> + com.droiddeck.launcher.input.ControllerPrefs.saveScreenLayout(this@SessionActivity, name, keys.export()) + } + screenLayoutNames = layoutNames() + }, + onLoad = { name -> + com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this@SessionActivity)[name]?.let { screenKeys?.load(it) } + screenLayoutsOpen = false + }, + onDelete = { name -> + com.droiddeck.launcher.input.ControllerPrefs.deleteScreenLayout(this@SessionActivity, name) + screenLayoutNames = layoutNames() + }, + onImport = { text -> + val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels + val keys = com.droiddeck.launcher.input.importScreenLayout(text, width, resources.displayMetrics.density) + if (keys != null) { + screenKeys?.load(com.droiddeck.launcher.input.ControllerPrefs.encodeScreenKeys(keys)) + screenLayoutsOpen = false + } + }, + exportText = { + val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels + val keys = com.droiddeck.launcher.input.ControllerPrefs.decodeScreenKeys(screenKeys?.export().orEmpty()) + com.droiddeck.launcher.input.exportScreenLayout(keys, width, resources.displayMetrics.density) + }, + onDismiss = { screenLayoutsOpen = false }, + ) androidx.compose.runtime.LaunchedEffect(drawerOpen) { if (drawerOpen) { syncLossless() @@ -794,6 +936,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { ) SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions( steam = SessionState.mode == SessionService.MODE_STEAM, + direct = noSteamSession(), title = if (SessionState.mode == SessionService.MODE_RUN) com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null, isHomeApp = isHomeApp, @@ -899,20 +1042,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { padType = id }, backActionsInverted = backActionsInverted, + backDoubleTapMs = backDoubleTapMs, + onBackDoubleTapMs = { ms -> + SessionPrefs.setBackDoubleTapMs(this@SessionActivity, ms) + backDoubleTapMs = ms + }, onBackActionsInverted = { inverted -> SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted) backActionsInverted = inverted }, - lowLatencyController = lowLatencyController, - lowLatencyTouch = lowLatencyTouch, - onLowLatencyController = { on -> - SessionPrefs.setLowLatencyController(this@SessionActivity, on) - lowLatencyController = on - applyLowLatency() - }, - onLowLatencyTouch = { on -> - SessionPrefs.setLowLatencyTouch(this@SessionActivity, on) - lowLatencyTouch = on + lowLatency = lowLatency, + onLowLatency = { on -> + SessionPrefs.setLowLatency(this@SessionActivity, on) + lowLatency = on applyLowLatency() }, onOsc = { v -> @@ -938,6 +1080,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true }, + onScreenKeys = { drawerOpen = false; screenKeys?.startEditing() }, + screenKeysShown = screenKeysShown, + onScreenKeysShown = { shown -> + screenKeysShown = shown + com.droiddeck.launcher.input.ControllerPrefs.setScreenKeysShown(this@SessionActivity, shown) + screenKeys?.stopEditing() + screenKeys?.visibility = if (shown) View.VISIBLE else View.GONE + }, + onScreenLayouts = { + drawerOpen = false + screenLayoutNames = layoutNames() + screenLayoutsOpen = true + }, onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() }, onSecondScreenMode = ::selectSecondScreenMode, onSecondScreenDisplay = ::selectSecondScreenDisplay, @@ -963,7 +1118,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { pipAutoEnter = on pip.refresh(true) }, - unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null, + unfoldedControls = unfoldedControls, onUnfoldedControls = ::chooseUnfoldedControls, unfoldedControlsWithController = unfoldedControlsWithController, onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController, @@ -1170,7 +1325,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { performBackAction(double = false) } pendingBackAction = pending - uiHandler.postDelayed(pending, 500L) + uiHandler.postDelayed(pending, backDoubleTapMs.toLong()) } private fun performBackAction(double: Boolean) { @@ -1183,7 +1338,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return incoming.action = null setIntent(incoming) - if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide() + if (SessionState.suspended) SessionService.resume(this) + else if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide() } @@ -1248,6 +1404,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { val activeAppId = AgentGuest.activeSteamAppId(this, installedAppIds) val selectedSteamAppId = runCatching { AgentGuest.selectedSteamAppId(this) } AgentGuest.selectedOrActiveInstalledSteamAppId(selectedSteamAppId, activeAppId, installedAppIds) + ?: SessionState.gameId?.toLongOrNull() ?: refresh.requestedAppId } else { refresh.requestedAppId @@ -1494,15 +1651,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (nextTouchMode == SessionPrefs.TOUCH_OFF || !usingTouchpad()) cursorVisible = false } touchMode = nextTouchMode - routedTouchMode = effectiveTouchMode() + val nextRoutedTouchMode = effectiveTouchMode() + if (routedTouchMode != nextRoutedTouchMode) gestureTouchStreamGate.reset() + routedTouchMode = nextRoutedTouchMode frameGen = FrameGen.mode(this) fexPreset = SessionPrefs.fexPreset(this) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) oscMode = SessionPrefs.oscMode(this) backActionsInverted = SessionPrefs.backActionsInverted(this) - lowLatencyController = SessionPrefs.lowLatencyController(this) - lowLatencyTouch = SessionPrefs.lowLatencyTouch(this) + backDoubleTapMs = SessionPrefs.backDoubleTapMs(this) + lowLatency = SessionPrefs.lowLatency(this) padType = SessionPrefs.steamController(this) } @@ -1533,10 +1692,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime" } if (problem == null && resume && !SessionState.stopRequested) { - SessionState.installing = "package" + if (activeInstallWorker === worker) SessionState.installing = "package" SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "package.resuming", mapOf("component" to "package")) - problem = com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, progressAsIs()) - ?.let { getString(R.string.session_package_resume_failed, it) } + val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested } + SessionState.installCancellation = cancellation + problem = try { + com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, cancellation, progressAsIs()) + ?.let { getString(R.string.session_package_resume_failed, it) } + } finally { + if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null + } if (problem == null) SessionEvents.record("package.ready") else failedComponent = "package" } if (problem == null && desktop && !SessionState.stopRequested) { @@ -1681,9 +1846,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { val driverId = if (CompositorHost.isStarted) null else turnip.install() val previous = SessionState.outputSize - val live = if (SessionState.followScreen && !isInPictureInPictureMode) - com.droiddeck.launcher.session.SessionDisplay.followSize(holder.surfaceFrame.width(), holder.surfaceFrame.height()) - else null + val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height()) val size = live ?: if (SessionState.running) previous else glassesOutputSize() ?: outputSize() SessionState.outputSize = size if (!SessionState.running) SessionState.refreshHz = refreshHz() @@ -1740,7 +1903,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { ) onOutputAttached(holder) if (SessionState.running && size != previous) { - Log.i(TAG, "follow screen: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface") + Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface") WaylandCompositor.nativeResizeOutput(size.first, size.second) } if (!SessionState.running) SessionEvents.record("compositor.started") @@ -1752,6 +1915,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { intent.getStringExtra(SessionService.EXTRA_STEAM_UI), intent.getStringExtra(SessionService.EXTRA_STEAM_URL), intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS), + intent.getStringExtra(SessionService.EXTRA_GAME_ID), sessionActivityDisplayId, ) } @@ -1771,15 +1935,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { cancelTouchGestures() Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor") CompositorHost.resize(holder.surface) { applyFrameGen() } - followWindow(width, height) + resizeOutputForWindow(width, height) } } - private fun followWindow(width: Int, height: Int) { - if (!SessionState.followScreen || isInPictureInPictureMode || !CompositorHost.isStarted) return - val size = com.droiddeck.launcher.session.SessionDisplay.followSize(width, height) ?: return + private fun windowOutputSize(width: Int, height: Int): Pair? { + if (isInPictureInPictureMode || width <= 0 || height <= 0) return null + return if (SessionState.followScreen) + com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, controlsBelowWanted()) + else if (glassesScreen == null) outputSize() else null + } + + private fun resizeOutputForWindow(width: Int, height: Int) { + if (!CompositorHost.isStarted) return + val size = windowOutputSize(width, height) ?: return if (size == SessionState.outputSize) return - Log.i(TAG, "follow screen: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}") + Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}") SessionState.outputSize = size val panel = panelBounds() SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1) @@ -1793,11 +1964,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } private fun applyFollowOrientation(config: android.content.res.Configuration) { - val wanted = if (SessionState.followScreen && config.smallestScreenWidthDp >= 600) { - android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER - } else { - SessionPrefs.orientation(this) - } + val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp) if (requestedOrientation != wanted) requestedOrientation = wanted } @@ -1809,6 +1976,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { cancelTouchGestures() applyFollowOrientation(newConfig) applyUnfoldedControls() + resizeOutputForWindow(surfaceW, surfaceH) } override fun surfaceDestroyed(holder: SurfaceHolder) { @@ -1850,7 +2018,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode)) com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN else SessionPrefs.resolutionChoice(this, mode, panel) - return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice) + return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice, + SessionPrefs.portrait(this) && !controlsBelowWanted()) } private fun refreshHz(): Float { @@ -1868,7 +2037,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun mirrorRefreshLimit(): Int = GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null) - private fun outputFpsLimit(): Int = GlassesRendering.fpsLimit(SessionState.fpsLimit, mirrorRefreshLimit()) + private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit()) private fun applyOutputPacing() { Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit())) @@ -1965,7 +2134,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { return } Thread({ - val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) + val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint() runOnUiThread { if (isFinishing || isDestroyed) return@runOnUiThread showEnded(status, hint) @@ -1987,12 +2156,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { repairOffered = hint?.repair == true loading.showEnded( hint?.text ?: stopped, - getString(R.string.session_ended_detail, status, SessionState.logFile?.path ?: getString(R.string.session_ended_no_log)), + getString(R.string.session_ended_detail, status, + SessionState.logFile?.path?.let { android.text.BidiFormatter.getInstance().unicodeWrap(it, android.text.TextDirectionHeuristics.LTR) } + ?: getString(R.string.session_ended_no_log)), ) focusEndedScreen() } private fun releasePads() { + com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this) + backQamInput.cancel() padBridge?.releaseAll() joyConVr?.releaseButtons() } @@ -2026,6 +2199,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { return EndHint(resources.getQuantityString(R.plurals.session_end_runtime_damaged, broken.size, broken.size, broken.first()), repair = true) } + private fun prootFailureHint(): EndHint? { + if (SessionState.failureCode != "PROOT_MISSING") return null + val message = SessionState.failureMessage ?: return null + return EndHint(message) + } + private fun sessionEndHint(log: File?): EndHint? { if (log == null || !log.isFile) return null return try { @@ -2062,10 +2241,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun dispatchKeyEvent(event: KeyEvent): Boolean { when (event.keyCode) { - KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> + KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> { + val steamVolume = + SessionState.mode == SessionService.MODE_STEAM && SessionState.running && + SessionState.firstFrameSeen && !SessionState.suspended && !ended && + !pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + !gestureSettingsOpen && !screenKeyTextFocus && window.decorView.hasWindowFocus() + if (steamVolume) { + val audio = getSystemService(android.media.AudioManager::class.java) + if (com.droiddeck.launcher.input.SteamVolumeKeys.dispatch(event, !audio.isVolumeFixed) { direction -> + audio.adjustStreamVolume(android.media.AudioManager.STREAM_MUSIC, direction, 0) + }) return true + } return super.dispatchKeyEvent(event) + } + } + val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen && + !SessionState.suspended && padBridge?.canHoldQam() == true + if (backQamInput.onKeyEvent(event, backToQam)) { + pendingBackAction?.let(uiHandler::removeCallbacks) + pendingBackAction = null + return true } if (pipUi) return true + if (screenKeyTextFocus) return super.dispatchKeyEvent(event) val pad = com.droiddeck.launcher.input.JoyCon.normalize(event) if (pad !== event) return dispatchKeyEvent(pad) val fromController = PadBridge.isControllerKeyEvent(event) @@ -2087,6 +2287,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } return super.dispatchKeyEvent(event) } + val drawerShortcutKey = event.deviceId to event.keyCode + if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) && + ((drawerOpen && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) { + if (event.action == KeyEvent.ACTION_DOWN) { + drawerShortcutKeysDown.add(drawerShortcutKey) + if (event.repeatCount == 0) { + releaseDrawerDirection() + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT) sendSteamGuide() else triggerSteamQam() + } + } else if (event.action == KeyEvent.ACTION_UP) { + drawerShortcutKeysDown.remove(drawerShortcutKey) + } + return true + } if (drawerOpen) { if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { @@ -2107,7 +2321,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { return true } val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START || - event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || event.keyCode == KeyEvent.KEYCODE_HOME + event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || HomeGuideInput.isHome(event.keyCode) val resumeKeyId = event.deviceId to event.keyCode if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) { if (event.action == KeyEvent.ACTION_DOWN) { @@ -2178,6 +2392,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (pipUi) return true if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) { drawerControllerActive = false + gestureTouchStreamGate.reset() } return super.dispatchTouchEvent(event) } @@ -2253,9 +2468,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { super.dispatchKeyEvent(event) } + private fun layoutNames(): List = + com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this).keys.sorted() + private fun refreshGestureConfig() { gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame) + gestureTouchStreamGate.reset() if (::touchscreenGestures.isInitialized) touchscreenGestures.configure(gestureConfig) + if (::directTouchHold.isInitialized) directTouchHold.configure(gestureConfig) gesturePointerReady = false recognizedGesture = null } @@ -2543,23 +2763,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun refreshControls() { applyUnfoldedControls() updateOnScreenControls() + screenKeys?.refreshAppearance() + } + + private fun controlsBelowWanted(): Boolean { + if (!::sessionRoot.isInitialized || glassesScreen != null || cardboard.enabled) return false + return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height, + pipUi || isInPictureInPictureMode) } private fun applyUnfoldedControls() { if (!::sessionRoot.isInitialized) return val width = sessionRoot.width val height = sessionRoot.height - val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted( - enabled = unfoldedControls, - foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this), - controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected, - keepWithController = unfoldedControlsWithController, - steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad, - pip = pipUi || isInPictureInPictureMode, - width = width, - height = height, - smallestWidthDp = resources.configuration.smallestScreenWidthDp, - ) + val wanted = controlsBelowWanted() val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height) else FrameLayout.LayoutParams.MATCH_PARENT val params = surfaceView.layoutParams as FrameLayout.LayoutParams @@ -2569,13 +2786,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { else "unfolded controls: game full screen") } var panel = unfoldedPanel + if (panel != null && panel.deckControls != SessionState.deckPad) { + sessionRoot.removeView(panel) + unfoldedPanel = null + panel = null + } if (!wanted) { if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() } return } if (panel == null) { panel = com.droiddeck.launcher.ui.DeckControlsPanel(this, onClose = { chooseUnfoldedControls(false) }, - onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge) + onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge, + portraitDock = !com.droiddeck.launcher.session.SessionDisplay.foldable(this)) sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1) unfoldedPanel = panel updateOnScreenControls() @@ -2628,6 +2851,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (::scrollTouch.isInitialized) scrollTouch.cancel() if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0) if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false + gestureTouchStreamGate.reset() routedTouchMode = next } @@ -2818,6 +3042,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { device.plugged = false uiHandler.postDelayed({ updateOnScreenControls() }, 700) } + view.onStyle = { screenKeys?.refreshAppearance() } + view.onTouchMiss = miss@{ event -> + if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss + event.offsetLocation(view.left - surfaceView.left.toFloat(), view.top - surfaceView.top.toFloat()) + onTouchEvent(event) + } root.addView(view, root.indexOfChild(onScreenControls) + 1) steamTouchControls = view steamTouchAvailable = true @@ -2848,6 +3078,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { controls.visibility = View.GONE steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE } com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false + screenKeys?.followSteam = false applyTouchRouting() return } @@ -2876,6 +3107,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onScreenButtonsVisible = show val drawn = show && !keyboardCoversPad() if (steam != null) { + screenKeys?.followSteam = drawn if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE } if (!drawn) steam.releaseAll() steam.visibility = if (drawn) View.VISIBLE else View.GONE @@ -2884,6 +3116,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden") return } + screenKeys?.followSteam = false if (drawn == (controls.visibility == View.VISIBLE)) return if (!drawn) controls.releaseAll() controls.visibility = if (drawn) View.VISIBLE else View.GONE @@ -2969,6 +3202,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { pendingBackAction = null releaseDrawerDirection() onScreenControls?.releaseAll() + screenKeys?.releaseAll() releasePads() touchpad.cancel() scrollTouch.cancel() @@ -3005,7 +3239,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) { super.onPictureInPictureModeChanged(inPip, newConfig) if (::pip.isInitialized) pip.changed(inPip) - if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH) + if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH) applyUnfoldedControls() updateGlassesScreen() } @@ -3024,6 +3258,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { started = true refreshActivityDisplayId() displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper())) + for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) { + contentResolver.registerContentObserver(android.provider.Settings.System.getUriFor(name), false, refreshSettingObserver) + } refreshSecondScreenDisplays() if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) startedScreens++ @@ -3038,6 +3275,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { started = false updateHandCamera() displayManager.unregisterDisplayListener(displayListener) + contentResolver.unregisterContentObserver(refreshSettingObserver) closeSecondScreen(reset = false) startedScreens = (startedScreens - 1).coerceAtLeast(0) updateGlassesScreen() @@ -3081,6 +3319,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (!SessionState.suspended) pausedFrame = null com.droiddeck.launcher.ui.Motion.refresh(this) refreshHomeApp() + if (::memoryHud.isInitialized && SessionState.running && SessionState.firstFrameSeen) memoryHud.refresh() if (intent?.action == SessionService.ACTION_RESUME) { intent.action = null SessionService.resume(this) @@ -3092,6 +3331,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onScreenControls?.reload() controllerSettings = ControllerPrefs.read(this) resumed = true + com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this, + enabled = { + resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen && + !achievementsOpen && !gestureSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended && + SessionState.mode == SessionService.MODE_STEAM && padBridge != null + }, + setPressed = { padBridge?.setHomeGuidePressed(it) }, + onCancel = { padBridge?.cancelHomeGuide() }, + ) updatePointerCapture() if (!pipUi) sessionClipboard.start() updatePadMotion() @@ -3103,7 +3351,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onPause() { + com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) if (runtimeRemovalBlocked) { super.onPause(); return } + backQamInput.cancel() capturePausedFrame() sessionClipboard.stop() if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel() @@ -3478,15 +3728,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } private fun unbufferedSources() = - if (lowLatencyTouch) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES + if (lowLatency) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES private fun applyLowLatency() { - com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatencyController, lowLatencyTouch) + com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatency) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) window.decorView.requestUnbufferedDispatch(unbufferedSources()) } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) + if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this) + if (!hasFocus) backQamInput.cancel() if (!hasFocus && ::padMouse.isInitialized) padMouse.reset() if (runtimeRemovalBlocked) return if (!hasFocus) { @@ -3526,12 +3778,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { SessionEvents.firstFrame() if (SessionState.mode == SessionService.MODE_STEAM) SteamRepair.clientShown(this) runOnUiThread { + if (isFinishing || isDestroyed) return@runOnUiThread loading.visible = false hud.start() + memoryHud.start() } } override fun onDestroy() { + com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) + backQamInput.cancel() steamVrRecovery.close() uiHandler.removeCallbacks(steamTouchRetry) if (runtimeRemovalBlocked) { super.onDestroy(); return } @@ -3545,6 +3801,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { glassesScreen?.let { screen -> glassesScreen = null; runCatching { screen.dismiss() } } headTracker?.stop() if (::hud.isInitialized) hud.stop() + if (::memoryHud.isInitialized) memoryHud.stop() joyConVr?.close() joyConVr = null handCamera?.stop() diff --git a/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt b/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt index 8459bc7d95..5eb9ff4500 100644 --- a/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt @@ -29,6 +29,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl private var pending: AppUpdates.Release? = null private var lastCheck = 0L private var request = 0 + @Volatile private var session = -1 fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission) @@ -87,13 +88,14 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return } if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return } error = null + session = -1 stage = activity.getString(R.string.upd_stage_downloading) percent = 0 Thread({ val result = runCatching { val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } } ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 } - SelfInstaller.install(activity, file) + SelfInstaller.install(activity, file) { id -> session = id } } result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } } }, "app-update-install").start() @@ -101,13 +103,15 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { + if (intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1).let { it < 0 || it != session }) return when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) { PackageInstaller.STATUS_PENDING_USER_ACTION -> { val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java) else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT) - if (confirm == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return } + val safe = confirm?.let { SelfInstaller.safeConfirmIntent(activity, it) } + if (safe == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return } stage = activity.getString(R.string.upd_stage_confirm) - activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + if (runCatching { activity.startActivity(safe) }.isFailure) { stage = null; error = activity.getString(R.string.upd_not_offered) } } PackageInstaller.STATUS_SUCCESS -> stage = null else -> { diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt index 5f7f092628..0842f6b5a4 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt @@ -3,9 +3,13 @@ package com.droiddeck.launcher.agent import android.content.Context import android.util.Log import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.runtime.ProotFastPath +import com.droiddeck.launcher.session.SessionPhase +import com.droiddeck.launcher.session.SessionState import org.json.JSONArray import org.json.JSONObject import java.io.File +import java.security.MessageDigest import java.nio.file.Files import java.nio.file.LinkOption.NOFOLLOW_LINKS import java.nio.file.StandardOpenOption.READ @@ -55,6 +59,9 @@ object AgentEnv { fun override(context: Context, name: String): JSONObject = synchronized(lock) { AgentAccess.requireCommands(context) if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'") + if (name == "libblfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) { + throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library") + } val source = File(inbox(context), name) if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file") if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first") @@ -67,6 +74,10 @@ object AgentEnv { staged.delete() throw AgentException("OVERRIDE_FAILED", "Could not stage the override") } + if (name == "libblfastpath.so" && !arm64SharedLibrary(staged)) { + staged.delete() + throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library") + } if (!staged.setExecutable(true, false) || !staged.renameTo(target)) { staged.delete() throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs") @@ -76,6 +87,40 @@ object AgentEnv { state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name)))) save(context, state) state.put("installed", "$GUEST_BIN/$name") + if (name == "libblfastpath.so") { + val digest = MessageDigest.getInstance("SHA-256") + target.inputStream().use { input -> + val buffer = ByteArray(65536) + while (true) { + val count = input.read(buffer) + if (count < 0) break + digest.update(buffer, 0, count) + } + } + state.put("sha256", digest.digest().joinToString("") { "%02x".format(it) }) + } + state + } + + fun fastPathLibrary(context: Context): String = synchronized(lock) { + if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY + if ("libblfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY + val file = File(bin(context), "libblfastpath.so") + if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY + "$GUEST_BIN/libblfastpath.so" + } + + private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input -> + val header = ByteArray(20) + var count = 0 + while (count < header.size) { + val read = input.read(header, count, header.size - count) + if (read < 0) return@use false + count += read + } + header.take(7) == listOf(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1) && + header[16] == 3.toByte() && header[17] == 0.toByte() && + header[18] == 183.toByte() && header[19] == 0.toByte() } fun beginSession(context: Context): List = synchronized(lock) { @@ -86,13 +131,13 @@ object AgentEnv { val state = load(context) val active = strings(state.optJSONArray("pending")) val overrides = strings(state.optJSONArray("pendingOverrides")) - state.put("active", JSONArray(active)).put("pending", JSONArray()) - state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray()) - save(context, state) bin(context).listFiles() ?.filter { it.name !in overrides }?.forEach { it.delete() } val lines = strings(state.optJSONArray("persistent")) + active - val withPath = if (overrides.isEmpty()) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}" + val withPath = if (overrides.none { it != "libblfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}" + state.put("active", JSONArray(active)).put("pending", JSONArray()) + state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray()) + save(context, state) if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}") withPath } diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java index 3b73b6a3c9..32d5f5189e 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java @@ -26,6 +26,7 @@ public class PulseAudioComponent extends SessionPart { private final File workingDir; + private final File deviceControls; private File logFile; private final String micFifoPath; private volatile int pid = -1; @@ -36,6 +37,8 @@ public class PulseAudioComponent extends SessionPart { public PulseAudioComponent(Context context, String micFifoPath) { this.workingDir = new File(context.getFilesDir(), "pulseaudio"); + this.deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent.directory( + com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)); this.micFifoPath = micFifoPath; } @@ -94,7 +97,7 @@ public class PulseAudioComponent extends SessionPart { config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\"" + socket().getAbsolutePath() + "\""); config.add(".nofail"); - config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0"); + config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls); config.add("set-default-sink DirectAudio"); config.add(".fail"); if (micFifoPath != null && !micFifoPath.isEmpty()) { @@ -139,7 +142,7 @@ public class PulseAudioComponent extends SessionPart { } else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) { line = "== client sink: DirectAudio (module-directaudio-native-sink)"; } else { - boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null + boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null && pactl("set-default-sink", "AAudioSink") != null; line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)" : "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound"; diff --git a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt index 3021b7196d..7b8536202d 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt @@ -1,11 +1,32 @@ package com.droiddeck.launcher.core import android.content.Context +import android.content.pm.ActivityInfo +import com.droiddeck.launcher.R object AppUiPrefs { const val DEFAULT_SCALE = 100 val scales = listOf(75, 85, 100, 115, 125, 150) + val orientationOptions = listOf( + ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto, + ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait, + ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto, + ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape, + ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse, + ) + + fun orientation(context: Context): Int = + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE) + .getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_USER) + .takeIf { value -> orientationOptions.any { it.first == value } } + ?: ActivityInfo.SCREEN_ORIENTATION_USER + + fun setOrientation(context: Context, value: Int) { + require(orientationOptions.any { it.first == value }) + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply() + } + internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE fun scale(context: Context): Int = normalizeScale( diff --git a/app/src/main/java/com/droiddeck/launcher/core/BackgroundAppLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/BackgroundAppLimit.kt new file mode 100644 index 0000000000..02447f360c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/BackgroundAppLimit.kt @@ -0,0 +1,59 @@ +package com.droiddeck.launcher.core + +import android.content.Context +import android.util.Log +import java.util.concurrent.Executors + +object BackgroundAppLimit { + private const val TAG = "BackgroundAppLimit" + const val OFF = -1 + val CHOICES = listOf(OFF, 4, 1, 0) + private const val KEY = "max_cached_processes" + private const val STATE = "background-app-limit" + private const val APPLIED = "applied" + private const val PREVIOUS = "previous" + + private val worker = Executors.newSingleThreadExecutor { Thread(it, "background-app-limit").apply { isDaemon = true } } + + internal fun readCommand() = "device_config get activity_manager $KEY" + internal fun setCommand(limit: Int): String { + require(limit in 0..1024) + return "device_config put activity_manager $KEY $limit" + } + internal fun restoreCommand(previous: String?) = + if (previous == null) "device_config delete activity_manager $KEY" else "device_config put activity_manager $KEY $previous" + + internal fun parse(output: String): String? = output.trim().takeIf { it.toIntOrNull() != null } + + private fun state(context: Context) = context.applicationContext.getSharedPreferences(STATE, Context.MODE_PRIVATE) + + fun applied(context: Context): Boolean = state(context).getBoolean(APPLIED, false) + + fun applyAsync(context: Context, limit: Int) { + val app = context.applicationContext + worker.execute { + runCatching { + if (!applied(app)) { + val previous = parse(WirelessAdbFix.shell(app, readCommand())) + check(state(app).edit().putBoolean(APPLIED, true).putString(PREVIOUS, previous).commit()) { "previous value not saved" } + } + WirelessAdbFix.shell(app, setCommand(limit)) + }.onSuccess { Log.i(TAG, "at most $limit cached app(s) while the session runs") } + .onFailure { Log.w(TAG, "limit not set: ${it.message}") } + } + } + + fun restoreAsync(context: Context) { + val app = context.applicationContext + worker.execute { + if (!applied(app)) return@execute + val previous = state(app).getString(PREVIOUS, null) + runCatching { WirelessAdbFix.shell(app, restoreCommand(previous)) } + .onSuccess { + state(app).edit().putBoolean(APPLIED, false).remove(PREVIOUS).commit() + Log.i(TAG, "cached-app limit put back (${previous ?: "Android's own"})") + } + .onFailure { Log.w(TAG, "limit not put back yet: ${it.message}") } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index 058b07dd5d..d587ecb7cc 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -256,8 +256,13 @@ object DeviceReport { EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") } k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up") k("gamescope realtime", SessionPrefs.gamescopeRealtime(context)) + k("zRAM: compress Steam during games", SessionPrefs.zramClient(context)) + k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" }) + k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" }) k("proot without seccomp", SessionPrefs.prootNoSeccomp(context)) k("proot fast path", SessionPrefs.prootFastPath(context)) + k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path) + k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context)) k("Guest host name", SessionPrefs.guestHostname(context)) k("DirectAudio for games", SessionPrefs.directAudio(context)) k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context)) diff --git a/app/src/main/java/com/droiddeck/launcher/core/DownloadSource.kt b/app/src/main/java/com/droiddeck/launcher/core/DownloadSource.kt index 870e8ed424..b11e3113af 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DownloadSource.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DownloadSource.kt @@ -3,6 +3,8 @@ package com.droiddeck.launcher.core import android.content.Context import android.content.SharedPreferences import java.net.HttpURLConnection +import java.net.InetSocketAddress +import java.net.Proxy import java.net.URL import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CountDownLatch @@ -20,6 +22,7 @@ object DownloadSource { private const val KEY_MODE = "mode" private const val KEY_MIRROR = "mirror" private const val KEY_CUSTOM = "custom" + private const val KEY_PROXY = "proxy" private const val KEY_FASTEST = "fastest" private const val PROBE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/README.md" @@ -175,6 +178,22 @@ object DownloadSource { prefs(context)?.edit()?.putString(KEY_CUSTOM, normalizePrefix(prefix))?.apply() } + fun proxyHostPort(context: Context): String = prefs(context)?.getString(KEY_PROXY, "") ?: "" + + fun setProxy(context: Context, value: String) { + prefs(context)?.edit()?.putString(KEY_PROXY, normalizeProxy(value))?.apply() + } + + /** An HTTP proxy every Downloader connection uses, or null when none is configured. */ + fun httpProxy(): Proxy? = proxyOf(prefs()?.getString(KEY_PROXY, "") ?: "") + + internal fun proxyOf(value: String): Proxy? { + val host = value.substringBefore(':') + val port = value.substringAfter(':', "").toIntOrNull() ?: return null + if (host.isEmpty()) return null + return Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port)) + } + fun reset(context: Context) { lastGood = null prefs(context)?.edit()?.clear()?.apply() @@ -205,4 +224,11 @@ object DownloadSource { if (trimmed.isEmpty() || trimmed.startsWith("http://")) return "" return if (trimmed.startsWith("https://")) trimmed else "https://$trimmed" } + + internal fun normalizeProxy(value: String): String { + val trimmed = value.trim().removePrefix("http://").trimEnd('/') + val host = trimmed.substringBefore(':') + val port = trimmed.substringAfter(':', "").toIntOrNull() ?: 0 + return if (host.isNotEmpty() && port in 1..65535) "$host:$port" else "" + } } diff --git a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java index 7a88f6beb4..31e8f45f55 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java +++ b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java @@ -11,6 +11,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; +import java.net.Proxy; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; @@ -151,11 +152,16 @@ public final class Downloader { // A cancel is not a source failure: no other mirror, and no DownloadSource.failed(). if (outcome == Outcome.CANCELLED) return false; if (outcome == Outcome.DONE) { - if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) { - Log.w(TAG, "checksum mismatch from " + source + "; trying another source"); - if (!discardPartial(destination, identity)) return false; - continue; + if (expectedSha256 != null) { + String actualSha256 = Hashes.sha256(destination); + if (isCancelled(cancelled)) return false; + if (!expectedSha256.equalsIgnoreCase(actualSha256)) { + Log.w(TAG, "checksum mismatch from " + source + "; trying another source"); + if (!discardPartial(destination, identity)) return false; + continue; + } } + if (isCancelled(cancelled)) return false; resumeFile(destination).delete(); DownloadSource.INSTANCE.succeeded(source); if (progress != null) progress.accept(1f); @@ -384,7 +390,10 @@ public final class Downloader { } private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + // An explicit Proxy routes the connection through the app setting instead of the system-wide proxy. + Proxy proxy = DownloadSource.INSTANCE.httpProxy(); + HttpURLConnection connection = (HttpURLConnection) (proxy != null + ? new URL(url).openConnection(proxy) : new URL(url).openConnection()); connection.setConnectTimeout(CONNECT_TIMEOUT_MS); connection.setReadTimeout(readTimeoutMs); connection.setInstanceFollowRedirects(true); diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt index 3ad45c1fa6..bcf3a0448c 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt @@ -14,6 +14,8 @@ object GameEnvironmentOptions { Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")), Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")), Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")), + Option("PROTON_DXVK_D3D8", "1", R.string.game_env_dxvk_d3d8, Type.TOGGLE, listOf("0", "1")), + Option("WINE_D3D_CONFIG", "renderer=vulkan", R.string.game_env_wined3d_renderer, Type.CHOICE, listOf("renderer=vulkan", "renderer=gl")), Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")), Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")), Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")), @@ -32,6 +34,7 @@ object GameEnvironmentOptions { Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT), Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT), Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER), + Option("DROIDDECK_GAME_CORES", "", R.string.game_env_cores, Type.TEXT), Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")), Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")), Option("WINEDLLOVERRIDES", "", 0, Type.TEXT), diff --git a/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt b/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt new file mode 100644 index 0000000000..8cbf9bf39d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt @@ -0,0 +1,24 @@ +package com.droiddeck.launcher.core + +import android.content.Context +import android.net.Uri +import android.provider.Settings + +object GlobalSettings { + // Settings.Global caches values in-process and misses deletions made over adb; ask the provider directly. + fun read(context: Context, name: String): String? { + val uri = Uri.withAppendedPath(Settings.Global.CONTENT_URI, name) + context.contentResolver.query(uri, arrayOf(Settings.NameValueTable.VALUE), null, null, null)?.use { cursor -> + return if (cursor.moveToFirst()) cursor.getString(0) else null + } + return Settings.Global.getString(context.contentResolver, name) + } + + fun isOn(context: Context, name: String): Boolean = + runCatching { read(context, name)?.trim() == "1" }.getOrDefault(false) + + fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED) + + // Settings.Global.ADB_WIFI_ENABLED is hidden; the key is stable since Android 11. + fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled") +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt index 4a8b12934e..0757192461 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt @@ -8,7 +8,11 @@ object HostProcess { private const val TAG = "HostProcess" @JvmStatic - fun start(command: String, env: Array?, dir: File?, onExit: Consumer?, onLine: Consumer?): Int { + fun start(command: String, env: Array?, dir: File?, onExit: Consumer?, onLine: Consumer?): Int = + start(command, env, dir, onExit, onLine, null) + + @JvmStatic + fun start(command: String, env: Array?, dir: File?, onExit: Consumer?, onLine: Consumer?, outputFile: File?): Int { val argv = split(command) if (argv.isEmpty()) return -1 return try { @@ -19,7 +23,10 @@ object HostProcess { if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1) } builder.redirectErrorStream(true) - if (onLine == null) builder.redirectOutput(File("/dev/null")) + if (onLine == null) { + if (outputFile == null) builder.redirectOutput(File("/dev/null")) + else builder.redirectOutput(ProcessBuilder.Redirect.appendTo(outputFile)) + } val process = builder.start() val pid = pidOf(process) Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)") diff --git a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt index 491101dba2..20073c4ca3 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt @@ -76,7 +76,7 @@ object LogRedactor { private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)" private val ACCOUNT_KV = Regex( - "(?i)(? setChildProcessLimit(appContext, host, port, enabled) } + } + + fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null + + fun clearCachedApps(context: Context) { + shell(context, "am kill-all") + } + + fun shell(context: Context, command: String): String { + var output = "" + withSavedPairing(context) { appContext, host, port -> + loadOrCreateIdentity(appContext) + Kadb.create(host, port).use { adb -> + val result = adb.shell(command) + check(result.exitCode == 0) { result.allOutput.ifBlank { appContext.getString(R.string.adbfix_command_failed, result.exitCode) } } + output = result.output + } + saveConnection(appContext, host, port) + } + return output + } + + private fun withSavedPairing(context: Context, action: (Context, String, Int) -> Unit) { val appContext = context.applicationContext val saved = savedConnection(appContext) ?: error(appContext.getString(R.string.adbfix_no_pairing)) val cachedPort = saved.port if (cachedPort != null) { - val cachedResult = runCatching { - setChildProcessLimit(appContext, saved.host, cachedPort, enabled) - } + val cachedResult = runCatching { action(appContext, saved.host, cachedPort) } if (cachedResult.isSuccess) return val discoveredPort = findConnectPort(appContext, saved.host) if (discoveredPort != null && discoveredPort != cachedPort) { - setChildProcessLimit(appContext, saved.host, discoveredPort, enabled) + action(appContext, saved.host, discoveredPort) } else { cachedResult.getOrThrow() } } else { val discoveredPort = findConnectPort(appContext, saved.host) ?: error(appContext.getString(R.string.adbfix_enter_address)) - setChildProcessLimit(appContext, saved.host, discoveredPort, enabled) + action(appContext, saved.host, discoveredPort) } } } 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 c924f85329..2d6adb902b 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt @@ -184,12 +184,15 @@ class WirelessAdbPairingService : Service() { setSound(null, null) enableVibration(false) }) + manager?.createNotificationChannel(NotificationChannel(PROGRESS_CHANNEL_ID, getString(R.string.adbpair_progress_channel_name), + NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) }) val open = PendingIntent.getActivity(this, 0, Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), PendingIntent.FLAG_IMMUTABLE) val cancel = PendingIntent.getService(this, 1, Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE) - val builder = Notification.Builder(this, CHANNEL_ID) + val quiet = stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working + val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID) .setSmallIcon(R.drawable.ic_stat_session) .setContentIntent(open) .setShowWhen(false) @@ -239,6 +242,7 @@ class WirelessAdbPairingService : Service() { companion object { private const val CHANNEL_ID = "wireless-adb-pairing" + private const val PROGRESS_CHANNEL_ID = "wireless-adb-pairing-progress" private const val NOTIFICATION_ID = 3 private const val PAIRING_TYPE = "_adb-tls-pairing._tcp" private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE" diff --git a/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt b/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt index bcba0189bd..b1d93fdaba 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt @@ -1,5 +1,7 @@ package com.droiddeck.launcher.files +import androidx.compose.foundation.shape.CircleShape +import com.droiddeck.launcher.ui.focusGlide import android.content.res.Configuration import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.background @@ -181,14 +183,14 @@ fun CollapsibleRail( modifier = Modifier.weight(1f), ) if (!state.portraitLocked) { - IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp)) { + IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp).focusGlide(CircleShape)) { Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp) } } } } if (collapsed && !state.portraitLocked) { - IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp)) { + IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp).focusGlide(CircleShape)) { Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp) } } @@ -197,14 +199,14 @@ fun CollapsibleRail( if (collapsed) { Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) { links.forEach { link -> - IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp)) { + IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp).focusGlide(CircleShape)) { Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp)) } } } } else { links.forEach { link -> - TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) { + TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp).focusGlide(CircleShape)) { Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp)) Spacer(Modifier.width(6.dp)) Text(link.label, fontSize = 12.sp) @@ -250,11 +252,11 @@ fun CollapsibleRail( if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f), shape, ) - .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick) + .focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick) .padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp) } else { base - .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick) + .focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick) .background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent) .padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp) } @@ -361,6 +363,7 @@ private fun TopTabCell( modifier = modifier .clip(RoundedCornerShape(9.dp)) .background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent) + .focusGlide(RoundedCornerShape(9.dp)) .then( if (isTab) { Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick) diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt index 1425a78e7e..873a413ad4 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt @@ -21,7 +21,7 @@ class FileManagerActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this) + requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this) if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1) } diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt index e6289a3b98..3fb876ac23 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt @@ -1,5 +1,7 @@ package com.droiddeck.launcher.files +import androidx.compose.foundation.shape.CircleShape +import com.droiddeck.launcher.ui.focusGlide import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background @@ -39,7 +41,7 @@ import androidx.compose.material.icons.filled.Storage import androidx.compose.material.icons.filled.Image import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults -import androidx.compose.material3.DropdownMenu +import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -105,12 +107,14 @@ private fun FileContextMenuItems( text = { Text(stringResource(R.string.fm_select)) }, leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) }, onClick = { onDismissMenu(); onSelect() }, + modifier = Modifier.focusGlide(), ) MenuItemDivider() DropdownMenuItem( text = { Text(stringResource(R.string.fm_properties)) }, leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) }, onClick = { onDismissMenu(); onProperties() }, + modifier = Modifier.focusGlide(), ) MenuItemDivider() if (isDir) { @@ -124,6 +128,7 @@ private fun FileContextMenuItems( ) }, onClick = { onToggleFavorite() }, + modifier = Modifier.focusGlide(), ) MenuItemDivider() } @@ -131,24 +136,28 @@ private fun FileContextMenuItems( text = { Text(stringResource(R.string.fm_rename)) }, leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) }, onClick = { onDismissMenu(); onRename() }, + modifier = Modifier.focusGlide(), ) MenuItemDivider() DropdownMenuItem( text = { Text(stringResource(R.string.fm_copy)) }, leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) }, onClick = { onDismissMenu(); onCopy() }, + modifier = Modifier.focusGlide(), ) MenuItemDivider() DropdownMenuItem( text = { Text(stringResource(R.string.fm_cut)) }, leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) }, onClick = { onDismissMenu(); onCut() }, + modifier = Modifier.focusGlide(), ) MenuItemDivider() DropdownMenuItem( text = { Text(stringResource(R.string.common_delete)) }, leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) }, onClick = { onDismissMenu(); onDelete() }, + modifier = Modifier.focusGlide(), ) } @@ -193,7 +202,7 @@ internal fun FileItemRow( modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 3.dp) - .combinedClickable(role = androidx.compose.ui.semantics.Role.Button, + .focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button, onClick = { if (selectionMode) onToggleSelect() else onTap() }, onLongClick = onLongPress, ), @@ -212,7 +221,7 @@ internal fun FileItemRow( modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp), ) { if (selectionMode) { - androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() }) + androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() }, modifier = Modifier.focusGlide()) Spacer(Modifier.width(4.dp)) } when { @@ -270,7 +279,7 @@ internal fun FileItemRow( ) } if (showActions) Box { - IconButton(onClick = onMenu) { + IconButton(onClick = onMenu, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Filled.MoreVert, stringResource(R.string.fm_actions), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp)) } DropdownMenu( @@ -302,7 +311,7 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) { modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 3.dp) - .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap), + .focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap), shape = RoundedCornerShape(10.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline), @@ -370,6 +379,7 @@ internal fun FavoritesList( TextButton( onClick = onPinCurrent, enabled = !currentAlreadyPinned, + modifier = Modifier.focusGlide(CircleShape), ) { Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp)) Spacer(Modifier.width(6.dp)) @@ -422,7 +432,7 @@ private fun FavoriteCard( modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 3.dp) - .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump), + .focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump), shape = RoundedCornerShape(10.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline), @@ -480,7 +490,7 @@ private fun FavoriteCard( overflow = TextOverflow.Ellipsis, ) } - IconButton(onClick = onUnpin) { + IconButton(onClick = onUnpin, modifier = Modifier.focusGlide(CircleShape)) { Icon( Icons.Filled.Star, contentDescription = stringResource(R.string.fm_unpin_favorite), @@ -526,7 +536,7 @@ internal fun FileGridTile( Card( modifier = Modifier .padding(4.dp) - .combinedClickable(role = androidx.compose.ui.semantics.Role.Button, + .focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button, onClick = { if (selectionMode) onToggleSelect() else onTap() }, onLongClick = onLongPress, ), @@ -570,7 +580,7 @@ internal fun FileGridTile( androidx.compose.material3.Checkbox( checked = selected, onCheckedChange = { onToggleSelect() }, - modifier = Modifier.align(Alignment.TopStart), + modifier = Modifier.align(Alignment.TopStart).focusGlide(), ) } } diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt index 627761c2da..4ea75ab1ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -1,9 +1,13 @@ package com.droiddeck.launcher.files +import androidx.compose.foundation.shape.CircleShape +import com.droiddeck.launcher.ui.focusGlide import android.widget.Toast import androidx.activity.compose.BackHandler import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.rememberScrollState import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -19,6 +23,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.grid.GridCells @@ -50,7 +55,7 @@ import androidx.compose.material.icons.filled.Description import androidx.compose.material.icons.filled.Image import androidx.compose.material.icons.filled.SportsEsports import androidx.compose.material3.Button -import androidx.compose.material3.DropdownMenu +import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider @@ -70,6 +75,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -99,7 +105,9 @@ import kotlinx.coroutines.withContext import java.io.File import java.util.Date -private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK } +private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK, UP } + +private const val HISTORY_LIMIT = 50 internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean = currentDir != currentRoot && currentDir.parentFile?.exists() == true @@ -193,10 +201,17 @@ fun FileManagerScreen( var favTick by remember { mutableIntStateOf(0) } var listingJob by remember { mutableStateOf(null) } + val history = remember { mutableStateListOf>() } + var shownRoot by remember { mutableStateOf(initialRoot) } - fun loadDirectory(dir: File, resetScroll: Boolean = true) { + fun loadDirectory(dir: File, resetScroll: Boolean = true, record: Boolean = true) { if (cancellingNavigation) return + if (record && dir != currentDir) { + history.add(currentDir to shownRoot) + if (history.size > HISTORY_LIMIT) history.removeAt(0) + } currentDir = dir + shownRoot = currentRoot if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply() listingJob?.cancel() listingJob = scope.launch { @@ -251,6 +266,18 @@ fun FileManagerScreen( FileManagerNavigation.EXIT -> onExit?.invoke() FileManagerNavigation.RETURN_TO_START -> returnToStart() FileManagerNavigation.BACK -> { + if (showFavorites) showFavorites = false + else { + while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex) + val previous = history.removeLastOrNull() + if (previous != null) { + currentRoot = previous.second + loadDirectory(previous.first, record = false) + } else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) } + else onExit?.invoke() + } + } + FileManagerNavigation.UP -> { if (showFavorites) showFavorites = false else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it) } else onExit?.invoke() @@ -263,7 +290,7 @@ fun FileManagerScreen( if (isOperationActive()) pendingNavigation = action else navigate(action) } - BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot) { + BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) { requestNavigation(FileManagerNavigation.BACK) } @@ -296,10 +323,10 @@ fun FileManagerScreen( navigate(action) } } - }) { Text(stringResource(R.string.fm_accept)) } + }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_accept)) } }, dismissButton = { - TextButton(onClick = { pendingNavigation = null }) { + TextButton(onClick = { pendingNavigation = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_decline)) } }, @@ -487,15 +514,16 @@ fun FileManagerScreen( onValueChange = { folderName = it }, label = { Text(stringResource(R.string.fm_folder_name)) }, singleLine = true, + modifier = Modifier.focusGlide(), ) }, confirmButton = { TextButton(onClick = { showNewFolderDialog = false if (folderName.isNotBlank()) createFolder(currentDir, folderName) - }) { Text(stringResource(R.string.fm_create)) } + }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_create)) } }, - dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text(stringResource(R.string.common_cancel)) } }, + dismissButton = { TextButton(onClick = { showNewFolderDialog = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } @@ -510,6 +538,7 @@ fun FileManagerScreen( onValueChange = { newName = it }, label = { Text(stringResource(R.string.fm_new_name)) }, singleLine = true, + modifier = Modifier.focusGlide(), ) }, confirmButton = { @@ -517,9 +546,9 @@ fun FileManagerScreen( val file = renameTarget renameTarget = null if (file != null && newName.isNotBlank()) performRename(file, newName) - }) { Text(stringResource(R.string.fm_rename)) } + }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_rename)) } }, - dismissButton = { TextButton(onClick = { renameTarget = null }) { Text(stringResource(R.string.common_cancel)) } }, + dismissButton = { TextButton(onClick = { renameTarget = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } @@ -541,9 +570,9 @@ fun FileManagerScreen( TextButton(onClick = { selectedEntry = null performDelete(file) - }) { Text(stringResource(R.string.common_delete)) } + }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) } }, - dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text(stringResource(R.string.common_cancel)) } }, + dismissButton = { TextButton(onClick = { selectedEntry = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } @@ -589,9 +618,9 @@ fun FileManagerScreen( Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show() } } - }) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) } + }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) } }, - dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text(stringResource(R.string.common_cancel)) } }, + dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } @@ -614,6 +643,7 @@ fun FileManagerScreen( androidx.compose.material3.Checkbox( checked = conflictApplyToAll, onCheckedChange = { conflictApplyToAll = it }, + modifier = Modifier.focusGlide(), ) Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp) } @@ -626,7 +656,7 @@ fun FileManagerScreen( ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip), ).forEach { (choice, label) -> TextButton( - modifier = Modifier.fillMaxWidth(), + modifier = Modifier.fillMaxWidth().focusGlide(CircleShape), onClick = { conflictChoice = choice; pendingConflict = null }, ) { Text(label, modifier = Modifier.fillMaxWidth()) } } @@ -634,13 +664,14 @@ fun FileManagerScreen( }, confirmButton = {}, dismissButton = { - TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) { + TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } + val compactToolbar = LocalConfiguration.current.screenWidthDp < 600 Column(modifier = Modifier.fillMaxSize()) { if (pickMode && !pickerTitle.isNullOrEmpty()) { Text( @@ -659,7 +690,7 @@ fun FileManagerScreen( onClick = { onPick?.invoke(currentDir) }, modifier = Modifier .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), + .padding(horizontal = 16.dp, vertical = 8.dp).focusGlide(CircleShape), ) { Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp)) Spacer(Modifier.width(8.dp)) @@ -671,9 +702,10 @@ fun FileManagerScreen( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.surfaceContainer) + .then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier) .padding(horizontal = 8.dp, vertical = 6.dp), ) { - IconButton(onClick = { requestNavigation(FileManagerNavigation.BACK) }, enabled = canGoUp && !cancellingNavigation) { + IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary) } @@ -722,6 +754,7 @@ fun FileManagerScreen( ).show() } }, + modifier = Modifier.focusGlide(), ) } linuxRoot?.let { root -> @@ -732,6 +765,7 @@ fun FileManagerScreen( Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp)) }, onClick = { showDriveMenu = false; openDrive(root) }, + modifier = Modifier.focusGlide(), ) } } @@ -747,10 +781,10 @@ fun FileManagerScreen( fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), + modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f), ) } else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) { - Spacer(Modifier.weight(1f)) + if (!compactToolbar) Spacer(Modifier.weight(1f)) } else { Text( text = currentDir.name.ifBlank { currentDir.absolutePath }, @@ -759,12 +793,12 @@ fun FileManagerScreen( fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), + modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f), ) } if (launchDir != null) { - IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation) { + IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary) } if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp)) @@ -776,7 +810,7 @@ fun FileManagerScreen( onClick = { showNewFolderDialog = true }, border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)), contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp), - modifier = Modifier.height(32.dp), + modifier = Modifier.height(32.dp).focusGlide(CircleShape), ) { Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp)) Spacer(Modifier.width(5.dp)) @@ -786,18 +820,18 @@ fun FileManagerScreen( IconButton(onClick = { gridView = !gridView browsePrefs.edit().putBoolean("fmGridView", gridView).apply() - }) { + }, modifier = Modifier.focusGlide(CircleShape)) { Icon( if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView, if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view), tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } - IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) { + IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant) } Box { - IconButton(onClick = { showSortMenu = true }) { + IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant) } DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) { @@ -814,6 +848,7 @@ fun FileManagerScreen( showSortMenu = false loadDirectory(currentDir, resetScroll = false) }, + modifier = Modifier.focusGlide(), ) } HorizontalDivider(color = MaterialTheme.colorScheme.outline) @@ -824,6 +859,7 @@ fun FileManagerScreen( browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply() showSortMenu = false }, + modifier = Modifier.focusGlide(), ) DropdownMenuItem( text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) }, @@ -833,12 +869,13 @@ fun FileManagerScreen( showSortMenu = false loadDirectory(currentDir, resetScroll = false) }, + modifier = Modifier.focusGlide(), ) } } } - IconButton(onClick = { showFavorites = !showFavorites }) { + IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) { if (showFavorites) { Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary) } else { @@ -846,7 +883,7 @@ fun FileManagerScreen( } } if (!pickMode && onExit != null) { - IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation) { + IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant) } } @@ -858,7 +895,7 @@ fun FileManagerScreen( onValueChange = { searchQuery = it }, singleLine = true, placeholder = { Text(stringResource(R.string.fm_filter_folder), fontSize = 13.sp) }, - modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp), + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).focusGlide(), ) } @@ -896,13 +933,14 @@ fun FileManagerScreen( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f)) + .then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier) .padding(horizontal = 12.dp, vertical = 6.dp), ) { Text( stringResource(R.string.fm_selected_count, selectedPaths.size), color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, - modifier = Modifier.weight(1f), + modifier = if (compactToolbar) Modifier.padding(end = 12.dp) else Modifier.weight(1f), ) val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths } val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths } @@ -913,6 +951,7 @@ fun FileManagerScreen( selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown }, contentPadding = selBarPadding, + modifier = Modifier.focusGlide(CircleShape), ) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) } Spacer(Modifier.width(4.dp)) OutlinedButton( @@ -924,6 +963,7 @@ fun FileManagerScreen( selectedPaths = emptySet() }, contentPadding = selBarPadding, + modifier = Modifier.focusGlide(CircleShape), ) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) } Spacer(Modifier.width(4.dp)) OutlinedButton( @@ -935,6 +975,7 @@ fun FileManagerScreen( selectedPaths = emptySet() }, contentPadding = selBarPadding, + modifier = Modifier.focusGlide(CircleShape), ) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) } Spacer(Modifier.width(4.dp)) OutlinedButton( @@ -942,11 +983,13 @@ fun FileManagerScreen( onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } }, contentPadding = selBarPadding, border = BorderStroke(1.dp, MaterialTheme.colorScheme.error), + modifier = Modifier.focusGlide(CircleShape), ) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) } Spacer(Modifier.width(4.dp)) OutlinedButton( onClick = { selectionMode = false; selectedPaths = emptySet() }, contentPadding = selBarPadding, + modifier = Modifier.focusGlide(CircleShape), ) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) } } } @@ -968,7 +1011,7 @@ fun FileManagerScreen( if (isCutOperation) stringResource(R.string.fm_paste_move_here, what) else stringResource(R.string.fm_paste_here, what), color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f), ) - TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) { + TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp) } } @@ -999,7 +1042,7 @@ fun FileManagerScreen( isOperationRunning = false operationDeterminate = false loadDirectory(currentDir, resetScroll = false) - }) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) } + }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) } } } Spacer(Modifier.height(4.dp)) @@ -1089,7 +1132,7 @@ fun FileManagerScreen( contentPadding = PaddingValues(8.dp), ) { if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) { - ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) }) + ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) }) } items(shownEntries, key = { it.absolutePath }) { file -> val isFav = remember(file.absolutePath, favTick) { @@ -1155,7 +1198,7 @@ fun FileManagerScreen( } else LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) { if (canGoUp) item(key = "..") { - ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) }) + ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) }) } if (entries.isEmpty()) { item { diff --git a/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt b/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt index 498ec504e8..39a83e40e1 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt @@ -25,7 +25,7 @@ class FilePickerActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this) + requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this) if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1) } diff --git a/app/src/main/java/com/droiddeck/launcher/files/FilePropertiesDialog.kt b/app/src/main/java/com/droiddeck/launcher/files/FilePropertiesDialog.kt index f4f8d80fb2..07fbb15606 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FilePropertiesDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FilePropertiesDialog.kt @@ -1,5 +1,7 @@ package com.droiddeck.launcher.files +import androidx.compose.foundation.shape.CircleShape +import com.droiddeck.launcher.ui.focusGlide import android.widget.Toast import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -128,7 +130,7 @@ internal fun FilePropertiesDialog( ) } }, - confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.fm_done)) } }, + confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_done)) } }, ) } @@ -182,6 +184,7 @@ private fun AttributeToggleRow( checked = checked, enabled = enabled, onCheckedChange = onToggle, + modifier = Modifier.focusGlide(), ) } } diff --git a/app/src/main/java/com/droiddeck/launcher/files/OutlinedAlertDialog.kt b/app/src/main/java/com/droiddeck/launcher/files/OutlinedAlertDialog.kt index 3919e89b0d..2eda726c3b 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/OutlinedAlertDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/OutlinedAlertDialog.kt @@ -1,7 +1,7 @@ package com.droiddeck.launcher.files import androidx.compose.foundation.border -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.AlertDialogDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable diff --git a/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt b/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt index 99e9401570..273917b007 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/StorageRoots.kt @@ -29,6 +29,50 @@ object StorageRoots { val seeds = LinkedHashSet() } + private val EXTERNAL_MOUNT_TYPES = setOf( + "vfat", "exfat", "texfat", "ntfs", "ntfs3", "fuseblk", "fuse", "sdcardfs", + ) + + internal data class MountPoint(val target: File, val type: String) + + internal fun parseMountPoints(mounts: String): List { + val out = ArrayList() + for (line in mounts.lineSequence()) { + val parts = line.split(' ') + if (parts.size < 3) continue + out.add(MountPoint(File(parts[1].replace("\\040", " ")), parts[2].lowercase())) + } + return out.distinct() + } + + internal fun isExternalMount(mount: MountPoint): Boolean { + val path = mount.target.path + val name = when { + path.startsWith("/storage/") -> path.removePrefix("/storage/") + path.startsWith("/mnt/media_rw/") -> path.removePrefix("/mnt/media_rw/") + path.startsWith("/mnt/") -> path.removePrefix("/mnt/") + else -> return false + } + if ('/' in name || name.isEmpty() || name == "emulated" || name == "self") return false + if (mount.type in EXTERNAL_MOUNT_TYPES) { + if (path.startsWith("/mnt/") && !path.startsWith("/mnt/media_rw/")) { + val lower = name.lowercase() + if (!lower.contains("usb") && !lower.contains("otg") && + !lower.contains("udisk") && !lower.contains("disk") + ) return false + } + return true + } + // vold-managed locations only hold removable volumes, whatever the fstype is. + return path.startsWith("/storage/") || path.startsWith("/mnt/media_rw/") + } + + internal fun parseExternalMounts(mounts: String): List = + parseMountPoints(mounts).filter(::isExternalMount).map { it.target } + + fun externalMounts(): List = + runCatching { parseExternalMounts(File("/proc/mounts").readText()) }.getOrDefault(emptyList()) + fun list(context: Context): List { val volumes = LinkedHashMap() @@ -44,21 +88,31 @@ object StorageRoots { val storageManager = context.getSystemService(StorageManager::class.java) storageManager?.storageVolumes.orEmpty() - .filter { isMounted(it.state) } - .forEach { volume -> + .filter { present(it.state) } + .forEachIndexed { index, volume -> val uuid = volume.uuid?.takeIf { it.isNotBlank() } - val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: return@forEach) + val dirName = volume.directory?.name?.takeIf { it.isNotBlank() } + // Unmounted volumes often report neither uuid nor directory; never drop the + // volume or a plugged-in drive stays invisible with no explanation. + val descSlug = volume.getDescription(context)?.trim() + ?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) } + ?.replace(Regex("[^A-Za-z0-9._-]+"), "-") + val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: dirName ?: descSlug ?: "volume-$index") entry.removable = !volume.isPrimary && volume.isRemovable - if (entry.label == null) entry.label = labelFor(context, volume, uuid) + if (entry.label == null) entry.label = labelFor(context, volume, uuid ?: dirName ?: descSlug) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { volume.directory?.let { entry.candidates += it } } - if (uuid != null) { - entry.candidates += File("/storage/$uuid") - entry.candidates += File("/mnt/media_rw/$uuid") + val name = uuid ?: dirName + if (name != null) { + entry.candidates += File("/storage/$name") + entry.candidates += File("/mnt/media_rw/$name") + // Only strict uuid matches own an app directory; a loose match would + // attach another volume's folder to this entry. + if (uuid != null) appDirs.filter { belongsTo(storageManager!!, it, volume) } + .forEach { entry.seeds += it } } - appDirs.filter { belongsTo(storageManager!!, it, volume) }.forEach { entry.seeds += it } } File("/storage").listFiles().orEmpty().forEach { child -> @@ -68,6 +122,13 @@ object StorageRoots { File("/mnt/media_rw").listFiles().orEmpty().forEach { child -> if (child.isDirectory) volumeOf(child.name).candidates += child } + // USB OTG drives do not always appear as storage volumes or under /storage for + // third-party apps, but their kernel mounts are still visible in /proc/mounts. + for (mount in externalMounts()) { + val entry = volumeOf(mount.name) + if (entry.label == null) entry.label = mount.name + entry.candidates += mount + } appDirs.forEach { dir -> val root = volumeRootOf(dir) ?: return@forEach @@ -141,15 +202,19 @@ object StorageRoots { private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String { if (volume.isPrimary) return context.getString(R.string.fm_drive_internal) - if (volume.isRemovable) return context.getString(R.string.fm_drive_sd) val description = volume.getDescription(context)?.trim() - return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) } - ?: uuid + if (!description.isNullOrBlank() && !description.equals("android", ignoreCase = true)) return description + if (volume.isRemovable) return context.getString(R.string.fm_drive_sd) + return uuid ?: context.getString(R.string.fm_drive_storage) } private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX) + private fun present(state: String?): Boolean = + isMounted(state) || state == Environment.MEDIA_UNMOUNTED || state == Environment.MEDIA_CHECKING || + state == Environment.MEDIA_NOFS || state == Environment.MEDIA_UNMOUNTABLE + private fun isMounted(state: String?): Boolean = state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt index 8315c22e9e..28eb1bf723 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt @@ -4,7 +4,9 @@ import android.content.Context import android.graphics.Bitmap import android.util.Log import com.droiddeck.launcher.files.PeIconExtractor +import com.droiddeck.launcher.runtime.BattleNet import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreArt import com.droiddeck.launcher.stores.StoreGameSidecar import org.json.JSONObject @@ -75,14 +77,18 @@ object AddedGameArt { ) } + private fun storeArt(context: Context, game: AddedGames.Game): BattleNet.Art? = + if (game.source != Store.BATTLENET.id) null else game.storeId?.let(BattleNet::title)?.let { BattleNet.art(context, it) } + fun resolve(context: Context, game: AddedGames.Game): Art { val own = local(game) val cache = cacheDir(context, game) + val store = storeArt(context, game) fun cached(name: String) = File(cache, name).takeIf { it.isFile } return Art( - portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: cached("p.jpg") ?: exeArt(context, game, cover = true), - header = chosen(cache, Slot.WIDE) ?: own.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false), - hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: cached("hero.jpg"), + portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: store?.cover ?: cached("p.jpg") ?: exeArt(context, game, cover = true), + header = chosen(cache, Slot.WIDE) ?: own.header ?: store?.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false), + hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: store?.header ?: cached("hero.jpg"), logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"), icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game), ) @@ -91,15 +97,16 @@ object AddedGameArt { fun describe(context: Context, game: AddedGames.Game): List { val own = local(game) val cache = cacheDir(context, game) + val store = storeArt(context, game) fun cached(name: String): Pair? = File(cache, name).takeIf { it.isFile }?.let { f -> f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM) } return Slot.values().map { slot -> chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) } val auto: Pair? = when (slot) { - Slot.COVER -> own.portrait?.let { it to FOLDER } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE } - Slot.WIDE -> own.header?.let { it to FOLDER } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE } - Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: cached("hero.jpg") + Slot.COVER -> own.portrait?.let { it to FOLDER } ?: store?.cover?.let { it to AUTO } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE } + Slot.WIDE -> own.header?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE } + Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("hero.jpg") Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png") Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB } ?: exeIcon(context, game)?.let { it to EXE } @@ -253,12 +260,13 @@ object AddedGameArt { internal fun missing(context: Context, game: AddedGames.Game): Set { val own = local(game) val cache = cacheDir(context, game) + val store = storeArt(context, game) fun has(slot: Slot, mine: File?, cached: String) = chosen(cache, slot) != null || mine != null || File(cache, cached).isFile return Slot.values().filterNot { slot -> when (slot) { - Slot.COVER -> has(slot, own.portrait, "p.jpg") - Slot.WIDE -> has(slot, own.header, "header.jpg") - Slot.BACKGROUND -> has(slot, own.hero, "hero.jpg") + Slot.COVER -> has(slot, own.portrait ?: store?.cover, "p.jpg") + Slot.WIDE -> has(slot, own.header ?: store?.header, "header.jpg") + Slot.BACKGROUND -> has(slot, own.hero ?: store?.header, "hero.jpg") Slot.LOGO -> has(slot, own.logo, "logo.png") Slot.ICON -> has(slot, own.icon, "icon-sgdb.png") } @@ -322,6 +330,10 @@ object AddedGameArt { } internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match { + if (game.source == Store.BATTLENET.id) { + val id = game.storeId?.let(BattleNet::title)?.steam + return SteamMatch.Match(id, if (id == null) SteamMatch.Certainty.NONE else SteamMatch.Certainty.FILES, Store.BATTLENET.id, System.currentTimeMillis()) + } val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search) match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") } return match @@ -361,14 +373,14 @@ object AddedGameArt { .filter { it.second > 0 && it.first.isNotEmpty() } .maxByOrNull { it.second }?.first - private fun search(name: String): String? { + internal fun search(name: String): String? { val term = name.replace(EDITION, " ").trim().ifEmpty { name } val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null val items = JSONObject(json).optJSONArray("items") ?: return null return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") }) } - private fun download(id: String, cache: File, slots: Set): Boolean { + internal fun download(id: String, cache: File, slots: Set = Slot.entries.toSet()): Boolean { var got = false for ((slot, remote, localName) in listOf( Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"), 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 340bc83ce0..aa1c6eef4c 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -79,6 +79,18 @@ object AddedGames { return null } + fun hostPath(context: Context, guest: String): File? { + if (!guest.startsWith("/") || guest.split('/').any { it == ".." }) return null + val mapped = roots(context).map { it.host to it.guest } + StoreInstallRoot.externalRoots(context) + + listOfNotNull(GameStorage.effective(context)?.let { File(it.path) to LIBRARY }) + + (android.os.Environment.getExternalStorageDirectory() to "/root/Storage") + for ((host, root) in mapped.sortedByDescending { it.second.length }) { + if (guest == root) return host + if (guest.startsWith("$root/")) return File(host, guest.removePrefix("$root/")) + } + return File(LinuxRuntime.rootDir(context), guest.removePrefix("/")) + } + fun candidates(folder: File): List = rank(folder).exes fun rank(folder: File): GameExePicker.Ranking { @@ -177,6 +189,9 @@ object AddedGames { scanGame(context, folder, out, single = entry) } for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out) + for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) { + if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add) + } return out.distinctBy { it.folder.canonicalPath } } 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 fc32744273..650c717d87 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt @@ -257,14 +257,18 @@ object AutoComponents { private const val FINDINGS = "wincomp-findings.json" + private const val DETECTORS = "d3" internal fun signature(context: Context, game: Library.SteamGame): String { val folder = game.gameFiles val parts = listOfNotNull( + DETECTORS, folder?.lastModified(), folder?.let { SteamRedists.manifest(it, game.appId)?.lastModified() }, folder?.let { StoreGameSidecar.file(it).lastModified() }, folder?.let { File(it, "fuel.json").lastModified() }, + folder?.listFiles { f -> f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") } } + ?.maxOfOrNull { it.lastModified() }, SteamAppInfo.appinfoFile(context).lastModified(), folder?.let { SteamMatch.get(context, it.path) }?.let { "${it.appId}/${it.certainty}" }, steamAppOf(context, game)?.let { SteamAppInfo.state(context, it) }, diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt index ab997f0271..388448e184 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt @@ -11,7 +11,7 @@ object GameRemoval { enum class Kind { STORE, SHORTCUT, LAUNCHER } fun kind(game: Library.SteamGame): Kind = when { - game.library == Library.EPIC_LAUNCHER -> Kind.LAUNCHER + game.library == Library.EPIC_LAUNCHER || game.library == Library.BATTLENET_LAUNCHER -> Kind.LAUNCHER game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT else -> Kind.STORE } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt index 05f3f98691..9fb776447a 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt @@ -22,11 +22,16 @@ object Library { SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo) val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId) - val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString() + val profileKey: String get() = when { + source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString() + library == ADDED -> java.lang.Integer.toUnsignedString(appId) + else -> appId.toString() + } } const val ADDED = "added" const val EPIC_LAUNCHER = "epic-launcher" const val EPIC_LAUNCHER_NAME = "Epic Games Launcher" + const val BATTLENET_LAUNCHER = "battlenet-launcher" const val XBOX_CLOUD = "xbox-cloud" const val SOURCE_STEAM = "steam" @@ -204,9 +209,24 @@ object Library { (runCatching { g.folder.canonicalPath }.getOrDefault(g.folder.absolutePath) !in claimed && AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed }) } - return (steam + own.map { g -> addedGame(context, g, roots) }).distinctBy { it.gameId } + val played = shortcutsLastPlayed(SessionPrefs.steamRoot(context, arch)) + return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) }).distinctBy { it.gameId } } + /** Steam's LastPlayTime for each non-Steam shortcut, by its unsigned shortcut app id. */ + internal fun shortcutsLastPlayed(root: File): Map = runCatching { + val config = AddedGames.accountConfig(root) ?: return emptyMap() + val bytes = File(config, "shortcuts.vdf").takeIf { it.isFile }?.readBytes() ?: return emptyMap() + val vdf = SteamAppInfo.readMap(java.nio.ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN), null) + (vdf["shortcuts"] as? Map<*, *>)?.values?.filterIsInstance>()?.mapNotNull { s -> + fun int(key: String) = s.entries.firstOrNull { (it.key as? String).equals(key, ignoreCase = true) } + ?.let { (it.value as? String)?.toLongOrNull() }?.and(0xFFFFFFFFL) + val id = int("appid") ?: return@mapNotNull null + val time = int("LastPlayTime")?.takeIf { it > 0L } ?: return@mapNotNull null + id to time + }?.toMap() + }.getOrNull().orEmpty() + fun claimedFolders(steam: List): Set = steam.filter(::fromSteamClient).flatMap { g -> val dir = g.gameFiles ?: return@flatMap emptyList() listOfNotNull( @@ -215,12 +235,16 @@ object Library { ) }.toSet() - fun addedGame(context: Context, g: AddedGames.Game, roots: List = steamLibraries(context).map { it.first }): SteamGame = + fun addedGame( + context: Context, g: AddedGames.Game, roots: List = steamLibraries(context).map { it.first }, + lastPlayed: Long = 0L, + ): SteamGame = AddedGameArt.resolve(context, g).let { art -> SteamGame( g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId, - hero = art.hero ?: art.header, gameFiles = g.folder, - protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots), + hero = art.hero ?: art.header, lastPlayed = lastPlayed, gameFiles = g.folder, + protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory } + else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots), icon = art.icon?.takeIf { it.extension.lowercase() != "ico" }, source = g.source, storeId = g.storeId, logo = art.logo, diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SteamGrid.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SteamGrid.kt index 47b679031f..88526f1bf7 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/SteamGrid.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SteamGrid.kt @@ -5,6 +5,7 @@ import android.util.Log import com.droiddeck.launcher.session.SessionPrefs import org.json.JSONObject import java.io.File +import java.util.UUID /** Steam keeps a game's custom art in `userdata//config/grid`; this is where DroidDeck's choices and Steam's meet. */ object SteamGrid { @@ -41,14 +42,42 @@ object SteamGrid { private fun sigFile(context: Context, target: Target, slot: AddedGameArt.Slot) = File(target.artDir, sigName(context, slot.key)) - private fun recorded(context: Context, target: Target, slot: AddedGameArt.Slot): String? = - sigFile(context, target, slot).takeIf { it.isFile }?.readText() + private const val GRID_ID = ".droiddeck-grid" + private const val UNKNOWN_GRID = "?" - private fun record(context: Context, target: Target, slot: AddedGameArt.Slot, value: String) { - target.artDir.mkdirs() - sigFile(context, target, slot).writeText(value) + /** + * A random id kept in the grid folder, so a record made against another account's folder, or one wiped with the + * runtime, reads as "not seen yet" instead of "removed in Steam". "?" never matches, so nothing is dropped. + */ + private fun gridId(grid: File): String = runCatching { + val f = File(grid, GRID_ID) + f.takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: UUID.randomUUID().toString().also { id -> + grid.mkdirs() + val tmp = File(grid, "$GRID_ID.tmp") + tmp.writeText(id) + if (f.isFile) f.delete() + if (!tmp.renameTo(f)) error("grid id") + } + }.getOrDefault(UNKNOWN_GRID) + + private fun readRecord(grid: File, file: File): String? { + val text = file.takeIf { it.isFile }?.readText() ?: return null + val cut = text.indexOf('\n') + val id = gridId(grid) + return if (cut > 0 && id != UNKNOWN_GRID && text.substring(0, cut) == id) text.substring(cut + 1) else null } + private fun writeRecord(grid: File, target: Target, file: File, value: String) { + target.artDir.mkdirs() + file.writeText("${gridId(grid)}\n$value") + } + + private fun recorded(context: Context, grid: File, target: Target, slot: AddedGameArt.Slot): String? = + readRecord(grid, sigFile(context, target, slot)) + + private fun record(context: Context, grid: File, target: Target, slot: AddedGameArt.Slot, value: String) = + writeRecord(grid, target, sigFile(context, target, slot), value) + private fun writtenByDroidDeck(grid: File): Set = runCatching { val manifest = JSONObject(File(grid, MANIFEST).readText()) manifest.keys().asSequence().filter { name -> File(grid, name).let { it.isFile && it.length() == manifest.optLong(name, -1L) } }.toSet() @@ -62,7 +91,7 @@ object SteamGrid { val grid = dir(context) ?: return true if (file == null) { if (files(grid, target.id, slot).map { it.delete() }.any { !it }) return false - record(context, target, slot, "") + record(context, grid, target, slot, "") return true } val ext = file.extension.lowercase().let { if (it == "jpeg") "jpg" else it } @@ -76,7 +105,7 @@ object SteamGrid { return false } if (files(grid, target.id, slot).filter { it != dst }.map { it.delete() }.any { !it }) return false - record(context, target, slot, signature(placed)) + record(context, grid, target, slot, signature(placed)) return true } @@ -90,13 +119,11 @@ object SteamGrid { /** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */ fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION)) - private fun positionRecorded(context: Context, target: Target): String? = - File(target.artDir, sigName(context, POSITION_SIG)).takeIf { it.isFile }?.readText() + private fun positionRecorded(context: Context, grid: File, target: Target): String? = + readRecord(grid, File(target.artDir, sigName(context, POSITION_SIG))) - private fun recordPosition(context: Context, target: Target, value: String) { - target.artDir.mkdirs() - File(target.artDir, sigName(context, POSITION_SIG)).writeText(value) - } + private fun recordPosition(context: Context, grid: File, target: Target, value: String) = + writeRecord(grid, target, File(target.artDir, sigName(context, POSITION_SIG)), value) private fun storePosition(target: Target, value: LogoPosition.Value?): Boolean { val file = File(target.artDir, POSITION) @@ -119,7 +146,7 @@ object SteamGrid { val next = if (value == null) existing?.let(LogoPosition::without) else LogoPosition.toJson(value, existing ?: JSONObject()) if (next == null) { if (file.isFile && !file.delete()) return false - recordPosition(context, target, "") + recordPosition(context, grid, target, "") return true } grid.mkdirs() @@ -129,7 +156,7 @@ object SteamGrid { tmp.delete() return false } - recordPosition(context, target, signature(file)) + recordPosition(context, grid, target, signature(file)) return true } @@ -144,16 +171,16 @@ object SteamGrid { if (hasUnknownPosition(file)) return val theirs = positionIn(file) val now = if (theirs != null) signature(file) else "" - val before = positionRecorded(context, target) + val before = positionRecorded(context, grid, target) val own = position(target) when { before == null && own != null && theirs == null -> placePosition(context, target, own) before == null || now != before -> { // Recorded only once the local side agrees, so a failed take-over is tried again on the next scan. if (theirs != null) { - if (own == theirs || storePosition(target, theirs)) recordPosition(context, target, now) + if (own == theirs || storePosition(target, theirs)) recordPosition(context, grid, target, now) } else { - if (own == null || storePosition(target, null)) recordPosition(context, target, "") + if (own == null || storePosition(target, null)) recordPosition(context, grid, target, "") } } own != null && own != theirs -> placePosition(context, target, own) @@ -173,20 +200,20 @@ object SteamGrid { val present = files(grid, target.id, slot) val theirs = present.filter { it.name !in ours }.maxByOrNull { it.lastModified() } val now = signature(theirs) - val before = recorded(context, target, slot) + val before = recorded(context, grid, target, slot) when { before == null && own != null && theirs == null -> write(context, target, slot, own) before == null || now != before -> { if (theirs != null) { - if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(context, target, slot, now) + if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(context, grid, target, slot, now) else if (AddedGameArt.store(target.artDir, slot, AddedGameArt.Option(AddedGameArt.STEAM, theirs.path, theirs.path))) { target.setSource(slot, AddedGameArt.STEAM + "|steam-client") - record(context, target, slot, now) + record(context, grid, target, slot, now) changed = true } } else { if (own != null && present.isEmpty()) { own.delete(); target.setSource(slot, ""); changed = true } - record(context, target, slot, "") + record(context, grid, target, slot, "") } } own != null && theirs != null && now == before && own.length() != theirs.length() -> write(context, target, slot, own) 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 f41b8265ff..e022ebc8ec 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt @@ -15,6 +15,11 @@ object SteamRedists { "228989" to ("vcredist2022_dll" to "VC++ 2022"), "228990" to ("d3dx9" to "DirectX (June 2010)"), ) + /** Redists a game's own install script runs on Windows that its shared depots don't name. */ + val SCRIPTED = mapOf( + 72850 to listOf("xact" to "DirectX XACT audio"), + 489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"), + ) private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE) private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"") @@ -23,6 +28,17 @@ object SteamRedists { return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile } } + /** Redists the game's own install script has Steam run on Windows, from its "Run Process" entries. */ + fun installScript(gameDir: File?): List> = + gameDir?.listFiles { f -> + f.isFile && f.length() < 1L shl 20 && f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") } + }.orEmpty().sortedBy { it.name }.flatMap { file -> + val root = runCatching { com.droiddeck.launcher.input.KeyValues.parse(file.readText()) }.getOrNull() ?: return@flatMap emptyList() + (root.child("InstallScript") ?: root).children("Run Process") + .flatMap { run -> run.entries.mapNotNull { (it.second as? com.droiddeck.launcher.input.KeyValues.Node)?.string("process 1") } } + .flatMap { path -> DependencyDetector.componentsFor(path).map { it to DependencyDetector.label(it) } } + }.distinctBy { it.first } + fun detect(gameDir: File?, appId: Int): List { val text = try { manifest(gameDir, appId)?.takeIf { it.length() < 1L shl 20 }?.readText() ?: return emptyList() diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/WinCompSources.kt b/app/src/main/java/com/droiddeck/launcher/frontend/WinCompSources.kt index 63e8627790..8e91102f3b 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/WinCompSources.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/WinCompSources.kt @@ -77,9 +77,10 @@ object WinCompSources { fun steamList(context: Context, gameDir: File?, appId: Int, gameName: String, auto: Boolean): List { val local = SteamRedists.detect(gameDir, appId) - val pairs = if (local.isNotEmpty()) local.map { it.componentName to it.label } - else SteamAppInfo.info(context, appId)?.let { steamDepots(it.sharedDepots) }.orEmpty() - return pairs.map { (component, label) -> + val pairs = (if (local.isNotEmpty()) local.map { it.componentName to it.label } + else SteamAppInfo.info(context, appId)?.let { steamDepots(it.sharedDepots) }.orEmpty()) + + SteamRedists.installScript(gameDir) + SteamRedists.SCRIPTED[appId].orEmpty() + return pairs.distinctBy { it.first.removeSuffix("_dll") }.map { (component, label) -> Finding(component, label, if (auto) Origin.STEAM else Origin.STEAM_NAME, auto, listOf(label, gameName, appId.toString())) } } diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/GlassesRendering.kt b/app/src/main/java/com/droiddeck/launcher/glasses/GlassesRendering.kt index f8d6f4c5f1..b07221556d 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/GlassesRendering.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/GlassesRendering.kt @@ -32,12 +32,6 @@ internal object GlassesRendering { return if (hz == 30 && kotlin.math.abs(state.hz - 30f) >= 0.5f) 60 else hz } - fun fpsLimit(requested: Int, mirrorRefreshLimit: Int): Int = when { - mirrorRefreshLimit <= 0 -> requested - requested <= 0 -> mirrorRefreshLimit - else -> minOf(requested, mirrorRefreshLimit) - } - fun usesGlasses(state: GlassesState, outputActive: Boolean, steamVrRunning: Boolean): Boolean = outputActive || (steamVrRunning && state.usable) diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/RokidModel.kt b/app/src/main/java/com/droiddeck/launcher/glasses/RokidModel.kt index a1ad6e83a1..35227206b7 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/RokidModel.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/RokidModel.kt @@ -3,7 +3,7 @@ package com.droiddeck.launcher.glasses import java.nio.ByteBuffer import java.nio.ByteOrder -/** Rokid Air/Max share one USB identity; the product string distinguishes them. */ +/** Rokid Air/Max share one USB identity; Max 2 has a separate product ID. */ internal class RokidModel private constructor(override val name: String, private val max: Boolean) : GlassesModel { override val controllable = true override val brightnessMax = BRIGHTNESS_STEPS @@ -33,6 +33,7 @@ internal class RokidModel private constructor(override val name: String, private companion object { const val VENDOR_ID = 0x04d2 const val PRODUCT_ID = 0x162f + const val MAX2_PRODUCT_ID = 0x2002 const val BRIGHTNESS_STEPS = 10 // Vendor control requests, device recipient. @@ -52,9 +53,9 @@ internal class RokidModel private constructor(override val name: String, private // 0x04d2 is a shared vendor ID, so the Rokid product string is required too. fun model(vid: Int, pid: Int, name: String?): GlassesModel? { - if (vid != VENDOR_ID || pid != PRODUCT_ID) return null + if (vid != VENDOR_ID || (pid != PRODUCT_ID && pid != MAX2_PRODUCT_ID)) return null val product = name?.trim()?.takeIf { it.startsWith("Rokid", ignoreCase = true) } ?: return null - return RokidModel(product, product.contains("Max", ignoreCase = true)) + return RokidModel(product, pid == MAX2_PRODUCT_ID || product.contains("Max", ignoreCase = true)) } fun isDisplay(name: String) = name.contains("Rokid", ignoreCase = true) diff --git a/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt b/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt new file mode 100644 index 0000000000..65f9e5b83e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt @@ -0,0 +1,93 @@ +package com.droiddeck.launcher.input + +import android.view.KeyEvent +import android.os.Handler +import android.os.Looper + +class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit, + private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {}) { + private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false) + private val handler = Handler(Looper.getMainLooper()) + private val presses = mutableMapOf() + private val cancelled = mutableSetOf() + private var tapPending = false + private val singleTap = Runnable { tapPending = false; onTap(false) } + + private fun cancelTap() { + handler.removeCallbacks(singleTap) + tapPending = false + } + + fun onChordInput() { + if (presses.isEmpty()) return + val alreadyHeld = presses.values.any { it.held } + presses.values.forEach { + handler.removeCallbacks(it.hold) + it.held = true + it.used = true + } + cancelTap() + if (!alreadyHeld) setPressed(true) + } + + fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean { + if (!enabled) cancel() + if (event.keyCode != KeyEvent.KEYCODE_BACK) return false + val device = event.deviceId + return when (event.action) { + KeyEvent.ACTION_DOWN -> { + if (event.repeatCount > 0) return enabled || device in presses || device in cancelled + cancelled.remove(device) + if (!enabled || event.isCanceled) return false + if (device in presses) return true + handler.removeCallbacks(singleTap) + val hold = Runnable { + val press = presses[device] ?: return@Runnable + val alreadyHeld = presses.values.any { it.held } + press.held = true + presses.values.forEach { it.used = true } + cancelTap() + if (!alreadyHeld) setPressed(true) + } + presses[device] = Press(hold, used = presses.values.any { it.held }) + handler.postDelayed(hold, 700) + true + } + KeyEvent.ACTION_UP -> { + val press = presses.remove(device) + val wasCancelled = cancelled.remove(device) + if (press != null) { + handler.removeCallbacks(press.hold) + if (press.held && presses.values.none { it.held }) setPressed(false) + if (!press.used && !event.isCanceled) { + if (tapPending) { cancelTap(); onTap(true) } + else { tapPending = true; handler.postDelayed(singleTap, doubleTapMs()) } + } else if (event.isCanceled) cancelTap() + } + press != null || wasCancelled || enabled + } + else -> device in presses || device in cancelled + } + } + + fun cancel() { + cancelTap() + val wasHeld = presses.values.any { it.held } + presses.values.forEach { handler.removeCallbacks(it.hold) } + cancelled.addAll(presses.keys) + presses.clear() + onCancel() + if (wasHeld) setPressed(false) + } + + fun onDeviceRemoved(device: Int) { + cancelled.remove(device) + val press = presses.remove(device) ?: return + handler.removeCallbacks(press.hold) + cancelTap() + if (press.held && presses.values.none { it.held }) { + onCancel() + setPressed(false) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerEditorActivity.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerEditorActivity.kt index 4bd76a4e73..cb544d5a4d 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControllerEditorActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerEditorActivity.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.input +import com.droiddeck.launcher.ui.focusGlide import android.os.Build import android.os.Bundle import android.view.Gravity @@ -104,6 +105,7 @@ class ControllerEditorActivity : ComponentActivity() { else -> Color.White.copy(alpha = 0.06f) }, ) + .focusGlide(RoundedCornerShape(50)) .then( if (selected == null) Modifier.clickable(onClick = onClick) else Modifier.toggleable(value = selected, role = Role.Switch, onValueChange = { onClick() }), diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt index 9b08fd8adb..c784bc3bf6 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt @@ -157,6 +157,56 @@ object ControllerPrefs { prefs(context).edit().remove("layout.${width}x$height").apply() } + fun screenKeysShown(context: Context): Boolean = prefs(context).getBoolean("screenKeysShown", true) + + fun setScreenKeysShown(context: Context, shown: Boolean) { + prefs(context).edit().putBoolean("screenKeysShown", shown).apply() + } + + fun screenKeys(context: Context): List = decodeScreenKeys(prefs(context).getString("screenKeys", null).orEmpty()) + + fun setScreenKeys(context: Context, keys: List) { + prefs(context).edit().putString("screenKeys", encodeScreenKeys(keys)).apply() + } + + fun encodeScreenKeys(keys: List): String = keys.joinToString(";") { + "${it.codes.joinToString("+")}:${it.x},${it.y},${it.size}:${escape(it.glyph)}:${escape(it.text)}:${escape(it.image)}:${it.opacity}:${it.shape}:${if (it.toggle) 1 else 0}:${if (it.labels) 1 else 0}" + } + + fun decodeScreenKeys(raw: String): List = raw.split(';').mapNotNull { entry -> + val parts = entry.split(':') + if (parts.size < 2) return@mapNotNull null + val keys = parts[0].split('+').mapNotNull { it.toIntOrNull() }.takeIf { it.isNotEmpty() } ?: return@mapNotNull null + val nums = parts[1].split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 3 } ?: return@mapNotNull null + ScreenKey( + keys, nums[0], nums[1], nums[2].toInt(), + parts.getOrNull(2)?.let(::unescape).orEmpty(), + parts.getOrNull(3)?.let(::unescape).orEmpty(), + parts.getOrNull(4)?.let(::unescape).orEmpty(), + parts.getOrNull(5)?.toFloatOrNull()?.coerceIn(0.2f, 1f) ?: 1f, + parts.getOrNull(6)?.toIntOrNull()?.coerceIn(SCREEN_KEY_PILL, SCREEN_KEY_STICK) ?: SCREEN_KEY_PILL, + parts.getOrNull(7) == "1", + parts.getOrNull(8) != "0", + ) + } + + fun screenLayouts(context: Context): Map = + prefs(context).all.mapNotNull { (key, value) -> + if (!key.startsWith("screenLayout.") || value !is String) null else key.removePrefix("screenLayout.") to value + }.toMap() + + fun saveScreenLayout(context: Context, name: String, raw: String) { + prefs(context).edit().putString("screenLayout.$name", raw).apply() + } + + fun deleteScreenLayout(context: Context, name: String) { + prefs(context).edit().remove("screenLayout.$name").apply() + } + + private fun escape(value: String) = value.replace("%", "%25").replace(";", "%3B").replace(":", "%3A").replace(",", "%2C") + + private fun unescape(value: String) = value.replace("%2C", ",").replace("%3A", ":").replace("%3B", ";").replace("%25", "%") + fun resetAll(context: Context) { prefs(context).edit().clear().putBoolean("rumble", true).apply() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/DirectTouchHold.kt b/app/src/main/java/com/droiddeck/launcher/input/DirectTouchHold.kt index 318941c71c..8bf852fdbd 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/DirectTouchHold.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/DirectTouchHold.kt @@ -15,6 +15,7 @@ class DirectTouchHold( private var y = 0f private var consumed = false private var pressed = false + private var delayMs = 0L private val release = Runnable { if (pressed) listener.onButton(PointerGestures.BTN_RIGHT, false, x, y) pressed = false @@ -28,6 +29,11 @@ class DirectTouchHold( handler.postDelayed(release, 50L) } + fun configure(config: TouchGestureConfig) { + cancel() + delayMs = if (config.longPressEnabled) config.longPressDelay.toLong().coerceAtLeast(1L) else 0L + } + fun cancel() { handler.removeCallbacks(hold) handler.removeCallbacks(release) @@ -40,7 +46,7 @@ class DirectTouchHold( MotionEvent.ACTION_DOWN -> { cancel() x = event.x; y = event.y - handler.postDelayed(hold, 500L) + if (delayMs > 0L) handler.postDelayed(hold, delayMs) } MotionEvent.ACTION_MOVE -> if (event.pointerCount > 1 || abs(event.x - x) > slopPx || abs(event.y - y) > slopPx) handler.removeCallbacks(hold) 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 05469e6340..f140314dc0 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java +++ b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java @@ -525,8 +525,8 @@ public class FakeInputWriter { } } - public static void setLowLatency(boolean controller, boolean touch) { - int flags = (controller ? LATENCY_CONTROLLER : 0) | (touch ? LATENCY_TOUCH : 0); + public static void setLowLatency(boolean enabled) { + int flags = enabled ? LATENCY_CONTROLLER | LATENCY_TOUCH : 0; latency = flags; RingSlot ringSlot; synchronized (RING_LOCK) { diff --git a/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt b/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt new file mode 100644 index 0000000000..68d5722d0a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt @@ -0,0 +1,21 @@ +package com.droiddeck.launcher.input + +import android.view.MotionEvent + +/** Keeps split Android touch targets from restarting one shared gesture recognizer. */ +internal class GestureTouchStreamGate { + enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS } + + private var owner: Source? = null + + fun accepts(source: Source, event: MotionEvent): Boolean { + if (owner == null && event.actionMasked == MotionEvent.ACTION_DOWN) owner = source + val accepted = owner == source + if (accepted && (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL)) { + owner = null + } + return accepted + } + + fun reset() { owner = null } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt b/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt new file mode 100644 index 0000000000..b85fecb120 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt @@ -0,0 +1,71 @@ +package com.droiddeck.launcher.input + +import android.accessibilityservice.AccessibilityService +import android.content.Context +import android.content.Intent +import android.hardware.input.InputManager +import android.os.Handler +import android.os.Looper +import android.view.KeyEvent +import android.view.accessibility.AccessibilityEvent +import com.droiddeck.launcher.HomeApp + +object HomeButtonShortcuts { + private var owner: Any? = null + private var enabled: () -> Boolean = { false } + private var setPressed: (Boolean) -> Unit = {} + private var onCancel: () -> Unit = {} + private val input = HomeGuideInput({ setPressed(it) }, { onCancel() }) + + fun attach(owner: Any, enabled: () -> Boolean, setPressed: (Boolean) -> Unit, onCancel: () -> Unit) { + input.cancel() + this.owner = owner + this.enabled = enabled + this.setPressed = setPressed + this.onCancel = onCancel + } + + fun cancel(owner: Any) { if (this.owner === owner) input.cancel() } + + fun detach(owner: Any) { + if (this.owner !== owner) return + input.cancel() + this.owner = null + enabled = { false } + setPressed = {} + onCancel = {} + } + + fun onKeyEvent(context: Context, event: KeyEvent): Boolean { + // AYN maps its system-assistant key (gpio-keys KEY_F24) to HOME too; only the pad's Home is Guide. + if (!HomeGuideInput.isHome(event.keyCode) || !PadBridge.isControllerKeyEvent(event)) return false + return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context)) + } + + fun release() = input.cancel() + fun onDeviceRemoved(device: Int) = input.onDeviceRemoved(device) +} + +class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener { + override fun onServiceConnected() { + getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper())) + } + + override fun onKeyEvent(event: KeyEvent) = HomeButtonShortcuts.onKeyEvent(this, event) + override fun onAccessibilityEvent(event: AccessibilityEvent?) {} + override fun onInterrupt() { HomeButtonShortcuts.release() } + override fun onInputDeviceAdded(deviceId: Int) {} + override fun onInputDeviceChanged(deviceId: Int) {} + override fun onInputDeviceRemoved(deviceId: Int) { HomeButtonShortcuts.onDeviceRemoved(deviceId) } + + override fun onUnbind(intent: Intent?): Boolean { + HomeButtonShortcuts.release() + return super.onUnbind(intent) + } + + override fun onDestroy() { + HomeButtonShortcuts.release() + getSystemService(InputManager::class.java).unregisterInputDeviceListener(this) + super.onDestroy() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt b/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt new file mode 100644 index 0000000000..785f7c1a13 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt @@ -0,0 +1,47 @@ +package com.droiddeck.launcher.input + +import android.view.KeyEvent + +class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCancel: () -> Unit = {}) { + private val presses = mutableSetOf() + private val cancelled = mutableSetOf() + + fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean { + if (!isHome(event.keyCode)) return false + if (!enabled) cancel() + val device = event.deviceId + return when (event.action) { + KeyEvent.ACTION_DOWN -> { + if (event.repeatCount > 0) return device in presses || device in cancelled + cancelled.remove(device) + if (!enabled || event.isCanceled) return false + if (presses.add(device) && presses.size == 1) setPressed(true) + true + } + KeyEvent.ACTION_UP -> { + val owned = presses.remove(device) + val wasCancelled = cancelled.remove(device) + if (owned && presses.isEmpty()) setPressed(false) + owned || wasCancelled + } + else -> device in presses || device in cancelled + } + } + + fun cancel() { + val held = presses.isNotEmpty() + cancelled.addAll(presses) + presses.clear() + if (held) { onCancel(); setPressed(false) } + } + + fun onDeviceRemoved(device: Int) { + cancelled.remove(device) + if (presses.remove(device) && presses.isEmpty()) { onCancel(); setPressed(false) } + } + + companion object { + // The Retroid Nova pad falls back to Generic.kl, which maps its Home scan code to MOVE_HOME. + fun isHome(keyCode: Int) = keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_HOME + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt index 50ffb17a81..e0a0b14b9b 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -96,6 +96,8 @@ class OnScreenControls( private var quickHidden = false private var quickPressedBy = -1 private var keyboardPressedBy = -1 + private var forwardedPointerBits = 0 + var onTouchMiss: ((MotionEvent) -> Unit)? = null private var settings = ControllerPrefs.read(context) private var snap = settings.snap private var safe = Rect() @@ -515,6 +517,9 @@ class OnScreenControls( val index = event.actionIndex val x = event.getX(index) val y = event.getY(index) + if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0 + if (event.actionMasked == MotionEvent.ACTION_POINTER_DOWN && forwardMiss(event, x, y)) return true + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) if (event.actionMasked == MotionEvent.ACTION_DOWN && keyboardContains(x, y)) { keyboardPressedBy = event.getPointerId(index) invalidate() @@ -542,11 +547,13 @@ class OnScreenControls( return true } MotionEvent.ACTION_MOVE -> { + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) if (keyboardPressedBy != -1) return true if (quickPressedBy != -1) return true var changed = false for (index in 0 until event.pointerCount) { val pointer = event.getPointerId(index) + if (forwardedPointerBits and (1 shl pointer) != 0) continue val x = event.getX(index) val y = event.getY(index) val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer } @@ -568,10 +575,16 @@ class OnScreenControls( } MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> { val pointer = event.getPointerId(event.actionIndex) + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) if (event.actionMasked == MotionEvent.ACTION_CANCEL) { + forwardedPointerBits = 0 releaseAll() return true } + if (forwardedPointerBits and (1 shl pointer) != 0) { + forwardedPointerBits = forwardedPointerBits and (1 shl pointer).inv() + return true + } if (keyboardPressedBy == pointer) { val tapped = event.actionMasked == MotionEvent.ACTION_UP && keyboardContains(event.x, event.y) keyboardPressedBy = -1 @@ -604,6 +617,23 @@ class OnScreenControls( return false } + private fun forwardMiss(event: MotionEvent, x: Float, y: Float): Boolean { + if (onTouchMiss == null || keyboardPressedBy != -1 || quickPressedBy != -1) return false + if (!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null) return false + forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(event.actionIndex)) + forwardPointers(event, forwardedPointerBits) + return true + } + + private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) { + val split = event.pointerSubset(pointerIdBits) ?: return + try { + onTouchMiss?.invoke(split) + } finally { + split.recycle() + } + } + private fun onEditTouch(event: MotionEvent): Boolean { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index cfb0978cb8..7dd234daf1 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -1,5 +1,6 @@ package com.droiddeck.launcher.input; +import android.os.Build; import android.os.Handler; import android.os.Looper; import android.util.Log; @@ -52,6 +53,7 @@ public final class PadBridge { private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS]; private final PadState[] playerStates = new PadState[SLOTS]; private final PadState effectiveState = new PadState(); + private final PadState homeGuideReport = new PadState(); private final Handler mainHandler = new Handler(Looper.getMainLooper()); private boolean open; private volatile boolean selectSteam; @@ -60,12 +62,21 @@ public final class PadBridge { private final PadState routedTouch = new PadState(); private boolean systemGuidePressed; private boolean systemQamPressed; + private boolean backQamPressed; + private boolean homeGuidePressed; + private int homeGuideSlot = -1; + private final PadState lastBackQamReport = new PadState(); + private final PadState lastWrittenReport = new PadState(); + private boolean backQamAxesBlocked; + private final java.util.Set backQamWrites = new java.util.HashSet<>(); + private long backQamDelayMs, backQamWriteAt; private boolean qamChordActive; private int chordButton = -1; private boolean chordButtonPressed; private boolean qamTapPressed; private int qamChordGeneration; private volatile Runnable onPlayerInput; + private Runnable onChordInput; private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean(); private static final long STATS_WINDOW_MS = 10_000; @@ -128,9 +139,12 @@ public final class PadBridge { } private void resetBuiltin() { + homeGuidePressed = false; + clearBackQamWrites(); routedTouch.clear(); systemGuidePressed = false; systemQamPressed = false; + backQamPressed = false; qamTapPressed = false; qamChordActive = false; chordButtonPressed = false; @@ -149,6 +163,9 @@ public final class PadBridge { } public synchronized void stop() { + homeGuidePressed = false; + homeGuideSlot = -1; + clearBackQamWrites(); releaseBackPaddles(); activeControllerId = NO_CONTROLLER; for (int slot = 0; slot < SLOTS; slot++) { @@ -164,6 +181,7 @@ public final class PadBridge { } systemGuidePressed = false; systemQamPressed = false; + backQamPressed = false; qamChordActive = false; chordButtonPressed = false; qamTapPressed = false; @@ -214,6 +232,7 @@ public final class PadBridge { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_MENU: case KeyEvent.KEYCODE_HOME: + case KeyEvent.KEYCODE_MOVE_HOME: if (!isFromController(device)) return false; return device.supportsSource(InputDevice.SOURCE_GAMEPAD) || device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC @@ -272,6 +291,14 @@ public final class PadBridge { onPlayerInput = listener; } + public synchronized void setOnChordInput(Runnable listener) { + onChordInput = listener; + } + + private void noteChordInput(int slot) { + if (slot == 0 && onChordInput != null) onChordInput.run(); + } + private void notePlayerInput() { Runnable listener = onPlayerInput; if (listener == null || !playerInputPosted.compareAndSet(false, true)) return; @@ -306,12 +333,13 @@ public final class PadBridge { case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break; case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.press(9, pressed); break; case KeyEvent.KEYCODE_BUTTON_MODE: - case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break; + case KeyEvent.KEYCODE_HOME: + case KeyEvent.KEYCODE_MOVE_HOME: pad.press(PadState.GUIDE, pressed); break; case KeyEvent.KEYCODE_BUTTON_Z: - if (isPrimary(event)) DeckControls.INSTANCE.setGrip(DeckControls.L4, pressed); + if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed); break; case KeyEvent.KEYCODE_BUTTON_C: - if (isPrimary(event)) DeckControls.INSTANCE.setGrip(DeckControls.R4, pressed); + if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.L4 : DeckControls.R4, pressed); break; case KeyEvent.KEYCODE_BUTTON_L2: pad.leftTrigger = pressed ? 1f : 0f; break; case KeyEvent.KEYCODE_BUTTON_R2: pad.rightTrigger = pressed ? 1f : 0f; break; @@ -322,6 +350,7 @@ public final class PadBridge { default: return false; } noteDevice(event.getDevice(), slot); + if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot); if (pressed) notePlayerInput(); statButtons++; scheduleStats(); @@ -351,6 +380,7 @@ public final class PadBridge { pad.rightX = x; pad.rightY = y; } + if (x != 0f || y != 0f) noteChordInput(slot); if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput(); publish(slot); return true; @@ -381,6 +411,8 @@ public final class PadBridge { pad.up = hatY < -0.5f; pad.down = hatY > 0.5f; } + if (pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f + || lt > 0f || rt > 0f || pad.up || pad.right || pad.down || pad.left) noteChordInput(slot); if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f || lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) { notePlayerInput(); @@ -457,7 +489,11 @@ public final class PadBridge { } public synchronized void releaseAll() { + homeGuidePressed = false; + homeGuideSlot = -1; + clearBackQamWrites(); routedTouch.clear(); + backQamPressed = false; releaseBackPaddles(); state.clear(); publish(); @@ -478,6 +514,146 @@ public final class PadBridge { return SessionState.getDeckPad() && FakeInputWriter.padHasQam(); } + public boolean canHoldQam() { + return builtinPad && nativeQam(); + } + + public synchronized void setHomeGuidePressed(boolean pressed) { + int slot = pressed ? firstPlayerSlot() : homeGuideSlot; + if (slot > 0) { + homeGuideSlot = pressed ? slot : -1; + publish(slot); + return; + } + if (homeGuidePressed == pressed) return; + homeGuidePressed = pressed; + updateHeldModifier(PadState.GUIDE, pressed); + } + + public synchronized void cancelHomeGuide() { + int slot = homeGuideSlot; + if (slot > 0) { + homeGuideSlot = -1; + publish(slot); + } + if (!homeGuidePressed) return; + clearBackQamWrites(); + homeGuidePressed = false; + state.clear(); + publish(); + } + + public synchronized void setBackQamPressed(boolean pressed) { + if (pressed && !canHoldQam()) return; + if (backQamPressed == pressed) return; + backQamPressed = pressed; + updateHeldModifier(PadState.QAM, pressed); + } + + private void updateHeldModifier(int button, boolean pressed) { + if (pressed && (open || start())) { + backQamAxesBlocked = false; + long now = android.os.SystemClock.uptimeMillis(); + long modifierAt = Math.max(now, backQamWriteAt); + backQamDelayMs = modifierAt - now + QAM_GUIDE_LEAD_MIN_MS; + PadState modifier = new PadState(); + modifier.copyFrom(lastBackQamReport); + modifier.press(button, true); + writeBackQamReport(modifier, modifierAt); + } + if (!pressed && !backQamPressed && !homeGuidePressed) { + backQamAxesBlocked = hasAxes(state); + if (!backQamWrites.isEmpty()) { + PadState neutral = new PadState(); + neutral.copyFrom(lastWrittenReport); + clearAxes(neutral); + writer.writePad(neutral); + lastWrittenReport.copyFrom(neutral); + } + } + publish(); + } + + public synchronized void cancelBackQam() { + if (!backQamPressed && backQamWrites.isEmpty()) return; + clearBackQamWrites(); + backQamPressed = false; + state.clear(); + publish(); + } + + private void clearBackQamWrites() { + for (Runnable pending : backQamWrites) mainHandler.removeCallbacks(pending); + backQamWrites.clear(); + backQamDelayMs = backQamWriteAt = 0; + lastBackQamReport.clear(); + lastWrittenReport.clear(); + backQamAxesBlocked = false; + } + + private void writeBackQamReport(PadState report, long at) { + lastBackQamReport.copyFrom(report); + if (backQamWrites.isEmpty() && at <= android.os.SystemClock.uptimeMillis()) { + writeReport(report, false); + return; + } + PadState queued = new PadState(); + queued.copyFrom(report); + Runnable pending = new Runnable() { + @Override public void run() { + synchronized (PadBridge.this) { + if (!backQamWrites.remove(this)) return; + writeReport(queued, true); + if (backQamWrites.isEmpty() && !hasButtons(lastBackQamReport)) backQamDelayMs = 0; + } + } + }; + backQamWrites.add(pending); + backQamWriteAt = at; + mainHandler.postAtTime(pending, at); + } + + private void writePad(PadState report) { + if (backQamAxesBlocked && !hasAxes(state)) backQamAxesBlocked = false; + long at = android.os.SystemClock.uptimeMillis(); + // Steam must see the modifier before a partner; preserve quick press/release pairs in order. + if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs; + writeBackQamReport(report, at); + } + + private static boolean hasAxes(PadState pad) { + return pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f + || pad.leftTrigger != 0f || pad.rightTrigger != 0f; + } + + private static void clearAxes(PadState pad) { + pad.leftX = pad.leftY = pad.rightX = pad.rightY = pad.leftTrigger = pad.rightTrigger = 0f; + } + + private static boolean hasButtons(PadState pad) { + for (int i = 0; i < 10; i++) if (pad.isDown(i)) return true; + return pad.isDown(PadState.GUIDE) || pad.up || pad.right || pad.down || pad.left; + } + + private void writeReport(PadState report, boolean queued) { + if (!queued && !backQamAxesBlocked) { + lastWrittenReport.copyFrom(report); + writer.writePad(report); + return; + } + PadState live = new PadState(); + live.copyFrom(report); + if (queued) { + live.leftX = state.leftX; live.leftY = state.leftY; + live.rightX = state.rightX; live.rightY = state.rightY; + live.leftTrigger = state.leftTrigger; live.rightTrigger = state.rightTrigger; + } + boolean held = (backQamPressed && report.isDown(PadState.QAM)) || (homeGuidePressed && report.isDown(PadState.GUIDE)); + if ((queued && !held) || backQamAxesBlocked) clearAxes(live); + lastWrittenReport.copyFrom(live); + writer.writePad(live); + } + public synchronized void triggerQam() { if (!builtinPad) return; if (!nativeQam()) { @@ -556,7 +732,9 @@ public final class PadBridge { slotJoyCons.set(slot * 2 + side, id); slotJoyCons.set(slot * 2 + 1 - side, owner.getId()); if (slot == firstPlayerSlot()) releaseBackPaddles(); + if (slot == 0) clearBackQamWrites(); stateFor(slot).clear(); + if (slot == 0) publish(); Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1)); return slot; } @@ -573,6 +751,12 @@ public final class PadBridge { return slot == 0 ? state : playerStates[slot]; } + private static boolean isNovaController(InputDevice device) { + return "Retroid Pocket Nova".equalsIgnoreCase(Build.MODEL) + && device.getVendorId() == 0x2022 + && (device.getProductId() == 0x3001 || device.getProductId() == 0x3002); + } + private boolean isPrimary(KeyEvent event) { int id = event.getDevice().getId(); int first = firstPlayerSlot(); @@ -585,6 +769,7 @@ public final class PadBridge { } private void leave(int slot, int id) { + if (slot == 0) clearBackQamWrites(); if (partners[slot] == NO_CONTROLLER) { free(slot); return; @@ -611,6 +796,7 @@ public final class PadBridge { partners[slot] = NO_CONTROLLER; clearJoyCons(slot); slotControllers.set(slot, NO_CONTROLLER); + if (slot == homeGuideSlot) homeGuideSlot = -1; if (slot == firstPlayerSlot()) releaseBackPaddles(); if (slot == 0) { state.clear(); @@ -667,7 +853,13 @@ public final class PadBridge { } playerWriters[slot] = player; } - player.writePad(playerStates[slot]); + PadState report = playerStates[slot]; + if (slot == homeGuideSlot) { + homeGuideReport.copyFrom(report); + homeGuideReport.press(PadState.GUIDE, true); + report = homeGuideReport; + } + player.writePad(report); } private void publish() { @@ -676,17 +868,17 @@ public final class PadBridge { statDropped++; return; } - boolean guide = systemGuidePressed || qamChordActive; - boolean qam = nativeQam() && (systemQamPressed || qamTapPressed); + boolean guide = systemGuidePressed || qamChordActive || homeGuidePressed; + boolean qam = nativeQam() && (systemQamPressed || qamTapPressed || backQamPressed); if (!guide && !qam) { - writer.writePad(state); + writePad(state); return; } effectiveState.copyFrom(state); if (guide) effectiveState.press(PadState.GUIDE, true); if (qam) effectiveState.press(PadState.QAM, true); if (chordButtonPressed) effectiveState.press(chordButton, true); - writer.writePad(effectiveState); + writePad(effectiveState); } public static boolean wiredXboxLayout(MotionEvent event) { diff --git a/app/src/main/java/com/droiddeck/launcher/input/PcKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/PcKeys.kt new file mode 100644 index 0000000000..f3ab1d4c6a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/PcKeys.kt @@ -0,0 +1,60 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import androidx.annotation.StringRes +import com.droiddeck.launcher.R + +data class PcKey( + val label: String, + val code: Int, + val weight: Float = 1f, + val shifted: String? = null, + @StringRes val labelRes: Int = 0, +) + +internal fun k(label: String, code: Int, weight: Float = 1f, shifted: String? = null) = PcKey(label, code, weight, shifted) + +internal fun k(@StringRes labelRes: Int, code: Int, weight: Float = 1f) = PcKey("", code, weight, null, labelRes) + +val PC_KEY_ROWS: List> = listOf( + listOf( + k(R.string.pckb_key_esc, 1), k("F1", 59), k("F2", 60), k("F3", 61), k("F4", 62), k("F5", 63), k("F6", 64), + k("F7", 65), k("F8", 66), k("F9", 67), k("F10", 68), k("F11", 87), k("F12", 88), + k(R.string.pckb_key_ins, 110), k(R.string.pckb_key_del, 111), k(R.string.pckb_key_home, 102), k(R.string.pckb_key_end, 107), k(R.string.pckb_key_pgup, 104), k(R.string.pckb_key_pgdn, 109), + ), + listOf( + k("`", 41, shifted = "~"), k("1", 2, shifted = "!"), k("2", 3, shifted = "@"), k("3", 4, shifted = "#"), + k("4", 5, shifted = "$"), k("5", 6, shifted = "%"), k("6", 7, shifted = "^"), k("7", 8, shifted = "&"), + k("8", 9, shifted = "*"), k("9", 10, shifted = "("), k("0", 11, shifted = ")"), k("-", 12, shifted = "_"), + k("=", 13, shifted = "+"), k(R.string.pckb_key_backspace, 14, 2f), + ), + listOf( + k(R.string.pckb_key_tab, 15, 1.5f), k("q", 16), k("w", 17), k("e", 18), k("r", 19), k("t", 20), k("y", 21), + k("u", 22), k("i", 23), k("o", 24), k("p", 25), k("[", 26, shifted = "{"), k("]", 27, shifted = "}"), + k("\\", 43, 1.5f, shifted = "|"), + ), + listOf( + k(R.string.pckb_key_caps, 58, 1.75f), k("a", 30), k("s", 31), k("d", 32), k("f", 33), k("g", 34), k("h", 35), + k("j", 36), k("k", 37), k("l", 38), k(";", 39, shifted = ":"), k("'", 40, shifted = "\""), + k(R.string.pckb_key_enter, 28, 2.25f), + ), + listOf( + k(R.string.pckb_key_shift, 42, 2.25f), k("z", 44), k("x", 45), k("c", 46), k("v", 47), k("b", 48), k("n", 49), + k("m", 50), k(",", 51, shifted = "<"), k(".", 52, shifted = ">"), k("/", 53, shifted = "?"), + k(R.string.pckb_key_shift, 54, 1.75f), k("↑", 103), + ), + listOf( + k(R.string.pckb_key_ctrl, 29, 1.5f), k(R.string.pckb_key_super, 125, 1.25f), k(R.string.pckb_key_alt, 56, 1.25f), k(R.string.pckb_key_space, 57, 6.25f), + k(R.string.pckb_key_altgr, 100, 1.25f), k(R.string.pckb_key_ctrl, 97, 1.25f), k("←", 105), k("↓", 108), k("→", 106), + ), +) + +val PC_MODIFIERS: Set = setOf(42, 54, 29, 97, 56, 100, 125) + +val PC_KEYS: Map = PC_KEY_ROWS.flatten().associateBy { it.code } + +fun pcKeyLabel(context: Context, code: Int): String { + val key = PC_KEYS[code] ?: return code.toString() + val text = if (key.labelRes != 0) context.getString(key.labelRes) else key.label + return if (text.length == 1 && text[0].isLetter()) text.uppercase() else text +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/PointerSubset.kt b/app/src/main/java/com/droiddeck/launcher/input/PointerSubset.kt new file mode 100644 index 0000000000..d6d990ea8f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/PointerSubset.kt @@ -0,0 +1,35 @@ +package com.droiddeck.launcher.input + +import android.view.MotionEvent + +internal fun MotionEvent.pointerSubset(pointerIdBits: Int): MotionEvent? { + val indices = (0 until pointerCount).filter { index -> + pointerIdBits and (1 shl getPointerId(index)) != 0 + } + if (indices.isEmpty()) return null + val splitIndex = indices.indexOf(actionIndex) + val splitAction = when (actionMasked) { + MotionEvent.ACTION_DOWN -> if (splitIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE + MotionEvent.ACTION_POINTER_DOWN -> if (splitIndex >= 0) { + if (indices.size == 1) MotionEvent.ACTION_DOWN + else MotionEvent.ACTION_POINTER_DOWN or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) + } else MotionEvent.ACTION_MOVE + MotionEvent.ACTION_UP -> if (splitIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE + MotionEvent.ACTION_POINTER_UP -> if (splitIndex >= 0) { + if (indices.size == 1) MotionEvent.ACTION_UP + else MotionEvent.ACTION_POINTER_UP or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) + } else MotionEvent.ACTION_MOVE + else -> action + } + val properties = Array(indices.size) { MotionEvent.PointerProperties() } + val coordinates = Array(indices.size) { MotionEvent.PointerCoords() } + indices.forEachIndexed { target, index -> + getPointerProperties(index, properties[target]) + getPointerCoords(index, coordinates[target]) + } + return MotionEvent.obtain( + downTime, eventTime, splitAction, indices.size, properties, coordinates, + metaState, buttonState, xPrecision, yPrecision, + deviceId, edgeFlags, source, flags, + ) +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/ScreenKey.kt b/app/src/main/java/com/droiddeck/launcher/input/ScreenKey.kt new file mode 100644 index 0000000000..2967a06f6a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ScreenKey.kt @@ -0,0 +1,63 @@ +package com.droiddeck.launcher.input + +import android.content.Context + +fun screenKeyLabel(context: Context, codes: List): String = + codes.filter { it != 0 }.joinToString("+") { short(context, it) } + +private fun short(context: Context, code: Int): String = when (code) { + 28 -> "⏎" + 14 -> "⌫" + 15 -> "Tab" + 57 -> "Space" + 58 -> "Caps" + 42, 54 -> "Shift" + 29, 97 -> "Ctrl" + 56 -> "Alt" + 100 -> "AltGr" + 125 -> "Super" + else -> pcKeyLabel(context, code) +} + +const val SCREEN_KEY_PILL = 0 +const val SCREEN_KEY_ROUND = 1 +const val SCREEN_KEY_CIRCLE = 2 +const val SCREEN_KEY_RECT = 3 +const val SCREEN_KEY_TRIGGER = 4 +const val SCREEN_KEY_DPAD = 5 +const val SCREEN_KEY_STICK = 6 + +val SCREEN_KEY_DPAD_DIRS = listOf("↑", "→", "↓", "←") +val SCREEN_KEY_STICK_DIRS = listOf("↑", "↗", "→", "↘", "↓", "↙", "←", "↖") + +fun screenKeyDirections(shape: Int): List = when (shape) { + SCREEN_KEY_DPAD -> SCREEN_KEY_DPAD_DIRS + SCREEN_KEY_STICK -> SCREEN_KEY_STICK_DIRS + else -> emptyList() +} + +val SCREEN_KEY_SHAPES = + listOf( + SCREEN_KEY_PILL, SCREEN_KEY_ROUND, SCREEN_KEY_CIRCLE, SCREEN_KEY_RECT, + SCREEN_KEY_TRIGGER, SCREEN_KEY_DPAD, SCREEN_KEY_STICK, + ) + +data class ScreenKey( + val codes: List, + val x: Float, + val y: Float, + val size: Int, + val glyph: String = "", + val text: String = "", + val image: String = "", + val opacity: Float = 1f, + val shape: Int = SCREEN_KEY_PILL, + val toggle: Boolean = false, + val labels: Boolean = true, +) { + fun shownLabel(context: Context): String = when { + text.isNotEmpty() -> text + glyph.isNotEmpty() -> glyph + else -> screenKeyLabel(context, codes) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/ScreenKeyIcons.kt b/app/src/main/java/com/droiddeck/launcher/input/ScreenKeyIcons.kt new file mode 100644 index 0000000000..b1ea677b99 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ScreenKeyIcons.kt @@ -0,0 +1,148 @@ +package com.droiddeck.launcher.input + +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Path + +object ScreenKeyIcons { + fun has(code: Int): Boolean = code in SET + + private val SET = setOf(28, 14, 15, 57, 42, 54, 29, 97, 125, 103, 108, 105, 106) + + fun draw(canvas: Canvas, code: Int, cx: Float, cy: Float, box: Float, paint: Paint): Boolean { + if (!has(code)) return false + val h = box / 2f + val stroke = box * 0.085f + val path = Path() + paint.style = Paint.Style.STROKE + paint.strokeWidth = stroke + paint.strokeCap = Paint.Cap.ROUND + paint.strokeJoin = Paint.Join.ROUND + when (code) { + 28 -> { + path.moveTo(cx - 0.34f * h, cy - 0.22f * h) + path.lineTo(cx + 0.30f * h, cy - 0.22f * h) + path.lineTo(cx + 0.30f * h, cy + 0.24f * h) + path.lineTo(cx - 0.04f * h, cy + 0.24f * h) + canvas.drawPath(path, paint) + path.reset() + path.moveTo(cx + 0.12f * h, cy + 0.06f * h) + path.lineTo(cx - 0.04f * h, cy + 0.24f * h) + path.lineTo(cx + 0.12f * h, cy + 0.42f * h) + canvas.drawPath(path, paint) + } + + 14 -> { + path.moveTo(cx - 0.72f * h, cy) + path.lineTo(cx - 0.10f * h, cy - 0.50f * h) + path.lineTo(cx + 0.74f * h, cy - 0.50f * h) + path.lineTo(cx + 0.74f * h, cy + 0.50f * h) + path.lineTo(cx - 0.10f * h, cy + 0.50f * h) + path.close() + canvas.drawPath(path, paint) + path.reset() + path.moveTo(cx + 0.10f * h, cy - 0.20f * h) + path.lineTo(cx + 0.44f * h, cy + 0.20f * h) + path.moveTo(cx + 0.44f * h, cy - 0.20f * h) + path.lineTo(cx + 0.10f * h, cy + 0.20f * h) + canvas.drawPath(path, paint) + } + + 15 -> { + path.moveTo(cx - 0.72f * h, cy) + path.lineTo(cx + 0.44f * h, cy) + path.moveTo(cx + 0.14f * h, cy - 0.30f * h) + path.lineTo(cx + 0.46f * h, cy) + path.lineTo(cx + 0.14f * h, cy + 0.30f * h) + canvas.drawPath(path, paint) + path.reset() + path.moveTo(cx + 0.70f * h, cy - 0.48f * h) + path.lineTo(cx + 0.70f * h, cy + 0.48f * h) + canvas.drawPath(path, paint) + } + + 57 -> { + path.moveTo(cx - 0.64f * h, cy - 0.22f * h) + path.lineTo(cx - 0.64f * h, cy + 0.20f * h) + path.lineTo(cx + 0.64f * h, cy + 0.20f * h) + path.lineTo(cx + 0.64f * h, cy - 0.22f * h) + canvas.drawPath(path, paint) + } + + 42, 54 -> { + paint.style = Paint.Style.FILL + path.moveTo(cx, cy - 0.55f * h) + path.lineTo(cx + 0.62f * h, cy + 0.02f * h) + path.lineTo(cx + 0.26f * h, cy + 0.02f * h) + path.lineTo(cx + 0.26f * h, cy + 0.32f * h) + path.lineTo(cx - 0.26f * h, cy + 0.32f * h) + path.lineTo(cx - 0.26f * h, cy + 0.02f * h) + path.lineTo(cx - 0.62f * h, cy + 0.02f * h) + path.close() + canvas.drawPath(path, paint) + path.reset() + path.moveTo(cx - 0.26f * h, cy + 0.44f * h) + path.lineTo(cx + 0.26f * h, cy + 0.44f * h) + path.lineTo(cx + 0.26f * h, cy + 0.58f * h) + path.lineTo(cx - 0.26f * h, cy + 0.58f * h) + path.close() + canvas.drawPath(path, paint) + } + + 29, 97 -> { + path.moveTo(cx - 0.58f * h, cy + 0.26f * h) + path.lineTo(cx, cy - 0.28f * h) + path.lineTo(cx + 0.58f * h, cy + 0.26f * h) + canvas.drawPath(path, paint) + } + + 125 -> { + paint.style = Paint.Style.FILL + val gap = 0.07f * h + val side = 0.34f * h + for (dxi in -1..1 step 2) for (dyi in -1..1 step 2) { + val left = cx + dxi * (gap + side / 2f) - side / 2f + val top = cy + dyi * (gap + side / 2f) - side / 2f + path.addRect(left, top, left + side, top + side, Path.Direction.CW) + } + canvas.drawPath(path, paint) + } + + 103, 108, 105, 106 -> { + paint.style = Paint.Style.FILL + val r = 0.52f * h + when (code) { + 103 -> { + path.moveTo(cx, cy - r) + path.lineTo(cx + r * 0.80f, cy + r * 0.55f) + path.lineTo(cx - r * 0.80f, cy + r * 0.55f) + } + + 108 -> { + path.moveTo(cx, cy + r) + path.lineTo(cx + r * 0.80f, cy - r * 0.55f) + path.lineTo(cx - r * 0.80f, cy - r * 0.55f) + } + + 105 -> { + path.moveTo(cx - r, cy) + path.lineTo(cx + r * 0.55f, cy - r * 0.80f) + path.lineTo(cx + r * 0.55f, cy + r * 0.80f) + } + + else -> { + path.moveTo(cx + r, cy) + path.lineTo(cx - r * 0.55f, cy - r * 0.80f) + path.lineTo(cx - r * 0.55f, cy + r * 0.80f) + } + } + path.close() + canvas.drawPath(path, paint) + } + } + paint.style = Paint.Style.FILL + paint.strokeCap = Paint.Cap.BUTT + paint.strokeJoin = Paint.Join.MITER + return true + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt new file mode 100644 index 0000000000..c7a9291e9e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt @@ -0,0 +1,1094 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.PointF +import android.graphics.Rect +import android.graphics.RectF +import android.graphics.Typeface +import android.os.Build +import android.view.MotionEvent +import android.view.View +import android.view.WindowInsets +import java.io.File +import kotlin.math.abs +import kotlin.math.hypot +import kotlin.math.round + +class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit) : View(context) { + private class Entry(val codes: List) { + var glyph = "" + var text = "" + var image = "" + var bitmap: Bitmap? = null + var bitmapFor = "" + var x = 0.5f + var y = 0.5f + var size = DEFAULT_SIZE + var opacity = 1f + var shape = SCREEN_KEY_PILL + var toggle = false + var labels = true + var armed = -1 + var cx = 0f + var cy = 0f + var halfW = 0f + var halfH = 0f + } + + private val entries = mutableListOf() + private val down = HashMap() + private val latched = mutableListOf() + private val dpadDown = HashMap() + private val stickEntries = HashMap() + private val stickCodes = HashMap>() + private val held = HashMap() + private var forwardedPointerBits = 0 + private var addX = -1f + private var addY = -1f + private var pressX = 0f + private var pressY = 0f + private var guideX = -1f + private var guideY = -1f + private val addPress = Runnable { addX = pressX; addY = pressY; onAdd?.invoke() } + private var editing = false + private var selected: Entry? = null + private var dragX = 0f + private var dragY = 0f + private var dragging = false + private var moved = false + private var toolbarDrag = false + private var safe = Rect() + private var tint = ControllerPrefs.STEAM_BLUE + + init { + ControllerPrefs.screenKeys(context).forEach { key -> entries += entryOf(key) } + } + + var followSteam = false + set(value) { + if (field == value) return + field = value + invalidate() + } + + var steamStyle: () -> Pair? = { null } + + var onAdd: (() -> Unit)? = null + var onSelect: ((List) -> Unit)? = null + var onEditingChanged: ((Boolean) -> Unit)? = null + var onTouchMiss: ((MotionEvent) -> Unit)? = null + + private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val ringPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textAlign = Paint.Align.CENTER + typeface = Typeface.DEFAULT_BOLD + } + private val gridPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val rect = RectF() + private val bodyPathRect = RectF() + private val bodyPath = android.graphics.Path() + private val clipPath = android.graphics.Path() + private val imageRect = RectF() + private val bitmapRect = RectF() + + private val capsuleRadius = dp(24f) + private val capsuleGap = dp(62f) + private val toolbar = PointF() + private val addCenter = PointF() + private val doneCenter = PointF() + + fun startEditing() { + if (editing) return + editing = true + releaseAll() + selected = null + placeToolbar() + invalidate() + onEditingChanged?.invoke(true) + } + + fun stopEditing() { + if (!editing) return + releaseAll() + editing = false + selected = null + save() + invalidate() + onEditingChanged?.invoke(false) + } + + fun add(codes: List) { + if (codes.isEmpty()) return + entries.firstOrNull { it.codes == codes }?.let { + selected = it + invalidate() + return + } + val entry = Entry(codes) + if (addX >= 0f && width > 0) { + entry.x = (addX / width).coerceIn(0.05f, 0.95f) + entry.y = (addY / height).coerceIn(0.05f, 0.95f) + } else { + entry.x = (0.30f + 0.08f * (entries.size % 5)).coerceAtMost(0.70f) + entry.y = 0.62f + } + addX = -1f + addY = -1f + entries += entry + if (width > 0) measure(entry) + selected = entry + save() + invalidate() + } + + fun remove(codes: List) { + val entry = entries.firstOrNull { it.codes == codes } ?: return + entries.remove(entry) + if (selected === entry) selected = null + save() + invalidate() + } + + fun setCodes(from: List, to: List): ScreenKey? { + if (to.isEmpty()) return null + val index = entries.indexOfFirst { it.codes == from } + if (index < 0) return null + val old = entries[index] + if (to != from && entries.any { it !== old && it.codes == to }) return null + val fresh = Entry(to).also { + it.glyph = old.glyph + it.text = old.text + it.image = old.image + it.bitmap = old.bitmap + it.bitmapFor = old.bitmapFor + it.x = old.x + it.y = old.y + it.size = old.size + it.opacity = old.opacity + it.shape = old.shape + it.toggle = old.toggle + it.labels = old.labels + } + entries[index] = fresh + measure(fresh) + if (selected === old) selected = fresh + save() + invalidate() + return stateOf(fresh.codes) + } + + fun setText(codes: List, text: String) { + val entry = entries.firstOrNull { it.codes == codes } ?: return + entry.text = text + measure(entry) + save() + invalidate() + } + + fun setImage(codes: List, image: String) { + val entry = entries.firstOrNull { it.codes == codes } ?: return + val previous = entry.image + entry.image = image + entry.bitmap = null + entry.bitmapFor = "" + if (previous.isNotEmpty() && previous != image) File(File(context.filesDir, IMAGE_DIR), previous).delete() + measure(entry) + save() + invalidate() + } + + fun resize(codes: List, size: Int) { + val entry = entries.firstOrNull { it.codes == codes } ?: return + entry.size = size.coerceIn(MIN_SIZE, MAX_SIZE) + measure(entry) + save() + invalidate() + } + + fun setOpacity(codes: List, opacity: Float) { + val entry = entries.firstOrNull { it.codes == codes } ?: return + entry.opacity = opacity.coerceIn(0.2f, 1f) + save() + invalidate() + } + + fun setShape(codes: List, shape: Int) { + val entry = entries.firstOrNull { it.codes == codes } ?: return + entry.shape = shape.coerceIn(SCREEN_KEY_PILL, SCREEN_KEY_STICK) + measure(entry) + save() + invalidate() + } + + fun setToggle(codes: List, toggle: Boolean) { + val entry = entries.firstOrNull { it.codes == codes } ?: return + entry.toggle = toggle + if (!toggle && latched.remove(entry)) release(entry) + save() + invalidate() + } + + fun setLabels(codes: List, labels: Boolean) { + val entry = entries.firstOrNull { it.codes == codes } ?: return + entry.labels = labels + save() + invalidate() + } + + fun setDirection(codes: List, index: Int, code: Int): ScreenKey? { + val entry = entries.firstOrNull { it.codes == codes } ?: entries.firstOrNull { it.codes == trimmed(codes) } ?: return null + val next = entry.codes.toMutableList() + while (next.size <= index) next += 0 + next[index] = code + val nextCodes = trimmed(next) + if (entries.any { it !== entry && it.codes == nextCodes }) return null + val updated = Entry(nextCodes).also { + it.glyph = entry.glyph + it.text = entry.text + it.image = entry.image + it.bitmap = entry.bitmap + it.bitmapFor = entry.bitmapFor + it.x = entry.x + it.y = entry.y + it.size = entry.size + it.opacity = entry.opacity + it.shape = entry.shape + it.toggle = entry.toggle + it.labels = entry.labels + } + entries[entries.indexOf(entry)] = updated + measure(updated) + if (selected === entry) selected = updated + save() + invalidate() + return stateOf(updated.codes) + } + + private fun trimmed(codes: List): List = codes.dropLastWhile { it == 0 }.ifEmpty { listOf(0) } + + fun stateOf(codes: List): ScreenKey? = entries.firstOrNull { it.codes == codes }?.let { + ScreenKey(it.codes, it.x, it.y, it.size, it.glyph, it.text, it.image, it.opacity, it.shape, it.toggle, it.labels) + } + + fun deselect() { + if (selected == null) return + selected = null + invalidate() + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + refreshAppearance() + } + + fun refreshAppearance() { + tint = ControllerPrefs.read(context).tint + invalidate() + } + + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + super.onSizeChanged(w, h, oldw, oldh) + entries.forEach { measure(it) } + placeToolbar() + } + + override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets { + val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null + val fresh = Rect( + cutout?.safeInsetLeft ?: 0, cutout?.safeInsetTop ?: 0, + cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0, + ) + if (fresh != safe) { + safe = fresh + placeToolbar() + invalidate() + } + return super.onApplyWindowInsets(insets) + } + + override fun onDetachedFromWindow() { + releaseAll() + super.onDetachedFromWindow() + } + + override fun onVisibilityChanged(changedView: View, visibility: Int) { + super.onVisibilityChanged(changedView, visibility) + if (visibility != VISIBLE) releaseAll() + } + + override fun setVisibility(visibility: Int) { + super.setVisibility(visibility) + if (visibility != VISIBLE) releaseAll() + } + + fun releaseAll() { + dpadDown.values.forEach { releaseKey(it) } + dpadDown.clear() + entries.forEach { it.armed = -1 } + stickCodes.values.flatten().forEach { if (it != 0) releaseKey(it) } + stickCodes.clear() + stickEntries.clear() + down.values.forEach { release(it) } + down.clear() + latched.toList().forEach { release(it) } + latched.clear() + invalidate() + } + + private fun snap(value: Float) = if (width > 0) round(value / (width / 100f)) * (width / 100f) else value + + private fun placeToolbar() { + if (width == 0 || height == 0) return + if (toolbar.x == 0f && toolbar.y == 0f) { + toolbar.set(width - safe.right - capsuleGap - capsuleRadius, height - safe.bottom - capsuleRadius - dp(20f)) + } + addCenter.set(toolbar.x - capsuleGap / 2f, toolbar.y) + doneCenter.set(toolbar.x + capsuleGap / 2f, toolbar.y) + } + + private fun entryOf(key: ScreenKey): Entry = Entry(key.codes).also { + it.glyph = key.glyph + it.text = key.text + it.image = key.image + it.x = key.x + it.y = key.y + it.size = key.size + it.opacity = key.opacity + it.shape = key.shape + it.toggle = key.toggle + it.labels = key.labels + } + + private fun label(entry: Entry) = when { + entry.text.isNotEmpty() -> entry.text + entry.glyph.isNotEmpty() -> entry.glyph + else -> screenKeyLabel(context, entry.codes) + } + + private fun bitmapFor(entry: Entry): Bitmap? { + if (entry.image.isEmpty()) return null + if (entry.bitmapFor == entry.image) return entry.bitmap + val file = File(File(context.filesDir, IMAGE_DIR), entry.image) + val bitmap = if (file.isFile) BitmapFactory.decodeFile(file.absolutePath) else null + entry.bitmap = bitmap + entry.bitmapFor = entry.image + return bitmap + } + + private fun measure(entry: Entry) { + val h = dp(entry.size.toFloat()) + entry.halfH = h / 2f + entry.halfW = when { + entry.shape == SCREEN_KEY_CIRCLE -> entry.halfH + entry.shape == SCREEN_KEY_TRIGGER -> entry.halfH * 1.7f + entry.shape == SCREEN_KEY_DPAD || entry.shape == SCREEN_KEY_STICK -> entry.halfH * 1.15f + entry.image.isNotEmpty() -> entry.halfH * 1.15f + hasIcon(entry) -> entry.halfH * 1.15f + else -> { + val chars = label(entry).length + entry.halfH * (0.55f * chars + 1.05f).coerceIn(1.7f, 4.6f) + } + } + entry.cx = entry.x * width + entry.cy = entry.y * height + } + + private fun hasIcon(entry: Entry): Boolean = + entry.text.isEmpty() && entry.glyph.isEmpty() && entry.codes.size == 1 && ScreenKeyIcons.has(entry.codes[0]) + + private fun unit() = minOf(width / 1280f, height / 720f) + + private fun accent(): Pair { + val style = if (followSteam) steamStyle() else null + return (style?.first ?: tint) to (style?.second ?: 1f) + } + + private fun tinted(color: Int, alpha: Float): Int { + val scale = accent().second + return Color.argb( + (alpha * scale * 255f).toInt().coerceIn(0, 255), + Color.red(color), Color.green(color), Color.blue(color), + ) + } + + private fun triggerPath(entry: Entry, path: android.graphics.Path, inset: Float = 0f) { + val lean = (entry.halfH - inset) * 0.6f + val left = entry.cx - entry.halfW + inset + val right = entry.cx + entry.halfW - inset + val top = entry.cy - entry.halfH + inset + val bottom = entry.cy + entry.halfH - inset + path.reset() + path.moveTo(left + lean, top) + path.lineTo(right, top) + path.lineTo(right - lean, bottom) + path.lineTo(left, bottom) + path.close() + } + + private fun body(canvas: Canvas, entry: Entry, radius: Float, paint: Paint, inset: Float = 0f) { + if (entry.shape != SCREEN_KEY_TRIGGER) { + canvas.drawRoundRect(rect, radius, radius, paint) + return + } + triggerPath(entry, bodyPath, inset) + canvas.drawPath(bodyPath, paint) + } + + private fun drawDpad(canvas: Canvas, entry: Entry) { + val color = accent().first + val alpha = entry.opacity + val r = minOf(entry.halfW, entry.halfH) + val t = r * 0.42f + val hairline = maxOf(dp(1.2f), entry.halfH * 0.032f) + val engaged = entry.armed >= 0 + crossPath(entry, bodyPath, r, t) + fillPaint.style = Paint.Style.FILL + fillPaint.color = tinted(color, if (entry.armed >= 0) 0.26f * alpha else 0.10f * alpha) + canvas.drawPath(bodyPath, fillPaint) + if (entry.armed >= 0) { + armRect(entry, bodyPathRect, entry.armed, r, t) + fillPaint.color = tinted(color, 0.55f * alpha) + canvas.drawRoundRect(bodyPathRect, t * 0.6f, t * 0.6f, fillPaint) + } + strokePaint.strokeJoin = Paint.Join.ROUND + strokePaint.strokeWidth = if (engaged) hairline * 1.6f else hairline + strokePaint.color = tinted(color, (if (editing) 0.90f else 0.80f) * alpha) + canvas.drawPath(bodyPath, strokePaint) + textPaint.setShadowLayer(0f, 0f, 0f, 0) + fillPaint.color = tinted(color, if (editing) 0.90f else 0.80f) + DPAD_DIRS.forEachIndexed { index, dir -> + val on = entry.armed == index + val code = entry.codes.getOrNull(index) ?: 0 + val name = if (code == 0) "" else screenKeyLabel(context, listOf(code)) + if (entry.labels && name.isNotEmpty()) { + textPaint.color = if (on) Color.WHITE else tinted(color, alpha) + textPaint.textSize = dp(48f) + val fit = 48f * (t * 1.9f) / textPaint.measureText(name).coerceAtLeast(1f) + textPaint.textSize = minOf(fit, t * 1.7f).coerceIn(dp(8f), dp(60f)) + val tx = entry.cx + dir.first * (r - t * 0.6f) + val ty = entry.cy + dir.second * (r - t * 0.6f) + canvas.drawText(name, tx, ty - (textPaint.ascent() + textPaint.descent()) / 2f, textPaint) + } else { + fillPaint.color = if (on) Color.WHITE else tinted(color, if (editing) 0.90f else 0.80f) + arrow(canvas, fillPaint, entry.cx, entry.cy, r - t * 0.55f, dir.first, dir.second, t * 0.8f) + } + } + if (editing && selected === entry) { + ringPaint.strokeWidth = hairline * 0.8f + ringPaint.color = tinted(color, 0.9f) + ringPaint.style = Paint.Style.STROKE + canvas.drawCircle(entry.cx, entry.cy, r + hairline * 3f, ringPaint) + } + } + + private fun crossPath(entry: Entry, path: android.graphics.Path, r: Float, t: Float) { + val cx = entry.cx + val cy = entry.cy + path.reset() + path.moveTo(cx - t, cy - r) + path.lineTo(cx + t, cy - r) + path.lineTo(cx + t, cy - t) + path.lineTo(cx + r, cy - t) + path.lineTo(cx + r, cy + t) + path.lineTo(cx + t, cy + t) + path.lineTo(cx + t, cy + r) + path.lineTo(cx - t, cy + r) + path.lineTo(cx - t, cy + t) + path.lineTo(cx - r, cy + t) + path.lineTo(cx - r, cy - t) + path.lineTo(cx - t, cy - t) + path.close() + } + + private fun armRect(entry: Entry, rect: RectF, index: Int, r: Float, t: Float) { + when (index) { + 0 -> rect.set(entry.cx - t, entry.cy - r, entry.cx + t, entry.cy - t) + 1 -> rect.set(entry.cx + t, entry.cy - t, entry.cx + r, entry.cy + t) + 2 -> rect.set(entry.cx - t, entry.cy + t, entry.cx + t, entry.cy + r) + else -> rect.set(entry.cx - r, entry.cy - t, entry.cx - t, entry.cy + t) + } + } + + private fun arrow(canvas: Canvas, paint: Paint, cx: Float, cy: Float, dist: Float, dx: Float, dy: Float, size: Float) { + val tipX = cx + dx * dist + val tipY = cy + dy * dist + val baseX = cx + dx * (dist - size) + val baseY = cy + dy * (dist - size) + val nx = -dy * size * 0.62f + val ny = dx * size * 0.62f + bodyPath.reset() + bodyPath.moveTo(tipX, tipY) + bodyPath.lineTo(baseX + nx, baseY + ny) + bodyPath.lineTo(baseX - nx, baseY - ny) + bodyPath.close() + canvas.drawPath(bodyPath, paint) + } + + private fun armOf(entry: Entry, x: Float, y: Float): Int { + val dx = x - entry.cx + val dy = y - entry.cy + return if (abs(dx) > abs(dy)) (if (dx > 0f) 1 else 3) else (if (dy > 0f) 2 else 0) + } + + private fun drawStick(canvas: Canvas, entry: Entry) { + val color = accent().first + val alpha = entry.opacity + val engaged = entry.armed >= 0 + val radius = minOf(entry.halfW, entry.halfH) + val hairline = maxOf(dp(1.2f), entry.halfH * 0.032f) + fillPaint.style = Paint.Style.FILL + fillPaint.color = tinted(color, 0.14f * alpha) + canvas.drawCircle(entry.cx, entry.cy, radius - hairline, fillPaint) + strokePaint.strokeWidth = if (engaged) hairline * 1.6f else hairline + strokePaint.color = tinted(color, (if (editing) 0.90f else 0.80f) * alpha) + canvas.drawCircle(entry.cx, entry.cy, radius - hairline / 2f, strokePaint) + val dir = if (engaged) STICK_DIRS[entry.armed.coerceIn(0, 7)] else 0f to 0f + val knob = radius * 0.36f + fillPaint.color = tinted(color, if (engaged) 0.55f * alpha else 0.24f * alpha) + canvas.drawCircle(entry.cx + dir.first * radius * 0.40f, entry.cy + dir.second * radius * 0.40f, knob, fillPaint) + strokePaint.strokeWidth = hairline + strokePaint.color = tinted(color, (if (editing) 0.90f else 0.80f) * alpha) + canvas.drawCircle(entry.cx + dir.first * radius * 0.40f, entry.cy + dir.second * radius * 0.40f, knob, strokePaint) + textPaint.setShadowLayer(0f, 0f, 0f, 0) + STICK_DIRS.forEachIndexed { index, unit -> + val on = entry.armed == index + val code = entry.codes.getOrNull(index) ?: 0 + val name = if (code == 0) "" else screenKeyLabel(context, listOf(code)) + if (entry.labels && name.isNotEmpty()) { + textPaint.color = if (on) Color.WHITE else tinted(color, 0.85f * alpha) + textPaint.textSize = dp(48f) + val fit = 48f * (radius * 0.34f) / textPaint.measureText(name).coerceAtLeast(1f) + textPaint.textSize = minOf(fit, radius * 0.22f).coerceAtLeast(dp(6f)) + val tx = entry.cx + unit.first * radius * 0.66f + val ty = entry.cy + unit.second * radius * 0.66f + canvas.drawText(name, tx, ty - (textPaint.ascent() + textPaint.descent()) / 2f, textPaint) + } else { + fillPaint.color = if (on) Color.WHITE else tinted(color, if (editing) 0.88f else 0.72f) + arrow(canvas, fillPaint, entry.cx, entry.cy, radius * 0.88f, unit.first, unit.second, radius * 0.16f) + } + } + if (editing && selected === entry) { + ringPaint.strokeWidth = hairline * 0.8f + ringPaint.color = tinted(color, 0.9f) + ringPaint.style = Paint.Style.STROKE + canvas.drawCircle(entry.cx, entry.cy, radius + hairline * 3f, ringPaint) + } + } + + private fun directionCodes(entry: Entry, index: Int): List { + if (index < 0) return emptyList() + val code = entry.codes.getOrNull(index) ?: 0 + if (code != 0) return listOf(code) + if (entry.shape != SCREEN_KEY_STICK || index % 2 == 0) return emptyList() + return listOfNotNull( + entry.codes.getOrNull((index + 7) % 8)?.takeIf { it != 0 }, + entry.codes.getOrNull((index + 1) % 8)?.takeIf { it != 0 }, + ) + } + + private fun stickSector(entry: Entry, x: Float, y: Float): Int { + val dx = x - entry.cx + val dy = y - entry.cy + if (hypot(dx, dy) < minOf(entry.halfW, entry.halfH) * 0.24f) return -1 + val degrees = Math.toDegrees(kotlin.math.atan2(dy, dx).toDouble()).toFloat() + val index = (round(degrees / 45f).toInt() + 2) % 8 + return (index + 8) % 8 + } + + private fun radiusOf(entry: Entry): Float = when (entry.shape) { + SCREEN_KEY_ROUND -> entry.halfH * 0.30f + SCREEN_KEY_RECT -> entry.halfH * 0.12f + SCREEN_KEY_TRIGGER -> entry.halfH * 0.45f + else -> entry.halfH + } + + private fun entryAt(x: Float, y: Float): Entry? = entries.lastOrNull { entry -> + x >= entry.cx - entry.halfW && x <= entry.cx + entry.halfW && y >= entry.cy - entry.halfH && y <= entry.cy + entry.halfH + } + + private fun inCircle(center: PointF, x: Float, y: Float, radius: Float) = hypot(x - center.x, y - center.y) <= radius + + private fun inToolbar(x: Float, y: Float): Boolean = + editing && x >= toolbar.x - capsuleGap / 2f - capsuleRadius && x <= toolbar.x + capsuleGap / 2f + capsuleRadius && + y >= toolbar.y - capsuleRadius && y <= toolbar.y + capsuleRadius + + override fun onDraw(canvas: Canvas) { + if (editing) drawGrid(canvas) + entries.forEach { draw(canvas, it) } + if (editing) { + drawGuides(canvas) + drawToolbar(canvas) + } + } + + private fun drawGuides(canvas: Canvas) { + if (guideX < 0f && guideY < 0f) return + gridPaint.strokeWidth = dp(1f) + gridPaint.color = tinted(accent().first, 0.9f) + if (guideX >= 0f) canvas.drawLine(guideX, 0f, guideX, height.toFloat(), gridPaint) + if (guideY >= 0f) canvas.drawLine(0f, guideY, width.toFloat(), guideY, gridPaint) + } + + private fun drawGrid(canvas: Canvas) { + if (width == 0 || height == 0) return + val step = width / 100f + gridPaint.strokeWidth = dp(1f) + gridPaint.color = Color.argb(38, 255, 255, 255) + var x = step + while (x < width) { + canvas.drawLine(x, 0f, x, height.toFloat(), gridPaint) + x += step + } + var y = step + while (y < height) { + canvas.drawLine(0f, y, width.toFloat(), y, gridPaint) + y += step + } + gridPaint.color = Color.argb(96, 255, 255, 255) + gridPaint.strokeWidth = dp(1f) + canvas.drawLine(width / 2f, 0f, width / 2f, height.toFloat(), gridPaint) + canvas.drawLine(0f, height / 2f, width.toFloat(), height / 2f, gridPaint) + } + + private fun draw(canvas: Canvas, entry: Entry) { + if (entry.shape == SCREEN_KEY_DPAD) { + drawDpad(canvas, entry) + return + } + if (entry.shape == SCREEN_KEY_STICK) { + drawStick(canvas, entry) + return + } + val style = if (followSteam) steamStyle() else null + val engaged = down.values.any { it === entry } || latched.contains(entry) + val bitmap = bitmapFor(entry) + val icon = bitmap == null && hasIcon(entry) + val frameless = entry.text.isBlank() && (bitmap != null || icon) + val alpha = entry.opacity + val h2 = entry.halfH * 2f + val radius = radiusOf(entry) + val selectedNow = editing && selected === entry + val hairline = maxOf(dp(1.2f), h2 * 0.032f) + rect.set(entry.cx - entry.halfW, entry.cy - entry.halfH, entry.cx + entry.halfW, entry.cy + entry.halfH) + val inkColor: Int + if (style != null) { + val inkAlpha = (255f * style.second * alpha).toInt().coerceIn(30, 255) + inkColor = Color.argb(inkAlpha, Color.red(style.first), Color.green(style.first), Color.blue(style.first)) + fillPaint.style = Paint.Style.FILL + if (engaged) { + fillPaint.color = Color.argb((inkAlpha * 0.85f).toInt(), 230, 233, 236) + body(canvas, entry, radius, fillPaint) + } + if (frameless) { + if (engaged) { + fillPaint.color = Color.argb((inkAlpha * 0.45f).toInt(), 230, 233, 236) + body(canvas, entry, radius, fillPaint) + } + } else { + strokePaint.color = if (selectedNow) Color.rgb(26, 159, 255) else inkColor + strokePaint.strokeWidth = if (engaged) hairline * 1.6f else hairline + body(canvas, entry, radius, strokePaint) + } + } else { + fillPaint.style = Paint.Style.FILL + if (!frameless) { + fillPaint.color = tinted(BODY, 0.60f * alpha) + canvas.drawRoundRect(rect, radius, radius, fillPaint) + } + if (engaged) { + fillPaint.color = tinted(accent().first, if (frameless) 0.32f * alpha else 0.42f * alpha) + canvas.drawRoundRect(rect, radius, radius, fillPaint) + } + if (!frameless) { + strokePaint.strokeWidth = if (engaged) hairline * 1.6f else hairline + strokePaint.color = tinted( + accent().first, + (if (engaged) 0.96f else if (editing) 0.80f else 0.68f) * alpha, + ) + body(canvas, entry, radius, strokePaint) + } + inkColor = if (engaged) Color.WHITE else tinted(accent().first, alpha) + } + if (editing && selected === entry) { + ringPaint.strokeWidth = hairline * 0.8f + ringPaint.color = tinted(accent().first, 0.9f) + val gap = hairline * 2.4f + rect.set( + entry.cx - entry.halfW - gap, entry.cy - entry.halfH - gap, + entry.cx + entry.halfW + gap, entry.cy + entry.halfH + gap, + ) + if (entry.shape == SCREEN_KEY_TRIGGER) { + body(canvas, entry, radius + gap, ringPaint, gap) + } else { + canvas.drawRoundRect(rect, radius + gap, radius + gap, ringPaint) + } + rect.set(entry.cx - entry.halfW, entry.cy - entry.halfH, entry.cx + entry.halfW, entry.cy + entry.halfH) + } + + if (bitmap != null) { + imageRect.set(rect) + canvas.save() + clipPath.reset() + when (entry.shape) { + SCREEN_KEY_CIRCLE -> clipPath.addCircle( + entry.cx, entry.cy, minOf(entry.halfW, entry.halfH), android.graphics.Path.Direction.CW, + ) + SCREEN_KEY_TRIGGER -> triggerPath(entry, clipPath, 0f) + else -> clipPath.addRoundRect(rect, radius, radius, android.graphics.Path.Direction.CW) + } + canvas.clipPath(clipPath) + val scale = maxOf(imageRect.width() / bitmap.width, imageRect.height() / bitmap.height) + val w = bitmap.width * scale + val h = bitmap.height * scale + bitmapRect.set( + imageRect.centerX() - w / 2f, imageRect.centerY() - h / 2f, + imageRect.centerX() + w / 2f, imageRect.centerY() + h / 2f, + ) + canvas.drawBitmap(bitmap, null, bitmapRect, fillPaint) + canvas.restore() + } + + val name = label(entry) + textPaint.color = inkColor + if (bitmap != null && name.isEmpty()) return + var iconDrawn = false + if (icon) { + val box = minOf(entry.halfW, entry.halfH) * 1.35f + iconDrawn = ScreenKeyIcons.draw(canvas, entry.codes[0], entry.cx, entry.cy, box, textPaint) + textPaint.color = inkColor + } + if (iconDrawn || name.isEmpty()) return + val overImage = bitmap != null + if (overImage) textPaint.color = Color.WHITE + textPaint.setShadowLayer(if (overImage) dp(3f) else 0f, 0f, 0f, Color.argb(200, 0, 0, 0)) + textPaint.textSize = dp(48f) + val available = rect.width() - hairline * 4f + val fit = 48f * available / textPaint.measureText(name).coerceAtLeast(1f) + textPaint.textSize = minOf(fit, entry.halfH * 1.15f).coerceIn(dp(8f), dp(120f)) + canvas.drawText(name, entry.cx, entry.cy - (textPaint.ascent() + textPaint.descent()) / 2f, textPaint) + textPaint.clearShadowLayer() + } + + private fun drawToolbar(canvas: Canvas) { + val (color, _) = accent() + val capsule = RectF( + toolbar.x - capsuleGap / 2f - capsuleRadius, toolbar.y - capsuleRadius, + toolbar.x + capsuleGap / 2f + capsuleRadius, toolbar.y + capsuleRadius, + ) + fillPaint.style = Paint.Style.FILL + fillPaint.color = tinted(color, 0.30f) + canvas.drawRoundRect(capsule, capsuleRadius, capsuleRadius, fillPaint) + strokePaint.strokeWidth = dp(1.5f) + strokePaint.color = tinted(color, 0.85f) + canvas.drawRoundRect(capsule, capsuleRadius, capsuleRadius, strokePaint) + + textPaint.color = Color.WHITE + textPaint.setShadowLayer(0f, 0f, 0f, 0) + textPaint.textSize = capsuleRadius * 1.15f + val plus = "+" + canvas.drawText(plus, addCenter.x, addCenter.y - (textPaint.ascent() + textPaint.descent()) / 2f, textPaint) + val path = android.graphics.Path() + val check = capsuleRadius * 0.42f + path.moveTo(doneCenter.x - check, doneCenter.y) + path.lineTo(doneCenter.x - check * 0.25f, doneCenter.y + check * 0.7f) + path.lineTo(doneCenter.x + check, doneCenter.y - check * 0.7f) + ringPaint.strokeWidth = dp(3f) + ringPaint.strokeCap = Paint.Cap.ROUND + ringPaint.color = Color.WHITE + canvas.drawPath(path, ringPaint) + ringPaint.strokeCap = Paint.Cap.BUTT + } + + override fun onTouchEvent(event: MotionEvent): Boolean = if (editing) editTouch(event) else playTouch(event) + + private fun playTouch(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { + val index = event.actionIndex + val entry = entryAt(event.getX(index), event.getY(index)) + if (entry == null) { + if (event.actionMasked == MotionEvent.ACTION_DOWN) return false + forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(index)) + forwardPointers(event, forwardedPointerBits) + return true + } + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) + if (entry.shape == SCREEN_KEY_DPAD) { + val arm = armOf(entry, event.getX(index), event.getY(index)) + val code = entry.codes.getOrNull(arm) ?: 0 + if (code == 0) return true + val pid = event.getPointerId(index) + dpadDown.remove(pid)?.let { releaseKey(it) } + dpadDown[pid] = code + entry.armed = arm + pressKey(code) + invalidate() + return true + } + if (entry.shape == SCREEN_KEY_STICK) { + val sector = stickSector(entry, event.getX(index), event.getY(index)) + val pid = event.getPointerId(index) + stickCodes.remove(pid)?.forEach { if (it != 0) releaseKey(it) } + val codes = directionCodes(entry, sector) + stickEntries[pid] = entry + stickCodes[pid] = codes + entry.armed = if (codes.isEmpty()) -1 else sector + codes.forEach { pressKey(it) } + invalidate() + return true + } + if (entry.toggle) { + if (latched.remove(entry)) release(entry) else { + latched += entry + entry.codes.forEach { pressKey(it) } + } + invalidate() + return true + } + if (down.values.any { it === entry }) return true + down[event.getPointerId(index)] = entry + entry.codes.forEach { pressKey(it) } + invalidate() + return true + } + + MotionEvent.ACTION_MOVE -> { + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) + if (stickEntries.isEmpty()) return true + repeat(event.pointerCount) { index -> + val pid = event.getPointerId(index) + val entry = stickEntries[pid] ?: return@repeat + val sector = stickSector(entry, event.getX(index), event.getY(index)) + val codes = directionCodes(entry, sector) + val previous = stickCodes[pid].orEmpty() + if (codes != previous) { + previous.filterNot { it in codes }.forEach { releaseKey(it) } + codes.filterNot { it in previous }.forEach { pressKey(it) } + stickCodes[pid] = codes + entry.armed = if (codes.isEmpty()) -1 else sector + invalidate() + } + } + return true + } + + MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> { + val pid = event.getPointerId(event.actionIndex) + if (forwardedPointerBits and (1 shl pid) != 0) { + forwardPointers(event, forwardedPointerBits) + forwardedPointerBits = forwardedPointerBits and (1 shl pid).inv() + if (stickCodes.containsKey(pid) || dpadDown.containsKey(pid)) return true + down.remove(pid)?.let(::release) + return true + } + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) + if (stickCodes.containsKey(pid)) { + stickCodes.remove(pid)?.forEach { if (it != 0) releaseKey(it) } + stickEntries.remove(pid)?.armed = -1 + invalidate() + return true + } + val armedCode = dpadDown.remove(pid) + if (armedCode != null) { + releaseKey(armedCode) + entries.firstOrNull { it.armed >= 0 && it.codes.contains(armedCode) }?.armed = -1 + invalidate() + return true + } + val entry = down.remove(pid) + if (entry != null) release(entry) + return true + } + + MotionEvent.ACTION_CANCEL -> { + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) + forwardedPointerBits = 0 + stickCodes.values.flatten().forEach { if (it != 0) releaseKey(it) } + stickCodes.clear() + stickEntries.clear() + entries.forEach { it.armed = -1 } + dpadDown.values.forEach { releaseKey(it) } + dpadDown.clear() + entries.forEach { it.armed = -1 } + down.values.forEach { release(it) } + down.clear() + return true + } + } + return true + } + + private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) { + val split = event.pointerSubset(pointerIdBits) ?: return + try { + onTouchMiss?.invoke(split) + } finally { + split.recycle() + } + } + + private fun editTouch(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + val x = event.x + val y = event.y + if (inCircle(addCenter, x, y, capsuleRadius)) { + onAdd?.invoke() + return true + } + if (inCircle(doneCenter, x, y, capsuleRadius)) { + stopEditing() + return true + } + if (inToolbar(x, y)) { + toolbarDrag = true + dragX = toolbar.x - x + dragY = toolbar.y - y + return true + } + val entry = entryAt(x, y) + if (entry == null) { + pressX = x + pressY = y + postDelayed(addPress, 520) + selected = null + invalidate() + return true + } + selected = entry + dragging = true + moved = false + dragX = entry.cx - x + dragY = entry.cy - y + invalidate() + return true + } + + MotionEvent.ACTION_MOVE -> { + if (toolbarDrag) { + val maxX = width - safe.right - capsuleGap / 2f - capsuleRadius + val maxY = height - safe.bottom - capsuleRadius + toolbar.x = (event.x + dragX).coerceIn(safe.left + capsuleGap / 2f + capsuleRadius, maxOf(safe.left + capsuleGap / 2f + capsuleRadius, maxX)) + toolbar.y = (event.y + dragY).coerceIn(safe.top + capsuleRadius, maxOf(safe.top + capsuleRadius, maxY)) + addCenter.set(toolbar.x - capsuleGap / 2f, toolbar.y) + doneCenter.set(toolbar.x + capsuleGap / 2f, toolbar.y) + invalidate() + return true + } + val entry = selected + if (entry == null) { + if (hypot(event.x - pressX, event.y - pressY) > dp(10f)) removeCallbacks(addPress) + return true + } + if (!dragging) return true + if (hypot(event.x - (entry.cx - dragX), event.y - (entry.cy - dragY)) > dp(10f)) removeCallbacks(addPress) + var nextX = snap((event.x + dragX).coerceIn(entry.halfW + safe.left, width - entry.halfW - safe.right)) + var nextY = snap((event.y + dragY).coerceIn(entry.halfH + safe.top, height - entry.halfH - safe.bottom)) + guideX = -1f + guideY = -1f + entries.forEach { other -> + if (other === entry) return@forEach + if (abs(nextX - other.cx) < dp(8f)) { nextX = other.cx; guideX = other.cx } + if (abs(nextY - other.cy) < dp(8f)) { nextY = other.cy; guideY = other.cy } + } + if (abs(nextX - width / 2f) < dp(8f)) { nextX = width / 2f; guideX = nextX } + if (abs(nextY - height / 2f) < dp(8f)) { nextY = height / 2f; guideY = nextY } + if (hypot(nextX - entry.cx, nextY - entry.cy) > dp(4f)) moved = true + entry.cx = nextX + entry.cy = nextY + entry.x = entry.cx / width + entry.y = entry.cy / height + invalidate() + return true + } + + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + removeCallbacks(addPress) + guideX = -1f + guideY = -1f + if (toolbarDrag) { + toolbarDrag = false + return true + } + val entry = selected + if (entry != null && dragging) { + dragging = false + if (moved) { + save() + invalidate() + } else { + onSelect?.invoke(entry.codes) + } + } + return true + } + } + return true + } + + private fun pressKey(code: Int) { + val owners = held[code] ?: 0 + held[code] = owners + 1 + if (owners == 0) sendKey(code, true) + } + + private fun releaseKey(code: Int) { + val owners = held[code] ?: return + if (owners > 1) { + held[code] = owners - 1 + return + } + held.remove(code) + sendKey(code, false) + } + + private fun release(entry: Entry) { + entry.codes.asReversed().forEach { releaseKey(it) } + invalidate() + } + + fun export(): String = ControllerPrefs.encodeScreenKeys( + entries.map { ScreenKey(it.codes, it.x, it.y, it.size, it.glyph, it.text, it.image, it.opacity, it.shape, it.toggle, it.labels) }, + ) + + fun load(raw: String) { + releaseAll() + entries.clear() + ControllerPrefs.decodeScreenKeys(raw).forEach { entries += entryOf(it) } + entries.forEach { measure(it) } + selected = null + save() + invalidate() + } + + private fun save() { + ControllerPrefs.setScreenKeys( + context, + entries.map { ScreenKey(it.codes, it.x, it.y, it.size, it.glyph, it.text, it.image, it.opacity, it.shape, it.toggle, it.labels) }, + ) + } + + private fun dp(value: Float) = value * resources.displayMetrics.density + + companion object { + private val DPAD_DIRS = listOf( + 0f to -1f, 1f to 0f, 0f to 1f, -1f to 0f, + ) + private val STICK_DIRS = listOf( + 0f to -1f, 0.7071f to -0.7071f, 1f to 0f, 0.7071f to 0.7071f, + 0f to 1f, -0.7071f to 0.7071f, -1f to 0f, -0.7071f to -0.7071f, + ) + const val DEFAULT_SIZE = 44 + const val MIN_SIZE = 24 + const val MAX_SIZE = 140 + const val IMAGE_DIR = "screenkeys" + private const val BODY = 0xFF14181F.toInt() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/ScreenLayoutFile.kt b/app/src/main/java/com/droiddeck/launcher/input/ScreenLayoutFile.kt new file mode 100644 index 0000000000..fc25940719 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ScreenLayoutFile.kt @@ -0,0 +1,140 @@ +package com.droiddeck.launcher.input + +import org.json.JSONArray +import org.json.JSONObject +import kotlin.math.roundToInt + +private val ICP_NAMES: Map = mapOf( + 103 to "KEY_UP", 106 to "KEY_RIGHT", 108 to "KEY_DOWN", 105 to "KEY_LEFT", + 28 to "KEY_ENTER", 1 to "KEY_ESC", 14 to "KEY_BKSP", 111 to "KEY_DEL", 15 to "KEY_TAB", + 57 to "KEY_SPACE", 29 to "KEY_CTRL_L", 97 to "KEY_CTRL_R", 110 to "KEY_INSERT", + 42 to "KEY_SHIFT_L", 54 to "KEY_SHIFT_R", 56 to "KEY_ALT_L", 100 to "KEY_ALT_R", + 102 to "KEY_HOME", 107 to "KEY_END", 99 to "KEY_PRTSCN", 104 to "KEY_PG_UP", 109 to "KEY_PG_DOWN", + 58 to "KEY_CAPS_LOCK", 69 to "KEY_NUM_LOCK", 41 to "KEY_GRAVE", 12 to "KEY_MINUS", + 11 to "KEY_0", 2 to "KEY_1", 3 to "KEY_2", 4 to "KEY_3", 5 to "KEY_4", 6 to "KEY_5", + 7 to "KEY_6", 8 to "KEY_7", 9 to "KEY_8", 10 to "KEY_9", + 30 to "KEY_A", 48 to "KEY_B", 46 to "KEY_C", 32 to "KEY_D", 18 to "KEY_E", 33 to "KEY_F", + 34 to "KEY_G", 35 to "KEY_H", 23 to "KEY_I", 36 to "KEY_J", 37 to "KEY_K", 38 to "KEY_L", + 50 to "KEY_M", 49 to "KEY_N", 24 to "KEY_O", 25 to "KEY_P", 16 to "KEY_Q", 19 to "KEY_R", + 31 to "KEY_S", 20 to "KEY_T", 22 to "KEY_U", 47 to "KEY_V", 17 to "KEY_W", 45 to "KEY_X", + 21 to "KEY_Y", 44 to "KEY_Z", + 26 to "KEY_BRACKET_LEFT", 27 to "KEY_BRACKET_RIGHT", 43 to "KEY_BACKSLASH", 53 to "KEY_SLASH", + 39 to "KEY_SEMICOLON", 51 to "KEY_COMMA", 52 to "KEY_PERIOD", 40 to "KEY_APOSTROPHE", + 59 to "KEY_F1", 60 to "KEY_F2", 61 to "KEY_F3", 62 to "KEY_F4", 63 to "KEY_F5", 64 to "KEY_F6", + 65 to "KEY_F7", 66 to "KEY_F8", 67 to "KEY_F9", 68 to "KEY_F10", 87 to "KEY_F11", 88 to "KEY_F12", + 79 to "KEY_KP_1", 80 to "KEY_KP_2", 81 to "KEY_KP_3", 75 to "KEY_KP_4", 76 to "KEY_KP_5", + 77 to "KEY_KP_6", 71 to "KEY_KP_7", 72 to "KEY_KP_8", 73 to "KEY_KP_9", 82 to "KEY_KP_0", +) + +private val ICP_CODES: Map = ICP_NAMES.entries.associate { (code, name) -> name to code } + +private fun icpShape(shape: Int): String = when (shape) { + SCREEN_KEY_CIRCLE -> "CIRCLE" + SCREEN_KEY_RECT -> "RECT" + SCREEN_KEY_ROUND -> "ROUND_RECT" + SCREEN_KEY_DPAD -> "ROUND_RECT" + SCREEN_KEY_STICK -> "ROUND_RECT" + SCREEN_KEY_TRIGGER -> "ROUND_RECT" + else -> "ROUND_RECT" +} + +private fun screenKeyShape(shape: String): Int = when (shape) { + "CIRCLE" -> SCREEN_KEY_CIRCLE + "RECT" -> SCREEN_KEY_RECT + "SQUARE" -> SCREEN_KEY_ROUND + else -> SCREEN_KEY_PILL +} + +fun exportScreenLayout(keys: List, widthPx: Int, density: Float): String { + val snap = widthPx / 100f + val elements = JSONArray() + keys.forEach { key -> + val binds = JSONArray() + val directional = key.shape == SCREEN_KEY_DPAD || key.shape == SCREEN_KEY_STICK + key.codes.forEach { code -> + val name = ICP_NAMES[code] + if (name != null) binds.put(name) else if (directional) binds.put("") + } + if (binds.length() == 0) return@forEach + val shape = icpShape(key.shape) + val sizePx = key.size * density + val scale = when { + key.shape == SCREEN_KEY_DPAD -> sizePx * 2.3f / (14f * snap) + key.shape == SCREEN_KEY_STICK -> sizePx * 2.3f / (14f * snap) + shape == "CIRCLE" -> sizePx / (6f * snap) + else -> sizePx / (4f * snap) + } + elements.put( + JSONObject() + .put( + "type", + when (key.shape) { + SCREEN_KEY_DPAD -> "D_PAD" + SCREEN_KEY_STICK -> "STICK" + else -> "BUTTON" + }, + ) + .put("shape", shape) + .put("customColor", 0) + .put("bindings", binds) + .put("scale", scale) + .put("x", key.x) + .put("y", key.y) + .put("toggleSwitch", key.toggle) + .put("swipeable", false) + .put("text", key.text) + .put("iconId", 0) + .apply { if (key.opacity < 1f) put("opacity", key.opacity) }, + ) + } + return JSONObject() + .put("id", 0) + .put("name", "DroidDeck") + .put("cursorSpeed", 1.5f) + .put("elements", elements) + .toString() +} + +fun importScreenLayout(raw: String, widthPx: Int, density: Float): List? { + val root = runCatching { JSONObject(raw) }.getOrNull() ?: return null + val elements = root.optJSONArray("elements") ?: return null + val snap = widthPx / 100f + val keys = mutableListOf() + for (i in 0 until elements.length()) { + val element = elements.optJSONObject(i) ?: continue + val type = element.optString("type", "BUTTON") + if (type != "BUTTON" && type != "D_PAD" && type != "STICK") continue + val binds = element.optJSONArray("bindings") ?: continue + val raw = (0 until binds.length()).map { ICP_CODES[binds.optString(it)] ?: 0 } + val codes = if (type == "D_PAD" || type == "STICK") { + raw.dropLastWhile { it == 0 }.ifEmpty { listOf(0) } + } else { + raw.filter { it != 0 } + } + if (codes.isEmpty()) continue + val dpad = type == "D_PAD" + val stick = type == "STICK" + val shape = when { + dpad -> SCREEN_KEY_DPAD + stick -> SCREEN_KEY_STICK + else -> screenKeyShape(element.optString("shape")) + } + val scale = element.optDouble("scale", 1.0).toFloat().takeIf { it > 0f } ?: 1f + val sizePx = when { + dpad || stick -> 14f * snap * scale / 2.3f + shape == SCREEN_KEY_CIRCLE -> 6f * snap * scale + else -> 4f * snap * scale + } + keys += ScreenKey( + codes = codes, + x = element.optDouble("x", 0.5).toFloat().coerceIn(0f, 1f), + y = element.optDouble("y", 0.5).toFloat().coerceIn(0f, 1f), + size = (sizePx / density).roundToInt().coerceIn(ScreenKeys.MIN_SIZE, ScreenKeys.MAX_SIZE), + text = element.optString("text").take(24), + opacity = element.optDouble("opacity", 1.0).toFloat().coerceIn(0.2f, 1f), + shape = shape, + toggle = element.optBoolean("toggleSwitch"), + ) + } + return keys +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt index 1c6921a890..2138f9c92b 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt @@ -93,13 +93,18 @@ class SteamTouchControls( private var opened = 0 private var elements: List = emptyList() private var tint = Color.WHITE - private var alphaScale = 0.45f + private var alphaScale = 0.99f + var style: Pair = Color.WHITE to 0.99f + private set + var onStyle: (() -> Unit)? = null private class Visual(val ref: SteamTouchBindings.Ref?, val binding: SteamTouchBindings.Binding?) private var visuals: Map> = emptyMap() private class Finger(val element: Element?, var x: Float, var y: Float, val toolbar: Int = -1) private val fingers = HashMap() + private var forwardedPointerBits = 0 + var onTouchMiss: ((MotionEvent) -> Unit)? = null private var editing = false private var editElements: MutableList = mutableListOf() @@ -191,6 +196,8 @@ class SteamTouchControls( private fun applyColor(color: FloatArray?) { tint = if (color != null) Color.rgb((color[0] * 255).toInt(), (color[1] * 255).toInt(), (color[2] * 255).toInt()) else Color.WHITE alphaScale = ((color?.get(3) ?: 0.45f) * 2.2f).coerceIn(0.15f, 1f) + style = tint to alphaScale + onStyle?.invoke() } private fun rebuildVisuals() { @@ -624,7 +631,17 @@ class SteamTouchControls( MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { val x = event.getX(index) val y = event.getY(index) - val e = hit(live(), x, y) ?: return event.actionMasked == MotionEvent.ACTION_POINTER_DOWN + if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0 + val e = hit(live(), x, y) + if (e == null) { + if (event.actionMasked == MotionEvent.ACTION_DOWN) return false + if (onTouchMiss != null) { + forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(index)) + forwardPointers(event, forwardedPointerBits) + } + return true + } + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) fingers[event.getPointerId(index)] = Finger(e, x, y) if (feedback) performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY) requestUnbufferedDispatch(event) @@ -632,6 +649,7 @@ class SteamTouchControls( return true } MotionEvent.ACTION_MOVE -> { + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) for (i in 0 until event.pointerCount) { val f = fingers[event.getPointerId(i)] ?: continue f.x = event.getX(i) @@ -650,12 +668,14 @@ class SteamTouchControls( } MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> { val id = event.getPointerId(index) + if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits) + forwardedPointerBits = if (event.actionMasked == MotionEvent.ACTION_CANCEL) 0 else forwardedPointerBits and (1 shl id).inv() val f = fingers.remove(id) if (event.actionMasked == MotionEvent.ACTION_CANCEL) fingers.clear() val e = f?.element if (event.actionMasked != MotionEvent.ACTION_CANCEL && e != null && reach(e, event.getX(index), event.getY(index)) <= 1.3f) { when (e.type) { - SteamTouchConfig.THUMB -> openMenu() + SteamTouchConfig.THUMB -> { cancelForwarded(event); openMenu() } SteamTouchConfig.KEYBOARD -> onKeyboard() SteamTouchConfig.PASTE -> onPaste() } @@ -668,6 +688,25 @@ class SteamTouchControls( } + private fun cancelForwarded(event: MotionEvent) { + val split = event.pointerSubset(forwardedPointerBits).also { forwardedPointerBits = 0 } ?: return + split.action = MotionEvent.ACTION_CANCEL + try { + onTouchMiss?.invoke(split) + } finally { + split.recycle() + } + } + + private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) { + val split = event.pointerSubset(pointerIdBits) ?: return + try { + onTouchMiss?.invoke(split) + } finally { + split.recycle() + } + } + val isEditing get() = editing fun startEditing() { diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt new file mode 100644 index 0000000000..3e0ca925aa --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt @@ -0,0 +1,22 @@ +package com.droiddeck.launcher.input + +import android.media.AudioManager +import android.view.KeyEvent + +/** Use Steam's PulseAudio bridge for feedback instead of requesting Android's volume UI. */ +internal object SteamVolumeKeys { + fun dispatch(event: KeyEvent, enabled: Boolean, adjust: (Int) -> Unit): Boolean { + val direction = when (event.keyCode) { + KeyEvent.KEYCODE_VOLUME_UP -> AudioManager.ADJUST_RAISE + KeyEvent.KEYCODE_VOLUME_DOWN -> AudioManager.ADJUST_LOWER + KeyEvent.KEYCODE_VOLUME_MUTE -> AudioManager.ADJUST_TOGGLE_MUTE + else -> return false + } + if (!enabled) return false + if (event.action == KeyEvent.ACTION_DOWN && + (event.keyCode != KeyEvent.KEYCODE_VOLUME_MUTE || event.repeatCount == 0)) { + adjust(direction) + } + return event.action == KeyEvent.ACTION_DOWN || event.action == KeyEvent.ACTION_UP + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt new file mode 100644 index 0000000000..e3a64e9628 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt @@ -0,0 +1,420 @@ +package com.droiddeck.launcher.runtime + +import android.app.ActivityManager +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.session.ComponentsManager +import com.droiddeck.launcher.session.GameEnvironmentStore +import java.io.File + +object BattleNet { + private const val TAG = "BattleNet" + + const val APP_ID = 2596113170L + + const val FEX_REQUEST = "battlenet-fex.request" + const val FEX_RESULT = "battlenet-fex.result" + + const val PROGRAM = "/usr/local/bin/droiddeck-battlenet" + + class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null) + + internal val TITLES = listOf( + Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow"), + Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic"), + Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era"), + Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary"), + Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"), + Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"), + Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"), + Title("s1", "StarCraft", "S1", shop = "starcraft-remastered", product = "s1"), + Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone", product = "hsb"), + Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm", product = "hero"), + Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch", product = "pro"), + Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged", product = "w3"), + Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4", product = "viper"), + Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare", product = "odin"), + Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered", product = "lazr"), + Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war", product = "zeus"), + Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard", product = "fore"), + Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii", product = "auks"), + Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii", product = "pinta"), + Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4", product = "wlby"), + Title("osi", "Diablo II: Resurrected", "OSI", product = "osi"), + Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection", product = "rtro"), + Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal", product = "anbs"), + Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"), + Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"), + Title("d1", "Diablo", "D1", shop = "diablo", product = "drtl"), + Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans", product = "war1"), + Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition", product = "w2bn"), + Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered", product = "w1r"), + Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered", product = "w2r"), + Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble", product = "gryphon"), + Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages", product = "aris"), + Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves", product = "scor"), + Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2", product = "ark"), + Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710, product = "lbra"), + Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"), + ) + + val STORE: List get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" } + + fun notInstalled(title: Title, installedIds: Collection<String?>) = + installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code } + + private const val COVER_RETRY_MS = 24 * 3600_000L + + private fun coverDir(context: Context, title: Title) = + File(context.filesDir, "battlenet-art/${(TITLES.firstOrNull { it.code == title.code } ?: title).uid}") + + fun cover(context: Context, title: Title): File? = art(context, title).cover + + private val coverLock = Any() + + fun fetchCovers(context: Context, titles: List<Title> = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" }): Boolean = synchronized(coverLock) { + val art = com.droiddeck.launcher.frontend.AddedGameArt + val key = com.droiddeck.launcher.frontend.SteamGridDb.key(context) + var got = false + for (title in titles) { + val dir = coverDir(context, title) + val tried = File(dir, ".tried") + val wide = File(dir, BLIZZARD) + val done = File(dir, "p.jpg").isFile && (title.shop == null || wide.isFile) + if (done || System.currentTimeMillis() - tried.lastModified() < COVER_RETRY_MS) continue + dir.mkdirs() + if (title.steam != null && runCatching { art.download(title.steam.toString(), dir) }.getOrDefault(false)) got = true + if (title.shop != null && !wide.isFile) { + val cover = File(dir, BLIZZARD_COVER).takeUnless { File(dir, "p.jpg").isFile } + if (runCatching { com.droiddeck.launcher.stores.battlenet.BlizzardArt.fetch(title.shop, wide, cover) } + .onFailure { Log.w(TAG, "Blizzard art for ${title.uid}: ${it.javaClass.simpleName}") }.getOrDefault(false)) got = true + } + if (!File(dir, "p.jpg").isFile && !File(dir, BLIZZARD_COVER).isFile && key.isNotEmpty()) { + val id = runCatching { com.droiddeck.launcher.frontend.SteamGridDb.gameId(key, title.steam, title.name) }.getOrNull() + if (id != null && runCatching { com.droiddeck.launcher.frontend.SteamGridDb.download(key, id, dir) }.getOrDefault(false)) got = true + } + runCatching { tried.writeText("") ; tried.setLastModified(System.currentTimeMillis()) } + } + got + } + + private val LOCALES = setOf( + "enus", "engb", "dede", "eses", "esmx", "frfr", "itit", "kokr", "plpl", "ptbr", "ptpt", "ruru", "zhcn", "zhtw", "jajp", "thth", "trtr", "arsa", + ) + + private val NOT_GAMES = setOf("agent", "bna", "battle.net") + + class Game(val uid: String, val name: String, val code: String, val folder: File, val installUid: String = uid) { + val title: Title get() = title(uid) ?: Title(uid, name, code) + } + + class Art(val cover: File?, val header: File?) + + private const val BLIZZARD = "blizzard.jpg" + private const val BLIZZARD_COVER = "p-blizzard.jpg" + + fun art(context: Context, title: Title): Art { + val dir = coverDir(context, title) + fun first(vararg names: String) = names.map { File(dir, it) }.firstOrNull { it.isFile } + return Art(first("p.jpg", BLIZZARD_COVER), first(BLIZZARD, "header.jpg")) + } + + fun prefix(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/compatdata/$APP_ID") + + fun client(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe") + + fun installed(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe").isFile + + fun profile(context: Context): Pair<String, String>? = + (APP_ID.toString() to context.getString(com.droiddeck.launcher.R.string.bnet_name)).takeIf { installed(context) } + + fun icon(context: Context): File? { + val out = File(context.filesDir, "battlenet-art/launcher/icon.png") + if (out.isFile) return out + val exe = client(context).takeIf { it.isFile } ?: return null + val bitmap = runCatching { com.droiddeck.launcher.files.PeIconExtractor.extract(exe) }.getOrNull() ?: return null + return runCatching { + out.parentFile?.mkdirs() + val tmp = File(out.path + ".tmp") + tmp.outputStream().use { check(bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it)) } + check(tmp.renameTo(out)) + out + }.getOrNull() + } + + fun launcherEntry(installed: Boolean, art: File? = null): com.droiddeck.launcher.frontend.Library.SteamGame? = + if (!installed) null + else com.droiddeck.launcher.frontend.Library.SteamGame( + appId = APP_ID.toInt(), name = com.droiddeck.launcher.stores.Store.BATTLENET.label, art = art, + library = com.droiddeck.launcher.frontend.Library.BATTLENET_LAUNCHER, gameId = APP_ID, + source = com.droiddeck.launcher.stores.Store.BATTLENET.id, + ) + + fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"] + + internal fun title(uid: String): Title? { + val id = uid.lowercase() + TITLES.firstOrNull { it.uid == id }?.let { return it } + val base = id.substringBeforeLast('_', "") + return if (base.isNotEmpty() && id.substringAfterLast('_') in LOCALES) TITLES.firstOrNull { it.uid == base } else null + } + + fun games(context: Context): List<Game> { + val pfx = File(prefix(context), "pfx") + val entries = installs( + runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()), + runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull(), + ) + val found = LinkedHashMap<String, Game>() + for ((uid, path) in entries) { + val title = title(uid) + if (title == null) { + if (uid.lowercase() !in NOT_GAMES) Log.i(TAG, "not listed: $uid (no launch code known)") + continue + } + if (title.code in found) continue + val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue + found[title.code] = Game(title.uid, title.name, title.code, folder, uid) + } + return found.values.toList() + } + + internal fun installs(registry: List<Pair<String, String>>, agent: List<Pair<String, String>>?): List<Pair<String, String>> { + if (agent == null) return registry + val tracked = agent.map { it.first.lowercase() }.toSet() + return registry.filter { it.first.lowercase() in tracked } + agent + } + + internal fun hostFolder(context: Context, path: String): File? { + val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null + val relative = drive.groupValues[2].replace('\\', '/').trim('/') + if (relative.isEmpty() || relative.split('/').any { it == ".." }) return null + return if (drive.groupValues[1].equals("c", ignoreCase = true)) File(prefix(context), "pfx/drive_c/$relative") + else com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "/$relative") + } + + private val KEY = Regex("""^\[(.+)\](?:\s+\d+)?\s*$""") + private val UNINSTALL = Regex("""(?i)\\CurrentVersion\\Uninstall\\[^\\]+$""") + private val VALUE = Regex("""^"((?:[^"\\]|\\.)*)"=(?:str\(\d+\):)?"((?:[^"\\]|\\.)*)"\s*$""") + private val UID = Regex("""--uid=([A-Za-z0-9_.-]+)""") + + internal fun uninstallEntries(lines: Sequence<String>): List<Pair<String, String>> { + val out = ArrayList<Pair<String, String>>() + var inside = false + var uid: String? = null + var location: String? = null + fun flush() { + val u = uid + val l = location + if (u != null && l != null) out.add(u to l) + uid = null + location = null + } + for (line in lines) { + if (line.startsWith("[")) { + flush() + inside = KEY.matchEntire(line)?.groupValues?.get(1)?.let { UNINSTALL.containsMatchIn(unescape(it)) } == true + continue + } + if (!inside) continue + val value = VALUE.matchEntire(line) ?: continue + val text = unescape(value.groupValues[2]) + when (unescape(value.groupValues[1]).lowercase()) { + "uninstallstring" -> if (text.contains("battle.net", ignoreCase = true)) uid = UID.find(text)?.groupValues?.get(1) + "installlocation" -> location = text + } + } + flush() + return out + } + + private fun unescape(s: String): String { + val out = StringBuilder(s.length) + var i = 0 + while (i < s.length) { + val c = s[i++] + if (c != '\\' || i >= s.length) { out.append(c); continue } + when (val e = s[i++]) { + 'n' -> out.append('\n') + 'r' -> out.append('\r') + 't' -> out.append('\t') + '0' -> out.append('\u0000') + 'x' -> { + var end = i + while (end < s.length && end - i < 4 && s[end].lowercaseChar() in "0123456789abcdef") end++ + if (end > i) { out.append(s.substring(i, end).toInt(16).toChar()); i = end } else out.append('x') + } + else -> out.append(e) + } + } + return out.toString() + } + + internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? { + val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null + return installs.map { (_, start, end) -> + runCatching { + val install = fields(bytes, start, end) + val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) } + val path = install.firstOrNull { it.first == 3 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } } + ?.let { String(bytes, it.second, it.third - it.second) } + val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } } + ?.let { s -> varints(bytes, s.second, s.third)[1] } + if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path + }.getOrElse { return null } + }.filterNotNull() + } + + private fun fields(bytes: ByteArray, from: Int, to: Int): List<Triple<Int, Int, Int>> = walk(bytes, from, to) { _, _ -> } + + private fun varints(bytes: ByteArray, from: Int, to: Int): Map<Int, Long> = + HashMap<Int, Long>().also { found -> walk(bytes, from, to) { field, value -> found.putIfAbsent(field, value) } } + + private fun walk(bytes: ByteArray, from: Int, to: Int, varint: (Int, Long) -> Unit): List<Triple<Int, Int, Int>> { + val out = ArrayList<Triple<Int, Int, Int>>() + var i = from + fun next(): Long { + var value = 0L + var shift = 0 + while (true) { + require(i < to && shift < 64) { "truncated" } + val b = bytes[i++].toInt() and 0xff + value = value or ((b and 0x7f).toLong() shl shift) + if (b < 0x80) return value + shift += 7 + } + } + while (i < to) { + val key = next() + when ((key and 7).toInt()) { + 0 -> varint((key ushr 3).toInt(), next()) + 1 -> { require(to - i >= 8) { "truncated" }; i += 8 } + 2 -> { + val n = next() + require(n in 0..(to - i).toLong()) { "truncated" } + out.add(Triple((key ushr 3).toInt(), i, i + n.toInt())) + i += n.toInt() + } + 5 -> { require(to - i >= 4) { "truncated" }; i += 4 } + else -> error("wire type ${key and 7}") + } + } + return out + } + + fun shortcut(context: Context, game: Game): com.droiddeck.launcher.frontend.AddedGames.Game? { + val added = com.droiddeck.launcher.frontend.AddedGames + val client = client(context) + val guestExe = added.guestPath(context, client) ?: return null + val guestDir = added.guestPath(context, client.parentFile ?: return null) ?: return null + val guestPrefix = added.guestPath(context, prefix(context)) ?: return null + val crc = java.util.zip.CRC32().apply { update("\"$guestExe\"${game.name}".toByteArray()) }.value + val appId = com.droiddeck.launcher.session.SessionPrefs.addedGameAppId(context, game.folder.path, crc or 0x80000000L) + val exe = added.candidates(game.folder).firstOrNull() ?: client + return com.droiddeck.launcher.frontend.AddedGames.Game( + game.folder, game.name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, listOf(exe), + source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = game.uid, + launchOptions = "STEAM_COMPAT_DATA_PATH=$guestPrefix %command% --exec=\"launch ${game.code}\"", + ) + } + + fun remove(context: Context) { + val root = LinuxRuntime.rootDir(context) + com.droiddeck.launcher.core.FileUtils.delete(prefix(context)) + File(root, "usr/local/share/applications/droiddeck-battlenet.desktop").delete() + com.droiddeck.launcher.core.FileUtils.delete(File(root, "root/.cache/droiddeck/battlenet")) + ComponentsManager.clearGameComponents(context, APP_ID.toString()) + Log.i(TAG, "removed") + } + + private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""") + + private const val LISTING_MAX_AGE = 6 * 3600L + + private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b -> + for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i]) + if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second) + } + + internal fun d2rfix(file: String): Pair<List<Long>, Long>? { + val m = D2RFIX.matchEntire(file) ?: return null + val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null } + return version to (m.groupValues[2].toLongOrNull() ?: return null) + } + + internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? = + items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } } + .maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first + + fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items } + + @Synchronized + internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String { + val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing") + val file = ComponentsManager.safeName(item.file) + if (ComponentsManager.packages(context).none { it.file == file }) { + Log.i(TAG, "downloading ${item.file}") + ComponentsManager.download(context, item) {} + } + val scope = APP_ID.toString() + if (ComponentsManager.gameComponents(context, scope)["fex"] != file) { + ComponentsManager.setGameComponent(context, scope, "fex", file) + Log.i(TAG, "FEX for the Battle.net prefix: $file") + } else if (ComponentsManager.republish(context)) { + Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton") + } + return file + } + + private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> { + val cached = ComponentsManager.catalog(context, false) + val age = System.currentTimeMillis() / 1000 - cached.fetchedAt + if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items + val fetched = runCatching { refresh(context) } + .onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty() + return if (newestD2rFix(fetched) != null) fetched else cached.items + } + + internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt() + + internal fun videoMemoryOptions(megabytes: Int): String = + "dxgi.maxDeviceMemory = $megabytes; dxgi.maxSharedMemory = $megabytes; d3d9.maxAvailableMemory = $megabytes" + + fun ensureVideoMemory(context: Context): Boolean { + val memory = ActivityManager.MemoryInfo() + context.getSystemService(ActivityManager::class.java)?.getMemoryInfo(memory) ?: return false + if (memory.totalMem <= 0) return false + val options = videoMemoryOptions(videoMemory(memory.totalMem / (1024 * 1024))) + val set = GameEnvironmentStore.setDefault(context, APP_ID.toString(), DXVK_CONFIG, options) + if (set) Log.i(TAG, "DXVK_CONFIG for the Battle.net profile: $options") + return set + } + + private const val DXVK_CONFIG = "DXVK_CONFIG" + + fun ensureNoSteam(context: Context): Boolean { + if (com.droiddeck.launcher.session.SessionPrefs.battleNetNoSteamSet(context)) return false + GameEnvironmentStore.setGameNoSteam(context, APP_ID.toString(), true) + com.droiddeck.launcher.session.SessionPrefs.setBattleNetNoSteamSet(context) + Log.i(TAG, "Start without Steam for the Battle.net profile") + return true + } + + fun answerFexRequest(context: Context, dir: File) { + val app = context.applicationContext + Thread({ + runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) } + runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) } + val answer = try { + "ok " + ensureFex(app) + } catch (e: Exception) { + Log.w(TAG, "FEX for the Battle.net prefix", e) + "error " + (e.message ?: e.javaClass.simpleName) + } + Log.i(TAG, "FEX request: $answer") + val result = File(dir, FEX_RESULT) + val partial = File(dir, "$FEX_RESULT.tmp") + runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) } + }, "battlenet-fex").start() + } +} 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 4825646786..81fabd7f7d 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt @@ -220,6 +220,7 @@ object BwrapSpawner { val binds = ArrayList<Bind>() val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } } env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":") + File(rootfs, NET_LINK).takeIf { it.isFile }?.let { binds.add(Bind(it.path, "/$NET_LINK")) } env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev -> binds.addAll(bindsFor(session, rootfs, dev, dev)) } @@ -227,6 +228,7 @@ object BwrapSpawner { } private const val PRELOAD_DIR = "/run/droiddeck-preload" + private const val NET_LINK = "etc/droiddeck-net" private const val ZYPAK_SHIM = "#!/bin/sh\nprogram=\$1\nshift\nexec \"\$program\" --no-sandbox \"\$@\"\n" diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt index b7977a909d..f2e4a357c4 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt @@ -71,9 +71,22 @@ object DesktopCatalog { } fun resumeInterrupted(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) { + resumeInterrupted(context, null, listener) + } + + fun resumeInterrupted( + context: Context, + cancelled: Downloader.Cancellation?, + listener: LinuxRuntimeInstaller.ProgressListener?, + ): String? = synchronized(installLock) { for (entry in interrupted(context)) { Log.w(TAG, "finishing the interrupted install of ${entry.id} ${entry.version}") - install(context, entry, listener)?.let { return it } + val problem = if (cancelled == null) { + install(context, entry, listener) + } else { + install(context, entry, cancelled, listener) + } + if (problem != null) return problem } null } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt new file mode 100644 index 0000000000..f5780da94f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt @@ -0,0 +1,188 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.content.Intent +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.database.ContentObserver +import android.media.AudioManager +import android.os.FileObserver +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import android.util.Log +import com.droiddeck.launcher.core.SessionPart +import com.droiddeck.launcher.R +import java.io.File +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import org.json.JSONObject +import kotlin.math.roundToInt + +class DeviceControlsComponent(context: Context, root: File, private val activityVisible: () -> Boolean = { false }) : SessionPart() { + private val context = context.applicationContext + private val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager + private val directory = directory(root) + private val handler = Handler(Looper.getMainLooper()) + private var running = false + private var permissionNotified = false + private var previous = "" + private var revision = 0L + init { prepareBacklight(context, root) } + private val observer = object : ContentObserver(handler) { + override fun onChange(selfChange: Boolean) { if (running) publish() } + } + private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) { + override fun onEvent(event: Int, path: String?) { + if (path in REQUESTS) handler.post { if (running) consume() } + } + } + private val refresh = object : Runnable { + override fun run() { + if (!running) return + consume() + if (permissionNotified && Settings.System.canWrite(context)) + context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION) + publish() + handler.postDelayed(this, 250) + } + } + + fun publish(force: Boolean = false) { + try { + directory.mkdirs() + val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC) + val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1) + val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC) + write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n") + val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) + write("backlight/droiddeck/brightness", "$value\n") + write("backlight/droiddeck/actual_brightness", "$value\n") + val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0) + .put("brightnessWritable", Settings.System.canWrite(context)).toString() + if (force || state != previous) { + write("state.json", JSONObject(state).put("revision", ++revision).toString()) + previous = state + } + } catch (e: Exception) { + Log.w(TAG, "Could not publish Android controls", e) + } + } + + override fun start() { + handler.post { + REQUESTS.forEach { + File(directory, it).delete() + File(directory, "$it.processing").delete() + } + running = true + permissionNotified = false + context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer) + requests.startWatching() + refresh.run() + } + } + + override fun stop() { + handler.post { + running = false + handler.removeCallbacks(refresh) + requests.stopWatching() + context.contentResolver.unregisterContentObserver(observer) + context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION) + } + } + + private fun consume() { + for (name in REQUESTS) { + val file = File(directory, name) + if (!file.isFile) continue + val claimed = File(directory, "$name.processing") + try { + Files.move(file.toPath(), claimed.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + if (claimed.length() > 64) continue + val text = claimed.readText().trim() + when (name) { + "brightness.request" -> text.toFloatOrNull()?.takeIf { it.isFinite() && it in 0f..1f }?.let(::brightness) + "volume.request" -> text.toIntOrNull()?.let { + audio.setStreamVolume(AudioManager.STREAM_MUSIC, + it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0) + } + "mute.request" -> if (text == "0" || text == "1") { + audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, + if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0) + } + } + } catch (e: Exception) { + Log.w(TAG, "Could not apply $name", e) + } finally { + publish(force = true) + claimed.delete() + } + } + } + + private fun brightness(value: Float) { + if (!Settings.System.canWrite(context)) { + if (!permissionNotified) { + permissionNotified = true + try { + val intent = Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java) + .setAction(com.droiddeck.launcher.core.SteamIntegration.ACTION_SETUP) + .putExtra(com.droiddeck.launcher.core.SteamIntegration.EXTRA_FEATURE, "BRIGHTNESS") + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) + val manager = context.getSystemService(NotificationManager::class.java) + manager.createNotificationChannel(NotificationChannel(PERMISSION_CHANNEL, + context.getString(R.string.brightness_permission_title), NotificationManager.IMPORTANCE_DEFAULT)) + val action = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) + manager.notify(PERMISSION_NOTIFICATION, Notification.Builder(context, PERMISSION_CHANNEL) + .setSmallIcon(R.drawable.ic_stat_session) + .setContentTitle(context.getString(R.string.brightness_permission_title)) + .setContentText(context.getString(R.string.brightness_permission_text)) + .setContentIntent(action).setOnlyAlertOnce(true).setAutoCancel(true).build()) + if (activityVisible()) android.widget.Toast.makeText(context, R.string.integration_brightness_needed, + android.widget.Toast.LENGTH_LONG).show() + } catch (e: Exception) { + Log.w(TAG, "Could not open brightness permission", e) + } + } + return + } + val level = 1 + (value * 254).roundToInt() + try { + Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, + Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL) + Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, level) + } catch (e: SecurityException) { + Log.w(TAG, "Brightness permission was revoked", e) + } + } + + private fun write(name: String, text: String) { + val file = File(directory, name) + if (file.isFile && file.readText() == text) return + val staged = File(directory, "$name.tmp") + staged.writeText(text) + Files.move(staged.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } + + companion object { + private const val TAG = "DeviceControls" + private const val PERMISSION_CHANNEL = "brightness_permission" + private const val PERMISSION_NOTIFICATION = 0x4442 + private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request") + @JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls") + @JvmStatic fun prepareBacklight(context: Context, root: File): File { + val base = File(directory(root), "backlight") + val panel = File(base, "droiddeck").apply { mkdirs() } + val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) + for ((name, text) in mapOf("type" to "raw", "max_brightness" to "255", "brightness" to "$value", + "actual_brightness" to "$value", "bl_power" to "0", "scale" to "linear")) { + File(panel, name).writeText("$text\n") + } + return base + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt index 8b4f14e5ad..5a72e9f228 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt @@ -2,16 +2,19 @@ package com.droiddeck.launcher.runtime import android.content.Context import android.os.Environment +import com.droiddeck.launcher.core.DownloadSource import com.droiddeck.launcher.core.HostProcess import com.droiddeck.launcher.session.OrphanReaper import com.droiddeck.launcher.session.SessionFiles import com.droiddeck.launcher.session.SessionPaths import com.droiddeck.launcher.session.SessionPrefs import java.io.File +import java.util.concurrent.atomic.AtomicBoolean object GuestCommand { fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null, - linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, onLine: (String) -> Unit): Int { + linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null, + onLine: (String) -> Unit): Int { val log = logName?.let { try { File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter() @@ -19,14 +22,14 @@ object GuestCommand { } log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}") try { - return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath) { line -> log?.println(line); log?.flush(); onLine(line) } + return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) } } finally { log?.close() } } private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?, - fastPath: Boolean, onLine: (String) -> Unit): Int { + fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int { val root = LinuxRuntime.rootDir(context) LinuxRuntime.writeAccounts(context) SessionFiles.stage(context, root) @@ -45,6 +48,15 @@ object GuestCommand { "DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}", "XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share", ) + // The Steam client installer and the package tools inside the guest fetch over plain curl, + // so the app proxy has to reach them through the environment proot starts them with. + DownloadSource.proxyHostPort(context).takeIf { it.isNotEmpty() }?.let { hostPort -> + cmd += listOf( + "http_proxy=http://$hostPort", "https_proxy=http://$hostPort", + "HTTP_PROXY=http://$hostPort", "HTTPS_PROXY=http://$hostPort", + "no_proxy=localhost,127.0.0.1,::1", "NO_PROXY=localhost,127.0.0.1,::1", + ) + } fastPathKey?.let { cmd += ProotFastPath.guestEnv(root, binds, it) } cmd += argv val builder = ProcessBuilder(cmd).directory(root).redirectErrorStream(true) @@ -56,13 +68,32 @@ object GuestCommand { fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } } LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) } } + if (cancelled?.get() == true) return 130 val process = builder.start() val pid = HostProcess.pidOf(process) OrphanReaper.keep(pid) + val watcher = cancelled?.let { flag -> + Thread({ + try { + while (process.isAlive && !flag.get()) Thread.sleep(200) + if (flag.get()) { + // PRoot ignores SIGTERM; SIGQUIT makes it kill its tracees and exit cleanly. + if (pid > 0) { + runCatching { android.system.Os.kill(pid, android.system.OsConstants.SIGQUIT) } + } else { + process.destroy() + } + if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) process.destroyForcibly() + } + } catch (_: InterruptedException) { + } + }, "guest-cancel").apply { isDaemon = true; start() } + } try { process.inputStream.bufferedReader().useLines { lines -> lines.forEach(onLine) } return process.waitFor() } finally { + watcher?.interrupt() OrphanReaper.release(pid) } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java index 6d17f2d75a..d02fdf0c2f 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java @@ -63,15 +63,48 @@ public final class LinuxRuntime { } private static final String HOST_DIR = "opt/android-host"; + /** The downloaded add-on pack. The APK does not ship this binary. */ + public static final String PROOT_PACK = "add-on pack"; + /** Termux's unpatched proot inside the rootfs. Developer switch only. */ + public static final String PROOT_ROOTFS = "rootfs fallback"; + public static final String PROOT_MISSING = "missing"; + + private static File rootfsProot(Context context) { + return new File(rootDir(context), HOST_DIR + "/proot"); + } + + private static File rootfsLoader(Context context) { + return new File(rootDir(context), HOST_DIR + "/loader"); + } + + private static boolean rootfsProotReady(Context context) { + return rootfsProot(context).isFile() && rootfsLoader(context).isFile(); + } + + /** Patched proot is the add-on pack. The rootfs copy is not that binary. */ + public static boolean patchedProot(Context context) { + return AddonPack.PROOT.installed(context); + } public static File prootBinary(Context context) { if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot.so"); - return new File(rootDir(context), HOST_DIR + "/proot"); + if (SessionPrefs.allowStockProot(context)) return rootfsProot(context); + return AddonPack.PROOT.file(context, "libproot.so"); } public static File prootLoader(Context context) { if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot-loader.so"); - return new File(rootDir(context), HOST_DIR + "/loader"); + if (SessionPrefs.allowStockProot(context)) return rootfsLoader(context); + return AddonPack.PROOT.file(context, "libproot-loader.so"); + } + + /** Where {@link #prootBinary} came from: {@link #PROOT_PACK}, {@link #PROOT_ROOTFS} or {@link #PROOT_MISSING}. */ + public static String prootSource(Context context) { + File bin = prootBinary(context); + if (!bin.isFile()) return PROOT_MISSING; + if (AddonPack.PROOT.installed(context) + && bin.getPath().equals(AddonPack.PROOT.file(context, "libproot.so").getPath())) return PROOT_PACK; + return PROOT_ROOTFS; } public static String prootLibraryPath(Context context) { @@ -85,8 +118,7 @@ public final class LinuxRuntime { return new File(root, "usr/bin/gamescope").isFile() && (new File(root, SESSION_SCRIPT.substring(1)).isFile() || new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile()) - && prootBinary(context).isFile() - && prootLoader(context).isFile(); + && (patchedProot(context) || rootfsProotReady(context)); } public static File vulkanIcd(Context context) { @@ -160,6 +192,7 @@ public final class LinuxRuntime { bind(cmd, "/dev"); bind(cmd, "/proc"); bind(cmd, "/sys"); + bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight"); bind(cmd, "/dev/urandom:/dev/random"); bind(cmd, "/proc/self/fd:/dev/fd"); bind(cmd, "/proc/self/fd/0:/dev/stdin"); diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java index d6f6b00762..5975f6501a 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java @@ -6,6 +6,7 @@ import android.util.Log; import com.droiddeck.launcher.R; +import com.droiddeck.launcher.session.SessionPrefs; import com.droiddeck.launcher.core.ArchivePaths; import com.droiddeck.launcher.core.Downloader; import com.droiddeck.launcher.core.Hashes; @@ -262,7 +263,9 @@ public final class LinuxRuntimeInstaller { emptyTrash(LinuxRuntime.rootDir(context).getParentFile()); String downloading = context.getString(R.string.rtinst_downloading); if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0); - if (!AddonPack.PROOT.await(context)) throw new IOException("Cannot download proot"); + if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context) + && !SessionPrefs.allowStockProot(context)) + throw new IOException("Cannot download proot"); if (!AddonPack.DIRECTAUDIO.await(context)) throw new IOException("Cannot download DirectAudio"); boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> { if (listener != null) { @@ -299,27 +302,50 @@ public final class LinuxRuntimeInstaller { discard(staging, null); return false; } + java.util.List<String> carryPaths = root.isDirectory() + ? RuntimeFileTree.existingUserPaths(root, staging) : java.util.Collections.emptyList(); if (root.isDirectory() && !root.renameTo(old)) { RuntimeFileTree.delete(staging, null); return false; } + File carryMarker = new File(staging, CARRY_MARKER); + java.util.List<String> encodedPaths = new java.util.ArrayList<>(); + for (String rel : carryPaths) encodedPaths.add(java.net.URLEncoder.encode(rel, "UTF-8")); + if (!FileUtils.writeString(carryMarker, String.join("\n", encodedPaths))) { + if (old.isDirectory() && !old.renameTo(root)) + Log.w(TAG, "could not restore the previous runtime; retained at " + old); + discard(staging, null); + return false; + } + java.util.List<String> carried; try { - RuntimeFileTree.carryHome(old, staging); + carried = RuntimeFileTree.carryUserData(old, staging, false, carryPaths); } catch (IOException e) { - Log.w(TAG, "could not carry root across the update; rolling back", e); - old.renameTo(root); - try { RuntimeFileTree.delete(staging, null); } - catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); } + Log.w(TAG, "could not carry user data across the update; rolling back", e); + if (old.isDirectory() && !old.renameTo(root)) + Log.w(TAG, "could not restore the previous runtime; retained at " + old); + if (e.getSuppressed().length == 0) { + new File(staging, CARRY_MARKER).delete(); + try { RuntimeFileTree.delete(staging, null); } + catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); } + } else { + Log.w(TAG, "incomplete rollback; retaining user data in " + staging); + } return false; } if (!staging.renameTo(root)) { - File keptTo = new File(staging, USER_DATA); - if (keptTo.isDirectory() && old.isDirectory()) keptTo.renameTo(new File(old, USER_DATA)); - if (old.isDirectory()) old.renameTo(root); + if (old.isDirectory()) { + try { + RuntimeFileTree.carryBack(staging, old, carried); + new File(staging, CARRY_MARKER).delete(); + } catch (IOException e) { Log.w(TAG, "could not move all user data back after a failed swap", e); } + old.renameTo(root); + } return false; } + new File(root, CARRY_MARKER).delete(); discard(old, null); return LinuxRuntime.isInstalled(context); } catch (Exception e) { @@ -330,17 +356,41 @@ public final class LinuxRuntimeInstaller { } } + static final String CARRY_MARKER = ".droiddeck-carry"; + static void recoverInterruptedSwap(File root, File staging, File old) throws IOException { + if (!root.isDirectory() && old.isDirectory()) { + if (!old.renameTo(root)) throw new IOException("Cannot restore the previous runtime at " + old); + Log.w(TAG, "restored the previous runtime after an interrupted update"); + } + File marker = new File(staging, CARRY_MARKER); + if (!RuntimeFileTree.exists(marker.toPath())) return; File target = root.isDirectory() ? root : old; + String markerContent = FileUtils.readString(marker); + if (markerContent == null) throw new IOException("Cannot read runtime recovery marker: " + marker); + if (!markerContent.equals("1")) { + java.util.List<String> intended = new java.util.ArrayList<>(); + for (String rel : markerContent.split("\\n")) + if (!rel.isEmpty()) intended.add(java.net.URLDecoder.decode(rel, "UTF-8")); + if (target.isDirectory()) RuntimeFileTree.recoverCarriedPaths(staging, target, intended); + if (staging.isDirectory() && RuntimeFileTree.hasPaths(staging, intended)) + throw new IOException("User data still needs recovery from " + staging); + marker.delete(); + return; + } File stagedHome = new File(staging, USER_DATA); File home = new File(target, USER_DATA); - if (target.isDirectory() && stagedHome.isDirectory() && (!home.exists() || isEmptyDir(home))) { + if (target.isDirectory() && stagedHome.isDirectory() && (!RuntimeFileTree.exists(home.toPath()) || isEmptyDir(home))) { RuntimeFileTree.carryHome(staging, target); Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update"); } - if (!root.isDirectory() && old.isDirectory() && old.renameTo(root)) { - Log.w(TAG, "restored the previous runtime after an interrupted update"); + if (target.isDirectory() && staging.isDirectory()) { + java.util.List<String> rest = RuntimeFileTree.carryUserData(staging, target, true); + if (!rest.isEmpty()) Log.w(TAG, "recovered " + rest + " from an interrupted update"); } + if (staging.isDirectory() && RuntimeFileTree.hasUserData(staging, target)) + throw new IOException("User data still needs recovery from " + staging); + new File(staging, CARRY_MARKER).delete(); } static final String TRASH = ".runtime-trash"; @@ -364,9 +414,10 @@ public final class LinuxRuntimeInstaller { Log.i(TAG, "some runtime leftovers still cannot be deleted: " + trash); } - private static boolean isEmptyDir(File dir) { - String[] names = dir.list(); - return dir.isDirectory() && names != null && names.length == 0; + private static boolean isEmptyDir(File dir) throws IOException { + try (java.nio.file.DirectoryStream<java.nio.file.Path> entries = java.nio.file.Files.newDirectoryStream(dir.toPath())) { + return !entries.iterator().hasNext(); + } } public static Removal beginUninstall(Context context) { diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt b/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt index 94508e3729..485d7178a0 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt @@ -1,18 +1,32 @@ package com.droiddeck.launcher.runtime import android.content.Context -import com.droiddeck.launcher.core.AddonPack +import android.util.Log import com.droiddeck.launcher.session.SessionPrefs import java.io.File import java.security.MessageDigest object ProotFastPath { + private const val TAG = "ProotFastPath" const val LIBRARY = "/usr/local/lib/libblfastpath.so" const val MAX_BINDS = 256 - fun enabled(context: Context): Boolean = - SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context) && - LinuxRuntime.prootBinary(context).parentFile == AddonPack.PROOT.dir(context) + /** + * The fast path's trampoline is let through only by the proot built with patches/0014. + * The rootfs copy (Termux's stock proot) is not that binary, so the library stays out. + */ + fun allows(preference: Boolean, noSeccomp: Boolean, source: String): Boolean = + preference && !noSeccomp && source == LinuxRuntime.PROOT_PACK + + fun enabled(context: Context): Boolean { + val preference = SessionPrefs.prootFastPath(context) + val noSeccomp = SessionPrefs.prootNoSeccomp(context) + val source = LinuxRuntime.prootSource(context) + val on = allows(preference, noSeccomp, source) + if (preference && !noSeccomp && !on) + Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot") + return on + } fun key(root: File, binds: List<String>): String? { if (binds.size > MAX_BINDS || binds.any { it.contains('|') } || root.path.contains('|')) return null diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeFileTree.java b/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeFileTree.java index 5fb94de051..42e7f5b110 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeFileTree.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeFileTree.java @@ -74,6 +74,163 @@ public final class RuntimeFileTree { throw new IOException("Cannot make directory removable: " + dir); } + /** + * Paths in a runtime tree that belong to the user: the home folder, imported AppImages and script apps, and catalog + * AppImages with their menu entries and markers. Tar-kind catalog packages (the desktop) unpack over /usr and cannot + * be carried. + */ + static java.util.List<String> userPaths(File tree) throws IOException { + java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps")); + for (String n : children(new File(tree, "usr/local/share/applications"))) { + if (n.endsWith(".desktop") && (n.startsWith("droiddeck-app-") || n.startsWith("droiddeck-appimage-"))) + paths.add("usr/local/share/applications/" + n); + } + for (String n : children(new File(tree, "opt/appimages"))) { + if (!n.endsWith(".AppImage")) continue; + String id = n.substring(0, n.length() - ".AppImage".length()); + java.util.Collections.addAll(paths, "opt/appimages/" + n, + "usr/share/applications/droiddeck-" + id + ".desktop", ".droiddeck-pkg-" + id); + } + for (String n : children(new File(tree, "usr/share/applications"))) { + if (!n.startsWith("droiddeck-") || !n.endsWith(".desktop")) continue; + String id = n.substring("droiddeck-".length(), n.length() - ".desktop".length()); + if (!exists(new File(tree, "opt/appimages/" + id + ".AppImage").toPath())) + paths.add("usr/share/applications/" + n); + } + for (String n : children(tree)) { + if (!n.startsWith(".droiddeck-pkg-")) continue; + String id = n.substring(".droiddeck-pkg-".length()); + boolean hasMenu = exists(new File(tree, "usr/share/applications/droiddeck-" + id + ".desktop").toPath()); + if (hasMenu && !exists(new File(tree, "opt/appimages/" + id + ".AppImage").toPath())) + paths.add(n); + } + return paths; + } + + static java.util.List<String> existingUserPaths(File from, File to) throws IOException { + java.util.List<String> paths = new java.util.ArrayList<>(); + for (String rel : userPaths(from, to)) if (exists(safePath(from, rel).toPath())) paths.add(rel); + return paths; + } + + private static java.util.List<String> children(File dir) throws IOException { + java.util.List<String> names = new java.util.ArrayList<>(); + try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir.toPath())) { + for (Path entry : entries) names.add(entry.getFileName().toString()); + } catch (NoSuchFileException e) { + return names; + } + return names; + } + + static boolean exists(Path path) throws IOException { + try { Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); return true; } + catch (NoSuchFileException e) { return false; } + } + + private static java.util.Set<String> userPaths(File from, File to) throws IOException { + java.util.Set<String> paths = new java.util.LinkedHashSet<>(userPaths(from)); + paths.addAll(userPaths(to)); + return paths; + } + + static boolean hasUserData(File from, File to) throws IOException { + for (String rel : userPaths(from, to)) if (exists(new File(from, rel).toPath())) return true; + return false; + } + + /** + * Moves each user path that exists in {@code from} into {@code to}, replacing what {@code to} ships there. With + * {@code onlyMissing}, a path already present in {@code to} is left alone. On failure the paths already moved go back + * before the exception is thrown. Rollback failures are suppressed on that exception; callers must retain the source + * of any incomplete rollback. + * Returns the moved paths. + */ + static java.util.List<String> carryUserData(File from, File to, boolean onlyMissing) throws IOException { + return carryUserData(from, to, onlyMissing, new java.util.ArrayList<>(userPaths(from, to))); + } + + static java.util.List<String> carryUserData(File from, File to, boolean onlyMissing, java.util.List<String> paths) throws IOException { + java.util.List<String> moved = new java.util.ArrayList<>(); + try { + for (String rel : paths) { + File src = safePath(from, rel); + if (!exists(src.toPath())) continue; + File dst = safePath(to, rel); + if (onlyMissing && exists(dst.toPath())) continue; + move(from, to, rel); + moved.add(rel); + } + } catch (IOException e) { + for (int i = moved.size() - 1; i >= 0; i--) { + try { move(to, from, moved.get(i)); } + catch (IOException back) { e.addSuppressed(back); } + } + throw e; + } + return moved; + } + + /** Puts the given paths back from {@code from} into {@code to}; failures are collected, not stopped on. */ + static void carryBack(File from, File to, java.util.List<String> paths) throws IOException { + IOException failed = null; + for (int i = paths.size() - 1; i >= 0; i--) { + try { move(from, to, paths.get(i)); } + catch (IOException e) { if (failed == null) failed = e; else failed.addSuppressed(e); } + } + if (failed != null) throw failed; + } + + private static void move(File from, File to, String rel) throws IOException { + File src = safePath(from, rel); + File dst = safePath(to, rel); + File parent = src.getParentFile(); + if (parent != null) makeWritable(parent); + java.util.List<File> made = new java.util.ArrayList<>(); + for (File d = dst.getParentFile(); d != null; d = d.getParentFile()) { + made.add(d); + if (d.equals(to)) break; + } + for (int i = made.size() - 1; i >= 0; i--) { + File d = made.get(i); + if (!d.isDirectory() && !d.mkdirs()) throw new IOException("Cannot create " + d); + makeWritable(d); + } + delete(dst, null); + if (!src.renameTo(dst)) throw new IOException("Cannot carry " + rel + " across the update"); + } + + static void recoverCarriedPaths(File staging, File target, java.util.List<String> paths) throws IOException { + for (String rel : paths) { + File src = safePath(staging, rel); + if (!exists(src.toPath())) continue; + File dst = safePath(target, rel); + if (!exists(dst.toPath())) move(staging, target, rel); + } + } + + static boolean hasPaths(File tree, java.util.List<String> paths) throws IOException { + for (String rel : paths) if (exists(safePath(tree, rel).toPath())) return true; + return false; + } + + private static File safePath(File tree, String rel) throws IOException { + Path relative = java.nio.file.Paths.get(rel); + if (relative.isAbsolute() || relative.getNameCount() == 0) throw new IOException("Invalid runtime path: " + rel); + for (Path part : relative) if (part.toString().equals("..")) throw new IOException("Invalid runtime path: " + rel); + Path current = tree.toPath(); + for (int i = 0; i < relative.getNameCount() - 1; i++) { + current = current.resolve(relative.getName(i)); + try { + BasicFileAttributes attrs = Files.readAttributes(current, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!attrs.isDirectory()) throw new IOException("Runtime path has a non-directory parent: " + current); + } catch (NoSuchFileException ignored) { + break; + } + } + return tree.toPath().resolve(relative).toFile(); + } + static void carryHome(File old, File staging) throws IOException { File home = new File(old, "root"); if (!home.isDirectory()) return; diff --git a/app/src/main/java/com/droiddeck/launcher/session/BatteryComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/BatteryComponent.kt index 252e06a9e2..517fa6c74f 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/BatteryComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/BatteryComponent.kt @@ -56,8 +56,9 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L val charging = status == BatteryManager.BATTERY_STATUS_CHARGING val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L + // Android can keep reporting charging at 100%; Linux reports Full there, and Steam shows 99% until it does. val statusText = when (status) { - BatteryManager.BATTERY_STATUS_CHARGING -> "Charging" + BatteryManager.BATTERY_STATUS_CHARGING -> if (pct >= 100) "Full" else "Charging" BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging" BatteryManager.BATTERY_STATUS_FULL -> "Full" BatteryManager.BATTERY_STATUS_NOT_CHARGING -> "Not charging" diff --git a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt index ae405a80ae..8b7ad50f0c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt @@ -155,8 +155,7 @@ object ComponentsManager { if (staged.exists()) check(staged.delete()) { "Could not remove unpublished component selections" } } - private fun saveState(context: Context, state: JSONObject) { - val prepared = prepareLaunchState(context, state) + private fun saveState(context: Context, state: JSONObject, prepared: PreparedLaunchState = prepareLaunchState(context, state)) { val dir = launchDir(context) val tmp = File(dir, "desired.tsv.tmp") try { @@ -175,6 +174,17 @@ object ComponentsManager { ?.forEach { it.deleteRecursively() } } + fun republish(context: Context): Boolean = synchronized(lock) { + recoverState(context) + val saved = stateFile(context) + if (saved.exists() && runCatching { JSONObject(saved.readText()) }.isFailure) return false + val state = loadState(context) + val prepared = prepareLaunchState(context, state) + if ((FileUtils.readString(File(launchDir(context), "desired.tsv")) ?: "") == prepared.text) return false + saveState(context, state, prepared) + true + } + private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) } private fun rememberProfiledComponent(state: JSONObject, comp: String) { @@ -780,6 +790,64 @@ object ComponentsManager { true } + private fun checkPackageUnused(context: Context, state: JSONObject, name: String) { + val installed = protons(context).distinctBy { it.id }.associateBy { it.id } + for (key in listOf("queued", "active")) { + val byProton = state.sub(key) + for (pid in byProton.keys()) { + val comps = byProton.optJSONObject(pid) ?: continue + for (comp in comps.keys()) { + val entry = comps.optJSONObject(comp) ?: continue + check(entry.optString("file") != name || !liveSelection(key, entry, installed[pid])) { + context.getString(R.string.cmgr_package_in_use, name, installed[pid]?.name ?: pid) + } + } + } + } + val profiles = state.sub("profiles") + for (scope in profiles.keys()) { + val profile = profiles.optJSONObject(scope) ?: continue + check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) } + } + } + + fun carryOver(context: Context, fromDir: String, toDir: String) { + synchronized(lock) { + val target = protons(context).firstOrNull { it.id == safeName(toDir) } ?: return + val state = loadState(context) + val wanted = carried(state, safeName(fromDir)) { File(packagesDir(context), it).isFile } + val active = state.sub("active").optJSONObject(target.id) + val queued = state.sub("queued").sub(target.id) + var changed = false + wanted.forEach { (comp, entry) -> + if (active?.has(comp) != true && !queued.has(comp)) { + queued.put(comp, entry) + changed = true + } + } + if (queued.length() == 0) state.sub("queued").remove(target.id) + if (changed) saveState(context, state) + } + } + + internal fun carried(state: JSONObject, from: String, present: (String) -> Boolean): Map<String, JSONObject> = buildMap { + state.optJSONObject("active")?.optJSONObject(from)?.let { active -> + active.keys().forEach { comp -> + val entry = active.optJSONObject(comp) ?: return@forEach + val file = entry.optString("file") + if (comp in COMPONENTS && file.endsWith(".wcp") && present(file)) { + put(comp, JSONObject().put("kind", "package").put("file", file).put("label", entry.optString("label"))) + } + } + } + state.optJSONObject("queued")?.optJSONObject(from)?.let { queued -> + queued.keys().forEach { comp -> + val entry = queued.optJSONObject(comp) ?: return@forEach + if (comp in COMPONENTS && entry.optString("kind") == "package" && present(entry.optString("file"))) put(comp, entry) + } + } + } + fun forgetProton(context: Context, dirName: String) { synchronized(lock) { val id = safeName(dirName) @@ -791,6 +859,33 @@ object ComponentsManager { } } + private fun storePackage(context: Context, part: File, dest: File) { + try { + if (dest.isFile && runCatching { Hashes.sha256(dest) }.getOrNull()?.equals(Hashes.sha256(part), true) == true) return + if (dest.exists()) checkPackageUnused(context, loadState(context), dest.name) + val store = File(launchDir(context), "store").canonicalFile + val cacheKey = unpackedCacheKey(dest.name) + val unpacked = File(store, cacheKey).canonicalFile + check(unpacked.parentFile == store) { "Invalid unpacked component cache path for ${dest.name}" } + val complete = File(unpacked, ".complete") + if (complete.exists()) check(complete.delete()) { "Could not invalidate unpacked component ${dest.name}" } + if (!part.renameTo(dest)) { + dest.delete() + check(part.renameTo(dest)) { "Could not store ${dest.name}" } + } + if (!unpacked.deleteRecursively() && unpacked.exists()) { + check(!complete.exists()) { "Could not invalidate unpacked component ${dest.name}" } + Log.w(TAG, "Could not remove stale unpacked files for ${dest.name}; cache marker is invalidated") + } + } finally { + part.delete() + } + } + + internal fun unpackedCacheKey(filename: String): String = safeName(filename.removeSuffix(".wcp")).also { + require(it != "." && it != "..") { "Invalid component cache name" } + } + fun deletePackage(context: Context, file: String): String = synchronized(lock) { val name = safeName(file) val state = loadState(context) @@ -840,7 +935,7 @@ object ComponentsManager { fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) { val info = packageInfo(context, source) val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" }) - source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest) + storePackage(context, source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true), dest) info.copy(file = dest.name) } @@ -863,6 +958,7 @@ object ComponentsManager { .put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest"))) } } + if (items.length() == 0 && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) } val out = JSONObject().put("items", items).put("fetchedAt", System.currentTimeMillis() / 1000) val tmp = File(cache.parentFile, cache.name + ".tmp") tmp.writeText(out.toString()); tmp.renameTo(cache) @@ -992,7 +1088,7 @@ object ComponentsManager { } if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error(context.getString(R.string.cmgr_checksum_mismatch)) } val info = runCatching { packageInfo(context, part) }.getOrElse { part.delete(); throw it } - synchronized(lock) { part.renameTo(dest) } + synchronized(lock) { storePackage(context, part, dest) } return info.copy(file = dest.name) } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt b/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt index 73f42cb141..92cd7652da 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt @@ -8,7 +8,7 @@ import org.json.JSONObject import java.io.File /** - * The FEX build DroidDeck-Components' fex.json names for the x86-64 client. A session uses the last copy read. + * The FEX build DroidDeck-Components' fex.json names for x86 programs. A session uses the last copy read. * Components' build-fex.yml replaces the archive on its single `fex` release and records the build's version; * a release per build (fex-2610-r5) is still read. */ @@ -62,7 +62,7 @@ object FexCatalog { return build } - /** For droiddeck-steam-x64: the build and every source its archive may come from (it checks the sha256). */ + /** For droiddeck-fex-update: the build and every source its archive may come from (it checks the sha256). */ fun environment(build: Build, sources: List<String> = DownloadSource.candidates(build.url)): List<String> = listOf( "BL_FEX_TAG=${build.tag}", "BL_FEX_SHA256=${build.sha256}", diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt index 351fe304c0..4d1ae8de21 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt @@ -78,6 +78,14 @@ object GameEnvironmentStore { return config } + @Synchronized + fun setDefault(context: Context, scope: String, name: String, value: String): Boolean { + val config = read(context) + if (GameEnvironment.hasOverride(config, scope, name)) return false + save(context, GameEnvironment.withScopeValue(config, scope, name, value)) + return true + } + @Synchronized fun publish(context: Context, config: GameEnvironment.Config = read(context)) { val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared) 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 90feec16e1..447fb254c9 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt @@ -14,9 +14,12 @@ object GameStorage { fun options(context: Context): List<Option> { val sm = context.getSystemService(StorageManager::class.java) + val primary = context.getExternalFilesDir(null)?.absolutePath + val primaryStorage = Environment.getExternalStorageDirectory()?.absolutePath return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir -> - val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false } - if (!removable) return@mapNotNull null + // Non-primary app dirs are usable even when Android reports the volume as non-removable (USB SSDs often do). + if (primary != null && dir.absolutePath == primary) return@mapNotNull null + if (!primaryStorage.isNullOrBlank() && dir.absolutePath.startsWith("$primaryStorage/")) return@mapNotNull null val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null } val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: context.getString(R.string.gstore_sd_card) Option(context.getString(R.string.gstore_volume_free, name, free(dir)), File(dir, "steam").absolutePath, name) diff --git a/app/src/main/java/com/droiddeck/launcher/session/MemoryReadout.kt b/app/src/main/java/com/droiddeck/launcher/session/MemoryReadout.kt new file mode 100644 index 0000000000..c5fcf8a733 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/MemoryReadout.kt @@ -0,0 +1,175 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.os.Handler +import android.os.Looper +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.R +import java.io.File +import java.util.Locale + +internal object MemoryReadout { + data class Device(val totalKb: Long, val availableKb: Long, val swapTotalKb: Long, val swapFreeKb: Long) { + val usedKb get() = (totalKb - availableKb).coerceAtLeast(0) + val swapUsedKb get() = (swapTotalKb - swapFreeKb).coerceAtLeast(0) + } + + data class Split(val gameKb: Long, val droiddeckKb: Long, val gpuKb: Long?) + + fun parseMeminfo(text: String): Device? { + fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(text)?.groupValues?.get(1)?.toLongOrNull() + val total = field("MemTotal") ?: return null + val available = field("MemAvailable") ?: return null + return Device(total, available, field("SwapTotal") ?: 0, field("SwapFree") ?: 0) + } + + fun residentKb(status: String): Long { + fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(status)?.groupValues?.get(1)?.toLongOrNull() ?: 0 + return field("RssAnon") + field("RssShmem") + } + + fun inWinePrefix(environ: ByteArray): Boolean { + var start = 0 + val key = "WINEPREFIX=".toByteArray() + for (i in 0..environ.size) { + if (i == environ.size || environ[i] == 0.toByte()) { + if (i - start >= key.size && (key.indices).all { environ[start + it] == key[it] }) return true + start = i + 1 + } + } + return false + } + + fun androidKb(device: Device, split: Split): Long = + (device.usedKb - split.gameKb - split.droiddeckKb - (split.gpuKb ?: 0)).coerceAtLeast(0) + + fun gb(kb: Long): String = String.format(Locale.US, "%.1f", kb / (1024.0 * 1024.0)) + + fun availableMb(): Long? = runCatching { parseMeminfo(File("/proc/meminfo").readText())?.availableKb?.div(1024) }.getOrNull() + + fun device(): Device? = runCatching { parseMeminfo(File("/proc/meminfo").readText()) }.getOrNull() + + fun split(root: Int = android.os.Process.myPid()): Split { + val parents = HashMap<Int, Int>() + File("/proc").listFiles()?.forEach { entry -> + val pid = entry.name.toIntOrNull() ?: return@forEach + parentOf(pid)?.let { parents[pid] = it } + } + val children = parents.entries.groupBy({ it.value }, { it.key }) + var game = 0L + var droiddeck = 0L + val queue = ArrayDeque<Int>().apply { add(root) } + val seen = HashSet<Int>() + while (queue.isNotEmpty()) { + val pid = queue.removeFirst() + if (!seen.add(pid)) continue + val status = runCatching { File("/proc/$pid/status").readText() }.getOrNull() + if (status != null) { + val kb = residentKb(status) + val windows = pid != root && runCatching { inWinePrefix(File("/proc/$pid/environ").readBytes()) }.getOrDefault(false) + if (windows) game += kb else droiddeck += kb + } + children[pid]?.let(queue::addAll) + } + return Split(game, droiddeck, gpuKb()) + } + + private fun parentOf(pid: Int): Int? { + val stat = runCatching { File("/proc/$pid/stat").readText() }.getOrNull() ?: return null + val close = stat.lastIndexOf(')') + if (close < 0 || close + 2 >= stat.length) return null + return stat.substring(close + 2).split(' ').getOrNull(1)?.toIntOrNull() + } + + private fun gpuKb(): Long? = runCatching { + File("/sys/class/kgsl/kgsl/page_alloc").readText().trim().split(Regex("\\s+"))[0].toLong() / 1024 + }.getOrNull() +} + +object MemoryLog { + private const val TAG = "Memory" + private const val PERIOD_MS = 10_000L + @Volatile private var thread: Thread? = null + + internal fun line(device: MemoryReadout.Device, split: MemoryReadout.Split): String = + "used ${device.usedKb / 1024}/${device.totalKb / 1024} MB, available ${device.availableKb / 1024} MB, " + + "swap ${device.swapUsedKb / 1024}/${device.swapTotalKb / 1024} MB | game ${split.gameKb / 1024}, " + + "droiddeck ${split.droiddeckKb / 1024}, android ${MemoryReadout.androidKb(device, split) / 1024}, " + + "gpu ${split.gpuKb?.div(1024) ?: "?"} MB" + + @Synchronized + fun start() { + if (thread != null) return + thread = Thread({ + while (!Thread.currentThread().isInterrupted) { + runCatching { MemoryReadout.device()?.let { android.util.Log.i(TAG, line(it, MemoryReadout.split())) } } + try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break } + } + }, "memory-log").apply { isDaemon = true; start() } + } + + @Synchronized + fun stop() { + thread?.interrupt() + thread = null + } +} + +class MemoryHud(context: Context) { + var text by mutableStateOf("") + private set + + private val context = context.applicationContext + private val handler = Handler(Looper.getMainLooper()) + @Volatile private var running = false + @Volatile private var generation = 0 + private var thread: Thread? = null + + fun refresh() { + if (SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) stop() else start() + } + + fun start() { + if (running || SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) return + running = true + val token = ++generation + thread = Thread({ + while (running && generation == token) { + val line = runCatching { sample() }.getOrDefault("") + handler.post { if (running && generation == token) text = line } + try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break } + } + }, "memory-hud").apply { isDaemon = true; start() } + } + + fun stop() { + running = false + generation++ + thread?.interrupt() + thread = null + text = "" + } + + private fun sample(): String { + val device = MemoryReadout.device() ?: return "" + val memory = context.getString( + R.string.memory_hud_simple, + MemoryReadout.gb(device.usedKb), MemoryReadout.gb(device.totalKb), + MemoryReadout.gb(device.swapUsedKb), MemoryReadout.gb(device.swapTotalKb), + ) + if (SessionPrefs.memoryHud(context) != SessionPrefs.MEMORY_HUD_ADVANCED) return memory + val split = MemoryReadout.split() + val parts = context.getString( + R.string.memory_hud_split, + MemoryReadout.gb(split.gameKb), MemoryReadout.gb(split.droiddeckKb), MemoryReadout.gb(MemoryReadout.androidKb(device, split)), + ) + val gpu = split.gpuKb?.let { context.getString(R.string.memory_hud_gpu, MemoryReadout.gb(it)) } + return listOfNotNull(memory, parts, gpu).joinToString("\n") + } + + private companion object { + const val PERIOD_MS = 2000L + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt b/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt index 6787d92d22..8d8070f875 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt @@ -9,11 +9,13 @@ import com.droiddeck.launcher.stores.epic.EpicClient object NoSteamLaunch { const val PROTON_RUN = "/usr/local/bin/droiddeck-proton-run" const val EPIC = "/usr/local/bin/droiddeck-epic" + const val BATTLENET = com.droiddeck.launcher.runtime.BattleNet.PROGRAM class Command(val program: String, val args: List<String>, val name: String) fun scope(game: Library.SteamGame): String? = when { game.library == Library.EPIC_LAUNCHER -> EpicClient.shortcutAppId.toString() + game.library == Library.BATTLENET_LAUNCHER -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString() game.library == Library.ADDED || game.appId > 0 -> game.profileKey else -> null }?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) } @@ -30,6 +32,8 @@ object NoSteamLaunch { fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when { game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name) + game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> + game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.let { Command(BATTLENET, listOf("launch", it.code), game.name) } game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) } game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name) else -> null @@ -37,7 +41,9 @@ object NoSteamLaunch { fun addedCommand(game: AddedGames.Game): Command = Command( PROTON_RUN, - listOf("--app", (game.appId and 0xFFFFFFFFL).toString(), "--dir", game.guestDir, "--options", game.launchOptions, "--", game.guestExe), + listOf("--app", (game.appId and 0xFFFFFFFFL).toString(), "--dir", game.guestDir) + + (if (game.launchOptions.isEmpty()) emptyList() else listOf("--options", game.launchOptions)) + + listOf("--", game.guestExe), game.name, ) @@ -45,11 +51,13 @@ object NoSteamLaunch { fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? { val id = game.appId.toLong() and 0xFFFFFFFFL - return AddedGames.scan(context).firstOrNull { settingsId(it) == id } + val one = game.gameFiles?.let { AddedGames.single(context, it.path) } + return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id } } fun nameFor(program: String?, args: List<String>): String? = when (program) { EPIC -> Library.EPIC_LAUNCHER_NAME + BATTLENET -> args.getOrNull(args.indexOf("launch") + 1)?.takeIf { args.contains("launch") }?.let { names[it] } ?: com.droiddeck.launcher.stores.Store.BATTLENET.label PROTON_RUN -> args.getOrNull(args.indexOf("--app") + 1)?.takeIf { args.contains("--app") }?.let { names[it] } else -> null } @@ -58,5 +66,6 @@ object NoSteamLaunch { fun remember(command: Command) { if (command.program == PROTON_RUN) command.args.getOrNull(command.args.indexOf("--app") + 1)?.let { names[it] = command.name } + if (command.program == BATTLENET) command.args.getOrNull(command.args.indexOf("launch") + 1)?.takeIf { command.args.contains("launch") }?.let { names[it] = command.name } } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt b/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt index 3829d9a258..6453f65f9c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt @@ -18,7 +18,6 @@ import com.droiddeck.launcher.wayland.WaylandCompositor import java.io.File import java.util.Locale import java.util.concurrent.atomic.AtomicInteger -import java.util.concurrent.atomic.AtomicLong class PerfHud(context: Context) { var text by mutableStateOf("") @@ -32,9 +31,9 @@ class PerfHud(context: Context) { private var lastFps = 0f private var running = false private val handler = Handler(Looper.getMainLooper()) - private val intervals = FloatArray(GRAPH) - private val graphWrite = AtomicInteger() - private val lastFrameNs = AtomicLong() + private val samples = FloatArray(GRAPH) + private var graphBase = 0L + private var graphSeen = 0L @Volatile private var showFps = true @Volatile private var showBattery = true @@ -59,14 +58,6 @@ class PerfHud(context: Context) { } override fun onGameFrame() { frames.incrementAndGet() - if (!showGraph) return - val now = System.nanoTime() - val previous = lastFrameNs.getAndSet(now) - if (previous == 0L) return - val ms = ((now - previous) / 1_000_000f).coerceIn(0f, 50f) - val slot = graphWrite.get() - intervals[slot and (GRAPH - 1)] = ms - graphWrite.compareAndSet(slot, slot + 1) } } @@ -100,9 +91,9 @@ class PerfHud(context: Context) { if (!enabled || !anyPart || running) return running = true lastTick = SystemClock.elapsedRealtime() - lastFrameNs.set(0L) frames.set(0) - graphWrite.set(0) + graphBase = shownTotal() + graphSeen = graphBase WaylandCompositor.setGameListener(listener) handler.postDelayed(tick, TICK_MS) } @@ -135,23 +126,19 @@ class PerfHud(context: Context) { return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) } + private fun shownTotal(): Long = try { WaylandCompositor.nativeHudFrameTimes(samples) } catch (t: Throwable) { 0L } + private fun clearGraph() { - lastFrameNs.set(0L) - graphWrite.set(0) + graphBase = shownTotal() + graphSeen = graphBase if (graph.isNotEmpty()) graph = FloatArray(0) } private fun publishGraph() { - val count = graphWrite.get() - val shown = minOf(count, GRAPH) - if (shown < 2) { - graph = FloatArray(0) - return - } - val out = FloatArray(shown) - val start = count - shown - for (i in 0 until shown) out[i] = intervals[(start + i) and (GRAPH - 1)] - graph = out + val total = shownTotal() + if (total == graphSeen && graph.isNotEmpty()) return + graphSeen = total + graph = recent(samples, total, graphBase) } private fun line(base: Float): String { @@ -176,6 +163,14 @@ class PerfHud(context: Context) { companion object { private const val TICK_MS = 1_000L private const val GRAPH = 128 + internal const val GRAPH_MAX_MS = 50f + + internal fun recent(samples: FloatArray, total: Long, base: Long): FloatArray { + val filled = minOf(total, samples.size.toLong()).toInt() + val shown = minOf(filled.toLong(), (total - base).coerceAtLeast(0L)).toInt() + if (shown < 2) return FloatArray(0) + return FloatArray(shown) { samples[filled - shown + it].coerceIn(0f, GRAPH_MAX_MS) } + } internal fun batteryCelsius(deci: Int): String? = if (deci <= 0) null else String.format(Locale.US, "%.1f°C", deci / 10f) diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonDefault.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonDefault.kt index ff3214cf79..2c7110a855 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonDefault.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonDefault.kt @@ -114,12 +114,19 @@ object ProtonDefault { return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START } + internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? { + if (choices.values.none { it != null && !it.valve && it.dir in from }) return null + return choices.mapValues { (_, choice) -> if (choice != null && !choice.valve && choice.dir in from) GameChoice(false, to) else choice } + } + @Synchronized - fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome { - require(GameEnvironment.validScope(scope)) + fun moveGames(context: Context, from: Set<String>, to: String) { val d = dir(context) - val choices = parseGames(read(File(d, GAMES))).toMutableMap() - choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) } + val moved = movedGames(parseGames(read(File(d, GAMES))), from, to) ?: return + writeGames(d, moved) + } + + private fun writeGames(d: File, choices: Map<String, GameChoice?>) { val games = JSONObject() choices.forEach { (id, choice) -> games.put(id, choice?.let { JSONObject().put("valve", it.valve).put("dir", it.dir) } ?: JSONObject.NULL) @@ -134,6 +141,15 @@ object ProtonDefault { Log.w(TAG, "could not write the per-game Proton request", e) throw e } + } + + @Synchronized + fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome { + require(GameEnvironment.validScope(scope)) + val d = dir(context) + val choices = parseGames(read(File(d, GAMES))).toMutableMap() + choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) } + writeGames(d, choices) val state = state(context) val tool = proton?.let { selected -> state.tools.firstOrNull { it.valve == selected.valve && it.dir == selected.dir.name } } return if (SessionState.running && state.live && (proton == null || tool != null && state.pending != tool.name)) { 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 20714ba95a..962291d2c7 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -16,16 +16,20 @@ object ProtonExtras { private const val TAG = "ProtonExtras" private const val NEED_BYTES = 4L * 1024 * 1024 * 1024 private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15" - const val CHECK_EVERY_MS = 6L * 60 * 60 * 1000 + const val CHECK_EVERY_MS = 60L * 60 * 1000 @Volatile var installInProgress = false private set + @Volatile + private var replacing = false class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex) internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long, val sha256: String? = null) + const val OWN = "droiddeck" + val tools = listOf( Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")), Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")), @@ -78,11 +82,23 @@ object ProtonExtras { fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool)) + fun missing(context: Context, tool: Tool): String? = + if (tool.id == OWN && !declined(context) && installedAll(context, tool).isEmpty()) cachedLatest(context, tool) else null + + private fun choices(context: Context) = context.getSharedPreferences("proton-auto-updates", Context.MODE_PRIVATE) + + fun declined(context: Context): Boolean = choices(context).getBoolean("$OWN.declined", false) + + fun setDeclined(context: Context, declined: Boolean) { + choices(context).edit().putBoolean("$OWN.declined", declined).apply() + } + fun cachedLatest(context: Context, tool: Tool): String? = readJson(latestFile(context)).optJSONObject(tool.id)?.optString("tag")?.ifEmpty { null } private val checkLock = Any() private const val RETRY_MS = 15L * 60 * 1000 + private const val USER_SETTINGS = "user_settings.py" private var lastAttempt = 0L fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean { @@ -145,6 +161,44 @@ object ProtonExtras { } } + private fun replaceOlder(context: Context, tool: Tool) { + val all = installedAll(context, tool) + val newest = all.lastOrNull() ?: return + val older = all.dropLast(1) + if (older.isEmpty()) return + replacing = true + try { + for (old in older.asReversed()) { + if (SessionState.running) break + if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue + if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue + if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue + if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old) + else Log.w(TAG, "could not remove $old") + } + } finally { + replacing = false + } + } + + private fun keepUserSettings(context: Context, old: String, newest: String) { + val from = File(File(toolsDir(context), old), USER_SETTINGS) + val to = File(File(toolsDir(context), newest), USER_SETTINGS) + if (from.isFile && !to.exists()) from.copyTo(to) + } + + fun tidy(context: Context) { + val tool = tools.firstOrNull { it.id == OWN } ?: return + if (installedAll(context, tool).size > 1) replaceOlder(context, tool) + } + + fun awaitReplacement(timeoutMs: Long) { + val until = System.currentTimeMillis() + timeoutMs + while (replacing && System.currentTimeMillis() < until) { + try { Thread.sleep(50) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return } + } + } + @Synchronized fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { if (installInProgress) return context.getString(R.string.pextra_busy) @@ -246,6 +300,7 @@ object ProtonExtras { archive.delete() unqueue(context, tool) record(context, tool, placed, asset.tag) + if (tool.id == OWN) replaceOlder(context, tool) if (EsyncPacks.enabled(context)) { onProgress(context.getString(R.string.esync_fetching), -1) try { diff --git a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt index f2b1c0a1e6..5826db97ab 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt @@ -30,6 +30,7 @@ class RumbleComponent : SessionPart() { private val joyConPairs = HashMap<Long, Motors>() private var preferences: SharedPreferences? = null private var enabled = false + private var quiet = false private var motorThread: HandlerThread? = null private var handler: Handler? = null private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> @@ -44,6 +45,11 @@ class RumbleComponent : SessionPart() { if (!enabled) cancelAll() } + @Synchronized fun quiet(on: Boolean) { + quiet = on + if (on) cancelAll() + } + override fun start() { val ctx = app() ?: return val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return } @@ -89,7 +95,7 @@ class RumbleComponent : SessionPart() { private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8) @Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) { - if (!enabled) return + if (!enabled || quiet) return val target = target(slot) val previous = playing[slot] if (target !== previous) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt index c0bba60936..31b9b10988 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt @@ -17,12 +17,13 @@ object SessionDisplay { fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> = (maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv()) - fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> { - if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return screenSize(panel) - presetHeight(choice)?.let { return resolve(panel, it, SessionPrefs.SHAPE_AUTO) } + fun resolveChoice(panel: Pair<Int, Int>, choice: String, portrait: Boolean = false): Pair<Int, Int> { + fun orient(size: Pair<Int, Int>) = if (portrait) size.second to size.first else size + if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return orient(screenSize(panel)) + presetHeight(choice)?.let { return orient(resolve(panel, it, SessionPrefs.SHAPE_AUTO)) } val parts = choice.split('x').map { it.toIntOrNull() } return if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!! - else resolve(panel, 720, SessionPrefs.SHAPE_AUTO) + else orient(resolve(panel, 720, SessionPrefs.SHAPE_AUTO)) } fun resolutionOptions(panel: Pair<Int, Int>): List<String> { @@ -31,8 +32,10 @@ object SessionDisplay { .filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN + FOLLOW_SCREEN } - fun followSize(width: Int, height: Int): Pair<Int, Int>? = - if (minOf(width, height) < FOLLOW_MIN_SIDE) null else (width and 1.inv()) to (height and 1.inv()) + fun followSize(width: Int, height: Int, controlsBelow: Boolean = false): Pair<Int, Int>? = + if (width <= 0 || height <= 0 || + (if (controlsBelow) width else minOf(width, height)) < FOLLOW_MIN_SIDE) null + else (width and 1.inv()) to (height and 1.inv()) const val UNFOLDED_MAX_GAME_SHARE = 0.8f @@ -49,13 +52,14 @@ object SessionDisplay { foldable: Boolean, controllerConnected: Boolean, keepWithController: Boolean, - steamDeckPad: Boolean, + gamepadAvailable: Boolean, pip: Boolean, width: Int, height: Int, smallestWidthDp: Int, - ): Boolean = enabled && foldable && (keepWithController || !controllerConnected) && steamDeckPad && - !pip && width > 0 && height > 0 && smallestWidthDp >= UNFOLDED_MIN_DP + ): Boolean = enabled && (keepWithController || !controllerConnected) && gamepadAvailable && + !pip && width > 0 && height > 0 && + (height > width || (foldable && smallestWidthDp >= UNFOLDED_MIN_DP)) fun panelSize(context: Context): Pair<Int, Int> { @@ -79,5 +83,5 @@ object SessionDisplay { } fun canStretch16x9(size: Pair<Int, Int>): Boolean = - (size.second * 16 + 4) / 9 / 2 * 2 > size.first + (size.second * 16 + 4) / 9 / 2 * 2 > size.first || (size.first * 9 + 8) / 16 / 2 * 2 > size.second } 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 38d6c6fd08..d9c59b1b88 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -74,12 +74,14 @@ object SessionFiles { "usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts", "usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox", "usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch", + "usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet", "usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic", "usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam", "usr/local/bin/droiddeck-open-url" to "usr/local/bin/droiddeck-open-url", "usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games", "usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults", "usr/local/bin/droiddeck-steam-x64" to "usr/local/bin/droiddeck-steam-x64", + "usr/local/bin/droiddeck-fex-update" to "usr/local/bin/droiddeck-fex-update", "usr/local/bin/droiddeck-steamrt-shim" to "usr/local/bin/droiddeck-steamrt-shim", "usr/local/bin/droiddeck-x64-arm-proton" to "usr/local/bin/droiddeck-x64-arm-proton", "usr/local/bin/droiddeck-x64-arm-webhelper" to "usr/local/bin/droiddeck-x64-arm-webhelper", @@ -97,6 +99,15 @@ object SessionFiles { "usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run", "usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open", "usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run", + "usr/local/bin/droiddeck-innoextract" to "usr/local/bin/droiddeck-innoextract", + "usr/local/lib/droiddeck-inno/innoextract" to "usr/local/lib/droiddeck-inno/innoextract", + "usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0", + "usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0", + "usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0", + "usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0", + "usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0", + "usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract" to "usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract", + "usr/local/share/licenses/droiddeck-inno/LICENSE.boost" to "usr/local/share/licenses/droiddeck-inno/LICENSE.boost", "usr/bin/steamos-update" to "usr/bin/steamos-update", "usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch", "usr/bin/steamos-session-select" to "usr/bin/steamos-session-select", @@ -141,6 +152,8 @@ object SessionFiles { } + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" } val optional = (arrayOf( "usr/local/bin/gamescope" to "usr/local/bin/gamescope", + // The gamescope pack carries its own WSI layer (patch 0117); it replaces the runtime's stock copy. + "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so", "usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime", "usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst", "usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE", @@ -205,7 +218,11 @@ object SessionFiles { if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) { preload.append("/usr/local/lib/libfakeinput.so\n") } - if (ProotFastPath.enabled(context)) preload.append(ProotFastPath.LIBRARY + "\n") + if (ProotFastPath.enabled(context)) { + val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context) + preload.append(library + "\n") + if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)") + } val etc = File(root, "etc").apply { mkdirs() } val staged = File(etc, "ld.so.preload.staged") if (!FileUtils.writeString(staged, preload.toString()) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionLogShare.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionLogShare.kt index b44c5c6260..ded53162c6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionLogShare.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionLogShare.kt @@ -12,6 +12,7 @@ import androidx.compose.runtime.setValue import androidx.core.content.FileProvider import com.droiddeck.launcher.R import com.droiddeck.launcher.core.LogRedactor +import com.droiddeck.launcher.runtime.BattleNet import com.droiddeck.launcher.runtime.LinuxRuntime import java.io.File import java.util.zip.ZipEntry @@ -49,7 +50,8 @@ object SessionLogShare { val logs = LinuxRuntime.logDir(context) val stores = recent(File(logs, STORES_DIR)) val tools = recent(File(logs, SessionPaths.TOOLS_DIR)) - val total = (files + live + stores + tools).sumOf { it.length() }.coerceAtLeast(1L) + val battleNet = battleNetLogs(context) + val total = (files + live + stores + tools + battleNet.map { it.second }).sumOf { it.length() }.coerceAtLeast(1L) var done = 0L var shown = -1 fun advance(f: File) { @@ -62,6 +64,7 @@ object SessionLogShare { live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) } stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) } tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) } + battleNet.forEach { (name, f) -> addEntry(z, "$BATTLENET_DIR/$name", f); advance(f) } } return zip } @@ -88,6 +91,27 @@ object SessionLogShare { private fun shareDir(context: Context): File = File(context.cacheDir, "share") + private const val BATTLENET_DIR = "battlenet" + + private fun battleNetLogs(context: Context): List<Pair<String, File>> { + val drive = File(BattleNet.prefix(context), "pfx/drive_c") + val data = File(drive, "ProgramData/Battle.net") + fun logsUnder(dir: File, prefix: String) = dir.listFiles { f -> f.isDirectory && f.name.startsWith(prefix) }.orEmpty().map { File(it, "Logs") } + return newest("droiddeck", listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")), 2, setOf("battlenet.log", "spawned.log")) + + newest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6) + + newest("agent", listOf(File(data, "Agent/Logs")) + logsUnder(File(data, "Agent"), "Agent."), 10, byDir = true) + + newest("setup", logsUnder(File(data, "Setup"), ""), 3, byDir = true) + } + + private fun newest(folder: String, dirs: List<File>, count: Int, names: Set<String>? = null, byDir: Boolean = false): List<Pair<String, File>> { + val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L + return dirs.flatMap { dir -> + dir.listFiles { f -> f.isFile && f.name.endsWith(".log") && (names == null || f.name in names) && f.lastModified() >= since && f.length() <= STEAM_LOG_MAX_BYTES }.orEmpty().toList() + }.sortedByDescending { it.lastModified() }.take(count).map { f -> + (if (byDir) "$folder/${f.parentFile?.parentFile?.name}/${f.name}" else "$folder/${f.name}") to f + } + } + private fun recent(dir: File): List<File> { val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty() 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 d77cced0b8..77601e3a3a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -9,6 +9,7 @@ import com.droiddeck.launcher.core.TextureFiltering import com.droiddeck.launcher.gpu.Cardboard import com.droiddeck.launcher.gpu.ScreenEffects import org.json.JSONObject +import java.io.File object SessionPrefs { data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null) @@ -43,6 +44,8 @@ object SessionPrefs { private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE) val orientationOptions = listOf( + ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto, + ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait, ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse, @@ -58,6 +61,17 @@ object SessionPrefs { prefs(context).edit().putInt("orientation", orientation).apply() } + fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int = + if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation")) + ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context) + + fun portrait(context: Context): Boolean = when (orientation(context)) { + ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true + ActivityInfo.SCREEN_ORIENTATION_USER -> + context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT + else -> false + } + fun launcherFullscreen(context: Context): Boolean = prefs(context).getBoolean("launcherFullscreen", true) fun setLauncherFullscreen(context: Context, on: Boolean) { @@ -111,6 +125,12 @@ object SessionPrefs { prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply() } + fun libraryShowUninstalled(context: Context): Boolean = prefs(context).getBoolean("libraryShowUninstalled", false) + + fun setLibraryShowUninstalled(context: Context, show: Boolean) { + prefs(context).edit().putBoolean("libraryShowUninstalled", show).apply() + } + fun storesTabOrder(context: Context): List<String> = idList(prefs(context).getString("storesTabOrder", null)) fun setStoresTabOrder(context: Context, order: List<String>) { @@ -141,6 +161,34 @@ object SessionPrefs { prefs(context).edit().putString("storesInstallLanguage", code).apply() } + const val DEFAULT_STORAGE_ASK = "ask" + const val DEFAULT_STORAGE_INTERNAL = "internal" + const val DEFAULT_STORAGE_EXTERNAL = "external" + private val DEFAULT_STORAGE_VALUES = setOf(DEFAULT_STORAGE_ASK, DEFAULT_STORAGE_INTERNAL, DEFAULT_STORAGE_EXTERNAL) + + fun defaultStorage(context: Context): String = + prefs(context).getString("defaultStorage", DEFAULT_STORAGE_ASK) + ?.takeIf { it in DEFAULT_STORAGE_VALUES } ?: DEFAULT_STORAGE_ASK + + fun setDefaultStorage(context: Context, value: String) { + prefs(context).edit().putString("defaultStorage", value.takeIf { it in DEFAULT_STORAGE_VALUES } ?: DEFAULT_STORAGE_ASK).apply() + } + + fun defaultStorageFolder(context: Context): String = prefs(context).getString("defaultStorageFolder", "") ?: "" + + fun defaultStorageFolderLabel(context: Context): String = prefs(context).getString("defaultStorageFolderLabel", "") ?: "" + + fun setDefaultStorageFolder(context: Context, path: String, label: String) { + prefs(context).edit() + .putString("defaultStorageFolder", path) + .putString("defaultStorageFolderLabel", label) + .apply() + } + + fun clearDefaultStorageFolder(context: Context) { + prefs(context).edit().remove("defaultStorageFolder").remove("defaultStorageFolderLabel").apply() + } + fun gameStoresParallel(context: Context): Int = prefs(context).getInt("gameStoresParallel", 1).coerceIn(1, 3) fun setGameStoresParallel(context: Context, count: Int) { @@ -195,16 +243,10 @@ object SessionPrefs { private fun mangoappSession(context: Context) = SessionState.mode == SessionService.MODE_STEAM && mangoapp(context) - fun lowLatencyController(context: Context): Boolean = prefs(context).getBoolean("lowLatencyController", false) + fun lowLatency(context: Context): Boolean = prefs(context).getBoolean("lowLatency", true) - fun setLowLatencyController(context: Context, on: Boolean) { - prefs(context).edit().putBoolean("lowLatencyController", on).apply() - } - - fun lowLatencyTouch(context: Context): Boolean = prefs(context).getBoolean("lowLatencyTouch", false) - - fun setLowLatencyTouch(context: Context, on: Boolean) { - prefs(context).edit().putBoolean("lowLatencyTouch", on).apply() + fun setLowLatency(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("lowLatency", on).apply() } fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false) @@ -213,6 +255,16 @@ object SessionPrefs { prefs(context).edit().putBoolean("backActionsInverted", inverted).apply() } + val BACK_DOUBLE_TAP_MS_OPTIONS = (100..800 step 100).toList() + + fun backDoubleTapMs(context: Context): Int = + prefs(context).getInt("backDoubleTapMs", 500).takeIf { it in BACK_DOUBLE_TAP_MS_OPTIONS } ?: 500 + + fun setBackDoubleTapMs(context: Context, ms: Int) { + require(ms in BACK_DOUBLE_TAP_MS_OPTIONS) + prefs(context).edit().putInt("backDoubleTapMs", ms).apply() + } + const val TOUCH_AUTO = "auto" const val TOUCH_PAD = "touchpad" const val TOUCH_DIRECT = "direct" @@ -453,6 +505,24 @@ object SessionPrefs { prefs(context).edit().putBoolean("gamescopeRealtime", on).apply() } + fun ramCapMb(context: Context): Int = prefs(context).getInt("ramCapMb", 0).coerceAtLeast(0) + + fun setRamCapMb(context: Context, mb: Int) { + prefs(context).edit().putInt("ramCapMb", mb.coerceAtLeast(0)).apply() + } + + fun zramClient(context: Context): Boolean = prefs(context).getBoolean("zramClient", true) + + fun setZramClient(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("zramClient", on).apply() + } + + fun vramCapMb(context: Context): Int = prefs(context).getInt("vramCapMb", 0).coerceAtLeast(0) + + fun setVramCapMb(context: Context, mb: Int) { + prefs(context).edit().putInt("vramCapMb", mb.coerceAtLeast(0)).apply() + } + fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false) fun setGpuClockPin(context: Context, on: Boolean) { @@ -481,6 +551,15 @@ object SessionPrefs { prefs(context).edit().putBoolean("cursorComposite", on).apply() } + /** + * The rootfs ships Termux's unpatched proot. A session uses it only when this file exists, + * so a missing add-on pack cannot silently fall back to it. + * Path: Android/data/<package>/files/droiddeck-stock-proot + */ + @JvmStatic + fun allowStockProot(context: Context): Boolean = + context.getExternalFilesDir(null)?.let { File(it, "droiddeck-stock-proot").isFile } == true + const val DEFAULT_GUEST_HOSTNAME = "DroidDeck" @JvmStatic @@ -523,6 +602,7 @@ object SessionPrefs { } fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true) + fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true) fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() } fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true) @@ -554,6 +634,32 @@ object SessionPrefs { prefs(context).edit().putBoolean("logs", on).apply() } + fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false) + fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() } + + fun clearCachedApps(context: Context): Boolean = prefs(context).getBoolean("clearCachedApps", false) + fun setClearCachedApps(context: Context, on: Boolean) { prefs(context).edit().putBoolean("clearCachedApps", on).apply() } + + fun backgroundAppLimit(context: Context): Int = + prefs(context).getInt("backgroundAppLimit", com.droiddeck.launcher.core.BackgroundAppLimit.OFF) + .takeIf { it in com.droiddeck.launcher.core.BackgroundAppLimit.CHOICES } ?: com.droiddeck.launcher.core.BackgroundAppLimit.OFF + fun setBackgroundAppLimit(context: Context, limit: Int) { + require(limit in com.droiddeck.launcher.core.BackgroundAppLimit.CHOICES) + prefs(context).edit().putInt("backgroundAppLimit", limit).apply() + } + + const val MEMORY_HUD_OFF = "off" + const val MEMORY_HUD_SIMPLE = "simple" + const val MEMORY_HUD_ADVANCED = "advanced" + + fun memoryHud(context: Context): String = + prefs(context).getString("memoryHud", MEMORY_HUD_OFF) + ?.takeIf { it == MEMORY_HUD_SIMPLE || it == MEMORY_HUD_ADVANCED } ?: MEMORY_HUD_OFF + fun setMemoryHud(context: Context, value: String) { + require(value == MEMORY_HUD_OFF || value == MEMORY_HUD_SIMPLE || value == MEMORY_HUD_ADVANCED) + prefs(context).edit().putString("memoryHud", value).apply() + } + fun storageDiagnosticsEnabled(context: Context): Boolean = prefs(context).getBoolean("storageDiagnostics", false) @@ -582,8 +688,10 @@ object SessionPrefs { parseResolution(value)?.let { return "${it.first}x${it.second}" } } if (!resolutionChosen(context, mode) && !saved.contains("shape")) return SessionDisplay.DEFAULT_RESOLUTION - val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), customResolution(context, mode)) + val custom = customResolution(context, mode) + val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), custom) return if (legacy == SessionDisplay.screenSize(panel)) SessionDisplay.MATCH_SCREEN + else if (custom == null && legacy == SessionDisplay.resolve(panel, legacy.second, SHAPE_AUTO)) "${legacy.second}p" else "${legacy.first}x${legacy.second}" } @@ -831,16 +939,15 @@ object SessionPrefs { prefs(context).edit().putBoolean("hdr.$mode", on).apply() } - fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0) + /** Compositor frame limit that releases buffers to the game unpaced. */ + const val FPS_UNPACED = -1 - fun setFpsLimit(context: Context, mode: String, fps: Int) { - prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply() - } - - val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120") - - fun fpsLimitChoices(context: Context): List<Pair<Int, String>> = - fpsLimitChoices.map { (fps, label) -> fps to if (fps == 0) context.getString(R.string.frame_gen_off) else label } + /** + * Buffers go back to the game as soon as they are replaced instead of once per refresh; + * Steam's Frame Limit in the Quick Access menu caps games. Mirroring still follows the glasses' refresh rate. + */ + fun compositorFpsLimit(mirrorRefreshLimit: Int): Int = + if (mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit val upscalerChoices = listOf( 0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR", @@ -1029,6 +1136,18 @@ object SessionPrefs { fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", false) + fun controlsBelowWanted(context: Context, mode: String, width: Int, height: Int, pip: Boolean = false): Boolean = + SessionDisplay.unfoldedControlsWanted( + enabled = unfoldedControls(context), + foldable = SessionDisplay.foldable(context), + controllerConnected = com.droiddeck.launcher.input.PadBridge.anyControllerConnected() || + com.droiddeck.launcher.input.SteamControllerBle.connected, + keepWithController = unfoldedControlsWithController(context), + gamepadAvailable = mode == SessionService.MODE_STEAM && builtinPad(context), + pip = pip, width = width, height = height, + smallestWidthDp = context.resources.configuration.smallestScreenWidthDp, + ) + fun setUnfoldedControls(context: Context, enabled: Boolean) { prefs(context).edit().putBoolean("unfoldedControls", enabled).apply() } 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 f4aa173315..7c9ec9cd2c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -25,6 +25,7 @@ import android.os.PowerManager import android.hardware.display.DisplayManager import android.view.Display import android.util.Log +import android.widget.Toast import com.droiddeck.launcher.R import com.droiddeck.launcher.SessionActivity import com.droiddeck.launcher.audio.DirectAudioRelayComponent @@ -349,8 +350,10 @@ class SessionService : Service() { pipTask = false SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM) SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty() + SessionState.gameId = intent?.getStringExtra(EXTRA_GAME_ID) SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI) SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL) + com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this)) synchronized(stopLock) { SessionState.steamClientArch = null SessionState.running = true @@ -365,6 +368,9 @@ class SessionService : Service() { SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode)) com.droiddeck.launcher.wayland.CompositorHost.newSession() val gen = ++sessionGen + SessionPrefs.backgroundAppLimit(this).takeIf { it != com.droiddeck.launcher.core.BackgroundAppLimit.OFF } + ?.let { com.droiddeck.launcher.core.BackgroundAppLimit.applyAsync(this, it) } + if (SessionPrefs.clearCachedApps(this)) clearCachedApps() cancelQueuedSteamGame(clearMailbox = false) clearSteamGameMailbox() if (SessionState.mode == MODE_STEAM) SessionState.steamUrl @@ -372,6 +378,7 @@ class SessionService : Service() { acquireLocks() Thread({ OrphanReaper.reap("session starting") + ProtonExtras.awaitReplacement(120_000) runSession(gen) }, "session-start").start() return START_NOT_STICKY @@ -424,8 +431,33 @@ class SessionService : Service() { val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() } val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() } killStragglers() - for (pack in listOf(AddonPack.PROOT, AddonPack.DIRECTAUDIO)) - if (!pack.await(this, { gen == sessionGen && SessionState.running })) Log.w(TAG, "${pack.name} pack unavailable") + val stillStarting = { gen == sessionGen && SessionState.running } + val prootPack = LinuxRuntime.patchedProot(this) || AddonPack.PROOT.await(this, stillStarting) + val directAudioPack = AddonPack.DIRECTAUDIO.await(this, stillStarting) + if (!stillStarting()) { + Log.i(TAG, "session stopped while add-on packs were downloading") + return + } + if (!directAudioPack) { + Log.w(TAG, "directaudio pack unavailable; game audio drivers will not be staged") + mainHandler.post { + Toast.makeText(this, R.string.session_directaudio_missing, Toast.LENGTH_LONG).show() + } + } + if (!LinuxRuntime.patchedProot(this)) { + if (SessionPrefs.allowStockProot(this)) { + Log.w(TAG, "proot: patched proot missing; droiddeck-stock-proot allows the rootfs copy") + } else { + val message = getString(R.string.session_proot_missing) + Log.e(TAG, "$message (pack ready=$prootPack)") + SessionEvents.fail("PROOT_MISSING", message, -1) + stopSession(-1) + return + } + } + val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) } + .onFailure { Log.w(TAG, "agent environment skipped", it) } + .getOrDefault(emptyList()) SessionFiles.stage(this, root, startsSession = true) // Earlier sessions' reports still read the Steam logs and VAC marker this session replaces. SessionArtifacts.awaitCollections() @@ -437,6 +469,10 @@ class SessionService : Service() { val sessionDir = openSessionFolder() val sessionLog = File(sessionDir, "session.log") + val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})" + Log.i(TAG, prootLine) + runCatching { sessionLog.appendText(prootLine + "\n") } + .onFailure { Log.w(TAG, "could not write the proot line to ${sessionLog.path}", it) } Log.i(TAG, GpuClockPin.start(this)) Log.i(TAG, GameThreadHints.start(this)) @@ -444,16 +480,19 @@ class SessionService : Service() { val size = SessionState.outputSize val guest = ArrayList<String>() val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP + runCatching { ComponentsManager.republish(this) } + .onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") } + .onFailure { Log.w(TAG, "component selections", it) } if (steamHere) { runCatching { ComponentsManager.ensureForcedPackages(this) } .onSuccess { if (it != null) Log.i(TAG, it) } .onFailure { Log.w(TAG, "forced components", it) } } - addClientEnvironment(guest, steamHere) + addClientEnvironment(guest, steamHere, agentEnvironment) if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId) val fastPathAt = guest.size - val pulse = startAudio(guest, sessionDir) + val pulse = startAudio(guest, sessionDir, directAudioPack) if (steamHere) { val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock")) encoder.attach(this) @@ -463,13 +502,21 @@ class SessionService : Service() { guest.add("BL_WIDTH=" + size.first) guest.add("BL_HEIGHT=" + size.second) - if (SessionState.followScreen) guest.add("BL_FOLLOW_OUTPUT=1") + if (SessionState.followScreen || size.first < size.second || + SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) + guest.add("BL_FOLLOW_OUTPUT=1") if (SessionState.hdr) { guest.add("BL_HDR=1") guest.add("DXVK_HDR=1") Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1") } - guest.add("BL_FPS=" + SessionState.fpsLimit) + // gamescope's WSI layer and winex11 reuse their per-present window checks for this long. + guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100") + guest.add("WINE_OFFSCREEN_CHECK_MS=100") + // gamescope turns buffers around slower than an uncapped game draws; more images keep it drawing. + // The WSI layer goes back to its default count while Steam's Frame Limit holds the game. + guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8") + guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1") guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz)) guest.add("BL_LOG=" + sessionLog.path) guest.add("BL_DEBUG_DIR=" + sessionDir.path) @@ -559,6 +606,9 @@ class SessionService : Service() { Log.i(TAG, "proot: seccomp acceleration off by request") } fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> hostEnv[k] = v } } + for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) { + guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { hostEnv[key] = it } + } val prootLibs = LinuxRuntime.prootLibraryPath(this) if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs @@ -580,6 +630,10 @@ class SessionService : Service() { networkLink.attach(this) networkLink.publish() components.add(networkLink) + val deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent(this, root) { activityVisible && screenOn } + deviceControls.attach(this) + deviceControls.publish() + components.add(deviceControls) if (gen != sessionGen || !SessionState.running) { Log.i(TAG, "session stopped while it was starting; not launching it") if (gen == sessionGen) components.clear() @@ -601,7 +655,7 @@ class SessionService : Service() { val program = programStatus(sessionRoot) Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "") stopSession(program ?: status ?: -1) - }, null) + }, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() }) Log.i(TAG, "session pid $pid, log ${sessionLog.path}") if (gen != sessionGen || !SessionState.running) { Log.i(TAG, "session stopped while its guest was starting; taking it down") @@ -670,10 +724,11 @@ class SessionService : Service() { DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode) NetworkReport.write(this, File(sessionDir, "network.txt")) SessionLogCapture.start(File(sessionDir, "app.log")) + MemoryLog.start() return sessionDir } - private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean) { + private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean, agentEnvironment: List<String>) { guest.add("/usr/bin/env") guest.add("-i") guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this)) @@ -726,8 +781,8 @@ class SessionService : Service() { SessionArtifacts.recordClient(it, arch) SessionArtifacts.markSteamLogs(it, File(SessionPrefs.steamRoot(this, arch), "logs")) } - if (arch == "x86_64") FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) } } + FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) } if (SessionState.mode == MODE_STEAM) { guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0")) } @@ -737,9 +792,14 @@ class SessionService : Service() { guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0")) guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0")) if (SessionPrefs.cursorComposite(this)) guest.add("BL_CURSOR_COMPOSITE=1") - if (com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1") + if (com.droiddeck.launcher.core.ZramSupport.supported()) { + guest.add("BL_ZRAM=1") + if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_RAM_CAP_MB=$it") } + if (!SessionPrefs.zramClient(this)) guest.add("BL_ZRAM_CLIENT=0") + } + SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_VRAM_MB=$it") } guest.add("BANNER_AUDIO_DIRECT_DECAY=0") - val extra = extraEnv() + com.droiddeck.launcher.agent.AgentEnv.beginSession(this) + val extra = extraEnv() + agentEnvironment if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else "")) extra.forEach { guest.add(it) } com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") } @@ -752,10 +812,11 @@ class SessionService : Service() { } private fun noSteamGame(): Boolean = - SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC) + SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET) - private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent { - val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) && + private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent { + val wantsDirectAudio = directAudioPack && + (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) && SessionPrefs.directAudio(this) val wantsMic = SessionPrefs.micEnabled(this) && checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED @@ -824,7 +885,7 @@ class SessionService : Service() { SessionState.deckPad = deckBinds.isNotEmpty() if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller") logControllersAtStart() - com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatencyController(this), SessionPrefs.lowLatencyTouch(this)) + com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatency(this)) if (uinput) { guest.add("FAKE_EVDEV_UINPUT=1") if (SessionState.deckPad) { @@ -1052,6 +1113,7 @@ class SessionService : Service() { if (!stillSameProcess()) return val tree = descendants(prootPid) if (!stillSameProcess()) return + saveWineRegistries(tree) android.os.Process.sendSignal(prootPid, 15) if (!waitForExit(prootPid, GRACE_MS)) { if (!stillSameProcess()) return @@ -1068,6 +1130,31 @@ class SessionService : Service() { if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind") } + private fun clearCachedApps() { + val app = applicationContext + Thread({ + val before = MemoryReadout.availableMb() + val result = runCatching { com.droiddeck.launcher.core.WirelessAdbFix.clearCachedApps(app) } + val after = MemoryReadout.availableMb() + result.onSuccess { Log.i(TAG, "cached apps closed: available memory $before -> $after MB") } + .onFailure { Log.w(TAG, "cached apps not closed: ${it.message}") } + }, "clear-cached-apps").start() + } + + private fun saveWineRegistries(tree: List<Pair<Int, Long>>) { + val servers = tree.filter { (pid, started) -> + readStat(pid)?.second == started && WineProcesses.isWineserver( + runCatching { File("/proc/$pid/cmdline").readBytes() }.getOrNull(), + runCatching { File("/proc/$pid/comm").readText() }.getOrNull(), + ) + } + if (servers.isEmpty()) return + servers.forEach { (pid, _) -> android.os.Process.sendSignal(pid, 15) } + val deadline = System.currentTimeMillis() + WINE_SAVE_MS + val saved = servers.count { (pid, _) -> waitForExit(pid, (deadline - System.currentTimeMillis()).coerceAtLeast(0)) } + Log.i(TAG, "wineserver registry save: $saved of ${servers.size} exited after SIGTERM") + } + private fun descendants(root: Int): List<Pair<Int, Long>> { val started = HashMap<Int, Long>() val children = HashMap<Int, MutableList<Int>>() @@ -1347,6 +1434,11 @@ class SessionService : Service() { } return } + if (path == com.droiddeck.launcher.runtime.BattleNet.FEX_REQUEST) { + File(dir, path).delete() + com.droiddeck.launcher.runtime.BattleNet.answerFexRequest(this@SessionService, dir) + return + } if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) { val request = File(dir, path) val text = runCatching { request.readText() }.getOrNull() ?: return @@ -1466,6 +1558,9 @@ class SessionService : Service() { SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && prepared && !downloadsBlockingSuspend else -> false } + // A frozen game never sends the stop for a held rumble, so the keepalive would run on. + val quietRumble = !screenOn || shouldSuspend || SessionState.suspended + components.forEach { (it as? RumbleComponent)?.quiet(quietRumble) } if (freezePending && !shouldSuspend && !freezeCancelled) { freezeCancelled = true controller.cancelFreeze() @@ -1630,6 +1725,8 @@ class SessionService : Service() { runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) } .onFailure { Log.w(TAG, "clearing the agent's session environment", it) } releaseLocks() + MemoryLog.stop() + com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext) if (status == 0) { SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status)) } else { @@ -1683,7 +1780,8 @@ class SessionService : Service() { updateDownloadMonitoring() val stoppedGen = sessionGen val stoppedSession = SessionState.sessionId - val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC + val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC || + SessionState.program == NoSteamLaunch.BATTLENET SessionState.stopRequested = false GpuClockPin.stop(this) GameThreadHints.stop() @@ -1743,6 +1841,9 @@ class SessionService : Service() { private fun importLauncherGames() { runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.importClientGames(this) } .onFailure { Log.w(TAG, "client library scan failed: ${it.javaClass.simpleName}") } + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(this) } + .onFailure { Log.w(TAG, "Battle.net sign-in check failed: ${it.javaClass.simpleName}") } + com.droiddeck.launcher.stores.StoresState.notifyLibraryChanged(this) } override fun onTaskRemoved(rootIntent: Intent?) { @@ -1990,6 +2091,7 @@ class SessionService : Service() { private val STRAGGLERS = listOf("droiddeck-session", "gamescope", "Xwayland", "steamrtarm64", "steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so") private const val GRACE_MS = 1200L + private const val WINE_SAVE_MS = 3000L private const val STEAM_PICKUP_MS = 1500L private const val STEAM_EXIT_MS = 10_000L private const val GAME_LAUNCH_RETRY_MS = 250L @@ -2021,6 +2123,7 @@ class SessionService : Service() { fun start( context: Context, mode: String = MODE_STEAM, program: String? = null, steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null, + gameId: String? = null, displayId: Int = Display.DEFAULT_DISPLAY, ) { SessionState.activityDisplayId = displayId @@ -2031,6 +2134,7 @@ class SessionService : Service() { if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs) if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi) if (steamUrl != null) intent.putExtra(EXTRA_STEAM_URL, steamUrl) + if (gameId != null) intent.putExtra(EXTRA_GAME_ID, gameId) if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent) } 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 e5af742994..59adab0c66 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -62,6 +62,8 @@ object SessionState { @Volatile var programArgs: List<String> = emptyList() @Volatile + var gameId: String? = null + @Volatile var steamUi: String? = null @Volatile var steamUrl: String? = null @@ -104,9 +106,6 @@ object SessionState { @Volatile var upscaleRatio: Float = 0f - @Volatile - var fpsLimit: Int = 0 - @Volatile var firstFrameSeen = false diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index 27bc081b0d..27c97b2ba0 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -14,11 +14,11 @@ object SettingsReset { "orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt", "gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", - "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController", + "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", "stretch16x9", "picturePosition", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", - "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", + "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", "noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite", "guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics", @@ -29,7 +29,7 @@ object SettingsReset { ) internal val SESSION_PREFIXES = listOf( - "resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "suspendPolicy.", + "resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "performanceMode.", "suspendPolicy.", ) private val STEAM_TOUCH_KEYS = listOf("feedback", "autoFade", "gyro", "shake") diff --git a/app/src/main/java/com/droiddeck/launcher/session/WineProcesses.kt b/app/src/main/java/com/droiddeck/launcher/session/WineProcesses.kt new file mode 100644 index 0000000000..d80099bdd6 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/WineProcesses.kt @@ -0,0 +1,13 @@ +package com.droiddeck.launcher.session + +internal object WineProcesses { + private const val WINESERVER = "wineserver" + + fun isWineserver(cmdline: ByteArray?, comm: String?): Boolean { + val program = cmdline?.let { bytes -> + val end = bytes.indexOf(0.toByte()).let { if (it < 0) bytes.size else it } + String(bytes, 0, end, Charsets.UTF_8).substringAfterLast('/') + } + return program == WINESERVER || comm?.trim() == WINESERVER + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudSavePaths.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudSavePaths.kt index 194448f0c8..9dfc6b6658 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudSavePaths.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudSavePaths.kt @@ -3,8 +3,28 @@ package com.droiddeck.launcher.stores import java.io.File object CloudSavePaths { + const val GOG_DEFAULT_NAMESPACE = "__default" + fun profile(prefix: File): File = File(prefix, "drive_c/users/steamuser") + fun gogGalaxySdkTemplate(clientId: String) = + "%LocalAppData%/GOG.com/Galaxy/Applications/$clientId/Storage/Shared/Files" + + class GogCloudLocation(val name: String, val template: String) + + /** + * cloudStorage.enabled with an empty locations list is Galaxy SDK IStorage, whose objects the + * API names under a location called `__default`. + */ + fun gogSaveFromRemote(enabled: Boolean, locations: List<Pair<String, String>>, clientId: String): GogCloudLocation? { + if (!enabled) return null + val named = locations.filter { it.second.isNotEmpty() } + val pick = named.firstOrNull { it.first.equals("saves", true) } ?: named.firstOrNull() + if (pick != null) return GogCloudLocation(pick.first, pick.second) + if (clientId.isEmpty()) return null + return GogCloudLocation(GOG_DEFAULT_NAMESPACE, gogGalaxySdkTemplate(clientId)) + } + fun gog(template: String, prefix: File, install: File): File? { val norm = template.replace('\\', '/').trim().trimStart('/') val match = Regex("^(<\\?[^?>]+\\?>|%[^%]+%)").find(norm) ?: return null 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 669a13eee0..659ae7005c 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.stores import android.content.Context +import android.content.SharedPreferences import android.util.Log import com.droiddeck.launcher.frontend.AddedGames import com.droiddeck.launcher.frontend.Library @@ -22,6 +23,7 @@ object CloudSaves { private const val TAG = "CloudSaves" private const val BACKUPS = 3 private const val PARALLEL = 6 + private const val CLOUD_LAYOUT = 2 class Result(val result: String, val files: Int, val bytes: Long, val reason: String, val conflicts: Int = 0) { val ok: Boolean get() = result != "failed" @@ -47,20 +49,54 @@ object CloudSaves { private fun markSynced(context: Context, store: Store, id: String) = prefs(context, store).edit().putLong("cloud_sync_$id", System.currentTimeMillis()).apply() + private const val TEMPLATE_NONE = "none" + internal const val TEMPLATE_NONE_TTL_MS = 24 * 60 * 60 * 1000L + + internal fun noneTemplateIsCurrent(storedAtMs: Long, nowMs: Long) = + storedAtMs > 0L && nowMs - storedAtMs < TEMPLATE_NONE_TTL_MS + + private fun rememberNoCloud(p: SharedPreferences, id: String) { + p.edit().putString("cloud_template_$id", TEMPLATE_NONE) + .putLong("cloud_template_at_$id", System.currentTimeMillis()).apply() + } + fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? { val p = prefs(context, store) - if (p.contains("cloud_template_$id")) return p.getString("cloud_template_$id", "") + var retryNone = false + if (p.contains("cloud_template_$id")) { + val cached = p.getString("cloud_template_$id", "") ?: "" + if (cached == TEMPLATE_NONE) { + if (noneTemplateIsCurrent(p.getLong("cloud_template_at_$id", 0L), System.currentTimeMillis())) return "" + retryNone = true + } else if (cached.isNotEmpty()) return cached + } + var gogLocation = "" val fetched = when (store) { - Store.GOG -> gogTemplate(context, id, folder) + Store.GOG -> { + val config = gogConfig(context, id, folder) + if (config == null) { + if (retryNone) { rememberNoCloud(p, id); return "" } + return null + } + gogLocation = config.name + config.location + } Store.EPIC -> { val token = EpicCredentialStore.getValidAccessToken(context) ?: return null val ns = sidecar.extra["namespace"].orEmpty() val item = sidecar.extra["catalogItemId"].orEmpty() if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder") } - Store.AMAZON, Store.ITCH, Store.XBOX -> "" + Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> "" } ?: return null - p.edit().putString("cloud_template_$id", fetched).apply() + p.edit() + .putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE }) + .apply { + if (fetched.isEmpty()) putLong("cloud_template_at_$id", System.currentTimeMillis()) + else remove("cloud_template_at_$id") + if (store == Store.GOG && gogLocation.isNotEmpty()) putString("cloud_location_$id", gogLocation) + } + .apply() Log.i(TAG, "cloud ${store.id} $id template ${if (fetched.isEmpty()) "none" else "found"}") return fetched } @@ -69,8 +105,10 @@ object CloudSaves { GogPrefs.get(context).getString("client_id_$id", null)?.ifEmpty { null } ?: runCatching { JSONObject(File(folder, "goggame-$id.info").readText()).optString("clientId").ifEmpty { null } }.getOrNull() - private fun gogTemplate(context: Context, id: String, folder: File): String? { - val clientId = gogClientId(context, id, folder) ?: return "" + private class GogConfig(val name: String, val location: String) + + private fun gogConfig(context: Context, id: String, folder: File): GogConfig? { + val clientId = gogClientId(context, id, folder) ?: return GogConfig("", "") return try { val c = URL("https://remote-config.gog.com/components/galaxy_client/clients/$clientId?component_version=2.0.45").openConnection() as HttpURLConnection c.connectTimeout = 15_000; c.readTimeout = 15_000 @@ -78,16 +116,34 @@ object CloudSaves { if (c.responseCode !in 200..299) { c.disconnect(); return null } val cloud = JSONObject(c.inputStream.bufferedReader().readText()).optJSONObject("content")?.optJSONObject("Windows")?.optJSONObject("cloudStorage") c.disconnect() - if (cloud?.optBoolean("enabled", false) != true) return "" - val locations = cloud.optJSONArray("locations") ?: return "" - val all = (0 until locations.length()).mapNotNull { locations.optJSONObject(it) } - (all.firstOrNull { it.optString("name").equals("saves", true) } ?: all.firstOrNull())?.optString("location").orEmpty() + val locations = cloud?.optJSONArray("locations") + val picked = CloudSavePaths.gogSaveFromRemote( + enabled = cloud?.optBoolean("enabled", false) == true, + locations = (0 until (locations?.length() ?: 0)).mapNotNull { i -> + locations!!.optJSONObject(i)?.let { it.optString("name") to it.optString("location") } + }, + clientId = clientId, + ) + if (picked == null) GogConfig("", "") else GogConfig(picked.name, picked.template) } catch (e: Exception) { Log.w(TAG, "gog remote-config: ${e.javaClass.simpleName}") null } } + /** + * The selected cloud location's name: GOG prefixes every cloud file with it, and the local folder + * is the location itself. Older builds had no name cached; fetch it once for those. + */ + private fun gogLocationName(context: Context, id: String, folder: File): String? { + val p = GogPrefs.get(context) + p.getString("cloud_location_$id", null)?.ifEmpty { null }?.let { return it } + if (p.getString("cloud_template_$id", null)?.let { it.isEmpty() || it == TEMPLATE_NONE } == true) return null + val config = gogConfig(context, id, folder) ?: return null + if (config.name.isNotEmpty()) p.edit().putString("cloud_location_$id", config.name).apply() + return config.name.ifEmpty { null } + } + private fun saveFolder(context: Context, store: Store, id: String): Pair<File?, String> { val (folder, sidecar) = game(context, store, id) ?: return null to "not-installed" val template = template(context, store, id, folder, sidecar) ?: return null to "store-unreachable" @@ -96,7 +152,7 @@ object CloudSaves { val dir = when (store) { Store.GOG -> CloudSavePaths.gog(template, pfx, folder) Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id) - Store.AMAZON, Store.ITCH, Store.XBOX -> null + Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null } return dir to (if (dir == null) "unresolved" else "ok") } @@ -114,14 +170,14 @@ object CloudSaves { val galaxy = GogAuth.validToken(context) val clientId = gogClientId(context, id, folder) if (userId.isEmpty() || galaxy == null || clientId == null) null - else GogCloud(userId, clientId, gogScopedToken(context, id, clientId) ?: galaxy) + else GogCloud(userId, clientId, gogScopedToken(context, id, clientId) ?: galaxy, gogLocationName(context, id, folder)) } Store.EPIC -> { val token = EpicCredentialStore.getValidAccessToken(context) val account = EpicCredentialStore.load(context)?.accountId.orEmpty() if (token == null || account.isEmpty()) null else EpicCloud(account, id, token) } - Store.AMAZON, Store.ITCH, Store.XBOX -> null + Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null } private fun gogScopedToken(context: Context, id: String, clientId: String): String? { @@ -136,6 +192,83 @@ object CloudSaves { private fun saveBaseline(context: Context, store: Store, id: String, b: Map<String, CloudPlan.Entry>) = prefs(context, store).edit().putString("cloud_baseline_$id", CloudPlan.toJson(b)).apply() + internal class Migration(val baseline: Map<String, CloudPlan.Entry>, val moved: Int, val cleaned: Int, val failed: Int) + + /** + * Moves only files whose `"<location>/<path>"` key proves the old mapping wrote them; anything + * the game itself created under that name is left where it is. Identical duplicates are removed + * only when they prove the same. The name must be one path segment: it comes from remote config. + */ + internal fun migrateNested(dir: File, name: String, base: Map<String, CloudPlan.Entry>): Migration? { + if (name.isEmpty() || name == "." || name == ".." || name.contains('/') || name.contains('\\')) return null + val nested = File(dir, name) + if (!nested.isDirectory) return null + val root = runCatching { dir.canonicalFile }.getOrNull() ?: return null + if (runCatching { nested.canonicalFile }.getOrNull()?.parentFile != root) return null + val prefix = "$name/" + val next = HashMap(base) + var moved = 0 + var cleaned = 0 + var failed = 0 + for (src in nested.walkTopDown().filter { it.isFile }.toList()) { + if (runCatching { java.nio.file.Files.isSymbolicLink(src.toPath()) }.getOrDefault(true)) continue + val srcCanon = runCatching { src.canonicalFile }.getOrNull() ?: continue + if (!srcCanon.path.startsWith(root.path + File.separator)) continue + val rel = src.relativeTo(nested).path.replace(File.separatorChar, '/') + val key = prefix + rel + val entry = base[key] ?: continue + val dest = File(dir, rel) + val destCanon = runCatching { dest.canonicalFile }.getOrNull() ?: continue + if (!destCanon.path.startsWith(root.path + File.separator)) continue + if (dest.isFile && runCatching { md5(dest) == md5(src) }.getOrDefault(false)) { + if (!src.delete()) { failed++; continue } + cleaned++ + next[rel] = entry + next.remove(key) + continue + } + if (dest.exists()) continue + val copied = runCatching { + dest.parentFile?.mkdirs() + val tmp = File.createTempFile(dest.name + ".", ".migrate", dest.parentFile) + try { + src.copyTo(tmp, overwrite = true) + if (md5(tmp) != md5(src)) false + else { + java.nio.file.Files.move(tmp.toPath(), dest.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE) + true + } + } finally { + if (tmp.exists()) tmp.delete() + } + }.getOrDefault(false) + if (!copied) { failed++; continue } + if (!src.delete()) { failed++; continue } + moved++ + next[rel] = entry + next.remove(key) + } + if (nested.walkTopDown().none { it.isFile }) nested.deleteRecursively() + return Migration(next, moved, cleaned, failed) + } + + private fun migrateGogNested(context: Context, id: String, folder: File, dir: File) { + val p = GogPrefs.get(context) + // Run once per game: after this the flat layout is authoritative, even if the game itself + // keeps a folder named like the cloud location. + if (p.getInt("cloud_layout_$id", 0) >= CLOUD_LAYOUT) return + val name = gogLocationName(context, id, folder) ?: return + val base = baseline(context, Store.GOG, id).orEmpty() + val result = migrateNested(dir, name, base) + if (result != null) { + if (result.baseline != base) saveBaseline(context, Store.GOG, id, result.baseline) + if (result.moved + result.cleaned > 0) { + StoresState.logLine("cloud gog $id migrate result=ok moved=${result.moved} cleaned=${result.cleaned} from=$name") + } + } + if (result == null || result.failed == 0) p.edit().putInt("cloud_layout_$id", CLOUD_LAYOUT).apply() + } + fun conflicts(context: Context, store: Store, id: String): List<String> = prefs(context, store).getString("cloud_conflicts_$id", "").orEmpty().split('\n').filter { it.isNotEmpty() } @@ -180,6 +313,7 @@ object CloudSaves { !g.second.cloud -> Result("skipped", 0, 0, "off") else -> { val (dir, reason) = saveFolder(context, store, id) + if (dir != null && store == Store.GOG) migrateGogNested(context, id, g.first, dir) val cloud = if (dir != null) transport(context, store, id, g.first) else null when { dir == null -> Result("skipped", 0, 0, reason) @@ -189,7 +323,7 @@ object CloudSaves { } } } catch (e: NoCloudSaves) { - prefs(context, store).edit().putString("cloud_template_$id", "").apply() + rememberNoCloud(prefs(context, store), id) Result("skipped", 0, 0, "no-cloud-saves") } catch (e: Exception) { Result("failed", 0, 0, e.javaClass.simpleName) 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 33c34196ff..9c32bd4c1a 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt @@ -7,6 +7,8 @@ import java.net.URLEncoder import java.text.SimpleDateFormat import java.util.Locale import java.util.TimeZone +import java.util.zip.CRC32 +import java.util.zip.Deflater import org.json.JSONArray import org.json.JSONObject @@ -38,25 +40,101 @@ private fun httpDate(s: String?): Long = try { SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }.parse(s!!.trim())?.time ?: -1L } catch (e: Exception) { -1L } +internal fun isGzip(data: ByteArray) = + data.size >= 10 && data[0] == 0x1f.toByte() && data[1] == 0x8b.toByte() && data[2] == 0x08.toByte() + +internal fun gunzip(data: ByteArray): ByteArray? = try { + java.util.zip.GZIPInputStream(data.inputStream()).use { it.readBytes() } +} catch (e: Exception) { null } + +/** Same gzip GOG uses on PUT: deflate level 6, mtime 0, OS Unix. */ +internal fun gzipGogPut(data: ByteArray): ByteArray { + val deflater = Deflater(6, true) + val raw = ByteArrayOutputStream() + try { + deflater.setInput(data) + deflater.finish() + val buf = ByteArray(512) + while (!deflater.finished()) { + val n = deflater.deflate(buf) + if (n > 0) raw.write(buf, 0, n) + } + } finally { + deflater.end() + } + val crc = CRC32().also { it.update(data) } + return ByteArrayOutputStream(18 + raw.size()).apply { + write(byteArrayOf(0x1f, 0x8b.toByte(), 8, 0, 0, 0, 0, 0, 0, 3)) + write(raw.toByteArray()) + writeIntLe(crc.value.toInt()) + writeIntLe(data.size) + }.toByteArray() +} + +private fun ByteArrayOutputStream.writeIntLe(v: Int) { + write(v and 0xff) + write(v ushr 8 and 0xff) + write(v ushr 16 and 0xff) + write(v ushr 24 and 0xff) +} + +internal fun gogDecodeCloudBody(data: ByteArray, contentEncoding: String?): ByteArray { + val encodings = contentEncoding.orEmpty().split(',').map { it.trim().lowercase() } + if ("gzip" in encodings || "x-gzip" in encodings) { + if (!isGzip(data)) return data + return gunzip(data) ?: throw java.io.IOException("Invalid GOG cloud gzip body") + } + if (!isGzip(data)) return data + val inflated = gunzip(data) ?: return data + return if (gzipGogPut(inflated).contentEquals(data)) inflated else data +} + internal fun isoDate(s: String?): Long { - if (s == null || s.length < 19) return -1L - return try { - java.util.Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { - clear() - set(s.substring(0, 4).toInt(), s.substring(5, 7).toInt() - 1, s.substring(8, 10).toInt(), - s.substring(11, 13).toInt(), s.substring(14, 16).toInt(), s.substring(17, 19).toInt()) - }.timeInMillis - } catch (e: Exception) { -1L } + if (s == null) return -1L + return runCatching { java.time.OffsetDateTime.parse(s).toInstant().toEpochMilli() } + .recoverCatching { java.time.LocalDateTime.parse(s).toInstant(java.time.ZoneOffset.UTC).toEpochMilli() } + .getOrDefault(-1L) } class NoCloudSaves : Exception("no cloud saves") -class GogCloud(private val userId: String, private val clientId: String, private val token: String) : CloudTransport { +/** GOG cloud names are `<location name>/<path under that location>`; the name is not part of the folder. */ +internal fun splitGogName(name: String): Pair<String?, String> { + val slash = name.indexOf('/') + return if (slash <= 0 || slash == name.length - 1) null to name + else name.substring(0, slash) to name.substring(slash + 1) +} + +/** Maps cloud names to paths under the selected location's folder; the chosen location name is returned. */ +internal fun gogRelativeNames(files: List<CloudFile>, location: String?): Pair<String?, List<CloudFile>> { + val locations = files.mapNotNull { splitGogName(it.name).first }.distinct() + // Only infer a location when every name is prefixed; a mixed listing keeps its old shape. + val allPrefixed = files.isNotEmpty() && files.all { splitGogName(it.name).first != null } + val chosen = when { + location != null && (location in locations || allPrefixed) -> location + location == null && allPrefixed -> locations.singleOrNull() + else -> null + } ?: return null to files + return chosen to files.mapNotNull { file -> + val (dir, rel) = splitGogName(file.name) + if (dir == chosen) CloudFile(rel, file.modifiedMs, file.md5, file.readLink) else null + } +} + +class GogCloud( + private val userId: String, + private val clientId: String, + private val token: String, + private val location: String? = null, +) : CloudTransport { private val base = "https://cloudstorage.gog.com/v1/$userId/$clientId" private val ua = "GOG Galaxy" + private var prefix: String? = location?.let { "$it/" } private fun key(name: String) = URLEncoder.encode(name, "UTF-8").replace("+", "%20") + private fun cloudKey(name: String) = key((prefix ?: "") + name) + override fun list(): List<CloudFile> { val c = open(base, "GET", token, ua) val code = c.responseCode @@ -70,20 +148,38 @@ class GogCloud(private val userId: String, private val clientId: String, private val text = c.body().decodeToString().trim() c.disconnect() if (text.isEmpty() || text == "[]") return emptyList() - if (text.startsWith("[")) { + val raw = if (text.startsWith("[")) { val a = JSONArray(text) - return (0 until a.length()).mapNotNull { a.optJSONObject(it) }.mapNotNull { o -> + (0 until a.length()).mapNotNull { a.optJSONObject(it) }.mapNotNull { o -> val n = o.optString("name").ifEmpty { return@mapNotNull null } val lm = o.optLong("last_modified", 0L) - CloudFile(n, if (lm > 1_000_000_000_000L) lm else if (lm > 0) lm * 1000 else -1L) + val iso = isoDate(o.optString("last_modified").takeIf { it.isNotEmpty() }) + CloudFile(n, when { + lm > 1_000_000_000_000L -> lm + lm > 0 -> lm * 1000 + iso > 0 -> iso + else -> -1L + }) } + } else { + text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) } } - return text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) } + return relative(raw) + } + + /** + * The API names every file `<location>/<path>`. The location's folder is the sync root, so the + * first segment is dropped. Older builds kept it, writing saves one folder too deep. + */ + private fun relative(raw: List<CloudFile>): List<CloudFile> { + val (chosen, files) = gogRelativeNames(raw, location) + prefix = chosen?.let { "$it/" } + return files } override fun details(file: CloudFile) { if (file.modifiedMs > 0 && file.md5 != null) return - val c = open("$base/${key(file.name)}", "HEAD", token, ua) + val c = open("$base/${cloudKey(file.name)}", "HEAD", token, ua) if (c.responseCode in 200..299) { httpDate(c.getHeaderField("Last-Modified")).takeIf { it > 0 }?.let { file.modifiedMs = it } c.getHeaderField("ETag")?.replace("\"", "")?.trim()?.ifEmpty { null }?.let { file.md5 = it } @@ -92,14 +188,18 @@ class GogCloud(private val userId: String, private val clientId: String, private } override fun get(file: CloudFile): Pair<ByteArray, Long> { - val c = open("$base/${key(file.name)}", "GET", token, ua) + val c = open("$base/${cloudKey(file.name)}", "GET", token, ua) + c.setRequestProperty("Accept-Encoding", "identity") if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("GOG cloud get HTTP $code") } val modified = httpDate(c.getHeaderField("Last-Modified")) - return c.body().also { c.disconnect() } to modified + val encoding = c.getHeaderField("Content-Encoding") + val data = c.body() + c.disconnect() + return gogDecodeCloudBody(data, encoding) to modified } override fun put(files: Map<String, ByteArray>): Map<String, Long> = files.mapValues { (name, data) -> - val c = open("$base/${key(name)}", "PUT", token, ua) + val c = open("$base/${cloudKey(name)}", "PUT", token, ua) c.doOutput = true c.setRequestProperty("Content-Type", "application/octet-stream") c.setFixedLengthStreamingMode(data.size) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt index adb507e996..79ca0f8492 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt @@ -12,7 +12,7 @@ internal object LoginFlows { Store.GOG -> GogFlow(state, browserUserAgent) Store.EPIC -> epicFlow() Store.AMAZON -> amazonFlow() - Store.ITCH, Store.XBOX -> null + Store.ITCH, Store.XBOX, Store.BATTLENET -> null } @Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/SteamLiveShortcuts.kt b/app/src/main/java/com/droiddeck/launcher/stores/SteamLiveShortcuts.kt index 345f4da32b..0cc03b7028 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/SteamLiveShortcuts.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/SteamLiveShortcuts.kt @@ -23,14 +23,14 @@ object SteamLiveShortcuts { val wanted = games.filter(include) if (wanted.isEmpty() || !clientRunning()) return val list = JSONArray() - for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL)) + for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL).put("launch", g.launchOptions)) val js = """ (async () => { const want = ${list}; let added = 0; for (const w of want) { if (await ${KNOWN}(w.appid, w.name, w.exe)) continue; - if (await ${ADD}(w.name, w.exe, w.dir, true)) added++; + if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++; } return added; })() @@ -46,7 +46,7 @@ object SteamLiveShortcuts { (async () => { const known = await ${KNOWN}(${appId?.and(0xFFFFFFFFL) ?: 0}, ${JSONObject.quote(name)}, ${JSONObject.quote(exe)}); if (known) return known; - return await ${ADD}(${JSONObject.quote(name)}, ${JSONObject.quote(exe)}, ${JSONObject.quote(dir)}, $compat); + return await ${ADD}(${JSONObject.quote(name)}, ${JSONObject.quote(exe)}, ${JSONObject.quote(dir)}, $compat, ${JSONObject.quote(compatTool(context))}); })() """.trimIndent() val id = evaluate(context, js)?.toLongOrNull()?.and(0xFFFFFFFFL)?.takeIf { it != 0L } ?: return null @@ -161,12 +161,15 @@ object SteamLiveShortcuts { return 0; })""" - private val ADD = """(async (name, exe, dir, compat) => { - const id = await SteamClient.Apps.AddShortcut(name, exe, dir, ""); + private fun compatTool(context: Context): String = + com.droiddeck.launcher.session.ProtonDefault.state(context).default ?: COMPAT_TOOL + + private val ADD = """(async (name, exe, dir, compat, tool, launch) => { + const id = await SteamClient.Apps.AddShortcut(name, exe, dir, launch || ""); if (!id) return 0; try { SteamClient.Apps.SetShortcutName(id, name); } catch (e) {} try { SteamClient.Apps.AddUserTagToApps([id], ${JSONObject.quote(TAG_NAME)}); } catch (e) {} - if (compat) { try { SteamClient.Apps.SpecifyCompatTool(id, ${JSONObject.quote(COMPAT_TOOL)}); } catch (e) {} } + if (compat) { try { SteamClient.Apps.SpecifyCompatTool(id, tool); } catch (e) {} } for (let i = 0; i < 40; i++) { try { if (globalThis.appStore.GetAppOverviewByAppID(id)) break; } catch (e) {} await new Promise(r => setTimeout(r, 250)); diff --git a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt index b5e0d1fbf6..54476b6e19 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt @@ -5,7 +5,8 @@ enum class Store(val id: String, val label: String, val shortLabel: String) { EPIC("epic", "Epic Games", "Epic"), AMAZON("amazon", "Amazon Games", "Amazon"), XBOX("xbox", "Xbox", "Xbox"), - ITCH("itch", "itch.io", "itch"); + ITCH("itch", "itch.io", "itch"), + BATTLENET("battlenet", "Battle.net", "Battle.net"); companion object { fun byId(id: String?): Store? = entries.firstOrNull { it.id == id } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt index a740eb088e..f69380f7c4 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt @@ -90,6 +90,7 @@ object StoreAccounts { fun signedInAs(context: Context, store: Store): String? { val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null if (store == Store.XBOX) return json.optString("username").takeIf { it.isNotBlank() } + if (store == Store.BATTLENET) return json.optString("display_name").takeIf { it.isNotBlank() } if (json.optString("access_token", "").isEmpty()) return null return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt index 91a0f96f5b..c4faac54e5 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt @@ -5,6 +5,7 @@ import android.os.StatFs import android.os.storage.StorageManager import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.GameStorage +import com.droiddeck.launcher.session.SessionPrefs import java.io.File import java.util.zip.CRC32 @@ -76,32 +77,93 @@ object StoreInstallRoot { fun targets(context: Context): List<Target> { val internal = Target(internalRoot(context), context.getString(com.droiddeck.launcher.R.string.games_internal), removable = false) + val custom = customTarget(context) val cards = GameStorage.options(context).map { Target(File(it.path, ON_VOLUME), it.name, removable = true) } val library = GameStorage.effective(context)?.let { lib -> val root = File(lib.path, ON_VOLUME) if (cards.any { it.root.absolutePath == root.absolutePath }) return@let null - val volume = runCatching { context.getSystemService(StorageManager::class.java)?.getStorageVolume(File(lib.path)) }.getOrNull() - val name = File(lib.path).name.ifBlank { lib.label } - val where = volume?.takeUnless { it.isPrimary }?.getDescription(context) - val label = if (where.isNullOrBlank()) name else context.getString(com.droiddeck.launcher.R.string.gstore_folder_on_volume, name, where) - Target(root, label, removable = true, folder = true) + Target(root, folderLabel(context, File(lib.path)), removable = true, folder = true) } - return listOf(internal) + cards + listOfNotNull(library) + return (listOf(internal) + listOfNotNull(custom) + cards + listOfNotNull(library)) + .distinctBy { it.root.absolutePath } + } + + fun defaultStorageFolder(context: Context): File? = + SessionPrefs.defaultStorageFolder(context).takeIf { it.isNotBlank() }?.let(::File) + + fun customTarget(context: Context): Target? { + val folder = defaultStorageFolder(context) ?: return null + // Writes are probed when the folder is chosen; File.canWrite() is unreliable on FUSE volumes. + if (!folder.isDirectory) return null + val label = SessionPrefs.defaultStorageFolderLabel(context).ifBlank { folderLabel(context, folder) } + return Target(File(folder, ON_VOLUME), label, removable = true, folder = true) + } + + fun detectedExternalTarget(context: Context): Target? { + val custom = defaultStorageFolder(context)?.let { File(it, ON_VOLUME) }?.absolutePath + return externalTarget(targets(context).filter { it.root.absolutePath != custom }, internalRoot(context)) } fun installRoot(context: Context): File = internalRoot(context) + fun externalTarget(context: Context): Target? = + if (SessionPrefs.defaultStorageFolder(context).isNotBlank()) customTarget(context) + else detectedExternalTarget(context) + + internal fun externalTarget(targets: List<Target>, internalRoot: File): Target? = + targets.firstOrNull { it.folder && it.root.absolutePath != internalRoot.absolutePath } + ?: targets.firstOrNull { it.removable && it.root.absolutePath != internalRoot.absolutePath } + + fun defaultTarget(context: Context): Target? = when (SessionPrefs.defaultStorage(context)) { + SessionPrefs.DEFAULT_STORAGE_INTERNAL -> Target(internalRoot(context), context.getString(com.droiddeck.launcher.R.string.games_internal), removable = false) + SessionPrefs.DEFAULT_STORAGE_EXTERNAL -> externalTarget(context) + else -> null + } + + fun libraryRoot(context: Context): File? = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) } + fun roots(context: Context): List<File> { val cards = GameStorage.options(context).map { File(it.path, ON_VOLUME) } + val custom = defaultStorageFolder(context)?.takeIf { it.isDirectory }?.let { File(it, ON_VOLUME) } val library = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) } - return (listOf(internalRoot(context)) + cards + listOfNotNull(library)).distinctBy { it.absolutePath } + return (listOf(internalRoot(context)) + cards + listOfNotNull(custom) + listOfNotNull(library)) + .distinctBy { it.absolutePath } } fun externalRoots(context: Context): List<Pair<File, String>> { val library = GameStorage.effective(context)?.path + val used = mutableSetOf<String>() return roots(context) .filter { !isInternal(context, it) && (library == null || !it.absolutePath.startsWith("$library/")) } - .map { it to guestFor(context, it) } + .map { root -> + val base = guestFor(context, root) + val guest = if (used.add(base)) base else { + val suffix = "%08x".format(CRC32().apply { update(root.absolutePath.toByteArray()) }.value) + "$base-$suffix".also { used.add(it) } + } + root to guest + } + } + + fun folderLabel(context: Context, folder: File): String { + val name = folder.name.ifBlank { context.getString(com.droiddeck.launcher.R.string.gstore_folder) } + val volume = runCatching { + context.getSystemService(StorageManager::class.java)?.getStorageVolume(folder)?.getDescription(context) + }.getOrNull() + return if (volume.isNullOrBlank() || volume.equals("android", true) || volume.equals(name, true)) name + else context.getString(com.droiddeck.launcher.R.string.gstore_folder_on_volume, name, volume) + } + + fun prepareDefaultFolder(context: Context, folder: File): String? { + if (!folder.isDirectory) return context.getString(com.droiddeck.launcher.R.string.gstore_cannot_create, folder.path) + val root = File(folder, ON_VOLUME) + if (!root.isDirectory && !root.mkdirs()) return context.getString(com.droiddeck.launcher.R.string.gstore_cannot_create, folder.path) + return try { + File.createTempFile(".droiddeck-write-probe", null, root).delete() + null + } catch (e: Exception) { + context.getString(com.droiddeck.launcher.R.string.gstore_cannot_write_detail, root.path, e.message) + } } /** Xodus has its own PRoot mount table and cannot see the selected Steam library's SD bind. */ @@ -187,7 +249,7 @@ object StoreInstallRoot { fun isFinished(folder: File): Boolean = StoreGameSidecar.read(folder)?.isInstalled == true fun unfinished(context: Context): List<Unfinished> = roots(context).flatMap { root -> - Store.entries.flatMap { store -> + Store.entries.filter { it != Store.BATTLENET }.flatMap { store -> storeDir(root, store).listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { folder -> val sidecar = StoreGameSidecar.read(folder) when { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstalls.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstalls.kt index 65fdf6e921..9b73f8cc87 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstalls.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstalls.kt @@ -70,7 +70,7 @@ object StoreInstalls { fun uninstall(context: Context, game: InstalledStoreGame, progress: (Float) -> Unit = {}, removed: () -> Unit = {}) { val app = context.applicationContext val appId = SessionPrefs.addedGameStoredAppId(app, game.folder.path) - val files = game.folder.walkBottomUp().toList() + val files = game.folder.walkBottomUp().onEnter { !Files.isSymbolicLink(it.toPath()) }.toList() val step = (files.size / 100).coerceAtLeast(1) files.forEachIndexed { i, f -> f.delete() @@ -98,6 +98,10 @@ object StoreInstalls { } fun deleteTree(dir: File) { + if (Files.isSymbolicLink(dir.toPath())) { + dir.delete() + return + } dir.listFiles()?.forEach { if (it.isDirectory) deleteTree(it) else it.delete() } dir.delete() } 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 9a4f97c877..37169cf96f 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt @@ -88,6 +88,7 @@ class StoreLoginActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this) store = Store.byId(intent.getStringExtra(EXTRA_STORE)) clientUrl = intent.getStringExtra(EXTRA_CLIENT_URL)?.takeIf { store == Store.EPIC } oauthState = savedInstanceState?.getString(KEY_STATE) ?: generateState() diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt index 454e3d23bc..290676c9ed 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt @@ -55,7 +55,7 @@ object StoreSizes { Store.EPIC -> EpicPrefs.get(app).edit().putLong("size_${item.id}", it).apply() Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply() Store.ITCH -> {} - Store.GOG, Store.XBOX -> {} + Store.GOG, Store.XBOX, Store.BATTLENET -> {} } } }, pool).exceptionally { error -> @@ -111,7 +111,7 @@ object StoreSizes { val bytes = AmazonApiClient.getBytes(AmazonApiClient.appendPath(spec.downloadUrl, "manifest.proto"), token) ?: return 0L AmazonManifest.parse(bytes).totalInstallSize } - Store.GOG, Store.XBOX -> 0L + Store.GOG, Store.XBOX, Store.BATTLENET -> 0L Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index 1fcbcd4815..3edac79a4b 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -9,6 +9,7 @@ import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.stores.download.DownloadEntry object StoresState { @@ -77,10 +78,11 @@ object StoresState { val app = context.applicationContext com.droiddeck.launcher.stores.download.SavedQueue.restore(app) background("stores-refresh") { + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) } val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } } val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder -> StoreGameSidecar.read(folder)?.takeIf { it.isInstalled }?.let { InstalledStoreGame(it, folder) } - } + } + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList()) val partial = StoreInstallRoot.unfinished(app) val version = if (StoresNative.available) StoresNative.version ?: "" else "" main.post { @@ -128,7 +130,7 @@ object StoresState { fun detailItem(store: Store, id: String): CatalogItem? = detailCatalogItem( store, id, library[store].orEmpty(), - found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items else emptyList(), + found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items + com.droiddeck.launcher.stores.itch.ItchCollections.items() else emptyList(), shelves[store], ) @@ -189,6 +191,7 @@ object StoresState { backend?.signOut(app) if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) } else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store) + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchCollections.clear() main.post { if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store) @@ -212,18 +215,33 @@ object StoresState { } var pendingInstall by mutableStateOf<CatalogItem?>(null) + var itchPicking by mutableStateOf<CatalogItem?>(null) fun requestInstall(context: Context, item: CatalogItem) { askForNotifications(context) + if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return } if (isUnfinished(item)) { install(context, item); return } val targets = StoreInstallRoot.targets(context) - if (targets.size > 1 || StoreLanguage.selectable(item.store)) pendingInstall = item - else install(context, item, targets.first().root) + val preferred = StoreInstallRoot.defaultTarget(context) + val wantedExternal = SessionPrefs.defaultStorage(context) == SessionPrefs.DEFAULT_STORAGE_EXTERNAL + if (preferred != null) SessionPrefs.setStoresInstallTarget(context, preferred.root.absolutePath) + when { + preferred != null && !StoreLanguage.selectable(item.store) -> { + install(context, item, preferred.root) + } + targets.size > 1 || wantedExternal || StoreLanguage.selectable(item.store) -> pendingInstall = item + else -> install(context, item, targets.first().root) + } } fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) { val app = context.applicationContext - val folder = StoreInstallRoot.folderFor(app, item.store, item.id, item.title, root ?: StoreInstallRoot.installRoot(app)) + val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app) + if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) { + backends[item.store]?.install(app, item, targetRoot) + return + } + val folder = StoreInstallRoot.folderFor(app, item.store, item.id, item.title, targetRoot) val target = folder.parentFile!!.parentFile!! val code = language?.takeIf { it.isNotBlank() } ?: StoreLanguage.preferredCode(app) val tagged = if (StoreLanguage.selectable(item.store)) item.copy(extra = item.extra + (StoreLanguage.EXTRA to code)) else item @@ -256,6 +274,10 @@ object StoresState { uninstalling[key] = 0f background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) { runCatching { backends[game.sidecar.store]?.uninstall(app, game) } + if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) { + main.post { uninstalling.remove(key); onDone() } + return@background + } StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = { main.post { installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstall.kt b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstall.kt new file mode 100644 index 0000000000..0fe38c49db --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstall.kt @@ -0,0 +1,320 @@ +package com.droiddeck.launcher.stores.battlenet + +import android.content.Context +import android.util.Log +import androidx.compose.runtime.mutableStateMapOf +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.AddedGames +import com.droiddeck.launcher.runtime.BattleNet +import com.droiddeck.launcher.runtime.GuestCommand +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.GameStorage +import com.droiddeck.launcher.session.SecondaryLibrary +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.InstalledStoreGame +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreInstallRoot +import com.droiddeck.launcher.stores.StoreLanguage +import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.download.DownloadEntry +import com.droiddeck.launcher.stores.download.DownloadQueue +import com.droiddeck.launcher.stores.download.DownloadStage +import org.json.JSONObject +import java.io.File +import java.net.HttpURLConnection +import java.net.URL +import java.util.Locale +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean + +object BattleNetInstall { + private const val TAG = "BattleNetInstall" + internal const val PROGRESS = "BNET_PROGRESS " + internal const val STATE = "BNET_STATE " + internal const val DONE = "BNET_DONE " + internal const val ERROR = "BNET_ERROR " + private const val VERSIONS = "https://%s.version.battle.net/v2/products/%s/versions" + private const val BUILD_INFO = ".build.info" + private const val CHECK_AGAIN_MS = 30 * 60_000L + private const val START_WAIT_MS = 60_000L + + internal val LOCALES = listOf( + "enUS", "enGB", "esMX", "esES", "ptBR", "ptPT", "frFR", "deDE", "itIT", "ruRU", "jaJP", "koKR", "plPL", "trTR", + "zhTW", "zhCN", "thTH", "arSA", + ) + + internal val checks = Executors.newSingleThreadExecutor { r -> Thread(r, "battlenet-updates") } + internal val checkedAt = HashMap<String, Long>() + + val updates = mutableStateMapOf<String, Boolean>() + + fun product(id: String): String? = BattleNet.title(id)?.product + + fun headless(item: CatalogItem): Boolean = item.store == Store.BATTLENET && product(item.id) != null + + internal fun locale(locale: Locale): String { + val language = locale.language.lowercase(Locale.ROOT) + if (language == "zh") { + val traditional = locale.script.equals("Hant", true) || locale.country.uppercase(Locale.ROOT) in setOf("TW", "HK", "MO") + return if (traditional) "zhTW" else "zhCN" + } + val exact = language + locale.country.uppercase(Locale.ROOT) + return LOCALES.firstOrNull { it == exact } ?: LOCALES.firstOrNull { it.startsWith(language) } ?: "enUS" + } + + internal fun country(locale: Locale): Pair<String, String> { + val two = locale.country.uppercase(Locale.ROOT) + val three = runCatching { locale.isO3Country.uppercase(Locale.ROOT) }.getOrDefault("") + return if (two.matches(Regex("[A-Z]{2}")) && three.matches(Regex("[A-Z]{3}"))) three to two else "USA" to "US" + } + + internal fun binds(context: Context): List<String> { + val out = ArrayList<String>(StoreInstallRoot.externalBindSpecs(context)) + val root = LinuxRuntime.rootDir(context) + GameStorage.effective(context)?.let { library -> + if (!File(library.path).isDirectory) throw IllegalStateException(context.getString(R.string.game_sync_err_game_storage)) + val content = SecondaryLibrary.contentPath(File(library.path)).path + for (guest in SecondaryLibrary.CARD_GUESTS) { + File(root, guest.removePrefix("/")).mkdirs() + out += "$content:$guest" + } + } + for (folder in AddedGames.roots(context)) { + if (!folder.host.isDirectory || !folder.host.canRead()) continue + File(root, folder.guest.removePrefix("/")).mkdirs() + out += folder.host.path + ":" + folder.guest + } + return out + } + + internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int = + GuestCommand.run( + context, listOf(BattleNet.PROGRAM) + args, logName = "battlenet-agent", + extraBinds = binds(context), fastPath = true, cancelled = cancelled, onLine = onLine, + ) + + fun enqueue(context: Context, item: CatalogItem, folder: File, update: Boolean = false) { + val app = context.applicationContext + val entry = DownloadEntry( + Store.BATTLENET, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl, + location = StoreInstallRoot.labelFor(app, folder), + ) + DownloadQueue.enqueue(app, entry) { BattleNetInstaller(app, item, folder, update) } + } + + fun update(context: Context, game: InstalledStoreGame) { + val app = context.applicationContext + Thread({ + val item = CatalogItem( + Store.BATTLENET, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true, + extra = mapOf(INSTALL_UID to installUid(app, game)), + ) + game.folder.parentFile?.parentFile?.let { com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, it) } + enqueue(app, item, game.folder, update = true) + }, "battlenet-update").start() + } + + internal const val INSTALL_UID = "installUid" + + internal fun installUid(context: Context, game: InstalledStoreGame): String = + runCatching { BattleNet.games(context).firstOrNull { it.uid == game.sidecar.id }?.installUid }.getOrNull() ?: game.sidecar.id + + fun uninstall(context: Context, game: InstalledStoreGame): Boolean { + if (product(game.sidecar.id) == null || !BattleNet.installed(context)) return false + val done = agentUninstall(context, installUid(context, game)) + if (done) StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) } + return done + } + + internal fun agentUninstall(context: Context, uid: String): Boolean { + val stop = AtomicBoolean(false) + val started = AtomicBoolean(false) + val done = AtomicBoolean(false) + val guard = Thread({ + try { + Thread.sleep(START_WAIT_MS) + if (!started.get()) stop.set(true) + } catch (_: InterruptedException) { + } + }, "battlenet-uninstall-wait").apply { isDaemon = true; start() } + val code = runCatching { + run(context, listOf("agent-uninstall", uid), stop) { line -> + if (line == STATE + "starting") started.set(true) + if (line.startsWith(DONE)) done.set(true) + } + }.onFailure { Log.w(TAG, "uninstall $uid", it) }.getOrDefault(-1) + guard.interrupt() + Log.i(TAG, "uninstall $uid: ${if (done.get()) "done" else if (stop.get()) "Battle.net stayed busy" else "exit $code"}") + return done.get() + } + + internal fun buildKey(text: String): Pair<String, String>? { + val rows = text.lines().filter { it.isNotBlank() } + if (rows.size < 2) return null + val head = rows[0].split('|').map { it.substringBefore('!') } + val branch = head.indexOf("Branch") + val active = head.indexOf("Active") + val key = head.indexOf("Build Key") + if (branch < 0 || key < 0) return null + val row = rows.drop(1).map { it.split('|') }.firstOrNull { active < 0 || it.getOrNull(active) == "1" } ?: return null + val region = row.getOrNull(branch)?.takeIf { it.matches(Regex("[a-z]{2}")) } ?: return null + val build = row.getOrNull(key)?.takeIf { it.matches(Regex("[0-9a-f]{32}")) } ?: return null + return region to build + } + + internal fun latestBuild(text: String, region: String): String? { + val rows = text.lines().filter { it.isNotBlank() && !it.startsWith("##") } + if (rows.isEmpty()) return null + val head = rows[0].split('|').map { it.substringBefore('!') } + val at = head.indexOf("Region") + val key = head.indexOf("BuildConfig") + if (at < 0 || key < 0) return null + return rows.drop(1).map { it.split('|') }.firstOrNull { it.getOrNull(at) == region }?.getOrNull(key) + ?.takeIf { it.matches(Regex("[0-9a-f]{32}")) } + } + + fun checkUpdate(context: Context, game: InstalledStoreGame, force: Boolean = false) = check(game.sidecar.id, game.folder, force) + + internal fun check(id: String, folder: File, force: Boolean) { + val product = product(id) ?: return + val now = System.currentTimeMillis() + synchronized(checkedAt) { + if (!force && now - (checkedAt[id] ?: 0L) < CHECK_AGAIN_MS) return + checkedAt[id] = now + } + fun retryLater() = synchronized(checkedAt) { if (checkedAt[id] == now) checkedAt.remove(id) } + checks.execute { + val local = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull() + ?: return@execute retryLater() + val latest = runCatching { latestBuild(fetch(VERSIONS.format(Locale.ROOT, local.first, product)), local.first) } + .onFailure { Log.w(TAG, "versions of $product: ${it.javaClass.simpleName}") }.getOrNull() + ?: return@execute retryLater() + val behind = latest != local.second + Log.i(TAG, "$id: ${if (behind) "update available" else "up to date"}") + StoresState.post { if (behind) updates[id] = true else updates.remove(id) } + } + } + + private fun fetch(url: String): String { + val conn = (URL(url).openConnection() as HttpURLConnection).apply { + connectTimeout = 15_000 + readTimeout = 15_000 + setRequestProperty("User-Agent", "DroidDeck") + } + try { + if (conn.responseCode != 200) throw java.io.IOException("HTTP ${conn.responseCode}") + return conn.inputStream.bufferedReader().use { it.readText() } + } finally { + conn.disconnect() + } + } + + internal fun failure(context: Context, reason: String?, code: Int): String { + val detail = when { + reason == null -> "exit $code" + reason == "client" -> return context.getString(R.string.bnet_dl_client_first) + reason.startsWith("agent ") -> context.getString(R.string.bnet_dl_agent_error, reason.removePrefix("agent ")) + else -> reason.removePrefix("stopped ") + } + return context.getString(R.string.bnet_dl_failed, detail) + } + + internal fun localeTag(context: Context): String = locale(StoreLanguage.localeFor(null, context)) + + internal enum class Step { PREPARING, DOWNLOADING, APPLYING } + + internal fun step(state: Int, phase: Int, current: Long, total: Long): Step = when { + state == DONE_STATE || phase == APPLY_PHASE || total > 0L && current >= total -> Step.APPLYING + total > 0L -> Step.DOWNLOADING + else -> Step.PREPARING + } + + private const val DONE_STATE = 1004 + private const val APPLY_PHASE = 2000 +} + +internal class BattleNetInstaller( + private val app: Context, + private val item: CatalogItem, + private val folder: File, + private val update: Boolean, +) : DownloadQueue.DownloadJob { + private val cancelled = AtomicBoolean(false) + private val started = AtomicBoolean(false) + private val ended = java.util.concurrent.CountDownLatch(1) + private var before = 0L + private var kept = -1L + + override fun run(handle: DownloadQueue.JobHandle): String? { + started.set(true) + try { + return if (cancelled.get()) null else work(handle) + } finally { + ended.countDown() + } + } + + private fun work(handle: DownloadQueue.JobHandle): String? { + before = DownloadQueue.entry(handle.key)?.bytesTotal ?: 0L + handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting)) + if (!BattleNet.installed(app)) throw IllegalStateException(app.getString(R.string.bnet_dl_client_first)) + val title = BattleNet.title(item.id) + val product = title?.product ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, item.id)) + val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: title.uid + if (!update) folder.mkdirs() + val guest = AddedGames.guestPath(app, folder) ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, folder.path)) + val (country, region) = BattleNetInstall.country(Locale.getDefault()) + val args = if (update) listOf("agent-update", uid) + else listOf("agent-install", uid, product, guest, BattleNetInstall.localeTag(app), country, region) + var done: JSONObject? = null + var reason: String? = null + val code = BattleNetInstall.run(app, args, cancelled) { line -> + when { + line.startsWith(BattleNetInstall.PROGRESS) -> + runCatching { JSONObject(line.removePrefix(BattleNetInstall.PROGRESS)) }.getOrNull()?.let { progress(handle, it) } + line == BattleNetInstall.STATE + "waiting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_waiting)) + line == BattleNetInstall.STATE + "queued" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_queued)) + line == BattleNetInstall.STATE + "starting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting)) + line.startsWith(BattleNetInstall.DONE) -> done = runCatching { JSONObject(line.removePrefix(BattleNetInstall.DONE)) }.getOrNull() + line.startsWith(BattleNetInstall.ERROR) -> reason = line.removePrefix(BattleNetInstall.ERROR) + } + } + if (cancelled.get()) return null + if (done == null) throw IllegalStateException(BattleNetInstall.failure(app, reason, code)) + handle.log("Battle.net: ${item.title} ${if (update) "updated" else "installed"} ${done?.optString("version").orEmpty()}".trimEnd()) + StoresState.post { + BattleNetInstall.updates.remove(item.id) + StoresState.notifyLibraryChanged(app) + } + BattleNetInstall.check(item.id, folder, force = true) + return folder.absolutePath + } + + private fun progress(handle: DownloadQueue.JobHandle, status: JSONObject) { + val current = status.optLong("download_current", 0L) + val total = status.optLong("download_total", 0L) + when (BattleNetInstall.step(status.optInt("state", 0), status.optInt("phase", 0), current, total)) { + BattleNetInstall.Step.PREPARING -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_stage_checking)) + BattleNetInstall.Step.DOWNLOADING -> { + if (kept < 0L) kept = (before - total).coerceAtLeast(0L) + handle.progress(kept + current, kept + total) + } + BattleNetInstall.Step.APPLYING -> handle.stage(DownloadStage.INSTALL) + } + } + + override fun cancel(deleteFiles: Boolean) { + cancelled.set(true) + if (!deleteFiles || update) return + val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: BattleNet.title(item.id)?.uid ?: return + Thread({ + if (started.get() && !ended.await(END_WAIT_S, TimeUnit.SECONDS)) Log.w("BattleNetInstall", "the cancelled install of $uid is still stopping") + val gone = BattleNetInstall.agentUninstall(app, uid) + if (folder.isDirectory && (gone || folder.list().isNullOrEmpty())) com.droiddeck.launcher.core.FileUtils.delete(folder) + Log.i("BattleNetInstall", "cancelled install of $uid: ${if (gone) "removed" else "left for Battle.net to remove"}") + }, "battlenet-cancel").start() + } +} + +private const val END_WAIT_S = 120L diff --git a/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetStore.kt new file mode 100644 index 0000000000..737ba3b4ff --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetStore.kt @@ -0,0 +1,300 @@ +package com.droiddeck.launcher.stores.battlenet + +import android.content.Context +import android.net.Uri +import android.util.Log +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.AddedGames +import com.droiddeck.launcher.runtime.BattleNet +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.InstalledStoreGame +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreAccounts +import com.droiddeck.launcher.stores.StoreBackend +import com.droiddeck.launcher.stores.StoreGameSidecar +import com.droiddeck.launcher.stores.StoreInstallRoot +import com.droiddeck.launcher.stores.StoreShelves +import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.download.DownloadEntry +import com.droiddeck.launcher.stores.download.DownloadQueue +import com.droiddeck.launcher.stores.download.DownloadStage +import org.json.JSONObject +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.net.HttpURLConnection +import java.net.URL +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong + +object BattleNetClient { + private const val TAG = "BattleNetClient" + const val DOWNLOAD_ID = "battlenet-client" + const val DOWNLOAD_KEY = "battlenet:$DOWNLOAD_ID" + const val REQUEST = "battlenet-request" + internal const val INSTALLER_URL = "https://downloader.battle.net/download/getInstallerForGame?os=win&gameProgram=BATTLENET_APP&version=Live" + private const val SETUP = "root/.cache/droiddeck/battlenet/Battle.net-Setup.exe" + private const val CONFIG = "pfx/drive_c/users/steamuser/AppData/Roaming/Battle.net/Battle.net.config" + internal const val MIN_SETUP = 1L shl 20 + private val work = Executors.newSingleThreadExecutor { r -> Thread(r, "battlenet-client") } + + private val sequence = AtomicLong() + + @Volatile var opener: ((List<String>) -> Unit)? = null + + fun setup(context: Context): File = File(LinuxRuntime.rootDir(context), SETUP) + + internal fun setupReady(file: File): Boolean = runCatching { + file.length() >= MIN_SETUP && file.inputStream().use { input -> + val head = ByteArray(2) + input.read(head) == 2 && head[0] == 'M'.code.toByte() && head[1] == 'Z'.code.toByte() + } + }.getOrDefault(false) + + internal fun account(config: String?): String? { + val client = runCatching { JSONObject(config ?: return null).optJSONObject("Client") }.getOrNull() ?: return null + if (client.optString("AutoLogin") != "true") return null + return client.optString("SavedAccountNames").split(',').map { it.trim() }.firstOrNull { it.isNotEmpty() } + } + + private fun config(context: Context) = File(BattleNet.prefix(context), CONFIG) + + fun signedInAs(context: Context): String? = + if (!BattleNet.installed(context)) null + else account(runCatching { config(context).readText() }.getOrNull())?.let(StoreAccounts::maskEmail) + + fun syncAccount(context: Context): Boolean { + val name = signedInAs(context) + if (name == StoreAccounts.signedInAs(context, Store.BATTLENET)) return false + if (name == null) StoreAccounts.clear(context, Store.BATTLENET) + else StoreAccounts.write(context, Store.BATTLENET, JSONObject().put("display_name", name)) + Log.i(TAG, if (name == null) "Battle.net is signed out" else "Battle.net is signed in") + return true + } + + fun refresh(context: Context) { + val app = context.applicationContext + work.execute { + if (runCatching { syncAccount(app) }.getOrDefault(false)) StoresState.notifyLibraryChanged(app) + } + } + + fun signIn(context: Context) { + val app = context.applicationContext + work.execute { + if (BattleNet.installed(app) || setupReady(setup(app))) { + open(emptyList()) + return@execute + } + StoresState.post { + if (DownloadQueue.isActive(DOWNLOAD_KEY)) return@post + val entry = DownloadEntry( + Store.BATTLENET, DOWNLOAD_ID, app.getString(R.string.bnet_name), + location = StoreInstallRoot.labelFor(app, setup(app)), + ) + DownloadQueue.enqueue(app, entry) { SetupDownload(app) } + StoresState.openDownloads = true + } + } + } + + fun signOut(context: Context) { + val file = config(context) + runCatching { + val json = JSONObject(file.readText()) + json.optJSONObject("Client")?.put("AutoLogin", "false") ?: return@runCatching + val staged = File(file.path + ".droiddeck") + staged.writeText(json.toString(4)) + check(staged.renameTo(file)) + Log.i(TAG, "Battle.net will ask for a sign-in at its next start") + }.onFailure { Log.w(TAG, "Battle.net's sign-in kept: ${it.javaClass.simpleName}") } + } + + fun request(sessionRoot: File, args: List<String>): Boolean = runCatching { + require(args.none { '\n' in it }) + val now = System.nanoTime() + val name = "$REQUEST.%020d".format(java.util.Locale.ROOT, sequence.updateAndGet { maxOf(it + 1, now) }) + val staged = File(sessionRoot, "$name.tmp") + staged.writeText(args.joinToString("\n") + "\n") + check(staged.renameTo(File(sessionRoot, name))) + Log.i(TAG, "handed ${args.firstOrNull()} to the open Battle.net") + }.onFailure { Log.w(TAG, "Battle.net request not left: ${it.javaClass.simpleName}") }.isSuccess + + fun clearRequests(sessionRoot: File) { + sessionRoot.listFiles { file -> file.name == REQUEST || file.name.startsWith("$REQUEST.") }?.forEach { it.delete() } + } + + fun open(args: List<String>) { + StoresState.post { opener?.invoke(args) } + } + + fun library(context: Context, root: File = preferred(context)): List<String> = + AddedGames.guestPath(context, StoreInstallRoot.storeDir(root, Store.BATTLENET))?.let { listOf("--library", it) }.orEmpty() + + internal fun preferred(context: Context): File { + val second = StoreInstallRoot.libraryRoot(context)?.absolutePath + return StoreInstallRoot.targets(context).firstOrNull { it.root.absolutePath == second && (it.root.isDirectory || it.root.mkdirs()) }?.root + ?: StoreInstallRoot.internalRoot(context) + } + + fun installGame(context: Context, uid: String, root: File) { + val app = context.applicationContext + work.execute { open(library(app, root) + listOf("install-game", uid)) } + } + + internal fun downloaded(context: Context) { + Log.i(TAG, "Battle.net's installer downloaded from Blizzard") + open(emptyList()) + StoresState.post { StoresState.notifyLibraryChanged(context) } + } +} + +object BattleNetBackend : StoreBackend { + override val store: Store = Store.BATTLENET + + override fun signIn(context: Context) = BattleNetClient.signIn(context) + + override fun signOut(context: Context) { + BattleNetClient.signOut(context) + StoresState.post { StoresState.shelves.remove(store); StoresState.found.remove(store) } + } + + override fun syncLibrary(context: Context, force: Boolean) { + val app = context.applicationContext + Thread({ + val items = runCatching { installed(app).map { item(app, it.title, owned = true) } }.getOrDefault(emptyList()) + StoresState.post { StoresState.library[store] = items } + }, "battlenet-library").start() + } + + override fun loadShelves(context: Context, force: Boolean) { + val app = context.applicationContext + Thread({ + val known = shelves(app) + StoresState.post { StoresState.shelves[store] = known } + if (runCatching { BattleNet.fetchCovers(app) }.getOrDefault(false)) { + val covered = shelves(app) + val items = runCatching { installed(app).map { item(app, it.title, owned = true) } }.getOrDefault(emptyList()) + StoresState.post { + StoresState.shelves[store] = covered + StoresState.library[store] = items + StoresState.notifyLibraryChanged(app) + } + } + }, "battlenet-shelves").start() + } + + override fun search(context: Context, query: String): List<CatalogItem> = + BattleNet.STORE.filter { it.name.contains(query, ignoreCase = true) }.map { item(context, it) } + + override fun install(context: Context, item: CatalogItem, root: File) { + if (!BattleNetInstall.headless(item)) return BattleNetClient.installGame(context, item.id, root) + val app = context.applicationContext + BattleNetInstall.enqueue(app, item, StoreInstallRoot.folderFor(app, store, item.id, item.title, root)) + } + + override fun uninstall(context: Context, game: InstalledStoreGame) { + if (!BattleNetInstall.uninstall(context, game)) BattleNetClient.open(emptyList()) + } + + fun installed(context: Context): List<BattleNet.Game> = if (BattleNet.installed(context)) BattleNet.games(context) else emptyList() + + fun installedGames(context: Context): List<InstalledStoreGame> = installed(context).map { game -> + val art = BattleNet.art(context, game.title) + val cover = art.cover?.let { Uri.fromFile(it).toString() } + InstalledStoreGame(StoreGameSidecar(store, game.title.uid, game.name, "", cover = cover, hero = art.header?.let { Uri.fromFile(it).toString() } ?: cover), game.folder) + } + + private fun shelves(context: Context): StoreShelves { + val items = BattleNet.STORE.map { item(context, it) } + return StoreShelves(trending = items, art = items.mapNotNull { it.tallImageUrl }) + } + + private fun item(context: Context, title: BattleNet.Title, owned: Boolean = false): CatalogItem { + val art = BattleNet.art(context, title) + return CatalogItem( + store, title.uid, title.name, + imageUrl = (art.header ?: art.cover)?.let { Uri.fromFile(it).toString() }, + tallImageUrl = art.cover?.let { Uri.fromFile(it).toString() }, + owned = owned, + ) + } +} + +internal class SetupDownload(private val app: Context) : DownloadQueue.DownloadJob { + private val cancelled = AtomicBoolean(false) + @Volatile private var connection: HttpURLConnection? = null + + override fun run(handle: DownloadQueue.JobHandle): String? { + handle.stage(DownloadStage.DOWNLOAD) + if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.epic_client_no_runtime)) + val file = BattleNetClient.setup(app) + val partial = File(file.path + ".part") + file.parentFile?.mkdirs() + var attempt = 0 + while (!cancelled.get()) { + try { + fetch(partial, handle) + if (cancelled.get()) break + if (!BattleNetClient.setupReady(partial)) throw IOException("not a Windows program") + if (!partial.renameTo(file)) throw IOException("could not keep the installer") + BattleNetClient.downloaded(app) + return file.absolutePath + } catch (e: IOException) { + partial.delete() + if (cancelled.get()) break + attempt++ + handle.log("Battle.net installer attempt $attempt: ${e.message ?: e.javaClass.simpleName}") + if (attempt >= ATTEMPTS) throw IllegalStateException(app.getString(R.string.epic_client_download_failed, e.message ?: e.javaClass.simpleName)) + val until = System.currentTimeMillis() + (2_000L shl (attempt - 1)) + while (System.currentTimeMillis() < until && !cancelled.get()) Thread.sleep(100) + } + } + partial.delete() + return null + } + + private fun fetch(partial: File, handle: DownloadQueue.JobHandle) { + val conn = (URL(BattleNetClient.INSTALLER_URL).openConnection() as HttpURLConnection).apply { + connectTimeout = 20_000 + readTimeout = 30_000 + instanceFollowRedirects = true + setRequestProperty("User-Agent", "DroidDeck") + } + connection = conn + try { + if (conn.responseCode != 200) throw IOException("HTTP ${conn.responseCode}") + if (conn.url.protocol != "https") throw IOException("not served over HTTPS") + val total = conn.contentLengthLong + var done = 0L + conn.inputStream.use { input -> + FileOutputStream(partial).use { out -> + val buf = ByteArray(64 * 1024) + while (!cancelled.get()) { + val n = input.read(buf) + if (n < 0) break + out.write(buf, 0, n) + done += n + handle.progress(done, total) + } + out.fd.sync() + } + } + if (!cancelled.get() && total > 0 && done != total) throw IOException("the download ended early") + } finally { + connection = null + runCatching { conn.disconnect() } + } + } + + override fun cancel(deleteFiles: Boolean) { + cancelled.set(true) + runCatching { connection?.disconnect() } + } + + private companion object { + const val ATTEMPTS = 4 + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BlizzardArt.kt b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BlizzardArt.kt new file mode 100644 index 0000000000..3fc972ab20 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BlizzardArt.kt @@ -0,0 +1,93 @@ +package com.droiddeck.launcher.stores.battlenet + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import java.io.File +import java.io.IOException +import java.net.CookieManager +import java.net.CookiePolicy +import java.net.HttpURLConnection +import java.net.URL + +internal object BlizzardArt { + private const val SHOP = "https://us.shop.battle.net/en-us/product/" + private const val MAX_PAGE = 16 shl 20 + private const val MAX_IMAGE = 12 shl 20 + private const val WIDE = 1280 + private val OG = Regex("""<meta property="og:image" content="(https://[^"]+)"""") + private val THUMB = Regex("""\\?"imageUrl\\?":\\?"(//catalog\.blzstatic\.com/[^"\\]+)""") + private val HOSTS = listOf(".blzstatic.com", ".blz-contentstack.com", "blz-contentstack-images.akamaized.net") + + internal fun imageUrl(page: String): String? { + val og = OG.find(page)?.groupValues?.get(1)?.takeUnless { "youtube" in it || "maxresdefault" in it } + val thumbs = THUMB.findAll(page).map { it.groupValues[1] }.filter { "_bundle" !in it }.map { "https:$it" } + return (sequenceOf(og) + thumbs).filterNotNull().firstOrNull(::allowed) + } + + private fun allowed(url: String): Boolean { + val host = runCatching { URL(url).host }.getOrNull() ?: return false + return HOSTS.any { h -> host == h.trimStart('.') || host.endsWith(h) } + } + + fun fetch(slug: String, wide: File, cover: File?): Boolean { + val page = get(URL(SHOP + slug), MAX_PAGE, true)?.toString(Charsets.UTF_8) ?: return false + val url = imageUrl(page) ?: return false + val bytes = get(URL(url.substringBefore('?') + "?imwidth=$WIDE"), MAX_IMAGE, false) ?: return false + val art = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return false + try { + val scaled = if (art.width > WIDE) Bitmap.createScaledBitmap(art, WIDE, art.height * WIDE / art.width, true) else art + save(scaled, wide) + if (cover != null) { + val w = minOf(scaled.width, scaled.height * 2 / 3) + val crop = Bitmap.createBitmap(scaled, (scaled.width - w) / 2, 0, w, w * 3 / 2) + save(Bitmap.createScaledBitmap(crop, 600, 900, true), cover) + } + return true + } finally { + art.recycle() + } + } + + private fun save(bitmap: Bitmap, file: File) { + val tmp = File(file.path + ".tmp") + tmp.outputStream().use { if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 90, it)) throw IOException("not saved") } + if (!tmp.renameTo(file)) throw IOException("not kept") + } + + private fun get(start: URL, limit: Int, follow: Boolean): ByteArray? { + val cookies = CookieManager(null, CookiePolicy.ACCEPT_ALL) + var url = start + repeat(8) { + if (url.protocol != "https") return null + val conn = (url.openConnection() as HttpURLConnection).apply { + instanceFollowRedirects = false + connectTimeout = 15_000 + readTimeout = 20_000 + setRequestProperty("User-Agent", "DroidDeck") + cookies.get(url.toURI(), emptyMap()).forEach { (k, v) -> if (v.isNotEmpty()) setRequestProperty(k, v.joinToString("; ")) } + } + try { + val code = conn.responseCode + cookies.put(url.toURI(), conn.headerFields) + when { + code == 200 -> return conn.inputStream.use { input -> + val out = java.io.ByteArrayOutputStream() + val buf = ByteArray(64 * 1024) + while (true) { + val n = input.read(buf) + if (n < 0) break + out.write(buf, 0, n) + if (out.size() > limit) return null + } + out.toByteArray() + } + follow && code in 301..308 -> url = URL(url, conn.getHeaderField("Location") ?: return null) + else -> return null + } + } finally { + conn.disconnect() + } + } + return null + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/download/SavedQueue.kt b/app/src/main/java/com/droiddeck/launcher/stores/download/SavedQueue.kt index a9a25759e1..e9a0acbcfa 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/download/SavedQueue.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/download/SavedQueue.kt @@ -79,7 +79,7 @@ object SavedQueue { put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: "") i.logoUrl?.let { put("logo", it) } put("tags", i.tags); put("developer", i.developer); put("description", i.description) - put("size", i.sizeBytes); put("owned", i.owned); put("subscription", i.subscription) + put("size", i.sizeBytes); put("owned", i.owned); put("subscription", i.subscription); put("free", i.isFree) put("extra", JSONObject(i.extra)) } @@ -90,7 +90,7 @@ object SavedQueue { id = o.getString("id"), title = o.getString("title"), imageUrl = o.optString("image").ifEmpty { null }, tallImageUrl = o.optString("tall").ifEmpty { null }, tags = o.optString("tags"), developer = o.optString("developer"), description = o.optString("description"), - owned = o.optBoolean("owned", true), subscription = o.optBoolean("subscription"), sizeBytes = o.optLong("size"), + owned = o.optBoolean("owned", true), subscription = o.optBoolean("subscription"), isFree = o.optBoolean("free"), sizeBytes = o.optLong("size"), extra = extra?.keys()?.asSequence()?.associateWith { extra.getString(it) } ?: emptyMap(), logoUrl = o.optString("logo").ifEmpty { null }, ) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicClient.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicClient.kt index 8da3a96ad4..454d94826c 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicClient.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicClient.kt @@ -292,10 +292,24 @@ object EpicClient { AddedGames.guestPath(app, folder)?.let { t.root.absolutePath to (folder to it) } }.toMap() if (dirs.isEmpty()) return null - val chosen = dirs[SessionPrefs.storesInstallTarget(app)] ?: dirs[StoreInstallRoot.internalRoot(app).absolutePath] ?: dirs.values.first() + val preferred = StoreInstallRoot.defaultTarget(app)?.root?.absolutePath + val chosen = preferred?.let { dirs[it] } + ?: dirs[SessionPrefs.storesInstallTarget(app)] + ?: dirs[StoreInstallRoot.internalRoot(app).absolutePath] + ?: dirs.values.first() val file = File(dataDir(app), SETTINGS) val settings = runCatching { JSONObject(file.readText()) }.getOrNull() ?: JSONObject() val current = settings.optString("defaultInstallDir").trimEnd('/') + val externalMissing = SessionPrefs.defaultStorage(app) == SessionPrefs.DEFAULT_STORAGE_EXTERNAL && preferred == null + if (externalMissing && current.isNotEmpty() && + (current.startsWith("/mnt/droiddeck-") || current.startsWith("/root/Storage/"))) { + Log.w(TAG, "the configured external storage is disconnected; keeping $current") + return current + } + if (externalMissing && current.isEmpty()) { + Log.w(TAG, "the configured external storage is disconnected; not choosing an install folder") + return null + } if (current.isNotEmpty() && current != STOCK_INSTALL_DIR && dirs.values.none { it.second == current } && !(current.endsWith("/${Store.EPIC.shortLabel}") && (current.startsWith("/mnt/droiddeck-") || current.startsWith("/root/Storage/")))) return current if (!chosen.first.isDirectory && !chosen.first.mkdirs()) return null if (current == chosen.second) return current diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt index acb7333e82..bf62da5b59 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt @@ -102,24 +102,31 @@ object GogBackend : StoreBackend { StoreInstalls.begin(folder, Store.GOG, game.gameId, game.title, item.tallImageUrl ?: item.imageUrl, item.imageUrl) var downloading = false val language = item.extra[StoreLanguage.EXTRA] ?: StoreLanguage.preferredCode(app) - val result = GogDownloadManager.install(app, game, folder, object : GogDownloadManager.Callback { - override fun onProgress(message: String, pct: Int) { - when { - message.startsWith("Finishing") -> handle.stage(DownloadStage.INSTALL, message) - message.startsWith("Downloading") || message.startsWith("Verified") || message.startsWith("Resuming") -> { - if (!downloading) { downloading = true; handle.stage(DownloadStage.DOWNLOAD, message) } else handle.progress(-1, -1, message) + val result = try { + GogDownloadManager.install(app, game, folder, object : GogDownloadManager.Callback { + override fun onProgress(message: String, pct: Int) { + when { + message.startsWith("Finishing") || message.startsWith("Extracting") -> handle.stage(DownloadStage.INSTALL, message) + message.startsWith("Downloading") || message.startsWith("Verified") || message.startsWith("Resuming") -> { + if (!downloading) { downloading = true; handle.stage(DownloadStage.DOWNLOAD, message) } else handle.progress(-1, -1, message) + } + else -> handle.stage(DownloadStage.MANIFEST, message) } - else -> handle.stage(DownloadStage.MANIFEST, message) } + override fun onBytes(done: Long, total: Long, speedBps: Long) { handle.progress(done, total, null, speedBps) } + override fun onLog(line: String) { handle.log(line) } + override fun onSizes(downloadBytes: Long, diskBytes: Long) { handle.diskSize(diskBytes) } + override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) { + handle.stage(when (stage) { "check" -> DownloadStage.MANIFEST; "verify" -> DownloadStage.VERIFY; else -> DownloadStage.INSTALL }) + handle.stageProgress(done, total, items, itemsTotal, bytes = stage == "install") + } + }, cancelled, language) + } catch (t: Throwable) { + if (t is GogDownloadManager.InstallerException && !cancelled.get()) { + StoreInstalls.discard(app, folder, listOf(File(folder, ".gog_chunks"))) } - override fun onBytes(done: Long, total: Long, speedBps: Long) { handle.progress(done, total, null, speedBps) } - override fun onLog(line: String) { handle.log(line) } - override fun onSizes(downloadBytes: Long, diskBytes: Long) { handle.diskSize(diskBytes) } - override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) { - handle.stage(when (stage) { "check" -> DownloadStage.MANIFEST; "verify" -> DownloadStage.VERIFY; else -> DownloadStage.INSTALL }) - handle.stageProgress(done, total, items, itemsTotal, bytes = stage == "install") - } - }, cancelled, language) ?: return null + throw t + } ?: return null if (cancelled.get()) return null handle.stage(DownloadStage.INSTALL, app.getString(com.droiddeck.launcher.R.string.stores_registering)) val installedLanguage = result.language?.takeIf { it.isNotEmpty() } ?: language diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java index 05b182df7d..dae63e5a29 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java @@ -3,6 +3,8 @@ package com.droiddeck.launcher.stores.gog; import android.content.Context; import android.util.Log; +import com.droiddeck.launcher.frontend.AddedGames; +import com.droiddeck.launcher.runtime.GuestCommand; import com.droiddeck.launcher.stores.StoreLanguage; import com.droiddeck.launcher.stores.StoreLog; import com.droiddeck.launcher.stores.download.StoreDownloadTier; @@ -21,7 +23,9 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; +import java.nio.file.Files; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; @@ -63,10 +67,15 @@ public final class GogDownloadManager { Result(String exeRelative, String buildId, long bytes) { this.exeRelative = exeRelative; this.buildId = buildId; this.bytes = bytes; } } - public static final class InstallException extends Exception { + public static class InstallException extends Exception { InstallException(String message) { super(message); } } + /** A failure of the offline-installer fallback; its partial files can be discarded. */ + public static final class InstallerException extends InstallException { + InstallerException(String message) { super(message); } + } + private GogDownloadManager() {} public static Result install(Context ctx, GogGame game, File installPath, Callback cb, AtomicBoolean cancelled) throws InstallException { @@ -424,41 +433,149 @@ public final class GogDownloadManager { String productJson = httpGet("https://api.gog.com/products/" + game.gameId + "?expand=downloads", token); if (productJson == null) throw new InstallException("No downloadable builds for this game"); JSONObject downloads = new JSONObject(productJson).optJSONObject("downloads"); - JSONArray installers = downloads == null ? null : downloads.optJSONArray("installers"); - if (installers == null || installers.length() == 0) throw new InstallException("No downloadable builds for this game"); - String manualUrl = null, fileName = null; - for (int i = 0; i < installers.length(); i++) { - JSONObject inst = installers.getJSONObject(i); - if (!"windows".equals(inst.optString("os"))) continue; - JSONArray files = inst.optJSONArray("files"); - if (files != null && files.length() > 0) { - JSONObject f = files.getJSONObject(0); - manualUrl = f.optString("downlink", null); - if (manualUrl == null) manualUrl = f.optString("manualUrl", null); - fileName = f.optString("filename", null); - } - if (manualUrl == null) manualUrl = inst.optString("manualUrl", null); - if (fileName == null || fileName.isEmpty()) fileName = "setup_" + game.gameId + ".exe"; - break; - } - if (manualUrl == null) throw new InstallException("No Windows installer for this game"); - String downloadUrl = resolveRedirect(manualUrl, token); - if (downloadUrl == null) throw new InstallException("The installer link could not be resolved"); + List<InstallerPart> parts = installerParts(downloads, game.gameId); + if (parts.isEmpty()) throw new InstallException("No downloadable builds for this game"); installPath.mkdirs(); - File outFile = new File(installPath, fileName); - cb.onProgress("Downloading installer: " + fileName, 15); - long size = downloadWithProgress(downloadUrl, outFile, cb, cancelled); + long planned = 0; + boolean sized = true; + for (InstallerPart part : parts) { planned += part.size; if (part.size <= 0) sized = false; } + if (sized) { + long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath); + if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(planned, usable)) { + throw new InstallException("Not enough free space: need " + formatBytes(planned) + ", only " + formatBytes(usable) + " free"); + } + } + long total = 0; + for (InstallerPart part : parts) { + if (cancelled.get()) return null; + String downloadUrl = resolveRedirect(part.url, token); + if (downloadUrl == null) throw new InstallException("The installer link could not be resolved: " + part.filename); + File outFile; + try { + outFile = installerDestination(installPath, part.filename); + } catch (IOException e) { + throw new InstallException("The installer part is not inside the game folder: " + part.filename); + } + cb.onProgress("Downloading installer: " + part.filename, 15 + (int) ((total / (float) Math.max(1, planned)) * 80)); + long size = downloadWithProgress(downloadUrl, outFile, cb, cancelled, total, sized ? planned : 0); + if (cancelled.get()) return null; + if (size <= 0) throw new InstallException("The installer download failed: " + part.filename); + total += size; + } if (cancelled.get()) return null; - if (size <= 0) throw new InstallException("The installer download failed"); - cb.onLog("gog: installer downloaded; the game installs itself on first launch"); - return new Result(fileName, "", size); - } catch (InstallException e) { + cb.onLog("gog: installer downloaded (" + parts.size() + " file(s)); extracting natively"); + extractInstaller(ctx, installPath, parts.get(0).filename, cb, cancelled); + if (cancelled.get()) return null; + for (InstallerPart part : parts) new File(installPath, part.filename).delete(); + deleteDir(new File(installPath, "tmp")); + deleteDir(new File(installPath, "commonappdata")); + String exe = pickExe(installPath, null, game.title); + if (exe.isEmpty()) throw new InstallException("The installer was extracted but no game executable was found"); + cb.onLog("gog: installer extracted natively; game exe " + exe); + return new Result(exe, "", total); + } catch (InstallerException e) { throw e; + } catch (InstallException e) { + throw new InstallerException(e.getMessage()); } catch (Exception e) { - throw new InstallException("Installer download error: " + e.getClass().getSimpleName()); + throw new InstallerException("Installer download error: " + e.getClass().getSimpleName()); } } + /** + * GOG's Windows installer is a 32-bit Inno Setup stub. On ARM64 it runs through + * Proton/FEX, where its path strings are corrupted before CreateFileW (observed on + * Wine 11 + FEX: "Path not found"). Extracting the same files with innoextract in + * the Linux guest avoids that path entirely. + */ + private static void extractInstaller(Context ctx, File installPath, String setupName, Callback cb, AtomicBoolean cancelled) throws InstallException { + String guestDir = AddedGames.INSTANCE.guestPath(ctx, installPath); + if (guestDir == null || guestDir.isEmpty()) { + throw new InstallException("The game folder is not visible to the Linux session"); + } + String guestSetup = guestDir + "/" + setupName; + cb.onProgress("Extracting installer…", 95); + int rc; + try { + rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList( + "/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", + "-d", guestDir, guestSetup), + false, "gog-innoextract", null, null, false, cancelled, + line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; }); + } catch (Exception e) { + throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName()); + } + if (cancelled.get()) return; + if (rc != 0) throw new InstallException("The installer could not be extracted (innoextract exit " + rc + ")"); + } + + static final class InstallerPart { + final String url; + final String filename; + final long size; + InstallerPart(String url, String filename, long size) { this.url = url; this.filename = filename; this.size = size; } + } + + /** + * Every file of the first usable Windows installer. GOG lists a setup stub and its data parts as + * separate files, often without a filename; the parts are named after the stub so the installer + * finds them when launched (setup_<id>.exe, setup_<id>-1.bin, ...). + */ + static List<InstallerPart> installerParts(JSONObject downloads, String gameId) { + List<InstallerPart> out = new ArrayList<>(); + if (downloads == null) return out; + JSONArray installers = downloads.optJSONArray("installers"); + if (installers == null) return out; + for (int i = 0; i < installers.length(); i++) { + JSONObject inst = installers.optJSONObject(i); + if (inst == null || !"windows".equals(inst.optString("os"))) continue; + JSONArray files = inst.optJSONArray("files"); + String base = null; + if (files != null) { + for (int j = 0; j < files.length(); j++) { + JSONObject f = files.optJSONObject(j); + if (f == null) continue; + String url = f.optString("downlink", ""); + if (url.isEmpty()) url = f.optString("manualUrl", ""); + if (url.isEmpty()) continue; + String name = partName(f.optString("filename", "")); + if (name.isEmpty()) { + if (base == null) base = "setup_" + safeName(gameId); + name = out.isEmpty() ? base + ".exe" : base + "-" + out.size() + ".bin"; + } else if (base == null) { + base = name.toLowerCase(java.util.Locale.US).endsWith(".exe") ? name.substring(0, name.length() - 4) : name; + } + out.add(new InstallerPart(url, name, f.optLong("size", 0))); + } + } + if (out.isEmpty()) { + String url = inst.optString("manualUrl", ""); + if (url.isEmpty()) url = inst.optString("downlink", ""); + if (!url.isEmpty()) out.add(new InstallerPart(url, "setup_" + safeName(gameId) + ".exe", inst.optLong("total_size", 0))); + } + if (!out.isEmpty()) return out; + } + return out; + } + + static File installerDestination(File installPath, String filename) throws IOException { + File root = installPath.getCanonicalFile(); + File candidate = new File(root, filename); + if (Files.isSymbolicLink(candidate.toPath())) throw new IOException("installer part is a link"); + File out = candidate.getCanonicalFile(); + if (out.equals(root) || !out.toPath().startsWith(root.toPath())) throw new IOException("installer part leaves the game folder"); + return out; + } + + private static String partName(String raw) { + return raw == null ? "" : new File(raw.replace('\\', '/')).getName(); + } + + private static String safeName(String raw) { + String cleaned = raw == null ? "" : raw.replaceAll("[^A-Za-z0-9._-]", "_"); + return cleaned.isEmpty() ? "game" : cleaned; + } + private static String resolveRedirect(String url, String token) { try { if (url.startsWith("/")) url = "https://www.gog.com" + url; @@ -491,7 +608,7 @@ public final class GogDownloadManager { return null; } - private static long downloadWithProgress(String url, File out, Callback cb, AtomicBoolean cancelled) { + private static long downloadWithProgress(String url, File out, Callback cb, AtomicBoolean cancelled, long doneBefore, long planned) { try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(60_000); @@ -507,7 +624,11 @@ public final class GogDownloadManager { downloaded += n; windowBytes += n; long elapsed = System.currentTimeMillis() - windowStart; if (elapsed >= 500) { speed = windowBytes * 1000L / elapsed; windowStart = System.currentTimeMillis(); windowBytes = 0; } - if (total > 0) { + if (planned > 0) { + long shown = doneBefore + downloaded; + cb.onProgress("Downloading: " + out.getName() + speedSuffix(speed), 15 + (int) ((shown / (float) planned) * 80)); + cb.onBytes(shown, planned, speed); + } else if (total > 0) { cb.onProgress("Downloading: " + out.getName() + speedSuffix(speed), 15 + (int) ((downloaded / (float) total) * 80)); cb.onBytes(downloaded, total, speed); } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchApi.kt b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchApi.kt index 92635630d9..293a59c46d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchApi.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchApi.kt @@ -19,8 +19,13 @@ internal object ItchApi { fun ownedKeys(key: String, page: Int): JSONObject? = get("/profile/owned-keys?page=$page&per_page=500", key) + fun collections(key: String): JSONArray? = get("/profile/collections", key)?.optJSONArray("collections") + + fun collectionGames(key: String, collectionId: String, page: Int): JSONObject? = + get("/collections/$collectionId/collection-games?page=$page", key) + fun uploads(key: String, gameId: String, downloadKeyId: String): JSONArray? = - get("/games/$gameId/uploads?download_key_id=$downloadKeyId", key)?.optJSONArray("uploads") + get("/games/$gameId/uploads" + keyQuery(downloadKeyId), key)?.optJSONArray("uploads") fun search(key: String, query: String, page: Int): JSONArray? { val q = java.net.URLEncoder.encode(query, "UTF-8") @@ -28,7 +33,9 @@ internal object ItchApi { } fun downloadUrl(uploadId: String, downloadKeyId: String): String = - "$BASE/uploads/$uploadId/download?download_key_id=$downloadKeyId" + "$BASE/uploads/$uploadId/download" + keyQuery(downloadKeyId) + + private fun keyQuery(downloadKeyId: String): String = if (downloadKeyId.isBlank()) "" else "?download_key_id=$downloadKeyId" fun pageUrl(slug: String): String = "$WEB/$slug" } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBackend.kt index b1bf834c15..66ca72602a 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBackend.kt @@ -55,7 +55,7 @@ object ItchBackend : StoreBackend { override fun install(context: Context, item: CatalogItem, root: File) { val app = context.applicationContext - if (item.extra["downloadKeyId"].isNullOrEmpty()) { + if (item.extra["downloadKeyId"].isNullOrEmpty() && !item.isFree) { StoresState.logLine("itch.io: \"${item.title}\" is not in the library") return } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchCollections.kt b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchCollections.kt new file mode 100644 index 0000000000..30e216f103 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchCollections.kt @@ -0,0 +1,116 @@ +package com.droiddeck.launcher.stores.itch + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.StoresState +import org.json.JSONArray +import org.json.JSONObject +import java.util.concurrent.ConcurrentHashMap + +internal class ItchCollection(val id: String, val title: String, val count: Int) + +internal object ItchCollections { + var list by mutableStateOf<List<ItchCollection>>(emptyList()) + private set + var selected by mutableStateOf<String?>(null) + private set + private val games = mutableStateMapOf<String, List<CatalogItem>>() + private val loading = ConcurrentHashMap.newKeySet<String>() + @Volatile private var generation = 0 + + fun items(): List<CatalogItem> = games.values.flatten() + + fun gamesOf(id: String): List<CatalogItem>? = games[id] + + fun chosen(): ItchCollection? = list.firstOrNull { it.id == selected } + + fun clear() { + generation++ + StoresState.post { + list = emptyList() + selected = null + games.clear() + } + } + + fun load(context: Context) { + val app = context.applicationContext + val started = generation + val guard = "$started:" + if (!loading.add(guard)) return + Thread({ + try { + val key = ItchAuth.key(app) + if (key.isBlank()) return@Thread + val parsed = parseCollections(ItchApi.collections(key) ?: return@Thread) + if (started != generation) return@Thread + StoresState.post { + if (started != generation) return@post + list = parsed + if (selected != null && parsed.none { it.id == selected }) selected = null + } + StoresState.logLine("itch.io: ${parsed.size} collections") + selected?.let { fetchGames(key, it, started) } + } finally { + loading.remove(guard) + } + }, "itch-collections").start() + } + + fun select(context: Context, id: String?) { + selected = id + if (id == null) return + val app = context.applicationContext + val started = generation + Thread({ + val key = ItchAuth.key(app) + if (key.isNotBlank()) fetchGames(key, id, started) + }, "itch-collection-games").start() + } + + private fun fetchGames(key: String, id: String, started: Int) { + val guard = "$started:$id" + if (!loading.add(guard)) return + try { + val out = ArrayList<CatalogItem>() + val seen = HashSet<String>() + var page = 1 + while (true) { + val body = ItchApi.collectionGames(key, id, page) + if (body == null) { + StoresState.logLine("itch.io: collection $id page $page failed") + return + } + val batch = parseGames(body) + if (batch.isEmpty()) break + val before = out.size + out.addAll(batch.filter { seen.add(it.id) }) + if (out.size == before) break + page++ + } + val distinct = out.toList() + StoresState.post { if (started == generation) games[id] = distinct } + StoresState.logLine("itch.io: collection $id has ${distinct.size} games") + } finally { + loading.remove(guard) + } + } + + internal fun parseCollections(array: JSONArray): List<ItchCollection> = (0 until array.length()).mapNotNull { i -> + val c = array.optJSONObject(i) ?: return@mapNotNull null + val id = c.opt("id")?.toString().orEmpty().takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null + val title = c.optString("title").ifBlank { return@mapNotNull null } + ItchCollection(id, title, c.optInt("games_count", c.optInt("gamesCount"))) + } + + internal fun parseGames(body: JSONObject): List<CatalogItem> { + val rows = body.optJSONArray("collection_games") ?: body.optJSONArray("collectionGames") ?: return emptyList() + return (0 until rows.length()).mapNotNull { i -> + rows.optJSONObject(i)?.optJSONObject("game")?.let { ItchLibrary.item(it, "") } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchGame.kt b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchGame.kt new file mode 100644 index 0000000000..39b69ea3fc --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchGame.kt @@ -0,0 +1,44 @@ +package com.droiddeck.launcher.stores.itch + +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.StoreNet +import org.json.JSONArray + +internal class ItchBuild( + val uploadId: String, + val filename: String, + val size: Long, + val updatedAt: String, + val platforms: Set<String>, + val demo: Boolean, +) { + val installable: Boolean get() = "windows" in platforms +} + +internal object ItchGame { + private val PATH_AFTER = Regex("""name="itch:path"[^>]*content="games/(\d+)"""") + private val PATH_BEFORE = Regex("""content="games/(\d+)"[^>]*name="itch:path"""") + + fun idFromPage(html: String): String? = + PATH_AFTER.find(html)?.groupValues?.get(1) ?: PATH_BEFORE.find(html)?.groupValues?.get(1) + + fun resolveId(item: CatalogItem): String? { + item.extra["gameId"]?.takeIf { it.isNotBlank() }?.let { return it } + if (item.storeUrl.isBlank()) return null + val html = StoreNet.get(item.storeUrl) ?: return null + return idFromPage(html) + } + + fun builds(uploads: JSONArray?): List<ItchBuild> { + if (uploads == null) return emptyList() + return (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) } + .filter { it.optString("storage") != "external" } + .map { + ItchBuild( + it.optString("id"), ItchUploads.filename(it), ItchUploads.size(it), + it.optString("updated_at", it.optString("updatedAt")), ItchUploads.platforms(it), it.optBoolean("demo"), + ) + } + .sortedWith(compareByDescending<ItchBuild> { it.installable }.thenByDescending { it.updatedAt }) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchInstaller.kt b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchInstaller.kt index 96ec0ae353..5037de863c 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchInstaller.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchInstaller.kt @@ -38,11 +38,14 @@ internal class ItchInstaller( val key = ItchAuth.key(app) if (key.isBlank()) throw IllegalStateException(app.getString(R.string.stores_sync_sign_in)) val downloadKeyId = item.extra["downloadKeyId"].orEmpty() - if (downloadKeyId.isBlank()) throw IllegalStateException(app.getString(R.string.stores_itch_not_owned)) - val gameId = item.extra["gameId"].orEmpty().ifBlank { item.id.substringAfterLast('/') } + if (downloadKeyId.isBlank() && !item.isFree) throw IllegalStateException(app.getString(R.string.stores_itch_not_owned)) + val gameId = ItchGame.resolveId(item) ?: throw IllegalStateException(app.getString(R.string.stores_itch_no_game)) + val resuming = StoreGameSidecar.read(folder)?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true StoreInstalls.begin(folder, Store.ITCH, item.id, item.title, item.imageUrl, item.imageUrl) handle.stage(DownloadStage.MANIFEST) - val upload = ItchUploads.windows(ItchApi.uploads(key, gameId, downloadKeyId)) + val uploads = ItchApi.uploads(key, gameId, downloadKeyId) + val chosen = item.extra["uploadId"].orEmpty() + val upload = (if (chosen.isBlank()) ItchUploads.windows(uploads) else ItchUploads.byId(uploads, chosen)) ?: throw IllegalStateException(app.getString(R.string.stores_itch_no_upload)) val uploadId = upload.optString("id") val filename = ItchUploads.filename(upload) @@ -55,7 +58,7 @@ internal class ItchInstaller( download(key, downloadKeyId, uploadId, upload.optString("updated_at", upload.optString("updatedAt")), archive, size, handle) if (cancelled.get()) return null handle.stage(DownloadStage.INSTALL) - install(archive, filename, handle) + install(archive, filename, handle, resuming) } catch (t: Throwable) { if (!cancelled.get()) StoreInstalls.discard(app, folder, listOf(scratch)) throw t @@ -147,8 +150,16 @@ internal class ItchInstaller( } } - private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle): String? { + private fun clearPartialInstall() { + folder.listFiles()?.forEach { + if (it.name == StoreGameSidecar.FILE_NAME) return@forEach + if (it.isDirectory) StoreInstalls.deleteTree(it) else it.delete() + } + } + + private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean): String? { folder.mkdirs() + if (resuming) clearPartialInstall() when (val kind = sniff(archive, filename)) { "zip" -> unzip(archive, handle) "7z" -> sevenZip(archive, handle) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchUploads.kt b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchUploads.kt index 773ad22c30..7e3ed94b47 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchUploads.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchUploads.kt @@ -30,6 +30,28 @@ internal object ItchUploads { return names.none { it in PLATFORM_TRAITS } } + fun platforms(upload: JSONObject): Set<String> { + val found = LinkedHashSet<String>() + upload.optJSONObject("platforms")?.let { flags -> + for (name in listOf("windows", "linux", "osx", "android")) if (flags.optBoolean(name)) found.add(name) + } + upload.optJSONArray("traits")?.let { traits -> + for (i in 0 until traits.length()) when (traits.optString(i)) { + "p_windows" -> found.add("windows") + "p_linux" -> found.add("linux") + "p_osx" -> found.add("osx") + "p_android" -> found.add("android") + } + } + if (upload.optString("type") == "html") found.add("web") + return if (found.isEmpty()) setOf("windows") else found + } + + fun byId(uploads: JSONArray?, id: String): JSONObject? { + if (uploads == null || id.isBlank()) return null + return (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }.firstOrNull { it.optString("id") == id } + } + fun size(upload: JSONObject): Long = upload.optLong("size", upload.optLong("size_bytes")) fun filename(upload: JSONObject): String = upload.optString("filename").substringAfterLast('/') diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsActivity.kt index bfe1e3908e..1d6c3df63e 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsActivity.kt @@ -1,5 +1,7 @@ package com.droiddeck.launcher.stores.xbox +import androidx.compose.foundation.shape.CircleShape +import com.droiddeck.launcher.ui.focusGlide import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent @@ -45,7 +47,7 @@ class XboxCloudSettingsActivity : ComponentActivity() { } Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).verticalScroll(rememberScrollState())) { Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) { - OutlinedButton(onClick = { finish() }) { Text("Back") } + OutlinedButton(onClick = { finish() }, modifier = Modifier.focusGlide(CircleShape)) { Text("Back") } Text("Xbox Cloud Gaming", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 16.dp)) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt index 0a09fd7890..1131fb1245 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt @@ -1,5 +1,8 @@ package com.droiddeck.launcher.stores.xbox +import com.droiddeck.launcher.ui.glideBorder +import androidx.compose.foundation.shape.CircleShape +import com.droiddeck.launcher.ui.focusGlide import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope @@ -16,7 +19,6 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Switch import androidx.compose.material3.Text -import androidx.compose.foundation.border import androidx.compose.foundation.background import androidx.compose.foundation.focusable import androidx.compose.foundation.gestures.detectTapGestures @@ -148,7 +150,7 @@ private fun PanelContent( Toggle("Toon", "Cartoon outlines.", settings.toon) { onChange(settings.copy(toon = it)) } Choice("Frame-rate cap", listOf(0 to "Off", 30 to "30 fps", 45 to "45 fps", 60 to "60 fps"), settings.maxFps) { onChange(settings.copy(maxFps = it)) } Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedButton(onClick = { onChange(settings.withoutEffects()) }) { Text("Reset picture") } + OutlinedButton(onClick = { onChange(settings.withoutEffects()) }, modifier = Modifier.focusGlide(CircleShape)) { Text("Reset picture") } } Text("Effects cost a little GPU time; with none set the stream is shown directly.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp)) @@ -220,7 +222,7 @@ private fun SettingRow( Row( Modifier.fillMaxWidth().padding(vertical = 1.dp).clip(shape) .background(if (focused) cs.primary.copy(alpha = 0.16f) else Color.Transparent) - .border(2.dp, if (focused) cs.primary else Color.Transparent, shape) + .glideBorder(focused, shape, cs.primary, hotFillAlpha = 0f) .let { if (panel != null && index >= 0) it.focusRequester(panel.requester(index)) else it } .onFocusChanged { state -> focused = state.isFocused; if (state.isFocused && index >= 0) panel?.onFocused?.invoke(index) } .onKeyEvent { event -> @@ -299,8 +301,9 @@ internal fun XboxMenuEntry(title: String, note: String?, focus: FocusRequester? val shape = RoundedCornerShape(10.dp) androidx.compose.material3.Surface( onClick = onClick, color = if (focused) cs.primary.copy(alpha = 0.2f) else cs.surfaceContainerHigh, shape = shape, - border = if (focused) androidx.compose.foundation.BorderStroke(2.dp, cs.primary) else null, + border = null, modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 3.dp) + .glideBorder(focused, shape, cs.primary, hotFillAlpha = 0f) .let { if (focus != null) it.focusRequester(focus) else it } .onFocusChanged { state -> focused = state.isFocused; if (state.isFocused) onFocused() } .onKeyEvent { event -> if (event.type == KeyEventType.KeyDown && event.key == Key.ButtonA) { onClick(); true } else false }, diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLoginActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLoginActivity.kt index 10fc5ea71a..39840b2608 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLoginActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLoginActivity.kt @@ -36,6 +36,7 @@ class XboxLoginActivity : ComponentActivity() { @SuppressLint("SetJavaScriptEnabled") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this) host = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setBackgroundColor(Color.BLACK) } status = TextView(this).apply { setTextColor(Color.WHITE); text = "Preparing Microsoft sign-in…"; setPadding(24, 16, 24, 16) } host.addView(status) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt index 97fd03a3da..1333be117c 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt @@ -1,5 +1,7 @@ package com.droiddeck.launcher.stores.xbox +import androidx.compose.foundation.shape.CircleShape +import com.droiddeck.launcher.ui.focusGlide import android.content.Context import android.content.Intent import android.graphics.Color @@ -181,10 +183,10 @@ class XboxNativePlayerActivity : ComponentActivity() { fun NoticeButton(label: String, focus: androidx.compose.ui.focus.FocusRequester?, onClick: () -> Unit) = androidx.compose.material3.TextButton(onClick = onClick, modifier = androidx.compose.ui.Modifier.let { if (focus != null) it.focusRequester(focus) else it } - .onKeyEvent { e -> if (e.type == KeyEventType.KeyDown && e.key == Key.ButtonA) { onClick(); true } else false }) { + .onKeyEvent { e -> if (e.type == KeyEventType.KeyDown && e.key == Key.ButtonA) { onClick(); true } else false }.focusGlide(CircleShape)) { androidx.compose.material3.Text(label) } - androidx.compose.material3.AlertDialog( + com.droiddeck.launcher.ui.GlideAlertDialog( onDismissRequest = { finish() }, properties = androidx.compose.ui.window.DialogProperties(dismissOnClickOutside = false), title = { androidx.compose.material3.Text(title) }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt index b3b88f0aa4..660e0723c0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt @@ -88,7 +88,7 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.sp -import androidx.compose.ui.window.Dialog +import com.droiddeck.launcher.ui.GlideDialog as Dialog import androidx.compose.ui.window.DialogProperties import coil.compose.AsyncImage import coil.request.ImageRequest diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt index 3d86510f70..6e2ae810c0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt @@ -475,7 +475,7 @@ internal fun TextEntryDialog(title: String, initial: String, onDismiss: () -> Un AppDialog(shown, close, "textEntry", wide = false, maxWidth = 460.dp) { DialogTitleRow(title, onClose = close) androidx.compose.material3.OutlinedTextField( - value, { value = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusRequester(focus), + value, { value = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusRequester(focus).focusGlide(), keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { onSave(value.trim()); close() }), keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Done), ) @@ -644,7 +644,7 @@ private fun SgdbSearchDialog( SmallIconButton(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.common_back), colors.onBackground, onClick = back) }) androidx.compose.material3.OutlinedTextField( - query, { query = it }, singleLine = true, modifier = Modifier.fillMaxWidth(), + query, { query = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusGlide(), label = { Text(stringResource(R.string.art_sgdb_search_label)) }, keyboardActions = androidx.compose.foundation.text.KeyboardActions(onSearch = { leaveField(); search() }), keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Search), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt new file mode 100644 index 0000000000..fdd0fdd8cb --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt @@ -0,0 +1,959 @@ +package com.droiddeck.launcher.ui + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.view.KeyEvent +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.focusable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.GridItemSpan +import androidx.compose.foundation.lazy.grid.LazyGridState +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.grid.rememberLazyGridState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.FilterAlt +import androidx.compose.material.icons.filled.Sort +import androidx.compose.material.icons.filled.Widgets +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +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.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.compose.ui.zIndex +import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.HomeFolders +import com.droiddeck.launcher.HomeHidden +import com.droiddeck.launcher.HomePins +import android.content.pm.ShortcutInfo +import android.graphics.Bitmap +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.droiddeck.launcher.HomeWidgets +import com.droiddeck.launcher.R +import kotlinx.coroutines.launch +import kotlin.math.roundToInt + +private sealed interface AppEntry : AppEntryKey { + val key: String + + class App(val app: HomeApp.LaunchableApp) : AppEntry { + override val label get() = app.label + override val key get() = "app:" + app.key + override val installedAt get() = app.installedAt + override val updatedAt get() = app.updatedAt + } + + class Folder(val folder: HomeFolders.Folder, val apps: List<HomeApp.LaunchableApp>) : AppEntry { + override val label get() = folder.name + override val key get() = "folder:" + folder.id + override val installedAt get() = apps.maxOf { it.installedAt } + override val updatedAt get() = apps.maxOf { it.updatedAt } + } + + class Shortcut(val pinned: HomePins.Pinned) : AppEntry { + override val label get() = pinned.label + override val key get() = pinned.key + override val installedAt get() = 0L + override val updatedAt get() = 0L + } +} + +private fun indexLetter(label: String): String { + val c = label.trim().firstOrNull()?.uppercaseChar() ?: return "#" + return if (c in 'A'..'Z') c.toString() else if (c.isLetter()) c.toString() else "#" +} + +private fun searchRank(label: String, q: String): Int? { + if (label.startsWith(q, ignoreCase = true)) return 0 + if (label.split(' ', '-', '_', '.').any { it.startsWith(q, ignoreCase = true) }) return 1 + if (label.contains(q, ignoreCase = true)) return 2 + return null +} + +internal fun Context.findActivity(): Activity? { + var c: Context? = this + while (c is ContextWrapper) { + if (c is Activity) return c + c = c.baseContext + } + return null +} + +private fun Modifier.menuKey(onMenu: () -> Unit): Modifier = onPreviewKeyEvent { event -> + val k = event.nativeKeyEvent + if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y && k.keyCode != KeyEvent.KEYCODE_MENU) false + else { + if (k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) onMenu() + true + } +} + +internal object AppsView { + const val ALL = "all" + const val GAMES = "games" + const val DOWNLOADED = "downloaded" + const val SYSTEM = "system" + const val HIDDEN = "hidden" + val FILTERS = listOf(ALL, GAMES, DOWNLOADED, SYSTEM, HIDDEN) + const val NAME_ASC = "nameAsc" + const val NAME_DESC = "nameDesc" + const val INSTALLED = "installed" + const val UPDATED = "updated" + val SORTS = listOf(NAME_ASC, NAME_DESC, INSTALLED, UPDATED) + + var filter by mutableStateOf(ALL) + var sort by mutableStateOf(NAME_ASC) + private var loaded = false + + private fun prefs(context: Context) = context.getSharedPreferences("home_launcher", Context.MODE_PRIVATE) + + fun load(context: Context) { + if (loaded) return + loaded = true + val p = prefs(context) + filter = p.getString("filter", ALL)?.takeIf { it in FILTERS } ?: ALL + sort = p.getString("sort", NAME_ASC)?.takeIf { it in SORTS } ?: NAME_ASC + } + + fun setFilter(context: Context, value: String) { + filter = value + prefs(context).edit().putString("filter", value).apply() + } + + fun setSort(context: Context, value: String) { + sort = value + prefs(context).edit().putString("sort", value).apply() + } + + fun keeps(app: HomeApp.LaunchableApp): Boolean { + val hidden = app.key in HomeHidden.keys + return when (filter) { + HIDDEN -> hidden + GAMES -> !hidden && app.game + DOWNLOADED -> !hidden && !app.system + SYSTEM -> !hidden && app.system + else -> !hidden + } + } + + fun comparator(): Comparator<AppEntryKey> = when (sort) { + NAME_DESC -> compareBy<AppEntryKey, String>(String.CASE_INSENSITIVE_ORDER) { it.label }.reversed() + INSTALLED -> compareByDescending<AppEntryKey> { it.installedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label } + UPDATED -> compareByDescending<AppEntryKey> { it.updatedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label } + else -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.label } + } +} + +internal interface AppEntryKey { + val label: String + val installedAt: Long + val updatedAt: Long +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) { + val ctx = LocalContext.current + remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); true } + val colors = MaterialTheme.colorScheme + val narrow = LocalNarrowPane.current + val padH = if (narrow) 16.dp else 22.dp + var query by rememberSaveable { mutableStateOf("") } + var openFolder by rememberSaveable { mutableStateOf<String?>(null) } + var renameOnOpen by rememberSaveable { mutableStateOf(false) } + var picking by rememberSaveable { mutableStateOf(false) } + val folders = HomeFolders.folders + val byKey = remember(s.androidApps) { s.androidApps.associateBy { it.key } } + val byPkg = remember(s.androidApps) { s.androidApps.filterNot { it.work }.groupBy { it.packageName }.mapNotNull { (pkg, apps) -> apps.singleOrNull()?.let { pkg to it } }.toMap() } + LaunchedEffect(byPkg) { if (byPkg.isNotEmpty()) HomeFolders.migrateMembers(ctx) { byPkg[it]?.key } } + val member: (String) -> HomeApp.LaunchableApp? = { byKey[it] ?: byPkg[it] } + val pins = HomePins.pinned + val hidden = HomeHidden.keys + val q = query.trim() + val filter = AppsView.filter + val sort = AppsView.sort + val entries: List<AppEntry> = remember(s.androidApps, folders, q, filter, sort, pins, hidden) { + val kept = s.androidApps.filter { AppsView.keeps(it) } + val shortcuts = if (filter == AppsView.ALL) pins.map { AppEntry.Shortcut(it) } else emptyList() + if (q.isNotEmpty()) { + (kept.map { AppEntry.App(it) } + shortcuts).mapNotNull { e -> searchRank(e.label, q)?.let { it to e } } + .sortedWith(compareBy<Pair<Int, AppEntry>> { it.first }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.second.label }) + .map { it.second } + } else if (filter != AppsView.ALL) { + kept.map { AppEntry.App(it) }.sortedWith(AppsView.comparator()) + } else { + val folderEntries = folders.mapNotNull { f -> + val apps = f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }) + if (apps.isEmpty()) null else AppEntry.Folder(f, apps) + } + val grouped = folderEntries.flatMap { f -> f.apps.map { it.key } }.toSet() + (folderEntries + kept.filter { it.key !in grouped }.map { AppEntry.App(it) } + shortcuts).sortedWith(AppsView.comparator()) + } + } + val grid = rememberLazyGridState() + LaunchedEffect(q, filter, sort) { grid.scrollToItem(0) } + val widgetsShown = q.isEmpty() && filter == AppsView.ALL && HomeWidgets.widgets.isNotEmpty() + val leadItems = if (widgetsShown) 1 else 0 + val byName = sort == AppsView.NAME_ASC || sort == AppsView.NAME_DESC + val newFolder: (HomeApp.LaunchableApp) -> Unit = { app -> + val f = HomeFolders.create(ctx, ctx.getString(R.string.apps_folder_default), app.key) + renameOnOpen = true + openFolder = f.id + } + + Box(modifier) { + Column(Modifier.fillMaxSize().imePadding()) { + Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = if (narrow) 8.dp else 12.dp)) { + ModeHeader( + stringResource(R.string.content_android_apps), query, { query = it }, + placeholder = stringResource(R.string.apps_search_hint), + clearSearchFocus = openFolder != null || picking, + lead = { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) { + Text(stringResource(R.string.content_android_apps), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1) + val shownCount = s.androidApps.count { AppsView.keeps(it) } + if (filter == AppsView.ALL) pins.size else 0 + Text(androidx.compose.ui.res.pluralStringResource(R.plurals.apps_count, shownCount, shownCount), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1) + } + }, + ) { + AppsFilterButton() + AppsSortButton() + HeaderIconButton(stringResource(R.string.apps_add_widget), Icons.Filled.Widgets, "add-widget") { + HomeWidgets.loadProviders(ctx) + picking = true + } + } + } + Box(Modifier.weight(1f).fillMaxWidth()) { + val scroller = q.isEmpty() && byName && entries.size > 16 + LazyVerticalGrid( + columns = GridCells.Adaptive(if (narrow) 84.dp else 96.dp), + state = grid, + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + contentPadding = PaddingValues(start = padH, end = if (scroller) padH + 22.dp else padH, top = 12.dp, bottom = 16.dp), + modifier = Modifier.fillMaxSize(), + ) { + if (widgetsShown) item(key = "widgets", span = { GridItemSpan(maxLineSpan) }) { + BoxWithConstraints(Modifier.fillMaxWidth()) { + val maxW = maxWidth + FlowRow( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp), + ) { + for (w in HomeWidgets.widgets) key(w.id) { WidgetCard(w, maxW.value.toInt()) } + } + } + } + if (entries.isEmpty()) item(key = "empty", span = { GridItemSpan(maxLineSpan) }) { + Note( + when { + q.isNotEmpty() -> stringResource(R.string.apps_no_match, q) + filter == AppsView.HIDDEN -> stringResource(R.string.apps_hidden_none) + else -> stringResource(R.string.content_no_android_apps) + }, + ) + } + items(entries, key = { it.key }) { entry -> + when (entry) { + is AppEntry.App -> AppTile( + entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder, + first = entry === entries.first(), + ) + is AppEntry.Shortcut -> PinnedTile(entry.pinned, first = entry === entries.first()) + is AppEntry.Folder -> FolderTile(entry, first = entry === entries.first(), onOpen = { renameOnOpen = false; openFolder = entry.folder.id }) { + renameOnOpen = true + openFolder = entry.folder.id + } + } + } + } + if (scroller) AlphabetScroller(entries, grid, leadItems, Modifier.align(Alignment.CenterEnd).fillMaxHeight().padding(end = 4.dp, top = 8.dp, bottom = 8.dp)) + } + } + + val folder = folders.firstOrNull { it.id == openFolder } + LaunchedEffect(folder == null, openFolder) { if (folder == null && openFolder != null) openFolder = null } + AnimatedVisibility( + folder != null, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)), + modifier = Modifier.fillMaxSize().zIndex(2f), + ) { + var last by remember { mutableStateOf(folder) } + if (folder != null) last = folder + last?.let { f -> + FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder) { + openFolder = null + renameOnOpen = false + } + } + } + AnimatedVisibility( + picking, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)), + modifier = Modifier.fillMaxSize().zIndex(3f), + ) { WidgetPicker(padH) { picking = false } } + } +} + +@Composable +private fun SwipeLock() { + DisposableEffect(Unit) { + PageSwipe.locks++ + onDispose { PageSwipe.locks-- } + } +} + +@Composable +private fun appsFilterLabel(filter: String): String = stringResource( + when (filter) { + AppsView.GAMES -> R.string.apps_filter_games + AppsView.DOWNLOADED -> R.string.apps_filter_downloaded + AppsView.SYSTEM -> R.string.apps_filter_system + AppsView.HIDDEN -> R.string.apps_filter_hidden + else -> R.string.apps_filter_all + }, +) + +@Composable +private fun appsSortLabel(sort: String): String = stringResource( + when (sort) { + AppsView.NAME_DESC -> R.string.apps_sort_name_desc + AppsView.INSTALLED -> R.string.apps_sort_installed + AppsView.UPDATED -> R.string.apps_sort_updated + else -> R.string.apps_sort_name_asc + }, +) + +@Composable +private fun AppsFilterButton() = HeaderChoiceButton( + stringResource(R.string.apps_filter), Icons.Filled.FilterAlt, "apps-filter", + AppsView.FILTERS, AppsView.filter, { appsFilterLabel(it) }, AppsView::setFilter, +) + +@Composable +private fun AppsSortButton() = HeaderChoiceButton( + stringResource(R.string.stores_sort), Icons.Filled.Sort, "apps-sort", + AppsView.SORTS, AppsView.sort, { appsSortLabel(it) }, AppsView::setSort, +) + +@Composable +private fun HeaderChoiceButton( + title: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, + options: List<String>, current: String, label: @Composable (String) -> String, onPick: (Context, String) -> Unit, +) { + val pal = LocalPalette.current + val ctx = LocalContext.current + var at by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) } + Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) { + HeaderIconButton("$title · ${label(current)}", icon, key) { + val from = at ?: return@HeaderIconButton + Steps.ask(StepAsk( + anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = options.size, + handle = { Icon(icon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) }, + ) { + StepTitle(title) + StepList { + options.forEachIndexed { i, option -> + StepChoice( + label(option), selected = option == current, enabled = open, + modifier = Modifier.fillMaxWidth().stepItem(i).then(if (option == current) Modifier.focusRequester(first) else Modifier), + ) { + onPick(ctx, option) + Steps.fold() + } + } + } + }) + } + } +} + +@Composable +private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val scope = rememberCoroutineScope() + val firstAt = remember(entries) { + val map = LinkedHashMap<String, Int>() + entries.forEachIndexed { i, e -> map.putIfAbsent(indexLetter(e.label), i) } + map + } + val letters = remember(firstAt) { firstAt.keys.toList() } + var dragging by remember { mutableStateOf<String?>(null) } + val current by remember(entries, leadItems) { + derivedStateOf { + val i = (grid.firstVisibleItemIndex - leadItems).coerceIn(0, (entries.size - 1).coerceAtLeast(0)) + entries.getOrNull(i)?.let { indexLetter(it.label) } + } + } + var height by remember { mutableIntStateOf(1) } + val jump: (Float) -> Unit = { y -> + val i = ((y / height) * letters.size).toInt().coerceIn(0, letters.size - 1) + val letter = letters[i] + if (letter != dragging) { + dragging = letter + val at = firstAt[letter] ?: 0 + scope.launch { grid.scrollToItem(if (at == 0) 0 else leadItems + at) } + } + } + Box(modifier.width(22.dp)) { + Column( + verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.fillMaxSize() + .clip(RoundedCornerShape(11.dp)) + .background(if (dragging != null) colors.surface.copy(alpha = 0.85f) else Color.Transparent) + .onSizeChanged { height = it.height.coerceAtLeast(1) } + .pointerInput(letters) { + awaitEachGesture { + val down = awaitFirstDown() + down.consume() + jump(down.position.y) + while (true) { + val event = awaitPointerEvent() + val c = event.changes.firstOrNull { it.id == down.id } ?: break + if (!c.pressed) break + c.consume() + jump(c.position.y) + } + dragging = null + } + }, + ) { + for (l in letters) { + val on = l == (dragging ?: current) + Text( + l, fontSize = 10.sp, lineHeight = 11.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Medium, + color = if (on) pal.signal else colors.onSurfaceVariant, textAlign = TextAlign.Center, + ) + } + } + dragging?.let { l -> + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.align(Alignment.Center).offset { IntOffset(-64.dp.roundToPx(), 0) }.size(56.dp) + .clip(CircleShape).background(pal.signal), + ) { Text(l, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = pal.onPrimary) } + } + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun TileFrame( + id: String, first: Boolean, onClick: () -> Unit, onMenu: () -> Unit, + content: @Composable (hot: Boolean) -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val pressed by src.collectIsPressedAsState() + val scale by animateFloatAsState(if (pressed) 0.95f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "appScale") + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.fillMaxWidth() + .paneItem("tile:$id").then(if (first) Modifier.firstTile().paneEntry() else Modifier) + .graphicsLayer { scaleX = scale; scaleY = scale } + .clip(Shape12) + .background(if (hot) colors.surface else colors.surface.copy(alpha = 0.55f)) + .glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp) + .hoverable(src) + .combinedClickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onLongClick = onMenu, onClick = onClick) + .controllerConfirm(onClick = onClick) + .menuKey(onMenu) + .padding(horizontal = 6.dp, vertical = 10.dp), + ) { content(hot) } +} + +@Composable +private fun TileLabel(text: String) = Text( + text, fontSize = 12.sp, lineHeight = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, + maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp), +) + +@Composable +private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.Dp) { + val icon = app.icon + if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(size)) + else Box(Modifier.size(size).clip(CircleShape).background(artBrush(hueOf(app.label)))) +} + +@Composable +private fun AppTile( + app: HomeApp.LaunchableApp, folderId: String?, first: Boolean, + onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, +) { + var menu by remember { mutableStateOf(false) } + Box { + TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) { + AppIcon(app, 52.dp) + TileLabel(app.label) + } + AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder) + } +} + +@Composable +private fun AppMenu( + app: HomeApp.LaunchableApp, folderId: String?, open: Boolean, + onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, +) { + val ctx = LocalContext.current + var choosing by remember { mutableStateOf(false) } + var shortcuts by remember { mutableStateOf<List<Pair<ShortcutInfo, Bitmap?>>>(emptyList()) } + LaunchedEffect(open) { + if (!open) { + choosing = false + return@LaunchedEffect + } + shortcuts = withContext(Dispatchers.IO) { + HomeApp.shortcuts(ctx, app).map { it to HomeApp.shortcutIcon(ctx, it, 64) } + } + } + val isHidden = app.key in HomeHidden.keys + AnchoredMenu(open, onDismiss = onDismiss, title = app.label, compact = true, minWidth = 200.dp) { first -> + if (choosing) { + val others = HomeFolders.folders.filter { it.id != folderId } + var firstUsed = false + for (f in others) key(f.id) { + MenuItem(f.name, checked = false, focusRequester = if (!firstUsed) first.also { firstUsed = true } else null) { + HomeFolders.add(ctx, f.id, app.key) + onDismiss() + } + } + MenuItem(stringResource(R.string.apps_new_folder), checked = false, focusRequester = if (others.isEmpty()) first else null) { + onDismiss() + onNewFolder(app) + } + } else { + shortcuts.forEachIndexed { i, (info, icon) -> + key(info.id) { + MenuItem( + info.shortLabel?.toString().orEmpty(), checked = false, + focusRequester = if (i == 0) first else null, + leading = { MenuIcon(icon) }, + ) { + onDismiss() + runCatching { HomeApp.startShortcut(ctx, info) } + } + } + } + if (shortcuts.isNotEmpty()) Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(LocalPalette.current.line)) + if (!isHidden) MenuItem(stringResource(R.string.apps_add_to_folder), checked = false, focusRequester = if (shortcuts.isEmpty()) first else null) { choosing = true } + if (folderId != null) MenuItem(stringResource(R.string.apps_remove_from_folder), checked = false) { + HomeFolders.remove(ctx, app.key) + onDismiss() + } + MenuItem(stringResource(if (isHidden) R.string.apps_unhide else R.string.apps_hide), checked = false, + focusRequester = if (isHidden && shortcuts.isEmpty()) first else null) { + onDismiss() + HomeHidden.set(ctx, app.key, !isHidden) + } + MenuItem(stringResource(R.string.apps_app_info), checked = false) { + onDismiss() + runCatching { HomeApp.openAppInfo(ctx, app) } + } + if (HomeApp.canUninstall(app)) MenuItem(stringResource(R.string.apps_uninstall), checked = false) { + onDismiss() + runCatching { HomeApp.uninstall(ctx, app) } + } + } + } +} + +@Composable +private fun MenuIcon(icon: Bitmap?) { + if (icon != null) Image(icon.asImageBitmap(), null, modifier = Modifier.size(20.dp)) + else Spacer(Modifier.size(20.dp)) +} + +@Composable +private fun PinnedTile(pinned: HomePins.Pinned, first: Boolean) { + val ctx = LocalContext.current + var menu by remember { mutableStateOf(false) } + Box { + TileFrame(pinned.key, first, onClick = { runCatching { HomeApp.startShortcut(ctx, pinned.info) } }, onMenu = { menu = true }) { + Box { + val icon = pinned.icon + if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp)) + else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label)))) + } + TileLabel(pinned.label) + } + AnchoredMenu(menu, onDismiss = { menu = false }, title = pinned.label, compact = true, minWidth = 180.dp) { firstItem -> + MenuItem(stringResource(R.string.apps_shortcut_remove), checked = false, detail = pinned.appLabel, focusRequester = firstItem) { + menu = false + HomePins.unpin(ctx, pinned) + } + } + } +} + +@Composable +private fun FolderIcon(apps: List<HomeApp.LaunchableApp>, size: androidx.compose.ui.unit.Dp) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val cell = (size - 14.dp) / 2 + Box( + Modifier.size(size).clip(RoundedCornerShape(size / 3.5f)).background(colors.surfaceVariant) + .glideBorder(false, RoundedCornerShape(size / 3.5f), pal.signal, pal.line2) + .padding(5.dp), + ) { + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + for (row in apps.take(4).chunked(2)) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + for (a in row) AppIcon(a, cell) + } + } + } +} + +@Composable +private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Unit, onRename: () -> Unit) { + val ctx = LocalContext.current + var menu by remember { mutableStateOf(false) } + Box { + TileFrame(entry.key, first, onClick = onOpen, onMenu = { menu = true }) { + FolderIcon(entry.apps, 52.dp) + TileLabel(entry.folder.name) + } + AnchoredMenu(menu, onDismiss = { menu = false }, title = entry.folder.name, compact = true, minWidth = 160.dp) { firstItem -> + MenuItem(stringResource(R.string.apps_folder_rename), checked = false, focusRequester = firstItem) { + menu = false + onRename() + } + MenuItem(stringResource(R.string.apps_folder_ungroup), checked = false) { + menu = false + HomeFolders.delete(ctx, entry.folder.id) + } + } + } +} + +@Composable +private fun FolderSheet( + folder: HomeFolders.Folder, apps: List<HomeApp.LaunchableApp>, renameFirst: Boolean, + onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit, +) { + SwipeLock() + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var renaming by remember(folder.id) { mutableStateOf(renameFirst) } + var name by remember(folder.id) { mutableStateOf(if (renameFirst) "" else folder.name) } + val commit = { + val n = name.trim() + if (n.isNotEmpty() && n != folder.name) HomeFolders.rename(ctx, folder.id, n) + renaming = false + } + val close = { if (renaming) commit(); onClose() } + BackHandler { close() } + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f)) + .pointerInput(Unit) { awaitEachGesture { val d = awaitFirstDown(); d.consume(); close() } }, + ) { + val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true } + AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160)), exit = scaleOut(Motion.tw(140)) + fadeOut(Motion.tw(140))) { + Column( + modifier = Modifier.widthIn(max = 620.dp).fillMaxWidth(0.9f).heightIn(max = 520.dp) + .clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f)) + .glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f)) + .pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } } + .controllerBack(close) + .padding(16.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) { + if (renaming) Box(Modifier.weight(1f)) { + AdbTextField( + value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name), + keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false, + placeholder = folder.name, focusOnShow = true, onDone = { commit() }, + ) + } else { + Text(folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + SmallIconButton(Icons.Filled.Edit, stringResource(R.string.apps_folder_rename), tint = colors.onSurfaceVariant) { renaming = true } + Spacer(Modifier.weight(1f)) + } + SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant) { close() } + } + LazyVerticalGrid( + columns = GridCells.Adaptive(92.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + items(apps, key = { it.key }) { app -> + AppTile(app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder) + } + } + } + } + } +} + +@Composable +private fun WidgetCard(w: HomeWidgets.Placed, maxWidthDp: Int) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var menu by remember { mutableStateOf(false) } + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val width = w.widthDp.coerceAtMost(maxWidthDp) + val activity = remember(ctx) { ctx.findActivity() } + Box { + Box( + Modifier.size(width.dp, w.heightDp.dp) + .clip(Shape16) + .background(colors.surface.copy(alpha = 0.35f)) + .glideBorder(hot || menu, Shape16, pal.signal) + .hoverable(src).focusable(interactionSource = src) + .controllerConfirm { menu = true } + .menuKey { menu = true }, + ) { + AndroidView( + factory = { c -> + (HomeWidgets.createView(c, w.id) ?: android.view.View(c)).apply { + val radius = 16 * c.resources.displayMetrics.density + outlineProvider = object : android.view.ViewOutlineProvider() { + override fun getOutline(view: android.view.View, outline: android.graphics.Outline) = + outline.setRoundRect(0, 0, view.width, view.height, radius) + } + clipToOutline = true + } + }, + update = { v -> + if (v is HomeWidgets.HomeWidgetView) { + v.onLongPress = { menu = true } + HomeWidgets.applySize(v, width, w.heightDp) + } + }, + modifier = Modifier.fillMaxSize(), + ) + } + val (minW, minH) = remember(w.id) { HomeWidgets.minSize(ctx, w.id) } + val index = HomeWidgets.widgets.indexOfFirst { it.id == w.id } + val label = remember(w.id) { HomeWidgets.info(ctx, w.id)?.loadLabel(ctx.packageManager) ?: "" } + AnchoredMenu(menu, onDismiss = { menu = false }, title = label, compact = true, minWidth = 180.dp) { first -> + val step = 48 + MenuItem(stringResource(R.string.apps_widget_wider), checked = false, enabled = width < maxWidthDp, focusRequester = first) { + HomeWidgets.resize(ctx, w.id, (width + step).coerceAtMost(maxWidthDp), w.heightDp) + } + MenuItem(stringResource(R.string.apps_widget_narrower), checked = false, enabled = width > minW) { + HomeWidgets.resize(ctx, w.id, (width - step).coerceAtLeast(minW), w.heightDp) + } + MenuItem(stringResource(R.string.apps_widget_taller), checked = false, enabled = w.heightDp < 480) { + HomeWidgets.resize(ctx, w.id, width, (w.heightDp + step).coerceAtMost(480)) + } + MenuItem(stringResource(R.string.apps_widget_shorter), checked = false, enabled = w.heightDp > minH) { + HomeWidgets.resize(ctx, w.id, width, (w.heightDp - step).coerceAtLeast(minH)) + } + if (index > 0) MenuItem(stringResource(R.string.apps_widget_move_earlier), checked = false) { HomeWidgets.move(ctx, w.id, -1) } + if (index in 0 until HomeWidgets.widgets.size - 1) MenuItem(stringResource(R.string.apps_widget_move_later), checked = false) { HomeWidgets.move(ctx, w.id, 1) } + if (activity != null && HomeWidgets.canReconfigure(ctx, w.id)) MenuItem(stringResource(R.string.apps_widget_configure), checked = false) { + menu = false + HomeWidgets.reconfigure(activity, w.id) + } + MenuItem(stringResource(R.string.apps_widget_remove), checked = false) { + menu = false + HomeWidgets.remove(ctx, w.id) + } + } + } +} + +@Composable +private fun WidgetPicker(padH: androidx.compose.ui.unit.Dp, onClose: () -> Unit) { + SwipeLock() + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val activity = remember(ctx) { ctx.findActivity() } + BackHandler { onClose() } + val providers = HomeWidgets.providers + Column(Modifier.fillMaxSize().background(colors.background).pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false) } }) { + LazyVerticalGrid( + columns = GridCells.Adaptive(150.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + contentPadding = PaddingValues(horizontal = padH, vertical = 14.dp), + modifier = Modifier.fillMaxSize(), + ) { + item(key = "back", span = { GridItemSpan(maxLineSpan) }) { + Column { + Box(Modifier.padding(bottom = 10.dp)) { BackLink(stringResource(R.string.rail_apps), compact = true, onClick = onClose) } + PageHeader(stringResource(R.string.apps_add_widget)) { + if (providers != null) Chip(providers.size.toString(), ok = false) + } + } + } + when { + providers == null -> item(key = "loading", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_loading)) } + providers.isEmpty() -> item(key = "none", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_none)) } + else -> items(providers, key = { it.info.provider.flattenToString() }) { p -> + ProviderCard(p, first = p === providers.first()) { + onClose() + if (activity != null) HomeWidgets.add(activity, p) + } + } + } + } + } +} + +@Composable +private fun ProviderCard(p: HomeWidgets.Provider, first: Boolean, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Column( + modifier = Modifier.fillMaxWidth().paneItem("widget:" + p.info.provider.flattenToString()).then(if (first) Modifier.firstTile() else Modifier) + .clip(Shape12).background(colors.surface) + .glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp) + .hoverable(src) + .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) + .controllerConfirm(onClick = onClick), + ) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxWidth().aspectRatio(1.6f).background(colors.surfaceVariant).padding(10.dp), + ) { + val preview = p.preview + if (preview != null) Image(preview.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) + } + Column(Modifier.padding(horizontal = 10.dp, vertical = 8.dp)) { + Text(p.label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + val cells = "${(p.widthDp / 80f).roundToInt().coerceAtLeast(1)} × ${(p.heightDp / 80f).roundToInt().coerceAtLeast(1)}" + Text(if (p.appLabel == p.label) cells else "${p.appLabel} · $cells", fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } +} + +@Composable +fun PinRequestPrompt(label: String, appLabel: String, icon: Bitmap?, wide: Boolean, onAdd: () -> Unit, onCancel: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + BackHandler { onCancel() } + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f)) + .pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); onCancel() } }, + ) { + val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true } + AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160))) { + Column( + verticalArrangement = Arrangement.spacedBy(14.dp), + modifier = Modifier.widthIn(min = 280.dp, max = 420.dp) + .clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f)) + .glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f)) + .pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } } + .controllerBack(onCancel) + .padding(18.dp), + ) { + Text( + stringResource(R.string.apps_pin_title).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, + letterSpacing = 1.5.sp, color = colors.onSurfaceVariant, + ) + if (wide && icon != null) Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxWidth().heightIn(max = 180.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface).padding(10.dp), + ) { Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxWidth()) } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) { + if (!wide) { + if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp)) + else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(label)))) + } + Column(Modifier.weight(1f)) { + Text(label, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(appLabel, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) { + SecondaryButton(stringResource(R.string.common_cancel), onClick = onCancel) + PrimaryButton(stringResource(R.string.apps_pin_add), onClick = onAdd) + } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt index c4d8053d98..2c090048d4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt @@ -308,12 +308,12 @@ private fun InstalledMoviesDialog(a: ModeSettingsActions, onDismiss: () -> Unit) @Composable private fun RemoveMovieDialog(entry: BootMovieLibrary.Entry, onConfirm: () -> Unit, onDismiss: () -> Unit) { - androidx.compose.material3.AlertDialog( + com.droiddeck.launcher.ui.GlideAlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.boot_movie_remove_confirm, entry.title)) }, text = { Text(stringResource(R.string.boot_movie_remove_confirm_body)) }, - confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm) { Text(stringResource(R.string.boot_movie_remove)) } }, - dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } }, + confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.boot_movie_remove)) } }, + dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/CardDetailHost.kt b/app/src/main/java/com/droiddeck/launcher/ui/CardDetailHost.kt index d94ee25a7d..f606e6008a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/CardDetailHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/CardDetailHost.kt @@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -37,6 +38,8 @@ import androidx.compose.runtime.setValue import androidx.compose.runtime.getValue /** A grid of cards with a game page that floods out of the opened card and drains back into it. */ +internal val LocalDetailFloor = compositionLocalOf<() -> Float> { { Float.MAX_VALUE } } + @OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) @Composable internal fun CardDetailHost( @@ -57,6 +60,7 @@ internal fun CardDetailHost( var from by remember { mutableStateOf<Origin?>(null) } var art by remember { mutableStateOf<String?>(null) } var viewportAt by remember { mutableStateOf(Offset.Zero) } + var viewportH by remember { mutableStateOf(0) } LaunchedEffect(open) { if (open != null) { val mark = StoresMotion.takeCard(open) @@ -83,7 +87,7 @@ internal fun CardDetailHost( val fade = with(density) { 14.dp.toPx() } Box( modifier.clipToBounds() - .onGloballyPositioned { viewportAt = it.positionInRoot() } + .onGloballyPositioned { viewportAt = it.positionInRoot(); viewportH = it.size.height } .graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen } .drawWithContent { drawContent() @@ -114,7 +118,10 @@ internal fun CardDetailHost( .onFocusChanged { onDetailFocus(it.hasFocus) } .focusProperties { exit = { if (coveringNow.value && Steps.step == null && StoresMotion.step == null) FocusRequester.Cancel else FocusRequester.Default } } .focusGroup(), - ) { detail(key) } + ) { + val floor = { viewportAt.y + viewportH - with(density) { 16.dp.toPx() } - detailScroll.value } + CompositionLocalProvider(LocalDetailFloor provides floor) { detail(key) } + } } } val origin = from diff --git a/app/src/main/java/com/droiddeck/launcher/ui/CollectionsIcon.kt b/app/src/main/java/com/droiddeck/launcher/ui/CollectionsIcon.kt new file mode 100644 index 0000000000..ade8c967f8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/CollectionsIcon.kt @@ -0,0 +1,15 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.unit.dp + +internal val CollectionsIcon: ImageVector = ImageVector.Builder("Collections", 24.dp, 24.dp, 24f, 24f).apply { + for (d in listOf( + "M2.65,4.6H7.33V22H2.65Z", + "M8.32,2H13V22H8.32Z", + "M13.9,5.4H18.5L21.4,22H16.8Z", + )) addPath(addPathNodes(d), fill = SolidColor(Color.Black)) +}.build() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index 0e99b6e714..a934d39cfa 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -38,7 +38,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.Refresh import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme @@ -699,7 +699,7 @@ fun ComponentsPage( Box(Modifier.fillMaxSize().onGloballyPositioned { pageAt = it.positionInRoot() }.onFocusChanged { pageFocused = it.hasFocus }) { Column( - Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp) + Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp).padding(top = if (narrow) 12.dp else 18.dp) .then(if (selectedGame == null) Modifier.bumpers( onPrevious = { pick(layerStep(layer, -1)) }, onNext = { pick(layerStep(layer, 1)) }, @@ -972,7 +972,7 @@ private fun Stack( onFocus = { onFocus(l) }, onClick = { onOpen(l) }, ) } - Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { StackHeading(stringResource(R.string.comp_this_device)) card(GPU_TAB) Spacer(Modifier.height(6.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt index 0a603d5a54..825b6980fb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt @@ -37,10 +37,12 @@ class DeckControlsPanel( private val onSteamMenu: () -> Unit, private val onQam: () -> Unit, private val pad: PadBridge? = null, + private val portraitDock: Boolean = false, ) : LinearLayout(context) { private enum class Tab(val label: Int) { GAMEPAD(R.string.deck_tab_gamepad), GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) } private val content = FrameLayout(context) + val deckControls = pad == null || SessionState.deckPad private val tabViews = HashMap<Tab, TextView>() private val topBar: View by lazy { topBar() } @@ -49,7 +51,7 @@ class DeckControlsPanel( setBackgroundColor(Color.BLACK) addView(topBar, LayoutParams(LayoutParams.MATCH_PARENT, dp(64))) addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) - select(if (pad != null) selectedWithPad else selected) + select(if (pad != null && !deckControls) Tab.GAMEPAD else if (pad != null) selectedWithPad else selected) } override fun onDetachedFromWindow() { @@ -67,6 +69,7 @@ class DeckControlsPanel( background = outline(CORNER_PILL, SURFACE) setPadding(dp(4), dp(4), dp(4), dp(4)) for (tab in Tab.values()) { + if (!deckControls && tab != Tab.GAMEPAD) continue if (tab == Tab.GAMEPAD && pad == null) continue val view = TextView(context).apply { text = context.getString(tab.label) @@ -170,7 +173,7 @@ class DeckControlsPanel( addView(grips, LayoutParams(LayoutParams.MATCH_PARENT, dp(84))) } - private fun gamepad(pad: PadBridge): View = GamepadLayout(context).apply { + private fun gamepad(pad: PadBridge): View = GamepadLayout(context, portraitDock).apply { fun pill(label: String, write: (PadState, Boolean) -> Unit) = PadButton(context, pad, label, write) place(surfaceSlot(pad, right = false), GamepadGeometry.Slot.LEFT_MAIN) place(DirectionPad(context, pad), GamepadGeometry.Slot.LEFT_SECOND) @@ -186,14 +189,22 @@ class DeckControlsPanel( place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM) } place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU) - place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) }, + if (deckControls) place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) }, GamepadGeometry.Slot.PANELS) + if (portraitDock && deckControls) { + place(GripButton(context, "L4", null, DeckControls.L4), GamepadGeometry.Slot.L4) + place(GripButton(context, "L5", null, DeckControls.L5), GamepadGeometry.Slot.L5) + place(GripButton(context, "R5", null, DeckControls.R5), GamepadGeometry.Slot.R5) + place(GripButton(context, "R4", null, DeckControls.R4), GamepadGeometry.Slot.R4) + } } private fun centreTap(label: String, description: String, onClick: () -> Unit) = TextView(context).apply { text = label contentDescription = description textSize = 13f + maxLines = 1 + setAutoSizeTextTypeUniformWithConfiguration(9, 13, 1, android.util.TypedValue.COMPLEX_UNIT_SP) typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) letterSpacing = 0.08f gravity = Gravity.CENTER @@ -206,6 +217,11 @@ class DeckControlsPanel( } private fun surfaceSlot(pad: PadBridge, right: Boolean): View = FrameLayout(context).apply { + if (!deckControls) { + addView(StickView(context, pad, right), + FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)) + return@apply + } val slot = this fun show() { slot.removeAllViews() @@ -617,7 +633,7 @@ class DeckControlsPanel( } } - private class GamepadLayout(context: Context) : ViewGroup(context) { + private class GamepadLayout(context: Context, private val portraitDock: Boolean) : ViewGroup(context) { private val slots = LinkedHashMap<View, GamepadGeometry.Slot>() fun place(view: View, slot: GamepadGeometry.Slot) { @@ -625,7 +641,7 @@ class DeckControlsPanel( addView(view) } - private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density) + private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density, portraitDock) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val w = MeasureSpec.getSize(widthMeasureSpec) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt index 2a22c0a155..067ff06ecc 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt @@ -31,7 +31,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.Refresh -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt index 0bc1ccc472..452a6160cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt @@ -11,6 +11,7 @@ import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf @@ -23,6 +24,7 @@ import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect @@ -54,10 +56,21 @@ internal class GlideSource { var shape: Shape by mutableStateOf<Shape>(androidx.compose.ui.graphics.RectangleShape) var color by mutableStateOf(Color.Transparent) var width by mutableStateOf(2.dp) + var fillAlpha by mutableFloatStateOf(RING_FILL) val requester = androidx.compose.ui.focus.FocusRequester() } -internal class FocusGlide(val view: View) { +internal class FocusGlide(view: View?) { + private val deferredWindow = view == null + var view = view + private set + + fun accepts(view: View): Boolean { + // DropdownMenu recreates its popup view after closing. + if (this.view == null || deferredWindow && this.view !== view && host?.isAttached != true) this.view = view + return this.view === view + } + var host: LayoutCoordinates? = null val hot = mutableStateListOf<GlideSource>() var moves by mutableIntStateOf(0) @@ -107,15 +120,17 @@ internal fun Modifier.glideBorder( restColor: Color = Color.Transparent, hotWidth: Dp = 2.dp, restWidth: Dp = 1.dp, + hotFillAlpha: Float = RING_FILL, ): Modifier { val glide = LocalFocusGlide.current - if (glide == null || glide.view !== LocalView.current) { + if (glide == null || !glide.accepts(LocalView.current)) { return border(if (hot) hotWidth else restWidth, if (hot) hotColor else restColor, shape) } val src = remember { GlideSource() } src.shape = shape src.color = hotColor src.width = hotWidth + src.fillAlpha = hotFillAlpha DisposableEffect(glide, hot) { if (hot) glide.claim(src) onDispose { glide.release(src) } @@ -140,12 +155,36 @@ private const val REPEAT_MS = 180L private val FAR = 360.dp +@Composable +internal fun Modifier.focusGlide( + shape: Shape = Shape12, + color: Color = LocalPalette.current.signal, +): Modifier { + var focused by remember { mutableStateOf(false) } + return glideBorder(focused, shape, color, hotFillAlpha = 0f) + .onFocusChanged { focused = it.isFocused } +} + @Composable internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable () -> Unit) { val view = LocalView.current + val glide = remember(view) { FocusGlide(view) } + Box(modifier.focusGlideOverlay(glide)) { + CompositionLocalProvider(LocalFocusGlide provides glide) { content() } + } +} + +@Composable +internal fun FocusGlideWindow(content: @Composable (Modifier) -> Unit) { + val glide = remember { FocusGlide(null) } + val overlay = Modifier.focusGlideOverlay(glide) + CompositionLocalProvider(LocalFocusGlide provides glide) { content(overlay) } +} + +@Composable +private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { val density = LocalDensity.current val dir = LocalLayoutDirection.current - val glide = remember(view) { FocusGlide(view) } val edges = remember { List(4) { Animatable(0f) } } val corner = remember { Animatable(0f) } val solid = remember { Animatable(0f) } @@ -162,6 +201,8 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable val color by animateColorAsState(cur?.color ?: lastColor, Motion.tw(160), label = "glideColor") var width by remember { mutableStateOf(2.dp) } if (cur != null) width = cur.width + var fillAlpha by remember { mutableFloatStateOf(RING_FILL) } + if (cur != null) fillAlpha = cur.fillAlpha LaunchedEffect(glide, Motion.scale) { var shown: GlideSource? = null @@ -339,8 +380,7 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable } } - Box( - modifier + return this .onGloballyPositioned { glide.host = it } .drawWithContent { drawContent() @@ -359,15 +399,12 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable if (f < 0.99f) { drawRoundRect( color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh), - cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * RING_FILL, + cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha, ) drawRoundRect( color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh), cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a, ) } - }, - ) { - CompositionLocalProvider(LocalFocusGlide provides glide) { content() } - } + } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index b70f9bb5e3..62c6a862e5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -10,6 +10,8 @@ import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.snap import androidx.compose.animation.core.tween import androidx.compose.animation.scaleIn +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.scaleOut import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.rememberUpdatedState @@ -105,7 +107,7 @@ import java.io.File internal fun Pane( s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier, onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit, - onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, + onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit, ) { BoxWithConstraints(modifier = modifier) { CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) { @@ -138,12 +140,19 @@ internal fun Pane( before[0] = target val targetNow by rememberUpdatedState(target) val leave = if (Hops.linking) PageLeave.Link else PageLeave.Ordinary - LaunchedEffect(target) { Hops.linking = false } + LaunchedEffect(target) { + Hops.linking = false + PageSwipe.direction = 0 + } AnimatedContent( targetState = target, modifier = Modifier.onGloballyPositioned { paneAt[0] = it.positionInRoot() }, transitionSpec = { + val swipe = PageSwipe.direction when { + swipe != 0 -> (fadeIn(Motion.tw(260, 40)) + slideInHorizontally(Motion.tw(360)) { it * swipe / 8 }) + .togetherWith(fadeOut(Motion.tw(160)) + slideOutHorizontally(Motion.tw(220)) { -it * swipe / 8 }) + .apply { targetContentZIndex = 1f } targetState in origins -> (fadeIn(Motion.tw(120))) .togetherWith(fadeOut(Motion.tw(320, 80)) + scaleOut(Motion.tw(480), targetScale = 0.95f)) .apply { targetContentZIndex = 1f } @@ -162,7 +171,7 @@ internal fun Pane( label = "pane", ) { key -> val drawn = (if (page != null && key == s.pageKey) page else pages[key]) - ?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb) } + ?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) } val hopSink by androidx.compose.animation.core.animateFloatAsState( if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink", ) @@ -223,7 +232,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, L private fun Content( s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier, onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit, - onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, + onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit, ) { val colors = MaterialTheme.colorScheme val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp @@ -232,13 +241,13 @@ private fun Content( val padH = if (narrow) 16.dp else 22.dp val padV = if (narrow) 12.dp else 18.dp if (selected == "setup") { - Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) { - SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb) + Column(modifier = modifier.padding(horizontal = padH).padding(top = padV)) { + SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) } return } if (selected == "updates") { - UpdatesPage(s, a, modifier.padding(horizontal = padH, vertical = padV)) + UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV)) return } if (selected == "steam") { @@ -261,24 +270,12 @@ private fun Content( DesktopPage(s, a, modifier, onSelect) return } + if (selected == "android-apps" && s.isHomeApp) { + AndroidAppsPage(s, modifier, onAndroidAppClick) + return + } Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) { when { - selected == "android-apps" && s.isHomeApp -> { - Rise(0) { PageHeader(stringResource(R.string.content_android_apps)) { Chip(stringResource(R.string.content_apps_count, s.androidApps.size), ok = false) } } - if (s.androidApps.isEmpty()) Rise(3) { Note(stringResource(R.string.content_no_android_apps)) } - else Rise(3, Modifier.fillMaxWidth()) { - ArtGrid(s.androidApps.map { app -> - Tile( - app.label, - null, - null, - "android:${app.packageName}", - onClick = { onAndroidAppClick(app) }, - iconBitmap = app.icon, - ) - }) - } - } selected.startsWith("user:") -> { val app = UserAppsState.items.firstOrNull { "user:${it.key}" == selected } if (app == null) Note(stringResource(R.string.user_apps_gone)) else UserAppPage(app, s, a, onSelect) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index 7136ac7f07..b7ac8ee43a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -41,6 +41,9 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Apps @@ -81,12 +84,48 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.layout.boundsInParent import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onPlaced import com.droiddeck.launcher.core.PhantomProcessLimit internal val AttentionAmber = Color(0xFFFFB547) +@Composable +internal fun BottomBar( + s: FrontEndState, selected: String, + onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit, a: FrontEndActions, modifier: Modifier, +) { + val shown = Hops.railPreview ?: selected + val keys = navigationKeys(s) + val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() } + val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal) + val content = remember { arrayOfNulls<LayoutCoordinates>(1) } + Row(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface), verticalAlignment = Alignment.CenterVertically) { + BoxWithConstraints(Modifier.weight(1f)) { + val itemWidth = (maxWidth / keys.size).coerceIn(56.dp, 88.dp) + Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onPlaced { content[0] = it }) { + if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f) + Row(Modifier.selectableGroup().padding(vertical = 4.dp), horizontalArrangement = Arrangement.Center) { + NavigationItems(s, shown, compact = true, iconOnly = false, height = 56.dp, width = itemWidth, + place = { key -> Modifier.onGloballyPositioned { item -> content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }; Hops.railBounds[key] = item.boundsInRoot() } }, + onSelect = onSelect, onFocusSelect = onFocusSelect) + } + } + } + if (s.running != null) ResumeRailItem(s.running, compact = true, iconOnly = true, a.onResume) + } +} + +internal fun navigationKeys(s: FrontEndState) = buildList { + add("steam"); add("games") + if (s.gameStoresEnabled) add("stores") + add("desktop"); add("components") + if (s.isHomeApp) add("android-apps") + add("setup"); add("updates") +} + @Composable internal fun SideRail( s: FrontEndState, selected: String, @@ -95,8 +134,6 @@ internal fun SideRail( val colors = MaterialTheme.colorScheme val compact = LocalConfiguration.current.screenHeightDp < 420 val iconOnly = isNarrowScreen() - val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) || - PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp), @@ -105,38 +142,24 @@ internal fun SideRail( BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp) val shown = Hops.railPreview ?: selected - val keys = buildList { - add("steam"); add("games") - if (s.gameStoresEnabled) add("stores") - add("desktop") - add("components") - if (s.isHomeApp) add("android-apps") - add("setup"); add("updates") - } + val keys = navigationKeys(s) val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() } val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal) - var railAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) } - Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onGloballyPositioned { railAt = it.boundsInRoot().topLeft }) { - if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-railAt), tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f) + val content = remember { arrayOfNulls<LayoutCoordinates>(1) } + Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onPlaced { content[0] = it }) { + if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f) Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth().selectableGroup(), ) { val place: (String) -> Modifier = { key -> - Modifier.onGloballyPositioned { - bounds[key] = it.boundsInRoot() - Hops.railBounds[key] = it.boundsInRoot() + Modifier.onGloballyPositioned { item -> + content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) } + Hops.railBounds[key] = item.boundsInRoot() } } - RailItem(stringResource(R.string.rail_steam), Icons.Outlined.SportsEsports, "steam", shown == "steam", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("steam") }) { onSelect("steam") } - RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", shown == "games", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("games") }) { onSelect("games") } - if (s.gameStoresEnabled) RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", shown == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, place = place, onFocus = { onFocusSelect("stores") }) { onSelect("stores") } - RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", shown == "desktop", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") } - RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", shown == "components", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("components") }) { onSelect("components") } - if (s.isHomeApp) RailItem(stringResource(R.string.rail_apps), Icons.Outlined.Apps, "android-apps", shown == "android-apps", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") } - RailItem(stringResource(R.string.rail_setup), Icons.Outlined.Tune, "setup", shown == "setup", compact, iconOnly, fit, badge = setupNeedsAttention, place = place, onFocus = { onFocusSelect("setup") }) { onSelect("setup") } - RailItem(stringResource(R.string.rail_updates), Icons.Outlined.SystemUpdate, "updates", shown == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, place = place, onFocus = { onFocusSelect("updates") }) { onSelect("updates") } + NavigationItems(s, shown, compact, iconOnly, fit, if (iconOnly) 52.dp else 80.dp, place, onSelect, onFocusSelect) } } } @@ -151,8 +174,36 @@ internal fun SideRail( } @Composable +private fun NavigationItems( + s: FrontEndState, shown: String, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp, + place: (String) -> Modifier, onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit, +) { + val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) || + PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) + for (key in navigationKeys(s)) { + val (label, icon) = when (key) { + "steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports + "games" -> R.string.rail_games to Icons.Outlined.VideoLibrary + "stores" -> R.string.rail_stores to Icons.Outlined.LocalMall + "desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows + "components" -> R.string.rail_components to Icons.Outlined.Layers + "android-apps" -> R.string.rail_apps to Icons.Outlined.Apps + "setup" -> R.string.rail_setup to Icons.Outlined.Tune + else -> R.string.rail_updates to Icons.Outlined.SystemUpdate + } + key(key) { + RailItem(stringResource(label), icon, key, shown == key, compact, iconOnly, height, width, + badge = (key == "setup" && setupNeedsAttention) || (key == "updates" && s.updates.hasUpdate), + count = if (key == "stores") s.storeDownloadsActive else 0, + place = place, onFocus = { onFocusSelect(key) }) { onSelect(key) } + } + } +} + +@Composable +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) private fun RailItem( - label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp, + label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp, badge: Boolean = false, count: Int = 0, place: (String) -> Modifier = { Modifier }, @@ -181,6 +232,8 @@ private fun RailItem( Motion.tw(220), label = "railFill", ) val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "railScale") + val bringIntoView = remember { BringIntoViewRequester() } + LaunchedEffect(current) { if (current) bringIntoView.bringIntoView() } Box( contentAlignment = Alignment.Center, modifier = Modifier @@ -189,7 +242,8 @@ private fun RailItem( .then(place(key)) .landingPop(Hops.railLanded[key] ?: 0) .graphicsLayer { scaleX = scale; scaleY = scale } - .size(width = if (iconOnly) 52.dp else 80.dp, height = height) + .size(width = width, height = height) + .bringIntoViewRequester(bringIntoView) .clip(Shape14) .background(fill) .glideBorder(focused, Shape14, pal.signal) 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 b8ac10ba11..69abceb386 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.focusGroup import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.onFocusChanged import android.provider.Settings import android.view.Display @@ -100,6 +101,10 @@ class FrontEndState( val logsEnabled: Boolean, val vacDiagnostics: Boolean = false, val agentCommands: Boolean = false, + val clearCachedApps: Boolean = false, + val adbPaired: Boolean = false, + val backgroundAppLimit: Int = -1, + val memoryHud: String = "off", val steamGames: List<Library.SteamGame>, val steamGamesX64: Boolean = false, val emulators: List<Library.Emulator>, @@ -116,6 +121,8 @@ class FrontEndState( val isHomeApp: Boolean = false, val homeScreenEnabled: Boolean = false, val defaultHomeLabel: String? = null, + val integration: com.droiddeck.launcher.core.SteamIntegration.State = com.droiddeck.launcher.core.SteamIntegration.State(suggested = false), + val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null, val androidApps: List<HomeApp.LaunchableApp> = emptyList(), val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(), val packages: List<PackageRow>? = null, @@ -124,6 +131,7 @@ class FrontEndState( val packageStage: String? = null, val packagePercent: Int = -1, val sessionRunning: Boolean = false, + val battleNetInstalled: Boolean = false, val removalPending: Boolean = false, val runtimeActionsBlocked: Boolean = false, val backActionsInverted: Boolean = false, @@ -133,10 +141,12 @@ class FrontEndState( val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE, val showPhantomGate: Boolean = false, val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, + val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER, val launcherFullscreen: Boolean = true, val downloadSource: String = DownloadSource.MODE_AUTO, val downloadMirror: String = "", val downloadPrefix: String = "", + val downloadProxy: String = "", val animationsEnabled: Boolean = true, val launcherIcon: String = com.droiddeck.launcher.LauncherIcon.DARK, val gameStoresEnabled: Boolean = true, @@ -175,6 +185,7 @@ class FrontEndActions( val onEmulator: (Library.Emulator) -> Unit, val onFlatpakApp: (String, String) -> Unit = { _, _ -> }, val onUserApp: (com.droiddeck.launcher.runtime.UserApps.App) -> Unit = {}, + val onBattleNet: () -> Unit = {}, val onRom: (Library.Rom) -> Unit, val onResume: () -> Unit, val onSteamSettings: () -> Unit, @@ -199,6 +210,9 @@ class FrontEndActions( val onLogs: () -> Unit, val onVacDiagnostics: () -> Unit = {}, val onAgentCommands: () -> Unit = {}, + val onClearCachedApps: (Boolean) -> Unit = {}, + val onMemoryHud: (String) -> Unit = {}, + val onBackgroundAppLimit: (Int) -> Unit = {}, val onShareLogs: () -> Unit = {}, val onClearLogs: () -> Unit = {}, val onResetSettings: () -> Unit = {}, @@ -209,11 +223,13 @@ class FrontEndActions( val onAppScale: (Int) -> Unit = {}, val onLauncherIcon: (String) -> Unit = {}, val onOrientation: (Int) -> Unit = {}, + val onLauncherOrientation: (Int) -> Unit = {}, val onLauncherFullscreen: (Boolean) -> Unit = {}, val onAnimationsEnabled: (Boolean) -> Unit = {}, val onDownloadSource: (String) -> Unit = {}, val onDownloadMirror: (String) -> Unit = {}, val onDownloadPrefix: (String) -> Unit = {}, + val onDownloadProxy: (String) -> Unit = {}, val onGameStoresEnabled: (Boolean) -> Unit = {}, val onGameStoresSpeedTier: (String) -> Unit = {}, val onNavigated: () -> Unit = {}, @@ -223,6 +239,11 @@ class FrontEndActions( val onLibraryChanged: () -> Unit = {}, val onHomeApp: () -> Unit = {}, val onHomeScreen: (Boolean) -> Unit = {}, + val onSteamIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature?) -> Unit = {}, + val onDismissIntegration: () -> Unit = {}, + val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {}, + val onIntegrationAppInfo: () -> Unit = {}, + val onIntegrationLocation: () -> Unit = {}, val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> }, val onBackActionsInverted: (Boolean) -> Unit = {}, val onRefreshPhantomStatus: () -> Unit = {}, @@ -234,6 +255,8 @@ class FrontEndActions( val onCopyPhantomCommand: (Boolean) -> Unit = {}, val onDismissPhantomGate: () -> Unit = {}, val onStartWirelessAdbPairing: () -> Unit = {}, + val onStartPairingGuide: (Int?) -> Boolean = { false }, + val onShowPhantomGate: () -> Unit = {}, val onOpenNotificationSettings: () -> Unit = {}, val controller: ControllerActions? = null, val updates: UpdatesActions = UpdatesActions(), @@ -375,7 +398,12 @@ internal suspend fun focusSoon(target: () -> FocusRequester) { @Composable fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) { val frontFocus = remember { FrontFocus() } - CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus) } + androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) { + CompositionLocalProvider( + LocalFrontFocus provides frontFocus, + LocalNarrowPane provides (maxWidth < NarrowPaneWidth), + ) { FrontEndScreenBody(s, a, page, frontFocus) } + } } @OptIn(ExperimentalComposeUiApi::class) @@ -389,6 +417,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com "stores:downloads" -> { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" } "components" -> a.onComponents(true) "setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" } + "setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" } else -> selected = target } a.onNavigated() @@ -398,6 +427,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) } var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) } + var developerChoiceGuided by rememberSaveable { mutableStateOf(false) } var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) } var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) } val colors = MaterialTheme.colorScheme @@ -406,9 +436,36 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice val requestDeveloperOptions = { + developerChoiceGuided = false if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null) else showDeveloperDisplayChoice = true } + val openDeveloperOptionsOn: (Int?) -> Unit = { displayId -> + if (developerChoiceGuided) a.onStartWirelessAdbPairing() + if (!developerChoiceGuided || !a.onStartPairingGuide(displayId)) a.onOpenDeveloperOptions(displayId) + developerChoiceGuided = false + } + 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 + } + } + var applyingSavedPairing by remember { mutableStateOf(false) } + val fixPhantomLimit = { + if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing() + else if (!applyingSavedPairing) { + applyingSavedPairing = true + a.onSetPhantomProcessLimit(false) { error -> + applyingSavedPairing = false + if (error != null) startGuidedPairing() + } + } + } val requestWirelessAdbFix: (Boolean) -> Unit = { enabled -> wirelessAdbDesiredEnabled = enabled showWirelessAdbFix = true @@ -450,6 +507,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop" else -> s.pageKey ?: selected } + val railSelectionNow = androidx.compose.runtime.rememberUpdatedState(railSelection) var railPicks by remember { mutableStateOf(0) } val showRailPage: (String, Boolean) -> Unit = { key, focusContent -> if (key == "components") a.onComponents(focusContent) @@ -475,11 +533,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com val window = LocalWindowInfo.current val androidContext = androidx.compose.ui.platform.LocalContext.current var anyFocused by remember { mutableStateOf(false) } - Box( + androidx.compose.foundation.layout.BoxWithConstraints( modifier = Modifier.fillMaxSize().background(colors.background) .windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars) .onFocusChanged { anyFocused = it.hasFocus }, ) { + val bottomNavigation = maxHeight > maxWidth LaunchedEffect(processSettingsPageVisible) { if (processSettingsPageVisible) return@LaunchedEffect snapshotFlow { window.isWindowFocused }.first { it } @@ -516,10 +575,19 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com focusWithinFrames({ frontFocus.focusedRail == null && anyFocused }) { frontFocus.paneEntry() } } val paneFocus = Modifier - .focusProperties { enter = { frontFocus.paneEntry() } } + .focusProperties { + enter = { frontFocus.paneEntry() } + exit = { direction -> + if (bottomNavigation && direction == FocusDirection.Down) frontFocus.railFor(railSelection) + else FocusRequester.Default + } + } .focusGroup() val railFocus = Modifier - .focusProperties { enter = { frontFocus.railFor(railSelection) } } + .focusProperties { + enter = { frontFocus.railFor(railSelection) } + if (bottomNavigation) up = frontFocus.paneEntry() + } .focusGroup() LaunchedEffect(Hops.restore) { val r = Hops.restore ?: return@LaunchedEffect @@ -533,26 +601,41 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } var screenAt by remember { mutableStateOf(Offset.Zero) } CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) { - Row(modifier = Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }) { - SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight()) - Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line)) - Column(modifier = Modifier.weight(1f).fillMaxHeight()) { + LauncherLayout( + bottomNavigation, pal.line, + Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }, + navigation = { + if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus) + else SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight()) + }, + ) { Pane( - s, selected, a, page, Modifier.weight(1f).fillMaxWidth().then(paneFocus), { selected = it }, + s, selected, a, page, + Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }) { dir -> + val keys = navigationKeys(s) + val at = keys.indexOf(railSelectionNow.value) + if (at >= 0) keys.getOrNull(at + dir)?.let { key -> + PageSwipe.direction = dir + showRailPage(key, false) + } + }, + { selected = it }, onAndroidAppClick = { app -> if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null) else appToChooseDisplay = app }, onOpenDeveloperOptions = requestDeveloperOptions, onRequestWirelessAdb = requestWirelessAdbFix, + onPairWirelessDebugging = startGuidedPairing, ) - } } } FlightsLayer(screenAt) GamesDialogs(a, s.steamGames) + StoreTheme(com.droiddeck.launcher.stores.Store.XBOX) { XboxStoreDialogs() } com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } } + com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } } StepsLayer(screenAt) appToChooseDisplay?.let { app -> @@ -577,10 +660,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com status = s.phantomProcessStatus, onDismiss = a.onDismissPhantomGate, onOpenDeveloperOptions = requestDeveloperOptions, - onFixWithWirelessDebugging = { - a.onStartWirelessAdbPairing() - requestDeveloperOptions() - }, + applyingSavedPairing = applyingSavedPairing, + onFixWithWirelessDebugging = fixPhantomLimit, onEnterAddressManually = { requestWirelessAdbFix(false) }, onCopyCommand = { a.onCopyPhantomCommand(false) }, onOpenNotificationSettings = a.onOpenNotificationSettings, @@ -606,13 +687,16 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com }, onMainScreen = { showDeveloperDisplayChoice = false - a.onOpenDeveloperOptions(null) + openDeveloperOptionsOn(null) }, onSecondaryScreen = { displayId -> showDeveloperDisplayChoice = false - a.onOpenDeveloperOptions(displayId) + openDeveloperOptionsOn(displayId) + }, + onDismiss = { + showDeveloperDisplayChoice = false + developerChoiceGuided = false }, - onDismiss = { showDeveloperDisplayChoice = false }, ) } } 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 8f92dbbc6a..7540949132 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -21,6 +21,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row @@ -90,6 +91,7 @@ private const val LAUNCHER_TAB = 2 internal object SetupTabs { var openLauncher = false + var openOverview = false } private const val GLASSES_TAB = 5 @@ -139,6 +141,7 @@ internal fun SetupPanel( a: FrontEndActions, onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, + onPairWirelessDebugging: () -> Unit, ) { val host = rememberMenuHost() val ctx = LocalContext.current @@ -174,6 +177,7 @@ internal fun SetupPanel( var showLimitDetails by rememberSaveable { mutableStateOf(false) } var editSgdbKey by remember { mutableStateOf(false) } var editDownloadPrefix by remember { mutableStateOf(false) } + var editDownloadProxy by remember { mutableStateOf(false) } if (editSgdbKey) SgdbKeyDialog(s.sgdbUserKey, onSave = { a.onSgdbKey(it); editSgdbKey = false }, onDismiss = { editSgdbKey = false }) if (editDownloadPrefix) TextEntryDialog( @@ -181,9 +185,15 @@ internal fun SetupPanel( onDismiss = { editDownloadPrefix = false }, onSave = { a.onDownloadPrefix(it); editDownloadPrefix = false }, ) + if (editDownloadProxy) TextEntryDialog( + stringResource(R.string.setup_download_proxy), s.downloadProxy, + onDismiss = { editDownloadProxy = false }, + onSave = { a.onDownloadProxy(it); editDownloadProxy = false }, + ) val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses)) var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) } SetupTabs.openLauncher = false + if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false } val chipFocus = remember { List(tabs.size) { FocusRequester() } } var tabTurned by remember { mutableStateOf(false) } val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true } @@ -194,13 +204,18 @@ internal fun SetupPanel( tab = STORAGE_TAB } } + LaunchedEffect(Unit) { + while (true) { + kotlinx.coroutines.delay(2_000) + a.onRefreshPhantomStatus() + } + } LaunchedEffect(tab) { if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) { androidx.compose.runtime.withFrameNanos { } runCatching { chipFocus[tab].requestFocus() } } } - val wide = !LocalNarrowPane.current val runtimeOk = s.ready && !s.busy && !s.removalPending val checks = listOf(gpuOk, runtimeOk, !limitBlocks, signedIn) val passing = checks.count { it } @@ -271,7 +286,7 @@ internal fun SetupPanel( }, divider = divider && !showLimitDetails, ) { - if (limitBlocks) PrimaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_fix_it), compact = true) { showLimitDetails = !showLimitDetails } + if (limitBlocks) PrimaryButton(stringResource(R.string.setup_fix_it), compact = true, onClick = a.onShowPhantomGate) else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) { SecondaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_details), compact = true) { showLimitDetails = !showLimitDetails } } @@ -284,11 +299,7 @@ internal fun SetupPanel( fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp), ) Actions { - if (limitBlocks) { - PrimaryButton(stringResource(R.string.setup_dev_options), compact = true, onClick = onOpenDeveloperOptions) - SecondaryButton(stringResource(R.string.setup_use_wireless), compact = true, enabled = !processLimitBusy) { setProcessLimit(false) } - SecondaryButton(stringResource(R.string.setup_check_again), compact = true, onClick = a.onRefreshPhantomStatus) - } else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) { + if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) { SecondaryButton(stringResource(R.string.setup_limit_turn_on), compact = true, enabled = !processLimitBusy) { setProcessLimit(true) } } } @@ -335,6 +346,7 @@ internal fun SetupPanel( } } SettingsGroup(stringResource(R.string.setup_runtime)) { runtimeCheck(false) } + SteamIntegrationGroup(s.integration, s.integrationFocus, a.onIntegration, a.onIntegrationAppInfo, a.onIntegrationLocation) } 1 -> { val controller = s.controller @@ -392,7 +404,12 @@ internal fun SetupPanel( ActionRow(stringResource(R.string.setup_default_home), s.defaultHomeLabel ?: stringResource(R.string.setup_choose_home), stringResource(R.string.setup_choose), a.onHomeApp) } ChoiceRow( - host, "orientation", stringResource(R.string.setup_orientation), null, + host, "launcher-orientation", stringResource(R.string.setup_launcher_orientation), null, + com.droiddeck.launcher.core.AppUiPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }, + s.launcherOrientation, onPick = a.onLauncherOrientation, + ) + ChoiceRow( + host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint), SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }, s.orientation, onPick = a.onOrientation, ) @@ -439,12 +456,20 @@ internal fun SetupPanel( onClick = { editDownloadPrefix = true }, ) } + ActionRow( + stringResource(R.string.setup_download_proxy), + s.downloadProxy.takeIf { it.isNotEmpty() }, + stringResource(R.string.mode_sgdb_edit), + onClick = { editDownloadProxy = true }, + ) } } - if (wide) Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Top) { - Column(Modifier.weight(1f)) { look() } - Column(Modifier.weight(1f)) { device(); art(); download() } - } else { look(); device(); art(); download() } + BoxWithConstraints(Modifier.fillMaxWidth()) { + if (maxWidth >= 840.dp && !LocalNarrowPane.current) Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Top) { + Column(Modifier.weight(1f)) { look() } + Column(Modifier.weight(1f)) { device(); art(); download() } + } else Column { look(); device(); art(); download() } + } } STORAGE_TAB -> StoragePanel(s, a) 4 -> { @@ -458,6 +483,38 @@ internal fun SetupPanel( ActionRow(stringResource(R.string.setup_reset_settings), stringResource(R.string.setup_reset_settings_hint), stringResource(R.string.setup_reset_settings_button), a.onResetSettings) } + SettingsGroup(stringResource(R.string.setup_group_memory)) { + ToggleRow( + host, "clear-cached-apps", stringResource(R.string.setup_clear_cached), + stringResource(if (s.adbPaired) R.string.setup_clear_cached_hint else R.string.setup_clear_cached_unpaired), + s.clearCachedApps, enabled = s.adbPaired || s.clearCachedApps, + ) { a.onClearCachedApps(it) } + ChoiceRow( + host, "background-app-limit", stringResource(R.string.setup_bg_limit), + stringResource(if (s.adbPaired) R.string.setup_bg_limit_hint else R.string.setup_clear_cached_unpaired), + listOf( + com.droiddeck.launcher.core.BackgroundAppLimit.OFF to stringResource(R.string.game_env_off), + 4 to stringResource(R.string.setup_bg_limit_4), + 1 to stringResource(R.string.setup_bg_limit_1), + 0 to stringResource(R.string.setup_bg_limit_0), + ), + s.backgroundAppLimit, enabled = s.adbPaired || s.backgroundAppLimit != com.droiddeck.launcher.core.BackgroundAppLimit.OFF, + onPick = a.onBackgroundAppLimit, + ) + ChoiceRow( + host, "memory-hud", stringResource(R.string.setup_memory_hud), stringResource(R.string.setup_memory_hud_hint), + listOf( + com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_OFF to stringResource(R.string.game_env_off), + com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_SIMPLE to stringResource(R.string.setup_memory_hud_simple), + com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_ADVANCED to stringResource(R.string.setup_memory_hud_advanced), + ), + s.memoryHud, onPick = a.onMemoryHud, + ) + if (!s.adbPaired) ActionRow( + stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint), + stringResource(R.string.setup_adb_pair_button), onPairWirelessDebugging, + ) + } } GLASSES_TAB -> GlassesSetupPanel() } 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 fb7d204852..0455366d26 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -186,7 +186,7 @@ internal fun PrimaryButton( .clip(Shape12) .background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant))) .then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, Shape12)) - .then(if (hot) Modifier.border(2.dp, pal.signal, Shape12) else Modifier) + .glideBorder(hot, Shape12, pal.signal, hotFillAlpha = 0f) .hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) { placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) } onClick() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 50b85c7e35..5350d2afa5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -56,6 +56,9 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.boundsInRoot import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.layout.positionInRoot +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag @@ -84,6 +87,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.StoreLanguage import com.droiddeck.launcher.stores.StoreSizes import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.battlenet.BattleNetInstall import com.droiddeck.launcher.stores.download.DownloadQueue import com.droiddeck.launcher.stores.download.DownloadState import com.droiddeck.launcher.stores.formatBytes @@ -215,6 +219,9 @@ internal fun GameDetail( } } if (StoresMotion.heroLands) hero() else Rise(1) { hero() } + if (!s.shortcutPicker) Rise(2) { + GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game, Modifier.padding(top = 6.dp)) + } if (tab != null) Rise(2) { Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { val labels = tabs.map { t -> @@ -265,13 +272,15 @@ private fun GameHero( ) } Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.55f to colors.background.copy(alpha = 0.58f), 1f to Color.Transparent))) + var scoresWidth by remember { mutableStateOf(0) } if (scores != null) { Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0.45f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f)))) - HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp)) + HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp).onSizeChanged { scoresWidth = it.width }) } + val scoresSpace = with(LocalDensity.current) { if (scores != null && scoresWidth > 0) scoresWidth.toDp() + 16.dp else 0.dp } Column( verticalArrangement = Arrangement.spacedBy(6.dp), - modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp), + modifier = Modifier.align(Alignment.BottomStart).padding(start = 22.dp, end = 22.dp + scoresSpace, top = 18.dp, bottom = 18.dp), content = content, ) Box(Modifier.align(Alignment.TopEnd).padding(12.dp), content = corner) @@ -317,7 +326,7 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) { } @Composable -private fun GameActions( +internal fun GameActions( store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?, s: FrontEndState, a: FrontEndActions, leadOn: Modifier, ) { @@ -326,22 +335,14 @@ private fun GameActions( val rawDownload = storeKey?.let { StoresState.download(it) } val download = rawDownload?.takeIf { it.isActive } val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED } + val cloud = game?.library == Library.XBOX_CLOUD && installed == null Actions { when { s.shortcutPicker && game != null -> { PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) } FileButtons(game, a) } - game?.library == Library.XBOX_CLOUD -> { - val cloudId = game.storeId.orEmpty() - XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn) - if (download != null) ActionChip(downloadLabel(download), ok = false) - else if (item?.installable == true) SecondaryButton( - if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install), - ) { StoresState.requestInstall(ctx, item) } - XboxLibraryButton(cloudId, item) - } - game != null || installed != null -> { + !cloud && (game != null || installed != null) -> { val gone = storeKey?.let { StoresState.uninstalling[it] } val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id) PrimaryButton( @@ -364,6 +365,19 @@ private fun GameActions( } SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) } } + if (store == Store.BATTLENET) { + if (installed != null && id != null) { + LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) } + if (download != null) { + ActionChip(downloadLabel(download), ok = false) + if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) } + else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) } + } else if (BattleNetInstall.updates[id] == true) { + SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) } + } + } + SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() } + } } download != null -> { ActionChip(downloadLabel(download), ok = false) @@ -378,6 +392,20 @@ private fun GameActions( } ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) } } + cloud -> { + val cloudId = game.storeId.orEmpty() + XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn) + if (item?.installable == true && item.xboxPc) { + SecondaryButton( + if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install) + else if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) + else stringResource(R.string.stores_install), + ) { StoresState.requestInstall(ctx, item) } + } + if (item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) } + XboxLibraryButton(cloudId, item) + } + store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> { XboxStreamButton(item.id, item.title, main = true, modifier = leadOn) XboxLibraryButton(item.id, item) @@ -397,9 +425,17 @@ private fun GameActions( } if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) } } + item != null && item.store == Store.ITCH && item.isFree -> { + InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } + SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) } + } item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } } + if (cloud && (download != null || failed != null)) { + XboxStreamButton(game.storeId.orEmpty(), game.name) + XboxLibraryButton(game.storeId.orEmpty(), item) + } BusyChip(s) } } @@ -517,6 +553,7 @@ private fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, la private fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) { val ctx = LocalContext.current val colors = MaterialTheme.colorScheme + if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id && installed?.sidecar?.id?.let(BattleNetInstall::product) == null) return if (installed != null) { val key = installed.key val gone = StoresState.uninstalling[key] @@ -592,7 +629,13 @@ private fun AboutTab(developer: String, publisher: String, releaseDate: String, val parts = listOf(developer, publisher, com.droiddeck.launcher.stores.GameFacts.releaseLabel(releaseDate).orEmpty()).filter { it.isNotBlank() }.distinct() Text(parts.joinToString(" · "), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.readable()) } - if (description.isNotBlank()) StoreAbout(description, AboutHeight, Modifier.fillMaxWidth()) + if (description.isNotBlank()) { + val floor = LocalDetailFloor.current + val density = LocalDensity.current + var room by remember { mutableStateOf(AboutHeight) } + val fill = Modifier.onGloballyPositioned { c -> room = maxOf(AboutHeight, with(density) { (floor() - c.positionInRoot().y).toDp() - 14.dp }) } + StoreAbout(description, room, Modifier.fillMaxWidth().then(fill)) + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt index f8f50a5ebc..8055f08649 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt @@ -101,7 +101,8 @@ internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", on LaunchedEffect(Unit) { runCatching { withContext(Dispatchers.IO) { - GameEnvironmentStore.read(context) to Library.steamGames(context).map { it.appId.toString() to it.name } + GameEnvironmentStore.read(context) to Library.steamGames(context).map { it.appId.toString() to it.name } + + listOfNotNull(com.droiddeck.launcher.runtime.BattleNet.profile(context)) } }.onSuccess { (settings, installed) -> config = settings; games = installed } .onFailure { error = true } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt new file mode 100644 index 0000000000..78384480a4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt @@ -0,0 +1,90 @@ +package com.droiddeck.launcher.ui + +import androidx.annotation.StringRes +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.OpenInNew +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.Library +import java.net.URLEncoder + +internal data class GameResource(@StringRes val label: Int, val url: String, @StringRes val detail: Int? = null) + +internal fun gameResources(title: String, game: Library.SteamGame?): List<GameResource> { + if (title.isBlank()) return emptyList() + val query = URLEncoder.encode(title.trim(), "UTF-8").replace("+", "%20") + val steamId = game?.takeIf { Library.fromSteamClient(it) && it.appId > 0 }?.appId + return buildList { + add(GameResource(R.string.game_resource_pcgw, "https://www.pcgamingwiki.com/w/index.php?search=$query")) + add(GameResource(R.string.game_resource_guides, "https://gamefaqs.gamespot.com/search?game=$query")) + if (steamId != null) { + add(GameResource(R.string.game_resource_protondb, "https://www.protondb.com/app/$steamId", R.string.game_resource_protondb_detail)) + add(GameResource(R.string.game_resource_steam_cloud, "https://store.steampowered.com/account/remotestorageapp/?appid=$steamId", R.string.game_resource_steam_cloud_detail)) + } + add(GameResource(R.string.game_resource_search, "https://www.google.com/search?q=$query")) + } +} + +@Composable +@OptIn(ExperimentalLayoutApi::class) +internal fun GameResourcesRow(title: String, game: Library.SteamGame?, modifier: Modifier = Modifier) { + val links = remember(title, game) { gameResources(title, game) } + if (links.isEmpty()) return + FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { + links.forEach { ResourceLink(it) } + } +} + +@Composable +private fun ResourceLink(link: GameResource) { + val ctx = LocalContext.current + val pal = LocalPalette.current + val source = remember { MutableInteractionSource() } + val hot = rememberHot(source) + val shape = RoundedCornerShape(8.dp) + val label = stringResource(link.label) + val description = listOfNotNull(label, link.detail?.let { stringResource(it) }, stringResource(R.string.game_resources_browser)).joinToString(". ") + val open = { openUrl(ctx, link.url) } + val tint = if (hot) pal.signal else pal.onSurfaceVariant + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp), + modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 44.dp).clip(shape) + .background(if (hot) pal.signal.copy(alpha = 0.08f) else Color.Transparent) + .glideBorder(hot, shape, pal.signal, restColor = Color.Transparent) + .semantics { contentDescription = description } + .hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = open) + .controllerConfirm(onClick = open).padding(horizontal = 8.dp), + ) { + Text(label, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = tint, maxLines = 1) + Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = tint.copy(alpha = 0.65f), modifier = Modifier.size(11.dp)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GamepadGeometry.kt b/app/src/main/java/com/droiddeck/launcher/ui/GamepadGeometry.kt index 466d57aecd..2b369c20aa 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GamepadGeometry.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GamepadGeometry.kt @@ -8,6 +8,7 @@ object GamepadGeometry { LEFT_OUTER_SHOULDER, LEFT_INNER_SHOULDER, RIGHT_INNER_SHOULDER, RIGHT_OUTER_SHOULDER, VIEW, STEAM, QAM, MENU, PANELS, + L4, L5, R5, R4, } data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) { @@ -25,8 +26,11 @@ object GamepadGeometry { fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f - fun layout(w: Float, h: Float, density: Float): Map<Slot, Box> { + fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map<Slot, Box> { if (w <= 0f || h <= 0f) return emptyMap() + if (portraitDock && h >= w * 0.9f && w >= 300 * density && h >= 360 * density) { + return portraitLayout(w, h, density) + } val pad = 8 * density val buttonH = 40 * density val rowButton = 64 * density @@ -67,7 +71,7 @@ object GamepadGeometry { } middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f) } else { - val side = min(w * 0.5f, h * 0.70f) + val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f) val main = side * 0.62f val second = side * 0.46f val secondCy = h - side * 0.97f @@ -87,4 +91,39 @@ object GamepadGeometry { } return boxes } + + private fun portraitLayout(w: Float, h: Float, density: Float): Map<Slot, Box> { + val pad = 8 * density + val gap = 8 * density + val buttonH = 44 * density + val scale = min(1f, (h - 2 * pad - 4 * gap - 3 * buttonH) / (w * 0.7f)) + val main = w * 0.4f * scale + val second = w * 0.3f * scale + val mainY = h - pad - main / 2f + val secondY = mainY - main / 2f - gap - second / 2f + val shoulderY = secondY - second / 2f - gap - buttonH / 2f + val boxes = linkedMapOf( + Slot.LEFT_MAIN to Box(w * 0.25f, mainY, main, main), + Slot.RIGHT_MAIN to Box(w * 0.75f, mainY, main, main), + Slot.LEFT_SECOND to Box(w * 0.25f, secondY, second, second), + Slot.RIGHT_SECOND to Box(w * 0.75f, secondY, second, second), + ) + val utilityW = (w - 2 * pad - 3 * gap) / 4f + for ((i, slot) in middle.withIndex()) { + boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), pad + buttonH / 2f, utilityW, buttonH) + } + val gripTop = pad + buttonH + gap + val gripH = min(64 * density, shoulderY - buttonH / 2f - gap - gripTop) + for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) { + boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), gripTop + gripH / 2f, utilityW, gripH) + } + val panelsW = min(112 * density, w * 0.22f) + val shoulderW = (w - 2 * pad - 4 * gap - panelsW) / 4f + boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH) + boxes[Slot.LEFT_OUTER_SHOULDER] = Box(pad + shoulderW / 2f, shoulderY, shoulderW, buttonH) + boxes[Slot.LEFT_INNER_SHOULDER] = Box(pad + shoulderW * 1.5f + gap, shoulderY, shoulderW, buttonH) + boxes[Slot.RIGHT_INNER_SHOULDER] = Box(w - pad - shoulderW * 1.5f - gap, shoulderY, shoulderW, buttonH) + boxes[Slot.RIGHT_OUTER_SHOULDER] = Box(w - pad - shoulderW / 2f, shoulderY, shoulderW, buttonH) + return boxes + } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GlassesCalibrationControls.kt b/app/src/main/java/com/droiddeck/launcher/ui/GlassesCalibrationControls.kt index 1f53c272dc..c2dde844e7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GlassesCalibrationControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GlassesCalibrationControls.kt @@ -1,7 +1,9 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.ui.Modifier import androidx.compose.foundation.layout.Column -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -32,8 +34,8 @@ internal fun GlassesCalibrationControls( onDismissRequest = { reset = false }, title = { Text(stringResource(R.string.glasses_calibration_reset)) }, text = { Text(stringResource(R.string.glasses_calibration_reset_hint)) }, - confirmButton = { TextButton(onClick = { onReset(); reset = false }) { Text(stringResource(R.string.glasses_calibration_reset_button)) } }, - dismissButton = { TextButton(onClick = { reset = false }) { Text(stringResource(R.string.common_cancel)) } }, + confirmButton = { TextButton(onClick = { onReset(); reset = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.glasses_calibration_reset_button)) } }, + dismissButton = { TextButton(onClick = { reset = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) if (shown) AlertDialog( onDismissRequest = { onCancel(); shown = false }, @@ -57,8 +59,8 @@ internal fun GlassesCalibrationControls( if (!state.running) TextButton(onClick = { if (state.phase == CalibrationPhase.SAVED) { onDone(); onCancel(); shown = false } else onStart() - }) { Text(stringResource(if (state.phase == CalibrationPhase.SAVED) R.string.glasses_calibration_done else R.string.glasses_calibration_start)) } + }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(if (state.phase == CalibrationPhase.SAVED) R.string.glasses_calibration_done else R.string.glasses_calibration_start)) } }, - dismissButton = { TextButton(onClick = { onCancel(); shown = false }) { Text(stringResource(R.string.common_cancel)) } }, + dismissButton = { TextButton(onClick = { onCancel(); shown = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt index 92e0aef3bc..877cad9240 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt @@ -347,6 +347,7 @@ internal fun GlassesCornerButton(slot: Int, tint: Int, opacity: Int, onClick: () .clip(CircleShape) .background(fill) .border(1.5.dp, line, CircleShape) + .focusGlide(CircleShape) .clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick) .testTag("glasses-button"), ) { @@ -382,6 +383,7 @@ private fun GlassesRecenterAction(label: String, tag: String, tint: Int, opacity .clip(shape) .background(fill) .border(1.5.dp, line, shape) + .focusGlide(shape) .clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick) .padding(horizontal = 18.dp) .testTag(tag), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt b/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt new file mode 100644 index 0000000000..dd362fe528 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.rememberScrollState +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.AlertDialogDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpOffset +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupPositionProvider +import androidx.compose.ui.window.PopupProperties + +@Composable +internal fun GlideDialog( + onDismissRequest: () -> Unit, + properties: DialogProperties = DialogProperties(), + content: @Composable () -> Unit, +) { + Dialog(onDismissRequest, properties) { FocusGlideHost(content = content) } +} + +@Composable +internal fun GlidePopup( + popupPositionProvider: PopupPositionProvider, + onDismissRequest: (() -> Unit)? = null, + properties: PopupProperties = PopupProperties(), + content: @Composable () -> Unit, +) { + Popup(popupPositionProvider, onDismissRequest, properties) { FocusGlideHost(content = content) } +} + +@Composable +internal fun GlideAlertDialog( + onDismissRequest: () -> Unit, + confirmButton: @Composable () -> Unit, + modifier: Modifier = Modifier, + dismissButton: (@Composable () -> Unit)? = null, + icon: (@Composable () -> Unit)? = null, + title: (@Composable () -> Unit)? = null, + text: (@Composable () -> Unit)? = null, + shape: Shape = AlertDialogDefaults.shape, + containerColor: Color = AlertDialogDefaults.containerColor, + iconContentColor: Color = AlertDialogDefaults.iconContentColor, + titleContentColor: Color = AlertDialogDefaults.titleContentColor, + textContentColor: Color = AlertDialogDefaults.textContentColor, + tonalElevation: Dp = AlertDialogDefaults.TonalElevation, + properties: DialogProperties = DialogProperties(), +) { + FocusGlideWindow { overlay -> + AlertDialog( + onDismissRequest, confirmButton, modifier.then(overlay), dismissButton, icon, title, text, + shape, containerColor, iconContentColor, titleContentColor, textContentColor, tonalElevation, properties, + ) + } +} + +@Composable +internal fun GlideDropdownMenu( + expanded: Boolean, + onDismissRequest: () -> Unit, + modifier: Modifier = Modifier, + offset: DpOffset = DpOffset.Zero, + scrollState: ScrollState = rememberScrollState(), + properties: PopupProperties = PopupProperties(focusable = true), + content: @Composable ColumnScope.() -> Unit, +) { + FocusGlideWindow { overlay -> + DropdownMenu(expanded, onDismissRequest, modifier.then(overlay), offset, scrollState, properties, content) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt index 8474050c34..fddb98c60b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt @@ -48,7 +48,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.AutoAwesome import androidx.compose.material.icons.outlined.Memory import androidx.compose.material.icons.outlined.Tune -import androidx.compose.material3.DropdownMenu +import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon diff --git a/app/src/main/java/com/droiddeck/launcher/ui/HandCameraUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/HandCameraUi.kt index 3aae52a767..50f6a9d458 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/HandCameraUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/HandCameraUi.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.shape.CircleShape import com.droiddeck.launcher.core.AddonPack import android.Manifest import android.content.Intent @@ -28,7 +29,7 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.RadioButton @@ -63,7 +64,7 @@ import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import androidx.compose.ui.window.Dialog +import com.droiddeck.launcher.ui.GlideDialog as Dialog import androidx.compose.ui.window.DialogProperties import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver @@ -129,7 +130,7 @@ internal fun HandCameraPrompt(sides: Set<String>, onAllow: (String?) -> Unit, on Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)) - .selectable(side == id, role = Role.RadioButton) { side = id } + .focusGlide(RoundedCornerShape(8.dp)).selectable(side == id, role = Role.RadioButton) { side = id } .testTag("hand-camera-$id") .padding(vertical = 4.dp), ) { @@ -144,12 +145,12 @@ internal fun HandCameraPrompt(sides: Set<String>, onAllow: (String?) -> Unit, on } }, confirmButton = { - TextButton(onClick = { onAllow(if (choose) side else null) }, modifier = Modifier.testTag("hand-camera-allow")) { + TextButton(onClick = { onAllow(if (choose) side else null) }, modifier = Modifier.testTag("hand-camera-allow").focusGlide(CircleShape)) { Text(stringResource(R.string.hand_camera_allow)) } }, dismissButton = { - TextButton(onClick = onNotNow, modifier = Modifier.testTag("hand-camera-not-now")) { Text(stringResource(R.string.hand_camera_not_now)) } + TextButton(onClick = onNotNow, modifier = Modifier.testTag("hand-camera-not-now").focusGlide(CircleShape)) { Text(stringResource(R.string.hand_camera_not_now)) } }, ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ItchBuildPicker.kt b/app/src/main/java/com/droiddeck/launcher/ui/ItchBuildPicker.kt new file mode 100644 index 0000000000..09c6d08f32 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ItchBuildPicker.kt @@ -0,0 +1,117 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.key +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.formatBytes +import com.droiddeck.launcher.stores.itch.ItchApi +import com.droiddeck.launcher.stores.itch.ItchAuth +import com.droiddeck.launcher.stores.itch.ItchBuild +import com.droiddeck.launcher.stores.itch.ItchGame +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +private class BuildList(val gameId: String, val builds: List<ItchBuild>) + +@Composable +internal fun ItchBuildPicker(item: CatalogItem, onDismiss: () -> Unit) { + val ctx = LocalContext.current + val app = ctx.applicationContext + val colors = MaterialTheme.colorScheme + val shown = rememberShown(onDismiss) + val close = { shown.targetState = false } + var loaded by remember(item) { mutableStateOf<BuildList?>(null) } + var failed by remember(item) { mutableStateOf(false) } + + val install: (BuildList, ItchBuild) -> Unit = install@{ list, build -> + if (!shown.targetState) return@install + val tagged = item.copy( + extra = item.extra + mapOf("gameId" to list.gameId, "uploadId" to build.uploadId), + sizeBytes = build.size.takeIf { it > 0 } ?: item.sizeBytes, + ) + close() + StoresState.requestInstall(ctx, tagged) + } + + LaunchedEffect(item) { + val result = withContext(Dispatchers.IO) { + val key = ItchAuth.key(app) + val id = if (key.isBlank()) null else ItchGame.resolveId(item) + val uploads = id?.let { ItchApi.uploads(key, it, item.extra["downloadKeyId"].orEmpty()) } + if (id == null || uploads == null) null else BuildList(id, ItchGame.builds(uploads)) + } + if (result == null) { failed = true; return@LaunchedEffect } + loaded = result + if (shown.targetState) result.builds.singleOrNull()?.takeIf { it.installable }?.let { install(result, it) } + } + + AppDialog(shown, close, "itchBuilds", wide = false, maxWidth = 460.dp) { + DialogTitleRow(stringResource(R.string.stores_itch_pick_title), close) + Text(item.title, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + val list = loaded + when { + failed -> Text(stringResource(R.string.stores_itch_pick_failed), fontSize = 13.sp, color = colors.onSurfaceVariant) + list == null -> LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 8.dp)) + list.builds.isEmpty() -> Text(stringResource(R.string.stores_itch_pick_none), fontSize = 13.sp, color = colors.onSurfaceVariant) + else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { + for (build in list.builds) key(build.uploadId) { BuildRow(item, build) { install(list, build) } } + } + } + } +} + +@Composable +private fun BuildRow(item: CatalogItem, build: ItchBuild, onInstall: () -> Unit) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val linux = "linux" in build.platforms && !build.installable + val detail = listOfNotNull( + build.platforms.map { platformName(it) }.joinToString(", "), + build.size.takeIf { it > 0 }?.let { formatBytes(it) }, + build.updatedAt.take(10).takeIf { it.isNotBlank() }, + if (build.demo) stringResource(R.string.stores_itch_build_demo) else null, + ).joinToString(" · ") + ListRow(enabled = !linux, onClick = { if (build.installable) onInstall() else openStoreUrl(ctx, item) }) { + Column(Modifier.weight(1f)) { + Text(build.filename.ifBlank { item.title }, fontSize = 13.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(detail, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + val label = when { + build.installable -> stringResource(R.string.stores_install) + linux -> stringResource(R.string.stores_itch_build_linux_soon) + else -> stringResource(R.string.stores_itch_build_open) + } + Text(label, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1) + } +} + +@Composable +private fun platformName(platform: String): String = stringResource( + when (platform) { + "windows" -> R.string.stores_itch_build_windows + "linux" -> R.string.stores_itch_build_linux + "osx" -> R.string.stores_itch_build_macos + "android" -> R.string.stores_itch_build_android + else -> R.string.stores_itch_build_web + }, +) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ItchKeyDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ItchKeyDialog.kt index cfeeeb8c41..0a0f0a813f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ItchKeyDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ItchKeyDialog.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.shape.CircleShape import android.content.ClipboardManager import android.content.Context import android.content.Intent @@ -9,7 +10,7 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -91,7 +92,7 @@ internal fun ItchKeyDialog(onDismiss: () -> Unit) { Row(horizontalArrangement = Arrangement.Start) { TextButton(onClick = { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ItchApi.KEYS_PAGE))) - }) { Text(stringResource(R.string.stores_itch_get_key)) } + }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.stores_itch_get_key)) } } if (rejected) { Spacer(Modifier.height(8.dp)) @@ -104,12 +105,12 @@ internal fun ItchKeyDialog(onDismiss: () -> Unit) { } }, confirmButton = { - TextButton(enabled = key.isNotBlank() && !busy, onClick = { submit() }) { + TextButton(enabled = key.isNotBlank() && !busy, onClick = { submit() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.game_env_save)) } }, dismissButton = { - TextButton(enabled = !busy, onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } + TextButton(enabled = !busy, onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/Layout.kt b/app/src/main/java/com/droiddeck/launcher/ui/Layout.kt index 9777ee83b2..594492f840 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/Layout.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/Layout.kt @@ -2,6 +2,12 @@ package com.droiddeck.launcher.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.compositionLocalOf +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.unit.Constraints import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.dp @@ -13,3 +19,38 @@ val LocalNarrowPane = compositionLocalOf { false } @Composable internal fun isNarrowScreen(): Boolean = LocalConfiguration.current.screenWidthDp < 600 +@Composable +internal fun LauncherLayout( + bottomNavigation: Boolean, divider: Color, modifier: Modifier = Modifier, + navigation: @Composable () -> Unit, content: @Composable () -> Unit, +) { + Layout(modifier = modifier, content = { + Box { content() } + Box(Modifier.background(divider)) + Box { navigation() } + }) { children, constraints -> + val width = constraints.maxWidth + val height = constraints.maxHeight + val line = 1.dp.roundToPx() + val nav = children[2].measure(Constraints( + minWidth = if (bottomNavigation) width else 0, maxWidth = width, + minHeight = if (bottomNavigation) 0 else height, maxHeight = height, + )) + val contentWidth = if (bottomNavigation) width else (width - nav.width - line).coerceAtLeast(0) + val contentHeight = if (bottomNavigation) (height - nav.height - line).coerceAtLeast(0) else height + val pane = children[0].measure(Constraints.fixed(contentWidth, contentHeight)) + val edge = children[1].measure(Constraints.fixed(if (bottomNavigation) width else line, if (bottomNavigation) line else height)) + layout(width, height) { + if (bottomNavigation) { + pane.placeRelative(0, 0) + edge.placeRelative(0, contentHeight) + nav.placeRelative(0, contentHeight + line) + } else { + nav.placeRelative(0, 0) + edge.placeRelative(nav.width, 0) + pane.placeRelative(nav.width + line, 0) + } + } + } +} + diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index d4dd41fe8b..0f1b579c92 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -35,7 +35,7 @@ import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.FilterList +import androidx.compose.material.icons.filled.FilterAlt import androidx.compose.material.icons.filled.GridView import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Sort @@ -86,8 +86,11 @@ import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreSizes import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.arrangeStoreTabs import com.droiddeck.launcher.stores.download.DownloadEntry import com.droiddeck.launcher.stores.formatBytes +import com.droiddeck.launcher.stores.itch.ItchCollection +import com.droiddeck.launcher.stores.itch.ItchCollections import com.droiddeck.launcher.stores.retainOrder import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter import com.droiddeck.launcher.stores.sortGames @@ -108,12 +111,16 @@ internal fun libraryEntries( ): List<LibraryEntry> { val claimed = HashSet<String>() val out = ArrayList<LibraryEntry>() - for (g in games) { + for (g in games.sortedBy { it.library == Library.XBOX_CLOUD }) { if (g.library == Library.EPIC_LAUNCHER) continue val storeKey = g.storeId?.let { "${g.source}:$it" } val item = storeKey?.let { k -> Store.byId(g.source)?.let { st -> owned[st]?.firstOrNull { it.key == k } } } - if (storeKey != null) claimed += storeKey - out += LibraryEntry(GameRef.key(g), g.source, g.name, g, item, installed = true) + if (storeKey != null) { + if (g.library == Library.XBOX_CLOUD && storeKey in claimed) continue + claimed.add(storeKey) + } + out += LibraryEntry(GameRef.key(g), g.source, g.name, g, item, + installed = g.library != Library.XBOX_CLOUD || storeKey in installedStore) } for (store in Store.entries) for (item in owned[store].orEmpty()) { if (!claimed.add(item.key)) continue @@ -122,18 +129,32 @@ internal fun libraryEntries( return out.distinctBy { it.key } } +internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>): List<LibraryEntry> { + val keys = items.map { it.key }.toSet() + val itch = all.filter { it.source == Store.ITCH.id } + val have = itch.mapNotNull { it.storeKey }.toSet() + return itch.filter { it.storeKey in keys } + + items.filter { it.key !in have }.map { LibraryEntry(GameRef.key(it), Store.ITCH.id, it.title, null, it, false) } +} + internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off } internal const val LIBRARY_ALL = "all" -internal val LIBRARY_SOURCES = listOf(Library.SOURCE_STEAM) + Store.entries.map { it.id } + Library.ADDED +internal fun librarySources(entries: List<LibraryEntry>, order: List<String>): List<String> = + (listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED) + .filter { source -> entries.any { it.source == source } } /** Survives leaving the page, so Stores can open the Library on one store's owned games. */ internal object LibraryView { var source by mutableStateOf(LIBRARY_ALL) var query by mutableStateOf("") var focusFirst = false + var ownedRequest by mutableIntStateOf(0) + private set - fun showOwned(store: Store) { + fun showOwned(context: android.content.Context, store: Store) { + SessionPrefs.setLibraryShowUninstalled(context, true) + ownedRequest++ source = store.id query = "" focusFirst = true @@ -157,13 +178,31 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val cloudRows = rememberXboxCloudRows(s) val all = remember(s.steamGames, cloudRows, owned, installedStore) { libraryEntries(s.steamGames + cloudRows, owned, installedStore) } LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) } - val sources = LIBRARY_SOURCES.filter { src -> all.any { it.source == src } } + var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) } + var collectionShows by remember { mutableStateOf<Pair<String, Boolean>?>(null) } + val setShowUninstalled = { show: Boolean -> + val picked = ItchCollections.selected.takeIf { LibraryView.source == Store.ITCH.id } + if (picked != null) collectionShows = picked to show + else { + showUninstalled = show + SessionPrefs.setLibraryShowUninstalled(ctx, show) + } + } + val itchSignedIn = owned.containsKey(Store.ITCH) + val listed = librarySources(all, SessionPrefs.storesTabOrder(ctx)) + val sources = if (itchSignedIn && Store.ITCH.id !in listed) listed + Store.ITCH.id else listed val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL val q = LibraryView.query.trim().lowercase() val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL - val candidates = all.filter { + LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) ItchCollections.load(ctx) } + val collection = if (source == Store.ITCH.id) ItchCollections.chosen() else null + val pool = if (collection == null) all else collectionEntries(all, ItchCollections.gamesOf(collection.id).orEmpty()) + val matching = pool.filter { (source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it) } + val listUninstalled = if (collection == null) showUninstalled else collectionShows?.takeIf { it.first == collection.id }?.second ?: true + val candidates = if (listUninstalled) matching else matching.filter { it.installed } + val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed } val sort = s.storesSort val sizeSort = sort == "sizeAsc" || sort == "sizeDesc" val installedAt = StoresState.installed.associate { it.key to it.sidecar.installedAt } @@ -206,6 +245,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val open = selected.takeIf { it.startsWith("app:") } val back = { onSelect("games") } + BackHandler(enabled = open == null && LibraryView.query.isNotEmpty()) { LibraryView.query = "" } BackHandler(enabled = open != null) { back() } val lead = remember { FocusRequester() } var detailFocused by remember { mutableStateOf(false) } @@ -245,7 +285,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, kotlinx.coroutines.delay(Motion.ms(240).toLong()) focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default } } - if (all.isEmpty() && open == null) { + if (all.isEmpty() && open == null && !itchSignedIn) { LibraryEmpty(s, a, modifier) return } @@ -253,7 +293,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val detailScroll = rememberScrollState() var cycled by remember { mutableIntStateOf(0) } var gridFocused by remember { mutableStateOf(false) } - LaunchedEffect(source, sort) { grid.scrollToItem(0) } + LaunchedEffect(source, sort, listUninstalled) { grid.scrollToItem(0) } LaunchedEffect(cycled) { if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect focusWithinFrames({ gridFocused }) { @@ -264,11 +304,13 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, open, detailScroll, gridScrolled = { grid.firstVisibleItemIndex > 0 || grid.firstVisibleItemScrollOffset > 0 }, onDetailFocus = { detailFocused = it }, - modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp), + modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp).padding(top = if (narrow) 10.dp else 14.dp), wrap = { key, content -> StoreTheme(GameRef.parse(key).let { r -> r.store ?: r.game(s.steamGames)?.source?.let { Store.byId(it) } }) { content() } }, grid = { LibraryGrid( - s, a, grid, visible, split, all.size, sources, source, sizesPending, syncing, + s, a, grid, visible, split, visible.size, sources, source, sizesPending, syncing, + showUninstalled = listUninstalled.takeIf { stores }, onShowUninstalled = setShowUninstalled, + hiddenUninstalled = hiddenUninstalled, onSource = { LibraryView.source = it }, onCycle = { step -> val ids = listOf(LIBRARY_ALL) + sources @@ -307,6 +349,7 @@ private fun LibraryEmpty(s: FrontEndState, a: FrontEndActions, modifier: Modifie private fun LibraryGrid( s: FrontEndState, a: FrontEndActions, grid: LazyGridState, visible: List<LibraryEntry>, split: Int, total: Int, sources: List<String>, source: String, sizesPending: Boolean, syncing: List<Pair<Store, String>>, + showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, hiddenUninstalled: Int, onSource: (String) -> Unit, onCycle: (Int) -> Unit, onOpen: (String) -> Unit, onFocus: (Boolean) -> Unit, searchCleared: Boolean, ) { val listMode = s.storesView == "list" @@ -360,7 +403,9 @@ private fun LibraryGrid( horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp), ) { - item(key = "header", span = { GridItemSpan(maxLineSpan) }) { Rise(0) { LibraryHeader(s, a, total, searchCleared, xbox = source == Store.XBOX.id) } } + item(key = "header", span = { GridItemSpan(maxLineSpan) }) { + Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = source == Store.ITCH.id) } + } item(key = "filters", span = { GridItemSpan(maxLineSpan) }) { Rise(1) { LibraryFilters(sources, source, onSource) } } @@ -378,7 +423,13 @@ private fun LibraryGrid( } } val empty = R.string.stores_nothing_matches - if (split == 0) libraryGrid(visible, empty, tile) + if (visible.isEmpty() && hiddenUninstalled > 0) item(key = "browse-owned", span = { GridItemSpan(maxLineSpan) }) { + Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp)) { + Text(stringResource(R.string.library_no_installed_matches), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + SecondaryButton(stringResource(R.string.library_browse_owned), modifier = Modifier.testTag("library-browse-owned")) { onShowUninstalled(true) } + } + } + else if (split == 0) libraryGrid(visible, empty, tile) else { item(key = "installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_installed)) } libraryGrid(visible.take(split), empty, tile) @@ -398,7 +449,10 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t } @Composable -private fun LibraryHeader(s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean) { +private fun LibraryHeader( + s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean, + showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Boolean, +) { val colors = MaterialTheme.colorScheme val narrow = LocalNarrowPane.current ModeHeader( @@ -413,7 +467,8 @@ private fun LibraryHeader(s: FrontEndState, a: FrontEndActions, total: Int, sear } }, ) { - if (xbox) XboxFilterButton() + if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox) + if (collections) CollectionsButton() SortButton(s, a) ViewButton(s, a) GameFileFolderActions(s, a) @@ -427,7 +482,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str if (sources.size < 2) return Row( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(top = 4.dp, bottom = 2.dp), + modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp).horizontalScroll(rememberScrollState()), ) { SourceFilterChip(LIBRARY_ALL, stringResource(R.string.stores_tab_all), source == LIBRARY_ALL, dot = null) { onSource(LIBRARY_ALL) } for (src in sources) { @@ -505,18 +560,31 @@ private fun LibraryTile(e: LibraryEntry, capsule: Boolean, first: Boolean, navig @Composable private fun RequestSize(e: LibraryEntry) { val ctx = LocalContext.current + if (e.installed) { + val inst = e.storeKey?.let { k -> StoresState.installed.firstOrNull { it.key == k } } + LaunchedEffect(e.key, inst) { + if (inst != null) StoreSizes.requestDisk(ctx, inst.key, inst) + else e.game?.gameFiles?.let { FolderSizes.request(it) } + } + return + } val item = e.item?.takeIf { !e.installed && it.accessible && it.sizeBytes <= 0 } ?: return LaunchedEffect(item.key) { StoreSizes.request(ctx, item) } } @Composable -private fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) { +internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) { val pal = LocalPalette.current + val size = if (e.installed) e.storeKey?.let { StoreSizes.onDisk[it] } + ?: e.game?.gameFiles?.let { FolderSizes.known[it.path] } + else e.item?.let { StoreSizes.size(it) }?.takeIf { it > 0 } when { download != null -> Text("${download.percent}%", fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1) - e.installed -> Unit e.item != null && StoresState.isUnfinished(e.item) -> Text(stringResource(R.string.stores_resume), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1) - else -> Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp)) + else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) { + if (size != null && size > 0) Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) + if (!e.installed) Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp)) + } } } @@ -570,7 +638,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch } @Composable -private fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) { +internal fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val src = remember { MutableInteractionSource() } @@ -587,7 +655,7 @@ private fun HeaderIconButton(description: String, icon: androidx.compose.ui.grap /** Choosing Library in the rail lands on the first game, as Play Steam does on the Steam page. */ @Composable -private fun Modifier.paneEntry(): Modifier { +internal fun Modifier.paneEntry(): Modifier { val ff = LocalFrontFocus.current ?: return this androidx.compose.runtime.DisposableEffect(ff) { ff.primaryAttached++ @@ -598,7 +666,7 @@ private fun Modifier.paneEntry(): Modifier { internal fun keepsXbox(filter: String, e: LibraryEntry): Boolean = when { filter == XboxLibraryFilter.ALL || e.source != Store.XBOX.id -> true - e.game?.library == Library.XBOX_CLOUD -> filter == XboxLibraryFilter.CLOUD + e.game?.library == Library.XBOX_CLOUD && e.item == null -> filter == XboxLibraryFilter.CLOUD else -> e.item?.let { XboxLibraryFilter.keeps(filter, it) } == true } @@ -611,24 +679,38 @@ private fun xboxFilterLabel(filter: String): String = when (filter) { } @Composable -private fun XboxFilterButton() { +private fun LibraryFilterButton(showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, xbox: Boolean) { val pal = LocalPalette.current val ctx = LocalContext.current - val title = stringResource(R.string.xbox_filter_show) + val title = stringResource(R.string.library_filter) + val visibility = stringResource(if (showUninstalled == true) R.string.library_filter_all_owned else R.string.library_filter_installed) + val description = title + " · " + if (showUninstalled == null) xboxFilterLabel(XboxLibraryFilter.current) else visibility + val offset = if (showUninstalled == null) 0 else 2 var at by remember { mutableStateOf<Rect?>(null) } Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) { - HeaderIconButton(title + " · " + xboxFilterLabel(XboxLibraryFilter.current), Icons.Filled.FilterList, "xbox-filter") { + HeaderIconButton(description, Icons.Filled.FilterAlt, "library-filter") { val from = at ?: return@HeaderIconButton Steps.ask(StepAsk( - anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = XboxLibraryFilter.ALL_FILTERS.size, - handle = { Text(title, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = offset + if (xbox) XboxLibraryFilter.ALL_FILTERS.size else 0, + handle = { Icon(Icons.Filled.FilterAlt, null, tint = pal.signal, modifier = Modifier.size(18.dp)) }, ) { StepTitle(title) StepList { - XboxLibraryFilter.ALL_FILTERS.forEachIndexed { i, filter -> + if (showUninstalled != null) listOf(false, true).forEachIndexed { i, show -> + StepChoice( + stringResource(if (show) R.string.library_filter_all_owned else R.string.library_filter_installed), + selected = show == showUninstalled, enabled = open, + modifier = Modifier.fillMaxWidth().stepItem(i).then(if (show == showUninstalled) Modifier.focusRequester(first) else Modifier), + ) { + onShowUninstalled(show) + Steps.fold() + } + } + if (xbox && showUninstalled != null) Text(Store.XBOX.shortLabel, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.stepItem(offset).padding(start = 4.dp, top = 10.dp, bottom = 4.dp)) + if (xbox) XboxLibraryFilter.ALL_FILTERS.forEachIndexed { i, filter -> StepChoice( xboxFilterLabel(filter), selected = filter == XboxLibraryFilter.current, enabled = open, - modifier = Modifier.fillMaxWidth().stepItem(i).then(if (filter == XboxLibraryFilter.current) Modifier.focusRequester(first) else Modifier), + modifier = Modifier.fillMaxWidth().stepItem(offset + i).then(if (showUninstalled == null && filter == XboxLibraryFilter.current) Modifier.focusRequester(first) else Modifier), ) { XboxLibraryFilter.set(ctx, filter) Steps.fold() @@ -640,6 +722,39 @@ private fun XboxFilterButton() { } } +@Composable +private fun CollectionsButton() { + val pal = LocalPalette.current + val ctx = LocalContext.current + val title = stringResource(R.string.itch_collections) + val all = stringResource(R.string.stores_tab_all) + var at by remember { mutableStateOf<Rect?>(null) } + Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) { + HeaderIconButton(title + " · " + (ItchCollections.chosen()?.title ?: all), CollectionsIcon, "itch-collections") { + val from = at ?: return@HeaderIconButton + val choices = listOf<ItchCollection?>(null) + ItchCollections.list + Steps.ask(StepAsk( + anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = choices.size, + handle = { Icon(CollectionsIcon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) }, + ) { + StepTitle(title) + StepList { + choices.forEachIndexed { i, c -> + val picked = c?.id == ItchCollections.selected + StepChoice( + c?.let { it.title + " (" + it.count + ")" } ?: all, selected = picked, enabled = open, + modifier = Modifier.fillMaxWidth().stepItem(i).then(if (picked) Modifier.focusRequester(first) else Modifier), + ) { + ItchCollections.select(ctx, c?.id) + Steps.fold() + } + } + } + }) + } + } +} + @Composable private fun SortButton(s: FrontEndState, a: FrontEndActions) { val pal = LocalPalette.current @@ -650,7 +765,7 @@ private fun SortButton(s: FrontEndState, a: FrontEndActions) { val from = at ?: return@HeaderIconButton Steps.ask(StepAsk( anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = SessionPrefs.STORES_SORTS.size, - handle = { Text(title, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + handle = { Icon(Icons.Filled.Sort, null, tint = pal.signal, modifier = Modifier.size(18.dp)) }, ) { StepTitle(title) StepList { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt index 0f4483c0a3..aa2b6da6c5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.shape.CircleShape import com.droiddeck.launcher.R import androidx.compose.ui.res.stringResource import androidx.compose.foundation.layout.Arrangement @@ -12,7 +13,7 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -46,9 +47,9 @@ fun ChooseAppDisplayDialog( ?: stringResource(R.string.main_secondary_gone), ) }, - confirmButton = { TextButton(onClick = onPrimary) { Text(stringResource(R.string.main_primary)) } }, + confirmButton = { TextButton(onClick = onPrimary, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.main_primary)) } }, dismissButton = { - TextButton(onClick = onSecondary, enabled = secondaryDisplay != null) { + TextButton(onClick = onSecondary, enabled = secondaryDisplay != null, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.main_secondary)) } }, @@ -61,8 +62,8 @@ fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () -> onDismissRequest = onDismiss, title = { Text(title) }, text = { Text(text) }, - confirmButton = { TextButton(onClick = { onDismiss(); onConfirm() }) { Text(confirm) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } }, + confirmButton = { TextButton(onClick = { onDismiss(); onConfirm() }, modifier = Modifier.focusGlide(CircleShape)) { Text(confirm) } }, + dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } @@ -72,11 +73,11 @@ fun RuntimeActionsDialog(onRepair: () -> Unit, onRemove: () -> Unit, onDismiss: onDismissRequest = onDismiss, title = { Text(stringResource(R.string.runtime_actions_title)) }, text = { Text(stringResource(R.string.runtime_actions_text)) }, - confirmButton = { TextButton(onClick = onRepair) { Text(stringResource(R.string.runtime_repair)) } }, + confirmButton = { TextButton(onClick = onRepair, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.runtime_repair)) } }, dismissButton = { Row { - TextButton(onClick = onRemove) { Text(stringResource(R.string.store_remove)) } - TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } + TextButton(onClick = onRemove, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.store_remove)) } + TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } } }, ) @@ -92,7 +93,7 @@ fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: ( Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { Text(stringResource(R.string.setup_reset_settings_body)) Row( - Modifier.fillMaxWidth().toggleable(gameProfiles, role = Role.Checkbox) { gameProfiles = it }, + Modifier.fillMaxWidth().focusGlide().toggleable(gameProfiles, role = Role.Checkbox) { gameProfiles = it }, verticalAlignment = Alignment.CenterVertically, ) { Checkbox(checked = gameProfiles, onCheckedChange = null) @@ -102,10 +103,10 @@ fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: ( } }, confirmButton = { - TextButton(onClick = { onDismiss(); onConfirm(gameProfiles) }) { + TextButton(onClick = { onDismiss(); onConfirm(gameProfiles) }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.setup_reset_settings_button), color = MaterialTheme.colorScheme.error) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } }, + dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } 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 c546a34c35..9c24f551cb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.shape.CircleShape import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.pluralStringResource import androidx.compose.foundation.clickable @@ -7,7 +8,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.size -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.LinearProgressIndicator @@ -59,7 +60,6 @@ class ModeSettings( val hdr: Boolean, val hdrReason: String?, val gpuDrivers: String? = null, - val fpsLimit: Int = 0, val upscaler: Int = 0, val upscaleSharpness: Int = 75, val touchMode: String, @@ -95,11 +95,7 @@ class ModeSettings( val bootMovieCustomName: String? = null, val bootMovieImporting: Boolean = false, val bootMovieProgress: Int = -1, - val wifiDiscovery: Boolean? = null, - val wifiDiscoveryPermission: Boolean = false, - val wifiDiscoveryLocation: Boolean = false, - val wifiDiscoveryAsked: Boolean = false, - val wifiDiscoveryBlocked: Boolean = false, + val integration: com.droiddeck.launcher.core.SteamIntegration.State? = null, val deckyInstalled: String? = null, val deckyLatestRelease: DeckyManager.Release? = null, val deckyBranch: Int = DeckyManager.BRANCH_STABLE, @@ -115,7 +111,6 @@ class ModeSettingsActions( val onResolution: (String) -> Unit, val onHdr: (Boolean) -> Unit, val onGpuDrivers: () -> Unit = {}, - val onFpsLimit: (Int) -> Unit = {}, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, val onTouch: (String) -> Unit, @@ -147,8 +142,9 @@ class ModeSettingsActions( val onBootMovieSound: (Boolean) -> Unit = {}, val onImportBootMovie: () -> Unit = {}, val onBootMovieChanged: () -> Unit = {}, - val onWifiDiscovery: (Boolean) -> Unit = {}, - val onWifiDiscoverySettings: () -> Unit = {}, + val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {}, + val onIntegrationAppInfo: () -> Unit = {}, + val onIntegrationLocation: () -> Unit = {}, val onDeckyInstall: (DeckyManager.Release) -> Unit = {}, val onDeckyCheck: () -> Unit = {}, val onDeckyBranch: (Int) -> Unit = {}, @@ -158,7 +154,7 @@ class ModeSettingsActions( val onDismiss: () -> Unit, ) -/** "2610 r3" from droiddeck-steam-x64's FEX_TAG line (fex-2610-r3), the build the x86-64 client downloads. */ +/** "2610 r3" from droiddeck-fex-update's FEX_TAG line (fex-2610-r3), the build x86 programs fall back to. */ internal fun fexVersionOf(script: String): String? = Regex("""(?m)^FEX_TAG=(fex-\d+-r\d+)\s*$""").find(script)?.let { fexVersionOfTag(it.groupValues[1]) } @@ -173,7 +169,7 @@ private fun x64FexVersion(context: android.content.Context): String? = remember runCatching { java.io.File(root, "usr/local/share/fex-emu/.droiddeck-tag").readText() }.getOrNull()?.let(::fexVersionOfTag) ?: com.droiddeck.launcher.session.FexCatalog.cached(context)?.tag?.let(::fexVersionOfTag) ?: runCatching { - context.assets.open("linuxfs/usr/local/bin/droiddeck-steam-x64").bufferedReader().use { fexVersionOf(it.readText()) } + context.assets.open("linuxfs/usr/local/bin/droiddeck-fex-update").bufferedReader().use { fexVersionOf(it.readText()) } }.getOrNull() } @@ -207,11 +203,17 @@ class SheetExtras( fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) { val steam = s.mode == SessionService.MODE_STEAM val host = rememberMenuHost() - var explainWifiDiscovery by remember { mutableStateOf(false) } if (tab == SheetTab.DISPLAY) { - val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution) + val context = LocalContext.current + val portraitWindow = SessionPrefs.portrait(context) + val longSide = maxOf(s.panelSize.first, s.panelSize.second) + val shortSide = minOf(s.panelSize.first, s.panelSize.second) + val controlsBelow = SessionPrefs.controlsBelowWanted(context, s.mode, + if (portraitWindow) shortSide else longSide, if (portraitWindow) longSide else shortSide) + val portrait = portraitWindow && !controlsBelow + val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution, portrait) SettingsGroup(stringResource(R.string.display_session)) { - ResolutionRow(host, s.resolution, s.panelSize, a.onResolution) + ResolutionRow(host, s.resolution, s.panelSize, a.onResolution, portrait = portrait) s.picturePosition?.let { position -> ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null, listOf("top" to stringResource(R.string.display_position_top), @@ -221,7 +223,8 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: } if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) || com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) { - val canStretch = com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize) + val canStretch = s.resolution != com.droiddeck.launcher.session.SessionDisplay.FOLLOW_SCREEN && + com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize) ChoiceRow(host, "game-fit", stringResource(R.string.display_game_fit), stringResource(if (canStretch) R.string.display_game_fit_hint else R.string.display_game_fit_unavailable), listOf(false to stringResource(R.string.display_preserve), true to stringResource(R.string.display_stretch)), @@ -239,10 +242,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: format = { "$it%" }, onChange = a.onUpscaleSharpness, ) } - SettingsGroup(stringResource(R.string.display_frame_rate)) { - ChoiceRow(host, "fps", stringResource(R.string.mode_fps), stringResource(R.string.common_applies_next_session), - SessionPrefs.fpsLimitChoices(LocalContext.current), s.fpsLimit, note = stringResource(R.string.mode_fps_note), onPick = a.onFpsLimit) - } SettingsGroup(stringResource(R.string.mode_hdr)) { ToggleRow( host, "hdr", stringResource(R.string.mode_hdr10), @@ -304,6 +303,9 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU), ), s.backActionsInverted, onPick = a.onBackActionsInverted, ) + if (steam && s.steamController in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) { + Note(stringResource(R.string.back_native_qam_hint)) + } } } if (tab == SheetTab.AUDIO && steam) { @@ -500,39 +502,9 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: ) } if (s.bootMovie != null) BootMovieGroup(s, a, host) - if (s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) { - val hint = when { - s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off) - !s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied) - else -> stringResource(R.string.mode_wifi_discovery_hint) - } - SettingsRow(stringResource(R.string.mode_wifi_discovery), hint) { - Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, - horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)) { - if (s.wifiDiscoveryBlocked || (s.wifiDiscovery && !s.wifiDiscoveryLocation)) { - SecondaryButton(stringResource(R.string.mode_wifi_open_settings), onClick = a.onWifiDiscoverySettings) - } - ToggleSwitch(s.wifiDiscovery, label = stringResource(R.string.mode_wifi_discovery)) { on -> - host.open = null - if (on) explainWifiDiscovery = true else a.onWifiDiscovery(false) - } - } - } - } + if (s.integration != null) SteamIntegrationGroup(s.integration, + onFeature = a.onIntegration, onAppInfo = a.onIntegrationAppInfo, onLocation = a.onIntegrationLocation) } - if (explainWifiDiscovery) AlertDialog( - onDismissRequest = { explainWifiDiscovery = false }, - title = { Text(stringResource(R.string.mode_wifi_explain_title)) }, - text = { Text(stringResource(R.string.mode_wifi_explain_text)) }, - confirmButton = { - TextButton(onClick = { explainWifiDiscovery = false; a.onWifiDiscovery(true) }) { - Text(stringResource(if (s.wifiDiscoveryBlocked) R.string.mode_wifi_open_settings else R.string.mode_wifi_continue)) - } - }, - dismissButton = { - TextButton(onClick = { explainWifiDiscovery = false }) { Text(stringResource(R.string.common_cancel)) } - }, - ) } @Composable @@ -577,14 +549,14 @@ internal fun DeckyZipWarningDialog(onConfirm: () -> Unit, onCancel: () -> Unit) title = { Text(stringResource(R.string.decky_zip_warning_title)) }, text = { Text(stringResource(R.string.decky_zip_warning_text)) }, confirmButton = { - androidx.compose.material3.TextButton(onClick = onConfirm, enabled = left == 0) { + androidx.compose.material3.TextButton(onClick = onConfirm, enabled = left == 0, modifier = Modifier.focusGlide(CircleShape)) { Text( if (left > 0) androidx.compose.ui.res.pluralStringResource(R.plurals.decky_zip_warning_wait, left, left) else stringResource(R.string.decky_zip_warning_continue), ) } }, - dismissButton = { androidx.compose.material3.TextButton(onClick = onCancel) { Text(stringResource(R.string.common_cancel)) } }, + dismissButton = { androidx.compose.material3.TextButton(onClick = onCancel, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } @@ -619,7 +591,7 @@ private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) { @Composable internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss: () -> Unit) { var key by remember { mutableStateOf("") } - androidx.compose.material3.AlertDialog( + com.droiddeck.launcher.ui.GlideAlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.mode_sgdb_key)) }, text = { @@ -627,14 +599,14 @@ internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss: key, { v -> key = v.trim() }, label = { Text(stringResource(R.string.mode_sgdb_key)) }, singleLine = true, visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation(), keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Password), - modifier = Modifier.fillMaxWidth(), + modifier = Modifier.fillMaxWidth().focusGlide(), ) }, - confirmButton = { androidx.compose.material3.TextButton(onClick = { onSave(key) }, enabled = key.isNotEmpty()) { Text(stringResource(R.string.common_ok)) } }, + confirmButton = { androidx.compose.material3.TextButton(onClick = { onSave(key) }, enabled = key.isNotEmpty(), modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_ok)) } }, dismissButton = { androidx.compose.foundation.layout.Row { - if (hasKey) androidx.compose.material3.TextButton(onClick = { onSave("") }) { Text(stringResource(R.string.common_delete)) } - androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } + if (hasKey) androidx.compose.material3.TextButton(onClick = { onSave("") }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) } + androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } } }, ) @@ -646,7 +618,7 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, var w by remember { mutableStateOf(initial?.first?.toString() ?: "") } var h by remember { mutableStateOf(initial?.second?.toString() ?: "") } val parsed = SessionPrefs.parseResolution("${w}x$h") - androidx.compose.material3.AlertDialog( + com.droiddeck.launcher.ui.GlideAlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.mode_custom_res_title)) }, text = { @@ -662,12 +634,12 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, val numbers = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Number) androidx.compose.material3.OutlinedTextField( w, { v -> w = v.filter(Char::isDigit).take(4) }, label = { Text(stringResource(R.string.mode_width)) }, - singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f), + singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f).focusGlide(), ) Text("×", fontSize = 18.sp, modifier = Modifier.padding(horizontal = 10.dp)) androidx.compose.material3.OutlinedTextField( h, { v -> h = v.filter(Char::isDigit).take(4) }, label = { Text(stringResource(R.string.mode_height)) }, - singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f), + singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f).focusGlide(), ) } androidx.compose.foundation.layout.FlowRow( @@ -678,6 +650,7 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, androidx.compose.material3.AssistChip( onClick = { w = pw.toString(); h = ph.toString() }, label = { Text("$pw×$ph · $tag", fontSize = 12.sp) }, + modifier = Modifier.focusGlide(), ) } } @@ -687,7 +660,7 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, ) } }, - confirmButton = { androidx.compose.material3.TextButton(enabled = parsed != null, onClick = { parsed?.let(onSave) }) { Text(stringResource(R.string.common_use)) } }, - dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } }, + confirmButton = { androidx.compose.material3.TextButton(enabled = parsed != null, onClick = { parsed?.let(onSave) }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_use)) } }, + dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt b/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt new file mode 100644 index 0000000000..94c7a8cf3c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt @@ -0,0 +1,60 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.util.VelocityTracker +import androidx.compose.ui.input.pointer.util.addPointerInputChange +import androidx.compose.ui.unit.dp +import kotlin.math.abs + +internal object PageSwipe { + var locks by mutableIntStateOf(0) + var direction by mutableIntStateOf(0) +} + +// Runs on the Final pass so carousels, sliders, scrollers and widgets that consumed the drag keep it. +@Composable +internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): Modifier { + val enabledNow by rememberUpdatedState(enabled) + val onSwipeNow by rememberUpdatedState(onSwipe) + return pointerInput(Unit) { + val distance = 72.dp.toPx() + val flingDistance = 32.dp.toPx() + val flingVelocity = 900.dp.toPx() + val slop = viewConfiguration.touchSlop + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Final) + if (!enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture + val tracker = VelocityTracker() + tracker.addPointerInputChange(down) + var total = Offset.Zero + var mine = false + while (true) { + val event = awaitPointerEvent(PointerEventPass.Final) + if (event.changes.size > 1) return@awaitEachGesture + val change = event.changes.firstOrNull { it.id == down.id } ?: return@awaitEachGesture + if (!change.pressed) break + if (!mine && change.isConsumed) return@awaitEachGesture + total += change.position - change.previousPosition + tracker.addPointerInputChange(change) + if (!mine && abs(total.x) > slop && abs(total.x) > abs(total.y) * 2f) mine = true + if (mine) change.consume() + } + if (!mine || PageSwipe.locks > 0) return@awaitEachGesture + val vx = tracker.calculateVelocity().x + val horizontal = abs(total.x) > abs(total.y) * 1.5f + val far = abs(total.x) > distance + val flung = abs(total.x) > flingDistance && abs(vx) > flingVelocity && (vx > 0) == (total.x > 0) + if (horizontal && (far || flung)) onSwipeNow(if (total.x < 0) 1 else -1) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt index 0fc5762777..6c68c9cfc6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt @@ -1,7 +1,9 @@ package com.droiddeck.launcher.ui import com.droiddeck.launcher.R -import androidx.annotation.StringRes +import com.droiddeck.launcher.input.PC_KEY_ROWS +import com.droiddeck.launcher.input.PC_MODIFIERS +import com.droiddeck.launcher.input.PcKey import androidx.compose.ui.res.stringResource import android.view.KeyEvent import androidx.compose.animation.animateColorAsState @@ -54,46 +56,6 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -private data class PcKey(val label: String, val code: Int, val weight: Float = 1f, val shifted: String? = null, @StringRes val labelRes: Int = 0) - -private fun k(label: String, code: Int, weight: Float = 1f, shifted: String? = null) = PcKey(label, code, weight, shifted) - -private fun k(@StringRes labelRes: Int, code: Int, weight: Float = 1f) = PcKey("", code, weight, null, labelRes) - -private val ROWS: List<List<PcKey>> = listOf( - listOf( - k(R.string.pckb_key_esc, 1), k("F1", 59), k("F2", 60), k("F3", 61), k("F4", 62), k("F5", 63), k("F6", 64), - k("F7", 65), k("F8", 66), k("F9", 67), k("F10", 68), k("F11", 87), k("F12", 88), - k(R.string.pckb_key_ins, 110), k(R.string.pckb_key_del, 111), k(R.string.pckb_key_home, 102), k(R.string.pckb_key_end, 107), k(R.string.pckb_key_pgup, 104), k(R.string.pckb_key_pgdn, 109), - ), - listOf( - k("`", 41, shifted = "~"), k("1", 2, shifted = "!"), k("2", 3, shifted = "@"), k("3", 4, shifted = "#"), - k("4", 5, shifted = "$"), k("5", 6, shifted = "%"), k("6", 7, shifted = "^"), k("7", 8, shifted = "&"), - k("8", 9, shifted = "*"), k("9", 10, shifted = "("), k("0", 11, shifted = ")"), k("-", 12, shifted = "_"), - k("=", 13, shifted = "+"), k(R.string.pckb_key_backspace, 14, 2f), - ), - listOf( - k(R.string.pckb_key_tab, 15, 1.5f), k("q", 16), k("w", 17), k("e", 18), k("r", 19), k("t", 20), k("y", 21), - k("u", 22), k("i", 23), k("o", 24), k("p", 25), k("[", 26, shifted = "{"), k("]", 27, shifted = "}"), - k("\\", 43, 1.5f, shifted = "|"), - ), - listOf( - k(R.string.pckb_key_caps, 58, 1.75f), k("a", 30), k("s", 31), k("d", 32), k("f", 33), k("g", 34), k("h", 35), - k("j", 36), k("k", 37), k("l", 38), k(";", 39, shifted = ":"), k("'", 40, shifted = "\""), - k(R.string.pckb_key_enter, 28, 2.25f), - ), - listOf( - k(R.string.pckb_key_shift, 42, 2.25f), k("z", 44), k("x", 45), k("c", 46), k("v", 47), k("b", 48), k("n", 49), - k("m", 50), k(",", 51, shifted = "<"), k(".", 52, shifted = ">"), k("/", 53, shifted = "?"), - k(R.string.pckb_key_shift, 54, 1.75f), k("↑", 103), - ), - listOf( - k(R.string.pckb_key_ctrl, 29, 1.5f), k(R.string.pckb_key_super, 125, 1.25f), k(R.string.pckb_key_alt, 56, 1.25f), k(R.string.pckb_key_space, 57, 6.25f), - k(R.string.pckb_key_altgr, 100, 1.25f), k(R.string.pckb_key_ctrl, 97, 1.25f), k("←", 105), k("↓", 108), k("→", 106), - ), -) - -private val MODIFIERS = setOf(42, 54, 29, 97, 56, 100, 125) private const val MOD_OFF = 0 private const val MOD_ONCE = 1 private const val MOD_LOCKED = 2 @@ -115,7 +77,7 @@ fun PcKeyboard( for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { sendKey(code, false); mods[code] = MOD_OFF } } fun press(key: PcKey) { - if (key.code in MODIFIERS) { + if (key.code in PC_MODIFIERS) { when (mods[key.code] ?: MOD_OFF) { MOD_OFF -> { sendKey(key.code, true); mods[key.code] = MOD_ONCE } MOD_ONCE -> mods[key.code] = MOD_LOCKED @@ -126,7 +88,7 @@ fun PcKeyboard( sendKey(key.code, true) } fun release(key: PcKey) { - if (key.code in MODIFIERS) return + if (key.code in PC_MODIFIERS) return sendKey(key.code, false) if (key.code == 58) capsOn = !capsOn releaseOnceModifiers() @@ -153,7 +115,7 @@ fun PcKeyboard( Spacer(Modifier.width(8.dp)) HeaderButton(stringResource(R.string.pckb_hide), onClose) } - ROWS.forEachIndexed { r, row -> + PC_KEY_ROWS.forEachIndexed { r, row -> Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) { row.forEachIndexed { i, key -> val state = mods[key.code] ?: MOD_OFF diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt index 25f344a77a..2c0927bc88 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt @@ -28,6 +28,8 @@ import com.droiddeck.launcher.session.SessionPrefs class CoreRow(val core: Int, val label: String) +private const val MEMORY_CAP_STEP_MB = 256 + @Composable fun PerformancePage( cores: List<CoreRow>, @@ -44,6 +46,11 @@ fun PerformancePage( fsyncFirst: Boolean, gamescopeRealtime: Boolean, gpuClockPin: Boolean, + ramCapMb: Int, + zramClient: Boolean, + vramCapMb: Int, + deviceRamMb: Int, + ramCapAvailable: Boolean, prootNoSeccomp: Boolean, prootFastPath: Boolean, cursorComposite: Boolean, @@ -60,6 +67,9 @@ fun PerformancePage( onFsyncFirst: (Boolean) -> Unit, onGamescopeRealtime: (Boolean) -> Unit, onGpuClockPin: (Boolean) -> Unit, + onRamCapMb: (Int) -> Unit, + onZramClient: (Boolean) -> Unit, + onVramCapMb: (Int) -> Unit, onProotNoSeccomp: (Boolean) -> Unit, onProotFastPath: (Boolean) -> Unit, onCursorComposite: (Boolean) -> Unit, @@ -123,6 +133,27 @@ fun PerformancePage( gpuClockPin, onChange = onGpuClockPin, ) } + SettingsGroup(stringResource(R.string.perf_memory)) { + val top = (deviceRamMb / MEMORY_CAP_STEP_MB * MEMORY_CAP_STEP_MB).coerceAtLeast(MEMORY_CAP_STEP_MB) + val off = stringResource(R.string.perf_cap_off) + val auto = stringResource(R.string.perf_cap_auto) + ToggleRow( + host, "zramclient", stringResource(R.string.perf_zram_client), + if (ramCapAvailable) stringResource(R.string.perf_zram_client_hint) else stringResource(R.string.perf_ram_cap_unavailable), + zramClient && ramCapAvailable, enabled = ramCapAvailable, onChange = onZramClient, + ) + SliderRow( + stringResource(R.string.perf_ram_cap), + if (ramCapAvailable) stringResource(R.string.perf_ram_cap_hint) else stringResource(R.string.perf_ram_cap_unavailable), + ramCapMb.coerceAtMost(top), 0..top, step = MEMORY_CAP_STEP_MB, enabled = ramCapAvailable, + format = { if (it == 0) off else "$it MB" }, onChange = onRamCapMb, + ) + SliderRow( + stringResource(R.string.perf_vram_cap), stringResource(R.string.perf_vram_cap_hint), + vramCapMb.coerceAtMost(top), 0..top, step = MEMORY_CAP_STEP_MB, + format = { if (it == 0) auto else "$it MB" }, onChange = onVramCapMb, + ) + } SettingsGroup(stringResource(R.string.perf_fixes)) { ToggleRow( host, "sysmem", stringResource(R.string.perf_sysmem), @@ -181,7 +212,7 @@ fun PerformancePage( }, singleLine = true, isError = !valid && draft.isNotBlank(), placeholder = { Text(SessionPrefs.DEFAULT_GUEST_HOSTNAME) }, - modifier = Modifier.width(220.dp), + modifier = Modifier.width(220.dp).focusGlide(), ) } } 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 10b6c00c8e..60b4223f0a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.shape.CircleShape import com.droiddeck.launcher.R import androidx.compose.ui.res.stringResource import android.content.Context @@ -17,7 +18,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -44,6 +45,7 @@ import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage @Composable fun PhantomProcessGatePage( status: PhantomProcessStatus, + applyingSavedPairing: Boolean, onDismiss: () -> Unit, onOpenDeveloperOptions: () -> Unit, onFixWithWirelessDebugging: () -> Unit, @@ -76,7 +78,7 @@ fun PhantomProcessGatePage( BoxWithConstraints(Modifier.fillMaxWidth()) { val wide = maxWidth >= 620.dp val fix: @Composable ColumnScope.() -> Unit = { - FixGroup(hasToggle, stage, environment, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, + FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging, onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) }) } val side: @Composable ColumnScope.() -> Unit = { @@ -118,6 +120,7 @@ private fun FixGroup( stage: Stage, environment: GateEnvironment, compact: Boolean, + applyingSavedPairing: Boolean, onOpenDeveloperOptions: () -> Unit, onFixWithWirelessDebugging: () -> Unit, onOpenNotificationSettings: () -> Unit, @@ -130,6 +133,10 @@ private fun FixGroup( verticalArrangement = Arrangement.spacedBy(8.dp), ) { when { + applyingSavedPairing -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) + Body(stringResource(R.string.adbpair_applying)) + } pairing -> PairingProgress(stage, onCancel) hasToggle -> { Body(stringResource(R.string.gate_toggle_steps)) @@ -276,12 +283,12 @@ fun DeveloperDisplayChoiceDialog( text = { Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.gate_choose_display)) - TextButton(modifier = Modifier.fillMaxWidth(), onClick = onMainScreen) { Text(stringResource(R.string.gate_main_screen)) } + TextButton(modifier = Modifier.fillMaxWidth().focusGlide(CircleShape), onClick = onMainScreen) { Text(stringResource(R.string.gate_main_screen)) } displays.forEach { (id, label) -> - TextButton(modifier = Modifier.fillMaxWidth(), onClick = { onSecondaryScreen(id) }) { Text(label) } + TextButton(modifier = Modifier.fillMaxWidth().focusGlide(CircleShape), onClick = { onSecondaryScreen(id) }) { Text(label) } } } }, - confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } }, + confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt index 5a0b88daaf..8db8910a80 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt @@ -14,16 +14,17 @@ import com.droiddeck.launcher.session.SessionDisplay fun ResolutionRow( host: MenuHost, choice: String, panel: Pair<Int, Int>, onPick: (String) -> Unit, chipModifier: Modifier = Modifier, + portrait: Boolean = false, ) { val custom = "custom" - val size = SessionDisplay.resolveChoice(panel, choice) - val screen = SessionDisplay.screenSize(panel) + val size = SessionDisplay.resolveChoice(panel, choice, portrait) + val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait) val choices = SessionDisplay.resolutionOptions(panel) val selected = if (choice == SessionDisplay.FOLLOW_SCREEN) choice else if (size == screen) SessionDisplay.MATCH_SCREEN else choice var editCustom by remember { mutableStateOf(false) } val options = choices.map { value -> - val dimensions = SessionDisplay.resolveChoice(panel, value) + val dimensions = SessionDisplay.resolveChoice(panel, value, portrait) value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second) else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen) else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}") diff --git a/app/src/main/java/com/droiddeck/launcher/ui/RomsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/RomsDialog.kt index 0417c5e098..2504a2eee3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/RomsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/RomsDialog.kt @@ -1,12 +1,13 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.shape.CircleShape import com.droiddeck.launcher.R import androidx.compose.ui.res.stringResource import androidx.compose.foundation.layout.Column import androidx.compose.ui.Modifier import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -38,10 +39,10 @@ fun RomsDialog(path: String?, onChoose: () -> Unit, onClear: () -> Unit, onDismi ) } }, - confirmButton = { TextButton(onClick = onChoose) { Text(if (path == null) stringResource(R.string.roms_choose) else stringResource(R.string.roms_change)) } }, + confirmButton = { TextButton(onClick = onChoose, modifier = Modifier.focusGlide(CircleShape)) { Text(if (path == null) stringResource(R.string.roms_choose) else stringResource(R.string.roms_change)) } }, dismissButton = { - if (path != null) TextButton(onClick = onClear) { Text(stringResource(R.string.common_forget)) } - else TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } + if (path != null) TextButton(onClick = onClear, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_forget)) } + else TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyEditor.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyEditor.kt new file mode 100644 index 0000000000..94e1a5ff27 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyEditor.kt @@ -0,0 +1,368 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.net.Uri +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.systemBarsPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.DragIndicator +import androidx.compose.material.icons.filled.Image +import androidx.compose.material.icons.filled.Keyboard +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.SCREEN_KEY_CIRCLE +import com.droiddeck.launcher.input.SCREEN_KEY_DPAD +import com.droiddeck.launcher.input.SCREEN_KEY_PILL +import com.droiddeck.launcher.input.SCREEN_KEY_RECT +import com.droiddeck.launcher.input.SCREEN_KEY_ROUND +import com.droiddeck.launcher.input.SCREEN_KEY_STICK +import com.droiddeck.launcher.input.SCREEN_KEY_TRIGGER +import com.droiddeck.launcher.input.ScreenKeys +import com.droiddeck.launcher.input.pcKeyLabel +import com.droiddeck.launcher.input.screenKeyDirections +import java.io.File +import kotlin.math.roundToInt + +private val PANEL_WIDTH = 600.dp +private val CHIP_PADDING = androidx.compose.foundation.layout.PaddingValues(horizontal = 6.dp, vertical = 2.dp) + +@Composable +fun ScreenKeyEditor( + codes: List<Int>, + keyY: Float, + size: Int, + opacity: Float, + shape: Int, + toggle: Boolean, + labels: Boolean, + text: String, + hasImage: Boolean, + onResize: (Int) -> Unit, + onOpacity: (Float) -> Unit, + onShape: (Int) -> Unit, + onToggle: (Boolean) -> Unit, + onLabels: (Boolean) -> Unit, + onText: (String) -> Unit, + onImage: (String) -> Unit, + onClearImage: () -> Unit, + onBind: () -> Unit, + onTextFocus: () -> Unit, + onTextBlur: () -> Unit, + onDirection: (Int) -> Unit, + onRemove: () -> Unit, + onDismiss: () -> Unit, +) { + val p = LocalPalette.current + val context = LocalContext.current + var offset by remember(codes) { mutableStateOf(Offset.Zero) } + val density = LocalDensity.current + val screen = LocalConfiguration.current + val panelWidthPx = with(density) { PANEL_WIDTH.toPx() } + val screenWidthPx = screen.screenWidthDp * density.density + val screenHeightPx = screen.screenHeightDp * density.density + val atTop = keyY > 0.45f + val button = shape <= SCREEN_KEY_RECT + val directions = screenKeyDirections(shape) + val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> + if (uri != null) importImage(context, uri, codes)?.let(onImage) + } + Box( + Modifier.fillMaxSize().systemBarsPadding().padding(horizontal = 10.dp, vertical = 6.dp), + contentAlignment = if (atTop) Alignment.TopCenter else Alignment.BottomCenter, + ) { + Surface( + Modifier.widthIn(max = PANEL_WIDTH).fillMaxWidth() + .offset { IntOffset(offset.x.roundToInt(), offset.y.roundToInt()) }, + shape = RoundedCornerShape(18.dp), + color = p.background, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2), + ) { + Column(Modifier.padding(start = 10.dp, end = 6.dp, top = 2.dp, bottom = 6.dp)) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Icon( + Icons.Default.DragIndicator, null, + tint = p.onBackground.copy(alpha = 0.45f), + modifier = Modifier.pointerInput(panelWidthPx, screenWidthPx, screenHeightPx) { + detectDragGestures { change, drag -> + change.consume() + offset = Offset( + (offset.x + drag.x).coerceIn( + -(screenWidthPx - panelWidthPx) / 2f + 8f, + (screenWidthPx - panelWidthPx) / 2f - 8f, + ), + (offset.y + drag.y).coerceIn( + -screenHeightPx * if (atTop) 0f else 0.75f, + screenHeightPx * if (atTop) 0.75f else 0f, + ), + ) + } + }, + ) + Box( + Modifier.weight(1f).height(36.dp) + .background(p.line2.copy(alpha = 0.24f), RoundedCornerShape(9.dp)) + .padding(horizontal = 10.dp), + contentAlignment = Alignment.CenterStart, + ) { + BasicTextField( + value = text, + onValueChange = { onText(it.take(24)) }, + singleLine = true, + textStyle = TextStyle( + color = p.onBackground, fontSize = 13.sp, + fontWeight = FontWeight.Medium, + ), + cursorBrush = androidx.compose.ui.graphics.SolidColor(p.primary), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), + modifier = Modifier.fillMaxWidth().onFocusChanged { + if (it.isFocused) onTextFocus() else onTextBlur() + }.focusGlide(), + ) + if (text.isEmpty()) { + Text( + stringResource(R.string.screen_key_text), + color = p.onBackground.copy(alpha = 0.4f), + style = MaterialTheme.typography.bodySmall, + ) + } + } + if (button) { + IconButton(onClick = onBind, modifier = Modifier.width(38.dp).focusGlide(CircleShape)) { + Icon( + Icons.Default.Keyboard, stringResource(R.string.screen_key_bind), + tint = p.onBackground.copy(alpha = 0.8f), + ) + } + } + IconButton(onClick = { pickImage.launch("image/*") }, modifier = Modifier.width(38.dp).focusGlide(CircleShape)) { + Icon( + Icons.Default.Image, stringResource(R.string.screen_key_image), + tint = p.onBackground.copy(alpha = 0.8f), + ) + } + if (hasImage) IconButton(onClick = onClearImage, modifier = Modifier.width(34.dp).focusGlide(CircleShape)) { + Icon(Icons.Default.Close, stringResource(R.string.screen_key_image_clear), tint = p.error) + } + IconButton(onClick = onRemove, modifier = Modifier.width(38.dp).focusGlide(CircleShape)) { + Icon(Icons.Default.Delete, stringResource(R.string.common_delete), tint = p.error) + } + IconButton(onClick = onDismiss, modifier = Modifier.width(34.dp).focusGlide(CircleShape)) { + Icon(Icons.Default.Close, null, tint = p.onBackground) + } + } + Row( + Modifier.fillMaxWidth().padding(vertical = 2.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + listOf<Pair<Int?, Int>>( + (if (button) SCREEN_KEY_PILL else null) to R.string.screen_key_type_button, + SCREEN_KEY_TRIGGER to R.string.screen_key_shape_trigger, + SCREEN_KEY_DPAD to R.string.touch_dpad, + SCREEN_KEY_STICK to R.string.deck_surface_stick, + ).forEach { (value, label) -> + val selected = if (value == null) button else shape == value + Chip(stringResource(label), selected, Modifier.weight(1f)) { + onShape(if (value == null) (if (button) shape else SCREEN_KEY_PILL) else value) + } + } + Box(Modifier.width(1.dp).height(20.dp).background(p.line2)) + listOf( + SCREEN_KEY_PILL to R.string.screen_key_shape_pill, + SCREEN_KEY_ROUND to R.string.screen_key_shape_round, + SCREEN_KEY_CIRCLE to R.string.screen_key_shape_circle, + SCREEN_KEY_RECT to R.string.screen_key_shape_rect, + ).forEach { (value, label) -> + Chip( + stringResource(label), button && shape == value, Modifier.weight(1f), enabled = button, + ) { onShape(value) } + } + Box(Modifier.width(1.dp).height(20.dp).background(p.line2)) + Text( + stringResource(R.string.screen_key_toggle), Modifier.padding(start = 6.dp, end = 2.dp), + style = MaterialTheme.typography.bodySmall, maxLines = 1, + ) + Switch(checked = toggle, onCheckedChange = onToggle, modifier = Modifier.height(30.dp).focusGlide()) + } + if (directions.isNotEmpty()) { + Row( + Modifier.fillMaxWidth().padding(vertical = 2.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + directions.forEachIndexed { index, arrow -> + val code = codes.getOrNull(index) ?: 0 + Chip( + if (code == 0) arrow else "$arrow ${pcKeyLabel(context, code)}", + code != 0, Modifier.weight(1f), + ) { onDirection(index) } + } + Text( + stringResource(R.string.screen_key_text), Modifier.padding(start = 6.dp, end = 2.dp), + style = MaterialTheme.typography.bodySmall, maxLines = 1, + ) + Switch(checked = labels, onCheckedChange = onLabels, modifier = Modifier.height(30.dp).focusGlide()) + } + } + Row( + Modifier.fillMaxWidth().padding(top = 2.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + KeySlider( + label = stringResource(R.string.screen_key_size), + value = "$size", + current = size.toFloat(), + min = ScreenKeys.MIN_SIZE.toFloat(), + max = ScreenKeys.MAX_SIZE.toFloat(), + modifier = Modifier.weight(1f), + ) { onResize(it.roundToInt()) } + KeySlider( + label = stringResource(R.string.screen_key_opacity), + value = "${(opacity * 100).roundToInt()}%", + current = opacity, + min = 0.2f, + max = 1f, + modifier = Modifier.weight(1f), + onChange = onOpacity, + ) + } + } + } + } +} + +@Composable +private fun KeySlider( + label: String, + value: String, + current: Float, + min: Float, + max: Float, + modifier: Modifier, + onChange: (Float) -> Unit, +) { + Row(modifier, verticalAlignment = Alignment.CenterVertically) { + Text(label, style = MaterialTheme.typography.bodySmall, maxLines = 1) + Slider(current, onChange, Modifier.weight(1f).height(28.dp).focusGlide(), valueRange = min..max) + Text( + value, Modifier.width(32.dp), style = MaterialTheme.typography.bodySmall, + fontWeight = FontWeight.SemiBold, maxLines = 1, + ) + } +} + +@Composable +private fun Chip( + label: String, + selected: Boolean, + modifier: Modifier = Modifier, + enabled: Boolean = true, + onClick: () -> Unit, +) { + val p = LocalPalette.current + Box( + modifier + .background( + if (selected) p.primary.copy(alpha = 0.18f) else p.line2.copy(alpha = 0.28f), + CircleShape, + ) + .focusGlide(RoundedCornerShape(8.dp)).clickable(enabled = enabled, onClick = onClick) + .padding(vertical = 6.dp), + contentAlignment = Alignment.Center, + ) { + Text( + label, style = MaterialTheme.typography.labelSmall, maxLines = 1, overflow = TextOverflow.Ellipsis, + color = when { + !enabled -> p.onBackground.copy(alpha = 0.28f) + selected -> p.primary + else -> p.onBackground.copy(alpha = 0.7f) + }, + ) + } +} + +private fun importImage(context: Context, uri: Uri, codes: List<Int>): String? { + val dir = File(context.filesDir, ScreenKeys.IMAGE_DIR).apply { mkdirs() } + val name = "key_" + codes.joinToString("_") + "_" + System.currentTimeMillis() + ".png" + val longest = (ScreenKeys.MAX_SIZE * context.resources.displayMetrics.density).toInt() + return runCatching { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) } + val source = maxOf(bounds.outWidth, bounds.outHeight) + if (source <= 0) return@runCatching null + var sample = 1 + while (source / (sample * 2) >= longest) sample *= 2 + val bitmap = context.contentResolver.openInputStream(uri)?.use { + BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply { inSampleSize = sample }) + } ?: return@runCatching null + val scale = longest.toFloat() / maxOf(bitmap.width, bitmap.height) + val scaled = if (scale < 1f) { + Bitmap.createScaledBitmap( + bitmap, + (bitmap.width * scale).toInt().coerceAtLeast(1), + (bitmap.height * scale).toInt().coerceAtLeast(1), + true, + ) + } else { + bitmap + } + try { + val saved = File(dir, name).outputStream().use { scaled.compress(Bitmap.CompressFormat.PNG, 100, it) } + if (saved) name else null + } finally { + if (scaled !== bitmap) bitmap.recycle() + scaled.recycle() + } + }.getOrNull().also { if (it == null) File(dir, name).delete() } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyPicker.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyPicker.kt new file mode 100644 index 0000000000..e70249eef2 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyPicker.kt @@ -0,0 +1,169 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.systemBarsPadding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.ui.GlideDialog as Dialog +import androidx.compose.ui.window.DialogProperties +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.PC_KEYS +import com.droiddeck.launcher.input.PC_KEY_ROWS +import com.droiddeck.launcher.input.PC_MODIFIERS +import com.droiddeck.launcher.input.PcKey +import com.droiddeck.launcher.input.pcKeyLabel + +@Composable +fun ScreenKeyPicker( + onDismiss: () -> Unit, + onAdd: (List<Int>) -> Unit, + initial: List<Int> = emptyList(), + sequence: Boolean = false, + sequenceLimit: Int = 4, + slots: List<String> = emptyList(), +) { + var picked by remember { mutableStateOf(initial) } + val p = LocalPalette.current + val toggle: (Int) -> Unit = { code -> + picked = if (sequence) { + if (code in picked) picked - code else (picked + code).take(sequenceLimit) + } else if (code in PC_MODIFIERS) { + if (code in picked) picked - code else picked + code + } else { + picked.filter { it in PC_MODIFIERS } + code + } + } + val rows = remember { + val functionRow = PC_KEY_ROWS[0] + val nav = listOfNotNull(PC_KEYS[110], PC_KEYS[111], PC_KEYS[102], PC_KEYS[107], PC_KEYS[104], PC_KEYS[109]) + + listOfNotNull(PC_KEYS[103], PC_KEYS[105], PC_KEYS[108], PC_KEYS[106]) + listOf(functionRow.take(13), nav) + PC_KEY_ROWS.drop(1) + } + val unit = remember { rows.maxOf { row -> row.fold(0f) { sum, key -> sum + key.weight } } } + Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) { + Box(Modifier.fillMaxSize().systemBarsPadding().padding(10.dp), contentAlignment = Alignment.Center) { + Surface( + Modifier.widthIn(max = 820.dp).fillMaxWidth().fillMaxHeight(), shape = RoundedCornerShape(20.dp), + color = p.background, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2), + ) { + Column { + Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.screen_keys_add), Modifier.weight(1f), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + IconButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Default.Close, null) } + } + Row( + Modifier.fillMaxWidth().heightIn(min = 26.dp).horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically, + ) { + if (sequence && slots.size >= sequenceLimit) { + slots.take(sequenceLimit).forEachIndexed { index, arrow -> + val code = picked.getOrNull(index) + Surface( + shape = RoundedCornerShape(8.dp), + color = if (code == null) p.line2.copy(alpha = 0.2f) else p.primary.copy(alpha = 0.16f), + modifier = if (code == null) Modifier else Modifier.clickable { picked = picked - code }, + ) { + Text( + if (code == null) arrow else "$arrow ${pcKeyLabel(LocalContext.current, code)}", + Modifier.padding(horizontal = 8.dp, vertical = 2.dp), + style = MaterialTheme.typography.labelMedium, + ) + } + } + } else { + picked.forEach { code -> + Surface( + shape = RoundedCornerShape(8.dp), color = p.primary.copy(alpha = 0.16f), + modifier = Modifier.clickable { picked = picked - code }, + ) { + Text(pcKeyLabel(LocalContext.current, code), Modifier.padding(horizontal = 8.dp, vertical = 2.dp), style = MaterialTheme.typography.labelMedium) + } + } + } + } + LazyColumn(Modifier.weight(1f).fillMaxWidth(), contentPadding = PaddingValues(vertical = 6.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + items(rows.size) { index -> + val row = rows[index] + Row( + Modifier.fillMaxWidth().padding(horizontal = 16.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + row.forEach { key -> KeyCell(key, key.code in picked, Modifier.weight(key.weight)) { toggle(key.code) } } + if (row.sumOf { it.weight.toDouble() } < unit) { + Spacer(Modifier.weight(unit - row.fold(0f) { sum, key -> sum + key.weight })) + } + } + } + } + Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button( + onClick = { onAdd(picked) }, + enabled = picked.isNotEmpty(), + modifier = Modifier.weight(1f).focusGlide(CircleShape), + ) { + Text(stringResource(R.string.screen_keys_add)) + } + } + } + } + } + } +} + +@Composable +private fun KeyCell(key: PcKey, selected: Boolean, modifier: Modifier, onClick: () -> Unit) { + val p = LocalPalette.current + val label = pcKeyLabel(LocalContext.current, key.code) + Surface( + shape = RoundedCornerShape(8.dp), + color = if (selected) p.primary.copy(alpha = 0.2f) else p.surface, + border = BorderStroke(1.dp, if (selected) p.primary else p.line), + modifier = modifier.height(36.dp).focusGlide(RoundedCornerShape(8.dp)).clickable(onClick = onClick), + ) { + Box(Modifier.fillMaxSize().padding(horizontal = 2.dp), contentAlignment = Alignment.Center) { + Text( + label, style = MaterialTheme.typography.labelMedium, maxLines = 1, + overflow = TextOverflow.Ellipsis, + fontSize = if (label.length > 4) 10.sp else 12.sp, + ) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScreenLayoutPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScreenLayoutPanel.kt new file mode 100644 index 0000000000..7bc78f7105 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenLayoutPanel.kt @@ -0,0 +1,139 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.shape.CircleShape +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.systemBarsPadding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.ui.GlideDialog as Dialog +import androidx.compose.ui.window.DialogProperties +import com.droiddeck.launcher.R + +@Composable +fun ScreenLayoutPanel( + layouts: List<String>, + onSave: (String) -> Unit, + onLoad: (String) -> Unit, + onDelete: (String) -> Unit, + onImport: (String) -> Unit, + exportText: () -> String, + onDismiss: () -> Unit, +) { + val p = LocalPalette.current + val context = LocalContext.current + var naming by remember { mutableStateOf(false) } + var name by remember { mutableStateOf("") } + + val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri == null) return@rememberLauncherForActivityResult + val text = runCatching { + context.contentResolver.openInputStream(uri)?.use { it.readBytes().toString(Charsets.UTF_8) } + }.getOrNull() + if (text != null) onImport(text) + } + val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri -> + if (uri == null) return@rememberLauncherForActivityResult + runCatching { context.contentResolver.openOutputStream(uri)?.use { it.write(exportText().toByteArray()) } } + } + + Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) { + Box(Modifier.fillMaxSize().systemBarsPadding().padding(16.dp), contentAlignment = Alignment.Center) { + Surface( + Modifier.widthIn(max = 520.dp).fillMaxWidth(), shape = RoundedCornerShape(22.dp), + color = p.background, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2), + ) { + Column(Modifier.padding(start = 20.dp, end = 8.dp, top = 6.dp, bottom = 12.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(R.string.screen_key_layout), Modifier.weight(1f), + style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, + ) + IconButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Default.Close, null) } + } + Row(Modifier.fillMaxWidth().padding(end = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + TextButton(onClick = { naming = true }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.screen_key_layout_save)) } + TextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "*/*")) }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.boot_movie_import)) + } + TextButton(onClick = { exporter.launch("droiddeck-layout.icp") }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.screen_key_layout_export)) + } + } + Column(Modifier.padding(end = 12.dp).heightIn(max = 320.dp).verticalScroll(rememberScrollState())) { + layouts.forEach { layout -> + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text( + layout, Modifier.weight(1f).clickable { onLoad(layout) }.padding(vertical = 14.dp), + style = MaterialTheme.typography.bodyLarge, + ) + TextButton(onClick = { onDelete(layout) }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.common_delete), color = p.error) + } + } + } + } + } + } + } + } + + if (naming) { + Dialog(onDismissRequest = { naming = false }, properties = DialogProperties(usePlatformDefaultWidth = false)) { + Box(Modifier.fillMaxSize().systemBarsPadding().padding(16.dp), contentAlignment = Alignment.Center) { + Surface( + Modifier.widthIn(max = 520.dp).fillMaxWidth(), shape = RoundedCornerShape(22.dp), + color = p.background, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2), + ) { + Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedTextField( + name, { name = it.take(24) }, Modifier.fillMaxWidth().focusGlide(), singleLine = true, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), + ) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = { naming = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } + Button(onClick = { onSave(name.trim()); naming = false }, enabled = name.isNotBlank(), modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.screen_key_layout_save)) + } + } + } + } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt index d1c478eb08..f3dfbcf82d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt @@ -18,6 +18,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.semantics.Role import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.session.LoadingState +import com.droiddeck.launcher.session.PerfHud import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import androidx.compose.animation.core.FastOutSlowInEasing @@ -116,7 +117,7 @@ fun HudText(text: String, graph: FloatArray = FloatArray(0), color: String = "mi @Composable private fun HudGraph(samples: FloatArray, accent: Color, wash: Float) { Canvas(Modifier.width(148.dp).height(44.dp)) { - val maxMs = (samples.maxOrNull() ?: 16.7f).coerceAtLeast(16.7f) + val maxMs = PerfHud.GRAPH_MAX_MS val step = size.width / (samples.size - 1) fun yOf(ms: Float) = size.height * (1f - (ms / maxMs).coerceIn(0f, 1f)) val fillAlpha = wash * 0.5f @@ -331,6 +332,7 @@ private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) { verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(22.dp)) .background(if (hot) colors.onBackground.copy(alpha = 0.08f) else Color.Transparent) + .glideBorder(hot, RoundedCornerShape(22.dp), LocalPalette.current.signal) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onCancel) .padding(horizontal = 12.dp), ) { 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 ef90316ea7..d9a50a20d3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -72,6 +72,8 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme @@ -193,6 +195,7 @@ private class DrawerFocus { class DrawerActions( val steam: Boolean, + val direct: Boolean = false, val title: String? = null, val isHomeApp: Boolean, val androidApps: List<HomeApp.LaunchableApp>, @@ -212,6 +215,8 @@ class DrawerActions( val micEnabled: Boolean = false, val onMicEnabled: (Boolean) -> Unit = {}, val backActionsInverted: Boolean, + val backDoubleTapMs: Int = 500, + val onBackDoubleTapMs: (Int) -> Unit = {}, val padType: String? = null, val onPadType: (String) -> Unit = {}, val touchMode: String, @@ -255,12 +260,14 @@ class DrawerActions( val onSuspendPolicy: (String) -> Unit, val onSteamDownloadsInBackground: (Boolean) -> Unit = {}, val onBackActionsInverted: (Boolean) -> Unit, - val lowLatencyController: Boolean = false, - val lowLatencyTouch: Boolean = false, - val onLowLatencyController: (Boolean) -> Unit = {}, - val onLowLatencyTouch: (Boolean) -> Unit = {}, + val lowLatency: Boolean = true, + val onLowLatency: (Boolean) -> Unit = {}, val onTouch: (String) -> Unit, val onGestureSettings: () -> Unit = {}, + val onScreenKeys: (() -> Unit)? = null, + val onScreenLayouts: (() -> Unit)? = null, + val screenKeysShown: Boolean = true, + val onScreenKeysShown: (Boolean) -> Unit = {}, val onFexPreset: (String) -> Unit, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, @@ -402,6 +409,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) { val short = maxHeight < 440.dp val sheetWidth = minOf(360.dp, maxWidth * 0.92f) + val narrow = sheetWidth < 320.dp AnimatedVisibility( open, enter = slideInHorizontally(Motion.sp(0.8f, Spring.StiffnessLow)) { it } + fadeIn(Motion.tw(220)), @@ -417,16 +425,23 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont .controllerBack { if (host.open != null) host.open = null else a.onClose() } - .padding(if (short) 12.dp else 16.dp), + .padding(12.dp), ) { + val title = a.title ?: if (a.steam) stringResource(R.string.drawer_steam) else stringResource(R.string.drawer_desktop) + if (narrow) Text(title, fontSize = 18.sp, fontWeight = FontWeight.Bold, + color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp), ) { - Text(a.title ?: if (a.steam) stringResource(R.string.drawer_steam) else stringResource(R.string.drawer_desktop), fontSize = if (short) 18.sp else 20.sp, fontWeight = FontWeight.Bold, + if (narrow) Spacer(Modifier.weight(1f)) else Text(title, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) - if (a.onSteamMenu != null && a.onQam != null) { + if (a.pipSupported) SteamActionPill( + stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"), + ) { host.open = null; a.onPip() } + if (a.steam && a.onSteamMenu != null && a.onQam != null) { val qamInteraction = remember { MutableInteractionSource() } var qamStartedOnPress by remember { mutableStateOf(false) } LaunchedEffect(qamInteraction) { @@ -438,13 +453,13 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } } - SteamActionPill(stringResource(R.string.drawer_steam_menu), Icons.Outlined.Home, focus.track(page, "steam")) { + SteamActionPill(stringResource(R.string.drawer_steam_menu), Icons.Outlined.Home, focus.track(page, "steam"), shortcut = "⧉") { host.open = null a.onSteamMenu.invoke() } SteamActionPill( stringResource(R.string.drawer_open_qam), Icons.Outlined.MoreHoriz, focus.track(page, "qam"), - interactionSource = qamInteraction, + interactionSource = qamInteraction, shortcut = "☰", onConfirm = { host.open = null; a.onQam.invoke() }, ) { host.open = null @@ -462,12 +477,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont Row( verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth().padding(top = if (short) 6.dp else 12.dp), + modifier = Modifier.fillMaxWidth().padding(top = 6.dp), ) { DrawerBumper("LB", stringResource(R.string.drawer_prev_page), modifier = focus.track(page, "prev")) { host.open = null; onPageChange(pages.step(page, -1)) } - DrawerPageTabs(page = page, pages = pages, compact = short, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) } + DrawerPageTabs(page = page, pages = pages, compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) } DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) { host.open = null; onPageChange(pages.step(page, 1)) } @@ -478,7 +493,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont ) { selectedGlassesTab = it } Column( modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)), - ) { CompositionLocalProvider(LocalChipMinWidth provides 120.dp) { + ) { CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) { when (page) { SessionDrawerPage.DISPLAY -> { SettingsGroup(stringResource(R.string.drawer_page_display)) { @@ -549,9 +564,28 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null, listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch) - ActionRow(stringResource(R.string.gesture_settings), stringResource(R.string.gesture_settings_hint), - stringResource(R.string.ctrl_edit), a.onGestureSettings, - modifier = focus.track(page, "gesture-settings")) + if (a.touchMode == SessionPrefs.TOUCH_GESTURES) { + ActionRow(stringResource(R.string.gesture_settings), null, + stringResource(R.string.ctrl_edit), a.onGestureSettings, + modifier = focus.track(page, "gesture-settings")) + } + if (a.onScreenKeys != null) { + SettingsRow(stringResource(R.string.screen_keys), null, stacked = narrow) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + SecondaryButton(stringResource(R.string.ctrl_edit), + modifier = focus.track(page, "screen-keys"), onClick = a.onScreenKeys) + a.onScreenLayouts?.let { open -> + SecondaryButton(stringResource(R.string.screen_key_layout), + modifier = focus.track(page, "screen-key-layouts"), onClick = open) + } + ToggleSwitch(a.screenKeysShown, true, + modifier = focus.track(page, "screen-keys-shown"), onChange = a.onScreenKeysShown) + } + } + } ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null, if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)) else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), @@ -577,6 +611,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.mode_back), null, listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)), a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted) + if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null, + SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) }, + a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs) if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), stringResource(R.string.unfolded_controls_hint), a.unfoldedControls, chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls) @@ -587,12 +624,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont onChange = a.onUnfoldedControlsWithController) } SettingsGroup(stringResource(R.string.drawer_latency)) { - ToggleRow(host, "low-latency-controller", stringResource(R.string.drawer_low_latency_controller), - stringResource(R.string.drawer_low_latency_controller_hint), a.lowLatencyController, - chipModifier = focus.track(page, "low-latency-controller"), onChange = a.onLowLatencyController) - ToggleRow(host, "low-latency-touch", stringResource(R.string.drawer_low_latency_touch), - stringResource(R.string.drawer_low_latency_touch_hint), a.lowLatencyTouch, - chipModifier = focus.track(page, "low-latency-touch"), onChange = a.onLowLatencyTouch) + ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency), + stringResource(R.string.drawer_low_latency_hint), a.lowLatency, + chipModifier = focus.track(page, "low-latency"), onChange = a.onLowLatency) } SettingsGroup(stringResource(R.string.drawer_keyboard)) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) { @@ -616,11 +650,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont steamVr = { SteamVrRow(a) }) } SessionDrawerPage.GAMES -> { - if (a.steam) SelectedGameProfileGroup(host, a) { key -> focus.track(page, key) } + if (a.steam || a.direct) SelectedGameProfileGroup(host, a) { key -> focus.track(page, key) } Text(stringResource(R.string.fex_next_launch), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) TextureFilteringGroup(host, a) { key -> focus.track(page, key) } - if (a.steam) SettingsGroup(stringResource(R.string.game_settings_title)) { + if (a.steam || a.direct) SettingsGroup(stringResource(R.string.game_settings_title)) { DrawerFexPresetRow(host, a, focus.track(page, "fex")) DrawerNoSteamRow(host, a, focus.track(page, "no-steam")) GameEnvironmentRow( @@ -711,8 +745,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont a.pipAutoEnter, onChange = a.onPipAutoEnter) } Column(Modifier.fillMaxWidth().padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - if (a.pipSupported) DrawerActionButton(stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, - modifier = focus.track(page, "pip")) { host.open = null; a.onPip() } if (!a.isHomeApp) DrawerActionButton(stringResource(R.string.drawer_background), Icons.AutoMirrored.Outlined.ExitToApp, modifier = focus.track(page, "background")) { host.open = null; a.onBackground() } } @@ -784,10 +816,10 @@ private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, pro OutlinedButton( onClick = onClick, interactionSource = source, - modifier = modifier.controllerConfirm(onClick = onClick), + modifier = modifier.controllerConfirm(onClick = onClick).focusGlide(RoundedCornerShape(12.dp)), shape = RoundedCornerShape(12.dp), contentPadding = PaddingValues(horizontal = 12.dp), - border = BorderStroke(if (hot) 2.dp else 1.dp, if (hot) pal.signal else colors.outline), + border = BorderStroke(1.dp, colors.outline), colors = ButtonDefaults.outlinedButtonColors(containerColor = if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent), ) { ProgressLabel({ m -> Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = m) }, progress, fontSize = 13.sp) } } @@ -818,6 +850,7 @@ private fun SteamActionPill( description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, modifier: Modifier, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, onConfirm: (() -> Unit)? = null, + shortcut: String? = null, onClick: () -> Unit, ) { val colors = MaterialTheme.colorScheme @@ -826,7 +859,7 @@ private fun SteamActionPill( val shape = RoundedCornerShape(22.dp) Box( contentAlignment = Alignment.Center, - modifier = modifier.size(width = 52.dp, height = 44.dp).semantics { contentDescription = description } + modifier = modifier.size(44.dp).semantics { contentDescription = description } .clip(shape).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(interactionSource) @@ -834,6 +867,10 @@ private fun SteamActionPill( .controllerConfirm(onClick = onConfirm ?: onClick), ) { Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(20.dp)) + if (shortcut != null) Text( + shortcut, fontSize = 8.sp, lineHeight = 9.sp, color = colors.onSurfaceVariant, + modifier = Modifier.align(Alignment.BottomEnd).padding(end = 8.dp, bottom = 6.dp), + ) } } @@ -873,16 +910,22 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds().selectableGroup(), ) { val tab = if (compact) 36f else 44f + val scrolling = maxWidth < (tab + (count - 1) * 24f).dp + val scroll = rememberScrollState() + val density = LocalDensity.current.density + LaunchedEffect(scrolling, selectedIndex, maxWidth) { + if (scrolling) scroll.animateScrollTo(((selectedIndex * (tab + 4f) + tab / 2f - maxWidth.value / 2f) * density).roundToInt().coerceAtLeast(0)) + } val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(24f, DRAWER_TAB_SPACING_DP) val leanStep = DRAWER_TAB_LEAN_DP * spacing / DRAWER_TAB_SPACING_DP val lean by animateFloatAsState(-(selectedIndex - middle) * leanStep, motion, label = "tabLean") - pages.forEachIndexed { index, item -> + @Composable fun tabs() { pages.forEachIndexed { index, item -> androidx.compose.runtime.key(item) { val selected = item == page val source = remember { MutableInteractionSource() } val focused = source.collectIsFocusedAsState().value - val scale by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_SCALE, motion, label = "tabScale") - val alpha by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_ALPHA, motion, label = "tabAlpha") + val scale by animateFloatAsState(if (selected || scrolling) 1f else DRAWER_TAB_SIDE_SCALE, motion, label = "tabScale") + val alpha by animateFloatAsState(if (selected || scrolling) 1f else DRAWER_TAB_SIDE_ALPHA, motion, label = "tabAlpha") val glow by animateFloatAsState(if (selected) 1f else 0f, motion, label = "tabGlow") val pageDescription = stringResource(R.string.drawer_page_desc, stringResource(item.title)) val tint by animateColorAsState(if (selected) colors.onBackground else colors.onSurfaceVariant, Motion.tw(340, easing = FastOutSlowInEasing), label = "tabTint") @@ -890,7 +933,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag Box( contentAlignment = Alignment.Center, modifier = Modifier - .offset(x = ((index - middle) * spacing + lean).dp) + .then(if (scrolling) Modifier else Modifier.offset(x = ((index - middle) * spacing + lean).dp)) .size(tab.dp) .graphicsLayer { scaleX = scale; scaleY = scale; this.alpha = alpha } .clip(RoundedCornerShape(16.dp)) @@ -910,6 +953,9 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag } } } + } + if (scrolling) Row(Modifier.fillMaxWidth().horizontalScroll(scroll), horizontalArrangement = Arrangement.spacedBy(4.dp)) { tabs() } + else tabs() } } @@ -1359,6 +1405,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin val pal = LocalPalette.current Column( modifier = Modifier.fillMaxWidth().then(track("cmp-running")) + .glideBorder(hot, Shape12, pal.signal) .focusable(interactionSource = src) .background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent) .padding(horizontal = 14.dp, vertical = 11.dp), @@ -1634,6 +1681,7 @@ private fun StopConfirm( Box(Modifier.fillMaxSize()) { Box( Modifier.fillMaxSize().graphicsLayer { alpha = dim.value }.background(Color(0x59000000)) + .focusProperties { canFocus = false } .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, enabled = open, onClick = onCancel), ) val path = remember { Path() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionPausedOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionPausedOverlay.kt index b7f5cbfebe..afe9f0ba4c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionPausedOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionPausedOverlay.kt @@ -17,6 +17,7 @@ import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.fillMaxSize @@ -168,6 +169,8 @@ fun SessionPausedOverlay( runCatching { focus.requestFocus() } } val resumeLabel = stringResource(R.string.resume_session) + val source = remember { MutableInteractionSource() } + val focused by source.collectIsFocusedAsState() Box( contentAlignment = Alignment.Center, modifier = Modifier @@ -176,7 +179,7 @@ fun SessionPausedOverlay( .focusRequester(focus) .controllerConfirm(enabled = idle, onClick = onResume) .clickable( - interactionSource = remember { MutableInteractionSource() }, + interactionSource = source, indication = null, role = Role.Button, onClickLabel = resumeLabel, @@ -187,7 +190,7 @@ fun SessionPausedOverlay( } else { Box(Modifier.fillMaxSize().graphicsLayer { alpha = presence }.background(Color.Black.copy(alpha = 0.55f))) } - ResumeOrb(orb.value, press.value, ring.value, shake.value, idle) + ResumeOrb(orb.value, press.value, ring.value, shake.value, idle, focused) } } @@ -221,7 +224,7 @@ private fun BoxScope.PausedCard(frame: PausedFrame, lift: Float, presence: Float } @Composable -private fun ResumeOrb(presence: Float, press: Float, ring: Float, shake: Float, idle: Boolean) { +private fun ResumeOrb(presence: Float, press: Float, ring: Float, shake: Float, idle: Boolean, focused: Boolean) { val glintAlpha by animateFloatAsState(if (idle) 1f else 0f, Motion.tw(160), label = "glintAlpha") val glint: State<Float>? = if (Motion.scale > 0f) { rememberInfiniteTransition(label = "glint").animateFloat( @@ -245,6 +248,7 @@ private fun ResumeOrb(presence: Float, press: Float, ring: Float, shake: Float, } .clip(CircleShape) .background(Color.White.copy(alpha = 0.08f)) + .glideBorder(focused, CircleShape, Color.White, hotFillAlpha = 0f) .drawWithContent { drawContent() val stroke = 2.5.dp.toPx() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 0d8909d825..6725ac3193 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -113,7 +113,7 @@ import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import androidx.compose.ui.window.Popup +import com.droiddeck.launcher.ui.GlidePopup as Popup import androidx.compose.ui.window.PopupPositionProvider import androidx.compose.ui.window.PopupProperties @@ -230,6 +230,7 @@ private fun BumperKey(label: String, description: String, onClick: () -> Unit) { } val LocalChipMinWidth = androidx.compose.runtime.compositionLocalOf { 150.dp } +internal val LocalCompactSettings = androidx.compose.runtime.compositionLocalOf { false } class MenuHost { var open by mutableStateOf<String?>(null) @@ -368,6 +369,7 @@ fun MenuItem( .then(focusRequester?.let { Modifier.focusRequester(it) } ?: Modifier) .clip(RoundedCornerShape(8.dp)) .background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent) + .glideBorder(hot && enabled, RoundedCornerShape(8.dp), pal.signal) .alpha(if (enabled) 1f else 0.4f) .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) @@ -388,6 +390,7 @@ fun MenuItem( @Composable fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Modifier = Modifier, onClick: () -> Unit) { + val compact = LocalCompactSettings.current val colors = MaterialTheme.colorScheme val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value @@ -404,30 +407,34 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo .alpha(if (enabled) 1f else 0.5f) .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) - .padding(horizontal = 12.dp, vertical = 8.dp), + .padding(horizontal = if (compact) 10.dp else 12.dp, vertical = if (compact) 6.dp else 8.dp), ) { AnimatedContent( targetState = text, transitionSpec = { (fadeIn(Motion.tw(260)) + slideInVertically(Motion.tw(260)) { it / 2 }) togetherWith (fadeOut(Motion.tw(160)) + slideOutVertically(Motion.tw(160)) { -it / 2 }) }, label = "chipText", - ) { t -> Text(t, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) } + ) { t -> Text(t, fontSize = if (compact) 12.sp else 13.sp, + lineHeight = if (compact) 16.sp else androidx.compose.ui.unit.TextUnit.Unspecified, + fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) } Spacer(Modifier.width(8.dp)) Text("▾", fontSize = 10.sp, color = colors.onSurfaceVariant, modifier = Modifier.rotate(rot)) } } @Composable -fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ColumnScope.() -> Unit) { +fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, content: @Composable ColumnScope.() -> Unit) { + val tight = compact || LocalCompactSettings.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current Column(Modifier.fillMaxWidth().sheetPiece()) { Row( verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(if (compact) 6.dp else 10.dp), - modifier = Modifier.fillMaxWidth().padding(top = if (compact) 4.dp else 16.dp, bottom = if (compact) 3.dp else 6.dp), + horizontalArrangement = Arrangement.spacedBy(if (tight) 6.dp else 10.dp), + modifier = Modifier.fillMaxWidth().padding(top = if (tight) 4.dp else 16.dp, bottom = if (tight) 3.dp else 6.dp), ) { - Text(title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant) + Text(title.uppercase(), fontSize = if (tight) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant) Box(modifier = Modifier.weight(1f).height(1.dp).background(pal.line)) + if (detail != null) Text(detail, fontSize = if (tight) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant) } Column(modifier = Modifier.fillMaxWidth().clip(GroupShape).background(colors.surface).border(1.dp, pal.line, GroupShape)) { content() } } @@ -435,19 +442,34 @@ fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable @Composable fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, stacked: Boolean = false, control: @Composable () -> Unit) { + val compact = LocalCompactSettings.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val bg by animateColorAsState(if (highlighted) pal.signal.copy(alpha = 0.10f) else Color.Transparent, Motion.tw(200), label = "rowBg") val hintText: @Composable (androidx.compose.ui.unit.TextUnit) -> Unit = { size -> Text(hint ?: "", fontSize = size, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp), + lineHeight = if (compact) 14.sp else androidx.compose.ui.unit.TextUnit.Unspecified, minLines = hintLines ?: 1, maxLines = hintLines ?: Int.MAX_VALUE, overflow = TextOverflow.Ellipsis) } - if (stacked || LocalNarrowPane.current) Column( - modifier = Modifier.fillMaxWidth().background(bg).padding(start = 14.dp, end = 14.dp, top = 11.dp, bottom = 12.dp), + if (compact && !stacked) Column( + modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp), ) { - Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) - if (hint != null || hintLines != null) hintText(13.sp) - Box(Modifier.padding(top = 8.dp)) { control() } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(label, fontSize = 13.sp, lineHeight = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, + modifier = Modifier.weight(1f)) + control() + } + if (hint != null || hintLines != null) hintText(11.sp) + } else if (stacked || LocalNarrowPane.current) Column( + modifier = Modifier.fillMaxWidth().background(bg).padding( + horizontal = if (compact) 10.dp else 14.dp, + vertical = if (compact) 6.dp else 12.dp), + ) { + Text(label, fontSize = if (compact) 13.sp else 15.sp, + lineHeight = if (compact) 16.sp else androidx.compose.ui.unit.TextUnit.Unspecified, + fontWeight = FontWeight.SemiBold, color = colors.onBackground) + if (hint != null || hintLines != null) hintText(if (compact) 11.sp else 13.sp) + Box(Modifier.padding(top = if (compact) 6.dp else 8.dp)) { control() } } else Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp), @@ -560,6 +582,7 @@ fun ValueSlider( value: Int, range: IntRange, step: Int, enabled: Boolean, label: String?, format: (Int) -> String, modifier: Modifier = Modifier, onChange: (Int) -> Unit, ) { + val compact = LocalCompactSettings.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val source = remember { MutableInteractionSource() } @@ -580,7 +603,7 @@ fun ValueSlider( } } Column( - modifier = modifier.fillMaxWidth().heightIn(min = 72.dp) + modifier = modifier.fillMaxWidth().heightIn(min = if (compact) 64.dp else 72.dp) .clip(shape).background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent) .glideBorder(hot, shape, pal.signal) .alpha(if (enabled) 1f else 0.5f) @@ -609,10 +632,10 @@ fun ValueSlider( .padding(horizontal = 8.dp, vertical = 6.dp), ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { - if (label != null) Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, + if (label != null) Text(label, fontSize = if (compact) 13.sp else 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f)) else Spacer(Modifier.weight(1f)) - Text(text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1) + Text(text, fontSize = if (compact) 12.sp else 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1) } Canvas( Modifier.fillMaxWidth().height(40.dp).onSizeChanged { trackPx = it.width } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SpatialTrackingActivity.kt b/app/src/main/java/com/droiddeck/launcher/ui/SpatialTrackingActivity.kt index 3b77e09f0f..a3dc1f4d65 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SpatialTrackingActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SpatialTrackingActivity.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.shape.CircleShape import android.os.Bundle import android.os.CancellationSignal import android.os.ParcelFileDescriptor @@ -242,8 +243,8 @@ internal fun SpatialSetupScreen( if (confirmRestart) AlertDialog( onDismissRequest = { confirmRestart = false }, title = { Text(stringResource(R.string.spatial_restart_title)) }, text = { Text(stringResource(R.string.spatial_restart_confirm)) }, - confirmButton = { TextButton(onClick = { confirmRestart = false; actions.restart() }) { Text(stringResource(R.string.spatial_restart)) } }, - dismissButton = { TextButton(onClick = { confirmRestart = false }) { Text(stringResource(R.string.common_cancel)) } }, + confirmButton = { TextButton(onClick = { confirmRestart = false; actions.restart() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.spatial_restart)) } }, + dismissButton = { TextButton(onClick = { confirmRestart = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } 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 dfb6d2525d..4a93056dda 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -128,7 +128,7 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) }, onOpen = a.onSteamSettings, onPrimary = a.onPlay, modifier = modifier.clipToBounds(), - start = if (narrow) 20.dp else 44.dp, bottom = if (narrow) 20.dp else 44.dp, + start = if (narrow) 20.dp else 44.dp, bottom = 44.dp, background = { when { games.isEmpty() -> EmptyLibrary( @@ -141,12 +141,22 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) }, scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() }, words = { - Row( + val runtimeStatus: @Composable () -> Unit = { + if (s.busy || !s.ready || (s.available != null && s.available != s.installed)) RuntimeChip(s) + else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) + IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration) + } + if (narrow) Column( + verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() }, + ) { + Wordmark(30.dp) + runtimeStatus() + } else Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() }, ) { Wordmark(if (narrow) 30.dp else 40.dp) - if (s.busy || !s.ready || (s.available != null && s.available != s.installed)) RuntimeChip(s) + runtimeStatus() } }, button = { click -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt new file mode 100644 index 0000000000..d7f030695d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt @@ -0,0 +1,215 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.animation.animateColorAsState +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.shape.CircleShape +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.Home +import androidx.compose.material.icons.outlined.KeyboardCommandKey +import androidx.compose.material.icons.outlined.LightMode +import androidx.compose.material.icons.outlined.Wifi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.core.SteamIntegration +import com.droiddeck.launcher.core.SteamIntegration.Feature + +private val BadgeShape = RoundedCornerShape(10.dp) + +internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) { + Feature.WIFI -> wifi && locationPermission && locationOn + Feature.BRIGHTNESS -> brightness + Feature.HOME -> home + Feature.SHORTCUTS -> home && shortcuts +} + +internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) } + +@Composable +internal fun SteamIntegrationGroup( + state: SteamIntegration.State, + focus: Feature? = null, + onFeature: (Feature) -> Unit, + onAppInfo: () -> Unit, + onLocation: () -> Unit = {}, +) { + SettingsGroup( + stringResource(R.string.integration_title), + detail = stringResource(R.string.integration_count, state.enabledCount(), Feature.entries.size), + ) { + Feature.entries.forEachIndexed { i, feature -> + IntegrationRow(state, feature, focus == feature, i < Feature.entries.lastIndex, onFeature, onAppInfo, onLocation) + } + } +} + +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) +@Composable +private fun IntegrationRow( + state: SteamIntegration.State, + feature: Feature, + focused: Boolean, + divider: Boolean, + onFeature: (Feature) -> Unit, + onAppInfo: () -> Unit, + onLocation: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val on = state.enabled(feature) + var flash by remember { mutableStateOf(false) } + val reveal = remember { BringIntoViewRequester() } + LaunchedEffect(focused) { + if (focused) try { flash = true; reveal.bringIntoView(); kotlinx.coroutines.delay(1600) } finally { flash = false } + } + val bg by animateColorAsState(if (flash) pal.signal.copy(alpha = 0.12f) else Color.Transparent, Motion.tw(400), label = "integrationFlash") + val wifiLocationOff = feature == Feature.WIFI && state.wifi && state.locationPermission && !state.locationOn + val wifiDenied = feature == Feature.WIFI && !state.locationPermission && state.locationBlocked + val needsHome = feature == Feature.SHORTCUTS && !state.home + val restricted = feature == Feature.SHORTCUTS && !needsHome && !state.shortcuts && state.shortcutsRestricted + val maybeRestricted = feature == Feature.SHORTCUTS && !needsHome && !state.shortcuts && !restricted && state.shortcutsTried && + android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU + val hint = stringResource(when { + wifiLocationOff -> R.string.integration_wifi_location_off + wifiDenied -> R.string.integration_wifi_denied + needsHome -> R.string.integration_shortcuts_needs_home + restricted -> R.string.integration_shortcuts_restricted + maybeRestricted -> R.string.integration_shortcuts_maybe_restricted + 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 + else -> R.string.integration_shortcuts_hint + }) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + modifier = Modifier.fillMaxWidth().bringIntoViewRequester(reveal).background(bg).heightIn(min = 64.dp) + .padding(horizontal = 14.dp, vertical = 10.dp) + .testTag("integration-${feature.name.lowercase()}"), + ) { + FeatureBadge(featureIcon(feature), on) + Column(Modifier.weight(1f)) { + Text(stringResource(featureTitle(feature)), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, + maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(hint, fontSize = 13.sp, color = if (wifiLocationOff || wifiDenied || restricted) AttentionAmber else colors.onSurfaceVariant, + maxLines = 1, overflow = TextOverflow.Ellipsis) + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + when { + wifiLocationOff -> SecondaryButton(stringResource(R.string.integration_location), compact = true, onClick = onLocation) + wifiDenied -> SecondaryButton(stringResource(R.string.integration_app_info), compact = true, onClick = onLocation) + restricted || maybeRestricted -> SecondaryButton(stringResource(R.string.integration_app_info), compact = true, onClick = onAppInfo) + } + val checked = if (feature == Feature.WIFI) state.wifi && state.locationPermission else on + ToggleSwitch(checked, enabled = !needsHome && !restricted, label = stringResource(featureTitle(feature)), + modifier = Modifier.testTag("integration-action-${feature.name.lowercase()}")) { onFeature(feature) } + } + } + if (divider) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) +} + +@Composable +private fun FeatureBadge(icon: ImageVector, on: Boolean) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val tint by animateColorAsState(if (on) pal.good else colors.onSurfaceVariant, Motion.tw(250), label = "badgeTint") + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.size(36.dp).clip(BadgeShape) + .background(if (on) pal.good.copy(alpha = 0.14f) else colors.surfaceVariant) + .border(1.dp, if (on) pal.good.copy(alpha = 0.3f) else pal.line2, BadgeShape), + ) { Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(19.dp)) } +} + +private fun featureIcon(feature: Feature) = when (feature) { + Feature.WIFI -> Icons.Outlined.Wifi + Feature.BRIGHTNESS -> Icons.Outlined.LightMode + Feature.HOME -> Icons.Outlined.Home + Feature.SHORTCUTS -> Icons.Outlined.KeyboardCommandKey +} + +private fun featureTitle(feature: Feature) = when (feature) { + Feature.WIFI -> R.string.integration_wifi + Feature.BRIGHTNESS -> R.string.integration_brightness + Feature.HOME -> R.string.integration_home + Feature.SHORTCUTS -> R.string.integration_shortcuts +} + +@Composable +internal fun IntegrationSuggestion(state: SteamIntegration.State, onOpen: () -> Unit, onLater: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val pill = RoundedCornerShape(99.dp) + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.clip(pill).background(colors.surfaceVariant.copy(alpha = 0.85f)) + .border(1.dp, pal.signal.copy(alpha = 0.3f), pill).testTag("integration-suggestion"), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.heightIn(min = 40.dp).clip(pill).glideBorder(hot, pill, pal.signal, Color.Transparent) + .hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onOpen) + .controllerConfirm(onClick = onOpen) + .padding(start = 12.dp, end = 10.dp, top = 6.dp, bottom = 6.dp), + ) { + Icon(Icons.Outlined.AutoAwesome, contentDescription = null, tint = pal.signal, modifier = Modifier.size(16.dp)) + Text(stringResource(R.string.integration_title), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1) + Text(stringResource(R.string.integration_count, state.enabledCount(), Feature.entries.size), fontSize = 12.sp, + color = colors.onSurfaceVariant, maxLines = 1) + } + val closeSrc = remember { MutableInteractionSource() } + val closeHot = rememberHot(closeSrc) + val later = stringResource(R.string.integration_later) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.padding(end = 4.dp).size(32.dp).clip(CircleShape) + .background(if (closeHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) + .glideBorder(closeHot, CircleShape, pal.signal, Color.Transparent) + .hoverable(closeSrc).clickable(role = Role.Button, interactionSource = closeSrc, indication = LocalIndication.current, onClick = onLater) + .controllerConfirm(onClick = onLater) + .semantics { contentDescription = later }, + ) { Icon(Icons.Outlined.Close, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.size(16.dp)) } + } +} 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 8b1ec5340c..badd3f1f4d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt @@ -1,5 +1,9 @@ package com.droiddeck.launcher.ui +import android.app.Activity +import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.LocalIndication @@ -43,7 +47,7 @@ import androidx.compose.material.icons.outlined.SaveAlt import androidx.compose.material.icons.outlined.ShoppingBag import androidx.compose.material.icons.outlined.Storage import androidx.compose.material.icons.outlined.VideogameAsset -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme @@ -51,6 +55,7 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable @@ -65,6 +70,7 @@ import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role @@ -74,6 +80,7 @@ import androidx.compose.ui.unit.dp 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.SessionPrefs import com.droiddeck.launcher.storage.Bucket import com.droiddeck.launcher.storage.CleanItem @@ -84,6 +91,8 @@ import com.droiddeck.launcher.storage.StorageState import com.droiddeck.launcher.storage.ToolReason import com.droiddeck.launcher.storage.ToolState import com.droiddeck.launcher.storage.ToolUsage +import com.droiddeck.launcher.stores.StoreInstallRoot +import java.io.File import java.text.DateFormat import java.util.Date @@ -144,6 +153,113 @@ internal fun StoragePanel(s: FrontEndState, a: FrontEndActions) { } } +@Composable +private fun DefaultStorageGroup() { + val ctx = LocalContext.current + var value by remember { mutableStateOf(SessionPrefs.defaultStorage(ctx)) } + var open by remember { mutableStateOf(false) } + var revision by remember { mutableIntStateOf(0) } + val customPath = SessionPrefs.defaultStorageFolder(ctx) + val customTarget = remember(customPath, revision) { StoreInstallRoot.customTarget(ctx) } + val detected = remember(customPath, revision) { StoreInstallRoot.detectedExternalTarget(ctx) } + val customLabel = SessionPrefs.defaultStorageFolderLabel(ctx).ifBlank { + customPath.takeIf { it.isNotBlank() }?.let { File(it).name }.orEmpty() + } + val pickFolder = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + if (result.resultCode != Activity.RESULT_OK) return@rememberLauncherForActivityResult + val path = InAppFilePicker.pickedPath(result.data) ?: return@rememberLauncherForActivityResult + val problem = StoreInstallRoot.prepareDefaultFolder(ctx, File(path)) + if (problem != null) { + Toast.makeText(ctx, ctx.getString(R.string.main_storage_not_usable, problem), Toast.LENGTH_LONG).show() + return@rememberLauncherForActivityResult + } + SessionPrefs.setDefaultStorageFolder(ctx, path, StoreInstallRoot.folderLabel(ctx, File(path))) + SessionPrefs.setDefaultStorage(ctx, SessionPrefs.DEFAULT_STORAGE_EXTERNAL) + value = SessionPrefs.DEFAULT_STORAGE_EXTERNAL + revision++ + open = false + } + fun chooseFolder() { + open = false + val initial = customPath.takeIf { it.isNotBlank() && File(it).isDirectory } + ?: detected?.root?.parentFile?.takeIf { it.isDirectory }?.absolutePath + pickFolder.launch(InAppFilePicker.buildDirIntent(ctx, ctx.getString(R.string.storage_default_choose_folder), initial)) + } + val title = stringResource(R.string.storage_default_title) + val chip = when (value) { + SessionPrefs.DEFAULT_STORAGE_INTERNAL -> stringResource(R.string.storage_default_internal) + SessionPrefs.DEFAULT_STORAGE_EXTERNAL -> when { + customPath.isNotBlank() -> customTarget?.label + ?: "$customLabel · ${stringResource(R.string.storage_default_folder_missing)}" + detected != null -> detected.label + else -> stringResource(R.string.storage_default_external) + } + else -> stringResource(R.string.storage_default_ask) + } + fun pick(next: String) { + SessionPrefs.setDefaultStorage(ctx, next) + value = next + open = false + } + SettingsGroup(stringResource(R.string.storage_default_group)) { + SettingsRow(label = title, hint = stringResource(R.string.storage_default_hint)) { + Box { + ValueChip(chip, open, modifier = Modifier.testTag("setting-default-storage")) { open = !open } + AnchoredMenu( + open, onDismiss = { open = false }, title = title, + note = stringResource(R.string.storage_default_note), + ) { firstItemFocus -> + MenuItem( + stringResource(R.string.storage_default_ask), value == SessionPrefs.DEFAULT_STORAGE_ASK, + detail = stringResource(R.string.storage_default_ask_detail), + focusRequester = firstItemFocus, + ) { pick(SessionPrefs.DEFAULT_STORAGE_ASK) } + MenuItem( + stringResource(R.string.storage_default_internal), value == SessionPrefs.DEFAULT_STORAGE_INTERNAL, + ) { pick(SessionPrefs.DEFAULT_STORAGE_INTERNAL) } + if (detected == null && customPath.isBlank()) { + MenuItem( + stringResource(R.string.storage_default_external), value == SessionPrefs.DEFAULT_STORAGE_EXTERNAL, + detail = stringResource(R.string.storage_default_choose_folder_detail), + ) { chooseFolder() } + } else { + if (detected != null) { + MenuItem( + stringResource(R.string.storage_default_external), + value == SessionPrefs.DEFAULT_STORAGE_EXTERNAL && customPath.isBlank(), + detail = detected.let { target -> + val free = target.freeBytes + if (free >= 0) stringResource(R.string.storage_default_external_detail, target.label, gb(free)) + else target.label + }, + ) { + SessionPrefs.clearDefaultStorageFolder(ctx) + pick(SessionPrefs.DEFAULT_STORAGE_EXTERNAL) + revision++ + } + } + if (customPath.isNotBlank()) { + MenuItem( + stringResource(R.string.storage_default_folder, customLabel), + value == SessionPrefs.DEFAULT_STORAGE_EXTERNAL, + detail = customTarget?.let { target -> + val free = target.freeBytes + 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() } + } + MenuItem( + stringResource(R.string.storage_default_choose_folder), checked = false, + detail = stringResource(R.string.storage_default_choose_folder_detail), + ) { chooseFolder() } + } + } + } + } + } +} + @OptIn(ExperimentalLayoutApi::class) @Composable private fun Overview(report: StorageReport, sessionRunning: Boolean, onCleanUp: () -> Unit, onOpen: (String) -> Unit) { @@ -189,6 +305,7 @@ private fun Overview(report: StorageReport, sessionRunning: Boolean, onCleanUp: Spacer(Modifier.height(8.dp)) Note(stringResource(R.string.storage_session_running)) } + DefaultStorageGroup() SectionTitle(stringResource(R.string.storage_where), null) val unused = report.unusedTools.sumOf { it.bytes } val tiles = listOf<@Composable (Modifier) -> Unit>( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt index e2ab2a77f1..642160b158 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt @@ -11,7 +11,7 @@ import androidx.compose.runtime.mutableIntStateOf import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle -import androidx.compose.ui.window.Dialog +import com.droiddeck.launcher.ui.GlideDialog as Dialog import androidx.compose.ui.window.DialogProperties import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.background diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt index e913dc6afc..40bfd22c4c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt @@ -31,6 +31,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) { Store.AMAZON.id -> SourceColours(Color(0xFF3A2A0A), Color(0xFFFFC266), Color(0xFFFF9900)) Store.XBOX.id -> SourceColours(Color(0xFF17381B), Color(0xFFC6EDC2), Color(0xFF70C850)) Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C)) + Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF)) Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF)) FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal) else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF)) @@ -44,6 +45,7 @@ internal fun sourceLabel(source: String): String = when (source) { Store.AMAZON.id -> Store.AMAZON.label Store.XBOX.id -> Store.XBOX.label Store.ITCH.id -> Store.ITCH.label + Store.BATTLENET.id -> Store.BATTLENET.label else -> stringResource(R.string.source_added) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt index 0facc0c070..e3724dd83d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt @@ -157,7 +157,7 @@ private fun FlathubHero(s: FrontEndState, ring: Int) { StoreState.sections.values.flatten().mapNotNull { it.icon }.distinct().take(48).takeIf { it.size >= 8 }.orEmpty() } val busy = StoreState.busy == "setup" - BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp)) { + BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = if (narrow) 14.dp else 22.dp).padding(top = if (narrow) 10.dp else 14.dp)) { val shape = RoundedCornerShape(20.dp) Box(Modifier.fillMaxWidth().height(maxHeight.coerceAtLeast(320.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) { androidx.compose.animation.Crossfade(icons, animationSpec = Motion.tw(600), label = "flathubWall") { tiles -> @@ -240,7 +240,7 @@ private fun SetupButton(s: FrontEndState, busy: Boolean, full: Dp, ring: Int, on drawRect(Brush.horizontalGradient(listOf(Color.Transparent, FlathubTeal.copy(alpha = 0.55f), Color.Transparent), startX = size.width * sweep - w, endX = size.width * sweep + w)) } } - .focusable() + .focusGlide(shape, FlathubTeal).focusable() .semantics { contentDescription = label } .padding(horizontal = 20.dp, vertical = 16.dp), ) { @@ -316,7 +316,7 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) { } Column( - Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp) + Modifier.fillMaxSize().padding(horizontal = padH).padding(top = if (narrow) 10.dp else 14.dp) .bumpers( onPrevious = { if (openApp == null) mode = modes[(modes.indexOf(mode) + modes.size - 1) % modes.size] }, onNext = { if (openApp == null) mode = modes[(modes.indexOf(mode) + 1) % modes.size] }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt index 8c7c92f524..e521856811 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt @@ -221,7 +221,7 @@ private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions, ArtStrip(d.cover, d.name) { StripLabel(d.name, d.store.id, stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), Color.White.copy(alpha = 0.72f)) if (d.state == DownloadState.INSTALLED) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) { - RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else launchStoreGame(ctx, d.store, d.id, s, a) } + RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(ctx, d.store, d.id, s, a) } } } } @@ -372,7 +372,7 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) CancelAction { DownloadQueue.clear(ctx, d.key) } } DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) { - RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else launchStoreGame(ctx, d.store, d.id, s, a) } + RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(ctx, d.store, d.id, s, a) } } DownloadState.CANCELLED -> {} } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt index 662e8236fd..c5dd008edb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt @@ -84,7 +84,7 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) { ) Text( stringResource(R.string.common_cancel), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant, - modifier = Modifier.clip(Shape12).clickable(role = Role.Button, onClick = close).controllerConfirm(onClick = close).padding(horizontal = 10.dp, vertical = 6.dp), + modifier = Modifier.clip(Shape12).focusGlide().clickable(role = Role.Button, onClick = close).controllerConfirm(onClick = close).padding(horizontal = 10.dp, vertical = 6.dp), ) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 46d12dc328..92b118d54b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -53,6 +53,8 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.focusGroup +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.hoverable import androidx.compose.foundation.selection.selectable @@ -86,6 +88,7 @@ import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.automirrored.filled.Login import androidx.compose.foundation.basicMarquee @@ -147,35 +150,6 @@ private data class PaneKey(val chip: String, val signedIn: Boolean, val accounts internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) { val ctx = LocalContext.current val focusManager = LocalFocusManager.current - com.droiddeck.launcher.stores.xbox.XboxContent.plan?.let { content -> - androidx.compose.material3.AlertDialog( - onDismissRequest = { com.droiddeck.launcher.stores.xbox.XboxContent.dismiss() }, - title = { Text(stringResource(R.string.stores_xbox_content_title)) }, - text = { Column { - if (content.error != null) Text(content.error) - else if (content.offers.isEmpty()) Text(stringResource(R.string.stores_xbox_content_none)) - content.offers.forEach { offer -> - androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxContent.install(ctx, offer.item) }) { - Text(stringResource(if (offer.installed) R.string.stores_xbox_content_update else R.string.stores_xbox_content_install, offer.item.title)) - } - } - } }, - confirmButton = { androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxContent.dismiss() }) { Text(stringResource(android.R.string.ok)) } }, - ) - } - com.droiddeck.launcher.stores.xbox.XboxBackend.packageChoice?.let { pending -> - androidx.compose.material3.AlertDialog( - onDismissRequest = { com.droiddeck.launcher.stores.xbox.XboxBackend.dismissPackages() }, - title = { Text(stringResource(R.string.stores_xbox_choose_content)) }, - text = { Column { pending.choices.forEach { choice -> - androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxBackend.selectPackage(ctx, choice) }) { - Text(stringResource(R.string.stores_xbox_choice, choice.getString("title"), choice.getString("kind"))) - } - } } }, - confirmButton = {}, - dismissButton = { androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxBackend.dismissPackages() }) { Text(stringResource(android.R.string.cancel)) } }, - ) - } val narrow = LocalNarrowPane.current val padH = if (narrow) 14.dp else 22.dp val tabs = remember { @@ -235,6 +209,12 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier LaunchedEffect(Unit) { StoresState.refresh(ctx) } val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle LaunchedEffect(chip) { + if (chip == Store.BATTLENET.id) { + while (true) { + if (lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) com.droiddeck.launcher.stores.battlenet.BattleNetClient.refresh(ctx) + delay(5_000) + } + } if (chip == Store.EPIC.id) { EpicClient.ensure(ctx) while (true) { @@ -331,7 +311,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier val backLabel = stringResource(R.string.common_back) Box(modifier.onGloballyPositioned { hostAt = it.positionInRoot() }) { Column( - modifier = Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp) + modifier = Modifier.fillMaxSize().padding(horizontal = padH).padding(top = if (narrow) 10.dp else 14.dp) .then(if (openGame != null && !arranging) Modifier else Modifier.bumpers( onPrevious = { val picked = Store.byId(focusedChip) @@ -604,6 +584,7 @@ private fun RowScope.ArrangeStoreChip( ) { onToggleTab(store) } } +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable private fun StoreChips( selected: String, focused: String?, active: Int, tabs: List<StoreTab>, arranging: Boolean, @@ -613,7 +594,6 @@ private fun StoreChips( val pal = LocalPalette.current val keys = tabs.filter { it.shown }.map { it.store.id } + DOWNLOADS val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, Rect>() } - val rootBounds = remember { HashMap<String, Rect>() } val highlighted = focused ?: selected val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard && !arranging @@ -623,47 +603,59 @@ private fun StoreChips( val gap = 8.dp val gapPx = with(androidx.compose.ui.platform.LocalDensity.current) { gap.toPx() } val drag = remember { ChipDrag() } + val tabScroll = rememberScrollState() Box(Modifier.fillMaxWidth()) { Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - for (tab in tabs) { - val store = tab.store - if (arranging) { - val index = tabs.indexOfFirst { it.store == store } - key(store) { ArrangeStoreChip(tab, index, tabs.lastIndex, gapPx, drag, onFocusChip, onMoveTab, onToggleTab) } - } else if (tab.shown) { - val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true - key(store) { - StoreChip( - label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot, - modifier = Modifier.weight(1f).onGloballyPositioned { bounds[store.id] = it.boundsInParent(); rootBounds[store.id] = it.boundsInRoot() }, - lead = { StoreDot(store, signedIn) }, - description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out), - onFocused = onFocusChip, - ) { onStore(store) } + Box(Modifier.weight(1f).then(if (arranging) Modifier else Modifier.edgeFade(tabScroll).horizontalScroll(tabScroll))) { + Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, + modifier = (if (arranging) Modifier.fillMaxWidth() else Modifier).focusGroup(), + ) { + for (tab in tabs) { + val store = tab.store + if (arranging) { + val index = tabs.indexOfFirst { it.store == store } + key(store) { ArrangeStoreChip(tab, index, tabs.lastIndex, gapPx, drag, onFocusChip, onMoveTab, onToggleTab) } + } else if (tab.shown) { + val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true + key(store) { + val reveal = remember { BringIntoViewRequester() } + LaunchedEffect(selected) { if (selected == store.id) reveal.bringIntoView() } + StoreChip( + label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot, + modifier = Modifier.bringIntoViewRequester(reveal).onGloballyPositioned { bounds[store.id] = it.boundsInParent() }, + lead = { StoreDot(store, signedIn) }, + description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out), + onFocused = onFocusChip, + ) { onStore(store) } + } + } } } + ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown && highlighted != DOWNLOADS) } if (arranging) { IconChip(Icons.Filled.Check, stringResource(R.string.stores_tabs_arrange_done)) { onArrangeDone() } } else { - StoreChip( - label = null, on = selected == DOWNLOADS, under = fillShown && highlighted == DOWNLOADS, key = DOWNLOADS, mark = pal.signal, - modifier = Modifier.onGloballyPositioned { - bounds[DOWNLOADS] = it.boundsInParent() - StoresMotion.downloadsChip = it.boundsInRoot() - }, - lead = { Icon(Icons.Outlined.Download, null, modifier = Modifier.size(18.dp)) }, - trail = if (active > 0) { { CountPill(active) } } else null, - description = stringResource(R.string.stores_tab_downloads), - onFocused = onFocusChip, - ) { onDownloads() } + Box { + StoreChip( + label = null, on = selected == DOWNLOADS, under = fillShown && highlighted == DOWNLOADS, key = DOWNLOADS, mark = pal.signal, + modifier = Modifier.onGloballyPositioned { + bounds[DOWNLOADS] = it.boundsInParent() + StoresMotion.downloadsChip = it.boundsInRoot() + }, + lead = { Icon(Icons.Outlined.Download, null, modifier = Modifier.size(18.dp)) }, + trail = if (active > 0) { { CountPill(active) } } else null, + description = stringResource(R.string.stores_tab_downloads), + onFocused = onFocusChip, + ) { onDownloads() } + ChipGlide(keys.indexOf(DOWNLOADS), bounds[DOWNLOADS], tint, visible = fillShown && highlighted == DOWNLOADS) + } var cogAt by remember { mutableStateOf<Rect?>(null) } Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) { IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) } } } } - ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } } @@ -827,6 +819,7 @@ private fun Storefront( clearSearchFocus: Boolean, onQuery: (String) -> Unit, onOpen: (String) -> Unit, ) { + BackHandler(enabled = query.isNotEmpty() && !clearSearchFocus) { onQuery("") } val ctx = LocalContext.current val library = StoresState.library[store] ?: emptyList() val shelves = StoresState.shelves[store] @@ -839,8 +832,10 @@ private fun Storefront( LaunchedEffect(store, q) { StoresState.search(ctx, store, q) } val browsing = store == Store.ITCH && q.isEmpty() && ItchBrowseState.active val browseItems = if (browsing) ItchBrowseState.items else emptyList() - val visible = remember(found, library, shelves, q, s.storesShowMature, browsing, browseItems) { - if (browsing) { + val catalog = store == Store.BATTLENET && q.isEmpty() + val visible = remember(found, library, shelves, q, s.storesShowMature, browsing, browseItems, catalog) { + if (catalog) shelf(shelves?.trending) ?: emptyList() + else if (browsing) { val owned = library.associateBy { it.id } browseItems.map { owned[it.id] ?: it }.filter(::shown) } else if (q.isEmpty()) emptyList() @@ -850,6 +845,7 @@ private fun Storefront( val nothing = stringResource(when { browsing && ItchBrowseState.loading -> R.string.stores_shelves_loading browsing && ItchBrowseState.failed -> R.string.stores_itch_browse_failed + catalog && shelves == null -> R.string.stores_shelves_loading else -> R.string.stores_nothing_matches }) var firstPlaced = false @@ -857,12 +853,12 @@ private fun Storefront( val density = androidx.compose.ui.platform.LocalDensity.current val focus = LocalFrontFocus.current val scope = rememberCoroutineScope() - val searching = q.isNotEmpty() || browsing + val searching = q.isNotEmpty() || browsing || catalog // A bar only while there is nothing else to look at: no shelves yet and no search results. val bareTab = if (searching) visible.isEmpty() else shelves == null || shelves.isEmpty val barLine = StoresState.status[store]?.takeIf { bareTab && syncCount(it) != null } val itchBar = store == Store.ITCH && q.isEmpty() - val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar) 1 else 0) + val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar) 1 else 0) + (if (catalog) 1 else 0) val card: @Composable (CatalogItem) -> Unit = { item -> val first = if (searching) item.key == visible.firstOrNull()?.key else !firstPlaced firstPlaced = true @@ -911,6 +907,9 @@ private fun Storefront( barLine?.let { line -> item(key = "sync", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { SyncBar(line) } } } StoresState.problems[store]?.let { line -> item(key = "problem", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { Box(Modifier.padding(bottom = 8.dp)) { Note(line) } } } } if (itchBar) item(key = "itch-browse-bar", span = { GridItemSpan(maxLineSpan) }) { ItchBrowseBar() } + if (catalog) item(key = "catalog-label", span = { GridItemSpan(maxLineSpan) }) { + Box(Modifier.padding(top = 10.dp)) { SectionLabel(stringResource(R.string.bnet_store)) } + } if (searching) { storeGrid(visible, nothing, card) if (browsing) item(key = "itch-more", span = { GridItemSpan(maxLineSpan) }) { ItchLoadMore() } @@ -954,7 +953,7 @@ private fun ProfileStrip(store: Store, owned: Int, loaded: Boolean, s: FrontEndS } Actions { SmallTextButton(stringResource(R.string.stores_owned_in_library), key = "owned-in-library") { - LibraryView.showOwned(store) + LibraryView.showOwned(ctx, store) show("games") } SmallTextButton(stringResource(R.string.stores_refresh)) { StoresState.open(ctx, store, force = true) } @@ -965,6 +964,39 @@ private fun ProfileStrip(store: Store, owned: Int, loaded: Boolean, s: FrontEndS } } if (store == Store.EPIC) EpicLauncherRow(s, a) + if (store == Store.BATTLENET) BattleNetLauncherRow(s, a) + } +} + +@Composable +private fun BattleNetLauncherRow(s: FrontEndState, a: FrontEndActions) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val title = stringResource(R.string.bnet_name) + Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().testTag("stores-battlenet-launcher")) { + val icon by androidx.compose.runtime.produceState<java.io.File?>(null, s.battleNetInstalled) { + value = if (!s.battleNetInstalled) null + else kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.droiddeck.launcher.runtime.BattleNet.icon(ctx) } + } + if (icon != null) AsyncImage(model = icon, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.size(36.dp).clip(RoundedCornerShape(8.dp))) + Text(title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + Actions { + SecondaryButton(stringResource(R.string.bnet_open), enabled = !s.busy, compact = true) { a.onBattleNet() } + val entry = remember(s.battleNetInstalled) { com.droiddeck.launcher.runtime.BattleNet.launcherEntry(s.battleNetInstalled) } + val scope = entry?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) } + if (entry != null && scope != null) { + val host = rememberMenuHost() + val settings = rememberGameSettings(scope) + Box { + SecondaryButton(stringResource(R.string.game_settings_card), compact = true) { + host.open = if (host.open == GAME_SETTINGS_MENU) null else GAME_SETTINGS_MENU + } + GameSettingsMenus(host, entry, settings) + } + } + } } } @@ -1033,32 +1065,67 @@ internal fun ModeHeader( var searching by remember { mutableStateOf(query.isNotEmpty()) } var focusOnOpen by remember { mutableStateOf(false) } val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "searchOpen") - Column(Modifier.fillMaxWidth()) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp).padding(vertical = 4.dp)) { - if (lead != null) lead() - else Text( - title, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, - modifier = Modifier.padding(start = 4.dp, end = 4.dp), - ) - BoxWithConstraints(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) { - if (searching || open > 0.01f) { - val w = androidx.compose.ui.unit.lerp(44.dp, maxWidth.coerceAtMost(520.dp), open) - Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) { - AdbTextField( - value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, - placeholder = placeholder, compact = true, focusOnShow = focusOnOpen, - clearFocus = clearSearchFocus, - onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } }, - ) - } - } else SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } + val close = { + searching = false + focusOnOpen = false + if (query.isNotEmpty()) onQuery("") + } + BackHandler(enabled = searching && !clearSearchFocus) { close() } + val heading: @Composable () -> Unit = { + if (lead != null) lead() + else Text( + title, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, + modifier = Modifier.padding(start = 4.dp, end = 4.dp), + ) + } + val searchField: @Composable (Modifier) -> Unit = { modifier -> + BoxWithConstraints(modifier, contentAlignment = Alignment.CenterStart) { + val closable = maxWidth >= 80.dp + val w = androidx.compose.ui.unit.lerp(44.dp, (maxWidth - if (closable) 36.dp else 0.dp).coerceIn(44.dp, 520.dp), open) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) { + AdbTextField( + value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, + placeholder = placeholder, compact = true, focusOnShow = focusOnOpen, + clearFocus = clearSearchFocus || !searching, + onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } }, + ) + } + if (searching && closable) SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant, onClick = close) } - trailing() } - Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) + } + val searchButton: @Composable () -> Unit = { + SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } + } + BoxWithConstraints(Modifier.fillMaxWidth()) { + val stacked = maxWidth < NarrowPaneWidth + Column(Modifier.fillMaxWidth()) { + if (stacked) { + Box(Modifier.padding(vertical = 4.dp)) { heading() } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).heightIn(min = 52.dp).padding(vertical = 4.dp), + ) { + searchButton() + trailing() + } + if (searching || open > 0.01f) searchField(Modifier.fillMaxWidth().padding(bottom = 6.dp)) + } else Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp).padding(vertical = 4.dp), + ) { + heading() + if (searching || open > 0.01f) searchField(Modifier.weight(1f)) + else Box(Modifier.weight(1f)) { searchButton() } + trailing() + } + Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) + } } } + internal fun storePalette(base: Palette, store: Store?): Palette { val (accent, deep) = when (store) { Store.GOG -> Color(0xFFC25BC8) to Color(0xFF9A3FA1) @@ -1066,6 +1133,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette { Store.AMAZON -> Color(0xFFFF9900) to Color(0xFFE07800) Store.XBOX -> Color(0xFF70C850) to Color(0xFF107C10) Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B) + Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3) null -> return base } val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White @@ -1271,7 +1339,8 @@ internal fun CardFace( Spacer(Modifier.matchParentSize().background(Color.Black.copy(alpha = if (blurs) 0.35f else 0.7f))) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.matchParentSize().padding(bottom = CardStrip)) } else if (art != null) AsyncImage( - model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize(), + model = art, contentDescription = null, contentScale = if (capsule) ContentScale.Fit else ContentScale.Crop, + modifier = Modifier.matchParentSize().padding(bottom = if (capsule) CardStrip else 0.dp), onSuccess = { r -> val drawn = r.result.drawable if (capsule && drawn.intrinsicWidth > 0 && drawn.intrinsicHeight > 0) landscape = drawn.intrinsicWidth > drawn.intrinsicHeight * 0.95f @@ -1354,7 +1423,11 @@ internal fun downloadLabel(d: com.droiddeck.launcher.stores.download.DownloadEnt @Composable internal fun activeStageLabel(d: com.droiddeck.launcher.stores.download.DownloadEntry): String = when (d.stage) { - DownloadStage.MANIFEST -> if (d.stageItemsTotal > 0) stringResource(R.string.stores_stage_checking) else stringResource(R.string.stores_stage_manifest) + DownloadStage.MANIFEST -> when { + d.store == Store.BATTLENET && d.detail.isNotBlank() -> d.detail + d.stageItemsTotal > 0 -> stringResource(R.string.stores_stage_checking) + else -> stringResource(R.string.stores_stage_manifest) + } DownloadStage.DOWNLOAD -> stringResource(R.string.stores_stage_downloading) DownloadStage.VERIFY -> stringResource(R.string.stores_stage_verifying) DownloadStage.INSTALL -> stringResource(R.string.stores_stage_installing) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt index 14527f5949..352b29a544 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt @@ -2,6 +2,10 @@ package com.droiddeck.launcher.ui import androidx.annotation.StringRes import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ProvideTextStyle +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.style.TextDirection import androidx.compose.material3.darkColorScheme import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode @@ -164,7 +168,22 @@ fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCA LocalPalette provides p, LocalDensity provides density, LocalConfiguration provides configuration, - ) { MaterialTheme(colorScheme = scheme, content = content) } + ) { + MaterialTheme(colorScheme = scheme, typography = ContentDirected) { + FocusGlideHost { ProvideTextStyle(TextStyle(textDirection = TextDirection.Content), content) } + } + } +} + +private val ContentDirected = Typography().run { + fun TextStyle.byContent() = copy(textDirection = TextDirection.Content) + Typography( + displayLarge.byContent(), displayMedium.byContent(), displaySmall.byContent(), + headlineLarge.byContent(), headlineMedium.byContent(), headlineSmall.byContent(), + titleLarge.byContent(), titleMedium.byContent(), titleSmall.byContent(), + bodyLarge.byContent(), bodyMedium.byContent(), bodySmall.byContent(), + labelLarge.byContent(), labelMedium.byContent(), labelSmall.byContent(), + ) } /** Turns the colour wheel on the system's own animation clock; with animations off, in the app or in Android, the colour holds still. */ diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TouchGestureDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/TouchGestureDialog.kt index db975a1996..0fda34fc28 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TouchGestureDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TouchGestureDialog.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.shape.CircleShape import androidx.annotation.StringRes import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background @@ -33,7 +34,7 @@ import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.LayoutDirection -import androidx.compose.ui.window.Dialog +import com.droiddeck.launcher.ui.GlideDialog as Dialog import androidx.compose.ui.window.DialogProperties import com.droiddeck.launcher.R import com.droiddeck.launcher.input.GestureKeys @@ -72,7 +73,7 @@ fun TouchGestureDialog(game: String?, onDismiss: () -> Unit, onSaved: () -> Unit GestureDialogFrame(onDismiss, footer = { Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) { - TextButton(onClick = onDismiss) { Text(stringResource(R.string.gesture_cancel)) } + TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.gesture_cancel)) } Spacer(Modifier.width(12.dp)) Button(onClick = { if (defaults != initialDefaults) GesturePrefs.save(context, null, defaults) @@ -80,13 +81,13 @@ fun TouchGestureDialog(game: String?, onDismiss: () -> Unit, onSaved: () -> Unit gameDraft?.let { GesturePrefs.save(context, targetGame, it) } ?: GesturePrefs.clear(context, targetGame) } onSaved() - }, modifier = Modifier.testTag("gesture-save")) { Text(stringResource(R.string.gesture_save_changes)) } + }, modifier = Modifier.testTag("gesture-save").focusGlide(CircleShape)) { Text(stringResource(R.string.gesture_save_changes)) } } }) { ScrollableTabRow(tab, edgePadding = 12.dp, containerColor = p.surface, divider = { HorizontalDivider(color = p.line) }) { tabs.forEachIndexed { index, title -> Tab(tab == index, onClick = { tab = index }, text = { Text(stringResource(title)) }, selectedContentColor = p.onBackground, - unselectedContentColor = p.onSurfaceVariant, modifier = Modifier.testTag("gesture-tab-$index")) + unselectedContentColor = p.onSurfaceVariant, modifier = Modifier.testTag("gesture-tab-$index").focusGlide()) } } key(tab) { @@ -96,7 +97,7 @@ fun TouchGestureDialog(game: String?, onDismiss: () -> Unit, onSaved: () -> Unit GestureFilterChip(!forGame, onClick = { forGame = false }, label = { Text(stringResource(R.string.gesture_defaults)) }, modifier = Modifier.testTag("gesture-scope-default")) if (targetGame != null) GestureFilterChip(forGame, onClick = { forGame = true }, label = { Text(stringResource(R.string.gesture_game)) }, modifier = Modifier.testTag("gesture-scope-game")) } - if (forGame && gameDraft != null) TextButton(onClick = { gameDraft = null }, modifier = Modifier.testTag("gesture-inherit")) { Text(stringResource(R.string.gesture_use_defaults)) } + if (forGame && gameDraft != null) TextButton(onClick = { gameDraft = null }, modifier = Modifier.testTag("gesture-inherit").focusGlide(CircleShape)) { Text(stringResource(R.string.gesture_use_defaults)) } } when (tab) { 0 -> { @@ -151,12 +152,12 @@ fun TouchGestureDialog(game: String?, onDismiss: () -> Unit, onSaved: () -> Unit } GestureSettingsCard(R.string.gesture_recognition) { Text(stringResource(R.string.gesture_threshold, config.gestureThreshold), style = MaterialTheme.typography.bodyMedium) - Slider(config.gestureThreshold.toFloat(), { change(config.copy(gestureThreshold = it.toInt())) }, valueRange = 10f..100f, steps = 17) + Slider(config.gestureThreshold.toFloat(), { change(config.copy(gestureThreshold = it.toInt())) }, valueRange = 10f..100f, steps = 17, modifier = Modifier.focusGlide()) } GestureSettingsCard(R.string.gesture_feedback) { GestureToggle(R.string.gesture_debug, config.showGestureDebugOverlay) { change(config.copy(showGestureDebugOverlay = it)) } } - OutlinedButton(onClick = { change(TouchGestureConfig()) }, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.gesture_reset)) } + OutlinedButton(onClick = { change(TouchGestureConfig()) }, modifier = Modifier.fillMaxWidth().focusGlide(CircleShape)) { Text(stringResource(R.string.gesture_reset)) } } } } @@ -177,7 +178,7 @@ private fun GestureDialogFrame(onDismiss: () -> Unit, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2)) { Column { Row(Modifier.fillMaxWidth().padding(end = 4.dp), horizontalArrangement = Arrangement.End) { - IconButton(onClick = onDismiss, modifier = Modifier.size(40.dp)) { Icon(Icons.Default.Close, stringResource(R.string.gesture_close)) } + IconButton(onClick = onDismiss, modifier = Modifier.size(40.dp).focusGlide(CircleShape)) { Icon(Icons.Default.Close, stringResource(R.string.gesture_close)) } } content() HorizontalDivider(color = p.line) @@ -201,7 +202,7 @@ private fun GestureCard(@StringRes title: Int, checked: Boolean, onToggle: (Bool Surface(Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), color = p.surface, border = BorderStroke(1.dp, if (checked) p.line2 else p.line)) { Column { - Row(Modifier.fillMaxWidth().toggleable(checked, role = Role.Switch, onValueChange = onToggle) + Row(Modifier.fillMaxWidth().focusGlide().toggleable(checked, role = Role.Switch, onValueChange = onToggle) .padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f).padding(end = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(stringResource(title), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold) @@ -217,7 +218,7 @@ private fun GestureCard(@StringRes title: Int, checked: Boolean, onToggle: (Bool private fun GestureActionField(id: String, @StringRes gesture: Int, selected: String, choices: List<String>, onChoose: (String) -> Unit) { var open by remember { mutableStateOf(false) } val p = LocalPalette.current - Surface(onClick = { open = true }, modifier = Modifier.fillMaxWidth().testTag("gesture-choice-$id"), shape = RoundedCornerShape(10.dp), + Surface(onClick = { open = true }, modifier = Modifier.fillMaxWidth().testTag("gesture-choice-$id").focusGlide(RoundedCornerShape(10.dp)), shape = RoundedCornerShape(10.dp), color = p.surfaceVariant, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2)) { Row(Modifier.padding(horizontal = 14.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { @@ -239,10 +240,10 @@ internal fun GestureActionPicker(choices: List<String>, selected: String, onDism val shown = filterGestureActions(catalog, query, category) val p = LocalPalette.current GestureDialogFrame(onDismiss) { - OutlinedTextField(query, onValueChange = { query = it }, modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).testTag("gesture-action-search"), + OutlinedTextField(query, onValueChange = { query = it }, modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).testTag("gesture-action-search").focusGlide(RoundedCornerShape(12.dp)), singleLine = true, shape = RoundedCornerShape(12.dp), placeholder = { Text(stringResource(R.string.gesture_search_actions)) }, leadingIcon = { Icon(Icons.Default.Search, null) }, trailingIcon = { - if (query.isNotEmpty()) IconButton(onClick = { query = "" }) { Icon(Icons.Default.Close, stringResource(R.string.gesture_clear_search)) } + if (query.isNotEmpty()) IconButton(onClick = { query = "" }, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Default.Close, stringResource(R.string.gesture_clear_search)) } }) Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { GestureFilterChip(category == null, onClick = { category = null }, label = { Text(stringResource(R.string.gesture_all_actions)) }) @@ -262,7 +263,7 @@ internal fun GestureActionPicker(choices: List<String>, selected: String, onDism val isSelected = action.id == selected Surface(shape = RoundedCornerShape(12.dp), color = if (isSelected) p.primary.copy(alpha = 0.12f) else p.surface, border = BorderStroke(1.dp, if (isSelected) p.primary else p.line)) { - Row(Modifier.fillMaxWidth().selectable(isSelected, role = Role.RadioButton, onClick = { onChoose(action.id) }) + Row(Modifier.fillMaxWidth().focusGlide().selectable(isSelected, role = Role.RadioButton, onClick = { onChoose(action.id) }) .testTag("gesture-action-${action.id}").padding(horizontal = 14.dp, vertical = 9.dp), verticalAlignment = Alignment.CenterVertically) { Icon(when (group) { GestureActionGroup.MOUSE -> Icons.Default.Mouse; GestureActionGroup.APP -> Icons.Default.TouchApp; else -> Icons.Default.Keyboard }, null, tint = if (isSelected) p.primary else p.onSurfaceVariant, modifier = Modifier.size(22.dp)) @@ -289,7 +290,7 @@ private fun GestureHoldOptions(action: String, behavior: String, delay: Int, onB @Composable private fun GestureFilterChip(selected: Boolean, onClick: () -> Unit, label: @Composable () -> Unit, modifier: Modifier = Modifier) { val p = LocalPalette.current - FilterChip(selected, onClick, label, modifier = modifier, colors = FilterChipDefaults.filterChipColors( + FilterChip(selected, onClick, label, modifier = modifier.focusGlide(), colors = FilterChipDefaults.filterChipColors( containerColor = p.surface, labelColor = p.onSurfaceVariant, selectedContainerColor = p.primary.copy(alpha = 0.16f), selectedLabelColor = p.onBackground)) } @@ -314,9 +315,9 @@ private fun GestureSettingsCard(@StringRes title: Int, content: @Composable Colu @Composable private fun GestureToggle(@StringRes title: Int, checked: Boolean, change: (Boolean) -> Unit) { - Row(Modifier.fillMaxWidth().toggleable(checked, role = Role.Switch, onValueChange = change).padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth().focusGlide().toggleable(checked, role = Role.Switch, onValueChange = change).padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) { Text(stringResource(title), Modifier.weight(1f).padding(end = 12.dp), style = MaterialTheme.typography.bodyMedium) - Switch(checked, null) + Switch(checked, null, modifier = Modifier.focusGlide()) } } @@ -326,5 +327,5 @@ private fun GestureDelay(label: String, value: Int, change: (Int) -> Unit) { Text(label, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium) Text(stringResource(R.string.gesture_ms, value), Modifier.background(LocalPalette.current.surfaceVariant, RoundedCornerShape(6.dp)).padding(horizontal = 10.dp, vertical = 5.dp), style = MaterialTheme.typography.labelLarge) } - Slider(value.toFloat().coerceIn(100f, 1000f), { change((it / 50).toInt() * 50) }, valueRange = 100f..1000f, steps = 17) + Slider(value.toFloat().coerceIn(100f, 1000f), { change((it / 50).toInt() * 50) }, valueRange = 100f..1000f, steps = 17, modifier = Modifier.focusGlide()) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt index a44f5ca19e..dd73939a7d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt @@ -9,6 +9,7 @@ import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.background +import androidx.compose.foundation.basicMarquee import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.hoverable @@ -42,7 +43,7 @@ import androidx.compose.material.icons.outlined.Verified import androidx.compose.material3.Icon import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.material3.AlertDialog +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -88,6 +89,7 @@ class UpdatesActions( val onDismissPermission: () -> Unit = {}, ) +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) { val u = s.updates @@ -95,10 +97,14 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie val me = remember { AppUpdates.installed() } val colors = MaterialTheme.colorScheme Column(modifier = modifier) { - PageHeader(stringResource(R.string.upd_title)) { + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp), + ) { Text( stringResource(R.string.upd_build, me.version, s.buildLabel), fontSize = 12.5.sp, color = colors.onSurfaceVariant, - maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f).padding(top = 6.dp), + maxLines = 1, modifier = Modifier.weight(1f) + .basicMarquee(iterations = Int.MAX_VALUE, initialDelayMillis = 700, velocity = 40.dp), ) val checked = u.catalog?.checkedAt?.takeIf { it > 0 } if (!LocalNarrowPane.current) Text( @@ -109,7 +115,7 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie } BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { val stacked = LocalNarrowPane.current || maxWidth < 600.dp - Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { + Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { if (stacked) { StatusPanel(s, u, ua, me) Box(Modifier.height(18.dp)) @@ -133,8 +139,8 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie stringResource(R.string.upd_perm_text), ) }, - confirmButton = { TextButton(onClick = ua.onAllowInstalls) { Text(stringResource(R.string.upd_open_settings)) } }, - dismissButton = { TextButton(onClick = ua.onDismissPermission) { Text(stringResource(R.string.upd_not_now)) } }, + confirmButton = { TextButton(onClick = ua.onAllowInstalls, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.upd_open_settings)) } }, + dismissButton = { TextButton(onClick = ua.onDismissPermission, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.upd_not_now)) } }, ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt index 5c719ca90d..7e67b352bf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt @@ -360,6 +360,7 @@ internal fun AdbTextField( onNext: (() -> Unit)? = null, onDone: (() -> Unit)? = null, focusOnShow: Boolean = false, + showLabel: Boolean = true, ) { val context = LocalContext.current val focusAsked = remember { booleanArrayOf(false) } @@ -374,7 +375,7 @@ internal fun AdbTextField( val colors = MaterialTheme.colorScheme Column(modifier = modifier.fillMaxWidth()) { - Text( + if (showLabel) Text( label, style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Medium, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/XboxStoreDialogs.kt b/app/src/main/java/com/droiddeck/launcher/ui/XboxStoreDialogs.kt new file mode 100644 index 0000000000..c2e4f30250 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/XboxStoreDialogs.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import com.droiddeck.launcher.R +import com.droiddeck.launcher.stores.xbox.XboxBackend +import com.droiddeck.launcher.stores.xbox.XboxContent + +@Composable +internal fun XboxStoreDialogs( + content: XboxContent.Plan? = XboxContent.plan, + pending: XboxBackend.PackageChoice? = XboxBackend.packageChoice, +) { + val ctx = LocalContext.current + content?.let { + AlertDialog( + onDismissRequest = { XboxContent.dismiss() }, + title = { Text(stringResource(R.string.stores_xbox_content_title)) }, + text = { Column(Modifier.verticalScroll(rememberScrollState())) { + if (content.error != null) Text(content.error) + else if (content.offers.isEmpty()) Text(stringResource(R.string.stores_xbox_content_none)) + content.offers.forEach { offer -> + TextButton(onClick = { XboxContent.install(ctx, offer.item) }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(if (offer.installed) R.string.stores_xbox_content_update else R.string.stores_xbox_content_install, offer.item.title)) + } + } + } }, + confirmButton = { TextButton(onClick = { XboxContent.dismiss() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(android.R.string.ok)) } }, + ) + } + pending?.let { + AlertDialog( + onDismissRequest = { XboxBackend.dismissPackages() }, + title = { Text(stringResource(R.string.stores_xbox_choose_content)) }, + text = { Column(Modifier.verticalScroll(rememberScrollState())) { pending.choices.forEach { choice -> + TextButton(onClick = { XboxBackend.selectPackage(ctx, choice) }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.stores_xbox_choice, choice.getString("title"), choice.getString("kind"))) + } + } } }, + confirmButton = {}, + dismissButton = { TextButton(onClick = { XboxBackend.dismissPackages() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(android.R.string.cancel)) } }, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/update/SelfInstaller.kt b/app/src/main/java/com/droiddeck/launcher/update/SelfInstaller.kt index 4ba3a20cc4..87d958889e 100644 --- a/app/src/main/java/com/droiddeck/launcher/update/SelfInstaller.kt +++ b/app/src/main/java/com/droiddeck/launcher/update/SelfInstaller.kt @@ -91,7 +91,8 @@ object SelfInstaller { } } - fun install(context: Context, apk: File) { + /** Reports the session id before the commit, so a status broadcast that arrives right away is recognised. */ + fun install(context: Context, apk: File, onSession: (Int) -> Unit = {}) { val installer = context.packageManager.packageInstaller val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply { setAppPackageName(context.packageName) @@ -108,10 +109,23 @@ object SelfInstaller { } val status = Intent(ACTION_STATUS).setPackage(context.packageName) val flags = PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0) + onSession(id) session.commit(PendingIntent.getBroadcast(context, id, status, flags).intentSender) } } + /** Only a system installer activity may be launched from the status broadcast, without URI grants. */ + fun safeConfirmIntent(context: Context, confirm: Intent): Intent? { + val target = confirm.resolveActivity(context.packageManager) ?: return null + val info = runCatching { context.packageManager.getApplicationInfo(target.packageName, 0) }.getOrNull() ?: return null + if (info.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM == 0) return null + return Intent(confirm).setComponent(target).apply { + flags = flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or + Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or Intent.FLAG_GRANT_PREFIX_URI_PERMISSION).inv() + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + } + fun describeFailure(context: Context, status: Int, message: String?): String = when { message?.contains("VERSION_DOWNGRADE") == true -> context.getString(R.string.upd_fail_downgrade) status == PackageInstaller.STATUS_FAILURE_CONFLICT || message?.contains("UPDATE_INCOMPATIBLE") == true -> 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 348e8ff1fb..fcf57b9515 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -1,7 +1,11 @@ package com.droiddeck.launcher.wayland +import android.os.Handler +import android.os.HandlerThread +import android.os.Process import android.view.Choreographer import android.view.Surface +import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionState object CompositorHost { @@ -14,8 +18,22 @@ object CompositorHost { @Volatile private var vsyncRunning = false - private val vsync = object : Choreographer.FrameCallback { + @Volatile + private var ownVsyncThread = true + + // The screen tick gets its own thread so a busy main thread cannot delay the compositor's frames. + private val vsyncThread: HandlerThread by lazy { + HandlerThread("droiddeck-vsync", Process.THREAD_PRIORITY_DISPLAY).apply { start() } + } + private val vsyncHandler: Handler by lazy { Handler(vsyncThread.looper) } + + @Volatile + private var vsyncGeneration = 0 + + // Each resume gets a new callback; one left queued from an earlier resume, on either thread, stops itself. + private fun vsyncCallback(generation: Int) = object : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { + if (generation != vsyncGeneration) return WaylandCompositor.nativeVsync(frameTimeNanos) if (vsyncRunning) Choreographer.getInstance().postFrameCallback(this) } @@ -34,6 +52,7 @@ object CompositorHost { refreshHz: Float, fpsLimit: Int, ): Boolean { + ownVsyncThread = SessionPrefs.vsyncThread(context) pace(refreshHz, fpsLimit) if (!SessionState.running) WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight) if (started) { @@ -103,8 +122,14 @@ object CompositorHost { private fun resumeVsync() { if (vsyncRunning) return + val callback = vsyncCallback(++vsyncGeneration) vsyncRunning = true - Choreographer.getInstance().postFrameCallback(vsync) + WaylandCompositor.nativeLog("screen", if (ownVsyncThread) "screen tick runs on its own display-priority thread" else "screen tick runs on the main thread") + if (!ownVsyncThread) { + Choreographer.getInstance().postFrameCallback(callback) + return + } + vsyncHandler.post { Choreographer.getInstance().postFrameCallback(callback) } } private fun pauseVsync() { 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 4111cea2ce..206b182805 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -307,6 +307,8 @@ public final class WaylandCompositor { public static native float[] nativeFrameGenStats(); + public static native long nativeHudFrameTimes(float[] out); + /** Stream mode: the scene is the Xbox Cloud Gaming native player's picture, handed over frame by frame. */ public static native void nativeStreamMode(boolean on); diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index d457db27a3..e07f0faded 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">نسبة أبعاد الشاشة</string> <string name="mode_ratio_custom">تحددها الدقة المخصّصة.</string> <string name="mode_ratio_auto">يستخدم الخيار «تلقائي» نسبة 16:9 على الأقل.</string> - <string name="mode_fps">حد الإطارات</string> - <string name="mode_fps_note">يحدّ الجلسة بأكملها. تنتقل الشاشة إلى معدل تحديث يكون من مضاعفات الحد.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">إخراج HDR10</string> <string name="mode_hdr_unavailable">غير متاح: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">لمس Steam (تجريبي)</string> <string name="osc_style_next_session">تبدأ عناصر التحكم باللمس من Steam مع جلسة Steam التالية</string> <string name="osc_steam_layout">تخطيط لمس Steam</string> + <string name="screen_keys">مفاتيح الشاشة</string> + <string name="screen_keys_add">إضافة مفتاح</string> + <string name="screen_key_text">نص</string> + <string name="screen_key_size">الحجم</string> + <string name="screen_key_opacity">العتامة</string> + <string name="screen_key_type_button">مفتاح</string> + <string name="screen_key_shape_trigger">زناد</string> + <string name="screen_key_toggle">تبديل</string> + <string name="screen_key_layout_export">تصدير</string> + <string name="screen_key_shape_pill">كبسولة</string> + <string name="screen_key_shape_round">مستدير</string> + <string name="screen_key_shape_circle">دائرة</string> + <string name="screen_key_shape_rect">مستطيل</string> + <string name="screen_key_bind">مفتاح</string> + <string name="screen_key_image">صورة</string> + <string name="screen_key_image_clear">مسح</string> + <string name="screen_key_layout">التخطيط</string> + <string name="screen_key_layout_save">حفظ</string> <string name="osc_steam_layout_hint">انقل عناصر التحكم باللمس لهذه اللعبة أو غيّر حجمها أو أخفها؛ ويتم الحفظ في Steam</string> <string name="mode_controller">وحدة التحكم</string> <string name="mode_controller_hint">كيف يرى Steam وحدة التحكم لديك. يُطبَّق في الجلسة التالية.</string> @@ -2009,7 +2025,6 @@ <string name="display_filter_live">يُطبَّق فوريًا. مشترك بين Steam وسطح المكتب.</string> <string name="display_filter_note">تُطبَّق FSR و GSR و NIS عند تكبير صورة الجلسة. ويعمل خيار «زيادة الحدة فقط» أيضًا دون تكبير.</string> <string name="display_sharpness">حدّة المرشِّح</string> - <string name="display_frame_rate">معدّل الإطارات</string> <string name="display_look_filter">%1$s يضبط أسلوب التكبير على %2$s.</string> <string name="display_match_screen">مطابقة الشاشة (%1$d×%2$d)</string> <string name="display_follow_screen">اتباع الشاشة (يُغيَّر الحجم عند الطي أو الفتح)</string> @@ -2062,6 +2077,15 @@ <string name="stores_shelf_trending">الرائج</string> <string name="stores_play">تشغيل</string> <string name="stores_install">تثبيت</string> + <string name="bnet_open">فتح Battle.net</string> + <string name="bnet_dl_starting">جارٍ تشغيل أداة التنزيل من Blizzard…</string> + <string name="bnet_dl_waiting">في انتظار إغلاق Battle.net…</string> + <string name="bnet_dl_queued">في انتظار تنزيل Battle.net الآخر…</string> + <string name="bnet_dl_client_first">افتح Battle.net وسجّل الدخول مرة واحدة، ثم ثبّت ألعابه من هنا.</string> + <string name="bnet_dl_failed">توقفت أداة التنزيل من Blizzard: %1$s</string> + <string name="bnet_dl_agent_error">خطأ Blizzard %1$s</string> + <string name="bnet_update">تحديث</string> + <string name="bnet_store">ألعاب Blizzard</string> <string name="stores_resume_install">استئناف التثبيت</string> <string name="stores_dl_interrupted">منقطع</string> <string name="stores_install_size">تثبيت · %1$s</string> @@ -2099,6 +2123,13 @@ <string name="stores_itch_browse_failed">تعذّر تحميل الألعاب من itch.io</string> <string name="stores_itch_archive">أرشيفات %1$s غير مدعومة</string> <string name="stores_itch_download_failed">استجاب itch.io بـ HTTP %1$d</string> + <string name="stores_itch_pick_title">اختر إصدارًا</string> + <string name="stores_itch_pick_none">لم يُعثر على تنزيلات لهذه اللعبة</string> + <string name="stores_itch_pick_failed">تعذر تحميل التنزيلات من itch.io</string> + <string name="stores_itch_build_demo">نسخة تجريبية</string> + <string name="stores_itch_build_open">فتح على itch.io</string> + <string name="stores_itch_build_linux_soon">غير مدعوم بعد</string> + <string name="stores_itch_no_game">تعذر العثور على هذه اللعبة على itch.io</string> <string name="stores_free">مجاني</string> <string name="stores_resume">استئناف</string> <string name="stores_refresh">تحديث</string> @@ -3136,6 +3167,25 @@ <string name="spatial_saved_views_hint">يمكن إعادة حساب المشاهدات المحفوظة. ابدأ معايرة جديدة لالتقاطها في نظام إحداثيات التتبع الحالي.</string> <string name="spatial_model_checksum_error">المجموع الاختباري لنموذج تتبع اليدين غير مطابق</string> <string name="spatial_opencv_load_error">تعذر تحميل OpenCV</string> + <string name="setup_group_memory">الذاكرة</string> + <string name="setup_clear_cached">إغلاق التطبيقات المخزّنة مؤقتًا قبل الجلسة</string> + <string name="setup_clear_cached_hint">عند بدء الجلسة، يُغلق DroidDeck التطبيقات التي يُبقيها Android في الخلفية، لتحصل اللعبة على ذاكرة أكبر. يجب تفعيل تصحيح الأخطاء اللاسلكي.</string> + <string name="setup_clear_cached_unpaired">يتطلّب إقران DroidDeck بتصحيح الأخطاء اللاسلكي (إقران، أدناه).</string> + <string name="setup_memory_hud">مؤشر الذاكرة</string> + <string name="setup_memory_hud_hint">الذاكرة وswap المستخدمة، على شاشة الجلسة. يقسّمها الوضع المتقدّم بين اللعبة وDroidDeck وAndroid وGPU.</string> + <string name="setup_memory_hud_simple">بسيط</string> + <string name="setup_memory_hud_advanced">متقدّم</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">اللعبة %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">التطبيقات في الخلفية أثناء الجلسة</string> + <string name="setup_bg_limit_hint">أثناء تشغيل الجلسة، يُبقي Android هذا العدد من التطبيقات كحد أقصى في الذاكرة المؤقتة ويُغلق الباقي، لتحصل اللعبة على ذاكرتها. يُعيد DroidDeck الحد إلى ما كان عليه عند انتهاء الجلسة. يجب تفعيل تصحيح الأخطاء اللاسلكي.</string> + <string name="setup_bg_limit_4">4 كحد أقصى</string> + <string name="setup_bg_limit_1">1 كحد أقصى</string> + <string name="setup_bg_limit_0">لا شيء</string> + <string name="setup_adb_pair">تصحيح الأخطاء اللاسلكي</string> + <string name="setup_adb_pair_hint">يُقرن DroidDeck بتصحيح الأخطاء اللاسلكي في Android للخيارات أعلاه. يبقى حد العمليات الفرعية متوقفًا.</string> + <string name="setup_adb_pair_button">إقران</string> <string name="epic_client_missing">غير مثبَّت</string> <string name="epic_client_open">فتح</string> <string name="epic_client_install">تثبيت</string> @@ -3168,6 +3218,53 @@ <string name="library_remove">إزالة من المكتبة</string> <string name="library_in">في المكتبة</string> <string name="xbox_filter_show">عرض</string> + <string name="itch_collections">المجموعات</string> <string name="xbox_filter_cloud">سحابية</string> <string name="stores_xbox_cloud_settings">إعدادات السحابة</string> + <string name="apps_search_hint">البحث في التطبيقات</string> + <string name="apps_no_match">لا توجد تطبيقات تطابق ”%1$s“.</string> + <string name="apps_add_widget">إضافة أداة</string> + <string name="apps_widgets_loading">جارٍ تحميل الأدوات…</string> + <string name="apps_widgets_none">لا توجد تطبيقات على هذا الجهاز توفّر أدوات.</string> + <string name="apps_widget_wider">أعرض</string> + <string name="apps_widget_narrower">أضيق</string> + <string name="apps_widget_taller">أطول</string> + <string name="apps_widget_shorter">أقصر</string> + <string name="apps_widget_move_earlier">نقل إلى الأمام</string> + <string name="apps_widget_move_later">نقل إلى الخلف</string> + <string name="apps_widget_configure">إعدادات الأداة</string> + <string name="apps_widget_remove">إزالة الأداة</string> + <string name="apps_add_to_folder">إضافة إلى مجلد</string> + <string name="apps_new_folder">مجلد جديد</string> + <string name="apps_remove_from_folder">إزالة من المجلد</string> + <string name="apps_app_info">معلومات التطبيق</string> + <string name="apps_uninstall">إلغاء التثبيت</string> + <string name="apps_folder_rename">إعادة التسمية</string> + <string name="apps_folder_ungroup">فك التجميع</string> + <string name="apps_folder_default">مجلد</string> + <string name="apps_folder_name">اسم المجلد</string> + <string name="apps_filter">عرض</string> + <string name="apps_filter_all">كل التطبيقات</string> + <string name="apps_filter_games">الألعاب</string> + <string name="apps_filter_downloaded">المنزّلة</string> + <string name="apps_filter_system">النظام</string> + <string name="apps_filter_hidden">المخفية</string> + <string name="apps_hide">إخفاء</string> + <string name="apps_unhide">إظهار في التطبيقات</string> + <string name="apps_shortcut_remove">إزالة الاختصار</string> + <string name="apps_pin_title">إضافة إلى التطبيقات</string> + <string name="apps_pin_add">إضافة</string> + <string name="apps_hidden_none">لا توجد تطبيقات مخفية.</string> + <string name="apps_sort_name_asc">الاسم أ–ي</string> + <string name="apps_sort_name_desc">الاسم ي–أ</string> + <string name="apps_sort_installed">المثبّتة مؤخرًا</string> + <string name="apps_sort_updated">المحدّثة مؤخرًا</string> + <plurals name="apps_count"> + <item quantity="zero">%d تطبيق</item> + <item quantity="one">تطبيق واحد</item> + <item quantity="two">تطبيقان</item> + <item quantity="few">%d تطبيقات</item> + <item quantity="many">%d تطبيقًا</item> + <item quantity="other">%d تطبيق</item> + </plurals> </resources> diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 598c110e21..0861e3525f 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Relación de aspecto</string> <string name="mode_ratio_custom">Definida por la resolución personalizada.</string> <string name="mode_ratio_auto">Auto usa al menos 16:9.</string> - <string name="mode_fps">Límite de fotogramas</string> - <string name="mode_fps_note">Limita toda la sesión. La pantalla cambia a una tasa de refresco que el límite divide exactamente.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Salida HDR10</string> <string name="mode_hdr_unavailable">No disponible: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Táctil de Steam (beta)</string> <string name="osc_style_next_session">Los controles táctiles de Steam se activan en la próxima sesión de Steam</string> <string name="osc_steam_layout">Disposición táctil de Steam</string> + <string name="screen_keys">Teclas en pantalla</string> + <string name="screen_keys_add">Agregar tecla</string> + <string name="screen_key_text">Texto</string> + <string name="screen_key_size">Tamaño</string> + <string name="screen_key_opacity">Opacidad</string> + <string name="screen_key_type_button">Tecla</string> + <string name="screen_key_shape_trigger">Gatillo</string> + <string name="screen_key_toggle">Alternar</string> + <string name="screen_key_layout_export">Exportar</string> + <string name="screen_key_shape_pill">Píldora</string> + <string name="screen_key_shape_round">Redondeado</string> + <string name="screen_key_shape_circle">Círculo</string> + <string name="screen_key_shape_rect">Rectángulo</string> + <string name="screen_key_bind">Tecla</string> + <string name="screen_key_image">Imagen</string> + <string name="screen_key_image_clear">Borrar</string> + <string name="screen_key_layout">Disposición</string> + <string name="screen_key_layout_save">Guardar</string> <string name="osc_steam_layout_hint">Mueve, cambia de tamaño u oculta los controles táctiles de este juego; se guarda en Steam</string> <string name="mode_controller">Control</string> <string name="mode_controller_hint">Cómo ve Steam tu control. Se aplica en la próxima sesión.</string> @@ -1978,7 +1994,6 @@ <string name="display_filter_live">Se aplica al instante. Compartido por Steam y Escritorio.</string> <string name="display_filter_note">FSR, GSR y NIS se aplican al ampliar la imagen de la sesión. Solo nitidez también funciona sin ampliar.</string> <string name="display_sharpness">Nitidez del filtro</string> - <string name="display_frame_rate">Velocidad de fotogramas</string> <string name="display_look_filter">%1$s Cambia el escalado a %2$s.</string> <string name="display_match_screen">Igual a la pantalla (%1$d×%2$d)</string> <string name="display_follow_screen">Seguir la pantalla (cambia de tamaño al plegar o desplegar)</string> @@ -2030,6 +2045,15 @@ <string name="stores_shelf_trending">En tendencia</string> <string name="stores_play">Jugar</string> <string name="stores_install">Instalar</string> + <string name="bnet_open">Abrir Battle.net</string> + <string name="bnet_dl_starting">Iniciando el descargador de Blizzard…</string> + <string name="bnet_dl_waiting">Esperando a que se cierre Battle.net…</string> + <string name="bnet_dl_queued">Esperando la otra descarga de Battle.net…</string> + <string name="bnet_dl_client_first">Abre Battle.net e inicia sesión una vez; luego instala sus juegos desde aquí.</string> + <string name="bnet_dl_failed">El descargador de Blizzard se detuvo: %1$s</string> + <string name="bnet_dl_agent_error">Error de Blizzard %1$s</string> + <string name="bnet_update">Actualizar</string> + <string name="bnet_store">Juegos de Blizzard</string> <string name="stores_resume_install">Reanudar instalación</string> <string name="stores_dl_interrupted">Interrumpida</string> <string name="stores_install_size">Instalar · %1$s</string> @@ -2783,6 +2807,13 @@ <string name="stores_itch_browse_failed">No se pudieron cargar los juegos de itch.io</string> <string name="stores_itch_archive">Los archivos %1$s no son compatibles</string> <string name="stores_itch_download_failed">itch.io respondió HTTP %1$d</string> + <string name="stores_itch_pick_title">Elige una versión</string> + <string name="stores_itch_pick_none">No se encontraron descargas para este juego</string> + <string name="stores_itch_pick_failed">No se pudieron cargar las descargas de itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Abrir en itch.io</string> + <string name="stores_itch_build_linux_soon">Aún no es compatible</string> + <string name="stores_itch_no_game">No se encontró este juego en itch.io</string> <string name="glasses_experimental">Cámaras Luma Ultra — Experimental</string> <string name="glasses_joycons">Seguimiento de posición de los Joy-Con</string> <string name="glasses_joycons_hint">Usa las cámaras de las gafas inteligentes para posicionar tus mandos Joy-Con emparejados. La rotación y las pulsaciones de los botones provienen de los mandos Joy-Con. La posición se estima cuando tus muñecas están ocultas. Reemplaza los mandos operados con las manos desnudas y pausa el seguimiento de la cámara del teléfono. Apunta los mandos Joy-Con hacia adelante al conectar o restablecer el centro de seguimiento.</string> @@ -2986,6 +3017,25 @@ <string name="spatial_saved_views_hint">Las vistas guardadas se pueden recalcular. Inicie una nueva calibración para capturar en el sistema de coordenadas de seguimiento actual.</string> <string name="spatial_model_checksum_error">La suma de comprobación del modelo de mano no coincide</string> <string name="spatial_opencv_load_error">OpenCV no se pudo cargar</string> + <string name="setup_group_memory">Memoria</string> + <string name="setup_clear_cached">Cerrar apps en caché antes de una sesión</string> + <string name="setup_clear_cached_hint">Al iniciar una sesión, DroidDeck cierra las apps que Android mantiene en segundo plano para que el juego tenga más memoria. La Depuración inalámbrica debe estar activada.</string> + <string name="setup_clear_cached_unpaired">DroidDeck debe estar vinculado con la Depuración inalámbrica (Vincular, abajo).</string> + <string name="setup_memory_hud">Indicador de memoria</string> + <string name="setup_memory_hud_hint">Memoria y swap en uso, en la pantalla de la sesión. Avanzado lo divide entre el juego, DroidDeck, Android y la GPU.</string> + <string name="setup_memory_hud_simple">Simple</string> + <string name="setup_memory_hud_advanced">Avanzado</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">juego %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Apps en segundo plano durante una sesión</string> + <string name="setup_bg_limit_hint">Mientras una sesión está en curso, Android mantiene en caché como máximo esta cantidad de apps y cierra las demás para que el juego use su memoria. DroidDeck restablece el límite anterior cuando termina la sesión. La Depuración inalámbrica debe estar activada.</string> + <string name="setup_bg_limit_4">Como máximo 4</string> + <string name="setup_bg_limit_1">Como máximo 1</string> + <string name="setup_bg_limit_0">Ninguna</string> + <string name="setup_adb_pair">Depuración inalámbrica</string> + <string name="setup_adb_pair_hint">Vincula DroidDeck con la Depuración inalámbrica de Android para las opciones de arriba. El límite de procesos secundarios sigue desactivado.</string> + <string name="setup_adb_pair_button">Vincular</string> <string name="epic_client_missing">No instalada</string> <string name="epic_client_open">Abrir</string> <string name="epic_client_install">Instalar</string> @@ -3018,6 +3068,50 @@ <string name="library_remove">Quitar de Biblioteca</string> <string name="library_in">En Biblioteca</string> <string name="xbox_filter_show">Mostrar</string> + <string name="itch_collections">Colecciones</string> <string name="xbox_filter_cloud">Nube</string> <string name="stores_xbox_cloud_settings">Configuración de nube</string> + <string name="apps_search_hint">Buscar apps</string> + <string name="apps_no_match">Ninguna app coincide con «%1$s».</string> + <string name="apps_add_widget">Agregar widget</string> + <string name="apps_widgets_loading">Cargando widgets…</string> + <string name="apps_widgets_none">Ninguna app de este dispositivo ofrece widgets.</string> + <string name="apps_widget_wider">Más ancho</string> + <string name="apps_widget_narrower">Más angosto</string> + <string name="apps_widget_taller">Más alto</string> + <string name="apps_widget_shorter">Más bajo</string> + <string name="apps_widget_move_earlier">Mover antes</string> + <string name="apps_widget_move_later">Mover después</string> + <string name="apps_widget_configure">Configuración del widget</string> + <string name="apps_widget_remove">Quitar widget</string> + <string name="apps_add_to_folder">Agregar a carpeta</string> + <string name="apps_new_folder">Carpeta nueva</string> + <string name="apps_remove_from_folder">Quitar de la carpeta</string> + <string name="apps_app_info">Información de la app</string> + <string name="apps_uninstall">Desinstalar</string> + <string name="apps_folder_rename">Cambiar nombre</string> + <string name="apps_folder_ungroup">Desagrupar</string> + <string name="apps_folder_default">Carpeta</string> + <string name="apps_folder_name">Nombre de la carpeta</string> + <string name="apps_filter">Mostrar</string> + <string name="apps_filter_all">Todas las apps</string> + <string name="apps_filter_games">Juegos</string> + <string name="apps_filter_downloaded">Descargadas</string> + <string name="apps_filter_system">Sistema</string> + <string name="apps_filter_hidden">Ocultas</string> + <string name="apps_hide">Ocultar</string> + <string name="apps_unhide">Mostrar en apps</string> + <string name="apps_shortcut_remove">Quitar acceso directo</string> + <string name="apps_pin_title">Agregar a Apps</string> + <string name="apps_pin_add">Agregar</string> + <string name="apps_hidden_none">No hay apps ocultas.</string> + <string name="apps_sort_name_asc">Nombre A–Z</string> + <string name="apps_sort_name_desc">Nombre Z–A</string> + <string name="apps_sort_installed">Instaladas recientemente</string> + <string name="apps_sort_updated">Actualizadas recientemente</string> + <plurals name="apps_count"> + <item quantity="one">%d app</item> + <item quantity="many">%d apps</item> + <item quantity="other">%d apps</item> + </plurals> </resources> diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index a0bc668c8a..fecfd3a044 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Пропорции на екрана</string> <string name="mode_ratio_custom">Определени от персонализираната резолюция.</string> <string name="mode_ratio_auto">Автоматично използва поне 16:9.</string> - <string name="mode_fps">Ограничение на кадрите</string> - <string name="mode_fps_note">Ограничава цялата сесия. Екранът преминава към честота на опресняване, която се дели точно на ограничението.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 изход</string> <string name="mode_hdr_unavailable">Не е налично: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Докосване в Steam (бета)</string> <string name="osc_style_next_session">Сензорните контроли на Steam ще стартират от следващата сесия на Steam</string> <string name="osc_steam_layout">Разположение на докосването в Steam</string> + <string name="screen_keys">Клавиши на екрана</string> + <string name="screen_keys_add">Добавяне на клавиш</string> + <string name="screen_key_text">Текст</string> + <string name="screen_key_size">Размер</string> + <string name="screen_key_opacity">Прозрачност</string> + <string name="screen_key_type_button">Клавиш</string> + <string name="screen_key_shape_trigger">Спускът</string> + <string name="screen_key_toggle">Превключване</string> + <string name="screen_key_layout_export">Експорт</string> + <string name="screen_key_shape_pill">Капсула</string> + <string name="screen_key_shape_round">Заоблено</string> + <string name="screen_key_shape_circle">Кръг</string> + <string name="screen_key_shape_rect">Правоъгълник</string> + <string name="screen_key_bind">Клавиш</string> + <string name="screen_key_image">Изображение</string> + <string name="screen_key_image_clear">Изчистване</string> + <string name="screen_key_layout">Разположение</string> + <string name="screen_key_layout_save">Запиши</string> <string name="osc_steam_layout_hint">Премествайте, преоразмерявайте или скривайте сензорните контроли на тази игра; записва се в Steam</string> <string name="mode_controller">Контролер</string> <string name="mode_controller_hint">Как Steam разпознава контролера ви. Прилага се от следващата сесия.</string> @@ -1925,7 +1941,6 @@ <string name="display_filter_live">Прилага се веднага. Общ за Steam и Desktop.</string> <string name="display_filter_note">FSR, GSR и NIS се прилагат при уголемяване на изображението на сесията. „Само изостряне“ работи и без уголемяване.</string> <string name="display_sharpness">Острота на филтъра</string> - <string name="display_frame_rate">Честота на кадрите</string> <string name="display_look_filter">%1$s Задава мащабиране на %2$s.</string> <string name="display_match_screen">Напасване на екрана (%1$d×%2$d)</string> <string name="display_follow_screen">Следване на екрана (преоразмерява при сгъване или разгъване)</string> @@ -1978,6 +1993,15 @@ <string name="stores_shelf_trending">Актуални</string> <string name="stores_play">Играй</string> <string name="stores_install">Инсталирай</string> + <string name="bnet_open">Отвори Battle.net</string> + <string name="bnet_dl_starting">Стартиране на програмата за изтегляне на Blizzard…</string> + <string name="bnet_dl_waiting">Изчакване Battle.net да се затвори…</string> + <string name="bnet_dl_queued">Изчакване на другото изтегляне от Battle.net…</string> + <string name="bnet_dl_client_first">Отворете Battle.net и влезте веднъж, след това инсталирайте игрите му оттук.</string> + <string name="bnet_dl_failed">Програмата за изтегляне на Blizzard спря: %1$s</string> + <string name="bnet_dl_agent_error">Грешка на Blizzard %1$s</string> + <string name="bnet_update">Актуализиране</string> + <string name="bnet_store">Игри на Blizzard</string> <string name="stores_resume_install">Продължи инсталацията</string> <string name="stores_dl_interrupted">Прекъснато</string> <string name="stores_install_size">Инсталация · %1$s</string> @@ -2015,6 +2039,13 @@ <string name="stores_itch_browse_failed">Игрите от itch.io не можаха да се заредят</string> <string name="stores_itch_archive">Архивите %1$s не се поддържат</string> <string name="stores_itch_download_failed">itch.io отговори HTTP %1$d</string> + <string name="stores_itch_pick_title">Изберете версия</string> + <string name="stores_itch_pick_none">Не са намерени изтегляния за тази игра</string> + <string name="stores_itch_pick_failed">Изтеглянията от itch.io не можаха да се заредят</string> + <string name="stores_itch_build_demo">Демо</string> + <string name="stores_itch_build_open">Отваряне в itch.io</string> + <string name="stores_itch_build_linux_soon">Все още не се поддържа</string> + <string name="stores_itch_no_game">Играта не беше намерена в itch.io</string> <string name="stores_free">Безплатна</string> <string name="stores_resume">Продължи</string> <string name="stores_refresh">Обнови</string> @@ -3000,6 +3031,25 @@ <string name="spatial_saved_views_hint">Запазените изгледи могат да бъдат преизчислени. Започнете ново калибриране за заснемане в текущата координатна система за проследяване.</string> <string name="spatial_model_checksum_error">Несъответствие на контролната сума на модела на ръката</string> <string name="spatial_opencv_load_error">OpenCV не можа да се зареди</string> + <string name="setup_group_memory">Памет</string> + <string name="setup_clear_cached">Затваряне на кешираните приложения преди сесия</string> + <string name="setup_clear_cached_hint">При стартиране на сесия DroidDeck затваря приложенията, които Android държи във фонов режим, за да има играта повече памет. Безжичното отстраняване на грешки трябва да е включено.</string> + <string name="setup_clear_cached_unpaired">Изисква DroidDeck да е сдвоен чрез безжично отстраняване на грешки (Сдвояване, по-долу).</string> + <string name="setup_memory_hud">Показател за паметта</string> + <string name="setup_memory_hud_hint">Използвана памет и swap на екрана на сесията. Разширеният режим я разделя между играта, DroidDeck, Android и GPU.</string> + <string name="setup_memory_hud_simple">Опростен</string> + <string name="setup_memory_hud_advanced">Разширен</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">игра %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Фонови приложения по време на сесия</string> + <string name="setup_bg_limit_hint">Докато сесията работи, Android държи в кеша най-много толкова приложения и затваря останалите, за да получи играта тяхната памет. DroidDeck връща предишното ограничение, когато сесията приключи. Безжичното отстраняване на грешки трябва да е включено.</string> + <string name="setup_bg_limit_4">Най-много 4</string> + <string name="setup_bg_limit_1">Най-много 1</string> + <string name="setup_bg_limit_0">Нито едно</string> + <string name="setup_adb_pair">Безжично отстраняване на грешки</string> + <string name="setup_adb_pair_hint">Сдвоява DroidDeck с безжичното отстраняване на грешки на Android за опциите по-горе. Ограничението на дъщерните процеси остава изключено.</string> + <string name="setup_adb_pair_button">Сдвояване</string> <string name="epic_client_missing">Не е инсталирано</string> <string name="epic_client_open">Отвори</string> <string name="epic_client_install">Инсталиране</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">Премахни от Библиотека</string> <string name="library_in">В Библиотека</string> <string name="xbox_filter_show">Показване</string> + <string name="itch_collections">Колекции</string> <string name="xbox_filter_cloud">Облак</string> <string name="stores_xbox_cloud_settings">Настройки на облака</string> + <string name="apps_search_hint">Търсене на приложения</string> + <string name="apps_no_match">Няма приложения, отговарящи на „%1$s“.</string> + <string name="apps_add_widget">Добавяне на приспособление</string> + <string name="apps_widgets_loading">Приспособленията се зареждат…</string> + <string name="apps_widgets_none">Няма приложения с приспособления на това устройство.</string> + <string name="apps_widget_wider">По-широко</string> + <string name="apps_widget_narrower">По-тясно</string> + <string name="apps_widget_taller">По-високо</string> + <string name="apps_widget_shorter">По-ниско</string> + <string name="apps_widget_move_earlier">Преместване по-рано</string> + <string name="apps_widget_move_later">Преместване по-късно</string> + <string name="apps_widget_configure">Настройки на приспособлението</string> + <string name="apps_widget_remove">Премахване на приспособлението</string> + <string name="apps_add_to_folder">Добавяне в папка</string> + <string name="apps_new_folder">Нова папка</string> + <string name="apps_remove_from_folder">Премахване от папката</string> + <string name="apps_app_info">Информация за приложението</string> + <string name="apps_uninstall">Деинсталиране</string> + <string name="apps_folder_rename">Преименуване</string> + <string name="apps_folder_ungroup">Разгрупиране</string> + <string name="apps_folder_default">Папка</string> + <string name="apps_folder_name">Име на папката</string> + <string name="apps_filter">Показване</string> + <string name="apps_filter_all">Всички приложения</string> + <string name="apps_filter_games">Игри</string> + <string name="apps_filter_downloaded">Изтеглени</string> + <string name="apps_filter_system">Системни</string> + <string name="apps_filter_hidden">Скрити</string> + <string name="apps_hide">Скриване</string> + <string name="apps_unhide">Показване в приложенията</string> + <string name="apps_shortcut_remove">Премахване на прекия път</string> + <string name="apps_pin_title">Добавяне към приложенията</string> + <string name="apps_pin_add">Добавяне</string> + <string name="apps_hidden_none">Няма скрити приложения.</string> + <string name="apps_sort_name_asc">Име А–Я</string> + <string name="apps_sort_name_desc">Име Я–А</string> + <string name="apps_sort_installed">Наскоро инсталирани</string> + <string name="apps_sort_updated">Наскоро актуализирани</string> + <plurals name="apps_count"> + <item quantity="one">%d приложение</item> + <item quantity="other">%d приложения</item> + </plurals> </resources> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 8880695bb6..b9694894ef 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Poměr stran obrazovky</string> <string name="mode_ratio_custom">Určen vlastním rozlišením.</string> <string name="mode_ratio_auto">Automaticky použije alespoň 16:9.</string> - <string name="mode_fps">Omezení snímků</string> - <string name="mode_fps_note">Omezuje celou relaci. Displej přejde na obnovovací frekvenci, kterou lze tímto limitem dělit beze zbytku.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Výstup HDR10</string> <string name="mode_hdr_unavailable">Není k dispozici: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Dotykové ovládání Steamu (beta)</string> <string name="osc_style_next_session">Dotykové ovládání Steamu se spustí od příští relace Steamu</string> <string name="osc_steam_layout">Rozvržení dotykového ovládání Steamu</string> + <string name="screen_keys">Klávesy na obrazovce</string> + <string name="screen_keys_add">Přidat klávesu</string> + <string name="screen_key_text">Text</string> + <string name="screen_key_size">Velikost</string> + <string name="screen_key_opacity">Průhlednost</string> + <string name="screen_key_type_button">Klávesa</string> + <string name="screen_key_shape_trigger">Spoušť</string> + <string name="screen_key_toggle">Přepínač</string> + <string name="screen_key_layout_export">Exportovat</string> + <string name="screen_key_shape_pill">Kapsle</string> + <string name="screen_key_shape_round">Zaoblené</string> + <string name="screen_key_shape_circle">Kruh</string> + <string name="screen_key_shape_rect">Obdélník</string> + <string name="screen_key_bind">Klávesa</string> + <string name="screen_key_image">Obrázek</string> + <string name="screen_key_image_clear">Vymazat</string> + <string name="screen_key_layout">Rozložení</string> + <string name="screen_key_layout_save">Uložit</string> <string name="osc_steam_layout_hint">Přesuňte, změňte velikost nebo skryjte dotykové ovládání této hry; uloží se do Steamu</string> <string name="mode_controller">Ovladač</string> <string name="mode_controller_hint">Jak Steam vidí váš ovladač. Použije se od příští relace.</string> @@ -1967,7 +1983,6 @@ <string name="display_filter_live">Použije se okamžitě. Sdíleno Steamem a Plochou.</string> <string name="display_filter_note">FSR, GSR a NIS se použijí při zvětšování obrazu relace. Jen zaostření funguje i bez zvětšení.</string> <string name="display_sharpness">Ostrost filtru</string> - <string name="display_frame_rate">Snímková frekvence</string> <string name="display_look_filter">%1$s Nastaví škálování na %2$s.</string> <string name="display_match_screen">Podle obrazovky (%1$d×%2$d)</string> <string name="display_follow_screen">Sledovat obrazovku (změní velikost při složení nebo rozložení)</string> @@ -2020,6 +2035,15 @@ <string name="stores_shelf_trending">Populární</string> <string name="stores_play">Hrát</string> <string name="stores_install">Instalovat</string> + <string name="bnet_open">Otevřít Battle.net</string> + <string name="bnet_dl_starting">Spouštění stahovače Blizzardu…</string> + <string name="bnet_dl_waiting">Čekání na zavření Battle.net…</string> + <string name="bnet_dl_queued">Čekání na druhé stahování z Battle.net…</string> + <string name="bnet_dl_client_first">Otevřete Battle.net a jednou se přihlaste, pak instalujte jeho hry odsud.</string> + <string name="bnet_dl_failed">Stahovač Blizzardu se zastavil: %1$s</string> + <string name="bnet_dl_agent_error">Chyba Blizzardu %1$s</string> + <string name="bnet_update">Aktualizovat</string> + <string name="bnet_store">Hry od Blizzardu</string> <string name="stores_resume_install">Pokračovat v instalaci</string> <string name="stores_dl_interrupted">Přerušeno</string> <string name="stores_install_size">Instalace · %1$s</string> @@ -2057,6 +2081,13 @@ <string name="stores_itch_browse_failed">Hry z itch.io se nepodařilo načíst</string> <string name="stores_itch_archive">Archivy %1$s nejsou podporovány</string> <string name="stores_itch_download_failed">itch.io odpovědělo HTTP %1$d</string> + <string name="stores_itch_pick_title">Vyberte verzi</string> + <string name="stores_itch_pick_none">Pro tuto hru nebyla nalezena žádná stažení</string> + <string name="stores_itch_pick_failed">Stahování z itch.io se nepodařilo načíst</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Otevřít na itch.io</string> + <string name="stores_itch_build_linux_soon">Zatím nepodporováno</string> + <string name="stores_itch_no_game">Tuto hru se na itch.io nepodařilo najít</string> <string name="stores_free">Zdarma</string> <string name="stores_resume">Pokračovat</string> <string name="stores_refresh">Obnovit</string> @@ -3068,6 +3099,25 @@ <string name="spatial_saved_views_hint">Uložená zobrazení lze přepočítat. Spusťte novou kalibraci pro zachycení v aktuálním sledovacím souřadnicovém systému.</string> <string name="spatial_model_checksum_error">Neshoda kontrolního součtu modelu ruky</string> <string name="spatial_opencv_load_error">OpenCV se nepodařilo načíst</string> + <string name="setup_group_memory">Paměť</string> + <string name="setup_clear_cached">Zavřít aplikace v mezipaměti před relací</string> + <string name="setup_clear_cached_hint">Při spuštění relace DroidDeck zavře aplikace, které Android drží na pozadí, aby hra měla více paměti. Musí být zapnuté Bezdrátové ladění.</string> + <string name="setup_clear_cached_unpaired">Vyžaduje DroidDeck spárovaný přes Bezdrátové ladění (Spárovat, níže).</string> + <string name="setup_memory_hud">Ukazatel paměti</string> + <string name="setup_memory_hud_hint">Využitá paměť a swap na obrazovce relace. Pokročilé zobrazení ji rozdělí na hru, DroidDeck, Android a GPU.</string> + <string name="setup_memory_hud_simple">Jednoduché</string> + <string name="setup_memory_hud_advanced">Pokročilé</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">hra %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Aplikace na pozadí během relace</string> + <string name="setup_bg_limit_hint">Během relace Android ponechá v mezipaměti nejvýše tolik aplikací a ostatní zavře, aby hra dostala jejich paměť. Po skončení relace DroidDeck vrátí limit na původní hodnotu. Musí být zapnuté Bezdrátové ladění.</string> + <string name="setup_bg_limit_4">Nejvýše 4</string> + <string name="setup_bg_limit_1">Nejvýše 1</string> + <string name="setup_bg_limit_0">Žádné</string> + <string name="setup_adb_pair">Bezdrátové ladění</string> + <string name="setup_adb_pair_hint">Spáruje DroidDeck s Bezdrátovým laděním Androidu pro výše uvedené možnosti. Omezení pro dětské procesy zůstane vypnuté.</string> + <string name="setup_adb_pair_button">Spárovat</string> <string name="epic_client_missing">Není nainstalováno</string> <string name="epic_client_open">Otevřít</string> <string name="epic_client_install">Instalovat</string> @@ -3100,6 +3150,51 @@ <string name="library_remove">Odebrat z knihovny</string> <string name="library_in">V knihovně</string> <string name="xbox_filter_show">Zobrazit</string> + <string name="itch_collections">Kolekce</string> <string name="xbox_filter_cloud">Cloud</string> <string name="stores_xbox_cloud_settings">Nastavení cloudu</string> + <string name="apps_search_hint">Hledat aplikace</string> + <string name="apps_no_match">Výrazu „%1$s“ neodpovídá žádná aplikace.</string> + <string name="apps_add_widget">Přidat widget</string> + <string name="apps_widgets_loading">Načítání widgetů…</string> + <string name="apps_widgets_none">Žádná aplikace v zařízení nenabízí widgety.</string> + <string name="apps_widget_wider">Širší</string> + <string name="apps_widget_narrower">Užší</string> + <string name="apps_widget_taller">Vyšší</string> + <string name="apps_widget_shorter">Nižší</string> + <string name="apps_widget_move_earlier">Posunout dříve</string> + <string name="apps_widget_move_later">Posunout později</string> + <string name="apps_widget_configure">Nastavení widgetu</string> + <string name="apps_widget_remove">Odebrat widget</string> + <string name="apps_add_to_folder">Přidat do složky</string> + <string name="apps_new_folder">Nová složka</string> + <string name="apps_remove_from_folder">Odebrat ze složky</string> + <string name="apps_app_info">Informace o aplikaci</string> + <string name="apps_uninstall">Odinstalovat</string> + <string name="apps_folder_rename">Přejmenovat</string> + <string name="apps_folder_ungroup">Zrušit složku</string> + <string name="apps_folder_default">Složka</string> + <string name="apps_folder_name">Název složky</string> + <string name="apps_filter">Zobrazit</string> + <string name="apps_filter_all">Všechny aplikace</string> + <string name="apps_filter_games">Hry</string> + <string name="apps_filter_downloaded">Stažené</string> + <string name="apps_filter_system">Systémové</string> + <string name="apps_filter_hidden">Skryté</string> + <string name="apps_hide">Skrýt</string> + <string name="apps_unhide">Zobrazit v aplikacích</string> + <string name="apps_shortcut_remove">Odebrat zkratku</string> + <string name="apps_pin_title">Přidat do aplikací</string> + <string name="apps_pin_add">Přidat</string> + <string name="apps_hidden_none">Žádné skryté aplikace.</string> + <string name="apps_sort_name_asc">Název A–Z</string> + <string name="apps_sort_name_desc">Název Z–A</string> + <string name="apps_sort_installed">Nedávno nainstalované</string> + <string name="apps_sort_updated">Nedávno aktualizované</string> + <plurals name="apps_count"> + <item quantity="one">%d aplikace</item> + <item quantity="few">%d aplikace</item> + <item quantity="many">%d aplikace</item> + <item quantity="other">%d aplikací</item> + </plurals> </resources> diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 853328bfd2..af13b452d1 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Billedformat</string> <string name="mode_ratio_custom">Angivet af den brugerdefinerede opløsning.</string> <string name="mode_ratio_auto">Auto bruger mindst 16:9.</string> - <string name="mode_fps">Billedgrænse</string> - <string name="mode_fps_note">Begrænser hele sessionen. Skærmen skifter til en opdateringshastighed, grænsen går lige op med.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-output</string> <string name="mode_hdr_unavailable">Ikke tilgængelig: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam-berøring (beta)</string> <string name="osc_style_next_session">Steams berøringskontroller starter med næste Steam-session</string> <string name="osc_steam_layout">Steam-berøringslayout</string> + <string name="screen_keys">Skærmtaster</string> + <string name="screen_keys_add">Tilføj tast</string> + <string name="screen_key_text">Tekst</string> + <string name="screen_key_size">Størrelse</string> + <string name="screen_key_opacity">Gennemsigtighed</string> + <string name="screen_key_type_button">Tast</string> + <string name="screen_key_shape_trigger">Udløser</string> + <string name="screen_key_toggle">Skift</string> + <string name="screen_key_layout_export">Eksportér</string> + <string name="screen_key_shape_pill">Kapsel</string> + <string name="screen_key_shape_round">Afrundet</string> + <string name="screen_key_shape_circle">Cirkel</string> + <string name="screen_key_shape_rect">Rektangel</string> + <string name="screen_key_bind">Tast</string> + <string name="screen_key_image">Billede</string> + <string name="screen_key_image_clear">Ryd</string> + <string name="screen_key_layout">Layout</string> + <string name="screen_key_layout_save">Gem</string> <string name="osc_steam_layout_hint">Flyt, tilpas størrelsen på eller skjul dette spils berøringskontroller; gemmes til Steam</string> <string name="mode_controller">Controller</string> <string name="mode_controller_hint">Hvordan Steam ser din controller. Gælder fra næste session.</string> @@ -1925,7 +1941,6 @@ <string name="display_filter_live">Træder i kraft øjeblikkeligt. Deles af Steam og Desktop.</string> <string name="display_filter_note">FSR, GSR og NIS anvendes ved forstørrelse af sessionsbilledet. Kun skærpning virker også uden forstørrelse.</string> <string name="display_sharpness">Filterskarphed</string> - <string name="display_frame_rate">Billedfrekvens</string> <string name="display_look_filter">%1$s Indstiller skalering til %2$s.</string> <string name="display_match_screen">Match skærm (%1$d×%2$d)</string> <string name="display_follow_screen">Følg skærm (ændrer størrelse ved fold/udfold)</string> @@ -1978,6 +1993,15 @@ <string name="stores_shelf_trending">Populært</string> <string name="stores_play">Spil</string> <string name="stores_install">Installer</string> + <string name="bnet_open">Åbn Battle.net</string> + <string name="bnet_dl_starting">Starter Blizzards downloader…</string> + <string name="bnet_dl_waiting">Venter på, at Battle.net lukker…</string> + <string name="bnet_dl_queued">Venter på den anden Battle.net-download…</string> + <string name="bnet_dl_client_first">Åbn Battle.net, og log ind én gang, og installer derefter dets spil herfra.</string> + <string name="bnet_dl_failed">Blizzards downloader stoppede: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard-fejl %1$s</string> + <string name="bnet_update">Opdater</string> + <string name="bnet_store">Blizzard-spil</string> <string name="stores_resume_install">Genoptag installation</string> <string name="stores_dl_interrupted">Afbrudt</string> <string name="stores_install_size">Installation · %1$s</string> @@ -2015,6 +2039,13 @@ <string name="stores_itch_browse_failed">Kunne ikke hente spil fra itch.io</string> <string name="stores_itch_archive">%1$s-arkiver understøttes ikke</string> <string name="stores_itch_download_failed">itch.io svarede HTTP %1$d</string> + <string name="stores_itch_pick_title">Vælg en version</string> + <string name="stores_itch_pick_none">Ingen downloads fundet til dette spil</string> + <string name="stores_itch_pick_failed">Kunne ikke indlæse downloads fra itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Åbn på itch.io</string> + <string name="stores_itch_build_linux_soon">Understøttes ikke endnu</string> + <string name="stores_itch_no_game">Kunne ikke finde dette spil på itch.io</string> <string name="stores_free">Gratis</string> <string name="stores_resume">Genoptag</string> <string name="stores_refresh">Opdater</string> @@ -3000,6 +3031,25 @@ <string name="spatial_saved_views_hint">Gemte visninger kan genberegnes. Start en ny kalibrering for at fange i det aktuelle sporingskoordinatsystem.</string> <string name="spatial_model_checksum_error">Håndmodel kontrolsum uoverensstemmelse</string> <string name="spatial_opencv_load_error">OpenCV kunne ikke indlæse</string> + <string name="setup_group_memory">Hukommelse</string> + <string name="setup_clear_cached">Luk cachelagrede apps før en session</string> + <string name="setup_clear_cached_hint">Når en session starter, lukker DroidDeck de apps, Android holder parkeret i baggrunden, så spillet får mere hukommelse. Trådløs fejlretning skal være slået til.</string> + <string name="setup_clear_cached_unpaired">Kræver, at DroidDeck er parret med Trådløs fejlretning (Par, nedenfor).</string> + <string name="setup_memory_hud">Hukommelsesvisning</string> + <string name="setup_memory_hud_hint">Hukommelse og swap i brug på sessionsskærmen. Avanceret fordeler det på spillet, DroidDeck, Android og GPU\'en.</string> + <string name="setup_memory_hud_simple">Enkel</string> + <string name="setup_memory_hud_advanced">Avanceret</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">spil %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Baggrundsapps under en session</string> + <string name="setup_bg_limit_hint">Mens en session kører, holder Android højst så mange apps i cache og lukker resten, så spillet får deres hukommelse. DroidDeck sætter grænsen tilbage, som den var, når sessionen slutter. Trådløs fejlretning skal være slået til.</string> + <string name="setup_bg_limit_4">Højst 4</string> + <string name="setup_bg_limit_1">Højst 1</string> + <string name="setup_bg_limit_0">Ingen</string> + <string name="setup_adb_pair">Trådløs fejlretning</string> + <string name="setup_adb_pair_hint">Parrer DroidDeck med Androids Trådløs fejlretning til indstillingerne ovenfor. Grænsen for underprocesser forbliver slået fra.</string> + <string name="setup_adb_pair_button">Par</string> <string name="epic_client_missing">Ikke installeret</string> <string name="epic_client_open">Åbn</string> <string name="epic_client_install">Installer</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">Fjern fra Bibliotek</string> <string name="library_in">I Bibliotek</string> <string name="xbox_filter_show">Vis</string> + <string name="itch_collections">Samlinger</string> <string name="xbox_filter_cloud">Sky</string> <string name="stores_xbox_cloud_settings">Skyindstillinger</string> + <string name="apps_search_hint">Søg i apps</string> + <string name="apps_no_match">Ingen apps matcher “%1$s”.</string> + <string name="apps_add_widget">Tilføj widget</string> + <string name="apps_widgets_loading">Indlæser widgets…</string> + <string name="apps_widgets_none">Ingen apps på enheden tilbyder widgets.</string> + <string name="apps_widget_wider">Bredere</string> + <string name="apps_widget_narrower">Smallere</string> + <string name="apps_widget_taller">Højere</string> + <string name="apps_widget_shorter">Lavere</string> + <string name="apps_widget_move_earlier">Flyt tidligere</string> + <string name="apps_widget_move_later">Flyt senere</string> + <string name="apps_widget_configure">Widgetindstillinger</string> + <string name="apps_widget_remove">Fjern widget</string> + <string name="apps_add_to_folder">Føj til mappe</string> + <string name="apps_new_folder">Ny mappe</string> + <string name="apps_remove_from_folder">Fjern fra mappe</string> + <string name="apps_app_info">Appinfo</string> + <string name="apps_uninstall">Afinstaller</string> + <string name="apps_folder_rename">Omdøb</string> + <string name="apps_folder_ungroup">Opløs</string> + <string name="apps_folder_default">Mappe</string> + <string name="apps_folder_name">Mappenavn</string> + <string name="apps_filter">Vis</string> + <string name="apps_filter_all">Alle apps</string> + <string name="apps_filter_games">Spil</string> + <string name="apps_filter_downloaded">Downloadet</string> + <string name="apps_filter_system">System</string> + <string name="apps_filter_hidden">Skjulte</string> + <string name="apps_hide">Skjul</string> + <string name="apps_unhide">Vis i apps</string> + <string name="apps_shortcut_remove">Fjern genvej</string> + <string name="apps_pin_title">Føj til Apps</string> + <string name="apps_pin_add">Tilføj</string> + <string name="apps_hidden_none">Ingen skjulte apps.</string> + <string name="apps_sort_name_asc">Navn A–Å</string> + <string name="apps_sort_name_desc">Navn Å–A</string> + <string name="apps_sort_installed">Senest installeret</string> + <string name="apps_sort_updated">Senest opdateret</string> + <plurals name="apps_count"> + <item quantity="one">%d app</item> + <item quantity="other">%d apps</item> + </plurals> </resources> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index db7241eaf3..9ffcfe1fd0 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Seitenverhältnis</string> <string name="mode_ratio_custom">Durch die benutzerdefinierte Auflösung festgelegt.</string> <string name="mode_ratio_auto">Auto verwendet mindestens 16:9.</string> - <string name="mode_fps">Bildratenlimit</string> - <string name="mode_fps_note">Begrenzt die gesamte Sitzung. Das Display wechselt auf eine Bildwiederholrate, die ein ganzzahliges Vielfaches des Limits ist.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-Ausgabe</string> <string name="mode_hdr_unavailable">Nicht verfügbar: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam-Touch (Beta)</string> <string name="osc_style_next_session">Steams Touch-Steuerung startet mit der nächsten Steam-Sitzung</string> <string name="osc_steam_layout">Steam-Touch-Layout</string> + <string name="screen_keys">Bildschirmtasten</string> + <string name="screen_keys_add">Taste hinzufügen</string> + <string name="screen_key_text">Text</string> + <string name="screen_key_size">Größe</string> + <string name="screen_key_opacity">Deckkraft</string> + <string name="screen_key_type_button">Taste</string> + <string name="screen_key_shape_trigger">Trigger</string> + <string name="screen_key_toggle">Umschalten</string> + <string name="screen_key_layout_export">Exportieren</string> + <string name="screen_key_shape_pill">Kapsel</string> + <string name="screen_key_shape_round">Rund</string> + <string name="screen_key_shape_circle">Kreis</string> + <string name="screen_key_shape_rect">Rechteck</string> + <string name="screen_key_bind">Taste</string> + <string name="screen_key_image">Bild</string> + <string name="screen_key_image_clear">Entfernen</string> + <string name="screen_key_layout">Layout</string> + <string name="screen_key_layout_save">Speichern</string> <string name="osc_steam_layout_hint">Touch-Steuerung dieses Spiels verschieben, skalieren oder ausblenden; wird in Steam gespeichert</string> <string name="mode_controller">Controller</string> <string name="mode_controller_hint">Wie Steam deinen Controller erkennt. Gilt ab der nächsten Sitzung.</string> @@ -1917,7 +1933,6 @@ <string name="display_filter_live">Wirkt sofort. Gemeinsam für Steam und Desktop.</string> <string name="display_filter_note">FSR, GSR und NIS wirken beim Vergrößern des Sitzungsbilds. „Nur schärfen“ funktioniert auch ohne Vergrößerung.</string> <string name="display_sharpness">Filterschärfe</string> - <string name="display_frame_rate">Bildrate</string> <string name="display_look_filter">%1$s Stellt die Skalierung auf %2$s.</string> <string name="display_match_screen">An Bildschirm anpassen (%1$d×%2$d)</string> <string name="display_follow_screen">Bildschirm folgen (passt sich beim Auf- und Zuklappen an)</string> @@ -1970,6 +1985,15 @@ <string name="stores_shelf_trending">Im Trend</string> <string name="stores_play">Spielen</string> <string name="stores_install">Installieren</string> + <string name="bnet_open">Battle.net öffnen</string> + <string name="bnet_dl_starting">Blizzards Downloader wird gestartet…</string> + <string name="bnet_dl_waiting">Warten, bis Battle.net geschlossen ist…</string> + <string name="bnet_dl_queued">Warten auf den anderen Battle.net-Download…</string> + <string name="bnet_dl_client_first">Öffne Battle.net und melde dich einmal an, dann installiere seine Spiele hier.</string> + <string name="bnet_dl_failed">Blizzards Downloader wurde beendet: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard-Fehler %1$s</string> + <string name="bnet_update">Aktualisieren</string> + <string name="bnet_store">Blizzard-Spiele</string> <string name="stores_resume_install">Installation fortsetzen</string> <string name="stores_dl_interrupted">Unterbrochen</string> <string name="stores_install_size">Installieren · %1$s</string> @@ -2007,6 +2031,13 @@ <string name="stores_itch_browse_failed">Spiele von itch.io konnten nicht geladen werden</string> <string name="stores_itch_archive">%1$s-Archive werden nicht unterstützt</string> <string name="stores_itch_download_failed">itch.io antwortete mit HTTP %1$d</string> + <string name="stores_itch_pick_title">Version auswählen</string> + <string name="stores_itch_pick_none">Für dieses Spiel wurden keine Downloads gefunden</string> + <string name="stores_itch_pick_failed">Die Downloads von itch.io konnten nicht geladen werden</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Auf itch.io öffnen</string> + <string name="stores_itch_build_linux_soon">Noch nicht unterstützt</string> + <string name="stores_itch_no_game">Dieses Spiel wurde auf itch.io nicht gefunden</string> <string name="stores_free">Kostenlos</string> <string name="stores_resume">Fortsetzen</string> <string name="stores_refresh">Aktualisieren</string> @@ -3000,6 +3031,25 @@ <string name="spatial_saved_views_hint">Gespeicherte Ansichten können neu berechnet werden. Starten Sie eine neue Kalibrierung zur Erfassung im aktuellen Tracking-Koordinatensystem.</string> <string name="spatial_model_checksum_error">Die Prüfsumme des Handmodells stimmt nicht überein</string> <string name="spatial_opencv_load_error">OpenCV konnte nicht geladen werden</string> + <string name="setup_group_memory">Arbeitsspeicher</string> + <string name="setup_clear_cached">Apps im Cache vor einer Sitzung schließen</string> + <string name="setup_clear_cached_hint">Beim Start einer Sitzung schließt DroidDeck die Apps, die Android im Hintergrund vorhält, damit das Spiel mehr Arbeitsspeicher hat. „Debugging über WLAN“ muss aktiviert sein.</string> + <string name="setup_clear_cached_unpaired">DroidDeck muss über „Debugging über WLAN“ gekoppelt sein (Koppeln, unten).</string> + <string name="setup_memory_hud">Speicheranzeige</string> + <string name="setup_memory_hud_hint">Belegter Arbeitsspeicher und Swap auf dem Sitzungsbildschirm. „Erweitert“ schlüsselt ihn nach Spiel, DroidDeck, Android und GPU auf.</string> + <string name="setup_memory_hud_simple">Einfach</string> + <string name="setup_memory_hud_advanced">Erweitert</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · Swap %3$s/%4$s GB</string> + <string name="memory_hud_split">Spiel %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Hintergrund-Apps während einer Sitzung</string> + <string name="setup_bg_limit_hint">Während eine Sitzung läuft, hält Android höchstens so viele Apps im Cache und schließt die übrigen, damit das Spiel deren Speicher bekommt. DroidDeck stellt das vorherige Limit wieder her, wenn die Sitzung endet. „Debugging über WLAN“ muss aktiviert sein.</string> + <string name="setup_bg_limit_4">Höchstens 4</string> + <string name="setup_bg_limit_1">Höchstens 1</string> + <string name="setup_bg_limit_0">Keine</string> + <string name="setup_adb_pair">Debugging über WLAN</string> + <string name="setup_adb_pair_hint">Koppelt DroidDeck mit „Debugging über WLAN“ von Android für die Optionen oben. Das Limit für untergeordnete Prozesse bleibt aus.</string> + <string name="setup_adb_pair_button">Koppeln</string> <string name="epic_client_missing">Nicht installiert</string> <string name="epic_client_open">Öffnen</string> <string name="epic_client_install">Installieren</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">Aus der Bibliothek entfernen</string> <string name="library_in">In der Bibliothek</string> <string name="xbox_filter_show">Anzeigen</string> + <string name="itch_collections">Sammlungen</string> <string name="xbox_filter_cloud">Cloud</string> <string name="stores_xbox_cloud_settings">Cloud-Einstellungen</string> + <string name="apps_search_hint">Apps durchsuchen</string> + <string name="apps_no_match">Keine Apps passen zu „%1$s“.</string> + <string name="apps_add_widget">Widget hinzufügen</string> + <string name="apps_widgets_loading">Widgets werden geladen…</string> + <string name="apps_widgets_none">Keine App auf diesem Gerät bietet Widgets an.</string> + <string name="apps_widget_wider">Breiter</string> + <string name="apps_widget_narrower">Schmaler</string> + <string name="apps_widget_taller">Höher</string> + <string name="apps_widget_shorter">Niedriger</string> + <string name="apps_widget_move_earlier">Nach vorne</string> + <string name="apps_widget_move_later">Nach hinten</string> + <string name="apps_widget_configure">Widget-Einstellungen</string> + <string name="apps_widget_remove">Widget entfernen</string> + <string name="apps_add_to_folder">Zu Ordner hinzufügen</string> + <string name="apps_new_folder">Neuer Ordner</string> + <string name="apps_remove_from_folder">Aus Ordner entfernen</string> + <string name="apps_app_info">App-Info</string> + <string name="apps_uninstall">Deinstallieren</string> + <string name="apps_folder_rename">Umbenennen</string> + <string name="apps_folder_ungroup">Auflösen</string> + <string name="apps_folder_default">Ordner</string> + <string name="apps_folder_name">Ordnername</string> + <string name="apps_filter">Anzeigen</string> + <string name="apps_filter_all">Alle Apps</string> + <string name="apps_filter_games">Spiele</string> + <string name="apps_filter_downloaded">Heruntergeladen</string> + <string name="apps_filter_system">System</string> + <string name="apps_filter_hidden">Ausgeblendet</string> + <string name="apps_hide">Ausblenden</string> + <string name="apps_unhide">In Apps anzeigen</string> + <string name="apps_shortcut_remove">Verknüpfung entfernen</string> + <string name="apps_pin_title">Zu Apps hinzufügen</string> + <string name="apps_pin_add">Hinzufügen</string> + <string name="apps_hidden_none">Keine ausgeblendeten Apps.</string> + <string name="apps_sort_name_asc">Name A–Z</string> + <string name="apps_sort_name_desc">Name Z–A</string> + <string name="apps_sort_installed">Zuletzt installiert</string> + <string name="apps_sort_updated">Zuletzt aktualisiert</string> + <plurals name="apps_count"> + <item quantity="one">%d App</item> + <item quantity="other">%d Apps</item> + </plurals> </resources> diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index f720eba4f9..c8588ac9c2 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Αναλογία οθόνης</string> <string name="mode_ratio_custom">Καθορίζεται από την προσαρμοσμένη ανάλυση.</string> <string name="mode_ratio_auto">Το Αυτόματο χρησιμοποιεί τουλάχιστον 16:9.</string> - <string name="mode_fps">Όριο καρέ</string> - <string name="mode_fps_note">Περιορίζει ολόκληρη τη συνεδρία. Η οθόνη μεταβαίνει σε ρυθμό ανανέωσης που διαιρείται ακριβώς με το όριο.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Έξοδος HDR10</string> <string name="mode_hdr_unavailable">Μη διαθέσιμο: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Αφή Steam (beta)</string> <string name="osc_style_next_session">Τα χειριστήρια αφής του Steam ξεκινούν από την επόμενη συνεδρία Steam</string> <string name="osc_steam_layout">Διάταξη αφής Steam</string> + <string name="screen_keys">Πλήκτρα οθόνης</string> + <string name="screen_keys_add">Προσθήκη πλήκτρου</string> + <string name="screen_key_text">Κείμενο</string> + <string name="screen_key_size">Μέγεθος</string> + <string name="screen_key_opacity">Διαφάνεια</string> + <string name="screen_key_type_button">Πλήκτρο</string> + <string name="screen_key_shape_trigger">Σκανδάλη</string> + <string name="screen_key_toggle">Εναλλαγή</string> + <string name="screen_key_layout_export">Εξαγωγή</string> + <string name="screen_key_shape_pill">Κάψουλα</string> + <string name="screen_key_shape_round">Στρογγυλεμένο</string> + <string name="screen_key_shape_circle">Κύκλος</string> + <string name="screen_key_shape_rect">Ορθογώνιο</string> + <string name="screen_key_bind">Πλήκτρο</string> + <string name="screen_key_image">Εικόνα</string> + <string name="screen_key_image_clear">Εκκαθάριση</string> + <string name="screen_key_layout">Διάταξη</string> + <string name="screen_key_layout_save">Αποθήκευση</string> <string name="osc_steam_layout_hint">Μετακινήστε, αλλάξτε μέγεθος ή αποκρύψτε τα χειριστήρια αφής αυτού του παιχνιδιού· αποθηκεύεται στο Steam</string> <string name="mode_controller">Χειριστήριο</string> <string name="mode_controller_hint">Πώς βλέπει το Steam το χειριστήριό σας. Εφαρμόζεται στην επόμενη συνεδρία.</string> @@ -1925,7 +1941,6 @@ <string name="display_filter_live">Εφαρμόζεται σε πραγματικό χρόνο. Κοινό για το Steam και την Επιφάνεια εργασίας.</string> <string name="display_filter_note">Τα FSR, GSR και NIS εφαρμόζονται κατά τη μεγέθυνση της εικόνας συνεδρίας. Το Μόνο όξυνση λειτουργεί και χωρίς μεγέθυνση.</string> <string name="display_sharpness">Οξύτητα φίλτρου</string> - <string name="display_frame_rate">Καρέ ανά δευτερόλεπτο</string> <string name="display_look_filter">%1$s Ορίζει την κλιμάκωση σε %2$s.</string> <string name="display_match_screen">Αντιστοίχιση οθόνης (%1$d×%2$d)</string> <string name="display_follow_screen">Ακολούθηση οθόνης (αλλάζει μέγεθος όταν διπλώνει ή ξεδιπλώνει)</string> @@ -1978,6 +1993,15 @@ <string name="stores_shelf_trending">Σε άνοδο</string> <string name="stores_play">Αναπαραγωγή</string> <string name="stores_install">Εγκατάσταση</string> + <string name="bnet_open">Άνοιγμα του Battle.net</string> + <string name="bnet_dl_starting">Εκκίνηση του προγράμματος λήψης της Blizzard…</string> + <string name="bnet_dl_waiting">Αναμονή για κλείσιμο του Battle.net…</string> + <string name="bnet_dl_queued">Αναμονή για την άλλη λήψη από το Battle.net…</string> + <string name="bnet_dl_client_first">Ανοίξτε το Battle.net και συνδεθείτε μία φορά, έπειτα εγκαταστήστε τα παιχνίδια του από εδώ.</string> + <string name="bnet_dl_failed">Το πρόγραμμα λήψης της Blizzard σταμάτησε: %1$s</string> + <string name="bnet_dl_agent_error">Σφάλμα Blizzard %1$s</string> + <string name="bnet_update">Ενημέρωση</string> + <string name="bnet_store">Παιχνίδια της Blizzard</string> <string name="stores_resume_install">Συνέχιση εγκατάστασης</string> <string name="stores_dl_interrupted">Διακόπηκε</string> <string name="stores_install_size">Εγκατάσταση · %1$s</string> @@ -2015,6 +2039,13 @@ <string name="stores_itch_browse_failed">Δεν ήταν δυνατή η φόρτωση παιχνιδιών από το itch.io</string> <string name="stores_itch_archive">Τα αρχεία %1$s δεν υποστηρίζονται</string> <string name="stores_itch_download_failed">Το itch.io απάντησε HTTP %1$d</string> + <string name="stores_itch_pick_title">Επιλέξτε έκδοση</string> + <string name="stores_itch_pick_none">Δεν βρέθηκαν λήψεις για αυτό το παιχνίδι</string> + <string name="stores_itch_pick_failed">Δεν ήταν δυνατή η φόρτωση των λήψεων από το itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Άνοιγμα στο itch.io</string> + <string name="stores_itch_build_linux_soon">Δεν υποστηρίζεται ακόμη</string> + <string name="stores_itch_no_game">Δεν βρέθηκε αυτό το παιχνίδι στο itch.io</string> <string name="stores_free">Δωρεάν</string> <string name="stores_resume">Συνέχιση</string> <string name="stores_refresh">Ανανέωση</string> @@ -3000,6 +3031,25 @@ <string name="spatial_saved_views_hint">Οι αποθηκευμένες προβολές μπορούν να υπολογιστούν εκ νέου. Ξεκινήστε μια νέα βαθμονόμηση για αποτύπωση στο τρέχον σύστημα συντεταγμένων παρακολούθησης.</string> <string name="spatial_model_checksum_error">Αναντιστοιχία αθροίσματος ελέγχου μοντέλου χεριού</string> <string name="spatial_opencv_load_error">Δεν ήταν δυνατή η φόρτωση του OpenCV</string> + <string name="setup_group_memory">Μνήμη</string> + <string name="setup_clear_cached">Κλείσιμο εφαρμογών στην προσωρινή μνήμη πριν από τη συνεδρία</string> + <string name="setup_clear_cached_hint">Όταν ξεκινά μια συνεδρία, το DroidDeck κλείνει τις εφαρμογές που το Android κρατά στο παρασκήνιο, ώστε το παιχνίδι να έχει περισσότερη μνήμη. Ο Ασύρματος εντοπισμός σφαλμάτων πρέπει να είναι ενεργός.</string> + <string name="setup_clear_cached_unpaired">Απαιτεί σύζευξη του DroidDeck με τον Ασύρματο εντοπισμό σφαλμάτων (Σύζευξη, παρακάτω).</string> + <string name="setup_memory_hud">Ένδειξη μνήμης</string> + <string name="setup_memory_hud_hint">Μνήμη και swap σε χρήση, στην οθόνη της συνεδρίας. Με την επιλογή «Για προχωρημένους» χωρίζεται σε παιχνίδι, DroidDeck, Android και GPU.</string> + <string name="setup_memory_hud_simple">Απλή</string> + <string name="setup_memory_hud_advanced">Για προχωρημένους</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">παιχνίδι %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Εφαρμογές παρασκηνίου κατά τη συνεδρία</string> + <string name="setup_bg_limit_hint">Όσο εκτελείται μια συνεδρία, το Android κρατά στην προσωρινή μνήμη το πολύ τόσες εφαρμογές και κλείνει τις υπόλοιπες, ώστε το παιχνίδι να πάρει τη μνήμη τους. Το DroidDeck επαναφέρει το όριο όπως ήταν όταν τελειώσει η συνεδρία. Ο Ασύρματος εντοπισμός σφαλμάτων πρέπει να είναι ενεργός.</string> + <string name="setup_bg_limit_4">Το πολύ 4</string> + <string name="setup_bg_limit_1">Το πολύ 1</string> + <string name="setup_bg_limit_0">Καμία</string> + <string name="setup_adb_pair">Ασύρματος εντοπισμός σφαλμάτων</string> + <string name="setup_adb_pair_hint">Συζευγνύει το DroidDeck με τον Ασύρματο εντοπισμό σφαλμάτων του Android για τις παραπάνω επιλογές. Το όριο θυγατρικών διαδικασιών παραμένει απενεργοποιημένο.</string> + <string name="setup_adb_pair_button">Σύζευξη</string> <string name="epic_client_missing">Δεν είναι εγκατεστημένο</string> <string name="epic_client_open">Άνοιγμα</string> <string name="epic_client_install">Εγκατάσταση</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">Αφαίρεση από τη Βιβλιοθήκη</string> <string name="library_in">Στη Βιβλιοθήκη</string> <string name="xbox_filter_show">Εμφάνιση</string> + <string name="itch_collections">Συλλογές</string> <string name="xbox_filter_cloud">Cloud</string> <string name="stores_xbox_cloud_settings">Ρυθμίσεις cloud</string> + <string name="apps_search_hint">Αναζήτηση εφαρμογών</string> + <string name="apps_no_match">Καμία εφαρμογή δεν ταιριάζει με «%1$s».</string> + <string name="apps_add_widget">Προσθήκη γραφικού στοιχείου</string> + <string name="apps_widgets_loading">Φόρτωση γραφικών στοιχείων…</string> + <string name="apps_widgets_none">Καμία εφαρμογή στη συσκευή δεν προσφέρει γραφικά στοιχεία.</string> + <string name="apps_widget_wider">Πλατύτερο</string> + <string name="apps_widget_narrower">Στενότερο</string> + <string name="apps_widget_taller">Ψηλότερο</string> + <string name="apps_widget_shorter">Χαμηλότερο</string> + <string name="apps_widget_move_earlier">Μετακίνηση νωρίτερα</string> + <string name="apps_widget_move_later">Μετακίνηση αργότερα</string> + <string name="apps_widget_configure">Ρυθμίσεις γραφικού στοιχείου</string> + <string name="apps_widget_remove">Αφαίρεση γραφικού στοιχείου</string> + <string name="apps_add_to_folder">Προσθήκη σε φάκελο</string> + <string name="apps_new_folder">Νέος φάκελος</string> + <string name="apps_remove_from_folder">Αφαίρεση από φάκελο</string> + <string name="apps_app_info">Πληροφορίες εφαρμογής</string> + <string name="apps_uninstall">Απεγκατάσταση</string> + <string name="apps_folder_rename">Μετονομασία</string> + <string name="apps_folder_ungroup">Κατάργηση ομάδας</string> + <string name="apps_folder_default">Φάκελος</string> + <string name="apps_folder_name">Όνομα φακέλου</string> + <string name="apps_filter">Εμφάνιση</string> + <string name="apps_filter_all">Όλες οι εφαρμογές</string> + <string name="apps_filter_games">Παιχνίδια</string> + <string name="apps_filter_downloaded">Ληφθείσες</string> + <string name="apps_filter_system">Συστήματος</string> + <string name="apps_filter_hidden">Κρυφές</string> + <string name="apps_hide">Απόκρυψη</string> + <string name="apps_unhide">Εμφάνιση στις εφαρμογές</string> + <string name="apps_shortcut_remove">Αφαίρεση συντόμευσης</string> + <string name="apps_pin_title">Προσθήκη στις Εφαρμογές</string> + <string name="apps_pin_add">Προσθήκη</string> + <string name="apps_hidden_none">Δεν υπάρχουν κρυφές εφαρμογές.</string> + <string name="apps_sort_name_asc">Όνομα Α–Ω</string> + <string name="apps_sort_name_desc">Όνομα Ω–Α</string> + <string name="apps_sort_installed">Πρόσφατα εγκατεστημένες</string> + <string name="apps_sort_updated">Πρόσφατα ενημερωμένες</string> + <plurals name="apps_count"> + <item quantity="one">%d εφαρμογή</item> + <item quantity="other">%d εφαρμογές</item> + </plurals> </resources> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 118be6cee0..82af913320 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Relación de aspecto</string> <string name="mode_ratio_custom">Definida por la resolución personalizada.</string> <string name="mode_ratio_auto">Auto usa al menos 16:9.</string> - <string name="mode_fps">Límite de fotogramas</string> - <string name="mode_fps_note">Limita toda la sesión. La pantalla cambia a una tasa de refresco que el límite divide exactamente.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Salida HDR10</string> <string name="mode_hdr_unavailable">No disponible: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Táctil de Steam (beta)</string> <string name="osc_style_next_session">Los controles táctiles de Steam se activan en la próxima sesión de Steam</string> <string name="osc_steam_layout">Disposición táctil de Steam</string> + <string name="screen_keys">Teclas en pantalla</string> + <string name="screen_keys_add">Añadir tecla</string> + <string name="screen_key_text">Texto</string> + <string name="screen_key_size">Tamaño</string> + <string name="screen_key_opacity">Opacidad</string> + <string name="screen_key_type_button">Tecla</string> + <string name="screen_key_shape_trigger">Gatillo</string> + <string name="screen_key_toggle">Alternar</string> + <string name="screen_key_layout_export">Exportar</string> + <string name="screen_key_shape_pill">Píldora</string> + <string name="screen_key_shape_round">Redondeado</string> + <string name="screen_key_shape_circle">Círculo</string> + <string name="screen_key_shape_rect">Rectángulo</string> + <string name="screen_key_bind">Tecla</string> + <string name="screen_key_image">Imagen</string> + <string name="screen_key_image_clear">Borrar</string> + <string name="screen_key_layout">Disposición</string> + <string name="screen_key_layout_save">Guardar</string> <string name="osc_steam_layout_hint">Mueve, cambia de tamaño u oculta los controles táctiles de este juego; se guarda en Steam</string> <string name="mode_controller">Mando</string> <string name="mode_controller_hint">Cómo ve Steam tu mando. Se aplica en la próxima sesión.</string> @@ -1948,7 +1964,6 @@ <string name="display_filter_live">Se aplica al instante. Compartido por Steam y Escritorio.</string> <string name="display_filter_note">FSR, GSR y NIS se aplican al ampliar la imagen de la sesión. Solo nitidez también funciona sin ampliar.</string> <string name="display_sharpness">Nitidez del filtro</string> - <string name="display_frame_rate">Velocidad de fotogramas</string> <string name="display_look_filter">%1$s Cambia el escalado a %2$s.</string> <string name="display_match_screen">Igual a la pantalla (%1$d×%2$d)</string> <string name="display_follow_screen">Seguir la pantalla (cambia de tamaño al plegar o desplegar)</string> @@ -2001,6 +2016,15 @@ <string name="stores_shelf_trending">En tendencia</string> <string name="stores_play">Jugar</string> <string name="stores_install">Instalar</string> + <string name="bnet_open">Abrir Battle.net</string> + <string name="bnet_dl_starting">Iniciando el descargador de Blizzard…</string> + <string name="bnet_dl_waiting">Esperando a que se cierre Battle.net…</string> + <string name="bnet_dl_queued">Esperando a la otra descarga de Battle.net…</string> + <string name="bnet_dl_client_first">Abre Battle.net e inicia sesión una vez; después instala sus juegos desde aquí.</string> + <string name="bnet_dl_failed">El descargador de Blizzard se ha detenido: %1$s</string> + <string name="bnet_dl_agent_error">Error de Blizzard %1$s</string> + <string name="bnet_update">Actualizar</string> + <string name="bnet_store">Juegos de Blizzard</string> <string name="stores_resume_install">Reanudar instalación</string> <string name="stores_dl_interrupted">Interrumpida</string> <string name="stores_install_size">Instalar · %1$s</string> @@ -2038,6 +2062,13 @@ <string name="stores_itch_browse_failed">No se pudieron cargar los juegos de itch.io</string> <string name="stores_itch_archive">Los archivos %1$s no son compatibles</string> <string name="stores_itch_download_failed">itch.io respondió HTTP %1$d</string> + <string name="stores_itch_pick_title">Elige una versión</string> + <string name="stores_itch_pick_none">No se han encontrado descargas para este juego</string> + <string name="stores_itch_pick_failed">No se pudieron cargar las descargas de itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Abrir en itch.io</string> + <string name="stores_itch_build_linux_soon">Aún no es compatible</string> + <string name="stores_itch_no_game">No se ha encontrado este juego en itch.io</string> <string name="stores_free">Gratis</string> <string name="stores_resume">Reanudar</string> <string name="stores_refresh">Actualizar</string> @@ -3036,6 +3067,25 @@ <string name="spatial_saved_views_hint">Las vistas guardadas se pueden recalcular. Inicie una nueva calibración para capturar en el sistema de coordenadas de seguimiento actual.</string> <string name="spatial_model_checksum_error">La suma de comprobación del modelo de mano no coincide</string> <string name="spatial_opencv_load_error">OpenCV no se pudo cargar</string> + <string name="setup_group_memory">Memoria</string> + <string name="setup_clear_cached">Cerrar apps en caché antes de una sesión</string> + <string name="setup_clear_cached_hint">Al empezar una sesión, cierra las apps que Android mantiene en segundo plano para que el juego tenga más memoria. La depuración inalámbrica debe estar activada.</string> + <string name="setup_clear_cached_unpaired">DroidDeck debe estar vinculado con la depuración inalámbrica (Vincular, abajo).</string> + <string name="setup_memory_hud">Indicador de memoria</string> + <string name="setup_memory_hud_hint">Memoria y swap en uso, en la pantalla de la sesión. Avanzado lo divide entre el juego, DroidDeck, Android y la GPU.</string> + <string name="setup_memory_hud_simple">Simple</string> + <string name="setup_memory_hud_advanced">Avanzado</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">juego %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Apps en segundo plano durante una sesión</string> + <string name="setup_bg_limit_hint">Mientras una sesión está en marcha, Android mantiene en caché como máximo este número de apps y cierra las demás, para que el juego tenga su memoria. Se restablece al terminar la sesión. La depuración inalámbrica debe estar activada.</string> + <string name="setup_bg_limit_4">Como máximo 4</string> + <string name="setup_bg_limit_1">Como máximo 1</string> + <string name="setup_bg_limit_0">Ninguna</string> + <string name="setup_adb_pair">Depuración inalámbrica</string> + <string name="setup_adb_pair_hint">Vincula DroidDeck con la depuración inalámbrica de Android para las opciones de arriba. El límite de procesos secundarios sigue desactivado.</string> + <string name="setup_adb_pair_button">Vincular</string> <string name="epic_client_missing">No instalada</string> <string name="epic_client_open">Abrir</string> <string name="epic_client_install">Instalar</string> @@ -3068,6 +3118,50 @@ <string name="library_remove">Quitar de la Biblioteca</string> <string name="library_in">En la Biblioteca</string> <string name="xbox_filter_show">Mostrar</string> + <string name="itch_collections">Colecciones</string> <string name="xbox_filter_cloud">Nube</string> <string name="stores_xbox_cloud_settings">Ajustes de nube</string> + <string name="apps_search_hint">Buscar aplicaciones</string> + <string name="apps_no_match">Ninguna aplicación coincide con «%1$s».</string> + <string name="apps_add_widget">Añadir widget</string> + <string name="apps_widgets_loading">Cargando widgets…</string> + <string name="apps_widgets_none">Ninguna aplicación de este dispositivo ofrece widgets.</string> + <string name="apps_widget_wider">Más ancho</string> + <string name="apps_widget_narrower">Más estrecho</string> + <string name="apps_widget_taller">Más alto</string> + <string name="apps_widget_shorter">Más bajo</string> + <string name="apps_widget_move_earlier">Mover antes</string> + <string name="apps_widget_move_later">Mover después</string> + <string name="apps_widget_configure">Ajustes del widget</string> + <string name="apps_widget_remove">Quitar widget</string> + <string name="apps_add_to_folder">Añadir a carpeta</string> + <string name="apps_new_folder">Carpeta nueva</string> + <string name="apps_remove_from_folder">Quitar de la carpeta</string> + <string name="apps_app_info">Información de la aplicación</string> + <string name="apps_uninstall">Desinstalar</string> + <string name="apps_folder_rename">Cambiar nombre</string> + <string name="apps_folder_ungroup">Desagrupar</string> + <string name="apps_folder_default">Carpeta</string> + <string name="apps_folder_name">Nombre de la carpeta</string> + <string name="apps_filter">Mostrar</string> + <string name="apps_filter_all">Todas las aplicaciones</string> + <string name="apps_filter_games">Juegos</string> + <string name="apps_filter_downloaded">Descargadas</string> + <string name="apps_filter_system">Sistema</string> + <string name="apps_filter_hidden">Ocultas</string> + <string name="apps_hide">Ocultar</string> + <string name="apps_unhide">Mostrar en aplicaciones</string> + <string name="apps_shortcut_remove">Quitar acceso directo</string> + <string name="apps_pin_title">Añadir a Aplicaciones</string> + <string name="apps_pin_add">Añadir</string> + <string name="apps_hidden_none">No hay aplicaciones ocultas.</string> + <string name="apps_sort_name_asc">Nombre A–Z</string> + <string name="apps_sort_name_desc">Nombre Z–A</string> + <string name="apps_sort_installed">Instaladas recientemente</string> + <string name="apps_sort_updated">Actualizadas recientemente</string> + <plurals name="apps_count"> + <item quantity="one">%d aplicación</item> + <item quantity="many">%d aplicaciones</item> + <item quantity="other">%d aplicaciones</item> + </plurals> </resources> diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index f94c35c110..3ad1e92476 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Näytön kuvasuhde</string> <string name="mode_ratio_custom">Määräytyy mukautetun resoluution mukaan.</string> <string name="mode_ratio_auto">Automaattinen käyttää vähintään 16:9:ää.</string> - <string name="mode_fps">Kuvanopeusraja</string> - <string name="mode_fps_note">Rajoittaa koko istuntoa. Näyttö vaihtaa virkistystaajuuteen, jonka rajoitus jakaa tasan.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-lähtö</string> <string name="mode_hdr_unavailable">Ei käytettävissä: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam-kosketus (beta)</string> <string name="osc_style_next_session">Steamin kosketusohjaimet otetaan käyttöön seuraavassa Steam-istunnossa</string> <string name="osc_steam_layout">Steamin kosketusasettelu</string> + <string name="screen_keys">Näytön näppäimet</string> + <string name="screen_keys_add">Lisää näppäin</string> + <string name="screen_key_text">Teksti</string> + <string name="screen_key_size">Koko</string> + <string name="screen_key_opacity">Peittävyys</string> + <string name="screen_key_type_button">Näppäin</string> + <string name="screen_key_shape_trigger">Liipaisin</string> + <string name="screen_key_toggle">Vaihda</string> + <string name="screen_key_layout_export">Vie</string> + <string name="screen_key_shape_pill">Kapseli</string> + <string name="screen_key_shape_round">Pyöristetty</string> + <string name="screen_key_shape_circle">Ympyrä</string> + <string name="screen_key_shape_rect">Suorakaide</string> + <string name="screen_key_bind">Näppäin</string> + <string name="screen_key_image">Kuva</string> + <string name="screen_key_image_clear">Tyhjennä</string> + <string name="screen_key_layout">Asettelu</string> + <string name="screen_key_layout_save">Tallenna</string> <string name="osc_steam_layout_hint">Siirrä, muuta kokoa tai piilota tämän pelin kosketusohjaimet; tallennetaan Steamiin</string> <string name="mode_controller">Ohjain</string> <string name="mode_controller_hint">Miten Steam näkee ohjaimesi. Tulee voimaan seuraavassa istunnossa.</string> @@ -1925,7 +1941,6 @@ <string name="display_filter_live">Vaikuttaa välittömästi. Yhteinen Steamille ja Työpöydälle.</string> <string name="display_filter_note">FSR, GSR ja NIS vaikuttavat, kun istunnon kuvaa suurennetaan. Vain terävöinti toimii myös suurentamatta.</string> <string name="display_sharpness">Suodattimen terävyys</string> - <string name="display_frame_rate">Kuvanopeus</string> <string name="display_look_filter">%1$s Asettaa skaalauksen tilaan %2$s.</string> <string name="display_match_screen">Sovita näyttöön (%1$d×%2$d)</string> <string name="display_follow_screen">Seuraa näyttöä (koko muuttuu taitettuna tai avattuna)</string> @@ -1978,6 +1993,15 @@ <string name="stores_shelf_trending">Nousussa</string> <string name="stores_play">Pelaa</string> <string name="stores_install">Asenna</string> + <string name="bnet_open">Avaa Battle.net</string> + <string name="bnet_dl_starting">Käynnistetään Blizzardin latausohjelmaa…</string> + <string name="bnet_dl_waiting">Odotetaan Battle.netin sulkeutumista…</string> + <string name="bnet_dl_queued">Odotetaan toista Battle.net-latausta…</string> + <string name="bnet_dl_client_first">Avaa Battle.net ja kirjaudu sisään kerran, asenna sitten sen pelit täältä.</string> + <string name="bnet_dl_failed">Blizzardin latausohjelma pysähtyi: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard-virhe %1$s</string> + <string name="bnet_update">Päivitä</string> + <string name="bnet_store">Blizzardin pelit</string> <string name="stores_resume_install">Jatka asennusta</string> <string name="stores_dl_interrupted">Keskeytynyt</string> <string name="stores_install_size">Asenna · %1$s</string> @@ -2015,6 +2039,13 @@ <string name="stores_itch_browse_failed">Pelien lataaminen itch.io:sta epäonnistui</string> <string name="stores_itch_archive">%1$s-arkistot eivät ole tuettuja</string> <string name="stores_itch_download_failed">itch.io vastasi HTTP %1$d</string> + <string name="stores_itch_pick_title">Valitse versio</string> + <string name="stores_itch_pick_none">Tälle pelille ei löytynyt latauksia</string> + <string name="stores_itch_pick_failed">Latausten haku itch.iosta epäonnistui</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Avaa itch.iossa</string> + <string name="stores_itch_build_linux_soon">Ei vielä tuettu</string> + <string name="stores_itch_no_game">Peliä ei löytynyt itch.iosta</string> <string name="stores_free">Ilmainen</string> <string name="stores_resume">Jatka</string> <string name="stores_refresh">Päivitä</string> @@ -3000,6 +3031,25 @@ <string name="spatial_saved_views_hint">Tallennetut näkymät voidaan laskea uudelleen. Aloita uusi kalibrointi kaapataksesi nykyiseen seurantakoordinaattijärjestelmään.</string> <string name="spatial_model_checksum_error">Käsimallin tarkistussumman epäsuhta</string> <string name="spatial_opencv_load_error">OpenCV:tä ei voitu ladata</string> + <string name="setup_group_memory">Muisti</string> + <string name="setup_clear_cached">Sulje välimuistissa olevat sovellukset ennen istuntoa</string> + <string name="setup_clear_cached_hint">Kun istunto alkaa, DroidDeck sulkee sovellukset, joita Android pitää taustalla, jotta pelillä on enemmän muistia. Langattoman virheenkorjauksen on oltava päällä.</string> + <string name="setup_clear_cached_unpaired">Vaatii, että DroidDeck on pariutettu Langattoman virheenkorjauksen kautta (Pariuta, alla).</string> + <string name="setup_memory_hud">Muistinäyttö</string> + <string name="setup_memory_hud_hint">Käytössä oleva muisti ja swap istuntonäytöllä. Laajennettu näyttää erikseen pelin, DroidDeckin, Androidin ja GPU:n osuuden.</string> + <string name="setup_memory_hud_simple">Yksinkertainen</string> + <string name="setup_memory_hud_advanced">Laajennettu</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">peli %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Taustasovellukset istunnon aikana</string> + <string name="setup_bg_limit_hint">Istunnon aikana Android pitää välimuistissa enintään näin monta sovellusta ja sulkee loput, jotta peli saa niiden muistin. DroidDeck palauttaa rajan ennalleen, kun istunto päättyy. Langattoman virheenkorjauksen on oltava päällä.</string> + <string name="setup_bg_limit_4">Enintään 4</string> + <string name="setup_bg_limit_1">Enintään 1</string> + <string name="setup_bg_limit_0">Ei mitään</string> + <string name="setup_adb_pair">Langaton virheenkorjaus</string> + <string name="setup_adb_pair_hint">Pariuttaa DroidDeckin Androidin Langattomaan virheenkorjaukseen yllä olevia asetuksia varten. Lapsiprosessien raja pysyy pois päältä.</string> + <string name="setup_adb_pair_button">Pariuta</string> <string name="epic_client_missing">Ei asennettu</string> <string name="epic_client_open">Avaa</string> <string name="epic_client_install">Asenna</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">Poista kirjastosta</string> <string name="library_in">Kirjastossa</string> <string name="xbox_filter_show">Näytä</string> + <string name="itch_collections">Kokoelmat</string> <string name="xbox_filter_cloud">Pilvi</string> <string name="stores_xbox_cloud_settings">Pilviasetukset</string> + <string name="apps_search_hint">Hae sovelluksia</string> + <string name="apps_no_match">Mikään sovellus ei vastaa hakua ”%1$s”.</string> + <string name="apps_add_widget">Lisää widget</string> + <string name="apps_widgets_loading">Ladataan widgettejä…</string> + <string name="apps_widgets_none">Mikään tämän laitteen sovellus ei tarjoa widgettejä.</string> + <string name="apps_widget_wider">Leveämpi</string> + <string name="apps_widget_narrower">Kapeampi</string> + <string name="apps_widget_taller">Korkeampi</string> + <string name="apps_widget_shorter">Matalampi</string> + <string name="apps_widget_move_earlier">Siirrä aiemmaksi</string> + <string name="apps_widget_move_later">Siirrä myöhemmäksi</string> + <string name="apps_widget_configure">Widgetin asetukset</string> + <string name="apps_widget_remove">Poista widget</string> + <string name="apps_add_to_folder">Lisää kansioon</string> + <string name="apps_new_folder">Uusi kansio</string> + <string name="apps_remove_from_folder">Poista kansiosta</string> + <string name="apps_app_info">Sovelluksen tiedot</string> + <string name="apps_uninstall">Poista asennus</string> + <string name="apps_folder_rename">Nimeä uudelleen</string> + <string name="apps_folder_ungroup">Pura kansio</string> + <string name="apps_folder_default">Kansio</string> + <string name="apps_folder_name">Kansion nimi</string> + <string name="apps_filter">Näytä</string> + <string name="apps_filter_all">Kaikki sovellukset</string> + <string name="apps_filter_games">Pelit</string> + <string name="apps_filter_downloaded">Ladatut</string> + <string name="apps_filter_system">Järjestelmä</string> + <string name="apps_filter_hidden">Piilotetut</string> + <string name="apps_hide">Piilota</string> + <string name="apps_unhide">Näytä sovelluksissa</string> + <string name="apps_shortcut_remove">Poista pikakuvake</string> + <string name="apps_pin_title">Lisää sovelluksiin</string> + <string name="apps_pin_add">Lisää</string> + <string name="apps_hidden_none">Ei piilotettuja sovelluksia.</string> + <string name="apps_sort_name_asc">Nimi A–Ö</string> + <string name="apps_sort_name_desc">Nimi Ö–A</string> + <string name="apps_sort_installed">Äskettäin asennetut</string> + <string name="apps_sort_updated">Äskettäin päivitetyt</string> + <plurals name="apps_count"> + <item quantity="one">%d sovellus</item> + <item quantity="other">%d sovellusta</item> + </plurals> </resources> diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 6b22a92a6e..ef4fdb8f56 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Format d\'écran</string> <string name="mode_ratio_custom">Défini par la résolution personnalisée.</string> <string name="mode_ratio_auto">Le mode automatique utilise au moins 16:9.</string> - <string name="mode_fps">Limite de taux de rafraîchissement</string> - <string name="mode_fps_note">Limite le taux de rafraîchissement de toute la session. Le moniteur basculera vers un taux de rafraîchissement divisible par cette limite.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Sortie HDR10</string> <string name="mode_hdr_unavailable">Non disponible : %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Tactile Steam (bêta)</string> <string name="osc_style_next_session">Les commandes tactiles de Steam s\'activeront à la prochaine session Steam</string> <string name="osc_steam_layout">Disposition tactile Steam</string> + <string name="screen_keys">Touches à l\'écran</string> + <string name="screen_keys_add">Ajouter une touche</string> + <string name="screen_key_text">Texte</string> + <string name="screen_key_size">Taille</string> + <string name="screen_key_opacity">Opacité</string> + <string name="screen_key_type_button">Touche</string> + <string name="screen_key_shape_trigger">Gâchette</string> + <string name="screen_key_toggle">Basculer</string> + <string name="screen_key_layout_export">Exporter</string> + <string name="screen_key_shape_pill">Pilule</string> + <string name="screen_key_shape_round">Arrondi</string> + <string name="screen_key_shape_circle">Cercle</string> + <string name="screen_key_shape_rect">Rectangle</string> + <string name="screen_key_bind">Touche</string> + <string name="screen_key_image">Image</string> + <string name="screen_key_image_clear">Effacer</string> + <string name="screen_key_layout">Disposition</string> + <string name="screen_key_layout_save">Enregistrer</string> <string name="osc_steam_layout_hint">Déplacez, redimensionnez ou masquez les commandes tactiles de ce jeu ; enregistré dans Steam</string> <string name="mode_controller">Manette</string> <string name="mode_controller_hint">Comment Steam reconnaît votre manette. Prendra effet à la prochaine session.</string> @@ -1948,7 +1964,6 @@ <string name="display_filter_live">S\'applique en direct. Partagé entre Steam et le bureau.</string> <string name="display_filter_note">FSR, GSR et NIS s\'appliquent lors de l\'agrandissement de l\'image de la session. « Netteté seule » fonctionne aussi sans agrandissement.</string> <string name="display_sharpness">Netteté du filtre</string> - <string name="display_frame_rate">Fréquence d\'images</string> <string name="display_look_filter">%1$s Règle la mise à l\'échelle sur %2$s.</string> <string name="display_match_screen">Adapter à l\'écran (%1$d×%2$d)</string> <string name="display_follow_screen">Suivre l\'écran (s\'adapte au pliage et au dépliage)</string> @@ -2001,6 +2016,15 @@ <string name="stores_shelf_trending">Tendances</string> <string name="stores_play">Jouer</string> <string name="stores_install">Installer</string> + <string name="bnet_open">Ouvrir Battle.net</string> + <string name="bnet_dl_starting">Démarrage du téléchargeur de Blizzard…</string> + <string name="bnet_dl_waiting">En attente de la fermeture de Battle.net…</string> + <string name="bnet_dl_queued">En attente de l\'autre téléchargement Battle.net…</string> + <string name="bnet_dl_client_first">Ouvrez Battle.net et connectez-vous une fois, puis installez ses jeux ici.</string> + <string name="bnet_dl_failed">Le téléchargeur de Blizzard s\'est arrêté : %1$s</string> + <string name="bnet_dl_agent_error">Erreur Blizzard %1$s</string> + <string name="bnet_update">Mettre à jour</string> + <string name="bnet_store">Jeux Blizzard</string> <string name="stores_resume_install">Reprendre l\'installation</string> <string name="stores_dl_interrupted">Interrompu</string> <string name="stores_install_size">Installer · %1$s</string> @@ -2038,6 +2062,13 @@ <string name="stores_itch_browse_failed">Impossible de charger les jeux d\'itch.io</string> <string name="stores_itch_archive">Les archives %1$s ne sont pas prises en charge</string> <string name="stores_itch_download_failed">itch.io a répondu HTTP %1$d</string> + <string name="stores_itch_pick_title">Choisissez une version</string> + <string name="stores_itch_pick_none">Aucun téléchargement trouvé pour ce jeu</string> + <string name="stores_itch_pick_failed">Impossible de charger les téléchargements depuis itch.io</string> + <string name="stores_itch_build_demo">Démo</string> + <string name="stores_itch_build_open">Ouvrir sur itch.io</string> + <string name="stores_itch_build_linux_soon">Pas encore pris en charge</string> + <string name="stores_itch_no_game">Ce jeu est introuvable sur itch.io</string> <string name="stores_free">Gratuit</string> <string name="stores_resume">Reprendre</string> <string name="stores_refresh">Actualiser</string> @@ -3036,6 +3067,25 @@ <string name="spatial_saved_views_hint">Les vues enregistrées peuvent être recalculées. Démarrez un nouvel étalonnage pour capturer dans le système de coordonnées de suivi actuel.</string> <string name="spatial_model_checksum_error">Incohérence de la somme de contrôle du modèle manuel</string> <string name="spatial_opencv_load_error">OpenCV n\'a pas pu charger</string> + <string name="setup_group_memory">Mémoire</string> + <string name="setup_clear_cached">Fermer les applis en cache avant une session</string> + <string name="setup_clear_cached_hint">Au début d\'une session, ferme les applis qu\'Android garde en arrière-plan, pour laisser plus de mémoire au jeu. Le débogage sans fil doit être activé.</string> + <string name="setup_clear_cached_unpaired">DroidDeck doit être associé au débogage sans fil (Associer, ci-dessous).</string> + <string name="setup_memory_hud">Indicateur de mémoire</string> + <string name="setup_memory_hud_hint">Mémoire et swap utilisés, sur l\'écran de la session. Avancé détaille le jeu, DroidDeck, Android et le GPU.</string> + <string name="setup_memory_hud_simple">Simple</string> + <string name="setup_memory_hud_advanced">Avancé</string> + <string name="memory_hud_simple">RAM %1$s/%2$s Go · swap %3$s/%4$s Go</string> + <string name="memory_hud_split">jeu %1$s · DroidDeck %2$s · Android %3$s Go</string> + <string name="memory_hud_gpu">GPU %1$s Go</string> + <string name="setup_bg_limit">Applis en arrière-plan pendant une session</string> + <string name="setup_bg_limit_hint">Pendant une session, Android garde au plus ce nombre d\'applis en cache et ferme les autres, pour laisser leur mémoire au jeu. Rétabli à la fin de la session. Le débogage sans fil doit être activé.</string> + <string name="setup_bg_limit_4">4 au maximum</string> + <string name="setup_bg_limit_1">1 au maximum</string> + <string name="setup_bg_limit_0">Aucune</string> + <string name="setup_adb_pair">Débogage sans fil</string> + <string name="setup_adb_pair_hint">Associe DroidDeck au débogage sans fil d\'Android pour les options ci-dessus. La limite des processus enfants reste désactivée.</string> + <string name="setup_adb_pair_button">Associer</string> <string name="epic_client_missing">Non installé</string> <string name="epic_client_open">Ouvrir</string> <string name="epic_client_install">Installer</string> @@ -3068,6 +3118,50 @@ <string name="library_remove">Retirer de la Bibliothèque</string> <string name="library_in">Dans la Bibliothèque</string> <string name="xbox_filter_show">Afficher</string> + <string name="itch_collections">Collections</string> <string name="xbox_filter_cloud">Cloud</string> <string name="stores_xbox_cloud_settings">Paramètres cloud</string> + <string name="apps_search_hint">Rechercher des applications</string> + <string name="apps_no_match">Aucune application ne correspond à « %1$s ».</string> + <string name="apps_add_widget">Ajouter un widget</string> + <string name="apps_widgets_loading">Chargement des widgets…</string> + <string name="apps_widgets_none">Aucune application de cet appareil ne propose de widgets.</string> + <string name="apps_widget_wider">Plus large</string> + <string name="apps_widget_narrower">Plus étroit</string> + <string name="apps_widget_taller">Plus haut</string> + <string name="apps_widget_shorter">Moins haut</string> + <string name="apps_widget_move_earlier">Avancer</string> + <string name="apps_widget_move_later">Reculer</string> + <string name="apps_widget_configure">Paramètres du widget</string> + <string name="apps_widget_remove">Retirer le widget</string> + <string name="apps_add_to_folder">Ajouter à un dossier</string> + <string name="apps_new_folder">Nouveau dossier</string> + <string name="apps_remove_from_folder">Retirer du dossier</string> + <string name="apps_app_info">Infos sur l’application</string> + <string name="apps_uninstall">Désinstaller</string> + <string name="apps_folder_rename">Renommer</string> + <string name="apps_folder_ungroup">Dégrouper</string> + <string name="apps_folder_default">Dossier</string> + <string name="apps_folder_name">Nom du dossier</string> + <string name="apps_filter">Afficher</string> + <string name="apps_filter_all">Toutes les applications</string> + <string name="apps_filter_games">Jeux</string> + <string name="apps_filter_downloaded">Téléchargées</string> + <string name="apps_filter_system">Système</string> + <string name="apps_filter_hidden">Masquées</string> + <string name="apps_hide">Masquer</string> + <string name="apps_unhide">Afficher dans les applications</string> + <string name="apps_shortcut_remove">Retirer le raccourci</string> + <string name="apps_pin_title">Ajouter aux applications</string> + <string name="apps_pin_add">Ajouter</string> + <string name="apps_hidden_none">Aucune application masquée.</string> + <string name="apps_sort_name_asc">Nom A–Z</string> + <string name="apps_sort_name_desc">Nom Z–A</string> + <string name="apps_sort_installed">Installées récemment</string> + <string name="apps_sort_updated">Mises à jour récemment</string> + <plurals name="apps_count"> + <item quantity="one">%d application</item> + <item quantity="many">%d applications</item> + <item quantity="other">%d applications</item> + </plurals> </resources> diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index d0e385c612..ea458fa238 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">स्क्रीन रेशियो</string> <string name="mode_ratio_custom">कस्टम रिज़ॉल्यूशन से तय होता है।</string> <string name="mode_ratio_auto">ऑटो कम से कम 16:9 इस्तेमाल करता है।</string> - <string name="mode_fps">फ़्रेम सीमा</string> - <string name="mode_fps_note">पूरे सेशन को सीमित करता है। डिस्प्ले उस रिफ्रेश रेट पर चला जाता है जिसे यह सीमा बराबर बांटती है।</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 आउटपुट</string> <string name="mode_hdr_unavailable">उपलब्ध नहीं: %1$s।</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam टच (बीटा)</string> <string name="osc_style_next_session">Steam के टच कंट्रोल अगले Steam सेशन से शुरू होंगे</string> <string name="osc_steam_layout">Steam टच लेआउट</string> + <string name="screen_keys">स्क्रीन कुंजियाँ</string> + <string name="screen_keys_add">कुंजी जोड़ें</string> + <string name="screen_key_text">टेक्स्ट</string> + <string name="screen_key_size">आकार</string> + <string name="screen_key_opacity">ओपैसिटी</string> + <string name="screen_key_type_button">कुंजी</string> + <string name="screen_key_shape_trigger">ट्रिगर</string> + <string name="screen_key_toggle">टॉगल</string> + <string name="screen_key_layout_export">निर्यात</string> + <string name="screen_key_shape_pill">कैप्सूल</string> + <string name="screen_key_shape_round">गोल</string> + <string name="screen_key_shape_circle">वृत्त</string> + <string name="screen_key_shape_rect">आयत</string> + <string name="screen_key_bind">कुंजी</string> + <string name="screen_key_image">छवि</string> + <string name="screen_key_image_clear">हटाएं</string> + <string name="screen_key_layout">लेआउट</string> + <string name="screen_key_layout_save">सेव करें</string> <string name="osc_steam_layout_hint">इस गेम के टच कंट्रोल को घुमाएं, आकार बदलें या छिपाएं; Steam में सेव होता है</string> <string name="mode_controller">कंट्रोलर</string> <string name="mode_controller_hint">Steam आपके कंट्रोलर को किस तरह पहचानता है। अगले सेशन से लागू होता है।</string> @@ -1925,7 +1941,6 @@ <string name="display_filter_live">लाइव लागू होता है। Steam और डेस्कटॉप में साझा।</string> <string name="display_filter_note">FSR, GSR और NIS सेशन इमेज को बड़ा करने पर लागू होते हैं। सिर्फ़ शार्पन बिना बड़ा किए भी काम करता है।</string> <string name="display_sharpness">फ़िल्टर शार्पनेस</string> - <string name="display_frame_rate">फ़्रेम रेट</string> <string name="display_look_filter">%1$s स्केलिंग को %2$s पर सेट करता है।</string> <string name="display_match_screen">स्क्रीन से मिलाएँ (%1$d×%2$d)</string> <string name="display_follow_screen">Follow screen (खुलने या बंद होने पर आकार बदलता है)</string> @@ -1978,6 +1993,15 @@ <string name="stores_shelf_trending">ट्रेंडिंग</string> <string name="stores_play">Play</string> <string name="stores_install">इंस्टॉल करें</string> + <string name="bnet_open">Battle.net खोलें</string> + <string name="bnet_dl_starting">Blizzard का डाउनलोडर शुरू हो रहा है…</string> + <string name="bnet_dl_waiting">Battle.net के बंद होने का इंतज़ार…</string> + <string name="bnet_dl_queued">दूसरे Battle.net डाउनलोड का इंतज़ार…</string> + <string name="bnet_dl_client_first">Battle.net खोलें और एक बार साइन इन करें, फिर इसके गेम यहाँ से इंस्टॉल करें।</string> + <string name="bnet_dl_failed">Blizzard का डाउनलोडर रुक गया: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard त्रुटि %1$s</string> + <string name="bnet_update">अपडेट करें</string> + <string name="bnet_store">Blizzard के गेम</string> <string name="stores_resume_install">इंस्टॉल फिर से शुरू करें</string> <string name="stores_dl_interrupted">बाधित</string> <string name="stores_install_size">इंस्टॉल · %1$s</string> @@ -2015,6 +2039,13 @@ <string name="stores_itch_browse_failed">itch.io से गेम लोड नहीं हो सके</string> <string name="stores_itch_archive">%1$s आर्काइव समर्थित नहीं हैं</string> <string name="stores_itch_download_failed">itch.io ने HTTP %1$d लौटाया</string> + <string name="stores_itch_pick_title">संस्करण चुनें</string> + <string name="stores_itch_pick_none">इस गेम के लिए कोई डाउनलोड नहीं मिला</string> + <string name="stores_itch_pick_failed">itch.io से डाउनलोड लोड नहीं हो सके</string> + <string name="stores_itch_build_demo">डेमो</string> + <string name="stores_itch_build_open">itch.io पर खोलें</string> + <string name="stores_itch_build_linux_soon">अभी समर्थित नहीं है</string> + <string name="stores_itch_no_game">यह गेम itch.io पर नहीं मिला</string> <string name="stores_free">फ़्री</string> <string name="stores_resume">फिर से शुरू करें</string> <string name="stores_refresh">रीफ़्रेश करें</string> @@ -3000,6 +3031,25 @@ <string name="spatial_saved_views_hint">सहेजे गए दृश्यों की पुनर्गणना की जा सकती है। वर्तमान ट्रैकिंग समन्वय प्रणाली में कैप्चर करने के लिए एक नया अंशांकन प्रारंभ करें।</string> <string name="spatial_model_checksum_error">हैंड मॉडल चेकसम बेमेल</string> <string name="spatial_opencv_load_error">OpenCV लोड नहीं हो सका</string> + <string name="setup_group_memory">मेमोरी</string> + <string name="setup_clear_cached">सेशन से पहले कैश्ड ऐप बंद करें</string> + <string name="setup_clear_cached_hint">सेशन शुरू होने पर DroidDeck उन ऐप को बंद कर देता है जिन्हें Android बैकग्राउंड में रखता है, ताकि गेम को ज़्यादा मेमोरी मिले। वायरलेस डीबगिंग चालू होनी चाहिए।</string> + <string name="setup_clear_cached_unpaired">DroidDeck को वायरलेस डीबगिंग से पेयर करना ज़रूरी है (नीचे, पेयर करें)।</string> + <string name="setup_memory_hud">मेमोरी रीडआउट</string> + <string name="setup_memory_hud_hint">सेशन स्क्रीन पर इस्तेमाल हो रही मेमोरी और swap। एडवांस्ड इसे गेम, DroidDeck, Android और GPU में बांटकर दिखाता है।</string> + <string name="setup_memory_hud_simple">सिंपल</string> + <string name="setup_memory_hud_advanced">एडवांस्ड</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">गेम %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">सेशन के दौरान बैकग्राउंड ऐप</string> + <string name="setup_bg_limit_hint">सेशन चलते समय Android ज़्यादा से ज़्यादा इतने ऐप कैश में रखता है और बाकी बंद कर देता है, ताकि गेम को उनकी मेमोरी मिले। सेशन खत्म होने पर DroidDeck सीमा को पहले जैसा कर देता है। वायरलेस डीबगिंग चालू होनी चाहिए।</string> + <string name="setup_bg_limit_4">ज़्यादा से ज़्यादा 4</string> + <string name="setup_bg_limit_1">ज़्यादा से ज़्यादा 1</string> + <string name="setup_bg_limit_0">कोई नहीं</string> + <string name="setup_adb_pair">वायरलेस डीबगिंग</string> + <string name="setup_adb_pair_hint">ऊपर दिए गए विकल्पों के लिए DroidDeck को Android की वायरलेस डीबगिंग से पेयर करता है। चाइल्ड-प्रोसेस सीमा बंद ही रहती है।</string> + <string name="setup_adb_pair_button">पेयर करें</string> <string name="epic_client_missing">इंस्टॉल नहीं है</string> <string name="epic_client_open">खोलें</string> <string name="epic_client_install">इंस्टॉल करें</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">लाइब्रेरी से हटाएँ</string> <string name="library_in">लाइब्रेरी में</string> <string name="xbox_filter_show">दिखाएँ</string> + <string name="itch_collections">संग्रह</string> <string name="xbox_filter_cloud">क्लाउड</string> <string name="stores_xbox_cloud_settings">क्लाउड सेटिंग्स</string> + <string name="apps_search_hint">ऐप खोजें</string> + <string name="apps_no_match">“%1$s” से कोई ऐप मेल नहीं खाता।</string> + <string name="apps_add_widget">विजेट जोड़ें</string> + <string name="apps_widgets_loading">विजेट लोड हो रहे हैं…</string> + <string name="apps_widgets_none">इस डिवाइस पर कोई ऐप विजेट नहीं देता।</string> + <string name="apps_widget_wider">चौड़ा</string> + <string name="apps_widget_narrower">पतला</string> + <string name="apps_widget_taller">लंबा</string> + <string name="apps_widget_shorter">छोटा</string> + <string name="apps_widget_move_earlier">पहले ले जाएँ</string> + <string name="apps_widget_move_later">बाद में ले जाएँ</string> + <string name="apps_widget_configure">विजेट सेटिंग</string> + <string name="apps_widget_remove">विजेट हटाएँ</string> + <string name="apps_add_to_folder">फ़ोल्डर में जोड़ें</string> + <string name="apps_new_folder">नया फ़ोल्डर</string> + <string name="apps_remove_from_folder">फ़ोल्डर से हटाएँ</string> + <string name="apps_app_info">ऐप की जानकारी</string> + <string name="apps_uninstall">अनइंस्टॉल करें</string> + <string name="apps_folder_rename">नाम बदलें</string> + <string name="apps_folder_ungroup">समूह तोड़ें</string> + <string name="apps_folder_default">फ़ोल्डर</string> + <string name="apps_folder_name">फ़ोल्डर का नाम</string> + <string name="apps_filter">दिखाएँ</string> + <string name="apps_filter_all">सभी ऐप</string> + <string name="apps_filter_games">गेम</string> + <string name="apps_filter_downloaded">डाउनलोड किए गए</string> + <string name="apps_filter_system">सिस्टम</string> + <string name="apps_filter_hidden">छिपे हुए</string> + <string name="apps_hide">छिपाएँ</string> + <string name="apps_unhide">ऐप में दिखाएँ</string> + <string name="apps_shortcut_remove">शॉर्टकट हटाएँ</string> + <string name="apps_pin_title">ऐप में जोड़ें</string> + <string name="apps_pin_add">जोड़ें</string> + <string name="apps_hidden_none">कोई छिपा हुआ ऐप नहीं।</string> + <string name="apps_sort_name_asc">नाम A–Z</string> + <string name="apps_sort_name_desc">नाम Z–A</string> + <string name="apps_sort_installed">हाल ही में इंस्टॉल किए गए</string> + <string name="apps_sort_updated">हाल ही में अपडेट किए गए</string> + <plurals name="apps_count"> + <item quantity="one">%d ऐप</item> + <item quantity="other">%d ऐप</item> + </plurals> </resources> diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index ada8fe46c2..8d8f2774de 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Képernyőarány</string> <string name="mode_ratio_custom">Az egyéni felbontás határozza meg.</string> <string name="mode_ratio_auto">Az Automatikus legalább 16:9-et használ.</string> - <string name="mode_fps">Képkocka-korlát</string> - <string name="mode_fps_note">Korlátozza a teljes munkamenetet. A kijelző olyan frissítési frekvenciára vált, amelyet a korlát egyenlően oszt.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-kimenet</string> <string name="mode_hdr_unavailable">Nem elérhető: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam érintés (béta)</string> <string name="osc_style_next_session">A Steam érintésvezérlői a következő Steam-munkamenettől lépnek életbe</string> <string name="osc_steam_layout">Steam érintéskiosztás</string> + <string name="screen_keys">Képernyőgombok</string> + <string name="screen_keys_add">Gomb hozzáadása</string> + <string name="screen_key_text">Szöveg</string> + <string name="screen_key_size">Méret</string> + <string name="screen_key_opacity">Átlátszatlanság</string> + <string name="screen_key_type_button">Gomb</string> + <string name="screen_key_shape_trigger">Trigger</string> + <string name="screen_key_toggle">Váltás</string> + <string name="screen_key_layout_export">Exportálás</string> + <string name="screen_key_shape_pill">Kapszula</string> + <string name="screen_key_shape_round">Lekerekített</string> + <string name="screen_key_shape_circle">Kör</string> + <string name="screen_key_shape_rect">Téglalap</string> + <string name="screen_key_bind">Billentyű</string> + <string name="screen_key_image">Kép</string> + <string name="screen_key_image_clear">Törlés</string> + <string name="screen_key_layout">Elrendezés</string> + <string name="screen_key_layout_save">Mentés</string> <string name="osc_steam_layout_hint">Mozgassa, méretezze vagy rejtse el a játék érintésvezérlőit; a Steamben mentve</string> <string name="mode_controller">Kontroller</string> <string name="mode_controller_hint">Hogyan látja a Steam a kontrollerét. A következő munkamenettől érvényes.</string> @@ -1925,7 +1941,6 @@ <string name="display_filter_live">Élőben érvénybe lép. A Steam és az Asztal közösen használja.</string> <string name="display_filter_note">Az FSR, a GSR és a NIS a munkamenet képének felnagyításakor lép érvénybe. A Csak élesítés nagyítás nélkül is működik.</string> <string name="display_sharpness">Szűrőélesség</string> - <string name="display_frame_rate">Képkockasebesség</string> <string name="display_look_filter">%1$s A méretezést erre állítja: %2$s.</string> <string name="display_match_screen">Képernyőhöz illesztés (%1$d×%2$d)</string> <string name="display_follow_screen">Képernyő követése (átméreteződik össze- vagy kinyitáskor)</string> @@ -1978,6 +1993,15 @@ <string name="stores_shelf_trending">Felkapott</string> <string name="stores_play">Játék</string> <string name="stores_install">Telepítés</string> + <string name="bnet_open">Battle.net megnyitása</string> + <string name="bnet_dl_starting">A Blizzard letöltőjének indítása…</string> + <string name="bnet_dl_waiting">Várakozás a Battle.net bezárására…</string> + <string name="bnet_dl_queued">Várakozás a másik Battle.net-letöltésre…</string> + <string name="bnet_dl_client_first">Nyisd meg a Battle.netet, és jelentkezz be egyszer, majd innen telepítsd a játékait.</string> + <string name="bnet_dl_failed">A Blizzard letöltője leállt: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard-hiba: %1$s</string> + <string name="bnet_update">Frissítés</string> + <string name="bnet_store">Blizzard-játékok</string> <string name="stores_resume_install">Telepítés folytatása</string> <string name="stores_dl_interrupted">Megszakítva</string> <string name="stores_install_size">Telepítés · %1$s</string> @@ -2015,6 +2039,13 @@ <string name="stores_itch_browse_failed">Nem sikerült betölteni a játékokat az itch.io-ról</string> <string name="stores_itch_archive">A(z) %1$s archívumok nem támogatottak</string> <string name="stores_itch_download_failed">Az itch.io HTTP %1$d választ adott</string> + <string name="stores_itch_pick_title">Válassz verziót</string> + <string name="stores_itch_pick_none">Ehhez a játékhoz nem található letöltés</string> + <string name="stores_itch_pick_failed">A letöltések betöltése az itch.io-ról nem sikerült</string> + <string name="stores_itch_build_demo">Demó</string> + <string name="stores_itch_build_open">Megnyitás az itch.io-n</string> + <string name="stores_itch_build_linux_soon">Még nem támogatott</string> + <string name="stores_itch_no_game">A játék nem található az itch.io-n</string> <string name="stores_free">Ingyenes</string> <string name="stores_resume">Folytatás</string> <string name="stores_refresh">Frissítés</string> @@ -2998,6 +3029,25 @@ <string name="spatial_saved_views_hint">Az elmentett nézetek újraszámíthatók. Indítson el egy új kalibrálást, hogy rögzítse az aktuális követési koordináta-rendszerben.</string> <string name="spatial_model_checksum_error">A kézi modell ellenőrzőösszegének eltérése</string> <string name="spatial_opencv_load_error">Az OpenCV betöltése nem sikerült</string> + <string name="setup_group_memory">Memória</string> + <string name="setup_clear_cached">Gyorsítótárazott alkalmazások bezárása munkamenet előtt</string> + <string name="setup_clear_cached_hint">Munkamenet indításakor a DroidDeck bezárja azokat az alkalmazásokat, amelyeket az Android a háttérben tart, így a játéknak több memória jut. A vezeték nélküli hibakeresésnek bekapcsolva kell lennie.</string> + <string name="setup_clear_cached_unpaired">A DroidDecket párosítani kell a vezeték nélküli hibakereséssel (Párosítás, lent).</string> + <string name="setup_memory_hud">Memóriakijelzés</string> + <string name="setup_memory_hud_hint">A használt memória és swap a munkamenet képernyőjén. A Speciális nézet szétbontja a játék, a DroidDeck, az Android és a GPU között.</string> + <string name="setup_memory_hud_simple">Egyszerű</string> + <string name="setup_memory_hud_advanced">Speciális</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">játék %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Háttéralkalmazások munkamenet közben</string> + <string name="setup_bg_limit_hint">Munkamenet közben az Android legfeljebb ennyi alkalmazást tart a gyorsítótárban, a többit bezárja, így azok memóriája a játéké lesz. A munkamenet végén a DroidDeck visszaállítja a korábbi korlátot. A vezeték nélküli hibakeresésnek bekapcsolva kell lennie.</string> + <string name="setup_bg_limit_4">Legfeljebb 4</string> + <string name="setup_bg_limit_1">Legfeljebb 1</string> + <string name="setup_bg_limit_0">Nincs</string> + <string name="setup_adb_pair">Vezeték nélküli hibakeresés</string> + <string name="setup_adb_pair_hint">Párosítja a DroidDecket az Android vezeték nélküli hibakeresésével a fenti beállításokhoz. A gyermekfolyamat-korlát kikapcsolva marad.</string> + <string name="setup_adb_pair_button">Párosítás</string> <string name="glasses_3dof">3DoF virtuális képernyő</string> <string name="glasses_6dof">6DoF virtuális képernyő</string> <string name="epic_client_missing">Nincs telepítve</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">Eltávolítás a könyvtárból</string> <string name="library_in">A könyvtárban</string> <string name="xbox_filter_show">Megjelenítés</string> + <string name="itch_collections">Gyűjtemények</string> <string name="xbox_filter_cloud">Felhő</string> <string name="stores_xbox_cloud_settings">Felhőbeállítások</string> + <string name="apps_search_hint">Alkalmazások keresése</string> + <string name="apps_no_match">Egy alkalmazás sem felel meg ennek: „%1$s”.</string> + <string name="apps_add_widget">Modul hozzáadása</string> + <string name="apps_widgets_loading">Modulok betöltése…</string> + <string name="apps_widgets_none">Az eszközön egyik alkalmazás sem kínál modult.</string> + <string name="apps_widget_wider">Szélesebb</string> + <string name="apps_widget_narrower">Keskenyebb</string> + <string name="apps_widget_taller">Magasabb</string> + <string name="apps_widget_shorter">Alacsonyabb</string> + <string name="apps_widget_move_earlier">Előrébb</string> + <string name="apps_widget_move_later">Hátrébb</string> + <string name="apps_widget_configure">Modulbeállítások</string> + <string name="apps_widget_remove">Modul eltávolítása</string> + <string name="apps_add_to_folder">Hozzáadás mappához</string> + <string name="apps_new_folder">Új mappa</string> + <string name="apps_remove_from_folder">Eltávolítás a mappából</string> + <string name="apps_app_info">Alkalmazásinformáció</string> + <string name="apps_uninstall">Eltávolítás</string> + <string name="apps_folder_rename">Átnevezés</string> + <string name="apps_folder_ungroup">Szétbontás</string> + <string name="apps_folder_default">Mappa</string> + <string name="apps_folder_name">Mappa neve</string> + <string name="apps_filter">Megjelenítés</string> + <string name="apps_filter_all">Összes alkalmazás</string> + <string name="apps_filter_games">Játékok</string> + <string name="apps_filter_downloaded">Letöltött</string> + <string name="apps_filter_system">Rendszer</string> + <string name="apps_filter_hidden">Rejtett</string> + <string name="apps_hide">Elrejtés</string> + <string name="apps_unhide">Megjelenítés az alkalmazások között</string> + <string name="apps_shortcut_remove">Parancsikon eltávolítása</string> + <string name="apps_pin_title">Hozzáadás az alkalmazásokhoz</string> + <string name="apps_pin_add">Hozzáadás</string> + <string name="apps_hidden_none">Nincsenek rejtett alkalmazások.</string> + <string name="apps_sort_name_asc">Név A–Z</string> + <string name="apps_sort_name_desc">Név Z–A</string> + <string name="apps_sort_installed">Nemrég telepített</string> + <string name="apps_sort_updated">Nemrég frissített</string> + <plurals name="apps_count"> + <item quantity="one">%d alkalmazás</item> + <item quantity="other">%d alkalmazás</item> + </plurals> </resources> diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 7a93dff316..c0c4fa21fe 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Rasio layar</string> <string name="mode_ratio_custom">Ditentukan oleh resolusi khusus.</string> <string name="mode_ratio_auto">Otomatis menggunakan setidaknya 16:9.</string> - <string name="mode_fps">Batas frame rate</string> - <string name="mode_fps_note">Membatasi seluruh sesi. Tampilan beralih ke refresh rate yang habis dibagi oleh batas ini.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Output HDR10</string> <string name="mode_hdr_unavailable">Tidak tersedia: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Sentuhan Steam (beta)</string> <string name="osc_style_next_session">Kontrol sentuh Steam dimulai pada sesi Steam berikutnya</string> <string name="osc_steam_layout">Tata letak sentuh Steam</string> + <string name="screen_keys">Tombol layar</string> + <string name="screen_keys_add">Tambah tombol</string> + <string name="screen_key_text">Teks</string> + <string name="screen_key_size">Ukuran</string> + <string name="screen_key_opacity">Opasitas</string> + <string name="screen_key_type_button">Tombol</string> + <string name="screen_key_shape_trigger">Pemicu</string> + <string name="screen_key_toggle">Alih</string> + <string name="screen_key_layout_export">Ekspor</string> + <string name="screen_key_shape_pill">Kapsul</string> + <string name="screen_key_shape_round">Membulat</string> + <string name="screen_key_shape_circle">Lingkaran</string> + <string name="screen_key_shape_rect">Persegi panjang</string> + <string name="screen_key_bind">Tombol</string> + <string name="screen_key_image">Gambar</string> + <string name="screen_key_image_clear">Hapus</string> + <string name="screen_key_layout">Tata letak</string> + <string name="screen_key_layout_save">Simpan</string> <string name="osc_steam_layout_hint">Pindahkan, ubah ukuran, atau sembunyikan kontrol sentuh gim ini; disimpan ke Steam</string> <string name="mode_controller">Pengontrol</string> <string name="mode_controller_hint">Cara Steam mendeteksi pengontrol Anda. Berlaku pada sesi berikutnya.</string> @@ -1904,7 +1920,6 @@ <string name="display_filter_live">Berlaku langsung. Digunakan bersama oleh Steam dan Desktop.</string> <string name="display_filter_note">FSR, GSR, dan NIS berlaku saat memperbesar gambar sesi. Hanya penajaman juga berfungsi tanpa pembesaran.</string> <string name="display_sharpness">Ketajaman filter</string> - <string name="display_frame_rate">Frame rate</string> <string name="display_look_filter">%1$s Mengatur skala ke %2$s.</string> <string name="display_match_screen">Sesuaikan layar (%1$d×%2$d)</string> <string name="display_follow_screen">Ikuti layar (ukuran berubah saat dilipat atau dibuka)</string> @@ -1957,6 +1972,15 @@ <string name="stores_shelf_trending">Sedang tren</string> <string name="stores_play">Mainkan</string> <string name="stores_install">Instal</string> + <string name="bnet_open">Buka Battle.net</string> + <string name="bnet_dl_starting">Memulai pengunduh Blizzard…</string> + <string name="bnet_dl_waiting">Menunggu Battle.net ditutup…</string> + <string name="bnet_dl_queued">Menunggu unduhan Battle.net lainnya…</string> + <string name="bnet_dl_client_first">Buka Battle.net dan masuk sekali, lalu instal gamenya dari sini.</string> + <string name="bnet_dl_failed">Pengunduh Blizzard berhenti: %1$s</string> + <string name="bnet_dl_agent_error">Kesalahan Blizzard %1$s</string> + <string name="bnet_update">Perbarui</string> + <string name="bnet_store">Game Blizzard</string> <string name="stores_resume_install">Lanjutkan instalasi</string> <string name="stores_dl_interrupted">Terhenti</string> <string name="stores_install_size">Instal · %1$s</string> @@ -1994,6 +2018,13 @@ <string name="stores_itch_browse_failed">Tidak dapat memuat game dari itch.io</string> <string name="stores_itch_archive">Arsip %1$s tidak didukung</string> <string name="stores_itch_download_failed">itch.io menjawab HTTP %1$d</string> + <string name="stores_itch_pick_title">Pilih versi</string> + <string name="stores_itch_pick_none">Tidak ada unduhan untuk game ini</string> + <string name="stores_itch_pick_failed">Tidak dapat memuat unduhan dari itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Buka di itch.io</string> + <string name="stores_itch_build_linux_soon">Belum didukung</string> + <string name="stores_itch_no_game">Game ini tidak ditemukan di itch.io</string> <string name="stores_free">Gratis</string> <string name="stores_resume">Lanjutkan</string> <string name="stores_refresh">Segarkan</string> @@ -2553,6 +2584,21 @@ <string name="storage_safe_hint">Runtime yang tidak dipakai, sisa, log lama</string> <string name="storage_clean_up">Membersihkan…</string> <string name="storage_session_running">Hentikan sesi untuk membersihkan atau menghapus apa pun. Ukuran tetap terlihat.</string> + <string name="storage_default_group">Lokasi instalasi</string> + <string name="storage_default_title">Penyimpanan default</string> + <string name="storage_default_hint">Instalasi toko baru akan disimpan di lokasi yang dipilih. Game yang sudah ada tetap di lokasinya. Library Steam memakai pengaturannya sendiri.</string> + <string name="storage_default_ask">Tanyakan setiap kali</string> + <string name="storage_default_ask_detail">Pilih target untuk setiap instalasi</string> + <string name="storage_default_internal">Penyimpanan internal</string> + <string name="storage_default_external">Penyimpanan eksternal</string> + <string name="storage_default_external_detail">%1$s · %2$s tersedia</string> + <string name="storage_default_external_missing">Tidak terhubung</string> + <string name="storage_default_folder">Folder · %1$s</string> + <string name="storage_default_folder_free">%1$s tersedia</string> + <string name="storage_default_folder_missing">Tidak terhubung</string> + <string name="storage_default_choose_folder">Pilih folder…</string> + <string name="storage_default_choose_folder_detail">Gunakan folder apa pun di kartu SD atau drive USB</string> + <string name="storage_default_note">Game akan disimpan di folder Games di dalam lokasi yang dipilih. Game yang sudah terpasang tidak dipindahkan.</string> <string name="storage_where">Ke mana perginya</string> <string name="storage_games">Gim Steam</string> <string name="storage_game_data">Data gim</string> @@ -2975,6 +3021,25 @@ <string name="spatial_saved_views_hint">Tampilan yang disimpan dapat dihitung ulang. Mulai kalibrasi baru untuk menangkap sistem koordinat pelacakan saat ini.</string> <string name="spatial_model_checksum_error">Ketidakcocokan checksum model tangan</string> <string name="spatial_opencv_load_error">OpenCV tidak dapat memuat</string> + <string name="setup_group_memory">Memori</string> + <string name="setup_clear_cached">Tutup aplikasi dalam cache sebelum sesi</string> + <string name="setup_clear_cached_hint">Saat sesi dimulai, DroidDeck menutup aplikasi yang disimpan Android di latar belakang agar gim mendapat lebih banyak memori. Debugging nirkabel harus aktif.</string> + <string name="setup_clear_cached_unpaired">DroidDeck harus disandingkan dengan Debugging nirkabel (Pasangkan, di bawah).</string> + <string name="setup_memory_hud">Tampilan memori</string> + <string name="setup_memory_hud_hint">Memori dan swap yang digunakan, di layar sesi. Lanjutan merincinya menjadi gim, DroidDeck, Android, dan GPU.</string> + <string name="setup_memory_hud_simple">Sederhana</string> + <string name="setup_memory_hud_advanced">Lanjutan</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">gim %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Aplikasi latar belakang selama sesi</string> + <string name="setup_bg_limit_hint">Selama sesi berjalan, Android menyimpan paling banyak sejumlah ini aplikasi di cache dan menutup sisanya agar gim mendapat memorinya. DroidDeck mengembalikan batas seperti semula saat sesi berakhir. Debugging nirkabel harus aktif.</string> + <string name="setup_bg_limit_4">Paling banyak 4</string> + <string name="setup_bg_limit_1">Paling banyak 1</string> + <string name="setup_bg_limit_0">Tidak ada</string> + <string name="setup_adb_pair">Debugging nirkabel</string> + <string name="setup_adb_pair_hint">Menyandingkan DroidDeck dengan Debugging nirkabel Android untuk opsi di atas. Batas proses turunan tetap nonaktif.</string> + <string name="setup_adb_pair_button">Pasangkan</string> <string name="epic_client_missing">Belum terinstal</string> <string name="epic_client_open">Buka</string> <string name="epic_client_install">Pasang</string> @@ -3007,6 +3072,48 @@ <string name="library_remove">Hapus dari Pustaka</string> <string name="library_in">Di Pustaka</string> <string name="xbox_filter_show">Tampilkan</string> + <string name="itch_collections">Koleksi</string> <string name="xbox_filter_cloud">Cloud</string> <string name="stores_xbox_cloud_settings">Pengaturan cloud</string> + <string name="apps_search_hint">Cari aplikasi</string> + <string name="apps_no_match">Tidak ada aplikasi yang cocok dengan “%1$s”.</string> + <string name="apps_add_widget">Tambahkan widget</string> + <string name="apps_widgets_loading">Memuat widget…</string> + <string name="apps_widgets_none">Tidak ada aplikasi di perangkat ini yang menyediakan widget.</string> + <string name="apps_widget_wider">Lebih lebar</string> + <string name="apps_widget_narrower">Lebih sempit</string> + <string name="apps_widget_taller">Lebih tinggi</string> + <string name="apps_widget_shorter">Lebih pendek</string> + <string name="apps_widget_move_earlier">Pindahkan ke depan</string> + <string name="apps_widget_move_later">Pindahkan ke belakang</string> + <string name="apps_widget_configure">Setelan widget</string> + <string name="apps_widget_remove">Hapus widget</string> + <string name="apps_add_to_folder">Tambahkan ke folder</string> + <string name="apps_new_folder">Folder baru</string> + <string name="apps_remove_from_folder">Keluarkan dari folder</string> + <string name="apps_app_info">Info aplikasi</string> + <string name="apps_uninstall">Uninstal</string> + <string name="apps_folder_rename">Ganti nama</string> + <string name="apps_folder_ungroup">Pisahkan</string> + <string name="apps_folder_default">Folder</string> + <string name="apps_folder_name">Nama folder</string> + <string name="apps_filter">Tampilkan</string> + <string name="apps_filter_all">Semua aplikasi</string> + <string name="apps_filter_games">Game</string> + <string name="apps_filter_downloaded">Didownload</string> + <string name="apps_filter_system">Sistem</string> + <string name="apps_filter_hidden">Tersembunyi</string> + <string name="apps_hide">Sembunyikan</string> + <string name="apps_unhide">Tampilkan di aplikasi</string> + <string name="apps_shortcut_remove">Hapus pintasan</string> + <string name="apps_pin_title">Tambahkan ke Aplikasi</string> + <string name="apps_pin_add">Tambahkan</string> + <string name="apps_hidden_none">Tidak ada aplikasi tersembunyi.</string> + <string name="apps_sort_name_asc">Nama A–Z</string> + <string name="apps_sort_name_desc">Nama Z–A</string> + <string name="apps_sort_installed">Baru diinstal</string> + <string name="apps_sort_updated">Baru diperbarui</string> + <plurals name="apps_count"> + <item quantity="other">%d aplikasi</item> + </plurals> </resources> diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 5491ea5244..c20bdc1513 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Proporzioni schermo</string> <string name="mode_ratio_custom">Definite dalla risoluzione personalizzata.</string> <string name="mode_ratio_auto">Auto usa almeno 16:9.</string> - <string name="mode_fps">Limite frame</string> - <string name="mode_fps_note">Limita l\'intera sessione. Lo schermo passa a una frequenza di aggiornamento multipla del limite.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Uscita HDR10</string> <string name="mode_hdr_unavailable">Non disponibile: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Touch di Steam (beta)</string> <string name="osc_style_next_session">I controlli touch di Steam partono dalla prossima sessione Steam</string> <string name="osc_steam_layout">Layout touch di Steam</string> + <string name="screen_keys">Tasti a schermo</string> + <string name="screen_keys_add">Aggiungi tasto</string> + <string name="screen_key_text">Testo</string> + <string name="screen_key_size">Dimensione</string> + <string name="screen_key_opacity">Opacità</string> + <string name="screen_key_type_button">Tasto</string> + <string name="screen_key_shape_trigger">Grilletto</string> + <string name="screen_key_toggle">Attiva</string> + <string name="screen_key_layout_export">Esporta</string> + <string name="screen_key_shape_pill">Capsula</string> + <string name="screen_key_shape_round">Arrotondato</string> + <string name="screen_key_shape_circle">Cerchio</string> + <string name="screen_key_shape_rect">Rettangolo</string> + <string name="screen_key_bind">Tasto</string> + <string name="screen_key_image">Immagine</string> + <string name="screen_key_image_clear">Cancella</string> + <string name="screen_key_layout">Layout</string> + <string name="screen_key_layout_save">Salva</string> <string name="osc_steam_layout_hint">Sposta, ridimensiona o nascondi i controlli touch di questo gioco; vengono salvati su Steam</string> <string name="mode_controller">Controller</string> <string name="mode_controller_hint">Come Steam vede il tuo controller. Si applica dalla prossima sessione.</string> @@ -1938,7 +1954,6 @@ <string name="display_filter_live">Si applica subito. Condiviso da Steam e Desktop.</string> <string name="display_filter_note">FSR, GSR e NIS si applicano quando l\'immagine della sessione viene ingrandita. Solo nitidezza funziona anche senza ingrandimento.</string> <string name="display_sharpness">Nitidezza del filtro</string> - <string name="display_frame_rate">Frequenza fotogrammi</string> <string name="display_look_filter">%1$s Imposta il ridimensionamento su %2$s.</string> <string name="display_match_screen">Adatta allo schermo (%1$d×%2$d)</string> <string name="display_follow_screen">Segui lo schermo (si ridimensiona quando lo pieghi o lo apri)</string> @@ -1991,6 +2006,15 @@ <string name="stores_shelf_trending">Di tendenza</string> <string name="stores_play">Gioca</string> <string name="stores_install">Installa</string> + <string name="bnet_open">Apri Battle.net</string> + <string name="bnet_dl_starting">Avvio del downloader di Blizzard…</string> + <string name="bnet_dl_waiting">In attesa della chiusura di Battle.net…</string> + <string name="bnet_dl_queued">In attesa dell\'altro download di Battle.net…</string> + <string name="bnet_dl_client_first">Apri Battle.net ed esegui l\'accesso una volta, poi installa qui i suoi giochi.</string> + <string name="bnet_dl_failed">Il downloader di Blizzard si è fermato: %1$s</string> + <string name="bnet_dl_agent_error">Errore Blizzard %1$s</string> + <string name="bnet_update">Aggiorna</string> + <string name="bnet_store">Giochi Blizzard</string> <string name="stores_resume_install">Riprendi installazione</string> <string name="stores_dl_interrupted">Interrotto</string> <string name="stores_install_size">Installa · %1$s</string> @@ -2028,6 +2052,13 @@ <string name="stores_itch_browse_failed">Impossibile caricare i giochi da itch.io</string> <string name="stores_itch_archive">Gli archivi %1$s non sono supportati</string> <string name="stores_itch_download_failed">itch.io ha risposto HTTP %1$d</string> + <string name="stores_itch_pick_title">Scegli una versione</string> + <string name="stores_itch_pick_none">Nessun download trovato per questo gioco</string> + <string name="stores_itch_pick_failed">Impossibile caricare i download da itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Apri su itch.io</string> + <string name="stores_itch_build_linux_soon">Non ancora supportato</string> + <string name="stores_itch_no_game">Gioco non trovato su itch.io</string> <string name="stores_free">Gratis</string> <string name="stores_resume">Riprendi</string> <string name="stores_refresh">Aggiorna</string> @@ -3032,6 +3063,25 @@ <string name="spatial_saved_views_hint">Le visualizzazioni salvate possono essere ricalcolate. Avvia una nuova calibrazione per acquisire il sistema di coordinate di tracciamento corrente.</string> <string name="spatial_model_checksum_error">Mancata corrispondenza del checksum del modello di mano</string> <string name="spatial_opencv_load_error">Impossibile caricare OpenCV</string> + <string name="setup_group_memory">Memoria</string> + <string name="setup_clear_cached">Chiudi le app in cache prima di una sessione</string> + <string name="setup_clear_cached_hint">All\'avvio di una sessione, DroidDeck chiude le app che Android tiene parcheggiate in background, così il gioco ha più memoria. Il Debug wireless deve essere attivo.</string> + <string name="setup_clear_cached_unpaired">Richiede DroidDeck accoppiato con il Debug wireless (Accoppia, qui sotto).</string> + <string name="setup_memory_hud">Indicatore della memoria</string> + <string name="setup_memory_hud_hint">Memoria e swap in uso, nella schermata della sessione. Avanzato la suddivide tra gioco, DroidDeck, Android e GPU.</string> + <string name="setup_memory_hud_simple">Semplice</string> + <string name="setup_memory_hud_advanced">Avanzato</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">gioco %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">App in background durante una sessione</string> + <string name="setup_bg_limit_hint">Durante una sessione, Android tiene in cache al massimo questo numero di app e chiude le altre, così il gioco ha la loro memoria. Al termine della sessione DroidDeck ripristina il limite precedente. Il Debug wireless deve essere attivo.</string> + <string name="setup_bg_limit_4">Al massimo 4</string> + <string name="setup_bg_limit_1">Al massimo 1</string> + <string name="setup_bg_limit_0">Nessuna</string> + <string name="setup_adb_pair">Debug wireless</string> + <string name="setup_adb_pair_hint">Accoppia DroidDeck al Debug wireless di Android per le opzioni qui sopra. Il limite dei processi figlio resta disattivato.</string> + <string name="setup_adb_pair_button">Accoppia</string> <string name="setup_glasses_scope">Le impostazioni dello schermo e del tracciamento della testa sono condivise tra menu, giochi e sessioni desktop di DroidDeck.</string> <string name="spatial_print_job">DroidDeck ChArUco 30 mm</string> <string name="epic_client_missing">Non installata</string> @@ -3066,6 +3116,50 @@ <string name="library_remove">Rimuovi dalla Libreria</string> <string name="library_in">Nella Libreria</string> <string name="xbox_filter_show">Mostra</string> + <string name="itch_collections">Raccolte</string> <string name="xbox_filter_cloud">Cloud</string> <string name="stores_xbox_cloud_settings">Impostazioni cloud</string> + <string name="apps_search_hint">Cerca app</string> + <string name="apps_no_match">Nessuna app corrisponde a «%1$s».</string> + <string name="apps_add_widget">Aggiungi widget</string> + <string name="apps_widgets_loading">Caricamento widget…</string> + <string name="apps_widgets_none">Nessuna app su questo dispositivo offre widget.</string> + <string name="apps_widget_wider">Più largo</string> + <string name="apps_widget_narrower">Più stretto</string> + <string name="apps_widget_taller">Più alto</string> + <string name="apps_widget_shorter">Più basso</string> + <string name="apps_widget_move_earlier">Sposta prima</string> + <string name="apps_widget_move_later">Sposta dopo</string> + <string name="apps_widget_configure">Impostazioni widget</string> + <string name="apps_widget_remove">Rimuovi widget</string> + <string name="apps_add_to_folder">Aggiungi a cartella</string> + <string name="apps_new_folder">Nuova cartella</string> + <string name="apps_remove_from_folder">Rimuovi dalla cartella</string> + <string name="apps_app_info">Info app</string> + <string name="apps_uninstall">Disinstalla</string> + <string name="apps_folder_rename">Rinomina</string> + <string name="apps_folder_ungroup">Separa</string> + <string name="apps_folder_default">Cartella</string> + <string name="apps_folder_name">Nome cartella</string> + <string name="apps_filter">Mostra</string> + <string name="apps_filter_all">Tutte le app</string> + <string name="apps_filter_games">Giochi</string> + <string name="apps_filter_downloaded">Scaricate</string> + <string name="apps_filter_system">Sistema</string> + <string name="apps_filter_hidden">Nascoste</string> + <string name="apps_hide">Nascondi</string> + <string name="apps_unhide">Mostra nelle app</string> + <string name="apps_shortcut_remove">Rimuovi scorciatoia</string> + <string name="apps_pin_title">Aggiungi ad App</string> + <string name="apps_pin_add">Aggiungi</string> + <string name="apps_hidden_none">Nessuna app nascosta.</string> + <string name="apps_sort_name_asc">Nome A–Z</string> + <string name="apps_sort_name_desc">Nome Z–A</string> + <string name="apps_sort_installed">Installate di recente</string> + <string name="apps_sort_updated">Aggiornate di recente</string> + <plurals name="apps_count"> + <item quantity="one">%d app</item> + <item quantity="many">%d app</item> + <item quantity="other">%d app</item> + </plurals> </resources> diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index f0df57bd02..87a910caef 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">画面比率</string> <string name="mode_ratio_custom">カスタム解像度で設定されます。</string> <string name="mode_ratio_auto">自動モードでは少なくとも16:9を使用します。</string> - <string name="mode_fps">フレームレート制限</string> - <string name="mode_fps_note">セッション全体のフレームレートを制限します。モニターはこの上限で割り切れるリフレッシュレートに切り替わります。</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10出力</string> <string name="mode_hdr_unavailable">利用不可:%1$s。</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steamタッチ(ベータ版)</string> <string name="osc_style_next_session">Steamのタッチコントロールは次回のSteamセッションから有効になります</string> <string name="osc_steam_layout">Steamタッチのレイアウト</string> + <string name="screen_keys">画面のキー</string> + <string name="screen_keys_add">キーを追加</string> + <string name="screen_key_text">テキスト</string> + <string name="screen_key_size">サイズ</string> + <string name="screen_key_opacity">不透明度</string> + <string name="screen_key_type_button">キー</string> + <string name="screen_key_shape_trigger">トリガー</string> + <string name="screen_key_toggle">トグル</string> + <string name="screen_key_layout_export">エクスポート</string> + <string name="screen_key_shape_pill">カプセル</string> + <string name="screen_key_shape_round">角丸</string> + <string name="screen_key_shape_circle">円</string> + <string name="screen_key_shape_rect">四角</string> + <string name="screen_key_bind">キー</string> + <string name="screen_key_image">画像</string> + <string name="screen_key_image_clear">クリア</string> + <string name="screen_key_layout">レイアウト</string> + <string name="screen_key_layout_save">保存</string> <string name="osc_steam_layout_hint">このゲームのタッチコントロールを移動、サイズ変更、非表示にします。Steamに保存されます</string> <string name="mode_controller">コントローラー</string> <string name="mode_controller_hint">Steamがコントローラーを認識する方法。次回のセッションで有効になります。</string> @@ -1906,7 +1922,6 @@ <string name="display_filter_live">すぐに反映されます。Steamとデスクトップで共有されます。</string> <string name="display_filter_note">FSR、GSR、NISはセッションの映像を拡大するときに機能します。「シャープのみ」は拡大しなくても機能します。</string> <string name="display_sharpness">フィルターのシャープネス</string> - <string name="display_frame_rate">フレームレート</string> <string name="display_look_filter">%1$s スケーリングを%2$sに設定します。</string> <string name="display_match_screen">画面に合わせる(%1$d×%2$d)</string> <string name="display_follow_screen">画面に追従(開閉時にサイズを変更)</string> @@ -1959,6 +1974,15 @@ <string name="stores_shelf_trending">トレンド</string> <string name="stores_play">プレイ</string> <string name="stores_install">インストール</string> + <string name="bnet_open">Battle.net を開く</string> + <string name="bnet_dl_starting">Blizzard のダウンローダーを起動しています…</string> + <string name="bnet_dl_waiting">Battle.net が閉じるのを待っています…</string> + <string name="bnet_dl_queued">もう一つの Battle.net のダウンロードを待っています…</string> + <string name="bnet_dl_client_first">Battle.net を開いて一度サインインしてから、ここでゲームをインストールしてください。</string> + <string name="bnet_dl_failed">Blizzard のダウンローダーが停止しました: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard エラー %1$s</string> + <string name="bnet_update">アップデート</string> + <string name="bnet_store">Blizzard のゲーム</string> <string name="stores_resume_install">インストールを再開</string> <string name="stores_dl_interrupted">中断</string> <string name="stores_install_size">インストール · %1$s</string> @@ -1996,6 +2020,13 @@ <string name="stores_itch_browse_failed">itch.io のゲームを読み込めませんでした</string> <string name="stores_itch_archive">%1$s 形式のアーカイブには対応していません</string> <string name="stores_itch_download_failed">itch.io が HTTP %1$d を返しました</string> + <string name="stores_itch_pick_title">バージョンを選択</string> + <string name="stores_itch_pick_none">このゲームのダウンロードが見つかりません</string> + <string name="stores_itch_pick_failed">itch.io からダウンロードを読み込めませんでした</string> + <string name="stores_itch_build_demo">デモ</string> + <string name="stores_itch_build_open">itch.io で開く</string> + <string name="stores_itch_build_linux_soon">まだ対応していません</string> + <string name="stores_itch_no_game">itch.io でこのゲームが見つかりませんでした</string> <string name="stores_free">無料</string> <string name="stores_resume">再開</string> <string name="stores_refresh">更新</string> @@ -2977,6 +3008,25 @@ <string name="spatial_opencv_load_error">OpenCVをロードできませんでした</string> <string name="tracking_recovery_look">明るい部屋でゆっくりと周囲を見回してください。\nトラッキングカメラを遮るものがないように、家具などの見えるものに顔を向けてください。</string> <string name="spatial_print_job">DroidDeck ChArUco 30 mm</string> + <string name="setup_group_memory">メモリ</string> + <string name="setup_clear_cached">セッション前にキャッシュ済みアプリを閉じる</string> + <string name="setup_clear_cached_hint">セッションの開始時に、Android がバックグラウンドに保持しているアプリを閉じ、ゲームに使えるメモリを増やします。ワイヤレスデバッグをオンにする必要があります。</string> + <string name="setup_clear_cached_unpaired">DroidDeck をワイヤレスデバッグとペア設定する必要があります(下の「ペア設定」)。</string> + <string name="setup_memory_hud">メモリ表示</string> + <string name="setup_memory_hud_hint">使用中のメモリとスワップをセッション画面に表示します。詳細設定では、ゲーム、DroidDeck、Android、GPU に分けて表示します。</string> + <string name="setup_memory_hud_simple">シンプル</string> + <string name="setup_memory_hud_advanced">詳細設定</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · スワップ %3$s/%4$s GB</string> + <string name="memory_hud_split">ゲーム %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">セッション中のバックグラウンドアプリ</string> + <string name="setup_bg_limit_hint">セッション中、Android がキャッシュに保持するアプリをこの数までに抑え、残りを閉じてゲームにメモリを回します。セッション終了時に元に戻します。ワイヤレスデバッグをオンにする必要があります。</string> + <string name="setup_bg_limit_4">最大 4 個</string> + <string name="setup_bg_limit_1">最大 1 個</string> + <string name="setup_bg_limit_0">なし</string> + <string name="setup_adb_pair">ワイヤレスデバッグ</string> + <string name="setup_adb_pair_hint">上のオプションのために DroidDeck を Android のワイヤレスデバッグとペア設定します。子プロセス制限はオフのままです。</string> + <string name="setup_adb_pair_button">ペア設定</string> <string name="epic_client_missing">未インストール</string> <string name="epic_client_open">開く</string> <string name="epic_client_install">インストール</string> @@ -3009,6 +3059,48 @@ <string name="library_remove">ライブラリから削除</string> <string name="library_in">ライブラリにあります</string> <string name="xbox_filter_show">表示</string> + <string name="itch_collections">コレクション</string> <string name="xbox_filter_cloud">クラウド</string> <string name="stores_xbox_cloud_settings">クラウド設定</string> + <string name="apps_search_hint">アプリを検索</string> + <string name="apps_no_match">「%1$s」に一致するアプリはありません。</string> + <string name="apps_add_widget">ウィジェットを追加</string> + <string name="apps_widgets_loading">ウィジェットを読み込み中…</string> + <string name="apps_widgets_none">このデバイスにはウィジェットを提供するアプリがありません。</string> + <string name="apps_widget_wider">幅を広く</string> + <string name="apps_widget_narrower">幅を狭く</string> + <string name="apps_widget_taller">高く</string> + <string name="apps_widget_shorter">低く</string> + <string name="apps_widget_move_earlier">前へ移動</string> + <string name="apps_widget_move_later">後ろへ移動</string> + <string name="apps_widget_configure">ウィジェットの設定</string> + <string name="apps_widget_remove">ウィジェットを削除</string> + <string name="apps_add_to_folder">フォルダに追加</string> + <string name="apps_new_folder">新しいフォルダ</string> + <string name="apps_remove_from_folder">フォルダから削除</string> + <string name="apps_app_info">アプリ情報</string> + <string name="apps_uninstall">アンインストール</string> + <string name="apps_folder_rename">名前を変更</string> + <string name="apps_folder_ungroup">グループを解除</string> + <string name="apps_folder_default">フォルダ</string> + <string name="apps_folder_name">フォルダ名</string> + <string name="apps_filter">表示</string> + <string name="apps_filter_all">すべてのアプリ</string> + <string name="apps_filter_games">ゲーム</string> + <string name="apps_filter_downloaded">ダウンロード済み</string> + <string name="apps_filter_system">システム</string> + <string name="apps_filter_hidden">非表示</string> + <string name="apps_hide">非表示にする</string> + <string name="apps_unhide">アプリに表示</string> + <string name="apps_shortcut_remove">ショートカットを削除</string> + <string name="apps_pin_title">アプリに追加</string> + <string name="apps_pin_add">追加</string> + <string name="apps_hidden_none">非表示のアプリはありません。</string> + <string name="apps_sort_name_asc">名前 A–Z</string> + <string name="apps_sort_name_desc">名前 Z–A</string> + <string name="apps_sort_installed">最近インストール</string> + <string name="apps_sort_updated">最近更新</string> + <plurals name="apps_count"> + <item quantity="other">%d 個のアプリ</item> + </plurals> </resources> diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 94e23ea9dd..10d6fd46dc 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">화면 비율</string> <string name="mode_ratio_custom">사용자 정의 해상도로 설정됩니다.</string> <string name="mode_ratio_auto">자동 모드에서는 최소 16:9를 사용합니다.</string> - <string name="mode_fps">프레임 속도 제한</string> - <string name="mode_fps_note">세션 전체의 프레임 속도를 제한합니다. 모니터는 이 상한으로 나누어떨어지는 주사율로 전환됩니다.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 출력</string> <string name="mode_hdr_unavailable">사용 불가: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam 터치(베타)</string> <string name="osc_style_next_session">Steam 터치 컨트롤은 다음 Steam 세션부터 적용됩니다</string> <string name="osc_steam_layout">Steam 터치 레이아웃</string> + <string name="screen_keys">화면 키</string> + <string name="screen_keys_add">키 추가</string> + <string name="screen_key_text">텍스트</string> + <string name="screen_key_size">크기</string> + <string name="screen_key_opacity">불투명도</string> + <string name="screen_key_type_button">키</string> + <string name="screen_key_shape_trigger">트리거</string> + <string name="screen_key_toggle">토글</string> + <string name="screen_key_layout_export">내보내기</string> + <string name="screen_key_shape_pill">캡슐</string> + <string name="screen_key_shape_round">둥근 모서리</string> + <string name="screen_key_shape_circle">원</string> + <string name="screen_key_shape_rect">사각형</string> + <string name="screen_key_bind">키</string> + <string name="screen_key_image">이미지</string> + <string name="screen_key_image_clear">지우기</string> + <string name="screen_key_layout">레이아웃</string> + <string name="screen_key_layout_save">저장</string> <string name="osc_steam_layout_hint">이 게임의 터치 컨트롤을 옮기거나 크기를 바꾸거나 숨깁니다. Steam에 저장됩니다</string> <string name="mode_controller">컨트롤러</string> <string name="mode_controller_hint">Steam이 컨트롤러를 인식하는 방식입니다. 다음 세션에 적용됩니다.</string> @@ -1906,7 +1922,6 @@ <string name="display_filter_live">즉시 적용됩니다. Steam과 데스크톱에서 공유됩니다.</string> <string name="display_filter_note">FSR, GSR, NIS는 세션 이미지를 확대할 때 적용됩니다. 샤프닝 전용은 확대하지 않아도 작동합니다.</string> <string name="display_sharpness">필터 선명도</string> - <string name="display_frame_rate">프레임 속도</string> <string name="display_look_filter">%1$s 스케일링을 %2$s(으)로 설정합니다.</string> <string name="display_match_screen">화면에 맞춤(%1$d×%2$d)</string> <string name="display_follow_screen">화면 따라가기(접거나 펼치면 크기 변경)</string> @@ -1959,6 +1974,15 @@ <string name="stores_shelf_trending">인기 급상승</string> <string name="stores_play">플레이</string> <string name="stores_install">설치</string> + <string name="bnet_open">Battle.net 열기</string> + <string name="bnet_dl_starting">Blizzard 다운로더를 시작하는 중…</string> + <string name="bnet_dl_waiting">Battle.net이 닫히기를 기다리는 중…</string> + <string name="bnet_dl_queued">다른 Battle.net 다운로드를 기다리는 중…</string> + <string name="bnet_dl_client_first">Battle.net을 열고 한 번 로그인한 다음 여기에서 게임을 설치하세요.</string> + <string name="bnet_dl_failed">Blizzard 다운로더가 중지됨: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard 오류 %1$s</string> + <string name="bnet_update">업데이트</string> + <string name="bnet_store">Blizzard 게임</string> <string name="stores_resume_install">설치 재개</string> <string name="stores_dl_interrupted">중단됨</string> <string name="stores_install_size">설치 · %1$s</string> @@ -1996,6 +2020,13 @@ <string name="stores_itch_browse_failed">itch.io에서 게임을 불러오지 못했습니다</string> <string name="stores_itch_archive">%1$s 압축 파일은 지원하지 않습니다</string> <string name="stores_itch_download_failed">itch.io가 HTTP %1$d을(를) 반환했습니다</string> + <string name="stores_itch_pick_title">버전 선택</string> + <string name="stores_itch_pick_none">이 게임의 다운로드를 찾을 수 없습니다</string> + <string name="stores_itch_pick_failed">itch.io에서 다운로드를 불러오지 못했습니다</string> + <string name="stores_itch_build_demo">데모</string> + <string name="stores_itch_build_open">itch.io에서 열기</string> + <string name="stores_itch_build_linux_soon">아직 지원되지 않음</string> + <string name="stores_itch_no_game">itch.io에서 이 게임을 찾을 수 없습니다</string> <string name="stores_free">무료</string> <string name="stores_resume">재개</string> <string name="stores_refresh">새로 고침</string> @@ -2977,6 +3008,25 @@ <string name="spatial_distance_result">카메라 측정 %1$s; 선택한 거리 %2$s. %3$s</string> <string name="spatial_wait_previews">보정을 시작하기 전에 두 카메라 미리보기를 모두 기다리세요.</string> <string name="spatial_saved_views_hint">저장된 뷰는 다시 계산될 수 있습니다. 현재 추적 좌표계에서 캡처하려면 새 보정을 시작하세요.</string> + <string name="setup_group_memory">메모리</string> + <string name="setup_clear_cached">세션 전에 캐시된 앱 닫기</string> + <string name="setup_clear_cached_hint">세션이 시작될 때 Android가 백그라운드에 보관 중인 앱을 닫아 게임이 메모리를 더 쓸 수 있게 합니다. 무선 디버깅이 켜져 있어야 합니다.</string> + <string name="setup_clear_cached_unpaired">DroidDeck을 무선 디버깅과 페어링해야 합니다(아래 페어링).</string> + <string name="setup_memory_hud">메모리 표시</string> + <string name="setup_memory_hud_hint">사용 중인 메모리와 스왑을 세션 화면에 표시합니다. 고급에서는 게임, DroidDeck, Android, GPU로 나눠 보여 줍니다.</string> + <string name="setup_memory_hud_simple">간단</string> + <string name="setup_memory_hud_advanced">고급</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · 스왑 %3$s/%4$s GB</string> + <string name="memory_hud_split">게임 %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">세션 중 백그라운드 앱</string> + <string name="setup_bg_limit_hint">세션이 실행되는 동안 Android가 캐시에 두는 앱을 이 개수까지로 제한하고 나머지는 닫아 게임이 그 메모리를 쓰게 합니다. 세션이 끝나면 원래대로 돌아갑니다. 무선 디버깅이 켜져 있어야 합니다.</string> + <string name="setup_bg_limit_4">최대 4개</string> + <string name="setup_bg_limit_1">최대 1개</string> + <string name="setup_bg_limit_0">없음</string> + <string name="setup_adb_pair">무선 디버깅</string> + <string name="setup_adb_pair_hint">위 옵션을 위해 DroidDeck을 Android 무선 디버깅과 페어링합니다. 하위 프로세스 제한은 꺼진 상태로 유지됩니다.</string> + <string name="setup_adb_pair_button">페어링</string> <string name="epic_client_missing">설치되지 않음</string> <string name="epic_client_open">열기</string> <string name="epic_client_install">설치</string> @@ -3009,6 +3059,48 @@ <string name="library_remove">라이브러리에서 제거</string> <string name="library_in">라이브러리에 있음</string> <string name="xbox_filter_show">표시</string> + <string name="itch_collections">컬렉션</string> <string name="xbox_filter_cloud">클라우드</string> <string name="stores_xbox_cloud_settings">클라우드 설정</string> + <string name="apps_search_hint">앱 검색</string> + <string name="apps_no_match">‘%1$s’와(과) 일치하는 앱이 없습니다.</string> + <string name="apps_add_widget">위젯 추가</string> + <string name="apps_widgets_loading">위젯 불러오는 중…</string> + <string name="apps_widgets_none">이 기기에 위젯을 제공하는 앱이 없습니다.</string> + <string name="apps_widget_wider">더 넓게</string> + <string name="apps_widget_narrower">더 좁게</string> + <string name="apps_widget_taller">더 높게</string> + <string name="apps_widget_shorter">더 낮게</string> + <string name="apps_widget_move_earlier">앞으로 이동</string> + <string name="apps_widget_move_later">뒤로 이동</string> + <string name="apps_widget_configure">위젯 설정</string> + <string name="apps_widget_remove">위젯 삭제</string> + <string name="apps_add_to_folder">폴더에 추가</string> + <string name="apps_new_folder">새 폴더</string> + <string name="apps_remove_from_folder">폴더에서 제거</string> + <string name="apps_app_info">앱 정보</string> + <string name="apps_uninstall">제거</string> + <string name="apps_folder_rename">이름 변경</string> + <string name="apps_folder_ungroup">그룹 해제</string> + <string name="apps_folder_default">폴더</string> + <string name="apps_folder_name">폴더 이름</string> + <string name="apps_filter">표시</string> + <string name="apps_filter_all">모든 앱</string> + <string name="apps_filter_games">게임</string> + <string name="apps_filter_downloaded">다운로드됨</string> + <string name="apps_filter_system">시스템</string> + <string name="apps_filter_hidden">숨김</string> + <string name="apps_hide">숨기기</string> + <string name="apps_unhide">앱에 표시</string> + <string name="apps_shortcut_remove">바로가기 삭제</string> + <string name="apps_pin_title">앱에 추가</string> + <string name="apps_pin_add">추가</string> + <string name="apps_hidden_none">숨긴 앱이 없습니다.</string> + <string name="apps_sort_name_asc">이름 A–Z</string> + <string name="apps_sort_name_desc">이름 Z–A</string> + <string name="apps_sort_installed">최근 설치</string> + <string name="apps_sort_updated">최근 업데이트</string> + <plurals name="apps_count"> + <item quantity="other">앱 %d개</item> + </plurals> </resources> diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 9ba680d285..098f2429a2 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Nisbah skrin</string> <string name="mode_ratio_custom">Ditetapkan oleh resolusi tersuai.</string> <string name="mode_ratio_auto">Auto menggunakan sekurang-kurangnya 16:9.</string> - <string name="mode_fps">Had bingkai</string> - <string name="mode_fps_note">Mengehadkan keseluruhan sesi. Paparan beralih kepada kadar penyegaran yang boleh dibahagi sama rata dengan had ini.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Output HDR10</string> <string name="mode_hdr_unavailable">Tidak tersedia: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Sentuhan Steam (beta)</string> <string name="osc_style_next_session">Kawalan sentuh Steam bermula pada sesi Steam seterusnya</string> <string name="osc_steam_layout">Susun atur sentuh Steam</string> + <string name="screen_keys">Kekunci skrin</string> + <string name="screen_keys_add">Tambah kekunci</string> + <string name="screen_key_text">Teks</string> + <string name="screen_key_size">Saiz</string> + <string name="screen_key_opacity">Kelegapan</string> + <string name="screen_key_type_button">Kekunci</string> + <string name="screen_key_shape_trigger">Pencetus</string> + <string name="screen_key_toggle">Togol</string> + <string name="screen_key_layout_export">Eksport</string> + <string name="screen_key_shape_pill">Kapsul</string> + <string name="screen_key_shape_round">Bulat</string> + <string name="screen_key_shape_circle">Bulatan</string> + <string name="screen_key_shape_rect">Segi empat</string> + <string name="screen_key_bind">Kekunci</string> + <string name="screen_key_image">Imej</string> + <string name="screen_key_image_clear">Kosongkan</string> + <string name="screen_key_layout">Susun atur</string> + <string name="screen_key_layout_save">Simpan</string> <string name="osc_steam_layout_hint">Gerakkan, ubah saiz atau sembunyikan kawalan sentuh permainan ini; disimpan ke Steam</string> <string name="mode_controller">Pengawal</string> <string name="mode_controller_hint">Cara Steam mengesan pengawal anda. Berkuat kuasa pada sesi seterusnya.</string> @@ -1904,7 +1920,6 @@ <string name="display_filter_live">Berkuat kuasa secara langsung. Dikongsi oleh Steam dan Desktop.</string> <string name="display_filter_note">FSR, GSR dan NIS berkuat kuasa semasa membesarkan imej sesi. Ketajaman sahaja juga berfungsi tanpa pembesaran.</string> <string name="display_sharpness">Ketajaman penapis</string> - <string name="display_frame_rate">Kadar bingkai</string> <string name="display_look_filter">%1$s Menetapkan penskalaan ke %2$s.</string> <string name="display_match_screen">Sepadan skrin (%1$d×%2$d)</string> <string name="display_follow_screen">Ikut skrin (mengubah saiz apabila dilipat atau dibuka)</string> @@ -1957,6 +1972,15 @@ <string name="stores_shelf_trending">Tular</string> <string name="stores_play">Main</string> <string name="stores_install">Pasang</string> + <string name="bnet_open">Buka Battle.net</string> + <string name="bnet_dl_starting">Memulakan pemuat turun Blizzard…</string> + <string name="bnet_dl_waiting">Menunggu Battle.net ditutup…</string> + <string name="bnet_dl_queued">Menunggu muat turun Battle.net yang lain…</string> + <string name="bnet_dl_client_first">Buka Battle.net dan log masuk sekali, kemudian pasang permainannya dari sini.</string> + <string name="bnet_dl_failed">Pemuat turun Blizzard berhenti: %1$s</string> + <string name="bnet_dl_agent_error">Ralat Blizzard %1$s</string> + <string name="bnet_update">Kemas kini</string> + <string name="bnet_store">Permainan Blizzard</string> <string name="stores_resume_install">Sambung pemasangan</string> <string name="stores_dl_interrupted">Terganggu</string> <string name="stores_install_size">Pasang · %1$s</string> @@ -1994,6 +2018,13 @@ <string name="stores_itch_browse_failed">Tidak dapat memuatkan permainan daripada itch.io</string> <string name="stores_itch_archive">Arkib %1$s tidak disokong</string> <string name="stores_itch_download_failed">itch.io menjawab HTTP %1$d</string> + <string name="stores_itch_pick_title">Pilih versi</string> + <string name="stores_itch_pick_none">Tiada muat turun ditemui untuk permainan ini</string> + <string name="stores_itch_pick_failed">Tidak dapat memuatkan muat turun daripada itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Buka di itch.io</string> + <string name="stores_itch_build_linux_soon">Belum disokong</string> + <string name="stores_itch_no_game">Permainan ini tidak ditemui di itch.io</string> <string name="stores_free">Percuma</string> <string name="stores_resume">Sambung</string> <string name="stores_refresh">Segar semula</string> @@ -2973,6 +3004,25 @@ <string name="spatial_saved_views_hint">Pandangan yang disimpan boleh dikira semula. Mulakan penentukuran baharu untuk ditangkap dalam sistem koordinat penjejakan semasa.</string> <string name="spatial_model_checksum_error">Ketakpadanan checksum model tangan</string> <string name="spatial_opencv_load_error">OpenCV tidak dapat dimuatkan</string> + <string name="setup_group_memory">Memori</string> + <string name="setup_clear_cached">Tutup apl dalam cache sebelum sesi</string> + <string name="setup_clear_cached_hint">Apabila sesi bermula, DroidDeck menutup apl yang disimpan Android di latar belakang supaya permainan mendapat lebih banyak memori. Debugging Wayarles mesti dihidupkan.</string> + <string name="setup_clear_cached_unpaired">Memerlukan DroidDeck digandingkan dengan Debugging Wayarles (Gandingkan, di bawah).</string> + <string name="setup_memory_hud">Paparan memori</string> + <string name="setup_memory_hud_hint">Memori dan swap yang digunakan, pada skrin sesi. Lanjutan memecahkannya kepada permainan, DroidDeck, Android dan GPU.</string> + <string name="setup_memory_hud_simple">Ringkas</string> + <string name="setup_memory_hud_advanced">Lanjutan</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">permainan %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Apl latar belakang semasa sesi</string> + <string name="setup_bg_limit_hint">Semasa sesi berjalan, Android menyimpan paling banyak bilangan apl ini dalam cache dan menutup selebihnya, supaya permainan mendapat memori apl tersebut. DroidDeck memulihkan had seperti asal apabila sesi tamat. Debugging Wayarles mesti dihidupkan.</string> + <string name="setup_bg_limit_4">Paling banyak 4</string> + <string name="setup_bg_limit_1">Paling banyak 1</string> + <string name="setup_bg_limit_0">Tiada</string> + <string name="setup_adb_pair">Debugging Wayarles</string> + <string name="setup_adb_pair_hint">Menggandingkan DroidDeck dengan Debugging Wayarles Android untuk pilihan di atas. Had proses anak kekal dimatikan.</string> + <string name="setup_adb_pair_button">Gandingkan</string> <string name="spatial_print_title">DroidDeck - Penentukuran Luma Ultra</string> <string name="spatial_base_loaded">Penentukuran asas Luma Ultra dimuatkan</string> <string name="epic_client_missing">Belum dipasang</string> @@ -3007,6 +3057,48 @@ <string name="library_remove">Alih keluar dari Pustaka</string> <string name="library_in">Dalam Pustaka</string> <string name="xbox_filter_show">Tunjukkan</string> + <string name="itch_collections">Koleksi</string> <string name="xbox_filter_cloud">Awan</string> <string name="stores_xbox_cloud_settings">Tetapan awan</string> + <string name="apps_search_hint">Cari apl</string> + <string name="apps_no_match">Tiada apl sepadan dengan “%1$s”.</string> + <string name="apps_add_widget">Tambah widget</string> + <string name="apps_widgets_loading">Memuatkan widget…</string> + <string name="apps_widgets_none">Tiada apl pada peranti ini yang menawarkan widget.</string> + <string name="apps_widget_wider">Lebih lebar</string> + <string name="apps_widget_narrower">Lebih sempit</string> + <string name="apps_widget_taller">Lebih tinggi</string> + <string name="apps_widget_shorter">Lebih rendah</string> + <string name="apps_widget_move_earlier">Alih ke depan</string> + <string name="apps_widget_move_later">Alih ke belakang</string> + <string name="apps_widget_configure">Tetapan widget</string> + <string name="apps_widget_remove">Alih keluar widget</string> + <string name="apps_add_to_folder">Tambah pada folder</string> + <string name="apps_new_folder">Folder baharu</string> + <string name="apps_remove_from_folder">Alih keluar daripada folder</string> + <string name="apps_app_info">Maklumat apl</string> + <string name="apps_uninstall">Nyahpasang</string> + <string name="apps_folder_rename">Namakan semula</string> + <string name="apps_folder_ungroup">Leraikan</string> + <string name="apps_folder_default">Folder</string> + <string name="apps_folder_name">Nama folder</string> + <string name="apps_filter">Tunjukkan</string> + <string name="apps_filter_all">Semua apl</string> + <string name="apps_filter_games">Permainan</string> + <string name="apps_filter_downloaded">Dimuat turun</string> + <string name="apps_filter_system">Sistem</string> + <string name="apps_filter_hidden">Tersembunyi</string> + <string name="apps_hide">Sembunyikan</string> + <string name="apps_unhide">Tunjukkan dalam apl</string> + <string name="apps_shortcut_remove">Alih keluar pintasan</string> + <string name="apps_pin_title">Tambah pada Apl</string> + <string name="apps_pin_add">Tambah</string> + <string name="apps_hidden_none">Tiada apl tersembunyi.</string> + <string name="apps_sort_name_asc">Nama A–Z</string> + <string name="apps_sort_name_desc">Nama Z–A</string> + <string name="apps_sort_installed">Dipasang baru-baru ini</string> + <string name="apps_sort_updated">Dikemas kini baru-baru ini</string> + <plurals name="apps_count"> + <item quantity="other">%d apl</item> + </plurals> </resources> diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index cd62ccb5ac..e95a57c22b 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Skjermforhold</string> <string name="mode_ratio_custom">Angis av den egendefinerte oppløsningen.</string> <string name="mode_ratio_auto">Auto bruker minst 16:9.</string> - <string name="mode_fps">Bildefrekvensgrense</string> - <string name="mode_fps_note">Begrenser hele sesjonen. Skjermen bytter til en oppdateringsfrekvens som grensen går opp i.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-utgang</string> <string name="mode_hdr_unavailable">Ikke tilgjengelig: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam-berøring (beta)</string> <string name="osc_style_next_session">Steams berøringskontroller starter med neste Steam-sesjon</string> <string name="osc_steam_layout">Steam-berøringslayout</string> + <string name="screen_keys">Skjermtaster</string> + <string name="screen_keys_add">Legg til tast</string> + <string name="screen_key_text">Tekst</string> + <string name="screen_key_size">Størrelse</string> + <string name="screen_key_opacity">Opasitet</string> + <string name="screen_key_type_button">Tast</string> + <string name="screen_key_shape_trigger">Utløser</string> + <string name="screen_key_toggle">Veksle</string> + <string name="screen_key_layout_export">Eksporter</string> + <string name="screen_key_shape_pill">Kapsel</string> + <string name="screen_key_shape_round">Avrundet</string> + <string name="screen_key_shape_circle">Sirkel</string> + <string name="screen_key_shape_rect">Rektangel</string> + <string name="screen_key_bind">Tast</string> + <string name="screen_key_image">Bilde</string> + <string name="screen_key_image_clear">Fjern</string> + <string name="screen_key_layout">Oppsett</string> + <string name="screen_key_layout_save">Lagre</string> <string name="osc_steam_layout_hint">Flytt, endre størrelse på eller skjul dette spillets berøringskontroller; lagres til Steam</string> <string name="mode_controller">Kontroller</string> <string name="mode_controller_hint">Hvordan Steam ser kontrolleren din. Gjelder fra neste sesjon.</string> @@ -1925,7 +1941,6 @@ <string name="display_filter_live">Gjelder live. Delt av Steam og Skrivebord.</string> <string name="display_filter_note">FSR, GSR og NIS gjelder ved forstørring av sesjonsbildet. Bare skarphet fungerer også uten forstørring.</string> <string name="display_sharpness">Filterskarphet</string> - <string name="display_frame_rate">Bildefrekvens</string> <string name="display_look_filter">%1$s Setter skalering til %2$s.</string> <string name="display_match_screen">Tilpass skjerm (%1$d×%2$d)</string> <string name="display_follow_screen">Følg skjermen (endrer størrelse ved sammenslåing eller utbretting)</string> @@ -1978,6 +1993,15 @@ <string name="stores_shelf_trending">Trender</string> <string name="stores_play">Spill</string> <string name="stores_install">Installer</string> + <string name="bnet_open">Åpne Battle.net</string> + <string name="bnet_dl_starting">Starter Blizzards nedlaster…</string> + <string name="bnet_dl_waiting">Venter på at Battle.net lukkes…</string> + <string name="bnet_dl_queued">Venter på den andre Battle.net-nedlastingen…</string> + <string name="bnet_dl_client_first">Åpne Battle.net og logg på én gang, og installer deretter spillene herfra.</string> + <string name="bnet_dl_failed">Blizzards nedlaster stoppet: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard-feil %1$s</string> + <string name="bnet_update">Oppdater</string> + <string name="bnet_store">Blizzard-spill</string> <string name="stores_resume_install">Gjenoppta installasjon</string> <string name="stores_dl_interrupted">Avbrutt</string> <string name="stores_install_size">Installer · %1$s</string> @@ -2015,6 +2039,13 @@ <string name="stores_itch_browse_failed">Kunne ikke laste spill fra itch.io</string> <string name="stores_itch_archive">%1$s-arkiver støttes ikke</string> <string name="stores_itch_download_failed">itch.io svarte HTTP %1$d</string> + <string name="stores_itch_pick_title">Velg en versjon</string> + <string name="stores_itch_pick_none">Fant ingen nedlastinger for dette spillet</string> + <string name="stores_itch_pick_failed">Kunne ikke laste inn nedlastingene fra itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Åpne på itch.io</string> + <string name="stores_itch_build_linux_soon">Støttes ikke ennå</string> + <string name="stores_itch_no_game">Fant ikke dette spillet på itch.io</string> <string name="stores_free">Gratis</string> <string name="stores_resume">Gjenoppta</string> <string name="stores_refresh">Oppdater</string> @@ -3000,6 +3031,25 @@ <string name="spatial_saved_views_hint">Lagrede visninger kan beregnes på nytt. Start en ny kalibrering for å fange opp i gjeldende sporingskoordinatsystem.</string> <string name="spatial_model_checksum_error">Uoverensstemmelse med håndmodellsjekksum</string> <string name="spatial_opencv_load_error">OpenCV kunne ikke laste</string> + <string name="setup_group_memory">Minne</string> + <string name="setup_clear_cached">Lukk bufrede apper før en sesjon</string> + <string name="setup_clear_cached_hint">Når en sesjon starter, lukker DroidDeck appene Android holder parkert i bakgrunnen, slik at spillet får mer minne. Trådløs feilsøking må være på.</string> + <string name="setup_clear_cached_unpaired">Krever at DroidDeck er paret med trådløs feilsøking (Koble sammen, nedenfor).</string> + <string name="setup_memory_hud">Minnevisning</string> + <string name="setup_memory_hud_hint">Minne og swap i bruk, på sesjonsskjermen. Avansert fordeler det på spillet, DroidDeck, Android og GPU-en.</string> + <string name="setup_memory_hud_simple">Enkel</string> + <string name="setup_memory_hud_advanced">Avansert</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">spill %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Bakgrunnsapper under en sesjon</string> + <string name="setup_bg_limit_hint">Mens en sesjon kjører, holder Android høyst så mange apper i hurtiglageret og lukker resten, slik at spillet får minnet deres. DroidDeck setter grensen tilbake slik den var når sesjonen avsluttes. Trådløs feilsøking må være på.</string> + <string name="setup_bg_limit_4">Høyst 4</string> + <string name="setup_bg_limit_1">Høyst 1</string> + <string name="setup_bg_limit_0">Ingen</string> + <string name="setup_adb_pair">Trådløs feilsøking</string> + <string name="setup_adb_pair_hint">Kobler DroidDeck sammen med trådløs feilsøking i Android for valgene ovenfor. Grensen for underprosesser forblir av.</string> + <string name="setup_adb_pair_button">Koble sammen</string> <string name="epic_client_missing">Ikke installert</string> <string name="epic_client_open">Åpne</string> <string name="epic_client_install">Installer</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">Fjern fra Bibliotek</string> <string name="library_in">I Bibliotek</string> <string name="xbox_filter_show">Vis</string> + <string name="itch_collections">Samlinger</string> <string name="xbox_filter_cloud">Sky</string> <string name="stores_xbox_cloud_settings">Skyinnstillinger</string> + <string name="apps_search_hint">Søk i apper</string> + <string name="apps_no_match">Ingen apper samsvarer med «%1$s».</string> + <string name="apps_add_widget">Legg til modul</string> + <string name="apps_widgets_loading">Laster inn moduler…</string> + <string name="apps_widgets_none">Ingen apper på enheten tilbyr moduler.</string> + <string name="apps_widget_wider">Bredere</string> + <string name="apps_widget_narrower">Smalere</string> + <string name="apps_widget_taller">Høyere</string> + <string name="apps_widget_shorter">Lavere</string> + <string name="apps_widget_move_earlier">Flytt tidligere</string> + <string name="apps_widget_move_later">Flytt senere</string> + <string name="apps_widget_configure">Modulinnstillinger</string> + <string name="apps_widget_remove">Fjern modul</string> + <string name="apps_add_to_folder">Legg til i mappe</string> + <string name="apps_new_folder">Ny mappe</string> + <string name="apps_remove_from_folder">Fjern fra mappe</string> + <string name="apps_app_info">Appinfo</string> + <string name="apps_uninstall">Avinstaller</string> + <string name="apps_folder_rename">Gi nytt navn</string> + <string name="apps_folder_ungroup">Løs opp</string> + <string name="apps_folder_default">Mappe</string> + <string name="apps_folder_name">Mappenavn</string> + <string name="apps_filter">Vis</string> + <string name="apps_filter_all">Alle apper</string> + <string name="apps_filter_games">Spill</string> + <string name="apps_filter_downloaded">Nedlastet</string> + <string name="apps_filter_system">System</string> + <string name="apps_filter_hidden">Skjult</string> + <string name="apps_hide">Skjul</string> + <string name="apps_unhide">Vis i apper</string> + <string name="apps_shortcut_remove">Fjern snarvei</string> + <string name="apps_pin_title">Legg til i Apper</string> + <string name="apps_pin_add">Legg til</string> + <string name="apps_hidden_none">Ingen skjulte apper.</string> + <string name="apps_sort_name_asc">Navn A–Å</string> + <string name="apps_sort_name_desc">Navn Å–A</string> + <string name="apps_sort_installed">Nylig installert</string> + <string name="apps_sort_updated">Nylig oppdatert</string> + <plurals name="apps_count"> + <item quantity="one">%d app</item> + <item quantity="other">%d apper</item> + </plurals> </resources> diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index c83f80dff1..5cd7fdf36d 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Beeldverhouding</string> <string name="mode_ratio_custom">Ingesteld door de aangepaste resolutie.</string> <string name="mode_ratio_auto">Automatisch gebruikt minimaal 16:9.</string> - <string name="mode_fps">Framelimiet</string> - <string name="mode_fps_note">Begrenst de hele sessie. Het scherm schakelt naar een verversingssnelheid die een veelvoud van de limiet is.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-uitvoer</string> <string name="mode_hdr_unavailable">Niet beschikbaar: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam-aanraakbediening (bèta)</string> <string name="osc_style_next_session">De aanraakbediening van Steam start bij de volgende Steam-sessie</string> <string name="osc_steam_layout">Steam-aanraakindeling</string> + <string name="screen_keys">Schermtoetsen</string> + <string name="screen_keys_add">Toets toevoegen</string> + <string name="screen_key_text">Tekst</string> + <string name="screen_key_size">Grootte</string> + <string name="screen_key_opacity">Transparantie</string> + <string name="screen_key_type_button">Toets</string> + <string name="screen_key_shape_trigger">Trigger</string> + <string name="screen_key_toggle">Schakelen</string> + <string name="screen_key_layout_export">Exporteren</string> + <string name="screen_key_shape_pill">Capsule</string> + <string name="screen_key_shape_round">Afgerond</string> + <string name="screen_key_shape_circle">Cirkel</string> + <string name="screen_key_shape_rect">Rechthoek</string> + <string name="screen_key_bind">Toets</string> + <string name="screen_key_image">Afbeelding</string> + <string name="screen_key_image_clear">Wissen</string> + <string name="screen_key_layout">Indeling</string> + <string name="screen_key_layout_save">Opslaan</string> <string name="osc_steam_layout_hint">Verplaats, schaal of verberg de aanraakbediening van deze game; opgeslagen in Steam</string> <string name="mode_controller">Controller</string> <string name="mode_controller_hint">Hoe Steam je controller ziet. Geldt vanaf de volgende sessie.</string> @@ -1925,7 +1941,6 @@ <string name="display_filter_live">Wordt direct toegepast. Gedeeld door Steam en Desktop.</string> <string name="display_filter_note">FSR, GSR en NIS worden toegepast bij het vergroten van het sessiebeeld. Alleen verscherpen werkt ook zonder vergroting.</string> <string name="display_sharpness">Filterscherpte</string> - <string name="display_frame_rate">Framerate</string> <string name="display_look_filter">%1$s Zet schaling op %2$s.</string> <string name="display_match_screen">Schermformaat (%1$d×%2$d)</string> <string name="display_follow_screen">Scherm volgen (past formaat aan bij vouwen of uitvouwen)</string> @@ -1978,6 +1993,15 @@ <string name="stores_shelf_trending">Populair</string> <string name="stores_play">Spelen</string> <string name="stores_install">Installeren</string> + <string name="bnet_open">Battle.net openen</string> + <string name="bnet_dl_starting">Blizzards downloader wordt gestart…</string> + <string name="bnet_dl_waiting">Wachten tot Battle.net is gesloten…</string> + <string name="bnet_dl_queued">Wachten op de andere Battle.net-download…</string> + <string name="bnet_dl_client_first">Open Battle.net en meld je één keer aan, installeer daarna de games hier.</string> + <string name="bnet_dl_failed">Blizzards downloader is gestopt: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard-fout %1$s</string> + <string name="bnet_update">Bijwerken</string> + <string name="bnet_store">Blizzard-games</string> <string name="stores_resume_install">Installatie hervatten</string> <string name="stores_dl_interrupted">Onderbroken</string> <string name="stores_install_size">Installeren · %1$s</string> @@ -2015,6 +2039,13 @@ <string name="stores_itch_browse_failed">Games van itch.io konden niet worden geladen</string> <string name="stores_itch_archive">%1$s-archieven worden niet ondersteund</string> <string name="stores_itch_download_failed">itch.io antwoordde HTTP %1$d</string> + <string name="stores_itch_pick_title">Kies een versie</string> + <string name="stores_itch_pick_none">Geen downloads gevonden voor deze game</string> + <string name="stores_itch_pick_failed">De downloads van itch.io konden niet worden geladen</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Openen op itch.io</string> + <string name="stores_itch_build_linux_soon">Nog niet ondersteund</string> + <string name="stores_itch_no_game">Deze game is niet gevonden op itch.io</string> <string name="stores_free">Gratis</string> <string name="stores_resume">Hervatten</string> <string name="stores_refresh">Vernieuwen</string> @@ -2998,6 +3029,25 @@ <string name="spatial_saved_views_hint">Opgeslagen weergaven kunnen opnieuw worden berekend. Start een nieuwe kalibratie om vast te leggen in het huidige volgcoördinatensysteem.</string> <string name="spatial_model_checksum_error">Controlesom handmodel komt niet overeen</string> <string name="spatial_opencv_load_error">OpenCV kon niet laden</string> + <string name="setup_group_memory">Geheugen</string> + <string name="setup_clear_cached">Gecachete apps sluiten voor een sessie</string> + <string name="setup_clear_cached_hint">Als een sessie start, sluit DroidDeck de apps die Android op de achtergrond geparkeerd houdt, zodat de game meer geheugen heeft. Draadloos debuggen moet aanstaan.</string> + <string name="setup_clear_cached_unpaired">DroidDeck moet gekoppeld zijn met Draadloos debuggen (Koppelen, hieronder).</string> + <string name="setup_memory_hud">Geheugenweergave</string> + <string name="setup_memory_hud_hint">Gebruikt geheugen en swap, op het sessiescherm. Geavanceerd verdeelt het over de game, DroidDeck, Android en de GPU.</string> + <string name="setup_memory_hud_simple">Eenvoudig</string> + <string name="setup_memory_hud_advanced">Geavanceerd</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">game %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Achtergrond-apps tijdens een sessie</string> + <string name="setup_bg_limit_hint">Tijdens een sessie houdt Android maximaal dit aantal apps in de cache en sluit de rest, zodat de game hun geheugen krijgt. DroidDeck zet de limiet terug zoals hij was als de sessie eindigt. Draadloos debuggen moet aanstaan.</string> + <string name="setup_bg_limit_4">Maximaal 4</string> + <string name="setup_bg_limit_1">Maximaal 1</string> + <string name="setup_bg_limit_0">Geen</string> + <string name="setup_adb_pair">Draadloos debuggen</string> + <string name="setup_adb_pair_hint">Koppelt DroidDeck aan Draadloos debuggen van Android voor de opties hierboven. De limiet voor subprocessen blijft uit.</string> + <string name="setup_adb_pair_button">Koppelen</string> <string name="glasses_6dof">Virtueel scherm met 6DoF</string> <string name="spatial_print_job">DroidDeck ChArUco 30 mm</string> <string name="epic_client_missing">Niet geïnstalleerd</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">Verwijderen uit Bibliotheek</string> <string name="library_in">In Bibliotheek</string> <string name="xbox_filter_show">Weergeven</string> + <string name="itch_collections">Collecties</string> <string name="xbox_filter_cloud">Cloud</string> <string name="stores_xbox_cloud_settings">Cloudinstellingen</string> + <string name="apps_search_hint">Apps zoeken</string> + <string name="apps_no_match">Geen apps gevonden voor ‘%1$s’.</string> + <string name="apps_add_widget">Widget toevoegen</string> + <string name="apps_widgets_loading">Widgets laden…</string> + <string name="apps_widgets_none">Geen enkele app op dit apparaat biedt widgets.</string> + <string name="apps_widget_wider">Breder</string> + <string name="apps_widget_narrower">Smaller</string> + <string name="apps_widget_taller">Hoger</string> + <string name="apps_widget_shorter">Lager</string> + <string name="apps_widget_move_earlier">Naar voren</string> + <string name="apps_widget_move_later">Naar achteren</string> + <string name="apps_widget_configure">Widgetinstellingen</string> + <string name="apps_widget_remove">Widget verwijderen</string> + <string name="apps_add_to_folder">Toevoegen aan map</string> + <string name="apps_new_folder">Nieuwe map</string> + <string name="apps_remove_from_folder">Uit map verwijderen</string> + <string name="apps_app_info">App-info</string> + <string name="apps_uninstall">Verwijderen</string> + <string name="apps_folder_rename">Naam wijzigen</string> + <string name="apps_folder_ungroup">Opheffen</string> + <string name="apps_folder_default">Map</string> + <string name="apps_folder_name">Mapnaam</string> + <string name="apps_filter">Tonen</string> + <string name="apps_filter_all">Alle apps</string> + <string name="apps_filter_games">Games</string> + <string name="apps_filter_downloaded">Gedownload</string> + <string name="apps_filter_system">Systeem</string> + <string name="apps_filter_hidden">Verborgen</string> + <string name="apps_hide">Verbergen</string> + <string name="apps_unhide">Tonen in apps</string> + <string name="apps_shortcut_remove">Snelkoppeling verwijderen</string> + <string name="apps_pin_title">Toevoegen aan Apps</string> + <string name="apps_pin_add">Toevoegen</string> + <string name="apps_hidden_none">Geen verborgen apps.</string> + <string name="apps_sort_name_asc">Naam A–Z</string> + <string name="apps_sort_name_desc">Naam Z–A</string> + <string name="apps_sort_installed">Recent geïnstalleerd</string> + <string name="apps_sort_updated">Recent bijgewerkt</string> + <plurals name="apps_count"> + <item quantity="one">%d app</item> + <item quantity="other">%d apps</item> + </plurals> </resources> diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index f1234702a1..4e87191fe1 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Proporcje ekranu</string> <string name="mode_ratio_custom">Ustalane przez własną rozdzielczość.</string> <string name="mode_ratio_auto">Auto używa co najmniej 16:9.</string> - <string name="mode_fps">Limit klatek</string> - <string name="mode_fps_note">Ogranicza całą sesję. Wyświetlacz przełącza się na częstotliwość odświeżania będącą wielokrotnością limitu.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Wyjście HDR10</string> <string name="mode_hdr_unavailable">Niedostępne: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Dotyk Steam (beta)</string> <string name="osc_style_next_session">Sterowanie dotykowe Steam zacznie działać od następnej sesji Steam</string> <string name="osc_steam_layout">Układ dotykowy Steam</string> + <string name="screen_keys">Klawisze ekranu</string> + <string name="screen_keys_add">Dodaj klawisz</string> + <string name="screen_key_text">Tekst</string> + <string name="screen_key_size">Rozmiar</string> + <string name="screen_key_opacity">Przezroczystość</string> + <string name="screen_key_type_button">Klawisz</string> + <string name="screen_key_shape_trigger">Spust</string> + <string name="screen_key_toggle">Przełącznik</string> + <string name="screen_key_layout_export">Eksportuj</string> + <string name="screen_key_shape_pill">Kapsułka</string> + <string name="screen_key_shape_round">Zaokrąglony</string> + <string name="screen_key_shape_circle">Koło</string> + <string name="screen_key_shape_rect">Prostokąt</string> + <string name="screen_key_bind">Klawisz</string> + <string name="screen_key_image">Obraz</string> + <string name="screen_key_image_clear">Wyczyść</string> + <string name="screen_key_layout">Układ</string> + <string name="screen_key_layout_save">Zapisz</string> <string name="osc_steam_layout_hint">Przesuwaj, zmieniaj rozmiar lub ukrywaj sterowanie dotykowe tej gry; zapisywane w Steam</string> <string name="mode_controller">Kontroler</string> <string name="mode_controller_hint">Jak Steam widzi Twój kontroler. Działa od następnej sesji.</string> @@ -1967,7 +1983,6 @@ <string name="display_filter_live">Działa od razu. Wspólny dla Steam i Pulpitu.</string> <string name="display_filter_note">FSR, GSR i NIS działają przy powiększaniu obrazu sesji. „Tylko wyostrzanie” działa też bez powiększania.</string> <string name="display_sharpness">Ostrość filtra</string> - <string name="display_frame_rate">Liczba klatek</string> <string name="display_look_filter">%1$s Ustawia skalowanie na %2$s.</string> <string name="display_match_screen">Dopasuj do ekranu (%1$d×%2$d)</string> <string name="display_follow_screen">Dopasuj do ekranu (zmienia rozmiar po złożeniu lub rozłożeniu)</string> @@ -2020,6 +2035,15 @@ <string name="stores_shelf_trending">Popularne</string> <string name="stores_play">Graj</string> <string name="stores_install">Zainstaluj</string> + <string name="bnet_open">Otwórz Battle.net</string> + <string name="bnet_dl_starting">Uruchamianie programu pobierającego Blizzarda…</string> + <string name="bnet_dl_waiting">Oczekiwanie na zamknięcie Battle.net…</string> + <string name="bnet_dl_queued">Oczekiwanie na drugie pobieranie z Battle.net…</string> + <string name="bnet_dl_client_first">Otwórz Battle.net i zaloguj się raz, a potem instaluj jego gry tutaj.</string> + <string name="bnet_dl_failed">Program pobierający Blizzarda zatrzymał się: %1$s</string> + <string name="bnet_dl_agent_error">Błąd Blizzarda %1$s</string> + <string name="bnet_update">Aktualizuj</string> + <string name="bnet_store">Gry Blizzarda</string> <string name="stores_resume_install">Wznów instalację</string> <string name="stores_dl_interrupted">Przerwano</string> <string name="stores_install_size">Instalacja · %1$s</string> @@ -2057,6 +2081,13 @@ <string name="stores_itch_browse_failed">Nie udało się wczytać gier z itch.io</string> <string name="stores_itch_archive">Archiwa %1$s nie są obsługiwane</string> <string name="stores_itch_download_failed">itch.io odpowiedziało HTTP %1$d</string> + <string name="stores_itch_pick_title">Wybierz wersję</string> + <string name="stores_itch_pick_none">Nie znaleziono plików do pobrania dla tej gry</string> + <string name="stores_itch_pick_failed">Nie udało się wczytać plików z itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Otwórz w itch.io</string> + <string name="stores_itch_build_linux_soon">Jeszcze nieobsługiwane</string> + <string name="stores_itch_no_game">Nie znaleziono tej gry w itch.io</string> <string name="stores_free">Bezpłatna</string> <string name="stores_resume">Wznów</string> <string name="stores_refresh">Odśwież</string> @@ -3067,6 +3098,25 @@ <string name="spatial_saved_views_hint">Zapisane widoki można przeliczyć. Rozpocznij nową kalibrację, aby przechwycić bieżący układ współrzędnych śledzenia.</string> <string name="spatial_model_checksum_error">Niezgodność sumy kontrolnej modelu ręki</string> <string name="spatial_opencv_load_error">Nie można załadować OpenCV</string> + <string name="setup_group_memory">Pamięć</string> + <string name="setup_clear_cached">Zamykaj aplikacje z pamięci podręcznej przed sesją</string> + <string name="setup_clear_cached_hint">Na początku sesji DroidDeck zamyka aplikacje, które Android trzyma w tle, aby gra miała więcej pamięci. Debugowanie bezprzewodowe musi być włączone.</string> + <string name="setup_clear_cached_unpaired">Wymaga sparowania DroidDeck przez Debugowanie bezprzewodowe (Sparuj, poniżej).</string> + <string name="setup_memory_hud">Wskaźnik pamięci</string> + <string name="setup_memory_hud_hint">Używana pamięć i swap na ekranie sesji. Tryb Zaawansowany dzieli ją na grę, DroidDeck, Androida i GPU.</string> + <string name="setup_memory_hud_simple">Prosty</string> + <string name="setup_memory_hud_advanced">Zaawansowany</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">gra %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Aplikacje w tle podczas sesji</string> + <string name="setup_bg_limit_hint">W trakcie sesji Android trzyma w pamięci podręcznej najwyżej tyle aplikacji, a resztę zamyka, aby gra dostała ich pamięć. Po zakończeniu sesji DroidDeck przywraca poprzedni limit. Debugowanie bezprzewodowe musi być włączone.</string> + <string name="setup_bg_limit_4">Najwyżej 4</string> + <string name="setup_bg_limit_1">Najwyżej 1</string> + <string name="setup_bg_limit_0">Brak</string> + <string name="setup_adb_pair">Debugowanie bezprzewodowe</string> + <string name="setup_adb_pair_hint">Paruje DroidDeck z Debugowaniem bezprzewodowym Androida na potrzeby opcji powyżej. Limit procesów podrzędnych pozostaje wyłączony.</string> + <string name="setup_adb_pair_button">Sparuj</string> <string name="spatial_gpu_hint">Domyślnie używany jest CPU. GPU jest opcją eksperymentalną i może powodować ponowne uruchamianie SteamVR. Wybór jest resetowany po ponownym uruchomieniu śledzenia.</string> <string name="spatial_print_job">DroidDeck ChArUco 30 mm</string> <string name="spatial_connect_hint">Podłącz Luma Ultra i włącz śledzenie pozycji.</string> @@ -3103,6 +3153,51 @@ <string name="library_remove">Usuń z biblioteki</string> <string name="library_in">W bibliotece</string> <string name="xbox_filter_show">Pokaż</string> + <string name="itch_collections">Kolekcje</string> <string name="xbox_filter_cloud">Chmura</string> <string name="stores_xbox_cloud_settings">Ustawienia chmury</string> + <string name="apps_search_hint">Szukaj aplikacji</string> + <string name="apps_no_match">Żadna aplikacja nie pasuje do „%1$s”.</string> + <string name="apps_add_widget">Dodaj widżet</string> + <string name="apps_widgets_loading">Wczytywanie widżetów…</string> + <string name="apps_widgets_none">Żadna aplikacja na tym urządzeniu nie oferuje widżetów.</string> + <string name="apps_widget_wider">Szerszy</string> + <string name="apps_widget_narrower">Węższy</string> + <string name="apps_widget_taller">Wyższy</string> + <string name="apps_widget_shorter">Niższy</string> + <string name="apps_widget_move_earlier">Przesuń wcześniej</string> + <string name="apps_widget_move_later">Przesuń później</string> + <string name="apps_widget_configure">Ustawienia widżetu</string> + <string name="apps_widget_remove">Usuń widżet</string> + <string name="apps_add_to_folder">Dodaj do folderu</string> + <string name="apps_new_folder">Nowy folder</string> + <string name="apps_remove_from_folder">Usuń z folderu</string> + <string name="apps_app_info">Informacje o aplikacji</string> + <string name="apps_uninstall">Odinstaluj</string> + <string name="apps_folder_rename">Zmień nazwę</string> + <string name="apps_folder_ungroup">Rozgrupuj</string> + <string name="apps_folder_default">Folder</string> + <string name="apps_folder_name">Nazwa folderu</string> + <string name="apps_filter">Pokaż</string> + <string name="apps_filter_all">Wszystkie aplikacje</string> + <string name="apps_filter_games">Gry</string> + <string name="apps_filter_downloaded">Pobrane</string> + <string name="apps_filter_system">Systemowe</string> + <string name="apps_filter_hidden">Ukryte</string> + <string name="apps_hide">Ukryj</string> + <string name="apps_unhide">Pokaż w aplikacjach</string> + <string name="apps_shortcut_remove">Usuń skrót</string> + <string name="apps_pin_title">Dodaj do aplikacji</string> + <string name="apps_pin_add">Dodaj</string> + <string name="apps_hidden_none">Brak ukrytych aplikacji.</string> + <string name="apps_sort_name_asc">Nazwa A–Z</string> + <string name="apps_sort_name_desc">Nazwa Z–A</string> + <string name="apps_sort_installed">Ostatnio zainstalowane</string> + <string name="apps_sort_updated">Ostatnio zaktualizowane</string> + <plurals name="apps_count"> + <item quantity="one">%d aplikacja</item> + <item quantity="few">%d aplikacje</item> + <item quantity="many">%d aplikacji</item> + <item quantity="other">%d aplikacji</item> + </plurals> </resources> diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 662a45b790..ceac1c5343 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Proporção do ecrã</string> <string name="mode_ratio_custom">Definida pela resolução personalizada.</string> <string name="mode_ratio_auto">Automático utiliza pelo menos 16:9.</string> - <string name="mode_fps">Limite de fotogramas</string> - <string name="mode_fps_note">Limita toda a sessão. O ecrã muda para uma taxa de atualização que seja múltipla do limite.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Saída HDR10</string> <string name="mode_hdr_unavailable">Indisponível: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Controlos táteis do Steam (beta)</string> <string name="osc_style_next_session">Os controlos táteis do Steam começam na próxima sessão do Steam</string> <string name="osc_steam_layout">Esquema tátil do Steam</string> + <string name="screen_keys">Teclas no ecrã</string> + <string name="screen_keys_add">Adicionar tecla</string> + <string name="screen_key_text">Texto</string> + <string name="screen_key_size">Tamanho</string> + <string name="screen_key_opacity">Opacidade</string> + <string name="screen_key_type_button">Tecla</string> + <string name="screen_key_shape_trigger">Gatilho</string> + <string name="screen_key_toggle">Alternar</string> + <string name="screen_key_layout_export">Exportar</string> + <string name="screen_key_shape_pill">Cápsula</string> + <string name="screen_key_shape_round">Arredondado</string> + <string name="screen_key_shape_circle">Círculo</string> + <string name="screen_key_shape_rect">Retângulo</string> + <string name="screen_key_bind">Tecla</string> + <string name="screen_key_image">Imagem</string> + <string name="screen_key_image_clear">Limpar</string> + <string name="screen_key_layout">Esquema</string> + <string name="screen_key_layout_save">Guardar</string> <string name="osc_steam_layout_hint">Mova, redimensione ou oculte os controlos táteis deste jogo; é guardado no Steam</string> <string name="mode_controller">Comando</string> <string name="mode_controller_hint">Como o Steam vê o seu comando. Aplica-se na próxima sessão.</string> @@ -1938,7 +1954,6 @@ <string name="display_filter_live">Aplica-se em tempo real. Partilhado pelo Steam e pelo Ambiente de trabalho.</string> <string name="display_filter_note">FSR, GSR e NIS aplicam-se ao ampliar a imagem da sessão. «Só nitidez» também funciona sem ampliação.</string> <string name="display_sharpness">Nitidez do filtro</string> - <string name="display_frame_rate">Taxa de fotogramas</string> <string name="display_look_filter">%1$s Define a escala como %2$s.</string> <string name="display_match_screen">Igual ao ecrã (%1$d×%2$d)</string> <string name="display_follow_screen">Seguir o ecrã (redimensiona ao dobrar ou desdobrar)</string> @@ -1991,6 +2006,15 @@ <string name="stores_shelf_trending">Tendências</string> <string name="stores_play">Jogar</string> <string name="stores_install">Instalar</string> + <string name="bnet_open">Abrir o Battle.net</string> + <string name="bnet_dl_starting">A iniciar o programa de transferência da Blizzard…</string> + <string name="bnet_dl_waiting">A aguardar que o Battle.net feche…</string> + <string name="bnet_dl_queued">A aguardar a outra transferência do Battle.net…</string> + <string name="bnet_dl_client_first">Abra o Battle.net e inicie sessão uma vez; depois instale os jogos dele aqui.</string> + <string name="bnet_dl_failed">O programa de transferência da Blizzard parou: %1$s</string> + <string name="bnet_dl_agent_error">Erro da Blizzard %1$s</string> + <string name="bnet_update">Atualizar</string> + <string name="bnet_store">Jogos da Blizzard</string> <string name="stores_resume_install">Retomar instalação</string> <string name="stores_dl_interrupted">Interrompida</string> <string name="stores_install_size">Instalar · %1$s</string> @@ -2028,6 +2052,13 @@ <string name="stores_itch_browse_failed">Não foi possível carregar os jogos do itch.io</string> <string name="stores_itch_archive">Ficheiros %1$s não são suportados</string> <string name="stores_itch_download_failed">O itch.io respondeu HTTP %1$d</string> + <string name="stores_itch_pick_title">Escolha uma versão</string> + <string name="stores_itch_pick_none">Não foram encontradas transferências para este jogo</string> + <string name="stores_itch_pick_failed">Não foi possível carregar as transferências do itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Abrir no itch.io</string> + <string name="stores_itch_build_linux_soon">Ainda não suportado</string> + <string name="stores_itch_no_game">Não foi possível encontrar este jogo no itch.io</string> <string name="stores_free">Grátis</string> <string name="stores_resume">Retomar</string> <string name="stores_refresh">Atualizar</string> @@ -3033,6 +3064,25 @@ <string name="spatial_saved_views_hint">As visualizações guardadas podem ser recalculadas. Inicie uma nova calibração para captar no sistema de coordenadas de seguimento atual.</string> <string name="spatial_model_checksum_error">Incompatibilidade de checksum do modelo de mãos</string> <string name="spatial_opencv_load_error">O OpenCV não conseguiu carregar</string> + <string name="setup_group_memory">Memória</string> + <string name="setup_clear_cached">Fechar apps em cache antes de uma sessão</string> + <string name="setup_clear_cached_hint">Quando uma sessão começa, o DroidDeck fecha as apps que o Android mantém em segundo plano, para que o jogo tenha mais memória. A Depuração sem fios tem de estar ativada.</string> + <string name="setup_clear_cached_unpaired">É necessário sincronizar o DroidDeck com a Depuração sem fios (Sincronizar, abaixo).</string> + <string name="setup_memory_hud">Indicador de memória</string> + <string name="setup_memory_hud_hint">Memória e swap em uso, no ecrã da sessão. O modo Avançado divide-a entre o jogo, o DroidDeck, o Android e a GPU.</string> + <string name="setup_memory_hud_simple">Simples</string> + <string name="setup_memory_hud_advanced">Avançado</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">jogo %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Apps em segundo plano durante uma sessão</string> + <string name="setup_bg_limit_hint">Enquanto uma sessão decorre, o Android mantém em cache no máximo este número de apps e fecha as restantes, para que o jogo fique com a memória delas. O DroidDeck repõe o limite anterior quando a sessão termina. A Depuração sem fios tem de estar ativada.</string> + <string name="setup_bg_limit_4">No máximo 4</string> + <string name="setup_bg_limit_1">No máximo 1</string> + <string name="setup_bg_limit_0">Nenhuma</string> + <string name="setup_adb_pair">Depuração sem fios</string> + <string name="setup_adb_pair_hint">Sincroniza o DroidDeck com a Depuração sem fios do Android para as opções acima. O limite de processos secundários continua desativado.</string> + <string name="setup_adb_pair_button">Sincronizar</string> <string name="tracking_recovery_look">Olhe em redor lentamente num ambiente bem iluminado.\nMantenha as câmaras de seguimento desobstruídas e viradas para móveis ou outros detalhes visíveis.</string> <string name="epic_client_missing">Não instalado</string> <string name="epic_client_open">Abrir</string> @@ -3066,6 +3116,50 @@ <string name="library_remove">Remover da Biblioteca</string> <string name="library_in">Na Biblioteca</string> <string name="xbox_filter_show">Mostrar</string> + <string name="itch_collections">Coleções</string> <string name="xbox_filter_cloud">Nuvem</string> <string name="stores_xbox_cloud_settings">Definições da nuvem</string> + <string name="apps_search_hint">Pesquisar aplicações</string> + <string name="apps_no_match">Nenhuma aplicação corresponde a “%1$s”.</string> + <string name="apps_add_widget">Adicionar widget</string> + <string name="apps_widgets_loading">A carregar widgets…</string> + <string name="apps_widgets_none">Nenhuma aplicação neste dispositivo oferece widgets.</string> + <string name="apps_widget_wider">Mais largo</string> + <string name="apps_widget_narrower">Mais estreito</string> + <string name="apps_widget_taller">Mais alto</string> + <string name="apps_widget_shorter">Mais baixo</string> + <string name="apps_widget_move_earlier">Mover para antes</string> + <string name="apps_widget_move_later">Mover para depois</string> + <string name="apps_widget_configure">Definições do widget</string> + <string name="apps_widget_remove">Remover widget</string> + <string name="apps_add_to_folder">Adicionar a pasta</string> + <string name="apps_new_folder">Nova pasta</string> + <string name="apps_remove_from_folder">Remover da pasta</string> + <string name="apps_app_info">Informações da aplicação</string> + <string name="apps_uninstall">Desinstalar</string> + <string name="apps_folder_rename">Mudar o nome</string> + <string name="apps_folder_ungroup">Desagrupar</string> + <string name="apps_folder_default">Pasta</string> + <string name="apps_folder_name">Nome da pasta</string> + <string name="apps_filter">Mostrar</string> + <string name="apps_filter_all">Todas as aplicações</string> + <string name="apps_filter_games">Jogos</string> + <string name="apps_filter_downloaded">Transferidas</string> + <string name="apps_filter_system">Sistema</string> + <string name="apps_filter_hidden">Ocultas</string> + <string name="apps_hide">Ocultar</string> + <string name="apps_unhide">Mostrar nas aplicações</string> + <string name="apps_shortcut_remove">Remover atalho</string> + <string name="apps_pin_title">Adicionar às Aplicações</string> + <string name="apps_pin_add">Adicionar</string> + <string name="apps_hidden_none">Nenhuma aplicação oculta.</string> + <string name="apps_sort_name_asc">Nome A–Z</string> + <string name="apps_sort_name_desc">Nome Z–A</string> + <string name="apps_sort_installed">Instaladas recentemente</string> + <string name="apps_sort_updated">Atualizadas recentemente</string> + <plurals name="apps_count"> + <item quantity="one">%d aplicação</item> + <item quantity="many">%d aplicações</item> + <item quantity="other">%d aplicações</item> + </plurals> </resources> diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index c0c4ca359e..825ef7b95d 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Proporção da tela</string> <string name="mode_ratio_custom">Definida pela resolução personalizada.</string> <string name="mode_ratio_auto">O Automático usa no mínimo 16:9.</string> - <string name="mode_fps">Limite de quadros</string> - <string name="mode_fps_note">Limita a sessão inteira. A tela muda para uma taxa de atualização que seja múltipla do limite.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Saída HDR10</string> <string name="mode_hdr_unavailable">Indisponível: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Toque da Steam (beta)</string> <string name="osc_style_next_session">Os controles de toque da Steam começam na próxima sessão da Steam</string> <string name="osc_steam_layout">Layout de toque da Steam</string> + <string name="screen_keys">Teclas na tela</string> + <string name="screen_keys_add">Adicionar tecla</string> + <string name="screen_key_text">Texto</string> + <string name="screen_key_size">Tamanho</string> + <string name="screen_key_opacity">Opacidade</string> + <string name="screen_key_type_button">Tecla</string> + <string name="screen_key_shape_trigger">Gatilho</string> + <string name="screen_key_toggle">Alternar</string> + <string name="screen_key_layout_export">Exportar</string> + <string name="screen_key_shape_pill">Cápsula</string> + <string name="screen_key_shape_round">Arredondado</string> + <string name="screen_key_shape_circle">Círculo</string> + <string name="screen_key_shape_rect">Retângulo</string> + <string name="screen_key_bind">Tecla</string> + <string name="screen_key_image">Imagem</string> + <string name="screen_key_image_clear">Limpar</string> + <string name="screen_key_layout">Layout</string> + <string name="screen_key_layout_save">Salvar</string> <string name="osc_steam_layout_hint">Mova, redimensione ou oculte os controles de toque deste jogo; salvo na Steam</string> <string name="mode_controller">Controle</string> <string name="mode_controller_hint">Como a Steam vê seu controle. Vale a partir da próxima sessão.</string> @@ -1938,7 +1954,6 @@ <string name="display_filter_live">Aplicado na hora. Compartilhado entre Steam e Área de trabalho.</string> <string name="display_filter_note">FSR, GSR e NIS são aplicados ao ampliar a imagem da sessão. Só nitidez também funciona sem ampliação.</string> <string name="display_sharpness">Nitidez do filtro</string> - <string name="display_frame_rate">Taxa de quadros</string> <string name="display_look_filter">%1$s Define a escala como %2$s.</string> <string name="display_match_screen">Igual à tela (%1$d×%2$d)</string> <string name="display_follow_screen">Seguir a tela (redimensiona ao dobrar ou desdobrar)</string> @@ -1991,6 +2006,15 @@ <string name="stores_shelf_trending">Em alta</string> <string name="stores_play">Jogar</string> <string name="stores_install">Instalar</string> + <string name="bnet_open">Abrir o Battle.net</string> + <string name="bnet_dl_starting">Iniciando o downloader da Blizzard…</string> + <string name="bnet_dl_waiting">Aguardando o Battle.net fechar…</string> + <string name="bnet_dl_queued">Aguardando o outro download do Battle.net…</string> + <string name="bnet_dl_client_first">Abra o Battle.net e entre uma vez; depois instale os jogos dele aqui.</string> + <string name="bnet_dl_failed">O downloader da Blizzard parou: %1$s</string> + <string name="bnet_dl_agent_error">Erro da Blizzard %1$s</string> + <string name="bnet_update">Atualizar</string> + <string name="bnet_store">Jogos da Blizzard</string> <string name="stores_resume_install">Retomar instalação</string> <string name="stores_dl_interrupted">Interrompido</string> <string name="stores_install_size">Instalar · %1$s</string> @@ -2028,6 +2052,13 @@ <string name="stores_itch_browse_failed">Não foi possível carregar os jogos do itch.io</string> <string name="stores_itch_archive">Arquivos %1$s não são suportados</string> <string name="stores_itch_download_failed">O itch.io respondeu HTTP %1$d</string> + <string name="stores_itch_pick_title">Escolha uma versão</string> + <string name="stores_itch_pick_none">Nenhum download encontrado para este jogo</string> + <string name="stores_itch_pick_failed">Não foi possível carregar os downloads do itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Abrir no itch.io</string> + <string name="stores_itch_build_linux_soon">Ainda não suportado</string> + <string name="stores_itch_no_game">Não foi possível encontrar este jogo no itch.io</string> <string name="stores_free">Grátis</string> <string name="stores_resume">Retomar</string> <string name="stores_refresh">Atualizar</string> @@ -3033,6 +3064,25 @@ <string name="spatial_saved_views_hint">As visualizações salvas podem ser recalculadas. Inicie uma nova calibração para capturar no sistema de coordenadas de rastreamento atual.</string> <string name="spatial_model_checksum_error">Incompatibilidade de soma de verificação do modelo de mãos</string> <string name="spatial_opencv_load_error">OpenCV não pôde carregar</string> + <string name="setup_group_memory">Memória</string> + <string name="setup_clear_cached">Fechar apps em cache antes de uma sessão</string> + <string name="setup_clear_cached_hint">Quando uma sessão começa, o DroidDeck fecha os apps que o Android mantém em segundo plano, para que o jogo tenha mais memória. A Depuração por Wi-Fi precisa estar ativada.</string> + <string name="setup_clear_cached_unpaired">O DroidDeck precisa estar pareado com a Depuração por Wi-Fi (Parear, abaixo).</string> + <string name="setup_memory_hud">Indicador de memória</string> + <string name="setup_memory_hud_hint">Memória e swap em uso, na tela da sessão. O modo Avançado divide entre o jogo, o DroidDeck, o Android e a GPU.</string> + <string name="setup_memory_hud_simple">Simples</string> + <string name="setup_memory_hud_advanced">Avançado</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">jogo %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Apps em segundo plano durante uma sessão</string> + <string name="setup_bg_limit_hint">Enquanto uma sessão está em andamento, o Android mantém no máximo esse número de apps em cache e fecha o restante, para que o jogo fique com a memória deles. O DroidDeck restaura o limite anterior quando a sessão termina. A Depuração por Wi-Fi precisa estar ativada.</string> + <string name="setup_bg_limit_4">No máximo 4</string> + <string name="setup_bg_limit_1">No máximo 1</string> + <string name="setup_bg_limit_0">Nenhum</string> + <string name="setup_adb_pair">Depuração por Wi-Fi</string> + <string name="setup_adb_pair_hint">Pareia o DroidDeck com a Depuração por Wi-Fi do Android para as opções acima. O limite de processos filhos continua desativado.</string> + <string name="setup_adb_pair_button">Parear</string> <string name="tracking_recovery_look">Olhe ao redor lentamente em um ambiente bem iluminado.\nMantenha as câmeras de rastreamento desobstruídas e voltadas para móveis ou outros detalhes visíveis.</string> <string name="epic_client_missing">Não instalado</string> <string name="epic_client_open">Abrir</string> @@ -3066,6 +3116,50 @@ <string name="library_remove">Remover da Biblioteca</string> <string name="library_in">Na Biblioteca</string> <string name="xbox_filter_show">Mostrar</string> + <string name="itch_collections">Coleções</string> <string name="xbox_filter_cloud">Nuvem</string> <string name="stores_xbox_cloud_settings">Configurações da nuvem</string> + <string name="apps_search_hint">Pesquisar apps</string> + <string name="apps_no_match">Nenhum app corresponde a “%1$s”.</string> + <string name="apps_add_widget">Adicionar widget</string> + <string name="apps_widgets_loading">Carregando widgets…</string> + <string name="apps_widgets_none">Nenhum app neste dispositivo oferece widgets.</string> + <string name="apps_widget_wider">Mais largo</string> + <string name="apps_widget_narrower">Mais estreito</string> + <string name="apps_widget_taller">Mais alto</string> + <string name="apps_widget_shorter">Mais baixo</string> + <string name="apps_widget_move_earlier">Mover para antes</string> + <string name="apps_widget_move_later">Mover para depois</string> + <string name="apps_widget_configure">Configurações do widget</string> + <string name="apps_widget_remove">Remover widget</string> + <string name="apps_add_to_folder">Adicionar à pasta</string> + <string name="apps_new_folder">Nova pasta</string> + <string name="apps_remove_from_folder">Remover da pasta</string> + <string name="apps_app_info">Informações do app</string> + <string name="apps_uninstall">Desinstalar</string> + <string name="apps_folder_rename">Renomear</string> + <string name="apps_folder_ungroup">Desagrupar</string> + <string name="apps_folder_default">Pasta</string> + <string name="apps_folder_name">Nome da pasta</string> + <string name="apps_filter">Mostrar</string> + <string name="apps_filter_all">Todos os apps</string> + <string name="apps_filter_games">Jogos</string> + <string name="apps_filter_downloaded">Baixados</string> + <string name="apps_filter_system">Sistema</string> + <string name="apps_filter_hidden">Ocultos</string> + <string name="apps_hide">Ocultar</string> + <string name="apps_unhide">Mostrar nos apps</string> + <string name="apps_shortcut_remove">Remover atalho</string> + <string name="apps_pin_title">Adicionar aos Apps</string> + <string name="apps_pin_add">Adicionar</string> + <string name="apps_hidden_none">Nenhum app oculto.</string> + <string name="apps_sort_name_asc">Nome A–Z</string> + <string name="apps_sort_name_desc">Nome Z–A</string> + <string name="apps_sort_installed">Instalados recentemente</string> + <string name="apps_sort_updated">Atualizados recentemente</string> + <plurals name="apps_count"> + <item quantity="one">%d app</item> + <item quantity="many">%d apps</item> + <item quantity="other">%d apps</item> + </plurals> </resources> diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 9bd9a1df3a..b95ef48573 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Raport de ecran</string> <string name="mode_ratio_custom">Stabilit de rezoluția personalizată.</string> <string name="mode_ratio_auto">Automat folosește cel puțin 16:9.</string> - <string name="mode_fps">Limită de cadre</string> - <string name="mode_fps_note">Limitează întreaga sesiune. Afișajul trece la o rată de reîmprospătare pe care limita o împarte exact.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Ieșire HDR10</string> <string name="mode_hdr_unavailable">Indisponibil: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Atingere Steam (beta)</string> <string name="osc_style_next_session">Comenzile tactile Steam pornesc odată cu următoarea sesiune Steam</string> <string name="osc_steam_layout">Aranjament tactil Steam</string> + <string name="screen_keys">Taste pe ecran</string> + <string name="screen_keys_add">Adaugă tastă</string> + <string name="screen_key_text">Text</string> + <string name="screen_key_size">Dimensiune</string> + <string name="screen_key_opacity">Opacitate</string> + <string name="screen_key_type_button">Tastă</string> + <string name="screen_key_shape_trigger">Trăgaci</string> + <string name="screen_key_toggle">Comutare</string> + <string name="screen_key_layout_export">Exportă</string> + <string name="screen_key_shape_pill">Capsulă</string> + <string name="screen_key_shape_round">Rotunjit</string> + <string name="screen_key_shape_circle">Cerc</string> + <string name="screen_key_shape_rect">Dreptunghi</string> + <string name="screen_key_bind">Tastă</string> + <string name="screen_key_image">Imagine</string> + <string name="screen_key_image_clear">Șterge</string> + <string name="screen_key_layout">Aranjament</string> + <string name="screen_key_layout_save">Salvează</string> <string name="osc_steam_layout_hint">Mută, redimensionează sau ascunde comenzile tactile ale acestui joc; salvate în Steam</string> <string name="mode_controller">Controller</string> <string name="mode_controller_hint">Cum vede Steam controllerul tău. Se aplică la sesiunea următoare.</string> @@ -1946,7 +1962,6 @@ <string name="display_filter_live">Se aplică live. Partajat de Steam și Desktop.</string> <string name="display_filter_note">FSR, GSR și NIS se aplică la mărirea imaginii sesiunii. Doar claritate funcționează și fără mărire.</string> <string name="display_sharpness">Claritatea filtrului</string> - <string name="display_frame_rate">Rata de cadre</string> <string name="display_look_filter">%1$s Setează scalarea la %2$s.</string> <string name="display_match_screen">Potrivire ecran (%1$d×%2$d)</string> <string name="display_follow_screen">Urmărește ecranul (se redimensionează la împăturire sau desfacere)</string> @@ -1999,6 +2014,15 @@ <string name="stores_shelf_trending">În tendințe</string> <string name="stores_play">Joacă</string> <string name="stores_install">Instalează</string> + <string name="bnet_open">Deschide Battle.net</string> + <string name="bnet_dl_starting">Se pornește programul de descărcare Blizzard…</string> + <string name="bnet_dl_waiting">Se așteaptă închiderea Battle.net…</string> + <string name="bnet_dl_queued">Se așteaptă cealaltă descărcare Battle.net…</string> + <string name="bnet_dl_client_first">Deschide Battle.net și conectează-te o dată, apoi instalează jocurile de aici.</string> + <string name="bnet_dl_failed">Programul de descărcare Blizzard s-a oprit: %1$s</string> + <string name="bnet_dl_agent_error">Eroare Blizzard %1$s</string> + <string name="bnet_update">Actualizează</string> + <string name="bnet_store">Jocuri Blizzard</string> <string name="stores_resume_install">Reia instalarea</string> <string name="stores_dl_interrupted">Întreruptă</string> <string name="stores_install_size">Instalare · %1$s</string> @@ -2036,6 +2060,13 @@ <string name="stores_itch_browse_failed">Nu s-au putut încărca jocurile de pe itch.io</string> <string name="stores_itch_archive">Arhivele %1$s nu sunt acceptate</string> <string name="stores_itch_download_failed">itch.io a răspuns HTTP %1$d</string> + <string name="stores_itch_pick_title">Alege o versiune</string> + <string name="stores_itch_pick_none">Nu s-au găsit descărcări pentru acest joc</string> + <string name="stores_itch_pick_failed">Descărcările de pe itch.io nu au putut fi încărcate</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Deschide pe itch.io</string> + <string name="stores_itch_build_linux_soon">Încă nu este acceptat</string> + <string name="stores_itch_no_game">Jocul nu a fost găsit pe itch.io</string> <string name="stores_free">Gratuit</string> <string name="stores_resume">Reluare</string> <string name="stores_refresh">Reîmprospătează</string> @@ -3034,6 +3065,25 @@ <string name="spatial_saved_views_hint">Vizualizările salvate pot fi recalculate. Începe o nouă calibrare pentru a captura în sistemul de coordonate de urmărire curent.</string> <string name="spatial_model_checksum_error">Nepotrivire a sumei de control a modelului de mâini</string> <string name="spatial_opencv_load_error">OpenCV nu s-a putut încărca</string> + <string name="setup_group_memory">Memorie</string> + <string name="setup_clear_cached">Închide aplicațiile din cache înainte de o sesiune</string> + <string name="setup_clear_cached_hint">La pornirea unei sesiuni, DroidDeck închide aplicațiile pe care Android le ține în fundal, ca jocul să aibă mai multă memorie. Depanarea wireless trebuie să fie activată.</string> + <string name="setup_clear_cached_unpaired">DroidDeck trebuie asociat prin Depanarea wireless (Asociază, mai jos).</string> + <string name="setup_memory_hud">Indicator de memorie</string> + <string name="setup_memory_hud_hint">Memoria și swap-ul folosite, pe ecranul sesiunii. Avansat le împarte între joc, DroidDeck, Android și GPU.</string> + <string name="setup_memory_hud_simple">Simplu</string> + <string name="setup_memory_hud_advanced">Avansat</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">joc %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Aplicații în fundal în timpul unei sesiuni</string> + <string name="setup_bg_limit_hint">Cât timp rulează o sesiune, Android păstrează în cache cel mult atâtea aplicații și le închide pe celelalte, ca jocul să primească memoria lor. DroidDeck readuce limita la valoarea anterioară când se termină sesiunea. Depanarea wireless trebuie să fie activată.</string> + <string name="setup_bg_limit_4">Cel mult 4</string> + <string name="setup_bg_limit_1">Cel mult 1</string> + <string name="setup_bg_limit_0">Niciuna</string> + <string name="setup_adb_pair">Depanare wireless</string> + <string name="setup_adb_pair_hint">Asociază DroidDeck cu Depanarea wireless din Android pentru opțiunile de mai sus. Limita proceselor-copil rămâne dezactivată.</string> + <string name="setup_adb_pair_button">Asociază</string> <string name="epic_client_missing">Neinstalat</string> <string name="epic_client_open">Deschide</string> <string name="epic_client_install">Instalează</string> @@ -3066,6 +3116,50 @@ <string name="library_remove">Elimină din Bibliotecă</string> <string name="library_in">În Bibliotecă</string> <string name="xbox_filter_show">Afișează</string> + <string name="itch_collections">Colecții</string> <string name="xbox_filter_cloud">Cloud</string> <string name="stores_xbox_cloud_settings">Setări cloud</string> + <string name="apps_search_hint">Caută aplicații</string> + <string name="apps_no_match">Nicio aplicație nu se potrivește cu „%1$s”.</string> + <string name="apps_add_widget">Adaugă widget</string> + <string name="apps_widgets_loading">Se încarcă widgeturile…</string> + <string name="apps_widgets_none">Nicio aplicație de pe acest dispozitiv nu oferă widgeturi.</string> + <string name="apps_widget_wider">Mai lat</string> + <string name="apps_widget_narrower">Mai îngust</string> + <string name="apps_widget_taller">Mai înalt</string> + <string name="apps_widget_shorter">Mai scund</string> + <string name="apps_widget_move_earlier">Mută mai devreme</string> + <string name="apps_widget_move_later">Mută mai târziu</string> + <string name="apps_widget_configure">Setări widget</string> + <string name="apps_widget_remove">Elimină widgetul</string> + <string name="apps_add_to_folder">Adaugă în dosar</string> + <string name="apps_new_folder">Dosar nou</string> + <string name="apps_remove_from_folder">Elimină din dosar</string> + <string name="apps_app_info">Informații despre aplicație</string> + <string name="apps_uninstall">Dezinstalează</string> + <string name="apps_folder_rename">Redenumește</string> + <string name="apps_folder_ungroup">Degrupează</string> + <string name="apps_folder_default">Dosar</string> + <string name="apps_folder_name">Numele dosarului</string> + <string name="apps_filter">Afișează</string> + <string name="apps_filter_all">Toate aplicațiile</string> + <string name="apps_filter_games">Jocuri</string> + <string name="apps_filter_downloaded">Descărcate</string> + <string name="apps_filter_system">Sistem</string> + <string name="apps_filter_hidden">Ascunse</string> + <string name="apps_hide">Ascunde</string> + <string name="apps_unhide">Afișează în aplicații</string> + <string name="apps_shortcut_remove">Elimină comanda rapidă</string> + <string name="apps_pin_title">Adaugă în Aplicații</string> + <string name="apps_pin_add">Adaugă</string> + <string name="apps_hidden_none">Nicio aplicație ascunsă.</string> + <string name="apps_sort_name_asc">Nume A–Z</string> + <string name="apps_sort_name_desc">Nume Z–A</string> + <string name="apps_sort_installed">Instalate recent</string> + <string name="apps_sort_updated">Actualizate recent</string> + <plurals name="apps_count"> + <item quantity="one">%d aplicație</item> + <item quantity="few">%d aplicații</item> + <item quantity="other">%d de aplicații</item> + </plurals> </resources> diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 7fa1bc8a6b..483d86ab5a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Соотношение сторон</string> <string name="mode_ratio_custom">Задается пользовательским разрешением.</string> <string name="mode_ratio_auto">Автоматический режим использует не менее 16:9.</string> - <string name="mode_fps">Ограничение частоты кадров</string> - <string name="mode_fps_note">Ограничивает частоту кадров всей сессии. Экран переключится на частоту обновления, кратную этому пределу.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Вывод HDR10</string> <string name="mode_hdr_unavailable">Недоступно: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Сенсорное управление Steam (бета)</string> <string name="osc_style_next_session">Сенсорное управление Steam включится со следующей сессии Steam</string> <string name="osc_steam_layout">Сенсорная раскладка Steam</string> + <string name="screen_keys">Экранные клавиши</string> + <string name="screen_keys_add">Добавить клавишу</string> + <string name="screen_key_text">Текст</string> + <string name="screen_key_size">Размер</string> + <string name="screen_key_opacity">Непрозрачность</string> + <string name="screen_key_type_button">Клавиша</string> + <string name="screen_key_shape_trigger">Триггер</string> + <string name="screen_key_toggle">Переключение</string> + <string name="screen_key_layout_export">Экспорт</string> + <string name="screen_key_shape_pill">Капсула</string> + <string name="screen_key_shape_round">Скругление</string> + <string name="screen_key_shape_circle">Круг</string> + <string name="screen_key_shape_rect">Прямоугольник</string> + <string name="screen_key_bind">Клавиша</string> + <string name="screen_key_image">Изображение</string> + <string name="screen_key_image_clear">Очистить</string> + <string name="screen_key_layout">Раскладка</string> + <string name="screen_key_layout_save">Сохранить</string> <string name="osc_steam_layout_hint">Перемещайте, меняйте размер или скрывайте сенсорные кнопки этой игры; сохраняется в Steam</string> <string name="mode_controller">Контроллер</string> <string name="mode_controller_hint">Как Steam распознает ваш контроллер. Вступит в силу в следующей сессии.</string> @@ -1969,7 +1985,6 @@ <string name="display_filter_live">Применяется сразу. Общий для Steam и рабочего стола.</string> <string name="display_filter_note">FSR, GSR и NIS работают при увеличении изображения сессии. «Sharpen only» работает и без увеличения.</string> <string name="display_sharpness">Резкость фильтра</string> - <string name="display_frame_rate">Частота кадров</string> <string name="display_look_filter">%1$s Устанавливает масштабирование: %2$s.</string> <string name="display_match_screen">По размеру экрана (%1$d×%2$d)</string> <string name="display_follow_screen">По экрану (меняется при складывании и раскладывании)</string> @@ -2022,6 +2037,15 @@ <string name="stores_shelf_trending">Популярное</string> <string name="stores_play">Играть</string> <string name="stores_install">Установить</string> + <string name="bnet_open">Открыть Battle.net</string> + <string name="bnet_dl_starting">Запуск загрузчика Blizzard…</string> + <string name="bnet_dl_waiting">Ожидание закрытия Battle.net…</string> + <string name="bnet_dl_queued">Ожидание другой загрузки Battle.net…</string> + <string name="bnet_dl_client_first">Откройте Battle.net и войдите один раз, затем устанавливайте его игры здесь.</string> + <string name="bnet_dl_failed">Загрузчик Blizzard остановился: %1$s</string> + <string name="bnet_dl_agent_error">Ошибка Blizzard %1$s</string> + <string name="bnet_update">Обновить</string> + <string name="bnet_store">Игры Blizzard</string> <string name="stores_resume_install">Продолжить установку</string> <string name="stores_dl_interrupted">Прервано</string> <string name="stores_install_size">Установить · %1$s</string> @@ -2059,6 +2083,13 @@ <string name="stores_itch_browse_failed">Не удалось загрузить игры с itch.io</string> <string name="stores_itch_archive">Архивы %1$s не поддерживаются</string> <string name="stores_itch_download_failed">itch.io ответил HTTP %1$d</string> + <string name="stores_itch_pick_title">Выберите версию</string> + <string name="stores_itch_pick_none">Для этой игры не найдено загрузок</string> + <string name="stores_itch_pick_failed">Не удалось загрузить список файлов с itch.io</string> + <string name="stores_itch_build_demo">Демо</string> + <string name="stores_itch_build_open">Открыть на itch.io</string> + <string name="stores_itch_build_linux_soon">Пока не поддерживается</string> + <string name="stores_itch_no_game">Не удалось найти эту игру на itch.io</string> <string name="stores_free">Бесплатно</string> <string name="stores_resume">Продолжить</string> <string name="stores_refresh">Обновить</string> @@ -3070,6 +3101,25 @@ <string name="spatial_gpu">Распознавание рук на GPU</string> <string name="spatial_gpu_hint">По умолчанию используется CPU. Режим GPU экспериментальный и может вызывать перезапуск SteamVR. Выбор сбрасывается при перезапуске отслеживания.</string> <string name="spatial_inference_error">Распознавание рук недоступно: %1$s. Измените режим CPU/GPU или выключите и снова включите управление руками, чтобы повторить попытку.</string> + <string name="setup_group_memory">Память</string> + <string name="setup_clear_cached">Закрывать фоновые приложения перед сеансом</string> + <string name="setup_clear_cached_hint">При запуске сеанса закрывает приложения, которые Android держит в фоне, чтобы игре досталось больше памяти. Отладка по Wi-Fi должна быть включена.</string> + <string name="setup_clear_cached_unpaired">DroidDeck должен быть сопряжён через отладку по Wi-Fi (кнопка «Сопрячь» ниже).</string> + <string name="setup_memory_hud">Индикатор памяти</string> + <string name="setup_memory_hud_hint">Используемая память и подкачка на экране сеанса. «Дополнительно» показывает отдельно игру, DroidDeck, Android и GPU.</string> + <string name="setup_memory_hud_simple">Простой</string> + <string name="setup_memory_hud_advanced">Дополнительно</string> + <string name="memory_hud_simple">ОЗУ %1$s/%2$s ГБ · подкачка %3$s/%4$s ГБ</string> + <string name="memory_hud_split">игра %1$s · DroidDeck %2$s · Android %3$s ГБ</string> + <string name="memory_hud_gpu">GPU %1$s ГБ</string> + <string name="setup_bg_limit">Фоновые приложения во время сеанса</string> + <string name="setup_bg_limit_hint">Пока идёт сеанс, Android хранит в кэше не больше этого числа приложений и закрывает остальные, чтобы их память досталась игре. После сеанса всё возвращается как было. Отладка по Wi-Fi должна быть включена.</string> + <string name="setup_bg_limit_4">Не больше 4</string> + <string name="setup_bg_limit_1">Не больше 1</string> + <string name="setup_bg_limit_0">Нет</string> + <string name="setup_adb_pair">Отладка по Wi-Fi</string> + <string name="setup_adb_pair_hint">Сопрягает DroidDeck с отладкой Android по Wi-Fi для параметров выше. Ограничение дочерних процессов остаётся отключённым.</string> + <string name="setup_adb_pair_button">Сопрячь</string> <string name="epic_client_missing">Не установлено</string> <string name="epic_client_open">Открыть</string> <string name="epic_client_install">Установить</string> @@ -3102,6 +3152,51 @@ <string name="library_remove">Убрать из библиотеки</string> <string name="library_in">В библиотеке</string> <string name="xbox_filter_show">Показать</string> + <string name="itch_collections">Коллекции</string> <string name="xbox_filter_cloud">Облако</string> <string name="stores_xbox_cloud_settings">Настройки облака</string> + <string name="apps_search_hint">Поиск приложений</string> + <string name="apps_no_match">Нет приложений по запросу «%1$s».</string> + <string name="apps_add_widget">Добавить виджет</string> + <string name="apps_widgets_loading">Загрузка виджетов…</string> + <string name="apps_widgets_none">На этом устройстве нет приложений с виджетами.</string> + <string name="apps_widget_wider">Шире</string> + <string name="apps_widget_narrower">Уже</string> + <string name="apps_widget_taller">Выше</string> + <string name="apps_widget_shorter">Ниже</string> + <string name="apps_widget_move_earlier">Переместить раньше</string> + <string name="apps_widget_move_later">Переместить позже</string> + <string name="apps_widget_configure">Настройки виджета</string> + <string name="apps_widget_remove">Удалить виджет</string> + <string name="apps_add_to_folder">Добавить в папку</string> + <string name="apps_new_folder">Новая папка</string> + <string name="apps_remove_from_folder">Убрать из папки</string> + <string name="apps_app_info">О приложении</string> + <string name="apps_uninstall">Удалить</string> + <string name="apps_folder_rename">Переименовать</string> + <string name="apps_folder_ungroup">Разгруппировать</string> + <string name="apps_folder_default">Папка</string> + <string name="apps_folder_name">Название папки</string> + <string name="apps_filter">Показать</string> + <string name="apps_filter_all">Все приложения</string> + <string name="apps_filter_games">Игры</string> + <string name="apps_filter_downloaded">Загруженные</string> + <string name="apps_filter_system">Системные</string> + <string name="apps_filter_hidden">Скрытые</string> + <string name="apps_hide">Скрыть</string> + <string name="apps_unhide">Показывать в приложениях</string> + <string name="apps_shortcut_remove">Удалить ярлык</string> + <string name="apps_pin_title">Добавить в приложения</string> + <string name="apps_pin_add">Добавить</string> + <string name="apps_hidden_none">Скрытых приложений нет.</string> + <string name="apps_sort_name_asc">Название А–Я</string> + <string name="apps_sort_name_desc">Название Я–А</string> + <string name="apps_sort_installed">Недавно установленные</string> + <string name="apps_sort_updated">Недавно обновлённые</string> + <plurals name="apps_count"> + <item quantity="one">%d приложение</item> + <item quantity="few">%d приложения</item> + <item quantity="many">%d приложений</item> + <item quantity="other">%d приложения</item> + </plurals> </resources> diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 1729070d38..72c27705b9 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Bildförhållande</string> <string name="mode_ratio_custom">Bestäms av den anpassade upplösningen.</string> <string name="mode_ratio_auto">Auto använder minst 16:9.</string> - <string name="mode_fps">Bildgräns</string> - <string name="mode_fps_note">Begränsar hela sessionen. Skärmen byter till en uppdateringsfrekvens som är en jämn multipel av gränsen.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-utgång</string> <string name="mode_hdr_unavailable">Inte tillgängligt: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam-pekstyrning (beta)</string> <string name="osc_style_next_session">Steams pekstyrning startar med nästa Steam-session</string> <string name="osc_steam_layout">Steams peklayout</string> + <string name="screen_keys">Skärmtangenter</string> + <string name="screen_keys_add">Lägg till tangent</string> + <string name="screen_key_text">Text</string> + <string name="screen_key_size">Storlek</string> + <string name="screen_key_opacity">Opacitet</string> + <string name="screen_key_type_button">Tangent</string> + <string name="screen_key_shape_trigger">Avtryckare</string> + <string name="screen_key_toggle">Växla</string> + <string name="screen_key_layout_export">Exportera</string> + <string name="screen_key_shape_pill">Kapsel</string> + <string name="screen_key_shape_round">Rundad</string> + <string name="screen_key_shape_circle">Cirkel</string> + <string name="screen_key_shape_rect">Rektangel</string> + <string name="screen_key_bind">Tangent</string> + <string name="screen_key_image">Bild</string> + <string name="screen_key_image_clear">Rensa</string> + <string name="screen_key_layout">Layout</string> + <string name="screen_key_layout_save">Spara</string> <string name="osc_steam_layout_hint">Flytta, ändra storlek på eller dölj spelets pekkontroller; sparas i Steam</string> <string name="mode_controller">Handkontroll</string> <string name="mode_controller_hint">Hur Steam ser din handkontroll. Gäller från nästa session.</string> @@ -1925,7 +1941,6 @@ <string name="display_filter_live">Tillämpas direkt. Delas av Steam och skrivbordet.</string> <string name="display_filter_note">FSR, GSR och NIS tillämpas när sessionens bild förstoras. Endast skärpa fungerar även utan förstoring.</string> <string name="display_sharpness">Filterskärpa</string> - <string name="display_frame_rate">Bildfrekvens</string> <string name="display_look_filter">%1$s Ställer in skalning till %2$s.</string> <string name="display_match_screen">Matcha skärmen (%1$d×%2$d)</string> <string name="display_follow_screen">Följ skärmen (ändrar storlek vid vikning)</string> @@ -1978,6 +1993,15 @@ <string name="stores_shelf_trending">Populärt nu</string> <string name="stores_play">Spela</string> <string name="stores_install">Installera</string> + <string name="bnet_open">Öppna Battle.net</string> + <string name="bnet_dl_starting">Startar Blizzards nedladdare…</string> + <string name="bnet_dl_waiting">Väntar på att Battle.net stängs…</string> + <string name="bnet_dl_queued">Väntar på den andra Battle.net-nedladdningen…</string> + <string name="bnet_dl_client_first">Öppna Battle.net och logga in en gång, installera sedan dess spel här.</string> + <string name="bnet_dl_failed">Blizzards nedladdare stoppades: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard-fel %1$s</string> + <string name="bnet_update">Uppdatera</string> + <string name="bnet_store">Blizzard-spel</string> <string name="stores_resume_install">Återuppta installation</string> <string name="stores_dl_interrupted">Avbruten</string> <string name="stores_install_size">Installation · %1$s</string> @@ -2015,6 +2039,13 @@ <string name="stores_itch_browse_failed">Det gick inte att läsa in spel från itch.io</string> <string name="stores_itch_archive">%1$s-arkiv stöds inte</string> <string name="stores_itch_download_failed">itch.io svarade HTTP %1$d</string> + <string name="stores_itch_pick_title">Välj en version</string> + <string name="stores_itch_pick_none">Inga nedladdningar hittades för det här spelet</string> + <string name="stores_itch_pick_failed">Det gick inte att läsa in nedladdningarna från itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Öppna på itch.io</string> + <string name="stores_itch_build_linux_soon">Stöds inte ännu</string> + <string name="stores_itch_no_game">Spelet hittades inte på itch.io</string> <string name="stores_free">Gratis</string> <string name="stores_resume">Återuppta</string> <string name="stores_refresh">Uppdatera</string> @@ -2999,6 +3030,25 @@ <string name="spatial_saved_views_hint">Sparade vyer kan räknas om. Starta en ny kalibrering för att fånga i det aktuella spårningskoordinatsystemet.</string> <string name="spatial_model_checksum_error">Kontrollsumman för handmodellen inte överensstämmer</string> <string name="spatial_opencv_load_error">OpenCV kunde inte laddas</string> + <string name="setup_group_memory">Minne</string> + <string name="setup_clear_cached">Stäng cachade appar före en session</string> + <string name="setup_clear_cached_hint">När en session startar stänger DroidDeck apparna som Android håller parkerade i bakgrunden, så att spelet får mer minne. Trådlös felsökning måste vara på.</string> + <string name="setup_clear_cached_unpaired">Kräver att DroidDeck är ihopparat via Trådlös felsökning (Para ihop, nedan).</string> + <string name="setup_memory_hud">Minnesvisning</string> + <string name="setup_memory_hud_hint">Minne och swap som används, på sessionsskärmen. Avancerat delar upp det på spelet, DroidDeck, Android och GPU:n.</string> + <string name="setup_memory_hud_simple">Enkel</string> + <string name="setup_memory_hud_advanced">Avancerat</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">spel %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Bakgrundsappar under en session</string> + <string name="setup_bg_limit_hint">Medan en session pågår håller Android högst så här många appar cachade och stänger resten, så att spelet får deras minne. DroidDeck återställer gränsen som den var när sessionen slutar. Trådlös felsökning måste vara på.</string> + <string name="setup_bg_limit_4">Högst 4</string> + <string name="setup_bg_limit_1">Högst 1</string> + <string name="setup_bg_limit_0">Ingen</string> + <string name="setup_adb_pair">Trådlös felsökning</string> + <string name="setup_adb_pair_hint">Parar ihop DroidDeck med Androids Trådlös felsökning för alternativen ovan. Gränsen för underprocesser förblir av.</string> + <string name="setup_adb_pair_button">Para ihop</string> <string name="glasses_6dof">Virtuell skärm med 6DoF</string> <string name="epic_client_missing">Inte installerad</string> <string name="epic_client_open">Öppna</string> @@ -3032,6 +3082,49 @@ <string name="library_remove">Ta bort från Bibliotek</string> <string name="library_in">I Bibliotek</string> <string name="xbox_filter_show">Visa</string> + <string name="itch_collections">Samlingar</string> <string name="xbox_filter_cloud">Moln</string> <string name="stores_xbox_cloud_settings">Molninställningar</string> + <string name="apps_search_hint">Sök appar</string> + <string name="apps_no_match">Inga appar matchar ”%1$s”.</string> + <string name="apps_add_widget">Lägg till widget</string> + <string name="apps_widgets_loading">Läser in widgetar…</string> + <string name="apps_widgets_none">Inga appar på enheten erbjuder widgetar.</string> + <string name="apps_widget_wider">Bredare</string> + <string name="apps_widget_narrower">Smalare</string> + <string name="apps_widget_taller">Högre</string> + <string name="apps_widget_shorter">Lägre</string> + <string name="apps_widget_move_earlier">Flytta tidigare</string> + <string name="apps_widget_move_later">Flytta senare</string> + <string name="apps_widget_configure">Widgetinställningar</string> + <string name="apps_widget_remove">Ta bort widget</string> + <string name="apps_add_to_folder">Lägg till i mapp</string> + <string name="apps_new_folder">Ny mapp</string> + <string name="apps_remove_from_folder">Ta bort från mapp</string> + <string name="apps_app_info">Appinfo</string> + <string name="apps_uninstall">Avinstallera</string> + <string name="apps_folder_rename">Byt namn</string> + <string name="apps_folder_ungroup">Dela upp</string> + <string name="apps_folder_default">Mapp</string> + <string name="apps_folder_name">Mappnamn</string> + <string name="apps_filter">Visa</string> + <string name="apps_filter_all">Alla appar</string> + <string name="apps_filter_games">Spel</string> + <string name="apps_filter_downloaded">Nedladdade</string> + <string name="apps_filter_system">System</string> + <string name="apps_filter_hidden">Dolda</string> + <string name="apps_hide">Dölj</string> + <string name="apps_unhide">Visa i appar</string> + <string name="apps_shortcut_remove">Ta bort genväg</string> + <string name="apps_pin_title">Lägg till i Appar</string> + <string name="apps_pin_add">Lägg till</string> + <string name="apps_hidden_none">Inga dolda appar.</string> + <string name="apps_sort_name_asc">Namn A–Ö</string> + <string name="apps_sort_name_desc">Namn Ö–A</string> + <string name="apps_sort_installed">Senast installerade</string> + <string name="apps_sort_updated">Senast uppdaterade</string> + <plurals name="apps_count"> + <item quantity="one">%d app</item> + <item quantity="other">%d appar</item> + </plurals> </resources> diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 3fca7f7dd1..9cdb0a55b3 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">อัตราส่วนหน้าจอ</string> <string name="mode_ratio_custom">กำหนดโดยความละเอียดกำหนดเอง</string> <string name="mode_ratio_auto">อัตโนมัติใช้อย่างน้อย 16:9</string> - <string name="mode_fps">ขีดจำกัดเฟรม</string> - <string name="mode_fps_note">จำกัดทั้งเซสชัน หน้าจอจะเปลี่ยนไปใช้อัตรารีเฟรชที่หารขีดจำกัดได้พอดี</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">เอาต์พุต HDR10</string> <string name="mode_hdr_unavailable">ไม่พร้อมใช้งาน: %1$s</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">การสัมผัสของ Steam (ทดลอง)</string> <string name="osc_style_next_session">ปุ่มสัมผัสของ Steam จะเริ่มใช้งานในเซสชัน Steam ถัดไป</string> <string name="osc_steam_layout">รูปแบบปุ่มสัมผัสของ Steam</string> + <string name="screen_keys">ปุ่มบนหน้าจอ</string> + <string name="screen_keys_add">เพิ่มปุ่ม</string> + <string name="screen_key_text">ข้อความ</string> + <string name="screen_key_size">ขนาด</string> + <string name="screen_key_opacity">ความโปร่งใส</string> + <string name="screen_key_type_button">ปุ่ม</string> + <string name="screen_key_shape_trigger">ไก</string> + <string name="screen_key_toggle">สลับ</string> + <string name="screen_key_layout_export">ส่งออก</string> + <string name="screen_key_shape_pill">แคปซูล</string> + <string name="screen_key_shape_round">มน</string> + <string name="screen_key_shape_circle">วงกลม</string> + <string name="screen_key_shape_rect">สี่เหลี่ยม</string> + <string name="screen_key_bind">ปุ่ม</string> + <string name="screen_key_image">รูปภาพ</string> + <string name="screen_key_image_clear">ล้าง</string> + <string name="screen_key_layout">การจัดวาง</string> + <string name="screen_key_layout_save">บันทึก</string> <string name="osc_steam_layout_hint">ย้าย ปรับขนาด หรือซ่อนปุ่มสัมผัสของเกมนี้ บันทึกไปยัง Steam</string> <string name="mode_controller">คอนโทรลเลอร์</string> <string name="mode_controller_hint">วิธีที่ Steam มองเห็นคอนโทรลเลอร์ของคุณ จะมีผลในเซสชันถัดไป</string> @@ -1904,7 +1920,6 @@ <string name="display_filter_live">มีผลทันที ใช้ร่วมกันระหว่าง Steam และเดสก์ท็อป</string> <string name="display_filter_note">FSR, GSR และ NIS จะมีผลเมื่อขยายภาพของเซสชัน เพิ่มความคมชัดเท่านั้นทำงานได้โดยไม่ต้องขยายภาพด้วย</string> <string name="display_sharpness">ความคมชัดของตัวกรอง</string> - <string name="display_frame_rate">อัตราเฟรม</string> <string name="display_look_filter">%1$s ตั้งการปรับขนาดเป็น %2$s</string> <string name="display_match_screen">พอดีหน้าจอ (%1$d×%2$d)</string> <string name="display_follow_screen">ตามหน้าจอ (ปรับขนาดเมื่อพับหรือกาง)</string> @@ -1957,6 +1972,15 @@ <string name="stores_shelf_trending">กำลังเป็นที่นิยม</string> <string name="stores_play">เล่น</string> <string name="stores_install">ติดตั้ง</string> + <string name="bnet_open">เปิด Battle.net</string> + <string name="bnet_dl_starting">กำลังเริ่มตัวดาวน์โหลดของ Blizzard…</string> + <string name="bnet_dl_waiting">กำลังรอให้ Battle.net ปิด…</string> + <string name="bnet_dl_queued">กำลังรอการดาวน์โหลด Battle.net อีกรายการ…</string> + <string name="bnet_dl_client_first">เปิด Battle.net และลงชื่อเข้าใช้หนึ่งครั้ง แล้วติดตั้งเกมจากที่นี่</string> + <string name="bnet_dl_failed">ตัวดาวน์โหลดของ Blizzard หยุดทำงาน: %1$s</string> + <string name="bnet_dl_agent_error">ข้อผิดพลาดของ Blizzard %1$s</string> + <string name="bnet_update">อัปเดต</string> + <string name="bnet_store">เกมของ Blizzard</string> <string name="stores_resume_install">ดำเนินการติดตั้งต่อ</string> <string name="stores_dl_interrupted">ถูกขัดจังหวะ</string> <string name="stores_install_size">ติดตั้ง · %1$s</string> @@ -1994,6 +2018,13 @@ <string name="stores_itch_browse_failed">โหลดเกมจาก itch.io ไม่ได้</string> <string name="stores_itch_archive">ไม่รองรับไฟล์ %1$s</string> <string name="stores_itch_download_failed">itch.io ตอบกลับ HTTP %1$d</string> + <string name="stores_itch_pick_title">เลือกเวอร์ชัน</string> + <string name="stores_itch_pick_none">ไม่พบไฟล์ดาวน์โหลดสำหรับเกมนี้</string> + <string name="stores_itch_pick_failed">โหลดรายการดาวน์โหลดจาก itch.io ไม่ได้</string> + <string name="stores_itch_build_demo">เดโม</string> + <string name="stores_itch_build_open">เปิดบน itch.io</string> + <string name="stores_itch_build_linux_soon">ยังไม่รองรับ</string> + <string name="stores_itch_no_game">ไม่พบเกมนี้บน itch.io</string> <string name="stores_free">ฟรี</string> <string name="stores_resume">ดำเนินการต่อ</string> <string name="stores_refresh">รีเฟรช</string> @@ -2974,6 +3005,25 @@ <string name="spatial_saved_views_hint">มุมมองที่บันทึกไว้สามารถคำนวณใหม่ได้ เริ่มการสอบเทียบใหม่เพื่อบันทึกในระบบพิกัดการติดตามปัจจุบัน</string> <string name="spatial_model_checksum_error">ผลรวมตรวจสอบแบบจำลองมือไม่ตรงกัน</string> <string name="spatial_opencv_load_error">OpenCV ไม่สามารถโหลดได้</string> + <string name="setup_group_memory">หน่วยความจำ</string> + <string name="setup_clear_cached">ปิดแอปที่แคชไว้ก่อนเริ่มเซสชัน</string> + <string name="setup_clear_cached_hint">เมื่อเซสชันเริ่ม DroidDeck จะปิดแอปที่ Android พักไว้ในพื้นหลัง เพื่อให้เกมมีหน่วยความจำมากขึ้น ต้องเปิด Wireless debugging ไว้</string> + <string name="setup_clear_cached_unpaired">ต้องจับคู่ DroidDeck กับ Wireless debugging ก่อน (จับคู่ ด้านล่าง)</string> + <string name="setup_memory_hud">การแสดงหน่วยความจำ</string> + <string name="setup_memory_hud_hint">หน่วยความจำและ swap ที่ใช้อยู่ บนหน้าจอเซสชัน โหมดขั้นสูงจะแยกเป็นเกม, DroidDeck, Android และ GPU</string> + <string name="setup_memory_hud_simple">แบบง่าย</string> + <string name="setup_memory_hud_advanced">ขั้นสูง</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">เกม %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">แอปพื้นหลังระหว่างเซสชัน</string> + <string name="setup_bg_limit_hint">ระหว่างที่เซสชันทำงาน Android จะเก็บแอปไว้ในแคชไม่เกินจำนวนนี้และปิดแอปที่เหลือ เพื่อให้เกมได้หน่วยความจำของแอปเหล่านั้น DroidDeck จะคืนค่าขีดจำกัดเดิมเมื่อเซสชันสิ้นสุด ต้องเปิด Wireless debugging ไว้</string> + <string name="setup_bg_limit_4">ไม่เกิน 4</string> + <string name="setup_bg_limit_1">ไม่เกิน 1</string> + <string name="setup_bg_limit_0">ไม่มี</string> + <string name="setup_adb_pair">Wireless debugging</string> + <string name="setup_adb_pair_hint">จับคู่ DroidDeck กับ Wireless debugging ของ Android สำหรับตัวเลือกด้านบน ขีดจำกัดโพรเซสลูกยังคงปิดอยู่</string> + <string name="setup_adb_pair_button">จับคู่</string> <string name="spatial_restored">กู้คืนมุมมองที่บันทึกไว้แล้ว %1$d รายการ คำนวณการสอบเทียบเพื่อลองอีกครั้ง หรือเริ่มชุดใหม่เพื่อบันทึกข้อมูลเพิ่มเติม</string> <string name="epic_client_missing">ยังไม่ติดตั้ง</string> <string name="epic_client_open">เปิด</string> @@ -3007,6 +3057,48 @@ <string name="library_remove">นำออกจากไลบรารี</string> <string name="library_in">อยู่ในไลบรารี</string> <string name="xbox_filter_show">แสดง</string> + <string name="itch_collections">คอลเลกชัน</string> <string name="xbox_filter_cloud">คลาวด์</string> <string name="stores_xbox_cloud_settings">การตั้งค่าคลาวด์</string> + <string name="apps_search_hint">ค้นหาแอป</string> + <string name="apps_no_match">ไม่มีแอปที่ตรงกับ “%1$s”</string> + <string name="apps_add_widget">เพิ่มวิดเจ็ต</string> + <string name="apps_widgets_loading">กำลังโหลดวิดเจ็ต…</string> + <string name="apps_widgets_none">ไม่มีแอปในอุปกรณ์นี้ที่มีวิดเจ็ต</string> + <string name="apps_widget_wider">กว้างขึ้น</string> + <string name="apps_widget_narrower">แคบลง</string> + <string name="apps_widget_taller">สูงขึ้น</string> + <string name="apps_widget_shorter">เตี้ยลง</string> + <string name="apps_widget_move_earlier">ย้ายไปก่อน</string> + <string name="apps_widget_move_later">ย้ายไปหลัง</string> + <string name="apps_widget_configure">การตั้งค่าวิดเจ็ต</string> + <string name="apps_widget_remove">นำวิดเจ็ตออก</string> + <string name="apps_add_to_folder">เพิ่มลงในโฟลเดอร์</string> + <string name="apps_new_folder">โฟลเดอร์ใหม่</string> + <string name="apps_remove_from_folder">นำออกจากโฟลเดอร์</string> + <string name="apps_app_info">ข้อมูลแอป</string> + <string name="apps_uninstall">ถอนการติดตั้ง</string> + <string name="apps_folder_rename">เปลี่ยนชื่อ</string> + <string name="apps_folder_ungroup">ยกเลิกกลุ่ม</string> + <string name="apps_folder_default">โฟลเดอร์</string> + <string name="apps_folder_name">ชื่อโฟลเดอร์</string> + <string name="apps_filter">แสดง</string> + <string name="apps_filter_all">แอปทั้งหมด</string> + <string name="apps_filter_games">เกม</string> + <string name="apps_filter_downloaded">ที่ดาวน์โหลด</string> + <string name="apps_filter_system">ระบบ</string> + <string name="apps_filter_hidden">ที่ซ่อนไว้</string> + <string name="apps_hide">ซ่อน</string> + <string name="apps_unhide">แสดงในแอป</string> + <string name="apps_shortcut_remove">นำทางลัดออก</string> + <string name="apps_pin_title">เพิ่มลงในแอป</string> + <string name="apps_pin_add">เพิ่ม</string> + <string name="apps_hidden_none">ไม่มีแอปที่ซ่อนไว้</string> + <string name="apps_sort_name_asc">ชื่อ A–Z</string> + <string name="apps_sort_name_desc">ชื่อ Z–A</string> + <string name="apps_sort_installed">ติดตั้งล่าสุด</string> + <string name="apps_sort_updated">อัปเดตล่าสุด</string> + <plurals name="apps_count"> + <item quantity="other">%d แอป</item> + </plurals> </resources> diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 9b917e2339..3dea1e5bc6 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Ekran oranı</string> <string name="mode_ratio_custom">Özel çözünürlüğe göre ayarlanır.</string> <string name="mode_ratio_auto">Otomatik en az 16:9 kullanır.</string> - <string name="mode_fps">Kare sınırı</string> - <string name="mode_fps_note">Tüm oturumu sınırlar. Ekran, sınırın tam katı olan bir yenileme hızına geçer.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 çıkışı</string> <string name="mode_hdr_unavailable">Kullanılamıyor: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam dokunmatik (beta)</string> <string name="osc_style_next_session">Steam\'in dokunmatik kontrolleri sonraki Steam oturumunda başlar</string> <string name="osc_steam_layout">Steam dokunmatik düzeni</string> + <string name="screen_keys">Ekran tuşları</string> + <string name="screen_keys_add">Tuş ekle</string> + <string name="screen_key_text">Metin</string> + <string name="screen_key_size">Boyut</string> + <string name="screen_key_opacity">Opaklık</string> + <string name="screen_key_type_button">Tuş</string> + <string name="screen_key_shape_trigger">Tetik</string> + <string name="screen_key_toggle">Aç/Kapa</string> + <string name="screen_key_layout_export">Dışa aktar</string> + <string name="screen_key_shape_pill">Kapsül</string> + <string name="screen_key_shape_round">Yuvarlak</string> + <string name="screen_key_shape_circle">Daire</string> + <string name="screen_key_shape_rect">Dikdörtgen</string> + <string name="screen_key_bind">Tuş</string> + <string name="screen_key_image">Görsel</string> + <string name="screen_key_image_clear">Temizle</string> + <string name="screen_key_layout">Düzen</string> + <string name="screen_key_layout_save">Kaydet</string> <string name="osc_steam_layout_hint">Bu oyunun dokunmatik kontrollerini taşıyın, boyutlandırın veya gizleyin; Steam\'e kaydedilir</string> <string name="mode_controller">Kumanda</string> <string name="mode_controller_hint">Steam\'in kumandanızı nasıl gördüğü. Sonraki oturumda uygulanır.</string> @@ -1919,7 +1935,6 @@ <string name="display_filter_live">Anında uygulanır. Steam ve Masaüstü tarafından paylaşılır.</string> <string name="display_filter_note">FSR, GSR ve NIS, oturum görüntüsü büyütülürken uygulanır. Yalnızca keskinleştirme büyütme olmadan da çalışır.</string> <string name="display_sharpness">Filtre keskinliği</string> - <string name="display_frame_rate">Kare hızı</string> <string name="display_look_filter">%1$s Ölçeklemeyi %2$s olarak ayarlar.</string> <string name="display_match_screen">Ekrana Uydur (%1$d×%2$d)</string> <string name="display_follow_screen">Ekranı takip et (katlanıp açıldığında yeniden boyutlanır)</string> @@ -1972,6 +1987,15 @@ <string name="stores_shelf_trending">Gündemde</string> <string name="stores_play">Oyna</string> <string name="stores_install">Yükle</string> + <string name="bnet_open">Battle.net\'i aç</string> + <string name="bnet_dl_starting">Blizzard indiricisi başlatılıyor…</string> + <string name="bnet_dl_waiting">Battle.net\'in kapanması bekleniyor…</string> + <string name="bnet_dl_queued">Diğer Battle.net indirmesi bekleniyor…</string> + <string name="bnet_dl_client_first">Battle.net\'i açıp bir kez oturum açın, ardından oyunlarını buradan yükleyin.</string> + <string name="bnet_dl_failed">Blizzard indiricisi durdu: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard hatası %1$s</string> + <string name="bnet_update">Güncelle</string> + <string name="bnet_store">Blizzard oyunları</string> <string name="stores_resume_install">Yüklemeyi sürdür</string> <string name="stores_dl_interrupted">Kesintiye uğradı</string> <string name="stores_install_size">Yükle · %1$s</string> @@ -2009,6 +2033,13 @@ <string name="stores_itch_browse_failed">itch.io oyunları yüklenemedi</string> <string name="stores_itch_archive">%1$s arşivleri desteklenmiyor</string> <string name="stores_itch_download_failed">itch.io HTTP %1$d yanıtı verdi</string> + <string name="stores_itch_pick_title">Bir sürüm seçin</string> + <string name="stores_itch_pick_none">Bu oyun için indirme bulunamadı</string> + <string name="stores_itch_pick_failed">İndirmeler itch.io\'dan yüklenemedi</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">itch.io\'da aç</string> + <string name="stores_itch_build_linux_soon">Henüz desteklenmiyor</string> + <string name="stores_itch_no_game">Bu oyun itch.io\'da bulunamadı</string> <string name="stores_free">Ücretsiz</string> <string name="stores_resume">Sürdür</string> <string name="stores_refresh">Yenile</string> @@ -2999,6 +3030,25 @@ <string name="spatial_saved_views_hint">Kaydedilen görünümler yeniden hesaplanabilir. Geçerli izleme koordinat sistemini yakalamak için yeni bir kalibrasyon başlatın.</string> <string name="spatial_model_checksum_error">El modeli sağlama toplamı uyuşmazlığı</string> <string name="spatial_opencv_load_error">OpenCV yüklenemedi</string> + <string name="setup_group_memory">Bellek</string> + <string name="setup_clear_cached">Oturumdan önce önbellekteki uygulamaları kapat</string> + <string name="setup_clear_cached_hint">Bir oturum başladığında DroidDeck, Android\'in arka planda tuttuğu uygulamaları kapatır; böylece oyuna daha fazla bellek kalır. Kablosuz hata ayıklama açık olmalıdır.</string> + <string name="setup_clear_cached_unpaired">DroidDeck\'in Kablosuz hata ayıklama ile eşlenmesi gerekir (Eşle, aşağıda).</string> + <string name="setup_memory_hud">Bellek göstergesi</string> + <string name="setup_memory_hud_hint">Oturum ekranında kullanılan bellek ve swap. Gelişmiş, bunu oyun, DroidDeck, Android ve GPU olarak ayırır.</string> + <string name="setup_memory_hud_simple">Basit</string> + <string name="setup_memory_hud_advanced">Gelişmiş</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">oyun %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Oturum sırasında arka plan uygulamaları</string> + <string name="setup_bg_limit_hint">Oturum sürerken Android önbellekte en fazla bu kadar uygulama tutar ve gerisini kapatır; böylece onların belleği oyuna kalır. Oturum bittiğinde DroidDeck sınırı eski haline getirir. Kablosuz hata ayıklama açık olmalıdır.</string> + <string name="setup_bg_limit_4">En fazla 4</string> + <string name="setup_bg_limit_1">En fazla 1</string> + <string name="setup_bg_limit_0">Yok</string> + <string name="setup_adb_pair">Kablosuz hata ayıklama</string> + <string name="setup_adb_pair_hint">Yukarıdaki seçenekler için DroidDeck\'i Android\'in Kablosuz hata ayıklama özelliğiyle eşler. Alt süreç sınırı kapalı kalır.</string> + <string name="setup_adb_pair_button">Eşle</string> <string name="tracking_recovery_look">İyi aydınlatılmış bir odada yavaşça etrafa bakın.\nİzleme kameralarını temiz tutun ve mobilyalara veya diğer görünür ayrıntılara doğru bakın.</string> <string name="spatial_need_views">Sabit kalibrasyon hedefinin en az 24 farklı görünümünü yakalayın.</string> <string name="spatial_need_rotation">Akıllı gözlükleri sola ve sağa çevirin, yukarı ve aşağı eğin; dönme olmadan hareket, kamera hizalamasını kalibre edemez.</string> @@ -3034,6 +3084,49 @@ <string name="library_remove">Kütüphane içinden kaldır</string> <string name="library_in">Kütüphane içinde</string> <string name="xbox_filter_show">Göster</string> + <string name="itch_collections">Koleksiyonlar</string> <string name="xbox_filter_cloud">Bulut</string> <string name="stores_xbox_cloud_settings">Bulut ayarları</string> + <string name="apps_search_hint">Uygulama ara</string> + <string name="apps_no_match">“%1$s” ile eşleşen uygulama yok.</string> + <string name="apps_add_widget">Widget ekle</string> + <string name="apps_widgets_loading">Widget’lar yükleniyor…</string> + <string name="apps_widgets_none">Bu cihazdaki hiçbir uygulama widget sunmuyor.</string> + <string name="apps_widget_wider">Daha geniş</string> + <string name="apps_widget_narrower">Daha dar</string> + <string name="apps_widget_taller">Daha uzun</string> + <string name="apps_widget_shorter">Daha kısa</string> + <string name="apps_widget_move_earlier">Öne taşı</string> + <string name="apps_widget_move_later">Arkaya taşı</string> + <string name="apps_widget_configure">Widget ayarları</string> + <string name="apps_widget_remove">Widget’ı kaldır</string> + <string name="apps_add_to_folder">Klasöre ekle</string> + <string name="apps_new_folder">Yeni klasör</string> + <string name="apps_remove_from_folder">Klasörden çıkar</string> + <string name="apps_app_info">Uygulama bilgileri</string> + <string name="apps_uninstall">Kaldır</string> + <string name="apps_folder_rename">Yeniden adlandır</string> + <string name="apps_folder_ungroup">Grubu çöz</string> + <string name="apps_folder_default">Klasör</string> + <string name="apps_folder_name">Klasör adı</string> + <string name="apps_filter">Göster</string> + <string name="apps_filter_all">Tüm uygulamalar</string> + <string name="apps_filter_games">Oyunlar</string> + <string name="apps_filter_downloaded">İndirilenler</string> + <string name="apps_filter_system">Sistem</string> + <string name="apps_filter_hidden">Gizli</string> + <string name="apps_hide">Gizle</string> + <string name="apps_unhide">Uygulamalarda göster</string> + <string name="apps_shortcut_remove">Kısayolu kaldır</string> + <string name="apps_pin_title">Uygulamalara ekle</string> + <string name="apps_pin_add">Ekle</string> + <string name="apps_hidden_none">Gizli uygulama yok.</string> + <string name="apps_sort_name_asc">Ad A–Z</string> + <string name="apps_sort_name_desc">Ad Z–A</string> + <string name="apps_sort_installed">Son yüklenenler</string> + <string name="apps_sort_updated">Son güncellenenler</string> + <plurals name="apps_count"> + <item quantity="one">%d uygulama</item> + <item quantity="other">%d uygulama</item> + </plurals> </resources> diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 8b55100f67..3084c36ba8 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Співвідношення сторін</string> <string name="mode_ratio_custom">Визначається власною роздільною здатністю.</string> <string name="mode_ratio_auto">«Авто» використовує щонайменше 16:9.</string> - <string name="mode_fps">Обмеження кадрів</string> - <string name="mode_fps_note">Обмежує весь сеанс. Екран перемикається на частоту оновлення, кратну цьому обмеженню.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Вивід HDR10</string> <string name="mode_hdr_unavailable">Недоступно: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Сенсорне керування Steam (бета)</string> <string name="osc_style_next_session">Сенсорне керування Steam увімкнеться з наступним сеансом Steam</string> <string name="osc_steam_layout">Розкладка сенсорного керування Steam</string> + <string name="screen_keys">Екранні клавіші</string> + <string name="screen_keys_add">Додати клавішу</string> + <string name="screen_key_text">Текст</string> + <string name="screen_key_size">Розмір</string> + <string name="screen_key_opacity">Непрозорість</string> + <string name="screen_key_type_button">Клавіша</string> + <string name="screen_key_shape_trigger">Тригер</string> + <string name="screen_key_toggle">Перемикання</string> + <string name="screen_key_layout_export">Експорт</string> + <string name="screen_key_shape_pill">Капсула</string> + <string name="screen_key_shape_round">Заокруглення</string> + <string name="screen_key_shape_circle">Коло</string> + <string name="screen_key_shape_rect">Прямокутник</string> + <string name="screen_key_bind">Клавіша</string> + <string name="screen_key_image">Зображення</string> + <string name="screen_key_image_clear">Очистити</string> + <string name="screen_key_layout">Розкладка</string> + <string name="screen_key_layout_save">Зберегти</string> <string name="osc_steam_layout_hint">Переміщуйте, змінюйте розмір або приховуйте сенсорні елементи керування цієї гри; зберігається в Steam</string> <string name="mode_controller">Контролер</string> <string name="mode_controller_hint">Яким Steam бачить ваш контролер. Застосовується в наступному сеансі.</string> @@ -1967,7 +1983,6 @@ <string name="display_filter_live">Застосовується відразу. Спільний для Steam і Робочого столу.</string> <string name="display_filter_note">FSR, GSR і NIS застосовуються під час збільшення зображення сеансу. «Лише різкість» працює і без збільшення.</string> <string name="display_sharpness">Різкість фільтра</string> - <string name="display_frame_rate">Частота кадрів</string> <string name="display_look_filter">%1$s Встановлює масштабування на %2$s.</string> <string name="display_match_screen">Під екран (%1$d×%2$d)</string> <string name="display_follow_screen">Слідувати за екраном (змінює розмір при згортанні чи розгортанні)</string> @@ -2020,6 +2035,15 @@ <string name="stores_shelf_trending">Популярне</string> <string name="stores_play">Грати</string> <string name="stores_install">Встановити</string> + <string name="bnet_open">Відкрити Battle.net</string> + <string name="bnet_dl_starting">Запуск завантажувача Blizzard…</string> + <string name="bnet_dl_waiting">Очікування закриття Battle.net…</string> + <string name="bnet_dl_queued">Очікування іншого завантаження Battle.net…</string> + <string name="bnet_dl_client_first">Відкрийте Battle.net і увійдіть один раз, потім встановлюйте його ігри тут.</string> + <string name="bnet_dl_failed">Завантажувач Blizzard зупинився: %1$s</string> + <string name="bnet_dl_agent_error">Помилка Blizzard %1$s</string> + <string name="bnet_update">Оновити</string> + <string name="bnet_store">Ігри Blizzard</string> <string name="stores_resume_install">Продовжити встановлення</string> <string name="stores_dl_interrupted">Перервано</string> <string name="stores_install_size">Встановити · %1$s</string> @@ -2057,6 +2081,13 @@ <string name="stores_itch_browse_failed">Не вдалося завантажити ігри з itch.io</string> <string name="stores_itch_archive">Архіви %1$s не підтримуються</string> <string name="stores_itch_download_failed">itch.io відповів HTTP %1$d</string> + <string name="stores_itch_pick_title">Виберіть версію</string> + <string name="stores_itch_pick_none">Для цієї гри не знайдено завантажень</string> + <string name="stores_itch_pick_failed">Не вдалося завантажити список файлів з itch.io</string> + <string name="stores_itch_build_demo">Демо</string> + <string name="stores_itch_build_open">Відкрити на itch.io</string> + <string name="stores_itch_build_linux_soon">Ще не підтримується</string> + <string name="stores_itch_no_game">Не вдалося знайти цю гру на itch.io</string> <string name="stores_free">Безкоштовно</string> <string name="stores_resume">Продовжити</string> <string name="stores_refresh">Оновити</string> @@ -3067,6 +3098,25 @@ <string name="spatial_saved_views_hint">Збережені перегляди можна перерахувати. Розпочніть нове калібрування для запису в поточній системі координат відстеження.</string> <string name="spatial_model_checksum_error">Невідповідність контрольної суми моделі руки</string> <string name="spatial_opencv_load_error">Не вдалося завантажити OpenCV</string> + <string name="setup_group_memory">Пам\'ять</string> + <string name="setup_clear_cached">Закривати кешовані додатки перед сеансом</string> + <string name="setup_clear_cached_hint">Коли починається сеанс, DroidDeck закриває додатки, які Android тримає у фоні, щоб грі дісталося більше пам\'яті. Бездротове налагодження має бути ввімкнене.</string> + <string name="setup_clear_cached_unpaired">Потрібно поєднати DroidDeck через бездротове налагодження («Поєднати», нижче).</string> + <string name="setup_memory_hud">Показник пам\'яті</string> + <string name="setup_memory_hud_hint">Використана пам\'ять і swap на екрані сеансу. «Розширений» розподіляє її між грою, DroidDeck, Android і GPU.</string> + <string name="setup_memory_hud_simple">Простий</string> + <string name="setup_memory_hud_advanced">Розширений</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">гра %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Фонові додатки під час сеансу</string> + <string name="setup_bg_limit_hint">Під час сеансу Android тримає в кеші не більше ніж стільки додатків і закриває решту, щоб гра отримала їхню пам\'ять. Коли сеанс завершується, DroidDeck повертає попереднє обмеження. Бездротове налагодження має бути ввімкнене.</string> + <string name="setup_bg_limit_4">Не більше 4</string> + <string name="setup_bg_limit_1">Не більше 1</string> + <string name="setup_bg_limit_0">Жодного</string> + <string name="setup_adb_pair">Бездротове налагодження</string> + <string name="setup_adb_pair_hint">Поєднує DroidDeck з бездротовим налагодженням Android для параметрів вище. Обмеження дочірніх процесів залишається вимкненим.</string> + <string name="setup_adb_pair_button">Поєднати</string> <string name="spatial_gpu_hint">Типово використовується CPU. Режим GPU є експериментальним і може спричинити перезапуск SteamVR. Вибір скидається після перезапуску відстеження.</string> <string name="epic_client_missing">Не встановлено</string> <string name="epic_client_open">Відкрити</string> @@ -3100,6 +3150,51 @@ <string name="library_remove">Прибрати з бібліотеки</string> <string name="library_in">У бібліотеці</string> <string name="xbox_filter_show">Показати</string> + <string name="itch_collections">Колекції</string> <string name="xbox_filter_cloud">Хмара</string> <string name="stores_xbox_cloud_settings">Налаштування хмари</string> + <string name="apps_search_hint">Пошук застосунків</string> + <string name="apps_no_match">Немає застосунків за запитом «%1$s».</string> + <string name="apps_add_widget">Додати віджет</string> + <string name="apps_widgets_loading">Завантаження віджетів…</string> + <string name="apps_widgets_none">На цьому пристрої немає застосунків із віджетами.</string> + <string name="apps_widget_wider">Ширше</string> + <string name="apps_widget_narrower">Вужче</string> + <string name="apps_widget_taller">Вище</string> + <string name="apps_widget_shorter">Нижче</string> + <string name="apps_widget_move_earlier">Перемістити раніше</string> + <string name="apps_widget_move_later">Перемістити пізніше</string> + <string name="apps_widget_configure">Налаштування віджета</string> + <string name="apps_widget_remove">Вилучити віджет</string> + <string name="apps_add_to_folder">Додати до папки</string> + <string name="apps_new_folder">Нова папка</string> + <string name="apps_remove_from_folder">Вилучити з папки</string> + <string name="apps_app_info">Про застосунок</string> + <string name="apps_uninstall">Видалити</string> + <string name="apps_folder_rename">Перейменувати</string> + <string name="apps_folder_ungroup">Розгрупувати</string> + <string name="apps_folder_default">Папка</string> + <string name="apps_folder_name">Назва папки</string> + <string name="apps_filter">Показати</string> + <string name="apps_filter_all">Усі застосунки</string> + <string name="apps_filter_games">Ігри</string> + <string name="apps_filter_downloaded">Завантажені</string> + <string name="apps_filter_system">Системні</string> + <string name="apps_filter_hidden">Приховані</string> + <string name="apps_hide">Приховати</string> + <string name="apps_unhide">Показувати в застосунках</string> + <string name="apps_shortcut_remove">Вилучити ярлик</string> + <string name="apps_pin_title">Додати до застосунків</string> + <string name="apps_pin_add">Додати</string> + <string name="apps_hidden_none">Прихованих застосунків немає.</string> + <string name="apps_sort_name_asc">Назва А–Я</string> + <string name="apps_sort_name_desc">Назва Я–А</string> + <string name="apps_sort_installed">Нещодавно встановлені</string> + <string name="apps_sort_updated">Нещодавно оновлені</string> + <plurals name="apps_count"> + <item quantity="one">%d застосунок</item> + <item quantity="few">%d застосунки</item> + <item quantity="many">%d застосунків</item> + <item quantity="other">%d застосунку</item> + </plurals> </resources> diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 0bde8b4a9f..0cfe20866d 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">Tỷ lệ màn hình</string> <string name="mode_ratio_custom">Được đặt theo độ phân giải tùy chỉnh.</string> <string name="mode_ratio_auto">Tự động dùng tối thiểu 16:9.</string> - <string name="mode_fps">Giới hạn khung hình</string> - <string name="mode_fps_note">Giới hạn toàn bộ phiên. Màn hình chuyển sang tốc độ làm mới mà giới hạn chia hết.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Xuất HDR10</string> <string name="mode_hdr_unavailable">Không khả dụng: %1$s.</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Chạm Steam (beta)</string> <string name="osc_style_next_session">Các nút chạm của Steam bắt đầu từ phiên Steam kế tiếp</string> <string name="osc_steam_layout">Bố cục chạm Steam</string> + <string name="screen_keys">Phím trên màn hình</string> + <string name="screen_keys_add">Thêm phím</string> + <string name="screen_key_text">Văn bản</string> + <string name="screen_key_size">Kích thước</string> + <string name="screen_key_opacity">Độ mờ</string> + <string name="screen_key_type_button">Phím</string> + <string name="screen_key_shape_trigger">Cò</string> + <string name="screen_key_toggle">Bật tắt</string> + <string name="screen_key_layout_export">Xuất</string> + <string name="screen_key_shape_pill">Viên nang</string> + <string name="screen_key_shape_round">Bo tròn</string> + <string name="screen_key_shape_circle">Tròn</string> + <string name="screen_key_shape_rect">Chữ nhật</string> + <string name="screen_key_bind">Phím</string> + <string name="screen_key_image">Hình ảnh</string> + <string name="screen_key_image_clear">Xóa</string> + <string name="screen_key_layout">Bố cục</string> + <string name="screen_key_layout_save">Lưu</string> <string name="osc_steam_layout_hint">Di chuyển, đổi kích thước hoặc ẩn các nút chạm của game này; được lưu vào Steam</string> <string name="mode_controller">Tay cầm</string> <string name="mode_controller_hint">Cách Steam nhận dạng tay cầm của bạn. Áp dụng từ phiên sau.</string> @@ -1904,7 +1920,6 @@ <string name="display_filter_live">Áp dụng ngay. Dùng chung cho Steam và Desktop.</string> <string name="display_filter_note">FSR, GSR và NIS áp dụng khi phóng to hình ảnh phiên. Chỉ làm nét cũng hoạt động mà không cần phóng to.</string> <string name="display_sharpness">Độ sắc nét bộ lọc</string> - <string name="display_frame_rate">Tốc độ khung hình</string> <string name="display_look_filter">%1$s Đặt chia tỷ lệ thành %2$s.</string> <string name="display_match_screen">Khớp màn hình (%1$d×%2$d)</string> <string name="display_follow_screen">Theo màn hình (đổi kích thước khi gập hoặc mở)</string> @@ -1957,6 +1972,15 @@ <string name="stores_shelf_trending">Xu hướng</string> <string name="stores_play">Chơi</string> <string name="stores_install">Cài</string> + <string name="bnet_open">Mở Battle.net</string> + <string name="bnet_dl_starting">Đang khởi động trình tải xuống của Blizzard…</string> + <string name="bnet_dl_waiting">Đang chờ Battle.net đóng…</string> + <string name="bnet_dl_queued">Đang chờ lượt tải Battle.net khác…</string> + <string name="bnet_dl_client_first">Mở Battle.net và đăng nhập một lần, sau đó cài trò chơi của nó tại đây.</string> + <string name="bnet_dl_failed">Trình tải xuống của Blizzard đã dừng: %1$s</string> + <string name="bnet_dl_agent_error">Lỗi Blizzard %1$s</string> + <string name="bnet_update">Cập nhật</string> + <string name="bnet_store">Trò chơi Blizzard</string> <string name="stores_resume_install">Tiếp tục cài</string> <string name="stores_dl_interrupted">Bị gián đoạn</string> <string name="stores_install_size">Cài · %1$s</string> @@ -1994,6 +2018,13 @@ <string name="stores_itch_browse_failed">Không tải được game từ itch.io</string> <string name="stores_itch_archive">Không hỗ trợ tệp %1$s</string> <string name="stores_itch_download_failed">itch.io trả về HTTP %1$d</string> + <string name="stores_itch_pick_title">Chọn phiên bản</string> + <string name="stores_itch_pick_none">Không tìm thấy bản tải xuống cho trò chơi này</string> + <string name="stores_itch_pick_failed">Không thể tải danh sách tải xuống từ itch.io</string> + <string name="stores_itch_build_demo">Bản demo</string> + <string name="stores_itch_build_open">Mở trên itch.io</string> + <string name="stores_itch_build_linux_soon">Chưa được hỗ trợ</string> + <string name="stores_itch_no_game">Không tìm thấy trò chơi này trên itch.io</string> <string name="stores_free">Miễn phí</string> <string name="stores_resume">Tiếp tục</string> <string name="stores_refresh">Làm mới</string> @@ -2974,6 +3005,25 @@ <string name="spatial_saved_views_hint">Các lượt xem đã lưu có thể được tính toán lại. Bắt đầu hiệu chuẩn mới để chụp trong hệ tọa độ theo dõi hiện tại.</string> <string name="spatial_model_checksum_error">Tổng kiểm tra mô hình bàn tay không khớp</string> <string name="spatial_opencv_load_error">OpenCV không thể tải</string> + <string name="setup_group_memory">Bộ nhớ</string> + <string name="setup_clear_cached">Đóng ứng dụng đã lưu đệm trước phiên</string> + <string name="setup_clear_cached_hint">Khi phiên bắt đầu, DroidDeck đóng các ứng dụng mà Android giữ ở nền để game có thêm bộ nhớ. Phải bật Gỡ lỗi qua mạng không dây.</string> + <string name="setup_clear_cached_unpaired">Cần ghép nối DroidDeck với Gỡ lỗi qua mạng không dây (Ghép nối, bên dưới).</string> + <string name="setup_memory_hud">Chỉ báo bộ nhớ</string> + <string name="setup_memory_hud_hint">Bộ nhớ và swap đang dùng, trên màn hình phiên. Nâng cao chia theo game, DroidDeck, Android và GPU.</string> + <string name="setup_memory_hud_simple">Đơn giản</string> + <string name="setup_memory_hud_advanced">Nâng cao</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">game %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Ứng dụng nền trong phiên</string> + <string name="setup_bg_limit_hint">Trong khi phiên chạy, Android chỉ giữ tối đa chừng này ứng dụng trong bộ nhớ đệm và đóng phần còn lại để game có bộ nhớ của chúng. DroidDeck đặt lại giới hạn như cũ khi phiên kết thúc. Phải bật Gỡ lỗi qua mạng không dây.</string> + <string name="setup_bg_limit_4">Tối đa 4</string> + <string name="setup_bg_limit_1">Tối đa 1</string> + <string name="setup_bg_limit_0">Không có</string> + <string name="setup_adb_pair">Gỡ lỗi qua mạng không dây</string> + <string name="setup_adb_pair_hint">Ghép nối DroidDeck với Gỡ lỗi qua mạng không dây của Android cho các tùy chọn ở trên. Giới hạn tiến trình con vẫn tắt.</string> + <string name="setup_adb_pair_button">Ghép nối</string> <string name="tracking_recovery_look">Nhìn xung quanh chậm rãi trong phòng có đủ ánh sáng.\nGiữ cho camera theo dõi rõ ràng và hướng về phía đồ nội thất hoặc các chi tiết có thể nhìn thấy khác.</string> <string name="epic_client_missing">Chưa cài</string> <string name="epic_client_open">Mở</string> @@ -3007,6 +3057,48 @@ <string name="library_remove">Xóa khỏi Thư viện</string> <string name="library_in">Trong Thư viện</string> <string name="xbox_filter_show">Hiển thị</string> + <string name="itch_collections">Bộ sưu tập</string> <string name="xbox_filter_cloud">Đám mây</string> <string name="stores_xbox_cloud_settings">Cài đặt đám mây</string> + <string name="apps_search_hint">Tìm ứng dụng</string> + <string name="apps_no_match">Không có ứng dụng nào khớp với “%1$s”.</string> + <string name="apps_add_widget">Thêm tiện ích</string> + <string name="apps_widgets_loading">Đang tải tiện ích…</string> + <string name="apps_widgets_none">Không có ứng dụng nào trên thiết bị này cung cấp tiện ích.</string> + <string name="apps_widget_wider">Rộng hơn</string> + <string name="apps_widget_narrower">Hẹp hơn</string> + <string name="apps_widget_taller">Cao hơn</string> + <string name="apps_widget_shorter">Thấp hơn</string> + <string name="apps_widget_move_earlier">Chuyển lên trước</string> + <string name="apps_widget_move_later">Chuyển ra sau</string> + <string name="apps_widget_configure">Cài đặt tiện ích</string> + <string name="apps_widget_remove">Xóa tiện ích</string> + <string name="apps_add_to_folder">Thêm vào thư mục</string> + <string name="apps_new_folder">Thư mục mới</string> + <string name="apps_remove_from_folder">Xóa khỏi thư mục</string> + <string name="apps_app_info">Thông tin ứng dụng</string> + <string name="apps_uninstall">Gỡ cài đặt</string> + <string name="apps_folder_rename">Đổi tên</string> + <string name="apps_folder_ungroup">Bỏ nhóm</string> + <string name="apps_folder_default">Thư mục</string> + <string name="apps_folder_name">Tên thư mục</string> + <string name="apps_filter">Hiển thị</string> + <string name="apps_filter_all">Tất cả ứng dụng</string> + <string name="apps_filter_games">Trò chơi</string> + <string name="apps_filter_downloaded">Đã tải xuống</string> + <string name="apps_filter_system">Hệ thống</string> + <string name="apps_filter_hidden">Đã ẩn</string> + <string name="apps_hide">Ẩn</string> + <string name="apps_unhide">Hiện trong ứng dụng</string> + <string name="apps_shortcut_remove">Xóa lối tắt</string> + <string name="apps_pin_title">Thêm vào Ứng dụng</string> + <string name="apps_pin_add">Thêm</string> + <string name="apps_hidden_none">Không có ứng dụng nào bị ẩn.</string> + <string name="apps_sort_name_asc">Tên A–Z</string> + <string name="apps_sort_name_desc">Tên Z–A</string> + <string name="apps_sort_installed">Mới cài đặt</string> + <string name="apps_sort_updated">Mới cập nhật</string> + <plurals name="apps_count"> + <item quantity="other">%d ứng dụng</item> + </plurals> </resources> diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index a2ca7e8574..416839104e 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">屏幕比例</string> <string name="mode_ratio_custom">由自定义分辨率决定。</string> <string name="mode_ratio_auto">自动模式至少使用 16:9。</string> - <string name="mode_fps">帧率上限</string> - <string name="mode_fps_note">限制整个会话。显示器会切换到能被该上限整除的刷新率。</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 输出</string> <string name="mode_hdr_unavailable">不可用:%1$s。</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam 触控(测试版)</string> <string name="osc_style_next_session">Steam 的触控按键将从下次 Steam 会话开始生效</string> <string name="osc_steam_layout">Steam 触控布局</string> + <string name="screen_keys">屏幕按键</string> + <string name="screen_keys_add">添加按键</string> + <string name="screen_key_text">文本</string> + <string name="screen_key_size">大小</string> + <string name="screen_key_opacity">透明</string> + <string name="screen_key_type_button">单键</string> + <string name="screen_key_shape_trigger">扳机</string> + <string name="screen_key_toggle">切换</string> + <string name="screen_key_layout_export">导出</string> + <string name="screen_key_shape_pill">胶囊</string> + <string name="screen_key_shape_round">圆角</string> + <string name="screen_key_shape_circle">圆形</string> + <string name="screen_key_shape_rect">矩形</string> + <string name="screen_key_bind">绑定</string> + <string name="screen_key_image">图片</string> + <string name="screen_key_image_clear">清除</string> + <string name="screen_key_layout">布局</string> + <string name="screen_key_layout_save">保存</string> <string name="osc_steam_layout_hint">移动、调整大小或隐藏此游戏的触控按键;保存到 Steam</string> <string name="mode_controller">手柄</string> <string name="mode_controller_hint">决定 Steam 把你的手柄识别为哪种类型,将在下次会话生效。</string> @@ -838,6 +854,7 @@ <string name="setup_download_source_custom">自定义前缀</string> <string name="setup_download_mirror">镜像站点</string> <string name="setup_download_prefix">前缀</string> + <string name="setup_download_proxy">HTTP 代理</string> <string name="setup_tool_files">文件</string> <string name="setup_tool_files_hint">浏览和管理文件</string> <string name="setup_tool_protons">Proton 版本</string> @@ -1983,7 +2000,6 @@ <string name="display_filter_live">即时生效。由 Steam 和桌面共享。</string> <string name="display_filter_note">FSR、GSR 和 NIS 在放大会话画面时生效。“仅锐化”在不放大时也可用。</string> <string name="display_sharpness">滤镜锐度</string> - <string name="display_frame_rate">帧率</string> <string name="display_look_filter">%1$s 将缩放设为 %2$s。</string> <string name="display_match_screen">匹配屏幕(%1$d×%2$d)</string> <string name="display_follow_screen">跟随屏幕(折叠或展开时调整大小)</string> @@ -2036,6 +2052,15 @@ <string name="stores_shelf_trending">趋势</string> <string name="stores_play">游玩</string> <string name="stores_install">安装</string> + <string name="bnet_open">打开 Battle.net</string> + <string name="bnet_dl_starting">正在启动暴雪下载器…</string> + <string name="bnet_dl_waiting">正在等待 Battle.net 关闭…</string> + <string name="bnet_dl_queued">正在等待另一个 Battle.net 下载…</string> + <string name="bnet_dl_client_first">请先打开 Battle.net 并登录一次,然后在这里安装其游戏。</string> + <string name="bnet_dl_failed">暴雪下载器已停止:%1$s</string> + <string name="bnet_dl_agent_error">暴雪错误 %1$s</string> + <string name="bnet_update">更新</string> + <string name="bnet_store">暴雪游戏</string> <string name="stores_resume_install">继续安装</string> <string name="stores_dl_interrupted">已中断</string> <string name="stores_install_size">安装 · %1$s</string> @@ -2073,6 +2098,13 @@ <string name="stores_itch_browse_failed">无法从 itch.io 加载游戏</string> <string name="stores_itch_archive">不支持 %1$s 压缩包</string> <string name="stores_itch_download_failed">itch.io 返回 HTTP %1$d</string> + <string name="stores_itch_pick_title">选择版本</string> + <string name="stores_itch_pick_none">未找到此游戏的下载</string> + <string name="stores_itch_pick_failed">无法从 itch.io 加载下载内容</string> + <string name="stores_itch_build_demo">试玩版</string> + <string name="stores_itch_build_open">在 itch.io 上打开</string> + <string name="stores_itch_build_linux_soon">暂不支持</string> + <string name="stores_itch_no_game">在 itch.io 上找不到这款游戏</string> <string name="stores_free">免费</string> <string name="stores_resume">继续</string> <string name="stores_refresh">刷新</string> @@ -2978,6 +3010,25 @@ <string name="glasses_6dof">6DoF 虚拟屏幕</string> <string name="tracking_recovery_look">在光线充足的房间内缓慢环顾四周。\n不要遮挡追踪摄像头,并面向家具等有明显细节的物体。</string> <string name="spatial_print_job">DroidDeck ChArUco 30 mm</string> + <string name="setup_group_memory">内存</string> + <string name="setup_clear_cached">会话前关闭缓存的应用</string> + <string name="setup_clear_cached_hint">会话开始时关闭 Android 留在后台的应用,让游戏有更多内存可用。需要开启无线调试。</string> + <string name="setup_clear_cached_unpaired">需要先将 DroidDeck 与无线调试配对(见下方“配对”)。</string> + <string name="setup_memory_hud">内存读数</string> + <string name="setup_memory_hud_hint">在会话画面上显示已用内存和交换空间。高级模式会分别显示游戏、DroidDeck、Android 和 GPU。</string> + <string name="setup_memory_hud_simple">简单</string> + <string name="setup_memory_hud_advanced">高级</string> + <string name="memory_hud_simple">内存 %1$s/%2$s GB · 交换 %3$s/%4$s GB</string> + <string name="memory_hud_split">游戏 %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">会话期间的后台应用</string> + <string name="setup_bg_limit_hint">会话运行期间,Android 最多缓存这么多个应用并关闭其余应用,让游戏使用它们的内存。会话结束后恢复原状。需要开启无线调试。</string> + <string name="setup_bg_limit_4">最多 4 个</string> + <string name="setup_bg_limit_1">最多 1 个</string> + <string name="setup_bg_limit_0">无</string> + <string name="setup_adb_pair">无线调试</string> + <string name="setup_adb_pair_hint">为上面的选项将 DroidDeck 与 Android 无线调试配对。子进程限制保持关闭。</string> + <string name="setup_adb_pair_button">配对</string> <string name="epic_client_missing">未安装</string> <string name="epic_client_open">打开</string> <string name="epic_client_install">安装</string> @@ -3010,6 +3061,48 @@ <string name="library_remove">从游戏库移除</string> <string name="library_in">已在游戏库</string> <string name="xbox_filter_show">显示</string> + <string name="itch_collections">收藏集</string> <string name="xbox_filter_cloud">云</string> <string name="stores_xbox_cloud_settings">云设置</string> + <string name="apps_search_hint">搜索应用</string> + <string name="apps_no_match">没有与“%1$s”匹配的应用。</string> + <string name="apps_add_widget">添加微件</string> + <string name="apps_widgets_loading">正在加载微件…</string> + <string name="apps_widgets_none">此设备上没有提供微件的应用。</string> + <string name="apps_widget_wider">加宽</string> + <string name="apps_widget_narrower">缩窄</string> + <string name="apps_widget_taller">加高</string> + <string name="apps_widget_shorter">降低</string> + <string name="apps_widget_move_earlier">前移</string> + <string name="apps_widget_move_later">后移</string> + <string name="apps_widget_configure">微件设置</string> + <string name="apps_widget_remove">移除微件</string> + <string name="apps_add_to_folder">添加到文件夹</string> + <string name="apps_new_folder">新建文件夹</string> + <string name="apps_remove_from_folder">从文件夹中移除</string> + <string name="apps_app_info">应用信息</string> + <string name="apps_uninstall">卸载</string> + <string name="apps_folder_rename">重命名</string> + <string name="apps_folder_ungroup">取消分组</string> + <string name="apps_folder_default">文件夹</string> + <string name="apps_folder_name">文件夹名称</string> + <string name="apps_filter">显示</string> + <string name="apps_filter_all">所有应用</string> + <string name="apps_filter_games">游戏</string> + <string name="apps_filter_downloaded">已下载</string> + <string name="apps_filter_system">系统</string> + <string name="apps_filter_hidden">已隐藏</string> + <string name="apps_hide">隐藏</string> + <string name="apps_unhide">在应用中显示</string> + <string name="apps_shortcut_remove">移除快捷方式</string> + <string name="apps_pin_title">添加到应用</string> + <string name="apps_pin_add">添加</string> + <string name="apps_hidden_none">没有隐藏的应用。</string> + <string name="apps_sort_name_asc">名称 A–Z</string> + <string name="apps_sort_name_desc">名称 Z–A</string> + <string name="apps_sort_installed">最近安装</string> + <string name="apps_sort_updated">最近更新</string> + <plurals name="apps_count"> + <item quantity="other">%d 个应用</item> + </plurals> </resources> diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 82daf9cca2..ee0daff391 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">螢幕比例</string> <string name="mode_ratio_custom">由自訂解像度決定。</string> <string name="mode_ratio_auto">自動模式至少使用 16:9。</string> - <string name="mode_fps">幀率限制</string> - <string name="mode_fps_note">限制整個會話的幀率。螢幕會切換至能被此上限整除的刷新率。</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 輸出</string> <string name="mode_hdr_unavailable">不可用:%1$s。</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam 觸控(測試版)</string> <string name="osc_style_next_session">Steam 的觸控控制會在下次 Steam 會話啟用</string> <string name="osc_steam_layout">Steam 觸控佈局</string> + <string name="screen_keys">螢幕按鍵</string> + <string name="screen_keys_add">新增按鍵</string> + <string name="screen_key_text">文本</string> + <string name="screen_key_size">大小</string> + <string name="screen_key_opacity">透明</string> + <string name="screen_key_type_button">單鍵</string> + <string name="screen_key_shape_trigger">扳機</string> + <string name="screen_key_toggle">切換</string> + <string name="screen_key_layout_export">匯出</string> + <string name="screen_key_shape_pill">膠囊</string> + <string name="screen_key_shape_round">圓角</string> + <string name="screen_key_shape_circle">圓形</string> + <string name="screen_key_shape_rect">矩形</string> + <string name="screen_key_bind">綁定</string> + <string name="screen_key_image">圖片</string> + <string name="screen_key_image_clear">清除</string> + <string name="screen_key_layout">佈局</string> + <string name="screen_key_layout_save">儲存</string> <string name="osc_steam_layout_hint">移動、調整大小或隱藏此遊戲的觸控控制;會儲存至 Steam</string> <string name="mode_controller">控制器</string> <string name="mode_controller_hint">Steam 如何識別你的控制器。下次會話生效。</string> @@ -1907,7 +1923,6 @@ <string name="display_filter_live">即時生效。Steam 和桌面共用。</string> <string name="display_filter_note">FSR、GSR 和 NIS 會在放大會話畫面時套用。「只銳化」不放大也能使用。</string> <string name="display_sharpness">濾鏡銳利度</string> - <string name="display_frame_rate">幀率</string> <string name="display_look_filter">%1$s 將縮放設為 %2$s。</string> <string name="display_match_screen">配合螢幕(%1$d×%2$d)</string> <string name="display_follow_screen">跟隨螢幕(摺疊或展開時調整大小)</string> @@ -1960,6 +1975,15 @@ <string name="stores_shelf_trending">趨勢</string> <string name="stores_play">開啟遊戲</string> <string name="stores_install">安裝</string> + <string name="bnet_open">開啟 Battle.net</string> + <string name="bnet_dl_starting">正在啟動暴雪下載器…</string> + <string name="bnet_dl_waiting">正在等待 Battle.net 關閉…</string> + <string name="bnet_dl_queued">正在等待另一個 Battle.net 下載…</string> + <string name="bnet_dl_client_first">請先開啟 Battle.net 並登入一次,然後在這裡安裝其遊戲。</string> + <string name="bnet_dl_failed">暴雪下載器已停止:%1$s</string> + <string name="bnet_dl_agent_error">暴雪錯誤 %1$s</string> + <string name="bnet_update">更新</string> + <string name="bnet_store">Blizzard 遊戲</string> <string name="stores_resume_install">繼續安裝</string> <string name="stores_dl_interrupted">已中斷</string> <string name="stores_install_size">安裝 · %1$s</string> @@ -1997,6 +2021,13 @@ <string name="stores_itch_browse_failed">無法從 itch.io 載入遊戲</string> <string name="stores_itch_archive">不支援 %1$s 壓縮檔</string> <string name="stores_itch_download_failed">itch.io 回應 HTTP %1$d</string> + <string name="stores_itch_pick_title">選擇版本</string> + <string name="stores_itch_pick_none">找不到此遊戲的下載</string> + <string name="stores_itch_pick_failed">無法從 itch.io 載入下載內容</string> + <string name="stores_itch_build_demo">試玩版</string> + <string name="stores_itch_build_open">在 itch.io 開啟</string> + <string name="stores_itch_build_linux_soon">暫不支援</string> + <string name="stores_itch_no_game">在 itch.io 找不到這款遊戲</string> <string name="stores_free">免費</string> <string name="stores_resume">繼續</string> <string name="stores_refresh">重新整理</string> @@ -2978,6 +3009,25 @@ <string name="glasses_6dof">6DoF 虛擬螢幕</string> <string name="tracking_recovery_look">在光線充足的房間內緩慢環顧四周。\n不要遮擋追蹤攝影機,並面向家具等有明顯細節的物體。</string> <string name="spatial_print_job">DroidDeck ChArUco 30 mm</string> + <string name="setup_group_memory">記憶體</string> + <string name="setup_clear_cached">工作階段前關閉快取的應用程式</string> + <string name="setup_clear_cached_hint">工作階段開始時關閉 Android 留在背景的應用程式,讓遊戲有更多記憶體可用。需要開啟無線偵錯。</string> + <string name="setup_clear_cached_unpaired">需要先將 DroidDeck 與無線偵錯配對(見下方「配對」)。</string> + <string name="setup_memory_hud">記憶體讀數</string> + <string name="setup_memory_hud_hint">在工作階段畫面上顯示已用記憶體和交換空間。進階模式會分別顯示遊戲、DroidDeck、Android 和 GPU。</string> + <string name="setup_memory_hud_simple">簡單</string> + <string name="setup_memory_hud_advanced">進階</string> + <string name="memory_hud_simple">記憶體 %1$s/%2$s GB · 交換 %3$s/%4$s GB</string> + <string name="memory_hud_split">遊戲 %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">工作階段期間的背景應用程式</string> + <string name="setup_bg_limit_hint">工作階段執行期間,Android 最多快取這麼多個應用程式並關閉其餘的,讓遊戲使用它們的記憶體。工作階段結束後還原。需要開啟無線偵錯。</string> + <string name="setup_bg_limit_4">最多 4 個</string> + <string name="setup_bg_limit_1">最多 1 個</string> + <string name="setup_bg_limit_0">無</string> + <string name="setup_adb_pair">無線偵錯</string> + <string name="setup_adb_pair_hint">為上面的選項將 DroidDeck 與 Android 無線偵錯配對。子進程限制保持關閉。</string> + <string name="setup_adb_pair_button">配對</string> <string name="epic_client_missing">未安裝</string> <string name="epic_client_open">開啟</string> <string name="epic_client_install">安裝</string> @@ -3010,6 +3060,48 @@ <string name="library_remove">從收藏庫移除</string> <string name="library_in">已在收藏庫</string> <string name="xbox_filter_show">顯示</string> + <string name="itch_collections">收藏集</string> <string name="xbox_filter_cloud">雲端</string> <string name="stores_xbox_cloud_settings">雲端設定</string> + <string name="apps_search_hint">搜尋應用程式</string> + <string name="apps_no_match">沒有符合「%1$s」的應用程式。</string> + <string name="apps_add_widget">新增小工具</string> + <string name="apps_widgets_loading">正在載入小工具…</string> + <string name="apps_widgets_none">此裝置上沒有提供小工具的應用程式。</string> + <string name="apps_widget_wider">加闊</string> + <string name="apps_widget_narrower">收窄</string> + <string name="apps_widget_taller">加高</string> + <string name="apps_widget_shorter">降低</string> + <string name="apps_widget_move_earlier">向前移</string> + <string name="apps_widget_move_later">向後移</string> + <string name="apps_widget_configure">小工具設定</string> + <string name="apps_widget_remove">移除小工具</string> + <string name="apps_add_to_folder">加入資料夾</string> + <string name="apps_new_folder">新資料夾</string> + <string name="apps_remove_from_folder">從資料夾移除</string> + <string name="apps_app_info">應用程式資料</string> + <string name="apps_uninstall">解除安裝</string> + <string name="apps_folder_rename">重新命名</string> + <string name="apps_folder_ungroup">取消組合</string> + <string name="apps_folder_default">資料夾</string> + <string name="apps_folder_name">資料夾名稱</string> + <string name="apps_filter">顯示</string> + <string name="apps_filter_all">所有應用程式</string> + <string name="apps_filter_games">遊戲</string> + <string name="apps_filter_downloaded">已下載</string> + <string name="apps_filter_system">系統</string> + <string name="apps_filter_hidden">已隱藏</string> + <string name="apps_hide">隱藏</string> + <string name="apps_unhide">在應用程式中顯示</string> + <string name="apps_shortcut_remove">移除捷徑</string> + <string name="apps_pin_title">加入應用程式</string> + <string name="apps_pin_add">新增</string> + <string name="apps_hidden_none">沒有隱藏的應用程式。</string> + <string name="apps_sort_name_asc">名稱 A–Z</string> + <string name="apps_sort_name_desc">名稱 Z–A</string> + <string name="apps_sort_installed">最近安裝</string> + <string name="apps_sort_updated">最近更新</string> + <plurals name="apps_count"> + <item quantity="other">%d 個應用程式</item> + </plurals> </resources> diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 26d108539b..27effeacb7 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -247,8 +247,6 @@ <string name="mode_ratio">螢幕比例</string> <string name="mode_ratio_custom">由自訂解析度設定。</string> <string name="mode_ratio_auto">自動模式至少使用 16:9。</string> - <string name="mode_fps">影格率限制</string> - <string name="mode_fps_note">限制整個工作階段的影格率。顯示器會切換到能夠被該上限整除的重新整理率。</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 輸出</string> <string name="mode_hdr_unavailable">無法使用:%1$s。</string> @@ -267,6 +265,24 @@ <string name="osc_steam_touch">Steam 觸控(測試版)</string> <string name="osc_style_next_session">Steam 觸控控制會在下次 Steam 工作階段啟用</string> <string name="osc_steam_layout">Steam 觸控版面配置</string> + <string name="screen_keys">螢幕按鍵</string> + <string name="screen_keys_add">新增按鍵</string> + <string name="screen_key_text">文本</string> + <string name="screen_key_size">大小</string> + <string name="screen_key_opacity">透明</string> + <string name="screen_key_type_button">單鍵</string> + <string name="screen_key_shape_trigger">扳機</string> + <string name="screen_key_toggle">切換</string> + <string name="screen_key_layout_export">匯出</string> + <string name="screen_key_shape_pill">膠囊</string> + <string name="screen_key_shape_round">圓角</string> + <string name="screen_key_shape_circle">圓形</string> + <string name="screen_key_shape_rect">矩形</string> + <string name="screen_key_bind">綁定</string> + <string name="screen_key_image">圖片</string> + <string name="screen_key_image_clear">清除</string> + <string name="screen_key_layout">版面配置</string> + <string name="screen_key_layout_save">儲存</string> <string name="osc_steam_layout_hint">移動、調整大小或隱藏這款遊戲的觸控控制;會儲存到 Steam</string> <string name="mode_controller">控制器</string> <string name="mode_controller_hint">Steam 辨識你的控制器的方式。下次工作階段生效。</string> @@ -1907,7 +1923,6 @@ <string name="display_filter_live">立即生效。Steam 和桌面共用。</string> <string name="display_filter_note">FSR、GSR 和 NIS 會在放大工作階段畫面時套用。「僅銳化」不放大也能使用。</string> <string name="display_sharpness">濾鏡銳利度</string> - <string name="display_frame_rate">影格率</string> <string name="display_look_filter">%1$s 將縮放設為 %2$s。</string> <string name="display_match_screen">符合螢幕(%1$d×%2$d)</string> <string name="display_follow_screen">跟隨螢幕(摺疊或展開時調整大小)</string> @@ -1960,6 +1975,15 @@ <string name="stores_shelf_trending">趨勢</string> <string name="stores_play">執行</string> <string name="stores_install">安裝</string> + <string name="bnet_open">開啟 Battle.net</string> + <string name="bnet_dl_starting">正在啟動暴雪下載器…</string> + <string name="bnet_dl_waiting">正在等待 Battle.net 關閉…</string> + <string name="bnet_dl_queued">正在等待另一個 Battle.net 下載…</string> + <string name="bnet_dl_client_first">請先開啟 Battle.net 並登入一次,然後在這裡安裝其遊戲。</string> + <string name="bnet_dl_failed">暴雪下載器已停止:%1$s</string> + <string name="bnet_dl_agent_error">暴雪錯誤 %1$s</string> + <string name="bnet_update">更新</string> + <string name="bnet_store">Blizzard 遊戲</string> <string name="stores_resume_install">繼續安裝</string> <string name="stores_dl_interrupted">已中斷</string> <string name="stores_install_size">安裝 · %1$s</string> @@ -1997,6 +2021,13 @@ <string name="stores_itch_browse_failed">無法從 itch.io 載入遊戲</string> <string name="stores_itch_archive">不支援 %1$s 壓縮檔</string> <string name="stores_itch_download_failed">itch.io 回應 HTTP %1$d</string> + <string name="stores_itch_pick_title">選擇版本</string> + <string name="stores_itch_pick_none">找不到此遊戲的下載</string> + <string name="stores_itch_pick_failed">無法從 itch.io 載入下載內容</string> + <string name="stores_itch_build_demo">試玩版</string> + <string name="stores_itch_build_open">在 itch.io 開啟</string> + <string name="stores_itch_build_linux_soon">尚未支援</string> + <string name="stores_itch_no_game">在 itch.io 找不到這款遊戲</string> <string name="stores_free">免費</string> <string name="stores_resume">繼續</string> <string name="stores_refresh">重新整理</string> @@ -2978,6 +3009,25 @@ <string name="glasses_6dof">6DoF 虛擬螢幕</string> <string name="tracking_recovery_look">在光線充足的房間內緩慢環顧四周。\n不要遮擋追蹤攝影機,並面向家具等有明顯細節的物體。</string> <string name="spatial_print_job">DroidDeck ChArUco 30 mm</string> + <string name="setup_group_memory">記憶體</string> + <string name="setup_clear_cached">工作階段前關閉快取的應用程式</string> + <string name="setup_clear_cached_hint">工作階段開始時關閉 Android 留在背景的應用程式,讓遊戲有更多記憶體可用。需要開啟無線偵錯。</string> + <string name="setup_clear_cached_unpaired">需要先將 DroidDeck 與無線偵錯配對(見下方「配對」)。</string> + <string name="setup_memory_hud">記憶體讀數</string> + <string name="setup_memory_hud_hint">在工作階段畫面上顯示已用記憶體和交換空間。進階模式會分別顯示遊戲、DroidDeck、Android 和 GPU。</string> + <string name="setup_memory_hud_simple">簡單</string> + <string name="setup_memory_hud_advanced">進階</string> + <string name="memory_hud_simple">記憶體 %1$s/%2$s GB · 交換 %3$s/%4$s GB</string> + <string name="memory_hud_split">遊戲 %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">工作階段期間的背景應用程式</string> + <string name="setup_bg_limit_hint">工作階段執行期間,Android 最多快取這麼多個應用程式並關閉其餘的,讓遊戲使用它們的記憶體。工作階段結束後還原。需要開啟無線偵錯。</string> + <string name="setup_bg_limit_4">最多 4 個</string> + <string name="setup_bg_limit_1">最多 1 個</string> + <string name="setup_bg_limit_0">無</string> + <string name="setup_adb_pair">無線偵錯</string> + <string name="setup_adb_pair_hint">為上面的選項將 DroidDeck 與 Android 無線偵錯配對。子處理程序限制保持關閉。</string> + <string name="setup_adb_pair_button">配對</string> <string name="epic_client_missing">未安裝</string> <string name="epic_client_open">開啟</string> <string name="epic_client_install">安裝</string> @@ -3010,6 +3060,48 @@ <string name="library_remove">從收藏庫移除</string> <string name="library_in">已在收藏庫</string> <string name="xbox_filter_show">顯示</string> + <string name="itch_collections">收藏集</string> <string name="xbox_filter_cloud">雲端</string> <string name="stores_xbox_cloud_settings">雲端設定</string> + <string name="apps_search_hint">搜尋應用程式</string> + <string name="apps_no_match">沒有符合「%1$s」的應用程式。</string> + <string name="apps_add_widget">新增小工具</string> + <string name="apps_widgets_loading">正在載入小工具…</string> + <string name="apps_widgets_none">這部裝置上沒有提供小工具的應用程式。</string> + <string name="apps_widget_wider">加寬</string> + <string name="apps_widget_narrower">縮窄</string> + <string name="apps_widget_taller">加高</string> + <string name="apps_widget_shorter">降低</string> + <string name="apps_widget_move_earlier">往前移</string> + <string name="apps_widget_move_later">往後移</string> + <string name="apps_widget_configure">小工具設定</string> + <string name="apps_widget_remove">移除小工具</string> + <string name="apps_add_to_folder">新增至資料夾</string> + <string name="apps_new_folder">新資料夾</string> + <string name="apps_remove_from_folder">從資料夾移除</string> + <string name="apps_app_info">應用程式資訊</string> + <string name="apps_uninstall">解除安裝</string> + <string name="apps_folder_rename">重新命名</string> + <string name="apps_folder_ungroup">取消群組</string> + <string name="apps_folder_default">資料夾</string> + <string name="apps_folder_name">資料夾名稱</string> + <string name="apps_filter">顯示</string> + <string name="apps_filter_all">所有應用程式</string> + <string name="apps_filter_games">遊戲</string> + <string name="apps_filter_downloaded">已下載</string> + <string name="apps_filter_system">系統</string> + <string name="apps_filter_hidden">已隱藏</string> + <string name="apps_hide">隱藏</string> + <string name="apps_unhide">在應用程式中顯示</string> + <string name="apps_shortcut_remove">移除捷徑</string> + <string name="apps_pin_title">新增至應用程式</string> + <string name="apps_pin_add">新增</string> + <string name="apps_hidden_none">沒有隱藏的應用程式。</string> + <string name="apps_sort_name_asc">名稱 A–Z</string> + <string name="apps_sort_name_desc">名稱 Z–A</string> + <string name="apps_sort_installed">最近安裝</string> + <string name="apps_sort_updated">最近更新</string> + <plurals name="apps_count"> + <item quantity="other">%d 個應用程式</item> + </plurals> </resources> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1ca3066271..8979e00b69 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -85,6 +85,8 @@ <string name="game_env_vkd3d_config">VKD3D options for D3D12. nodxr disables ray tracing; use only for a game that needs it.</string> <string name="game_env_proton_log">Set to 1 for a Proton diagnostic log. Logging can reduce performance and use storage.</string> <string name="game_env_wined3d">Set to 1 to use OpenGL-based WineD3D instead of DXVK for D3D9–11 compatibility testing.</string> + <string name="game_env_wined3d_renderer">Renderer for DirectDraw, Direct3D 1-7 and games run with WineD3D. Vulkan skips the OpenGL-on-Zink path and is much faster for old DirectDraw and Direct3D 7 games on Adreno.</string> + <string name="game_env_dxvk_d3d8">Set to 1 to run Direct3D 8 through DXVK instead of WineD3D. Faster in AIO Graphics Test\'s Direct3D 8 test on Adreno.</string> <string name="game_env_no_ntsync">Set to 1 to keep this game off ntsync (droiddeck-ntsync or a kernel driver); it uses droiddeck-esync where a pack exists, otherwise droiddeck-fsync.</string> <string name="game_env_no_esync">Set to 1 to turn droiddeck-esync off for this game; it uses droiddeck-fsync instead, or droiddeck-ntsync where fsync is off too.</string> <string name="game_env_no_fsync">Set to 1 to keep this game off droiddeck-fsync; it uses droiddeck-esync where a pack exists, otherwise droiddeck-ntsync.</string> @@ -92,7 +94,8 @@ <string name="game_env_xalia">Set to 0 to disable Proton’s gamepad-navigation helper for this game.</string> <string name="game_env_anticheat_offline">On by default. Starts an Easy Anti-Cheat game without its anti-cheat when the game supports offline play. Turn off to launch through Easy Anti-Cheat as usual. Online modes that require Easy Anti-Cheat remain unavailable.</string> <string name="game_env_hud">DXVK overlay for D3D9–11. fps displays frame rate; unset hides it.</string> - <string name="game_env_dxvk_config">DXVK settings separated by semicolons. Recent builds use dxvk.maxFrameRate for frame limiting; prefer the session frame limiter for ordinary play.</string> + <string name="game_env_dxvk_config">DXVK settings separated by semicolons. Recent builds use dxvk.maxFrameRate for frame limiting; prefer Steam\'s Quick Access menu frame limiter for ordinary play.</string> + <string name="game_env_cores">CPU cores for this game, such as 0-4 or 0,2,4, in place of the session\'s game cores. Fewer cores run cooler.</string> <string name="game_env_vkd3d_limit">D3D12 frame-rate limit. 0 disables the limit.</string> <string name="game_env_glthread">Mesa OpenGL threading. true can help CPU-limited OpenGL games; test per game.</string> <string name="sync_backend_title">Wine sync</string> @@ -143,6 +146,7 @@ <string name="user_apps_remove">Remove</string> <string name="user_apps_remove_confirm">Press again to remove</string> <string name="user_apps_stop_session">Stop the session to remove</string> + <string name="bnet_name" translatable="false">Battle.net</string> <string name="user_apps_script_linked">Runs %1$s from its folder, linked into the session where it lies. Removing the app leaves that folder alone.</string> <string name="user_apps_script_copied">Runs %1$s from a copy of its folder inside DroidDeck. Removing the app deletes the copy, not the original.</string> <string name="user_apps_runtime_required">Install the Linux runtime first</string> @@ -180,6 +184,8 @@ <string name="app_fex_hint">FEX runs x86 Linux programs on this ARM64 device. Auto uses it when the program is built for x86.</string> <string name="app_fex_x86">%1$s through FEX</string> <string name="app_fex_not_ready">This program is built for %1$s PCs and runs through FEX, which is not set up yet. Open Steam once while signed in: DroidDeck has it download FEX and the Steam Linux Runtime it needs, then this opens.</string> + <string name="session_proot_missing">DroidDeck\'s proot could not be downloaded. Check the connection and try again. The session was not started, because the fallback proot is too slow to play on.</string> + <string name="session_directaudio_missing">DirectAudio could not be downloaded, so game audio uses the slower path this session.</string> <string name="session_end_program">This program</string> <string name="session_end_steam_download">Couldn\'t download the Steam client. Your network or VPN may be blocking Steam\'s servers; check the connection and try again.</string> <string name="session_end_steam_setup">Couldn\'t set up the Steam client. Check your connection and free storage, then try again.</string> @@ -252,8 +258,6 @@ <string name="mode_ratio">Screen ratio</string> <string name="mode_ratio_custom">Set by the custom resolution.</string> <string name="mode_ratio_auto">Auto uses at least 16:9.</string> - <string name="mode_fps">Frame limit</string> - <string name="mode_fps_note">Caps the whole session. The display switches to a refresh rate the cap divides evenly.</string> <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 output</string> <string name="mode_hdr_unavailable">Not available: %1$s.</string> @@ -272,6 +276,24 @@ <string name="osc_steam_touch">Steam touch (beta)</string> <string name="osc_style_next_session">Steam\'s touch controls start with the next Steam session</string> <string name="osc_steam_layout">Steam touch layout</string> + <string name="screen_keys">Screen keys</string> + <string name="screen_keys_add">Add key</string> + <string name="screen_key_text">Text</string> + <string name="screen_key_size">Size</string> + <string name="screen_key_opacity">Alpha</string> + <string name="screen_key_type_button">Key</string> + <string name="screen_key_shape_pill">Pill</string> + <string name="screen_key_shape_round">Round</string> + <string name="screen_key_shape_circle">Circle</string> + <string name="screen_key_shape_rect">Rect</string> + <string name="screen_key_shape_trigger">Trigger</string> + <string name="screen_key_bind">Bind</string> + <string name="screen_key_image">Image</string> + <string name="screen_key_image_clear">Clear</string> + <string name="screen_key_toggle">Toggle</string> + <string name="screen_key_layout">Layout</string> + <string name="screen_key_layout_save">Save</string> + <string name="screen_key_layout_export">Export</string> <string name="osc_steam_layout_hint">Move, resize or hide this game\'s touch controls; saved to Steam</string> <string name="mode_controller">Controller</string> <string name="mode_controller_hint">How Steam sees your controller. Applies next session.</string> @@ -282,6 +304,11 @@ <string name="mode_controller_x360">Xbox 360 controller</string> <string name="mode_controller_note">Deck: Quick Access button and gyro. Steam Controller: the same, with grip sense on the back buttons. DualShock 4 and DualSense: gyro, and the trackpads as their touchpad. Xbox 360: open Quick Access with Guide+A.</string> <string name="mode_back">Back</string> + <string name="back_native_qam_hint">Hold Back for 700 ms, or hold Back and press another button for Steam shortcuts.</string> + <string name="back_double_tap_window">Double-tap window</string> + <string name="back_tap_ms">%1$d ms</string> + <string name="brightness_permission_title">Allow brightness control</string> + <string name="brightness_permission_text">Set up brightness control in DroidDeck.</string> <string name="back_menu_then_qam">Menu → QAM</string> <string name="back_qam_then_menu">QAM → Menu</string> <string name="mode_session">Session</string> @@ -552,6 +579,16 @@ <string name="perf_gsrealtime">gamescope: realtime GPU queue</string> <string name="perf_gsrealtime_hint">Prioritizes the compositor\'s GPU work. Can smooth frame pacing at some cost to games.</string> <string name="perf_gpu">GPU</string> + <string name="perf_memory">Memory</string> + <string name="perf_cap_off">Off</string> + <string name="perf_cap_auto">Driver default</string> + <string name="perf_zram_client">Compress Steam while a game runs</string> + <string name="perf_zram_client_hint">20 s after a game starts, the Steam client is compressed into zRAM to leave the game more memory, and read back when the game closes. Turn this off if the session closes shortly after games start. A RAM cap above still compresses Steam when the session goes over it.</string> + <string name="perf_ram_cap">RAM cap</string> + <string name="perf_ram_cap_hint">Applies while the Steam client runs, in Steam mode or from the desktop. When the session uses more than this, Steam and then the session\'s other supported processes are compressed into zRAM. A soft cap: nothing is closed, but games may stutter while pages come back.</string> + <string name="perf_ram_cap_unavailable">Needs zRAM swap, which this device does not have.</string> + <string name="perf_vram_cap">VRAM cap</string> + <string name="perf_vram_cap_hint">The video memory DXVK reports to Direct3D games, so they budget textures for less. A game\'s own DXVK settings still win. Takes effect at the next session.</string> <string name="perf_gpuclock">Hold the GPU at its top clock</string> <string name="perf_gpuclock_hint">Adreno only. Fewer hitches, more battery use and heat.</string> <string name="perf_fixes">Session fixes</string> @@ -668,6 +705,8 @@ <string name="drawer_touch_auto">Auto (%1$s)</string> <string name="drawer_keyboard">Keyboard</string> <string name="drawer_latency">Latency</string> + <string name="drawer_low_latency">Low latency mode</string> + <string name="drawer_low_latency_hint">Increases CPU and battery usage</string> <string name="drawer_low_latency_controller">Low-latency controller</string> <string name="drawer_low_latency_controller_hint">Pad reports at 1000 Hz instead of 250 Hz. Slightly more CPU.</string> <string name="drawer_low_latency_touch">Low-latency touch</string> @@ -793,6 +832,11 @@ <string name="setup_home_on">DroidDeck can be the Home app</string> <string name="setup_home_off">DroidDeck is never offered as a Home app</string> <string name="setup_orientation">Orientation</string> + <string name="setup_launcher_orientation">Launcher orientation</string> + <string name="setup_launcher_orientation_auto">Follow device rotation</string> + <string name="setup_orientation_portrait">Portrait</string> + <string name="setup_session_orientation">Session orientation</string> + <string name="setup_session_orientation_hint">Applies to Steam, games, desktop, and the controller editor. Resolution presets rotate with the session; custom width and height stay as entered.</string> <string name="setup_orientation_auto">Automatic landscape</string> <string name="setup_orientation_landscape">Landscape</string> <string name="setup_orientation_reverse">Reverse landscape</string> @@ -946,6 +990,12 @@ <string name="gate_step1">Open Settings → Developer options → Wireless debugging and turn it on</string> <string name="gate_step2">Tap “Pair device with pairing code”</string> <string name="gate_step3">Type the code into the DroidDeck notification</string> + <string name="pairguide_build_number">In About phone, tap Build number 7 times</string> + <string name="pairguide_wireless">Turn on Wireless debugging</string> + <string name="pairguide_pair">Open Wireless debugging, then tap “Pair device with pairing code”</string> + <string name="pairguide_row_build_number">Build number</string> + <string name="pairguide_row_wireless">Wireless debugging</string> + <string name="pairguide_row_pair">Pair device with pairing code</string> <string name="gate_waiting">Waiting for the pairing pop-up…</string> <string name="gate_code_needed">Pop-up found. Enter its code in the notification.</string> <string name="gate_status">Status</string> @@ -1031,6 +1081,48 @@ <string name="content_android_apps">Android apps</string> <string name="content_apps_count">%1$d apps</string> <string name="content_no_android_apps">No launchable Android apps found.</string> + <string name="apps_search_hint">Search apps</string> + <string name="apps_no_match">No apps match “%1$s”.</string> + <string name="apps_add_widget">Add widget</string> + <string name="apps_widgets_loading">Loading widgets…</string> + <string name="apps_widgets_none">No apps on this device offer widgets.</string> + <string name="apps_widget_wider">Wider</string> + <string name="apps_widget_narrower">Narrower</string> + <string name="apps_widget_taller">Taller</string> + <string name="apps_widget_shorter">Shorter</string> + <string name="apps_widget_move_earlier">Move earlier</string> + <string name="apps_widget_move_later">Move later</string> + <string name="apps_widget_configure">Widget settings</string> + <string name="apps_widget_remove">Remove widget</string> + <string name="apps_add_to_folder">Add to folder</string> + <string name="apps_new_folder">New folder</string> + <string name="apps_remove_from_folder">Remove from folder</string> + <string name="apps_app_info">App info</string> + <string name="apps_uninstall">Uninstall</string> + <string name="apps_folder_rename">Rename</string> + <string name="apps_folder_ungroup">Ungroup</string> + <string name="apps_folder_default">Folder</string> + <string name="apps_folder_name">Folder name</string> + <string name="apps_filter">Show</string> + <string name="apps_filter_all">All apps</string> + <string name="apps_filter_games">Games</string> + <string name="apps_filter_downloaded">Downloaded</string> + <string name="apps_filter_system">System</string> + <string name="apps_filter_hidden">Hidden</string> + <string name="apps_hide">Hide</string> + <string name="apps_unhide">Show in apps</string> + <string name="apps_shortcut_remove">Remove shortcut</string> + <string name="apps_pin_title">Add to Apps</string> + <string name="apps_pin_add">Add</string> + <string name="apps_hidden_none">No hidden apps.</string> + <plurals name="apps_count"> + <item quantity="one">%d app</item> + <item quantity="other">%d apps</item> + </plurals> + <string name="apps_sort_name_asc">Name A–Z</string> + <string name="apps_sort_name_desc">Name Z–A</string> + <string name="apps_sort_installed">Recently installed</string> + <string name="apps_sort_updated">Recently updated</string> <string name="content_desktop_installed">● Desktop installed</string> <string name="content_desktop_first_open">Installs on first open</string> <string name="content_available">Available to install</string> @@ -1210,10 +1302,10 @@ <string name="game_env_eyebrow">Proton games</string> <string name="pip_title">Picture in picture</string> <string name="pip_auto">Automatically enter PiP</string> - <string name="unfolded_controls">Controls on the unfolded screen</string> - <string name="unfolded_controls_hint">Unfolded, the game sits above the Steam Deck trackpads and back grips. Folded, the game is full screen.</string> + <string name="unfolded_controls">Controls below the game</string> + <string name="unfolded_controls_hint">In portrait or on an unfolded screen, place a landscape game above the touch controls.</string> <string name="unfolded_controls_with_controller">Keep them with a controller</string> - <string name="unfolded_controls_with_controller_hint">Also show the unfolded controls while a controller is connected, for controllers that hold the phone.</string> + <string name="unfolded_controls_with_controller_hint">Also show these touch controls while a controller is connected.</string> <string name="pip_suspended">Suspended</string> <string name="pip_not_ready">Picture in picture is available once the session is ready.</string> <string name="pip_permission">Allow picture in picture for DroidDeck in Android settings.</string> @@ -1241,6 +1333,10 @@ <string name="main_wait_runtime">Wait for the runtime operation to finish</string> <string name="main_wait_proton_install">Wait for the compatibility tool install to finish</string> + <string name="load_compat_title">Preparing compatibility tools</string> + <string name="load_compat_wait">Waiting for compatibility setup to finish</string> + <string name="load_compat_hint">Your session will start when setup finishes.</string> + <string name="load_compat_progress">%1$s · %2$d%%</string> <string name="main_wait_desktop_install">Wait for the desktop app install to finish</string> <string name="main_wait_install_game">Wait for the install to finish before launching a game</string> <string name="main_saves_close_session">Close the Steam session first, so the game can\'t save over the import</string> @@ -1801,6 +1897,7 @@ <string name="adbpair_applying">Applying the setting…</string> <string name="adbpair_command_failed">Wireless debugging command failed</string> <string name="adbpair_channel_name">Wireless debugging setup</string> + <string name="adbpair_progress_channel_name">Wireless debugging setup progress</string> <string name="adbpair_channel_description">Asks for the Wireless debugging pairing code while Settings is open</string> <string name="adbpair_title_pair">Pair Wireless debugging</string> <string name="adbpair_waiting_text">Turn on Wireless debugging, then tap “Pair device with pairing code”.</string> @@ -1995,7 +2092,7 @@ <string name="display_resolution">Resolution</string> <string name="display_game_fit">16:9 game fit</string> <string name="display_game_fit_hint">How 16:9 games fit this display. Next session.</string> - <string name="display_game_fit_unavailable">Choose Match screen or a custom size narrower than 16:9.</string> + <string name="display_game_fit_unavailable">Choose Match screen or a custom size that isn\'t 16:9.</string> <string name="display_preserve">Keep proportions</string> <string name="display_stretch">Stretch to display</string> <string name="display_image_scaling">Image scaling</string> @@ -2004,7 +2101,6 @@ <string name="display_filter_live">Applies live. Shared by Steam and Desktop.</string> <string name="display_filter_note">FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement.</string> <string name="display_sharpness">Filter sharpness</string> - <string name="display_frame_rate">Frame rate</string> <string name="display_look_filter">%1$s Sets scaling to %2$s.</string> <string name="display_match_screen">Match screen (%1$d×%2$d)</string> <string name="display_follow_screen">Follow screen (resizes when folded or unfolded)</string> @@ -2057,6 +2153,15 @@ <string name="stores_shelf_trending">Trending</string> <string name="stores_play">Play</string> <string name="stores_install">Install</string> + <string name="bnet_open">Open Battle.net</string> + <string name="bnet_dl_starting">Starting Blizzard\'s downloader…</string> + <string name="bnet_dl_waiting">Waiting for Battle.net to close…</string> + <string name="bnet_dl_queued">Waiting for the other Battle.net download…</string> + <string name="bnet_dl_client_first">Open Battle.net and sign in once, then install its games here.</string> + <string name="bnet_dl_failed">Blizzard\'s downloader stopped: %1$s</string> + <string name="bnet_dl_agent_error">Blizzard error %1$s</string> + <string name="bnet_update">Update</string> + <string name="bnet_store">Blizzard games</string> <string name="stores_resume_install">Resume install</string> <string name="stores_dl_interrupted">Interrupted</string> <string name="stores_install_size">Install · %1$s</string> @@ -2100,6 +2205,18 @@ <string name="stores_itch_browse_failed">Could not load games from itch.io</string> <string name="stores_itch_archive">%1$s archives are not supported</string> <string name="stores_itch_download_failed">itch.io answered HTTP %1$d</string> + <string name="stores_itch_pick_title">Choose a version</string> + <string name="stores_itch_pick_none">No downloads found for this game</string> + <string name="stores_itch_pick_failed">Could not load the downloads from itch.io</string> + <string name="stores_itch_build_demo">Demo</string> + <string name="stores_itch_build_open">Open on itch.io</string> + <string name="stores_itch_build_linux_soon">Not supported yet</string> + <string name="stores_itch_no_game">Could not find this game on itch.io</string> + <string name="stores_itch_build_windows" translatable="false">Windows</string> + <string name="stores_itch_build_macos" translatable="false">macOS</string> + <string name="stores_itch_build_linux" translatable="false">Linux</string> + <string name="stores_itch_build_android" translatable="false">Android</string> + <string name="stores_itch_build_web" translatable="false">Web</string> <string name="stores_free">Free</string> <string name="stores_resume">Resume</string> <string name="stores_refresh">Refresh</string> @@ -2412,6 +2529,7 @@ <string name="setup_download_source_custom">Custom prefix</string> <string name="setup_download_mirror">Site</string> <string name="setup_download_prefix">Prefix</string> + <string name="setup_download_proxy">HTTP proxy</string> <string name="flathub_eyebrow">LINUX APPS</string> <string name="flathub_name">Flathub</string> <string name="flathub_line">Desktop apps for the Linux desktop, opened from Desktop.</string> @@ -2701,6 +2819,21 @@ <string name="storage_safe_hint">Unused runtimes, leftovers, old logs</string> <string name="storage_clean_up">Clean up…</string> <string name="storage_session_running">Stop the session to clean up or remove anything. Sizes are still shown.</string> + <string name="storage_default_group">Install location</string> + <string name="storage_default_title">Default storage</string> + <string name="storage_default_hint">New store installs go to the selected location. Existing games stay where they are. Steam libraries keep their own setting.</string> + <string name="storage_default_ask">Ask every time</string> + <string name="storage_default_ask_detail">Choose a target for each install</string> + <string name="storage_default_internal">Internal storage</string> + <string name="storage_default_external">External storage</string> + <string name="storage_default_external_detail">%1$s · %2$s free</string> + <string name="storage_default_external_missing">Not connected</string> + <string name="storage_default_folder">Folder · %1$s</string> + <string name="storage_default_folder_free">%1$s free</string> + <string name="storage_default_folder_missing">Not connected</string> + <string name="storage_default_choose_folder">Choose folder…</string> + <string name="storage_default_choose_folder_detail">Use any folder on an SD card or USB drive</string> + <string name="storage_default_note">Games go into a Games folder inside the selected location. Existing games are not moved.</string> <string name="storage_where">Where it goes</string> <string name="storage_games">Steam games</string> <string name="storage_game_data">Game data</string> @@ -3082,6 +3215,25 @@ <string name="spatial_saved_views_hint">Saved views can be recalculated. Start a new calibration to capture in the current tracking frame.</string> <string name="spatial_model_checksum_error">Hand model checksum mismatch</string> <string name="spatial_opencv_load_error">OpenCV could not load</string> + <string name="setup_group_memory">Memory</string> + <string name="setup_clear_cached">Clear cached apps before a session</string> + <string name="setup_clear_cached_hint">When a session starts, DroidDeck closes the apps Android keeps parked in the background, so the game has more memory. Wireless debugging must be on.</string> + <string name="setup_clear_cached_unpaired">Needs DroidDeck paired with Wireless debugging (Pair, below).</string> + <string name="setup_memory_hud">Memory readout</string> + <string name="setup_memory_hud_hint">Memory and swap in use, on the session screen. Advanced splits it into the game, DroidDeck, Android and the GPU.</string> + <string name="setup_memory_hud_simple">Simple</string> + <string name="setup_memory_hud_advanced">Advanced</string> + <string name="memory_hud_simple">RAM %1$s/%2$s GB · swap %3$s/%4$s GB</string> + <string name="memory_hud_split">game %1$s · DroidDeck %2$s · Android %3$s GB</string> + <string name="memory_hud_gpu">GPU %1$s GB</string> + <string name="setup_bg_limit">Background apps during a session</string> + <string name="setup_bg_limit_hint">While a session runs, Android keeps at most this many apps cached and closes the rest, so the game has their memory. DroidDeck puts the limit back as it was when the session ends. Wireless debugging must be on.</string> + <string name="setup_bg_limit_4">At most 4</string> + <string name="setup_bg_limit_1">At most 1</string> + <string name="setup_bg_limit_0">None</string> + <string name="setup_adb_pair">Wireless debugging</string> + <string name="setup_adb_pair_hint">Pairs DroidDeck with Android\'s Wireless debugging for the options above. The child-process limit stays off.</string> + <string name="setup_adb_pair_button">Pair</string> <string name="stores_xbox_update">Update / verify</string> <string name="stores_xbox_manage">Manage content</string> <string name="stores_xbox_close_first">Close this Xbox game before updating it.</string> @@ -3098,7 +3250,20 @@ <string name="epic_client_open">Open</string> <string name="epic_client_install">Install</string> <string name="library_filter_added">Added</string> + <string name="library_filter">Filter</string> + <string name="library_filter_installed">Installed only</string> + <string name="library_filter_all_owned">All owned games</string> + <string name="library_no_installed_matches">No installed games match these filters.</string> + <string name="library_browse_owned">Browse owned games</string> <string name="game_tab_about">About</string> + <string name="game_resources_browser">Opens in your browser</string> + <string name="game_resource_pcgw" translatable="false">PCGamingWiki</string> + <string name="game_resource_guides">Guides</string> + <string name="game_resource_protondb" translatable="false">ProtonDB</string> + <string name="game_resource_protondb_detail">Linux / Proton compatibility reports</string> + <string name="game_resource_steam_cloud">Steam Cloud</string> + <string name="game_resource_steam_cloud_detail">For games with saves on your Steam account</string> + <string name="game_resource_search">Web search</string> <string name="game_tab_achievements_count" translatable="false">%1$s %2$d/%3$d</string> <string name="game_tab_launch">Launch</string> <string name="game_tab_saves_cloud">Saves & cloud</string> @@ -3117,8 +3282,32 @@ <string name="library_remove">Remove from Library</string> <string name="library_in">In Library</string> <string name="xbox_filter_show">Show</string> + <string name="itch_collections">Collections</string> <string name="xbox_filter_cloud">Cloud</string> <string name="stores_xbox_cloud_settings">Cloud settings</string> <string name="xbox_cloud_gaming" translatable="false">Xbox Cloud Gaming</string> <string name="xbox_filter_game_pass" translatable="false">Game Pass</string> + <string name="integration_title">Steam integration</string> + <string name="integration_count">%1$d of %2$d on</string> + <string name="integration_set_up">Set up</string> + <string name="integration_later">Not now</string> + <string name="integration_location">Location</string> + <string name="integration_app_info">App info</string> + <string name="integration_wifi">Wi-Fi names</string> + <string name="integration_brightness">Brightness</string> + <string name="integration_home">DroidDeck as Home</string> + <string name="integration_shortcuts">Home button shortcuts</string> + <string name="integration_wifi_hint">Show networks in Steam · needs Location access, never tracked</string> + <string name="integration_wifi_on">Networks show in Steam</string> + <string name="integration_wifi_location_off">Location is off</string> + <string name="integration_wifi_denied">Location denied · allow it in App info</string> + <string name="integration_brightness_hint">Steam’s slider sets screen brightness</string> + <string name="integration_home_hint">Home opens the Steam menu in a session</string> + <string name="integration_shortcuts_hint">Hold Home for Steam Guide chords</string> + <string name="integration_shortcuts_needs_home">Needs DroidDeck as Home</string> + <string name="integration_shortcuts_maybe_restricted">Greyed out in Android? App info → ⋮ → Allow restricted settings</string> + <string name="integration_shortcuts_restricted">Blocked by Android · App info → ⋮ → Allow restricted settings</string> + <string name="integration_shortcuts_service">DroidDeck Home button</string> + <string name="integration_shortcuts_service_description">Pass Home button presses to Steam Guide while a Steam session is focused and DroidDeck is the default Home app. Does not read screen content.</string> + <string name="integration_brightness_needed">Turn on Brightness in Setup → Steam integration</string> </resources> diff --git a/app/src/main/res/xml/home_button_service.xml b/app/src/main/res/xml/home_button_service.xml new file mode 100644 index 0000000000..3b094dcd54 --- /dev/null +++ b/app/src/main/res/xml/home_button_service.xml @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="utf-8"?> +<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android" + android:accessibilityFeedbackType="feedbackGeneric" + android:accessibilityFlags="flagRequestFilterKeyEvents" + android:canRequestFilterKeyEvents="true" + android:canRetrieveWindowContent="false" + android:description="@string/integration_shortcuts_service_description" /> diff --git a/app/src/main/rust/stores/src/fetch_core.rs b/app/src/main/rust/stores/src/fetch_core.rs index e0c10112ca..f019734405 100644 --- a/app/src/main/rust/stores/src/fetch_core.rs +++ b/app/src/main/rust/stores/src/fetch_core.rs @@ -1,7 +1,8 @@ use crate::fetch_tuning::{ budget_admits, connect_timeout, inflight_budget_bytes, retry_backoff_millis, AsyncFetchError, FetchFailKind, BOOTSTRAP_WINDOW, MAX_CHUNK_ATTEMPTS, NOMINAL_CHUNK_RESERVE_BYTES, - RATE_LIMIT_COOLDOWN_MS, SERVER_EXPLORE_EVERY, USER_AGENT, WINDOW_BPS_EWMA_ALPHA, + RATE_LIMIT_COOLDOWN_MS, SERVER_EXPLORE_EVERY, SERVER_FAULT_COOLDOWN_MS, USER_AGENT, + WINDOW_BPS_EWMA_ALPHA, WINDOW_COOLDOWN_MS, WINDOW_DECLINE_EPS, WINDOW_ERR_BURST_IMMEDIATE, WINDOW_ERR_RATE_HIGH, WINDOW_ERR_RATE_LOW, WINDOW_HARD_CAP, WINDOW_IMPROVE_EPS, WINDOW_LOG_EVERY_PROBES, WINDOW_MIN_FLOOR, WINDOW_PLATEAU_PATIENCE, WINDOW_PLATEAU_REARM_MAX_MS, @@ -607,6 +608,10 @@ fn classify_reqwest_error(err: &reqwest::Error) -> FetchFailKind { FetchFailKind::Timeout } else if err.is_connect() { FetchFailKind::Connect + } else if err.is_body() || err.is_decode() { + // A truncated or undecodable body comes from the CDN, not the request. Rest that host so + // the retry goes to another mirror instead of reading the same bad object again. + FetchFailKind::ServerFault } else { FetchFailKind::Other } @@ -663,14 +668,9 @@ async fn fetch_once( } Ok(None) => break, Err(err) => { - let kind = if err.is_timeout() { - FetchFailKind::Timeout - } else { - FetchFailKind::Other - }; return Err(AsyncFetchError { message: format!("http body: {err}"), - kind, + kind: classify_reqwest_error(&err), }); } } @@ -1150,7 +1150,7 @@ async fn run_driver(ctx: DriverCtx<'_>) { Ok(Fetched::Body(body)) => { let raw_len = body.len() as u64; meter.record(done.server_idx, raw_len); - sched.on_success(done.server_idx, raw_len, done.elapsed); + sched.on_success(done.server_idx, raw_len, done.elapsed, now); window.record_ok(done.elapsed.as_secs_f64() * 1000.0); if raw_len >= done.reserve { in_flight.fetch_add(raw_len - done.reserve, Ordering::Relaxed); @@ -1172,7 +1172,7 @@ async fn run_driver(ctx: DriverCtx<'_>) { } Ok(Fetched::Streamed(total_len)) => { meter.record(done.server_idx, total_len); - sched.on_success(done.server_idx, total_len, done.elapsed); + sched.on_success(done.server_idx, total_len, done.elapsed, now); window.record_ok(done.elapsed.as_secs_f64() * 1000.0); outstanding += 1; if txs[done.idx % txs.len()] @@ -1335,6 +1335,7 @@ struct ServerHealth { samples: u32, consecutive_errors: u32, cooldown_until: Option<Instant>, + fault_until: Option<Instant>, } struct FetchScheduler { @@ -1412,7 +1413,7 @@ impl FetchScheduler { }) } - fn on_success(&mut self, server_idx: usize, bytes: u64, elapsed: Duration) { + fn on_success(&mut self, server_idx: usize, bytes: u64, elapsed: Duration, now: Instant) { let secs = elapsed.as_secs_f64().max(0.001); let bps = bytes as f64 / secs; let h = &mut self.health[server_idx]; @@ -1423,7 +1424,15 @@ impl FetchScheduler { }; h.samples = h.samples.saturating_add(1); h.consecutive_errors = 0; - h.cooldown_until = None; + // A success can belong to a request that was already in flight when another response from + // this host failed. Keep a server-fault cooldown until it expires instead of clearing it + // early and sending the retry straight back to the same mirror. + if let Some(fault) = h.fault_until.filter(|until| *until > now) { + h.cooldown_until = Some(h.cooldown_until.map_or(fault, |current| current.max(fault))); + } else { + h.fault_until = None; + h.cooldown_until = None; + } } fn rest(&mut self, server_idx: usize, now: Instant, rest: Duration) { @@ -1436,10 +1445,18 @@ impl FetchScheduler { let h = &mut self.health[server_idx]; h.consecutive_errors = h.consecutive_errors.saturating_add(1); let mut backoff = retry_backoff_millis(h.consecutive_errors); - if kind == FetchFailKind::RateLimited { - backoff = backoff.max(RATE_LIMIT_COOLDOWN_MS); + match kind { + FetchFailKind::RateLimited => backoff = backoff.max(RATE_LIMIT_COOLDOWN_MS), + FetchFailKind::ServerFault => backoff = backoff.max(SERVER_FAULT_COOLDOWN_MS), + _ => {} } - h.cooldown_until = Some(now + Duration::from_millis(backoff)); + let until = now + Duration::from_millis(backoff); + if kind == FetchFailKind::ServerFault { + h.fault_until = Some(now + Duration::from_millis(SERVER_FAULT_COOLDOWN_MS)); + } + let current = h.cooldown_until.unwrap_or(until); + let fault = h.fault_until.unwrap_or(until); + h.cooldown_until = Some(current.max(fault).max(until)); h.ewma_bps *= 0.5; } } @@ -1806,6 +1823,7 @@ mod tests { use super::*; use crate::fetch_tuning::{ FETCH_INFLIGHT_BUDGET_FLOOR_BYTES, FETCH_INFLIGHT_BUDGET_HARD_CAP_BYTES, PER_HOST_CAP, + SERVER_FAULT_COOLDOWN_MS, }; use std::collections::HashMap; use std::io::{Read, Write}; @@ -1900,9 +1918,9 @@ mod tests { let mut s = FetchScheduler::new(&hosts, 2); let now = Instant::now(); assert_eq!(s.pick(now), Some(0)); - s.on_success(0, 1_000_000, Duration::from_millis(100)); + s.on_success(0, 1_000_000, Duration::from_millis(100), now); assert_eq!(s.pick(now), Some(1)); - s.on_success(1, 1_000_000, Duration::from_millis(500)); + s.on_success(1, 1_000_000, Duration::from_millis(500), now); assert_eq!(s.pick(now), Some(0)); s.on_error(0, now, FetchFailKind::Timeout); assert_eq!(s.pick(now), Some(1)); @@ -1911,6 +1929,57 @@ mod tests { assert_eq!(s.pick(now + Duration::from_secs(6)), Some(0)); } + #[test] + fn a_server_fault_rests_the_host_for_the_other_mirror() { + let hosts = vec!["a".to_string(), "b".to_string()]; + let mut s = FetchScheduler::new(&hosts, 2); + let now = Instant::now(); + s.on_success(0, 1_000_000, Duration::from_millis(100), now); + s.on_success(1, 1_000_000, Duration::from_millis(100), now); + s.on_error(0, now, FetchFailKind::ServerFault); + assert_eq!(s.pick(now), Some(1)); + assert_eq!( + s.pick(now + Duration::from_millis(SERVER_FAULT_COOLDOWN_MS - 1)), + Some(1) + ); + assert!(!s.eligible(0, now + Duration::from_millis(SERVER_FAULT_COOLDOWN_MS - 1))); + assert!(s.eligible(0, now + Duration::from_millis(SERVER_FAULT_COOLDOWN_MS))); + } + + #[test] + fn a_success_from_an_earlier_request_does_not_clear_a_server_fault_cooldown() { + let hosts = vec!["a".to_string(), "b".to_string()]; + let mut s = FetchScheduler::new(&hosts, 2); + let now = Instant::now(); + s.on_error(0, now, FetchFailKind::ServerFault); + s.on_success(0, 1_000_000, Duration::from_millis(100), now + Duration::from_millis(100)); + assert!(!s.eligible(0, now + Duration::from_millis(100))); + assert!(s.eligible(0, now + Duration::from_millis(SERVER_FAULT_COOLDOWN_MS))); + } + + #[test] + fn a_success_keeps_a_longer_cooldown_than_the_server_fault() { + let hosts = vec!["a".to_string(), "b".to_string()]; + let mut s = FetchScheduler::new(&hosts, 2); + let now = Instant::now(); + s.on_error(0, now, FetchFailKind::ServerFault); + s.rest(0, now, Duration::from_secs(30)); + s.on_success(0, 1_000_000, Duration::from_millis(100), now + Duration::from_millis(100)); + assert!(!s.eligible(0, now + Duration::from_secs(29))); + assert!(s.eligible(0, now + Duration::from_secs(30))); + } + + #[test] + fn a_server_fault_keeps_a_longer_host_stall_cooldown() { + let hosts = vec!["a".to_string(), "b".to_string()]; + let mut s = FetchScheduler::new(&hosts, 2); + let now = Instant::now(); + s.rest(0, now, Duration::from_secs(30)); + s.on_error(0, now, FetchFailKind::ServerFault); + assert!(!s.eligible(0, now + Duration::from_secs(29))); + assert!(s.eligible(0, now + Duration::from_secs(30))); + } + #[test] fn window_shrinks_only_on_error_bursts() { let now = Instant::now(); diff --git a/app/src/main/rust/stores/src/fetch_tuning.rs b/app/src/main/rust/stores/src/fetch_tuning.rs index 4f1f7074f9..5c380d537b 100644 --- a/app/src/main/rust/stores/src/fetch_tuning.rs +++ b/app/src/main/rust/stores/src/fetch_tuning.rs @@ -68,6 +68,10 @@ pub const SERVER_EXPLORE_EVERY: u64 = 8; pub const NOMINAL_CHUNK_RESERVE_BYTES: u64 = 1024 * 1024; pub const RATE_LIMIT_COOLDOWN_MS: u64 = 5_000; +// Long enough that every retry of the item (5 attempts, at most ~4.5 s of backoff) goes to another +// mirror after this one served a truncated or undecodable body. +pub const SERVER_FAULT_COOLDOWN_MS: u64 = 10_000; + pub fn retry_backoff_millis(attempt: u32) -> u64 { if attempt == 0 { return 0; diff --git a/app/src/test/java/com/droiddeck/launcher/CompatLaunchTest.kt b/app/src/test/java/com/droiddeck/launcher/CompatLaunchTest.kt new file mode 100644 index 0000000000..e19b1d6347 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/CompatLaunchTest.kt @@ -0,0 +1,268 @@ +package com.droiddeck.launcher + +import android.content.Intent +import android.os.Bundle +import android.os.Looper +import com.droiddeck.launcher.session.LoadingState +import com.droiddeck.launcher.session.ProtonExtras +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.ui.LaunchOrigin +import java.time.Duration +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.* +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 + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class CompatLaunchTest { + private lateinit var activity: FrontEndActivity + private lateinit var protons: ProtonMenu + + @Before fun setUp() { + installing(false) + LaunchOrigin.take() + activity = Robolectric.buildActivity(FrontEndActivity::class.java).get() + protons = ReflectionHelpers.getField(activity, "protons") + ReflectionHelpers.setField(activity, "compatLaunchVisible", true) + protons.protonBusyId = "droiddeck" + protons.protonProblem = null + protons.protonStage = "Downloading DroidDeck Proton" + protons.protonPercent = 37 + setString("setPkgStage", null) + } + + @After fun cleanUp() { + cancel() + protons.protonBusyId = null + protons.protonProblem = null + protons.protonStage = null + protons.protonPercent = -1 + setString("setPkgStage", null) + installing(false) + LaunchOrigin.take() + } + + @Test fun waitingShowsRealProgressThenStartsTheOriginalRequestOnce() { + activity.startActivity(request("steam://rungameid/42")) + assertNull(shadowOf(activity).nextStartedActivity) + assertEquals(37, loading().percent) + assertTrue(loading().step.contains("37%")) + protons.protonStage = "Verifying download" + protons.protonPercent = -1 + advance() + assertEquals("Verifying download", loading().step) + assertEquals(-1, loading().percent) + protons.protonBusyId = null + advance() + assertEquals("steam://rungameid/42", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL)) + assertNull(waiting()) + advance() + assertNull(shadowOf(activity).nextStartedActivity) + } + + @Test fun cancellingTheLaunchLeavesTheInstallRunningAndPreventsALateStart() { + activity.startActivity(request("first")) + cancel() + assertEquals("droiddeck", protons.protonBusyId) + protons.protonBusyId = null + advance() + assertNull(waiting()) + assertNull(shadowOf(activity).nextStartedActivity) + } + + @Test fun installationFailureStaysOnTheLoadingErrorWithoutStarting() { + activity.startActivity(request("first")) + protons.protonProblem = "Checksum verification failed" + protons.protonBusyId = null + advance() + assertTrue(loading().ended) + assertEquals("Checksum verification failed", loading().step) + assertNull(shadowOf(activity).nextStartedActivity) + } + + @Test fun repeatedLaunchesDoNotReplaceThePendingGame() { + activity.startActivity(request("first")) + activity.startActivity(request("second")) + protons.protonBusyId = null + advance() + assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL)) + assertNull(shadowOf(activity).nextStartedActivity) + } + + @Test fun anInstallOutsideTheLauncherUsesIndeterminateProgress() { + protons.protonBusyId = null + installing(true) + activity.startActivity(request("first")) + assertEquals(-1, loading().percent) + assertNull(shadowOf(activity).nextStartedActivity) + installing(false) + advance() + assertNotNull(shadowOf(activity).nextStartedActivity) + } + + @Test fun finishingInTheBackgroundWaitsUntilTheLauncherIsVisible() { + activity.startActivity(request("first")) + ReflectionHelpers.setField(activity, "compatLaunchVisible", false) + protons.protonBusyId = null + advance() + assertNull(shadowOf(activity).nextStartedActivity) + ReflectionHelpers.setField(activity, "compatLaunchVisible", true) + advance() + assertNotNull(shadowOf(activity).nextStartedActivity) + } + + @Test fun aRestoredCompletedRequestWaitsForResume() { + activity.startActivity(request("first")) + val saved = save() + cancel() + protons.protonBusyId = null + recreate(saved) + advance() + assertNull(shadowOf(activity).nextStartedActivity) + ReflectionHelpers.setField(activity, "compatLaunchVisible", true) + advance() + assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL)) + } + + @Test fun overlappingPackageWorkKeepsTheOriginalLaunchUntilItFinishes() { + activity.startActivity(request("first")) + setString("setPkgStage", "Installing desktop") + ReflectionHelpers.callInstanceMethod<Void>(activity, "setPkgPercent", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 64)) + protons.protonBusyId = null + advance() + assertNotNull(waiting()) + assertNull(shadowOf(activity).nextStartedActivity) + assertEquals("Installing desktop", loading().step) + assertEquals(64, loading().percent) + setString("setPkgStage", null) + advance() + assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL)) + advance() + assertNull(shadowOf(activity).nextStartedActivity) + } + + @Test fun overlappingRuntimeWorkDoesNotDropThePendingLaunch() { + activity.startActivity(request("first")) + setString("setStage", "Updating runtime") + ReflectionHelpers.callInstanceMethod<Void>(activity, "setBusy", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + protons.protonBusyId = null + advance() + assertNotNull(waiting()) + assertNull(shadowOf(activity).nextStartedActivity) + assertEquals("Updating runtime", loading().step) + ReflectionHelpers.callInstanceMethod<Void>(activity, "setBusy", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, false)) + advance() + assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL)) + } + + @Test fun aPackageDownloadStillBlocksTheLaunchAfterRecreationAndReportsOldWorkerProgress() { + activity.startActivity(request("first")) + setString("setPkgStage", "Downloading AppImage") + ReflectionHelpers.callInstanceMethod<Void>(activity, "setPkgPercent", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 23)) + val workerActivity = activity + val saved = save() + cancel() + recreate(saved) + ReflectionHelpers.setField(activity, "compatLaunchVisible", true) + protons.protonBusyId = null + advance() + assertNotNull(waiting()) + assertNull(shadowOf(activity).nextStartedActivity) + assertEquals("Downloading AppImage", loading().step) + assertEquals(23, loading().percent) + android.os.Handler(Looper.getMainLooper()).post { + setString("setPkgStage", "Placing AppImage", workerActivity) + ReflectionHelpers.callInstanceMethod<Void>(workerActivity, "setPkgPercent", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 90)) + } + advance() + assertEquals("Placing AppImage", loading().step) + assertEquals(90, loading().percent) + assertNull(shadowOf(activity).nextStartedActivity) + android.os.Handler(Looper.getMainLooper()).post { setString("setPkgStage", null, workerActivity) } + advance() + assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL)) + advance() + assertNull(shadowOf(activity).nextStartedActivity) + } + + @Test fun aFailedInstallAfterRecreationKeepsItsProgressAndError() = recreationFailure(false) + + @Test fun aFailedInstallBeforeRestorationStillShowsItsError() = recreationFailure(true) + + private fun recreationFailure(finishBeforeRestore: Boolean) { + val entered = CountDownLatch(1) + val finish = CountDownLatch(1) + protons.protonBusyId = null + protons.installer = { _, progress -> + progress("Verifying download", 64) + entered.countDown() + check(finish.await(5, TimeUnit.SECONDS)) + "Checksum verification failed" + } + try { + protons.installProton("droiddeck") + assertTrue(entered.await(5, TimeUnit.SECONDS)) + activity.startActivity(request("first")) + val saved = save() + cancel() + if (finishBeforeRestore) { + finish.countDown() + waitForInstall() + } + recreate(saved) + if (!finishBeforeRestore) { + advance() + assertEquals(64, loading().percent) + finish.countDown() + waitForInstall() + } + ReflectionHelpers.setField(activity, "compatLaunchVisible", true) + advance() + assertEquals("Checksum verification failed", loading().step) + assertTrue(loading().ended) + assertNull(shadowOf(activity).nextStartedActivity) + } finally { + finish.countDown() + waitForInstall() + } + } + + private fun waitForInstall() { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (protons.protonBusyId != null && System.nanoTime() < deadline) { + shadowOf(Looper.getMainLooper()).idle() + Thread.sleep(10) + } + assertNull(protons.protonBusyId) + } + + private fun save() = Bundle().also { + ReflectionHelpers.callInstanceMethod<Void>(activity, "saveCompatLaunch", ReflectionHelpers.ClassParameter.from(Bundle::class.java, it)) + } + + private fun recreate(saved: Bundle) { + activity = Robolectric.buildActivity(FrontEndActivity::class.java).get() + protons = ReflectionHelpers.getField(activity, "protons") + ReflectionHelpers.callInstanceMethod<Void>(activity, "restoreCompatLaunch", ReflectionHelpers.ClassParameter.from(Bundle::class.java, saved)) + } + + private fun setString(method: String, value: String?, target: FrontEndActivity = activity) { + ReflectionHelpers.callInstanceMethod<Void>(target, method, ReflectionHelpers.ClassParameter.from(String::class.java, value)) + } + + private fun request(url: String) = Intent(activity, SessionActivity::class.java).putExtra(SessionService.EXTRA_STEAM_URL, url) + private fun installing(on: Boolean) = ReflectionHelpers.setStaticField(ProtonExtras::class.java, "installInProgress", on) + private fun waiting(): Any? = ReflectionHelpers.callInstanceMethod(activity, "getCompatLaunch") + private fun loading(): LoadingState = ReflectionHelpers.getField(requireNotNull(waiting()), "loading") + private fun cancel() { ReflectionHelpers.callInstanceMethod<Void>(activity, "cancelCompatLaunch") } + private fun advance() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(250)) +} diff --git a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt index f0424bdaa0..9f79a6efad 100644 --- a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt @@ -56,6 +56,10 @@ class ProtonMenuAutoTest { .put("tag", "${tool.prefix}-11-12").put("at", System.currentTimeMillis())) File(activity.filesDir, "proton-latest.json").writeText(latest.toString()) menu = ProtonMenu(activity, Handler(Looper.getMainLooper())) { idle } + menu.protonBusyId = null + menu.protonProblem = null + menu.protonStage = null + menu.protonPercent = -1 menu.installer = { tool, progress -> progress("Installing ${tool.name}", 50) install("${tool.prefix}-11-12") @@ -64,6 +68,10 @@ class ProtonMenuAutoTest { } @After fun reset() { + menu.protonBusyId = null + menu.protonProblem = null + menu.protonStage = null + menu.protonPercent = -1 AutoComponents.online = online AutoComponents.unfavourable = constrained SessionState.running = false @@ -88,7 +96,7 @@ class ProtonMenuAutoTest { fail("Proton work did not finish") } - @Test fun aCachedCheckUpdatesOnlyInstalledFamiliesAndKeepsOlderBuildsAndSelections() { + @Test fun aCachedCheckUpdatesOnlyInstalledFamiliesAndReplacesOlderDroidDeckProton() { val older = install("DroidDeck-Proton-11-11.1") val request = File(root, "root/.local/share/droiddeck-compat/request.json").apply { parentFile!!.mkdirs() @@ -97,8 +105,8 @@ class ProtonMenuAutoTest { val before = request.readText() assertFalse(ProtonExtras.checkLatest(activity)) menu.checkUpdates() - waitUntil { menu.protonRows.singleOrNull { it.id == "droiddeck" }?.installed == "DroidDeck-Proton-11-12" && menu.protonBusyId == null } - assertTrue(older.isDirectory) + waitUntil { menu.protonRows.singleOrNull { it.id == "droiddeck" }?.installed == "DroidDeck-Proton-11-12" && menu.protonBusyId == null && !older.exists() } + assertEquals(listOf("DroidDeck-Proton-11-12"), ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "droiddeck" })) assertEquals(before, request.readText()) assertTrue(ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "ge" }).isEmpty()) assertTrue(ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "cachyos" }).isEmpty()) @@ -128,7 +136,7 @@ class ProtonMenuAutoTest { @Test fun aFailedUpdateDoesNotLoopOrBlockOtherInstalledFamilies() { val ge = install("GE-Proton11-11") - val dd = install("DroidDeck-Proton-11-11.1") + install("DroidDeck-Proton-11-11.1") menu.installer = { tool, _ -> attempts.add(tool.id) if (tool.id == "ge") throw IllegalStateException("download failed") @@ -138,10 +146,10 @@ class ProtonMenuAutoTest { menu.ensureAutoUpdates() waitUntil { menu.protonBusyId == null } menu.ensureAutoUpdates() - shadowOf(Looper.getMainLooper()).idle() + waitUntil { menu.protonBusyId == null } assertEquals(listOf("ge", "droiddeck"), attempts) assertTrue(ge.isDirectory) - assertTrue(dd.isDirectory) + assertEquals(listOf("DroidDeck-Proton-11-12"), ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "droiddeck" })) assertNull(menu.protonStage) assertEquals(-1, menu.protonPercent) } @@ -184,6 +192,31 @@ class ProtonMenuAutoTest { assertEquals("DroidDeck-Proton-11-12", ProtonExtras.installed(activity, ProtonExtras.tools.first { it.id == "droiddeck" })) } + @Test fun droidDeckProtonIsInstalledWhenMissingUnlessTheUserRemovedIt() { + menu.installer = { tool, _ -> attempts.add(tool.id); install("${tool.prefix}-11-12"); null } + ProtonExtras.setDeclined(activity, true) + menu.ensureAutoUpdates() + assertNull(menu.protonBusyId) + assertTrue(attempts.isEmpty()) + ProtonExtras.setDeclined(activity, false) + menu.ensureAutoUpdates() + waitUntil { menu.protonBusyId == null } + assertEquals(listOf("droiddeck"), attempts) + assertEquals("DroidDeck-Proton-11-12", ProtonExtras.installed(activity, ProtonExtras.tools.first { it.id == "droiddeck" })) + assertTrue(ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "ge" }).isEmpty()) + menu.removeProton("droiddeck") + waitUntil { menu.protonBusyId == null } + assertTrue(ProtonExtras.declined(activity)) + menu.installer = { _, _ -> "failed" } + menu.installProton("droiddeck") + waitUntil { menu.protonBusyId == null } + assertTrue(ProtonExtras.declined(activity)) + menu.installer = { tool, _ -> install("${tool.prefix}-11-12"); null } + menu.installProton("droiddeck") + waitUntil { menu.protonBusyId == null } + assertFalse(ProtonExtras.declined(activity)) + } + @Test fun aPendingAnimatedLaunchPreventsAnAutomaticInstall() { install("DroidDeck-Proton-11-11.1") val launcher = Robolectric.buildActivity(FrontEndActivity::class.java).get() diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentSecurityTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentSecurityTest.kt index df4bb15fc9..f625d6b41b 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/AgentSecurityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentSecurityTest.kt @@ -9,6 +9,8 @@ import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.text.AnnotatedString import com.droiddeck.launcher.R import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.runtime.ProotFastPath +import com.droiddeck.launcher.session.SessionState import org.json.JSONObject import org.junit.Assert.* import org.junit.After @@ -179,6 +181,31 @@ class AgentSecurityTest { assertEquals(listOf("TEST=old", "STICKY=1"), AgentEnv.beginSession(context)) } + @Test fun fastPathLibraryIsValidatedAndSelectedForOneSession() { + AgentAccess.setCommandsEnabled(context, true) + val source = File(AgentEnv.inbox(context).apply { mkdirs() }, "libblfastpath.so") + source.writeText("wrong architecture") + refused("INVALID_LIBRARY") { AgentEnv.override(context, source.name) } + val header = ByteArray(64) + byteArrayOf(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1).copyInto(header) + header[16] = 3 + header[18] = 183.toByte() + source.writeBytes(header) + SessionState.running = true + try { + refused("SESSION_ACTIVE") { AgentEnv.override(context, source.name) } + } finally { + SessionState.running = false + } + val response = AgentEnv.override(context, source.name) + assertEquals(64, response.getString("sha256").length) + assertEquals(ProotFastPath.LIBRARY, AgentEnv.fastPathLibrary(context)) + AgentEnv.beginSession(context) + assertEquals("/opt/droiddeck-agent/bin/libblfastpath.so", AgentEnv.fastPathLibrary(context)) + AgentEnv.endSession(context) + assertEquals(ProotFastPath.LIBRARY, AgentEnv.fastPathLibrary(context)) + } + @Test fun environmentValuesAreNotLogged() { AgentAccess.setCommandsEnabled(context, true) AgentEnv.set(context, listOf("CUSTOM=synthetic-private-value"), false) diff --git a/app/src/test/java/com/droiddeck/launcher/core/BackgroundAppLimitTest.kt b/app/src/test/java/com/droiddeck/launcher/core/BackgroundAppLimitTest.kt new file mode 100644 index 0000000000..1f9d3391e4 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/BackgroundAppLimitTest.kt @@ -0,0 +1,40 @@ +package com.droiddeck.launcher.core + +import com.droiddeck.launcher.session.SessionPrefs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +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 BackgroundAppLimitTest { + @Test fun theLimitIsActivityManagersCachedProcessCap() { + assertEquals("device_config get activity_manager max_cached_processes", BackgroundAppLimit.readCommand()) + assertEquals("device_config put activity_manager max_cached_processes 4", BackgroundAppLimit.setCommand(4)) + assertEquals("device_config put activity_manager max_cached_processes 0", BackgroundAppLimit.setCommand(0)) + assertThrows(IllegalArgumentException::class.java) { BackgroundAppLimit.setCommand(-1) } + } + + @Test fun whatWasThereIsWhatGoesBack() { + assertNull(BackgroundAppLimit.parse("null\n")) + assertNull(BackgroundAppLimit.parse("")) + assertEquals("16", BackgroundAppLimit.parse("16\n")) + assertEquals("device_config delete activity_manager max_cached_processes", BackgroundAppLimit.restoreCommand(null)) + assertEquals("device_config put activity_manager max_cached_processes 16", BackgroundAppLimit.restoreCommand("16")) + } + + @Test fun setupOffersOffAndDeveloperOptionsOwnLimits() { + val context = RuntimeEnvironment.getApplication() + assertEquals(BackgroundAppLimit.OFF, SessionPrefs.backgroundAppLimit(context)) + for (limit in listOf(4, 1, 0, BackgroundAppLimit.OFF)) { + SessionPrefs.setBackgroundAppLimit(context, limit) + assertEquals(limit, SessionPrefs.backgroundAppLimit(context)) + } + assertThrows(IllegalArgumentException::class.java) { SessionPrefs.setBackgroundAppLimit(context, 7) } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/core/DownloadSourceProxyTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DownloadSourceProxyTest.kt new file mode 100644 index 0000000000..46725fc7f2 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/DownloadSourceProxyTest.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.core + +import java.net.InetSocketAddress +import java.net.Proxy +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class DownloadSourceProxyTest { + @Test fun hostAndPortBecomeAnHttpProxy() { + val proxy = DownloadSource.proxyOf("127.0.0.1:9910") + assertEquals(Proxy.Type.HTTP, proxy?.type()) + val address = proxy?.address() as InetSocketAddress + assertEquals("127.0.0.1", address.hostString) + assertEquals(9910, address.port) + } + + @Test fun missingOrInvalidPortIsIgnored() { + assertNull(DownloadSource.proxyOf("")) + assertNull(DownloadSource.proxyOf("127.0.0.1")) + assertNull(DownloadSource.proxyOf("127.0.0.1:")) + assertNull(DownloadSource.proxyOf("127.0.0.1:notaport")) + } + + @Test fun normalizationAcceptsSchemeAndTrailingSlash() { + assertEquals("127.0.0.1:9910", DownloadSource.normalizeProxy(" http://127.0.0.1:9910/ ")) + assertEquals("192.168.1.2:8080", DownloadSource.normalizeProxy("192.168.1.2:8080")) + } + + @Test fun invalidInputDisablesTheProxy() { + assertEquals("", DownloadSource.normalizeProxy("")) + assertEquals("", DownloadSource.normalizeProxy("127.0.0.1")) + assertEquals("", DownloadSource.normalizeProxy("127.0.0.1:70000")) + assertEquals("", DownloadSource.normalizeProxy("http://127.0.0.1:notaport")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/core/HostProcessTest.kt b/app/src/test/java/com/droiddeck/launcher/core/HostProcessTest.kt new file mode 100644 index 0000000000..6fbe7ed10f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/HostProcessTest.kt @@ -0,0 +1,37 @@ +package com.droiddeck.launcher.core + +import org.junit.Assert.assertEquals +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.annotation.Config +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class HostProcessTest { + @get:Rule val temporary = TemporaryFolder() + + @Test fun appendsBothOutputStreamsToTheExistingLog() { + val windows = System.getProperty("os.name").orEmpty().startsWith("Windows") + val log = temporary.newFile("session.log").apply { writeText("guest output\n") } + val script = temporary.newFile(if (windows) "tracer.cmd" else "tracer.sh").apply { + writeText(if (windows) "@echo off\r\necho tracer stdout\r\necho tracer stderr>&2\r\n" + else "printf 'tracer stdout\\n'\nprintf 'tracer stderr\\n' >&2\n") + } + val finished = CountDownLatch(1) + var exitCode = -1 + val shell = if (windows) "cmd.exe /c" else "/bin/sh" + HostProcess.start("$shell ${script.name}", null, temporary.root, { + exitCode = it + finished.countDown() + }, null, log) + assertTrue(finished.await(5, TimeUnit.SECONDS)) + assertEquals(0, exitCode) + assertEquals(listOf("guest output", "tracer stdout", "tracer stderr"), log.readLines()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt b/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt index a67093e935..38849c41a8 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt @@ -195,6 +195,7 @@ class LogRedactorTest { "auth: login=maskeduser42&remember=1", "accountName: maskeduser42", "{\"username\": \"masked user 42\"}", + "[Clubs] {Main} Club membership subscription created: |accountId=maskeduser42", ) for (line in lines) { val out = LogRedactor.redactForShare(line) diff --git a/app/src/test/java/com/droiddeck/launcher/files/StorageRootsTest.kt b/app/src/test/java/com/droiddeck/launcher/files/StorageRootsTest.kt new file mode 100644 index 0000000000..279c69b2a7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/StorageRootsTest.kt @@ -0,0 +1,71 @@ +package com.droiddeck.launcher.files + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class StorageRootsTest { + @Test fun usbAndSdMountsAreFound() { + val mounts = """ + /dev/fuse /mnt/user/0/emulated fuse rw,nosuid,nodev 0 0 + /dev/block/vold/public:8,1 /mnt/media_rw/A1B2-C3D4 vfat rw,dirsync 0 0 + /mnt/media_rw/A1B2-C3D4 /storage/A1B2-C3D4 fuse rw,nosuid,nodev 0 0 + /dev/block/vold/public:179,65 /mnt/media_rw/9C33-1A2B exfat rw,dirsync 0 0 + /mnt/media_rw/9C33-1A2B /storage/9C33-1A2B fuse rw,nosuid,nodev 0 0 + /dev/block/dm-5 /data ext4 rw,seclabel 0 0 + """.trimIndent() + + val points = StorageRoots.parseExternalMounts(mounts).map { it.path } + + assertTrue(points.contains("/storage/A1B2-C3D4")) + assertTrue(points.contains("/storage/9C33-1A2B")) + assertTrue(points.contains("/mnt/media_rw/A1B2-C3D4")) + } + + @Test fun voldLocationsCountWhateverTheFstypeIs() { + val mounts = """ + /dev/block/sda1 /storage/0D19-CC0A fuse rw,nosuid,nodev 0 0 + /dev/block/sda1 /mnt/media_rw/0D19-CC0A exfat rw,dirsync 0 0 + """.trimIndent() + + val points = StorageRoots.parseExternalMounts(mounts).map { it.path } + + assertTrue(points.contains("/storage/0D19-CC0A")) + assertTrue(points.contains("/mnt/media_rw/0D19-CC0A")) + } + + @Test fun usbMountsDirectlyUnderMntAreFound() { + val mounts = """ + /dev/block/sda1 /mnt/usb_storage exfat rw,dirsync 0 0 + tmpfs /mnt/media_rw tmpfs rw,seclabel 0 0 + /dev/fuse /mnt/user/0/emulated fuse rw,nosuid,nodev 0 0 + """.trimIndent() + + val points = StorageRoots.parseExternalMounts(mounts).map { it.path } + + assertTrue(points.contains("/mnt/usb_storage")) + assertEquals(1, points.size) + } + + @Test fun emulatedAndSystemMountsAreIgnored() { + val mounts = """ + /dev/fuse /mnt/user/0/emulated fuse rw,nosuid,nodev 0 0 + /mnt/media_rw/emulated /storage/emulated sdcardfs rw,nosuid,nodev 0 0 + tmpfs /storage/self tmpfs rw,seclabel 0 0 + overlay /system ext4 ro,seclabel 0 0 + /dev/block/sda1 /data ext4 rw,seclabel 0 0 + """.trimIndent() + + assertEquals(emptyList<String>(), StorageRoots.parseExternalMounts(mounts).map { it.path }) + } + + @Test fun escapedSpacesAndNtfsAreHandled() { + val mounts = "/dev/block/vold/public:8,1 /mnt/media_rw/My\\040USB ntfs rw,dirsync 0 0\n" + + "/mnt/media_rw/My\\040USB /storage/My\\040USB fuse rw,nosuid,nodev 0 0\n" + + val points = StorageRoots.parseExternalMounts(mounts).map { it.path } + + assertTrue(points.contains("/mnt/media_rw/My USB")) + assertTrue(points.contains("/storage/My USB")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/LibraryShortcutsLastPlayedTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/LibraryShortcutsLastPlayedTest.kt new file mode 100644 index 0000000000..cc9a1ac7df --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/LibraryShortcutsLastPlayedTest.kt @@ -0,0 +1,54 @@ +package com.droiddeck.launcher.frontend + +import java.io.ByteArrayOutputStream +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class LibraryShortcutsLastPlayedTest { + @get:Rule val tmp = TemporaryFolder() + + private fun steamRoot(): File = tmp.newFolder("Steam").also { root -> + File(root, "config").mkdirs() + File(root, "config/loginusers.vdf").writeText( + "\"users\"\n{\n\t\"76561198352563669\"\n\t{\n\t\t\"AccountName\"\t\t\"a\"\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n") + } + + private class Vdf { + val out = ByteArrayOutputStream() + fun key(type: Int, k: String) { out.write(type); out.write(k.toByteArray()); out.write(0) } + fun map(k: String, body: Vdf.() -> Unit) { key(0, k); body(); out.write(8) } + fun str(k: String, v: String) { key(1, k); out.write(v.toByteArray()); out.write(0) } + fun int(k: String, v: Long) { key(2, k); out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(v.toInt()).array()) } + } + + @Test fun readsEachShortcutsLastPlayTimeByUnsignedAppId() { + val root = steamRoot() + val vdf = Vdf().apply { + map("shortcuts") { + map("0") { int("appid", 3388195926L); str("AppName", "Rayman 2"); int("LastPlayTime", 1792931476L) } + map("1") { int("appid", 2228102537L); str("AppName", "Do Not Disturb"); int("LastPlayTime", 0L) } + map("2") { int("appid", 1234L); str("appname", "Old"); int("lastplaytime", 1700000000L) } + } + out.write(8) + } + File(root, "userdata/392297941/config").apply { mkdirs() }.resolve("shortcuts.vdf").writeBytes(vdf.out.toByteArray()) + assertEquals(mapOf(3388195926L to 1792931476L, 1234L to 1700000000L), Library.shortcutsLastPlayed(root)) + } + + @Test fun missingOrBrokenShortcutsGiveNothing() { + val root = steamRoot() + assertEquals(emptyMap<Long, Long>(), Library.shortcutsLastPlayed(root)) + File(root, "userdata/392297941/config").apply { mkdirs() }.resolve("shortcuts.vdf").writeBytes(byteArrayOf(0, 's'.code.toByte())) + assertEquals(emptyMap<Long, Long>(), Library.shortcutsLastPlayed(root)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/SteamGridTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/SteamGridTest.kt index cc243e7438..7d0618d03e 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/SteamGridTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/SteamGridTest.kt @@ -238,4 +238,17 @@ class SteamGridTest { assertEquals(names.sorted(), names) assertEquals(5L, AddedGameArt.chosen(dir, AddedGameArt.Slot.COVER)?.length()) } + + @Test fun aChoiceSurvivesTheGridFolderBeingWipedAndIsPlacedAgain() { + File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs() + val picked = image("mine.png", 12) + SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)) + assertEquals(12L, File(grid, "620p.png").length()) + + assertTrue(grid.deleteRecursively()) + grid.mkdirs() + assertFalse(SteamGrid.sync(app, listOf(target()))) + assertEquals(12L, SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER)?.length()) + assertEquals(12L, File(grid, "620p.png").length()) + } } 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 fbf077910d..cdad5c09b7 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt @@ -42,6 +42,51 @@ class WinComponentDetectorsTest { assertEquals(emptyList<DependencyDetector.Recommendation>(), SteamRedists.detect(game, 1)) } + @Test fun skyrimGetsTheXactAudioItsInstallScriptRunsOnWindows() { + val steamapps = tmp.newFolder("steamapps") + val game = File(steamapps, "common/Skyrim Special Edition").apply { mkdirs() } + File(steamapps, "appmanifest_489830.acf").writeText("\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228990\"\t\t\"228980\"\n\t}\n}\n") + val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>() + val found = WinCompSources.steamList(context, game, 489830, "Skyrim Special Edition", auto = true) + assertEquals(listOf("d3dx9", "xact_x64"), found.map { it.component }) + assertTrue(found.all { it.auto && it.origin == WinCompSources.Origin.STEAM }) + assertEquals(listOf("DirectX XACT audio (64-bit)", "Skyrim Special Edition", "489830"), found.last().args) + assertEquals(emptyList<String?>(), WinCompSources.steamList(context, game, 409710, "Other", auto = true).map { it.component }) + } + + @Test fun theGamesInstallScriptRedistsAreInstalledAsSteamWould() { + val steamapps = tmp.newFolder("steamapps") + val game = File(steamapps, "common/DiRT 3 Complete Edition").apply { mkdirs() } + File(steamapps, "appmanifest_321040.acf").writeText("\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228983\"\t\t\"228980\"\n\t}\n}\n") + File(game, "installscript.vdf").writeText( + """ + "InstallScript" + { + "Registry" { "HKEY_LOCAL_MACHINE\\Software\\Codemasters" { "string" { "Path" "%INSTALLDIR%" } } } + "Run Process" + { + "OpenAL" + { + "HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\321040" + "process 1" "%INSTALLDIR%\\_CommonRedist\\OpenAL\\2.0.7.0\\oalinst.exe" + "command 1" "/s" + } + "VC2010" + { + "process 1" "%INSTALLDIR%\\_CommonRedist\\vcredist\\2010\\vcredist_x86.exe" + } + } + } + """.trimIndent(), + ) + assertEquals(listOf("oalinst", "vcredist2010"), SteamRedists.installScript(game).map { it.first }) + val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>() + val found = WinCompSources.steamList(context, game, 321040, "DiRT 3 Complete Edition", auto = true) + assertEquals(listOf("vcredist2010_dll", "oalinst"), found.map { it.component }) + assertTrue(found.all { it.auto && it.origin == WinCompSources.Origin.STEAM }) + assertEquals(emptyList<Pair<String, String>>(), SteamRedists.installScript(File(steamapps, "missing"))) + } + @Test fun thePrefixCountsOnlyWhatDroidDeckDidNotPutThere() { val compat = tmp.newFolder("compatdata", "409710") val pfx = File(compat, "pfx") diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesMirrorPacingTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesMirrorPacingTest.kt index b8306b936d..a8dff5a443 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesMirrorPacingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesMirrorPacingTest.kt @@ -1,10 +1,13 @@ package com.droiddeck.launcher.glasses +import android.content.Context +import android.database.ContentObserver +import android.provider.Settings import android.hardware.display.DisplayManager import android.view.Display import androidx.compose.runtime.MutableState import com.droiddeck.launcher.SessionActivity -import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.session.SessionPrefs import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before @@ -36,10 +39,12 @@ class GlassesMirrorPacingTest { val panel = Shadow.extract<ModeDisplay>(activity.display) panel.supported = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f)) panel.current = panel.supported.last() - SessionState.fpsLimit = 0 + activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() } - @After fun cleanup() { SessionState.fpsLimit = 0 } + @After fun cleanup() { + activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } @Test fun connectingChangingRateAndDisconnectingUpdatePhonePacingWithoutSavingPreferences() { apply(connected, settings) @@ -47,25 +52,33 @@ class GlassesMirrorPacingTest { apply(connected, settings.copy(refreshHz = 90)) expect(2, 90f, 90) apply(GlassesState(), settings) - expect(3, 120f, 0) - assertEquals(0, SessionState.fpsLimit) + expect(3, 120f, SessionPrefs.FPS_UNPACED) } - @Test fun lowerSavedLimitSurvivesMirroringAndStalePhoneRefreshReports() { - SessionState.fpsLimit = 30 + @Test fun retiredSavedLimitsDoNotCapThePhoneOrMirroredOutput() { + activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit() + .putInt("fpsLimit.steam", 30).putInt("fpsLimit.desktop", 40).commit() apply(connected, settings) - expect(1, 60f, 30) + expect(1, 60f, 60) apply(connected.copy(hz = 120f), settings) - expect(1, 60f, 30) + expect(1, 60f, 60) apply(GlassesState(), settings) - expect(3, 120f, 30) - assertEquals(30, SessionState.fpsLimit) + expect(3, 120f, SessionPrefs.FPS_UNPACED) } @Test fun pacingFollowsThePanelWhenTheSystemKeepsALowerRateThanRequested() { Shadow.extract<ModeDisplay>(activity.display).current = mode(2, 90f) apply(GlassesState(), settings) - expect(3, 90f, 0) + expect(3, 90f, SessionPrefs.FPS_UNPACED) + } + + @Test fun aHigherRefreshSettingChoosesTheFasterModeAgain() { + Settings.System.putFloat(activity.contentResolver, "peak_refresh_rate", 60f) + apply(GlassesState(), settings) + assertEquals(1, activity.window.attributes.preferredDisplayModeId) + Settings.System.putFloat(activity.contentResolver, "peak_refresh_rate", 120f) + ReflectionHelpers.getField<ContentObserver>(activity, "refreshSettingObserver").onChange(false) + assertEquals(3, activity.window.attributes.preferredDisplayModeId) } private fun apply(state: GlassesState, config: GlassesSettings) { diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesRenderingTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesRenderingTest.kt index 51d9aa7b72..4b5972ede3 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesRenderingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesRenderingTest.kt @@ -58,13 +58,6 @@ class GlassesRenderingTest { assertEquals(0, GlassesRendering.mirrorRefreshLimit(settings, ultra, true)) } - @Test fun mirrorCapPreservesLowerLimitsAndRestoresTheRequestedLimitAfterDisconnect() { - for (requested in listOf(0, 30, 60, 90, 120)) { - assertEquals(if (requested == 30) 30 else 60, GlassesRendering.fpsLimit(requested, 60)) - assertEquals(requested, GlassesRendering.fpsLimit(requested, 0)) - } - } - private fun render(settings: GlassesSettings, state: GlassesState = ultra, steamVr: Boolean = false) = GlassesRendering.cardboard(base, settings, state, outputActive = true, steamVrRunning = steamVr) 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 225805dc65..14dcf26d69 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt @@ -269,6 +269,17 @@ class GlassesUsbTest { assertTrue(Glasses.isGlassesDisplayName("Rokid Max")) } + @Test fun rokidMax2RequestsPermissionForItsOwnProductId() { + val max2 = device(0x2002, 0x04d2, "Rokid Max2") + manager.devices[max2.deviceName] = max2 + refresh(ask = true) + assertEquals("Rokid Max2", state.value.model) + assertTrue(state.value.controllable) + assertEquals(listOf(max2), manager.requests) + assertTrue(Glasses.isGlassesDisplayName("Rokid Max 2")) + assertEquals(null, Glasses.deviceModel(device(0x2002, 0x04d2, "Generic HID"))) + } + private fun device(pid: Int, vid: Int = VitureProtocol.VENDOR_ID, name: String = "VITURE device"): UsbDevice = ReflectionHelpers.callConstructor( UsbDevice::class.java, from(String::class.java, "/dev/bus/usb/$pid"), diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/RokidProtocolTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/RokidProtocolTest.kt index c2cf38e33b..538958801f 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/RokidProtocolTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/RokidProtocolTest.kt @@ -13,6 +13,10 @@ class RokidProtocolTest { @Test fun identityRequiresRokidProductString() { assertEquals("Rokid Max", RokidModel.model(0x04d2, 0x162f, "Rokid Max")?.name) assertEquals("Rokid Air", RokidModel.model(0x04d2, 0x162f, "Rokid Air")?.name) + assertEquals("Rokid Max2", RokidModel.model(0x04d2, 0x2002, "Rokid Max2")?.name) + assertNull(RokidModel.model(0x04d2, 0x2002, "USB Keyboard")) + assertNull(RokidModel.model(0x04d2, 0x2002, null)) + assertNull(RokidModel.model(0x1234, 0x2002, "Rokid Max2")) assertNull(RokidModel.model(0x04d2, 0x162f, "USB Keyboard")) assertNull(RokidModel.model(0x04d2, 0x162f, null)) assertNull(RokidModel.model(0x04d2, 0x1234, "Rokid Max")) @@ -40,6 +44,21 @@ class RokidProtocolTest { assertEquals(listOf(60), air.rates2d) } + @Test fun max2UsesMaxModesAndParsesItsCapturedCombinedReport() { + val max2 = RokidModel.model(0x04d2, 0x2002, "Rokid Max2")!! + assertEquals(RokidModel.MODE_2D_120, max2.mode(120, false, null)) + assertEquals(RokidModel.MODE_SBS_1080_60, max2.mode(60, true, GlassesResolution(1920, 1080))) + assertEquals(RokidModel.MODE_SBS_1200_90, max2.mode(90, true, null)) + val packet = hex("119ceac6a47b000000542389bf2f430f41de9f6fc000967a38666144bbd0d4413b66661bc2cdcc2c4066e6e142000000ea70a2a47b0000000000006464000000") + val sample = RokidProtocol.Parser().parse(packet)!! + assertEquals(0x7ba4c6ea9cL, sample.timeNs) + assertEquals(8.954f, sample.accel.y, 0.001f) + assertEquals(100, sample.brightness) + val pose = ImuFusion().update(sample.timeNs, sample.accel, sample.gyro) + assertNotNull(pose) + assertTrue(pose!!.all { it.isFinite() }) + } + @Test fun brightnessStepsRoundTripTheDevicePercent() { assertEquals(8, RokidModel.brightnessStep(80)) assertEquals(10, RokidModel.brightnessStep(100)) diff --git a/app/src/test/java/com/droiddeck/launcher/input/BackQamInputTest.kt b/app/src/test/java/com/droiddeck/launcher/input/BackQamInputTest.kt new file mode 100644 index 0000000000..5759556aea --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/BackQamInputTest.kt @@ -0,0 +1,247 @@ +package com.droiddeck.launcher.input + +import android.os.Looper +import android.view.KeyEvent +import java.time.Duration +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE) +class BackQamInputTest { + private val changes = mutableListOf<Boolean>() + private val taps = mutableListOf<Boolean>() + private val input = BackQamInput(changes::add, taps::add) + + @Test fun singleTapWaitsForTheDoubleTapWindowWithoutPressingQam() { + send(KeyEvent.ACTION_DOWN) + advance(100) + send(KeyEvent.ACTION_UP) + advance(499) + assertTrue(taps.isEmpty()) + advance(1) + assertEquals(listOf(false), taps) + assertTrue(changes.isEmpty()) + } + + @Test fun doubleTapProducesOnlyTheDoubleAction() { + repeat(2) { + send(KeyEvent.ACTION_DOWN) + advance(100) + send(KeyEvent.ACTION_UP) + advance(100) + } + advance(1000) + assertEquals(listOf(true), taps) + assertTrue(changes.isEmpty()) + } + + @Test fun theConfiguredWindowControlsSingleAndDoubleTaps() { + for (window in listOf(100L, 800L)) { + taps.clear() + val configured = BackQamInput(changes::add, taps::add, doubleTapMs = { window }) + fun press(action: Int) = configured.onKeyEvent(KeyEvent(action, KeyEvent.KEYCODE_BACK), true) + press(KeyEvent.ACTION_DOWN) + press(KeyEvent.ACTION_UP) + advance(window - 1) + assertTrue(taps.isEmpty()) + press(KeyEvent.ACTION_DOWN) + press(KeyEvent.ACTION_UP) + assertEquals(listOf(true), taps) + taps.clear() + press(KeyEvent.ACTION_DOWN) + press(KeyEvent.ACTION_UP) + advance(window - 1) + assertTrue(taps.isEmpty()) + advance(1) + assertEquals(listOf(false), taps) + assertTrue(changes.isEmpty()) + } + } + + @Test fun aHoldStartsAt700msAndNeverProducesATap() { + assertTrue(send(KeyEvent.ACTION_DOWN)) + advance(699) + assertTrue(changes.isEmpty()) + advance(1) + for (repeat in 1..10) assertTrue(send(KeyEvent.ACTION_DOWN, repeat = repeat)) + advance(4000) + assertEquals(listOf(true), changes) + assertTrue(send(KeyEvent.ACTION_UP)) + advance(1000) + assertEquals(listOf(true, false), changes) + assertTrue(taps.isEmpty()) + } + + @Test fun releasingBetween500And700msStillProducesASingleTap() { + send(KeyEvent.ACTION_DOWN) + advance(600) + send(KeyEvent.ACTION_UP) + advance(500) + assertEquals(listOf(false), taps) + assertTrue(changes.isEmpty()) + } + + @Test fun holdingTheSecondPressCancelsTheFirstTap() { + send(KeyEvent.ACTION_DOWN) + send(KeyEvent.ACTION_UP) + advance(400) + send(KeyEvent.ACTION_DOWN) + advance(699) + assertTrue(taps.isEmpty()) + advance(1) + assertEquals(listOf(true), changes) + send(KeyEvent.ACTION_UP) + advance(1000) + assertTrue(taps.isEmpty()) + } + + @Test fun otherButtonsAndSelectPassThroughWhileBackIsHeld() { + send(KeyEvent.ACTION_DOWN) + advance(700) + for (code in listOf(KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_BUTTON_SELECT)) { + for (action in listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) { + assertFalse(input.onKeyEvent(KeyEvent(action, code), true)) + } + } + assertEquals(listOf(true), changes) + send(KeyEvent.ACTION_UP) + assertEquals(listOf(true, false), changes) + } + + @Test fun aChordImmediatelyStartsAHoldAndSuppressesTheTap() { + send(KeyEvent.ACTION_DOWN) + advance(25) + input.onChordInput() + assertEquals(listOf(true), changes) + input.onChordInput() + send(KeyEvent.ACTION_UP) + advance(1000) + assertEquals(listOf(true, false), changes) + assertTrue(taps.isEmpty()) + } + + @Test fun aChordOnTheSecondPressCancelsBothTapActions() { + send(KeyEvent.ACTION_DOWN) + send(KeyEvent.ACTION_UP) + advance(100) + send(KeyEvent.ACTION_DOWN) + input.onChordInput() + send(KeyEvent.ACTION_UP) + advance(1000) + assertEquals(listOf(true, false), changes) + assertTrue(taps.isEmpty()) + } + + @Test fun controllerInputAfterBackIsReleasedOrCancelledCannotStartAHold() { + send(KeyEvent.ACTION_DOWN) + send(KeyEvent.ACTION_UP) + input.onChordInput() + advance(500) + assertEquals(listOf(false), taps) + send(KeyEvent.ACTION_DOWN) + input.cancel() + input.onChordInput() + advance(1000) + assertTrue(changes.isEmpty()) + } + + @Test fun anImmediateChordKeepsAllBackOwnersUntilTheLastRelease() { + send(KeyEvent.ACTION_DOWN, device = 4) + send(KeyEvent.ACTION_DOWN, device = 5) + input.onChordInput() + input.onDeviceRemoved(4) + assertEquals(listOf(true), changes) + send(KeyEvent.ACTION_UP, device = 5) + advance(1000) + assertEquals(listOf(true, false), changes) + assertTrue(taps.isEmpty()) + } + + @Test fun disabledRoutingPreservesBackNavigation() { + assertFalse(send(KeyEvent.ACTION_DOWN, enabled = false)) + assertFalse(send(KeyEvent.ACTION_UP, enabled = false)) + assertTrue(changes.isEmpty()) + assertTrue(taps.isEmpty()) + } + + @Test fun losingFocusReleasesQamAndConsumesTheLateRelease() { + send(KeyEvent.ACTION_DOWN) + advance(700) + input.cancel() + input.cancel() + assertTrue(send(KeyEvent.ACTION_DOWN, repeat = 1, enabled = false)) + assertTrue(send(KeyEvent.ACTION_UP, enabled = false)) + advance(1000) + assertEquals(listOf(true, false), changes) + assertTrue(taps.isEmpty()) + } + + @Test fun cancellationBeforeTheThresholdPreventsBothHoldAndTap() { + send(KeyEvent.ACTION_DOWN) + advance(100) + input.cancel() + send(KeyEvent.ACTION_UP) + advance(1000) + assertTrue(changes.isEmpty()) + assertTrue(taps.isEmpty()) + } + + @Test fun cancellationAlsoDiscardsAPendingSingleTap() { + send(KeyEvent.ACTION_DOWN) + send(KeyEvent.ACTION_UP) + input.cancel() + advance(1000) + assertTrue(taps.isEmpty()) + } + + @Test fun openingAnOverlayReleasesQamBeforeRoutingItsNextKey() { + send(KeyEvent.ACTION_DOWN) + advance(700) + assertFalse(input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_B), false)) + assertTrue(send(KeyEvent.ACTION_UP, enabled = false)) + assertEquals(listOf(true, false), changes) + } + + @Test fun repeatsAfterCancellationCannotReassertQam() { + send(KeyEvent.ACTION_DOWN) + advance(700) + input.cancel() + assertTrue(send(KeyEvent.ACTION_DOWN, repeat = 1)) + advance(1000) + assertEquals(listOf(true, false), changes) + assertTrue(send(KeyEvent.ACTION_DOWN)) + advance(700) + assertTrue(send(KeyEvent.ACTION_UP)) + assertEquals(listOf(true, false, true, false), changes) + } + + @Test fun cancelledReleaseNeverProducesATap() { + send(KeyEvent.ACTION_DOWN) + assertTrue(input.onKeyEvent(KeyEvent(0, 100, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK, + 0, 0, 4, 0, KeyEvent.FLAG_CANCELED), true)) + advance(1000) + assertTrue(changes.isEmpty()) + assertTrue(taps.isEmpty()) + } + + @Test fun removingOneDeviceDoesNotReleaseAnotherDevicesHold() { + send(KeyEvent.ACTION_DOWN, device = 4) + send(KeyEvent.ACTION_DOWN, device = 5) + advance(700) + input.onDeviceRemoved(4) + assertEquals(listOf(true), changes) + send(KeyEvent.ACTION_UP, device = 5) + assertEquals(listOf(true, false), changes) + assertTrue(taps.isEmpty()) + } + + private fun advance(millis: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(millis)) + + private fun send(action: Int, repeat: Int = 0, device: Int = 4, enabled: Boolean = true) = + input.onKeyEvent(KeyEvent(0, 100, action, KeyEvent.KEYCODE_BACK, repeat, 0, device, 0), enabled) +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/DirectTouchHoldTest.kt b/app/src/test/java/com/droiddeck/launcher/input/DirectTouchHoldTest.kt index d7dd5307a9..513ee330f3 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/DirectTouchHoldTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/DirectTouchHoldTest.kt @@ -22,7 +22,7 @@ class DirectTouchHoldTest { } override fun onWheel(steps: Int) {} override fun onLongPress() {} - }) { events += "cancel touch" } + }) { events += "cancel touch" }.also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) } @Test fun holdReleasesRawTouchBeforeClickAndConsumesTheLift() { assertFalse(touch(MotionEvent.ACTION_DOWN)) @@ -35,6 +35,25 @@ class DirectTouchHoldTest { hold.cancel() } + @Test fun stillHoldKeepsTheTouchWhenLongPressIsOff() { + hold.configure(TouchGestureConfig()) + assertFalse(touch(MotionEvent.ACTION_DOWN)) + advance(2000) + assertFalse(touch(MotionEvent.ACTION_MOVE)) + assertFalse(touch(MotionEvent.ACTION_UP)) + assertTrue(events.isEmpty()) + } + + @Test fun longPressFollowsTheConfiguredDelay() { + hold.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 800)) + touch(MotionEvent.ACTION_DOWN) + advance(700) + assertTrue(events.isEmpty()) + advance(100) + assertEquals(listOf("cancel touch", "true at 40.0,30.0"), events) + hold.cancel() + } + @Test fun tapDragSecondFingerAndCancellationDoNotRightClick() { for (action in listOf(MotionEvent.ACTION_UP, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_CANCEL)) { diff --git a/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt b/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt new file mode 100644 index 0000000000..3d2a2863ee --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.input + +import android.app.Application +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 = [28, 33], manifest = Config.NONE, application = Application::class) +class HomeGuideInputTest { + private val states = mutableListOf<Boolean>() + private var cancellations = 0 + private val input = HomeGuideInput({ states.add(it) }, { cancellations++ }) + + private fun home(action: Int, device: Int = 10, repeat: Int = 0, down: Long = 10) = + KeyEvent(down, down + 100, action, KeyEvent.KEYCODE_HOME, repeat, 0, device, 102) + + @Test fun guideIsHeldImmediatelyAndReleaseDoesNotDependOnAndroidDownTime() { + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true)) + assertEquals(listOf(true), states) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN, repeat = 1), true)) + assertFalse(input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_X), true)) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP, down = 77), true)) + assertEquals(listOf(true, false), states) + } + + @Test fun genericLayoutMoveHomeHoldsGuideLikeHome() { + val down = KeyEvent(10, 110, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MOVE_HOME, 0, 0, 10, 102) + val up = KeyEvent(10, 200, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MOVE_HOME, 0, 0, 10, 102) + assertTrue(input.onKeyEvent(down, true)) + assertTrue(input.onKeyEvent(up, true)) + assertEquals(listOf(true, false), states) + } + + @Test fun anUnownedHomePressKeepsAndroidBehaviorEvenIfSessionBecomesEligibleBeforeRelease() { + assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), false)) + assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_UP), true)) + assertTrue(states.isEmpty()) + } + + @Test fun focusLossReleasesGuideAndConsumesTheOwnedReleaseWithoutAnotherTap() { + input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true) + input.cancel() + assertEquals(1, cancellations) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN, repeat = 2), false)) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP), false)) + assertEquals(listOf(true, false), states) + assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_UP), false)) + } + + @Test fun disablingDuringAHoldReleasesItAndDoesNotStealTheNextAndroidHomePress() { + input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP), false)) + assertEquals(listOf(true, false), states) + assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), false)) + } + + @Test fun guideStaysHeldUntilAllOwnersReleaseAndDisconnectCancelsTheLastOwner() { + input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true) + input.onKeyEvent(home(KeyEvent.ACTION_DOWN, device = 11), true) + input.onKeyEvent(home(KeyEvent.ACTION_UP), true) + assertEquals(listOf(true), states) + input.onDeviceRemoved(11) + assertEquals(listOf(true, false), states) + assertEquals(1, cancellations) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/JoyConPadTest.kt b/app/src/test/java/com/droiddeck/launcher/input/JoyConPadTest.kt index 43f0a8d82a..a325632132 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/JoyConPadTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/JoyConPadTest.kt @@ -19,6 +19,7 @@ import org.robolectric.annotation.Config import org.robolectric.annotation.Implementation import org.robolectric.annotation.Implements import org.robolectric.shadows.InputDeviceBuilder +import org.robolectric.shadows.ShadowBuild @RunWith(RobolectricTestRunner::class) @Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"], @@ -82,6 +83,34 @@ class JoyConPadTest { assertEquals(0, RecordingWriter.grips) } + @Test fun novaControllerUsesCForTheLeftPaddleAndZForTheRight() { + ShadowBuild.setModel("Retroid Pocket Nova") + for (product in listOf(0x3001, 0x3002)) { + val pad = controller(0x2022, product) + assertPaddles(pad, KeyEvent.KEYCODE_BUTTON_C, KeyEvent.KEYCODE_BUTTON_Z) + bridge.onDeviceRemoved(pad.id) + } + } + + @Test fun theSameControllerIdsKeepTheDefaultPaddlesOnOtherHandhelds() { + for (product in listOf(0x3001, 0x3002)) { + val pad = controller(0x2022, product) + for (model in listOf("Retroid Pocket 6", "Retroid Pocket 5", "AYN Thor")) { + ShadowBuild.setModel(model) + assertPaddles(pad, KeyEvent.KEYCODE_BUTTON_Z, KeyEvent.KEYCODE_BUTTON_C) + } + bridge.onDeviceRemoved(pad.id) + } + } + + @Test fun otherControllerIdsKeepTheDefaultPaddlesOnANova() { + ShadowBuild.setModel("Retroid Pocket Nova") + for (pad in listOf(controller(0x045e, 0x0b13), controller(0x2022, 0x3003), controller(0x2020, 0x3001))) { + assertPaddles(pad, KeyEvent.KEYCODE_BUTTON_Z, KeyEvent.KEYCODE_BUTTON_C) + bridge.onDeviceRemoved(pad.id) + } + } + @Test fun whenOneJoyConLeavesTheOtherKeepsThePlayer() { pair() assertTrue(press(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH)) @@ -140,6 +169,17 @@ class JoyConPadTest { private fun pad(slot: Int): PadState = RecordingWriter.pads[slot] ?: PadState() + private fun assertPaddles(device: InputDevice, leftCode: Int, rightCode: Int) { + assertTrue(bridge.onKeyEvent(key(device, leftCode, 0))) + assertEquals(DeckControls.L4, RecordingWriter.grips) + assertTrue(bridge.onKeyEvent(key(device, rightCode, 0))) + assertEquals(DeckControls.L4 or DeckControls.R4, RecordingWriter.grips) + assertTrue(bridge.onKeyEvent(key(device, leftCode, 0, KeyEvent.ACTION_UP))) + assertEquals(DeckControls.R4, RecordingWriter.grips) + assertTrue(bridge.onKeyEvent(key(device, rightCode, 0, KeyEvent.ACTION_UP))) + assertEquals(0, RecordingWriter.grips) + } + private fun press(device: InputDevice, code: Int, scanCode: Int): Boolean = bridge.onKeyEvent(JoyCon.normalize(key(device, code, scanCode))) @@ -162,10 +202,12 @@ class JoyConPadTest { private var nextId = 60 - private fun joyCon(product: Int, vararg axes: Int): InputDevice { + private fun joyCon(product: Int, vararg axes: Int): InputDevice = controller(NINTENDO, product, *axes) + + private fun controller(vendor: Int, product: Int, vararg axes: Int): InputDevice { val id = nextId++ val builder = InputDeviceBuilder.newBuilder().setId(id).setName("Joy-Con $id").setDescriptor("joycon-$id") - .setExternal(true).setVendorId(NINTENDO).setProductId(product) + .setExternal(true).setVendorId(vendor).setProductId(product) .setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK or InputDevice.SOURCE_KEYBOARD) .setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC) .setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)) diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt index a1bb94bf1a..a857316e53 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt @@ -236,6 +236,53 @@ class OnScreenControlsTest { assertEquals(-1, field(control("ls"), "pressedBy")) } + @Test fun trackpadFingerKeepsItsOwnStreamWhileAStickIsHeld() { + val forwarded = mutableListOf<Triple<Int, Int, Float>>() + view.onTouchMiss = { forwarded += Triple(it.actionMasked, it.getPointerId(0), it.getX(0)) } + touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f)) + assertTrue(touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (540f to 400f), 9 to (600f to 200f))) + touch(MotionEvent.ACTION_MOVE, 7 to (500f to 400f), 9 to (650f to 200f)) + touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 7 to (500f to 400f), 9 to (650f to 200f)) + assertEquals(listOf( + Triple(MotionEvent.ACTION_DOWN, 9, 600f), + Triple(MotionEvent.ACTION_MOVE, 9, 650f), + Triple(MotionEvent.ACTION_UP, 9, 650f), + ), forwarded) + assertEquals(7, field(control("ls"), "pressedBy")) + assertTrue(value(control("ls"), "kx") < 0f) + } + + @Test fun stickPressedAfterTrackpadFingerReachesTheControls() { + val received = mutableListOf<Triple<Int, Int, Int>>() + val trackpad = View(context).apply { + setOnTouchListener { _, event -> received += Triple(event.actionMasked, event.pointerCount, event.getPointerId(0)); true } + } + val root = FrameLayout(context).apply { + isMotionEventSplittingEnabled = true + addView(trackpad, FrameLayout.LayoutParams(1200, 800)) + addView(view, FrameLayout.LayoutParams(1200, 800)) + measure(View.MeasureSpec.makeMeasureSpec(1200, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY)) + layout(0, 0, 1200, 800) + } + fun dispatch(action: Int, vararg pointers: Pair<Int, Pair<Float, Float>>) { + val properties = pointers.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray() + val coords = pointers.map { (_, position) -> MotionEvent.PointerCoords().apply { x = position.first; y = position.second; pressure = 1f; size = 1f } }.toTypedArray() + val event = MotionEvent.obtain(1000L, time++, action, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0) + try { assertTrue(root.dispatchTouchEvent(event)) } finally { event.recycle() } + } + dispatch(MotionEvent.ACTION_DOWN, 0 to (600f to 200f)) + dispatch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 0 to (600f to 200f), 1 to (540f to 400f)) + dispatch(MotionEvent.ACTION_MOVE, 0 to (640f to 220f), 1 to (500f to 400f)) + assertEquals(1, field(control("ls"), "pressedBy")) + assertTrue(value(control("ls"), "kx") < 0f) + dispatch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 0 to (640f to 220f), 1 to (500f to 400f)) + dispatch(MotionEvent.ACTION_UP, 0 to (640f to 220f)) + assertEquals(-1, field(control("ls"), "pressedBy")) + assertEquals(Triple(MotionEvent.ACTION_DOWN, 1, 0), received.first()) + assertEquals(Triple(MotionEvent.ACTION_UP, 1, 0), received.last()) + assertTrue(received.all { it.second == 1 && it.third == 0 }) + } + @Test fun adaptiveActivationLeavesFivePixelsAroundButtonHitTargets() { for (id in listOf("a", "rb")) { val button = control(id) diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt new file mode 100644 index 0000000000..47bf0719c0 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt @@ -0,0 +1,463 @@ +package com.droiddeck.launcher.input + +import android.os.Handler +import android.os.Looper +import android.hardware.input.InputManager +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent +import com.droiddeck.launcher.session.SessionState +import java.nio.file.Files +import java.time.Duration +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers +import org.robolectric.shadows.InputDeviceBuilder + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter", "com.droiddeck.launcher.wayland.WaylandCompositor"], + shadows = [JoyConPadTest.RecordingWriter::class, PadBridgeRoutingTest.RegisteredKeyEvent::class, + PadBridgeRoutingTest.RegisteredMotionEvent::class, SessionGestureRoutingTest.CompositorShadow::class]) +class PadBridgeQamTest { + private val directory = Files.createTempDirectory("qam-pad").toFile() + private lateinit var bridge: PadBridge + + @Before fun start() { + JoyConPadTest.RecordingWriter.pads.clear() + ReflectionHelpers.setStaticField(FakeInputWriter::class.java, "padType", FakeInputWriter.PAD_TYPE_DECK) + SessionState.deckPad = true + bridge = PadBridge(directory) + assertTrue(bridge.start()) + } + + @After fun stop() { + bridge.stop() + SessionState.deckPad = false + directory.deleteRecursively() + } + + @Test fun onlyNativeQamControllersAcceptAHeldBack() { + for (type in listOf(-1, FakeInputWriter.PAD_TYPE_DECK, FakeInputWriter.PAD_TYPE_STEAM, + FakeInputWriter.PAD_TYPE_XBOX, FakeInputWriter.PAD_TYPE_DS4, FakeInputWriter.PAD_TYPE_DUALSENSE)) { + ReflectionHelpers.setStaticField(FakeInputWriter::class.java, "padType", type) + val supported = type <= FakeInputWriter.PAD_TYPE_STEAM + assertEquals(supported, bridge.canHoldQam()) + bridge.setBackQamPressed(true) + bridge.applyExternal({}, false) + assertEquals(supported, pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(false) + advanceTime() + } + SessionState.deckPad = false + assertFalse(bridge.canHoldQam()) + } + + @Test fun qamAndOtherButtonsShareAReportUntilBackIsReleased() { + bridge.setBackQamPressed(true) + advanceTime() + bridge.applyExternal({ it.press(PadState.X, true); it.press(PadState.SELECT, true) }, true) + advanceTime() + assertTrue(pad().isDown(PadState.QAM)) + assertTrue(pad().isDown(PadState.X)) + assertTrue(pad().isDown(PadState.SELECT)) + bridge.setBackQamPressed(false) + advanceTime() + assertFalse(pad().isDown(PadState.QAM)) + assertTrue(pad().isDown(PadState.X)) + assertTrue(pad().isDown(PadState.SELECT)) + } + + @Test fun touchQamAndBackHaveIndependentReleases() { + bridge.setBackQamPressed(true) + bridge.setSystemButtons(false, true) + bridge.setBackQamPressed(false) + assertTrue(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(true) + bridge.setSystemButtons(false, false) + assertTrue(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(false) + advanceTime() + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun aTimedQamTapCannotReleaseAHeldBack() { + bridge.triggerQam() + bridge.setBackQamPressed(true) + advanceTime() + assertTrue(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(false) + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun releasingAllOrStoppingClearsTheHold() { + bridge.setBackQamPressed(true) + bridge.releaseAll() + assertFalse(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(true) + bridge.stop() + bridge.start() + bridge.applyExternal({}, false) + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun disablingTheBuiltinPadClearsAndRejectsTheHold() { + bridge.setBackQamPressed(true) + bridge.setBuiltinPad(false) + assertFalse(bridge.canHoldQam()) + assertFalse(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(true) + bridge.setBuiltinPad(true) + bridge.applyExternal({}, false) + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun aQuickPartnerPressReachesSteamWithQamAndReleasesIndependently() { + val device = controller() + val taps = mutableListOf<Boolean>() + val input = BackQamInput(bridge::setBackQamPressed, taps::add) + bridge.setOnChordInput { + assertFalse(pad().isDown(PadState.X)) + input.onChordInput() + } + input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK), true) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(25)) + assertTrue(bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X))) + assertTrue(pad().isDown(PadState.QAM)) + assertFalse(pad().isDown(PadState.X)) + advance(79) + assertFalse(pad().isDown(PadState.X)) + advance(1) + assertTrue(pad().isDown(PadState.X)) + input.onKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK), true) + assertFalse(pad().isDown(PadState.QAM)) + assertTrue(pad().isDown(PadState.X)) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.ACTION_UP)) + advance(80) + assertFalse(pad().isDown(PadState.X)) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertTrue(taps.isEmpty()) + } + + @Test fun onlyFreshAcceptedPrimaryControllerPressesPromoteAChord() { + val device = controller() + val second = controller(11) + val promoted = mutableListOf<Boolean>() + bridge.setOnChordInput { promoted.add(true) } + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.ACTION_UP)) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X, repeat = 1)) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_A)) + bridge.onKeyEvent(key(second, KeyEvent.KEYCODE_BUTTON_X)) + bridge.setExcluded { it == device.id } + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X)) + assertTrue(promoted.isEmpty()) + bridge.setExcluded { false } + for (code in listOf(KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_BUTTON_L2)) { + bridge.onKeyEvent(key(device, code)) + } + assertEquals(3, promoted.size) + } + + @Test fun aQuickChordKeepsItsPressAndReleaseAfterTheModifierLead() { + bridge.setBackQamPressed(true) + bridge.applyExternal({ it.press(PadState.X, true) }, true) + advance(20) + bridge.applyExternal({ it.press(PadState.X, false) }, true) + bridge.setBackQamPressed(false) + assertTrue(pad().isDown(PadState.QAM)) + assertFalse(pad().isDown(PadState.X)) + advance(60) + assertTrue(pad().isDown(PadState.QAM)) + assertTrue(pad().isDown(PadState.X)) + advance(19) + assertTrue(pad().isDown(PadState.X)) + advance(1) + assertFalse(pad().isDown(PadState.X)) + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun cancellationDiscardsQueuedPartnersAndTheirReleases() { + val input = BackQamInput(bridge::setBackQamPressed, {}, onCancel = bridge::cancelBackQam) + input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK), true) + input.onChordInput() + bridge.applyExternal({ it.press(PadState.LB, true) }, true) + input.onKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK), true) + input.cancel() + advance(1000) + assertFalse(pad().isDown(PadState.LB)) + assertFalse(pad().isDown(PadState.QAM)) + bridge.applyExternal({ it.press(PadState.X, true) }, true) + input.cancel() + assertTrue(pad().isDown(PadState.X)) + } + + @Test fun aSettledHoldDoesNotDelayLaterPartnerInput() { + bridge.setBackQamPressed(true) + advance(80) + bridge.applyExternal({ it.press(PadState.LB, true) }, true) + assertTrue(pad().isDown(PadState.LB)) + bridge.setBackQamPressed(false) + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun disconnectingThePartnerControllerDiscardsItsQueuedPress() { + val device = controller() + bridge.setBackQamPressed(true) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1)) + advance(20) + bridge.onDeviceRemoved(device.id) + assertTrue(pad().isDown(PadState.QAM)) + assertFalse(pad().isDown(PadState.LB)) + advance(60) + assertFalse(pad().isDown(PadState.LB)) + advance(1000) + assertFalse(pad().isDown(PadState.LB)) + assertTrue(pad().isDown(PadState.QAM)) + } + + @Test fun disconnectingThePartnerControllerImmediatelyReleasesADeliveredPress() { + val device = controller() + bridge.setBackQamPressed(true) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1)) + advance(80) + assertTrue(pad().isDown(PadState.LB)) + bridge.onDeviceRemoved(device.id) + assertFalse(pad().isDown(PadState.LB)) + assertTrue(pad().isDown(PadState.QAM)) + advance(1000) + assertFalse(pad().isDown(PadState.LB)) + } + + @Test fun removingAnotherPlayerDoesNotDiscardThePrimaryPlayersQueuedChord() { + val device = controller() + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.ACTION_UP)) + val other = controller(11) + bridge.onKeyEvent(key(other, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.ACTION_UP)) + bridge.setBackQamPressed(true) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1)) + bridge.onDeviceRemoved(other.id) + advance(80) + assertTrue(pad().isDown(PadState.LB)) + assertTrue(pad().isDown(PadState.QAM)) + } + + @Test fun pairingOnAnIgnoredRailKeyImmediatelyReleasesDeliveredButtonsAndDropsQueuedOnes() { + val left = controller(product = 0x2006) + bridge.setBackQamPressed(true) + bridge.onKeyEvent(key(left, KeyEvent.KEYCODE_BUTTON_L1)) + advance(80) + assertTrue(pad().isDown(PadState.LB)) + bridge.onKeyEvent(key(left, KeyEvent.KEYCODE_BUTTON_X)) + val right = controller(11, product = 0x2007) + assertTrue(bridge.onKeyEvent(key(right, KeyEvent.KEYCODE_BUTTON_L1, scan = 0x136))) + assertFalse(pad().isDown(PadState.LB)) + assertFalse(pad().isDown(PadState.X)) + assertTrue(pad().isDown(PadState.QAM)) + advance(1000) + assertFalse(pad().isDown(PadState.LB)) + assertFalse(pad().isDown(PadState.X)) + } + + @Test fun queuedReportsUseTheLiveStickAndStopItImmediatelyOnBackRelease() { + bridge.setBackQamPressed(true) + bridge.applyExternal({ it.press(PadState.X, true); it.leftY = -1f }, true) + advance(20) + bridge.applyExternal({ it.leftY = -0.25f }, true) + advance(60) + assertEquals(-0.25f, pad().leftY) + bridge.setBackQamPressed(false) + assertEquals(0f, pad().leftY) + advance(1000) + assertEquals(0f, pad().leftY) + bridge.applyExternal({ it.leftY = 0f }, true) + bridge.applyExternal({ it.leftY = 0.75f }, true) + assertEquals(0.75f, pad().leftY) + } + + @Test fun releasingBackDuringTheLeadNeverReplaysAnOldStickMovement() { + bridge.setBackQamPressed(true) + bridge.applyExternal({ it.leftY = -1f }, true) + advance(20) + bridge.setBackQamPressed(false) + advance(1000) + assertEquals(0f, pad().leftY) + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun theInitialPartnerKeepsItsDurationWhenReleasedAfterTheLead() { + bridge.setBackQamPressed(true) + bridge.applyExternal({ it.press(PadState.X, true) }, true) + advance(100) + bridge.applyExternal({ it.press(PadState.X, false) }, true) + assertTrue(pad().isDown(PadState.X)) + advance(79) + assertTrue(pad().isDown(PadState.X)) + advance(1) + assertFalse(pad().isDown(PadState.X)) + } + + @Test fun deliberateStickTriggerAndHatMotionPromoteChordsButNeutralAndDriftDoNot() { + val device = controller() + val promoted = mutableListOf<Boolean>() + bridge.setOnChordInput { promoted.add(true) } + for ((axis, value) in listOf(MotionEvent.AXIS_X to 0f, MotionEvent.AXIS_X to 0.1f, + MotionEvent.AXIS_LTRIGGER to 0f, MotionEvent.AXIS_HAT_Y to 0f)) motion(device, axis, value) + assertTrue(promoted.isEmpty()) + for ((axis, value) in listOf(MotionEvent.AXIS_X to -0.15f, MotionEvent.AXIS_LTRIGGER to 0.75f, + MotionEvent.AXIS_HAT_Y to -1f)) motion(device, axis, value) + assertEquals(3, promoted.size) + } + + private fun controller(id: Int = 10, product: Int = 0): InputDevice { + val builder = InputDeviceBuilder.newBuilder().setId(id).setName("QAM pad $id") + .setVendorId(if (product == 0) 0 else 0x057e).setProductId(product) + .setDescriptor("qam-pad-$id").setExternal(true).setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC) + .setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK) + for (axis in listOf(MotionEvent.AXIS_X, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_HAT_Y)) { + builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, 0f, 1f, 0f, 0f, 0f) + } + return builder.build().also { + shadowOf(RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)).addInputDevice(it) + bridge.applyExternal({}, false) + } + } + + @Test fun homeGuidePrecedesEarlyPartnerInputAndDoesNotGenerateABareButton() { + bridge.setHomeGuidePressed(true) + assertTrue(pad().isDown(PadState.GUIDE)) + bridge.applyExternal({ it.press(PadState.X, true) }, true) + assertFalse(pad().isDown(PadState.X)) + advance(80) + assertTrue(pad().isDown(PadState.GUIDE)) + assertTrue(pad().isDown(PadState.X)) + bridge.applyExternal({ it.press(PadState.X, false) }, true) + bridge.setHomeGuidePressed(false) + advance(1000) + assertFalse(pad().isDown(PadState.GUIDE)) + assertFalse(pad().isDown(PadState.X)) + } + + @Test fun homeGuideHoldsOnThePrimaryPlayerWithoutABuiltinPad() { + PadBridge.setFirstSlot(1) + try { + bridge.setBuiltinPad(false) + bridge.setHomeGuidePressed(true) + assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + bridge.setHomeGuidePressed(false) + assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + } finally { + PadBridge.setFirstSlot(0) + } + } + + @Test fun homeGuideAndControllerGuideReleaseIndependentlyOnThePrimaryPlayer() { + PadBridge.setFirstSlot(1) + try { + bridge.setBuiltinPad(false) + val device = controller() + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE)) + bridge.setHomeGuidePressed(true) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.ACTION_UP)) + assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE)) + bridge.setHomeGuidePressed(false) + assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.ACTION_UP)) + assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + } finally { + PadBridge.setFirstSlot(0) + } + } + + @Test fun removingThePrimaryPlayerForgetsItsHomeGuide() { + PadBridge.setFirstSlot(1) + try { + bridge.setBuiltinPad(false) + val device = controller() + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP)) + bridge.setHomeGuidePressed(true) + bridge.onDeviceRemoved(device.id) + JoyConPadTest.RecordingWriter.pads.remove(1) + bridge.cancelHomeGuide() + bridge.setHomeGuidePressed(false) + assertNull(JoyConPadTest.RecordingWriter.pads[1]) + } finally { + PadBridge.setFirstSlot(0) + } + } + + @Test fun cancellingHomeGuideOnAPlayerSlotKeepsItsHeldControls() { + PadBridge.setFirstSlot(1) + try { + bridge.setBuiltinPad(false) + val device = controller() + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A)) + bridge.setHomeGuidePressed(true) + bridge.cancelHomeGuide() + val pad = requireNotNull(JoyConPadTest.RecordingWriter.pads[1]) + assertFalse(pad.isDown(PadState.GUIDE)) + assertTrue(pad.isDown(PadState.A)) + } finally { + PadBridge.setFirstSlot(0) + } + } + + @Test fun cancellingHomeDiscardsQueuedPartnersAndReleasesGuideImmediately() { + bridge.setHomeGuidePressed(true) + bridge.applyExternal({ it.press(PadState.LB, true); it.leftY = -1f }, true) + bridge.cancelHomeGuide() + advance(1000) + assertFalse(pad().isDown(PadState.GUIDE)) + assertFalse(pad().isDown(PadState.LB)) + assertEquals(0f, pad().leftY) + } + + @Test fun homeAndTouchGuideHaveIndependentReleases() { + bridge.setHomeGuidePressed(true) + bridge.setSystemButtons(true, false) + bridge.setHomeGuidePressed(false) + advance(1000) + assertTrue(pad().isDown(PadState.GUIDE)) + bridge.setSystemButtons(false, false) + advance(1000) + assertFalse(pad().isDown(PadState.GUIDE)) + } + + @Test fun releasingHomeStopsHeldAxesFromBecomingNavigation() { + bridge.setHomeGuidePressed(true) + bridge.applyExternal({ it.leftY = -1f }, true) + advance(80) + assertEquals(-1f, pad().leftY) + bridge.setHomeGuidePressed(false) + advance(1000) + assertEquals(0f, pad().leftY) + assertFalse(pad().isDown(PadState.GUIDE)) + } + + private fun key(device: InputDevice, code: Int, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0, scan: Int = 0) = + KeyEvent(0L, 0L, action, code, repeat, 0, device.id, scan, 0, InputDevice.SOURCE_GAMEPAD) + + private fun motion(device: InputDevice, axis: Int, value: Float) { + val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1, + arrayOf(MotionEvent.PointerProperties().apply { id = 0 }), + arrayOf(MotionEvent.PointerCoords().apply { setAxisValue(axis, value) }), + 0, 0, 1f, 1f, device.id, 0, InputDevice.SOURCE_JOYSTICK, 0) + try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() } + } + + private fun pad() = requireNotNull(JoyConPadTest.RecordingWriter.pads[0]) + + private fun advanceTime() { + val handler = ReflectionHelpers.getStaticField<Handler>(PadBridge::class.java, "chordHandler") + shadowOf(handler.looper).idleFor(Duration.ofSeconds(2)) + advance(2000) + } + + private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms)) +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt index 1d2e1a10e8..a76da590a3 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt @@ -84,6 +84,20 @@ class PadBridgeRoutingTest { assertFalse(PadBridge.anyControllerConnected()) } + @Test fun homeShortcutsIgnoreHomeFromSystemKeys() { + val gpio = device(InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC, name = "gpio-keys") + val pad = device(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC) + assertFalse(PadBridge.isControllerKeyEvent(key(gpio, KeyEvent.KEYCODE_HOME, KeyEvent.ACTION_DOWN))) + assertTrue(PadBridge.isControllerKeyEvent(key(pad, KeyEvent.KEYCODE_HOME, KeyEvent.ACTION_DOWN))) + val owner = Any() + HomeButtonShortcuts.attach(owner, { true }, { fail("system Home must not press Guide") }, {}) + try { + for (action in listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) { + assertFalse(HomeButtonShortcuts.onKeyEvent(RuntimeEnvironment.getApplication(), key(gpio, KeyEvent.KEYCODE_HOME, action))) + } + } finally { HomeButtonShortcuts.detach(owner) } + } + @Test fun keyAndMotionOwnershipDoesNotFollowEverySourceOnTheDevice() { val keyboard = device(InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_ALPHABETIC) val composite = device(COMPOSITE, InputDevice.KEYBOARD_TYPE_ALPHABETIC) diff --git a/app/src/test/java/com/droiddeck/launcher/input/ScreenKeysTest.kt b/app/src/test/java/com/droiddeck/launcher/input/ScreenKeysTest.kt new file mode 100644 index 0000000000..8a95dd5128 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/ScreenKeysTest.kt @@ -0,0 +1,124 @@ +package com.droiddeck.launcher.input + +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.View +import org.junit.Assert.assertEquals +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 ScreenKeysTest { + private val context = RuntimeEnvironment.getApplication() + + @Before fun clearKeys() { + ControllerPrefs.setScreenKeys(context, emptyList()) + } + + @Test fun missesAreForwardedAsTheirOwnTouchStreamWhileAKeyIsHeld() { + val sent = mutableListOf<Pair<Int, Boolean>>() + val keys = ScreenKeys(context) { code, down -> sent += code to down } + keys.layout(0, 0, 1000, 600) + keys.add(listOf(KeyEvent.KEYCODE_W)) + val forwarded = mutableListOf<Pair<Int, Int>>() + keys.onTouchMiss = { forwarded += it.actionMasked to it.getPointerId(0) } + + send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f)) + send(keys, MotionEvent.ACTION_POINTER_DOWN or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), listOf(0, 1), listOf(300f, 900f), listOf(372f, 550f)) + send(keys, MotionEvent.ACTION_MOVE, listOf(0, 1), listOf(310f, 880f), listOf(372f, 530f)) + send(keys, MotionEvent.ACTION_POINTER_UP or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), listOf(0, 1), listOf(310f, 880f), listOf(372f, 530f)) + send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(310f), listOf(372f)) + + assertEquals( + listOf( + MotionEvent.ACTION_DOWN to 1, + MotionEvent.ACTION_MOVE to 1, + MotionEvent.ACTION_UP to 1, + ), + forwarded, + ) + assertEquals(listOf(KeyEvent.KEYCODE_W to true, KeyEvent.KEYCODE_W to false), sent) + } + + @Test fun gestureRecognizerKeepsOneSplitTargetOwnerUntilItsStreamEnds() { + val gate = GestureTouchStreamGate() + fun accepts(source: GestureTouchStreamGate.Source, action: Int): Boolean { + val event = MotionEvent.obtain(0L, 1L, action, 1f, 1f, 0) + return try { gate.accepts(source, event) } finally { event.recycle() } + } + + assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN)) + assertFalse(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN)) + assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_MOVE)) + assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_UP)) + assertTrue(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN)) + assertFalse(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN)) + assertTrue(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_CANCEL)) + assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN)) + assertFalse(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN)) + gate.reset() + assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN)) + } + + @Test fun loadingLayoutReleasesLatchedKeysBeforeReplacingEntries() { + val sent = mutableListOf<Pair<Int, Boolean>>() + val keys = ScreenKeys(context) { code, down -> sent += code to down } + keys.layout(0, 0, 1000, 600) + keys.add(listOf(KeyEvent.KEYCODE_SHIFT_LEFT)) + keys.setToggle(listOf(KeyEvent.KEYCODE_SHIFT_LEFT), true) + send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f)) + send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(300f), listOf(372f)) + + keys.load("") + + assertEquals(listOf(KeyEvent.KEYCODE_SHIFT_LEFT to true, KeyEvent.KEYCODE_SHIFT_LEFT to false), sent) + } + + @Test fun hidingTheViewReleasesLatchedKeys() { + val sent = mutableListOf<Pair<Int, Boolean>>() + val keys = ScreenKeys(context) { code, down -> sent += code to down } + keys.layout(0, 0, 1000, 600) + keys.add(listOf(KeyEvent.KEYCODE_SHIFT_LEFT)) + keys.setToggle(listOf(KeyEvent.KEYCODE_SHIFT_LEFT), true) + send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f)) + send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(300f), listOf(372f)) + + keys.visibility = View.GONE + + assertEquals(listOf(KeyEvent.KEYCODE_SHIFT_LEFT to true, KeyEvent.KEYCODE_SHIFT_LEFT to false), sent) + } + + private fun send(view: View, action: Int, ids: List<Int>, xs: List<Float>, ys: List<Float>) { + val properties = Array(ids.size) { index -> + MotionEvent.PointerProperties().apply { + id = ids[index] + toolType = MotionEvent.TOOL_TYPE_FINGER + } + } + val coordinates = Array(ids.size) { index -> + MotionEvent.PointerCoords().apply { + x = xs[index] + y = ys[index] + pressure = 1f + size = 1f + } + } + val event = MotionEvent.obtain( + 0L, 1L, action, ids.size, properties, coordinates, 0, 0, + 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0, + ) + try { + view.onTouchEvent(event) + } finally { + event.recycle() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionGestureRoutingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionGestureRoutingTest.kt index 7b2a55e2e0..7b33c71705 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SessionGestureRoutingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionGestureRoutingTest.kt @@ -172,7 +172,7 @@ class SessionGestureRoutingTest { val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0) try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() } val gestureMode = mode == SessionPrefs.TOUCH_GESTURES - shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(if (gestureMode) 350 else 500)) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(if (gestureMode) 350 else 320)) assertEquals(if (gestureMode) listOf(18 to true) else emptyList(), keys) assertEquals(if (gestureMode) emptyList() else listOf(PointerGestures.BTN_RIGHT to true), directButtons) ReflectionHelpers.callInstanceMethod<Unit>(activity, "onPause") @@ -220,7 +220,7 @@ class SessionGestureRoutingTest { override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { directButtons += button to pressed } override fun onWheel(steps: Int) {} override fun onLongPress() {} - }) {} + }) {}.also { it.configure(config) } setField("directTouchHold", directHold) launcherScroll = ScrollTouchGestures(8f, 50f, object : ScrollTouchGestures.Listener { override fun onMove(x: Float, y: Float) { scrollPositions += x to y } diff --git a/app/src/test/java/com/droiddeck/launcher/input/SteamVolumeKeysTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SteamVolumeKeysTest.kt new file mode 100644 index 0000000000..cce0daa3cc --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/SteamVolumeKeysTest.kt @@ -0,0 +1,46 @@ +package com.droiddeck.launcher.input + +import android.media.AudioManager +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 = [28, 33]) +class SteamVolumeKeysTest { + private val adjustments = mutableListOf<Int>() + + private fun key(code: Int, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0) = + KeyEvent(0L, 0L, action, code, repeat) + + private fun dispatch(code: Int, enabled: Boolean = true, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0) = + SteamVolumeKeys.dispatch(key(code, action, repeat), enabled, adjustments::add) + + @Test fun enabledKeysAdjustOncePerDownAndConsumeRelease() { + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP, repeat = 1)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP, action = KeyEvent.ACTION_UP)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_DOWN)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_DOWN, action = KeyEvent.ACTION_UP)) + assertEquals(listOf(AudioManager.ADJUST_RAISE, AudioManager.ADJUST_RAISE, AudioManager.ADJUST_LOWER), adjustments) + } + + @Test fun muteTogglesOnlyOnInitialPress() { + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE, repeat = 1)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE, action = KeyEvent.ACTION_UP)) + assertEquals(listOf(AudioManager.ADJUST_TOGGLE_MUTE), adjustments) + } + + @Test fun disabledAndNonVolumeKeysFallThrough() { + for (code in listOf(KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) { + assertFalse(dispatch(code, enabled = false)) + assertFalse(dispatch(code, enabled = false, action = KeyEvent.ACTION_UP)) + } + assertFalse(dispatch(KeyEvent.KEYCODE_BUTTON_A)) + assertTrue(adjustments.isEmpty()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt new file mode 100644 index 0000000000..a2c5e483bb --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -0,0 +1,398 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import com.droiddeck.launcher.session.ComponentsManager +import com.droiddeck.launcher.session.GameEnvironmentStore +import com.github.luben.zstd.ZstdOutputStream +import org.apache.commons.compress.archivers.tar.TarArchiveEntry +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File +import java.nio.file.Files +import java.util.zip.CRC32 + +private val REGISTRY = """ +WINE REGISTRY Version 2 +;; All keys relative to \\Machine + +[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Battle.net] 1760380000 +#time=1dc3c6e0a5e1f2a +"DisplayName"="Battle.net" +"InstallLocation"="C:\\Program Files (x86)\\Battle.net" +"UninstallString"="\"C:\\Program Files (x86)\\Battle.net\\Battle.net Uninstaller.exe\" --lang=enUS" + +[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Diablo IV] 1760380001 +"DisplayIcon"="C:\\Program Files (x86)\\Diablo IV\\Diablo IV Launcher.exe" +"DisplayName"="Diablo\xae IV" +"InstallLocation"="C:\\Program Files (x86)\\Diablo IV" +"Publisher"="Blizzard Entertainment" +"UninstallString"="\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --lang=enUS --uid=fenris --displayname=\"Diablo IV\"" + +[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Overwatch] 1760380002 +"InstallLocation"="C:\\Program Files (x86)\\Overwatch" +"UninstallString"="\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --lang=enUS --uid=prometheus --displayname=\"Overwatch\"" + +[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Steam] 1760380003 +"InstallLocation"="C:\\Program Files (x86)\\Steam" +"UninstallString"="C:\\Program Files (x86)\\Steam\\uninstall.exe --uid=steam" + +[Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Diablo II Resurrected] 1760380004 +"UninstallString"=str(2):"\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --lang=enUS --uid=osi --displayname=\"Diablo II: Resurrected\"" +"InstallLocation"="C:/Games/Diablo II Resurrected" + +[Software\\Wine\\Fonts] 1760380005 +"InstallLocation"="C:\\x" +"UninstallString"="Battle.net --uid=wow" +""".trimStart() + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class BattleNetTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + File(context.filesDir, "components").deleteRecursively() + LinuxRuntime.rootDir(context).deleteRecursively() + } + + @Test fun theIdIsTheShortcutIdTheScriptNames() { + val crc = CRC32().apply { update("\"droiddeck-battlenet\"Battle.net".toByteArray()) }.value + assertEquals(crc or 0x80000000L, BattleNet.APP_ID) + } + + @Test fun theNewestD2rfixIsTheHighestFexThenTheHighestFix() { + val items = listOf( + item("FEXCore-2610-linux.wcp"), + item("FEXCore-2609-d2rfix25-linux.wcp"), + item("FEXCore-2610-d2rfix9-linux.wcp"), + item("FEXCore-2610-d2rfix28-linux.wcp"), + item("FEXCore-2509.1-d2rfix40-linux.wcp"), + ) + assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.newestD2rFix(items)?.file) + assertEquals("FEXCore-2610.1-d2rfix1-linux.wcp", BattleNet.newestD2rFix(items + item("FEXCore-2610.1-d2rfix1-linux.wcp"))?.file) + assertEquals("FexCore-2611-D2RFIX2-linux.wcp", BattleNet.newestD2rFix(items + item("FexCore-2611-D2RFIX2-linux.wcp"))?.file) + } + + @Test fun onlyFexD2rfixPackagesCount() { + assertNull(BattleNet.newestD2rFix(listOf(item("FEXCore-2610-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp", comp = "dxvk")))) + assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp.part")) + assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix-linux.wcp")) + assertEquals(listOf(2610L) to 28L, BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp")) + } + + @Test fun theNewestStoredBuildIsSetForThePrefix() { + catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp", "FEXCore-2610-linux.wcp") + store("FEXCore-2610-d2rfix28-linux.wcp") + + assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh)) + + assertEquals(mapOf("fex" to "FEXCore-2610-d2rfix28-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) + assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh)) + } + + @Test fun aNewerBuildReplacesTheOldOne() { + catalog("FEXCore-2609-d2rfix25-linux.wcp") + store("FEXCore-2609-d2rfix25-linux.wcp") + BattleNet.ensureFex(context, ::noRefresh) + catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp") + store("FEXCore-2610-d2rfix28-linux.wcp") + + BattleNet.ensureFex(context, ::noRefresh) + + assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"]) + } + + @Test fun aStaleListingIsFetchedAgain() { + catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1) + store("FEXCore-2610-d2rfix28-linux.wcp") + + BattleNet.ensureFex(context) { listOf(item("FEXCore-2609-d2rfix25-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp")) } + + assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"]) + } + + @Test fun aFailedFetchFallsBackOnTheCachedListing() { + catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1) + store("FEXCore-2609-d2rfix25-linux.wcp") + + assertEquals("FEXCore-2609-d2rfix25-linux.wcp", BattleNet.ensureFex(context) { error("offline") }) + } + + @Test fun aListingWithoutD2rfixIsAnError() { + catalog("FEXCore-2610-linux.wcp") + var refreshed = 0 + assertThrows(IllegalStateException::class.java) { BattleNet.ensureFex(context) { refreshed++; emptyList() } } + assertEquals(1, refreshed) + assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) + } + + @Test fun installedIsTheLauncherInThePrefix() { + assertFalse(BattleNet.installed(context)) + launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } + assertTrue(BattleNet.installed(context)) + } + + @Test fun theEnvironmentEditorNamesBattleNetsProfileOnceItIsInstalled() { + assertNull(BattleNet.profile(context)) + launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } + assertEquals(BattleNet.APP_ID.toString() to "Battle.net", BattleNet.profile(context)) + } + + @Test fun removeTakesThePrefixItsMenuEntryAndCacheButNothingItLinksTo() { + catalog("FEXCore-2610-d2rfix28-linux.wcp") + store("FEXCore-2610-d2rfix28-linux.wcp") + BattleNet.ensureFex(context, ::noRefresh) + val root = LinuxRuntime.rootDir(context) + fun put(relative: String) = File(root, relative).apply { parentFile!!.mkdirs(); writeText("x") } + launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } + val outside = File(context.cacheDir, "bnet-outside").apply { mkdirs() } + val kept = File(outside, "kept").apply { writeText("x") } + val drives = File(BattleNet.prefix(context), "pfx/dosdevices").apply { mkdirs() } + Files.createSymbolicLink(File(drives, "z:").toPath(), outside.toPath()) + val menu = put("usr/local/share/applications/droiddeck-battlenet.desktop") + val otherMenu = put("usr/local/share/applications/other.desktop") + val log = put("root/.cache/droiddeck/battlenet/battlenet.log") + val otherPrefix = put("root/.local/share/Steam/steamapps/compatdata/123/pfx/system.reg") + + BattleNet.remove(context) + + assertFalse(BattleNet.prefix(context).exists()) + assertFalse(BattleNet.installed(context)) + assertTrue(kept.isFile) + assertFalse(menu.exists()) + assertTrue(otherMenu.isFile) + assertFalse(log.parentFile!!.exists()) + assertTrue(otherPrefix.isFile) + assertNull(BattleNet.fexInUse(context)) + outside.deleteRecursively() + } + + @Test fun anIdNamesItsTitleWithOrWithoutItsLocale() { + assertEquals("Pro", BattleNet.title("prometheus")?.code) + assertEquals("D3", BattleNet.title("diablo3_enus")?.code) + assertEquals("Fen", BattleNet.title("Fenris")?.code) + assertEquals("WTCG", BattleNet.title("hs_beta")?.code) + assertEquals("Diablo II: Resurrected", BattleNet.title("osi_dede")?.name) + assertEquals("WoWC", BattleNet.title("wow_classic")?.code) + assertEquals("WoWC", BattleNet.title("wow_classic_era_enus")?.code) + assertNull(BattleNet.title("agent")) + assertNull(BattleNet.title("osi_beta")) + } + + @Test fun theUninstallEntriesOfBattleNetsGamesAreRead() { + val entries = BattleNet.uninstallEntries(REGISTRY.lineSequence()) + assertEquals(listOf( + "fenris" to "C:\\Program Files (x86)\\Diablo IV", + "prometheus" to "C:\\Program Files (x86)\\Overwatch", + "osi" to "C:/Games/Diablo II Resurrected", + ), entries) + } + + @Test fun productDbsInstallsAreRead() { + val db = message( + field(1, message(field(1, "agent"), field(2, "agent"), field(3, message(field(1, "C:/ProgramData/Battle.net/Agent"))))), + varintField(7, 300), + field(1, message(field(1, "hs_beta"), field(2, "wtcg"), varintField(9, 1), field(3, message(field(1, "C:/Program Files (x86)/Hearthstone"), field(2, "US"))))), + field(1, message(field(1, "s2"))), + field(1, message(field(1, "s1"), field(3, message(field(1, "Z:/mnt/droiddeck-sd/Games/Battle.net/StarCraft"))), field(4, message(field(1, message(varintField(1, 0), varintField(2, 0))))))), + field(1, message(field(1, "wow_classic_anniversary"), field(3, message(field(1, "Z:/root/Games/World of Warcraft"))), field(4, message(field(1, message(varintField(1, 1), varintField(2, 1))))))), + ) + assertEquals(listOf("agent" to "C:/ProgramData/Battle.net/Agent", "hs_beta" to "C:/Program Files (x86)/Hearthstone", "wow_classic_anniversary" to "Z:/root/Games/World of Warcraft"), + BattleNet.productDbEntries(db)) + assertNull(BattleNet.productDbEntries(db.copyOf(db.size - 3))) + assertNull(BattleNet.productDbEntries(byteArrayOf(0x0a, 0x7f, 0x01))) + assertNull(BattleNet.productDbEntries(ByteArray(0))) + assertNull(BattleNet.productDbEntries(byteArrayOf(0x0a, 0x03, 0x0a, 0x7f, 0x01))) + assertEquals(emptyList<Pair<String, String>>(), BattleNet.productDbEntries(message(field(1, message(field(1, "s1"), field(3, message(field(1, "Z:/Games/StarCraft"))), field(4, message(field(1, message(varintField(1, 0)))))))))) + } + + @Test fun theAgentDoesNotStartWithoutTheGameStorageCard() { + val card = Files.createTempDirectory("card").toFile() + com.droiddeck.launcher.session.SessionPrefs.setGameStorage(context, card.path, "SD Card") + assertTrue(com.droiddeck.launcher.stores.battlenet.BattleNetInstall.binds(context).any { it.endsWith(":/mnt/droiddeck-sd") }) + card.deleteRecursively() + assertThrows(IllegalStateException::class.java) { com.droiddeck.launcher.stores.battlenet.BattleNetInstall.binds(context) } + } + + @Test fun aGameTheAgentNoLongerTracksIsNotInstalled() { + val registry = listOf("wow" to "Z:\\mnt\\droiddeck-sd\\Games\\Battle.net\\World of Warcraft", "hs_beta" to "C:\\Hearthstone") + assertEquals(listOf("hs_beta" to "C:\\Hearthstone", "HS_BETA" to "C:/Hearthstone"), BattleNet.installs(registry, listOf("HS_BETA" to "C:/Hearthstone"))) + assertEquals(registry, BattleNet.installs(registry, null)) + assertEquals(emptyList<Pair<String, String>>(), BattleNet.installs(registry, emptyList())) + } + + @Test fun theGamesAreTheTitlesInstalledInTheirFolders() { + val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() } + File(pfx, "system.reg").writeText(REGISTRY) + File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs() + File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message( + field(1, message(field(1, "hs_beta"), field(3, message(field(1, "C:/Program Files (x86)/Hearthstone"))))), + field(1, message(field(1, "fenris"), field(3, message(field(1, "C:/Program Files (x86)/Diablo IV"))))), + field(1, message(field(1, "wow_classic"), field(3, message(field(1, "C:/Program Files (x86)/World of Warcraft"))))), + )) + for (folder in listOf("Program Files (x86)/Diablo IV", "Games/Diablo II Resurrected", "Program Files (x86)/Hearthstone", "Program Files (x86)/World of Warcraft")) { + File(pfx, "drive_c/$folder").mkdirs() + } + val games = BattleNet.games(context) + assertEquals(listOf("Fen", "WTCG", "WoWC"), games.map { it.code }) + assertEquals(listOf("Diablo IV", "Hearthstone", "World of Warcraft Classic"), games.map { it.name }) + assertEquals(File(pfx, "drive_c/Program Files (x86)/Hearthstone"), games[1].folder) + File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").delete() + assertEquals(listOf("Fen", "OSI"), BattleNet.games(context).map { it.code }) + assertNull(BattleNet.hostFolder(context, "D:\\Games\\X")) + assertNull(BattleNet.hostFolder(context, "C:\\..\\..\\etc")) + assertNull(BattleNet.hostFolder(context, "Z:\\root\\..\\..\\etc")) + assertEquals(File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Hearthstone"), + BattleNet.hostFolder(context, "Z:/root/Games/Stores/Battle.net/Hearthstone/")) + } + + @Test fun aGamesShortcutHasBattleNetLaunchItInItsPrefix() { + val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Diablo IV").apply { mkdirs() } + File(folder, "Diablo IV Launcher.exe").writeBytes(byteArrayOf(0x4d, 0x5a)) + val shortcut = BattleNet.shortcut(context, BattleNet.Game("fenris", "Diablo IV", "Fen", folder))!! + val exe = "/root/.local/share/Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe" + assertEquals(exe, shortcut.guestExe) + assertEquals(exe.substringBeforeLast('/'), shortcut.guestDir) + assertEquals("STEAM_COMPAT_DATA_PATH=/root/.local/share/Steam/steamapps/compatdata/2596113170 %command% --exec=\"launch Fen\"", shortcut.launchOptions) + val crc = CRC32().apply { update("\"$exe\"Diablo IV".toByteArray()) }.value + assertEquals(crc or 0x80000000L, shortcut.appId) + assertEquals((shortcut.appId shl 32) or 0x02000000L, shortcut.gameId) + assertEquals(com.droiddeck.launcher.stores.Store.BATTLENET.id, shortcut.source) + assertEquals("Diablo IV Launcher.exe", shortcut.exe.name) + val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(context, listOf(shortcut)).readText() + val entry = JSONArray(listing).getJSONObject(0) + assertEquals(com.droiddeck.launcher.stores.Store.BATTLENET.id, entry.getString("store")) + assertEquals(shortcut.launchOptions, entry.getString("launch")) + assertEquals(exe, entry.getString("exe")) + } + + @Test fun titlesSharingALaunchCodeShareTheirArt() { + val cover = File(context.filesDir, "battlenet-art/fenris/p.jpg").apply { parentFile!!.mkdirs(); writeBytes(byteArrayOf(1)) } + assertEquals(cover, BattleNet.art(context, BattleNet.title("fen")!!).cover) + val wide = File(context.filesDir, "battlenet-art/wow_classic/blizzard.jpg").apply { parentFile!!.mkdirs(); writeBytes(byteArrayOf(1)) } + assertEquals(wide, BattleNet.art(context, BattleNet.title("wow_classic_anniversary")!!).header) + } + + @Test fun theStoreOffersEachTitleOnceAndHidesWhatIsInstalled() { + val codes = BattleNet.STORE.map { it.code } + assertEquals(codes.distinct(), codes) + assertTrue("Fen" in codes && "OSI" in codes && "WTCG" in codes) + assertFalse(BattleNet.STORE.any { it.uid == "d3cn" || it.uid == "fen" }) + assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid) + assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) }) + val installed = listOf("fenris", "diablo3_enus", null) + val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code } + assertFalse("Fen" in offered || "D3" in offered) + assertTrue("OSI" in offered) + } + + @Test fun aBattleNetGameStartsWithoutSteamThroughItsShortcutUntilThatIsSwitchedOff() { + File(context.filesDir, "game-environment.json").delete() + val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Diablo IV").apply { mkdirs() } + File(folder, "Diablo IV Launcher.exe").writeBytes(byteArrayOf(0x4d, 0x5a)) + val shortcut = BattleNet.shortcut(context, BattleNet.Game("fenris", "Diablo IV", "Fen", folder))!! + val game = com.droiddeck.launcher.frontend.Library.SteamGame( + shortcut.appId.toInt(), shortcut.name, null, com.droiddeck.launcher.frontend.Library.ADDED, shortcut.gameId, + source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = shortcut.storeId) + val noSteam = com.droiddeck.launcher.session.NoSteamLaunch + assertEquals(BattleNet.APP_ID.toString(), noSteam.scope(game)) + assertFalse(noSteam.enabled(context, game)) + assertTrue(BattleNet.ensureNoSteam(context)) + assertTrue(noSteam.enabled(context, game)) + val command = noSteam.command(game, shortcut)!! + assertEquals(noSteam.BATTLENET, command.program) + assertEquals(listOf("launch", "Fen"), command.args) + GameEnvironmentStore.setGameNoSteam(context, BattleNet.APP_ID.toString(), false) + assertFalse(BattleNet.ensureNoSteam(context)) + assertFalse(noSteam.enabled(context, game)) + } + + @Test fun theGamesAreToldOfAFifthOfThePhonesMemory() { + assertEquals(2048, BattleNet.videoMemory(11113)) + assertEquals(1536, BattleNet.videoMemory(7468)) + assertEquals(2560, BattleNet.videoMemory(15200)) + assertEquals(3584, BattleNet.videoMemory(60000)) + assertTrue(BattleNet.videoMemory(Long.MAX_VALUE / 2) < 4096) + assertEquals( + "dxgi.maxDeviceMemory = 2048; dxgi.maxSharedMemory = 2048; d3d9.maxAvailableMemory = 2048", + BattleNet.videoMemoryOptions(2048), + ) + } + + @Test fun theCapIsTheBattleNetProfilesOwnDxvkConfigUnlessItHasOne() { + File(context.filesDir, "game-environment.json").delete() + val manager = context.getSystemService(android.app.ActivityManager::class.java) + org.robolectric.Shadows.shadowOf(manager).setMemoryInfo(android.app.ActivityManager.MemoryInfo().apply { totalMem = 11113L shl 20 }) + val scope = BattleNet.APP_ID.toString() + assertTrue(BattleNet.ensureVideoMemory(context)) + assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + val published = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json").readText() + assertTrue("dxgi.maxDeviceMemory = 2048" in JSONObject(published).getJSONObject("games").getJSONObject(scope).getString("DXVK_CONFIG")) + assertFalse(BattleNet.ensureVideoMemory(context)) + for (own in listOf("dxvk.maxFrameRate = 30", null)) { + GameEnvironmentStore.save(context, GameEnvironmentStore.read(context).let { it.withEntries(scope, it.entries(scope) + ("DXVK_CONFIG" to own)) }) + assertFalse(BattleNet.ensureVideoMemory(context)) + assertEquals(own, GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + } + GameEnvironmentStore.save(context, GameEnvironmentStore.read(context).let { it.withEntries(scope, it.entries(scope) - "DXVK_CONFIG") }) + assertTrue(BattleNet.ensureVideoMemory(context)) + } + + private fun launcher() = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe") + + private fun varint(value: Long): ByteArray { + val out = java.io.ByteArrayOutputStream() + var v = value + while (v >= 0x80) { out.write(((v and 0x7f) or 0x80).toInt()); v = v ushr 7 } + out.write(v.toInt()) + return out.toByteArray() + } + + private fun field(number: Int, bytes: ByteArray) = varint((number shl 3 or 2).toLong()) + varint(bytes.size.toLong()) + bytes + private fun field(number: Int, text: String) = field(number, text.toByteArray()) + private fun varintField(number: Int, value: Long) = varint((number shl 3).toLong()) + varint(value) + private fun message(vararg fields: ByteArray) = fields.fold(ByteArray(0)) { all, f -> all + f } + + private fun noRefresh(context: Context): List<ComponentsManager.CatalogItem> = error("the cached listing was fresh") + + private fun item(file: String, comp: String = "fex") = ComponentsManager.CatalogItem( + file, comp, "FexCore-Linux", "https://github.com/The412Banner/Nightlies/releases/download/FexCore-Linux/$file", 4, "sha256:" + "ab".repeat(32), + ) + + private fun catalog(vararg files: String, fetchedAt: Long = System.currentTimeMillis() / 1000) { + val cache = File(context.filesDir, "components/catalog.json") + cache.parentFile!!.mkdirs() + val items = JSONArray() + for (file in files) items.put(JSONObject().put("file", file).put("comp", "fex").put("release", "FexCore-Linux") + .put("url", item(file).url).put("size", 4).put("digest", item(file).digest)) + cache.writeText(JSONObject().put("items", items).put("fetchedAt", fetchedAt).toString()) + } + + private fun store(file: String) { + val wcp = File(context.filesDir, "components/packages/$file") + wcp.parentFile!!.mkdirs() + TarArchiveOutputStream(ZstdOutputStream(wcp.outputStream())).use { tar -> + fun put(name: String, bytes: ByteArray) { + tar.putArchiveEntry(TarArchiveEntry(name).apply { size = bytes.size.toLong() }) + tar.write(bytes) + tar.closeArchiveEntry() + } + put("profile.json", JSONObject().put("type", "FEXCore-Linux").put("versionName", file.removeSuffix(".wcp")).toString().toByteArray()) + put("files/lib/wine/aarch64-windows/libarm64ecfex.dll", "arm64ec $file".toByteArray()) + put("files/lib/wine/aarch64-windows/libwow64fex.dll", "wow64 $file".toByteArray()) + } + } +} 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 2cb5e5edd6..dfb3286511 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt @@ -119,6 +119,21 @@ class BwrapSpawnerPlanTest { assertEquals("org.example.Game", plan.env["FLATPAK_ID"]) } + @Test fun sandboxedAppsSeeTheSessionsNetworkLink() { + val context = RuntimeEnvironment.getApplication() + val rootfs = LinuxRuntime.rootDir(context) + val lib = File(rootfs, "usr/local/lib/libblsession.so").apply { parentFile?.mkdirs(); writeText("") } + val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libblsession.so\n") } + val link = File(rootfs, "etc/droiddeck-net").apply { writeText("if wlan0 2 1500\n") } + try { + val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir) + assertEquals("/run/droiddeck-preload/libblsession.so", plan.env["LD_PRELOAD"]) + assertEquals(link.path, plan.binds.single { it.guest == "/etc/droiddeck-net" }.host) + } finally { + listOf(lib, preload, link).forEach { it.delete() } + } + } + @Test fun zypakLaunchesTheBrowserWithoutItsSandbox() { val context = RuntimeEnvironment.getApplication() val app = File(runtime, "app").apply { File(this, "bin").mkdirs() } diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt new file mode 100644 index 0000000000..db035a656a --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt @@ -0,0 +1,155 @@ +package com.droiddeck.launcher.runtime + +import android.app.Application +import android.app.NotificationManager +import android.content.Context +import android.media.AudioManager +import android.os.Looper +import android.provider.Settings +import java.io.File +import java.time.Duration +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +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.annotation.Implements +import org.robolectric.annotation.Implementation +import org.robolectric.shadows.ShadowSettings + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28, 33], manifest = Config.NONE, application = Application::class, shadows = [WriteSettingsShadow::class]) +class DeviceControlsComponentTest { + @get:Rule val tmp = TemporaryFolder() + private val context get() = RuntimeEnvironment.getApplication() + private val audio get() = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager + private lateinit var component: DeviceControlsComponent + private lateinit var directory: File + private var visible = true + + @Before fun start() { + WriteSettingsShadow.writable = true + Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) + val root = tmp.newFolder() + directory = DeviceControlsComponent.directory(root) + component = DeviceControlsComponent(context, root) { visible } + component.publish() + component.start() + shadowOf(Looper.getMainLooper()).idle() + } + + @After fun stop() { + component.stop() + shadowOf(Looper.getMainLooper()).idle() + } + + private fun tick() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(300)) + private fun request(name: String, text: String) { + File(directory, "$name.request").writeText(text) + tick() + } + + @Test fun androidChangesArePublishedAndRequestsUseDeviceVolumeSteps() { + request("volume", "999") + assertEquals(audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), audio.getStreamVolume(AudioManager.STREAM_MUSIC)) + audio.setStreamVolume(AudioManager.STREAM_MUSIC, 3, 0) + tick() + assertEquals("3", File(directory, "volume.state").readText().split(" ").first()) + request("volume", "invalid") + assertEquals(3, audio.getStreamVolume(AudioManager.STREAM_MUSIC)) + } + + @Test fun deniedBrightnessDoesNotOpenSettingsOrReplayAnOldSliderValueAfterPermission() { + WriteSettingsShadow.writable = false + request("brightness", "0.75") + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + assertNull(shadowOf(context).nextStartedActivity) + assertFalse(JSONObject(File(directory, "state.json").readText()).getBoolean("brightnessWritable")) + WriteSettingsShadow.writable = true + tick() + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + request("brightness", "0.75") + assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + } + + @Test fun brightnessIsBoundedAndExternalChangesAreReadBack() { + for (invalid in listOf("NaN", "Infinity", "-0.1", "1.1")) request("brightness", invalid) + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + request("brightness", "0") + assertEquals(1, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 255) + tick() + assertEquals(1.0, JSONObject(File(directory, "state.json").readText()).getDouble("brightness"), 0.0001) + } + + @Test fun permissionNotificationOpensOptionalLauncherSetupOnlyWhenSelected() { + visible = false + WriteSettingsShadow.writable = false + request("brightness", "0.25") + request("brightness", "0.75") + assertNull(shadowOf(context).nextStartedActivity) + val notifications = context.getSystemService(NotificationManager::class.java) + val notification = notifications.activeNotifications.single().notification + notification.contentIntent.send() + val intent = shadowOf(context).nextStartedActivity + assertEquals(com.droiddeck.launcher.core.SteamIntegration.ACTION_SETUP, intent.action) + assertEquals("BRIGHTNESS", intent.getStringExtra(com.droiddeck.launcher.core.SteamIntegration.EXTRA_FEATURE)) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(121)) + WriteSettingsShadow.writable = true + tick() + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + assertTrue(notifications.activeNotifications.isEmpty()) + } + + @Test fun stoppingClearsThePermissionNotificationAndPendingRequest() { + visible = false + WriteSettingsShadow.writable = false + request("brightness", "0.75") + component.stop() + shadowOf(Looper.getMainLooper()).idle() + assertTrue(context.getSystemService(NotificationManager::class.java).activeNotifications.isEmpty()) + WriteSettingsShadow.writable = true + tick() + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + } + + @Test fun stoppedSessionsDoNotConsumeNewCommands() { + component.stop() + shadowOf(Looper.getMainLooper()).idle() + request("brightness", "0.2") + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + } + + @Test fun repeatedSliderChangesDoNotInterruptTheSession() { + WriteSettingsShadow.writable = false + request("brightness", "0.75") + assertNull(shadowOf(context).nextStartedActivity) + request("brightness", "0.8") + assertNull(shadowOf(context).nextStartedActivity) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(5)) + request("brightness", "0.8") + assertNull(shadowOf(context).nextStartedActivity) + } + + @Test fun oversizedRequestsAreDiscardedAndDoNotBlockLaterCommands() { + request("brightness", "0".repeat(1000)) + assertFalse(File(directory, "brightness.request.processing").exists()) + request("brightness", "0.75") + assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + } +} + +@Implements(Settings.System::class) +class WriteSettingsShadow : ShadowSettings.ShadowSystem() { + companion object { + @JvmField var writable = true + @JvmStatic @Implementation fun canWrite(context: Context) = writable + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/ProotFastPathTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/ProotFastPathTest.kt index 5d4eb1d8ee..9b97bd4181 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/ProotFastPathTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/ProotFastPathTest.kt @@ -1,7 +1,9 @@ package com.droiddeck.launcher.runtime +import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Test import java.io.File @@ -17,4 +19,12 @@ class ProotFastPathTest { val binds = (1..ProotFastPath.MAX_BINDS + 1).map { "/host/$it:/guest/$it" } assertNull(ProotFastPath.key(root, binds)) } + + @Test fun fastPathStaysOffForTheRootfsProot() { + assertTrue(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK)) + assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_ROOTFS)) + assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_MISSING)) + assertFalse(ProotFastPath.allows(preference = false, noSeccomp = false, source = LinuxRuntime.PROOT_PACK)) + assertFalse(ProotFastPath.allows(preference = true, noSeccomp = true, source = LinuxRuntime.PROOT_PACK)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeInstallRollbackTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeInstallRollbackTest.kt new file mode 100644 index 0000000000..45b8019bb8 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeInstallRollbackTest.kt @@ -0,0 +1,140 @@ +package com.droiddeck.launcher.runtime + +import android.app.Application +import android.content.Context +import android.content.ContextWrapper +import com.droiddeck.launcher.BuildConfig +import com.droiddeck.launcher.core.AddonPack +import java.io.ByteArrayOutputStream +import java.io.File +import java.net.ServerSocket +import java.security.MessageDigest +import java.util.concurrent.atomic.AtomicBoolean +import java.util.function.Predicate +import org.apache.commons.compress.archivers.tar.TarArchiveEntry +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream +import org.apache.commons.compress.compressors.zstandard.ZstdCompressorOutputStream +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], application = Application::class) +class RuntimeInstallRollbackTest { + @get:Rule val tmp = TemporaryFolder() + @After fun resetFaults() { RuntimeFileTree.refuseForTest = null } + + private fun put(root: File, rel: String, data: String) = File(root, rel).apply { + checkNotNull(parentFile).mkdirs() + writeText(data) + } + + private data class Attempt(val root: File, val staging: File, val old: File, val result: Boolean) + + private fun attempt(failRollback: Boolean): Attempt { + val files = tmp.newFolder("files") + val cache = tmp.newFolder("cache") + val context = object : ContextWrapper(RuntimeEnvironment.getApplication()) { + override fun getFilesDir(): File = files + override fun getCacheDir(): File = cache + override fun getApplicationContext(): Context = this + } + for ((pack, pin, required) in listOf( + Triple(AddonPack.PROOT, BuildConfig.PACK_PROOT_SHA256, listOf("libproot.so", "libproot-loader.so")), + Triple(AddonPack.DIRECTAUDIO, BuildConfig.PACK_DIRECTAUDIO_SHA256, + listOf("linux-wine11/version.txt", "linux-wine11-systhread/version.txt")), + )) { + val version = pin.ifEmpty { "0".repeat(64) } + val directory = File(files, "addons/${pack.name}/$version") + required.forEach { put(directory, it, "test pack") } + put(directory, AddonPack.COMPLETE, version) + } + val root = LinuxRuntime.rootDir(context) + val staging = File(files, LinuxRuntime.DIR + ".new") + val old = File(files, LinuxRuntime.DIR + ".old") + put(root, "root/save.dat", "original user data") + put(root, "opt/appimages/user/game/app.AppImage", "original app") + put(root, "usr/bin/usable", "previous runtime") + + val payload = ByteArrayOutputStream().also { bytes -> + ZstdCompressorOutputStream(bytes).use { zstd -> + TarArchiveOutputStream(zstd).use { tar -> + for ((name, value) in listOf("root/.bashrc" to "shipped home", "usr/bin/new" to "new runtime", + "opt/appimages/user/block" to "shipped app")) { + val data = value.toByteArray() + tar.putArchiveEntry(TarArchiveEntry(name).apply { size = data.size.toLong() }) + tar.write(data) + tar.closeArchiveEntry() + } + } + } + }.toByteArray() + val digest = MessageDigest.getInstance("SHA-256").digest(payload).joinToString("") { "%02x".format(it) } + val faultSeen = AtomicBoolean() + RuntimeFileTree.refuseForTest = Predicate { path -> + if (path == File(staging, "opt/appimages/user/block").toPath() && faultSeen.compareAndSet(false, true)) { + if (failRollback) put(old, "root/rollback-block", "concurrent data") + true + } else failRollback && path == File(old, "root/rollback-block").toPath() + } + val server = ServerSocket(0) + val thread = Thread { + runCatching { + server.accept().use { socket -> + socket.soTimeout = 5000 + val input = socket.getInputStream().bufferedReader(Charsets.ISO_8859_1) + while (true) { + val line = input.readLine() ?: break + if (line.isEmpty()) break + } + val out = socket.getOutputStream() + out.write(("HTTP/1.1 200 OK\r\nContent-Length: ${payload.size}\r\nConnection: close\r\n\r\n").toByteArray()) + out.write(payload) + out.flush() + } + } + }.apply { isDaemon = true; start() } + try { + val release = LinuxRuntimeInstaller.Release("synthetic", "http://127.0.0.1:${server.localPort}/runtime.tar.zst", digest, payload.size.toLong()) + val result = LinuxRuntimeInstaller.install(context, release, null) + assertTrue("the intended carry fault was not reached", faultSeen.get()) + return Attempt(root, staging, old, result) + } finally { + server.close() + thread.join(1000) + RuntimeFileTree.refuseForTest = null + } + } + + @Test fun aFailedCarryAndFailedRollbackKeepTheOnlyStagedCopy() { + val attempt = attempt(failRollback = true) + assertFalse(attempt.result) + assertTrue("the only staged copy was deleted", File(attempt.staging, "root/save.dat").isFile) + assertEquals("original user data", File(attempt.staging, "root/save.dat").readText()) + assertEquals("original app", File(attempt.root, "opt/appimages/user/game/app.AppImage").readText()) + assertEquals("previous runtime", File(attempt.root, "usr/bin/usable").readText()) + repeat(2) { + assertThrows(java.io.IOException::class.java) { + LinuxRuntimeInstaller.recoverInterruptedSwap(attempt.root, attempt.staging, attempt.old) + } + assertEquals("original user data", File(attempt.staging, "root/save.dat").readText()) + } + } + + @Test fun aCompleteRollbackStillRestoresAndCleansTheFailedCandidate() { + val attempt = attempt(failRollback = false) + assertFalse(attempt.result) + assertEquals("original user data", File(attempt.root, "root/save.dat").readText()) + assertEquals("original app", File(attempt.root, "opt/appimages/user/game/app.AppImage").readText()) + assertFalse(attempt.staging.exists()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeRemovalTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeRemovalTest.kt index 318e6b9804..83d43250fd 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeRemovalTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeRemovalTest.kt @@ -69,6 +69,7 @@ class RuntimeRemovalTest { val old = File(dir, "linuxfs.old").apply { File(this, "root").mkdirs() } val staging = File(dir, "linuxfs.new").apply { File(this, "root").mkdirs() } File(staging, "root/save").writeText("user data") + File(staging, LinuxRuntimeInstaller.CARRY_MARKER).writeText("1") for (tree in listOf(old, staging)) Files.setPosixFilePermissions(tree.toPath(), PosixFilePermissions.fromString("r-xr-xr-x")) LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeUserDataCarryTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeUserDataCarryTest.kt new file mode 100644 index 0000000000..d977ffb8cc --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/RuntimeUserDataCarryTest.kt @@ -0,0 +1,243 @@ +package com.droiddeck.launcher.runtime + +import java.io.File +import java.io.IOException +import java.nio.file.Files +import org.junit.After +import org.junit.Assume.assumeTrue +import org.junit.Assert.assertThrows +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class RuntimeUserDataCarryTest { + @get:Rule val tmp = TemporaryFolder() + + @After fun resetFaults() { RuntimeFileTree.refuseForTest = null } + + private fun put(root: File, rel: String, text: String = rel) = File(root, rel).apply { parentFile.mkdirs(); writeText(text) } + + private fun userTree(): File = tmp.newFolder("old").also { old -> + put(old, "root/save.dat", "mine") + put(old, "opt/appimages/user/app1/app.AppImage") + put(old, "opt/droiddeck-apps/game/run.sh") + put(old, "usr/local/share/applications/droiddeck-app-game.desktop") + put(old, "usr/local/share/applications/droiddeck-appimage-app1.desktop") + put(old, "usr/local/share/applications/other.desktop") + put(old, "opt/appimages/dolphin.AppImage") + put(old, "usr/share/applications/droiddeck-dolphin.desktop") + put(old, ".droiddeck-pkg-dolphin", "1.0") + put(old, "usr/bin/tool", "old system file") + } + + @Test fun anUpdateKeepsImportedAppsCatalogAppImagesAndHome() { + val old = userTree() + val staging = tmp.newFolder("new").also { put(it, "root/.bashrc", "shipped"); put(it, "usr/bin/tool", "new system file") } + + val moved = RuntimeFileTree.carryUserData(old, staging, false) + + assertEquals("mine", File(staging, "root/save.dat").readText()) + assertFalse("the shipped home is replaced, not merged", File(staging, "root/.bashrc").exists()) + for (rel in listOf("opt/appimages/user/app1/app.AppImage", "opt/droiddeck-apps/game/run.sh", + "usr/local/share/applications/droiddeck-app-game.desktop", "usr/local/share/applications/droiddeck-appimage-app1.desktop", + "opt/appimages/dolphin.AppImage", "usr/share/applications/droiddeck-dolphin.desktop", ".droiddeck-pkg-dolphin")) { + assertTrue(rel, File(staging, rel).exists()) + assertTrue(rel, rel in moved || moved.any { rel.startsWith("$it/") }) + } + assertEquals("system files come from the new runtime", "new system file", File(staging, "usr/bin/tool").readText()) + assertFalse("only DroidDeck's own menu entries are user data", File(staging, "usr/local/share/applications/other.desktop").exists()) + } + + @Test fun aFailureHalfwayPutsEverythingBack() { + val old = userTree() + val staging = tmp.newFolder("new") + put(staging, "usr/local", "a file where a folder is needed") + + try { + RuntimeFileTree.carryUserData(old, staging, false) + fail("expected the carry to fail") + } catch (expected: IOException) { + } + + assertEquals("mine", File(old, "root/save.dat").readText()) + assertTrue(File(old, "opt/appimages/user/app1/app.AppImage").exists()) + assertTrue(File(old, "opt/droiddeck-apps/game/run.sh").exists()) + assertFalse(File(staging, "root").exists()) + } + + @Test fun recoveryOnlyFillsWhatIsMissing() { + val target = tmp.newFolder("target").also { put(it, "opt/droiddeck-apps/game/run.sh", "kept") } + val staging = tmp.newFolder("staging").also { + put(it, "opt/droiddeck-apps/game/run.sh", "stale") + put(it, "opt/appimages/user/app1/app.AppImage") + } + + val moved = RuntimeFileTree.carryUserData(staging, target, true) + + assertEquals(listOf("opt/appimages/user"), moved) + assertEquals("kept", File(target, "opt/droiddeck-apps/game/run.sh").readText()) + assertTrue(File(target, "opt/appimages/user/app1/app.AppImage").exists()) + } + @Test fun recoveryFindsCompanionsWhoseAppImageWasAlreadyPutBack() { + val root = tmp.newFolder("runtime") + val staging = tmp.newFolder("runtime.new") + val old = File(tmp.root, "runtime.old") + put(root, "opt/appimages/dolphin.AppImage", "user app") + put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1") + put(staging, "usr/share/applications/droiddeck-dolphin.desktop", "menu") + put(staging, ".droiddeck-pkg-dolphin", "version") + put(staging, ".droiddeck-pkg-desktop-kde", "system package marker") + + LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) + assertEquals("menu", File(root, "usr/share/applications/droiddeck-dolphin.desktop").readText()) + assertEquals("version", File(root, ".droiddeck-pkg-dolphin").readText()) + assertFalse(File(root, ".droiddeck-pkg-desktop-kde").exists()) + assertEquals("user app", File(root, "opt/appimages/dolphin.AppImage").readText()) + } + + @Test fun unmarkedExtractedStagingDoesNotBlockRecovery() { + val root = tmp.newFolder("runtime") + val staging = tmp.newFolder("runtime.new") + val old = File(tmp.root, "runtime.old") + put(root, "root/save.dat", "current user data") + put(staging, "root/.bashrc", "shipped home from interrupted extract") + + LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) + assertEquals("current user data", File(root, "root/save.dat").readText()) + assertEquals("shipped home from interrupted extract", File(staging, "root/.bashrc").readText()) + } + + @Test fun anUnreadableAppImageDirectoryAbortsBeforeMovingHome() { + assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix")) + val old = userTree() + val images = File(old, "opt/appimages") + val staging = tmp.newFolder("staging") + assertTrue(images.setReadable(false, false)) + assertTrue(images.setExecutable(false, false)) + try { + assertThrows(IOException::class.java) { RuntimeFileTree.carryUserData(old, staging, false) } + assertEquals("mine", File(old, "root/save.dat").readText()) + assertFalse(File(staging, "root/save.dat").exists()) + } finally { + images.setReadable(true, true) + images.setExecutable(true, true) + } + } + + @Test fun recoveryRestoresTheRuntimeBeforeTryingAFallibleHomeMove() { + val root = File(tmp.root, "runtime") + val old = tmp.newFolder("runtime.old") + val staging = tmp.newFolder("runtime.new") + put(old, "usr/bin/usable", "previous runtime") + File(old, "root").mkdirs() + put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1") + put(staging, "root/save.dat", "staged user data") + RuntimeFileTree.refuseForTest = java.util.function.Predicate { it.fileName.toString() == "root" } + + assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) } + assertTrue("the previous runtime was not restored", root.isDirectory) + assertEquals("previous runtime", File(root, "usr/bin/usable").readText()) + assertEquals("staged user data", File(staging, "root/save.dat").readText()) + } + + @Test fun conflictingRecoveryDataIsRetainedOnEveryRetry() { + val root = tmp.newFolder("runtime") + val staging = tmp.newFolder("runtime.new") + val old = File(tmp.root, "runtime.old") + put(root, "root/current.dat", "current user data") + put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1") + put(staging, "root/older.dat", "unrecovered user data") + + repeat(2) { + assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) } + assertEquals("current user data", File(root, "root/current.dat").readText()) + assertEquals("unrecovered user data", File(staging, "root/older.dat").readText()) + } + } + + @Test fun stagedDataWithoutASurvivingRuntimeIsKeptForRecovery() { + val root = File(tmp.root, "runtime") + val old = File(tmp.root, "runtime.old") + val staging = tmp.newFolder("runtime.new") + put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1") + put(staging, "root/save.dat", "only surviving user data") + assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) } + assertEquals("only surviving user data", File(staging, "root/save.dat").readText()) + } + + @Test fun conflictingIntendedHomesAreRetainedWithoutProofOfTheirContents() { + val root = File(tmp.root, "runtime") + val old = tmp.newFolder("runtime.old") + val staging = tmp.newFolder("runtime.new") + put(old, "root/save.dat", "user data") + put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "root") + put(staging, "root/.bashrc", "shipped default") + + assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) } + + assertEquals("user data", File(root, "root/save.dat").readText()) + assertEquals("shipped default", File(staging, "root/.bashrc").readText()) + assertTrue(File(staging, LinuxRuntimeInstaller.CARRY_MARKER).exists()) + } + + @Test fun anUnreadableCarryMarkerStopsRecovery() { + val root = tmp.newFolder("runtime") + val staging = tmp.newFolder("runtime.new") + val old = File(tmp.root, "runtime.old") + val marker = File(staging, LinuxRuntimeInstaller.CARRY_MARKER).apply { mkdirs() } + + assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) } + assertTrue(marker.isDirectory) + } + + @Test fun recoveryMovesOnlyAnIntendedPathThatWasAlreadyCarried() { + val root = File(tmp.root, "runtime") + val old = tmp.newFolder("runtime.old") + val staging = tmp.newFolder("runtime.new") + put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "root") + put(staging, "root/save.dat", "moved user data") + + LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) + + assertEquals("moved user data", File(root, "root/save.dat").readText()) + assertFalse(File(staging, LinuxRuntimeInstaller.CARRY_MARKER).exists()) + } + + @Test fun aSymlinkedParentCannotRedirectAUserDataMoveOutsideTheRuntime() { + val old = tmp.newFolder("old") + val staging = tmp.newFolder("staging") + val outside = tmp.newFolder("outside") + put(outside, "droiddeck-apps/game/run.sh", "outside data") + Files.createSymbolicLink(File(old, "opt").toPath(), outside.toPath()) + + assertThrows(IOException::class.java) { RuntimeFileTree.carryUserData(old, staging, false) } + + assertEquals("outside data", File(outside, "droiddeck-apps/game/run.sh").readText()) + assertFalse(File(staging, "opt/droiddeck-apps").exists()) + } + + @Test fun anInaccessibleLiveHomeIsNeverTreatedAsMissing() { + assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix")) + val root = tmp.newFolder("runtime") + val staging = tmp.newFolder("runtime.new") + val old = File(tmp.root, "runtime.old") + put(root, "root/keep.dat", "current user data") + put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1") + put(staging, "root/staged.dat", "staged user data") + assertTrue(root.setExecutable(false, false)) + val failure = try { + runCatching { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }.exceptionOrNull() + } finally { + root.setExecutable(true, true) + } + + assertTrue("the existing live home was deleted", File(root, "root/keep.dat").isFile) + assertEquals("current user data", File(root, "root/keep.dat").readText()) + assertEquals("staged user data", File(staging, "root/staged.dat").readText()) + assertTrue("inaccessible data must abort recovery", failure is IOException) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/BatteryComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/session/BatteryComponentTest.kt index 0c94f8225c..443559cf1e 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/BatteryComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/BatteryComponentTest.kt @@ -49,11 +49,25 @@ class BatteryComponentTest { assertEquals("-2000000", File(supplies, "BAT1/current_now").readText().trim()) } - private fun start(supplies: File, vpower: File, currentUa: Long) { + @Test fun chargingAtFullLevelIsReportedFullSoSteamStopsSaying99() { + val supplies = tmp.newFolder("power_supply") + val vpower = tmp.newFolder("vpower") + start(supplies, vpower, 2_000_000L, BatteryManager.BATTERY_STATUS_CHARGING, 100) + assertEquals("Full", File(supplies, "BAT1/status").readText().trim()) + assertEquals("Full", File(vpower, "battery_status").readText().trim()) + battery?.stop() + start(supplies, vpower, 2_000_000L, BatteryManager.BATTERY_STATUS_CHARGING, 99) + assertEquals("Charging", File(supplies, "BAT1/status").readText().trim()) + } + + private fun start( + supplies: File, vpower: File, currentUa: Long, + status: Int = BatteryManager.BATTERY_STATUS_DISCHARGING, level: Int = 50, + ) { val context = RuntimeEnvironment.getApplication() context.sendStickyBroadcast(Intent(Intent.ACTION_BATTERY_CHANGED).apply { - putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_DISCHARGING) - putExtra(BatteryManager.EXTRA_LEVEL, 50) + putExtra(BatteryManager.EXTRA_STATUS, status) + putExtra(BatteryManager.EXTRA_LEVEL, level) putExtra(BatteryManager.EXTRA_SCALE, 100) putExtra(BatteryManager.EXTRA_VOLTAGE, 4000) }) diff --git a/app/src/test/java/com/droiddeck/launcher/session/ComponentImportTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ComponentImportTest.kt new file mode 100644 index 0000000000..db42f4df1e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/ComponentImportTest.kt @@ -0,0 +1,135 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.core.Hashes +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.github.luben.zstd.ZstdOutputStream +import org.apache.commons.compress.archivers.tar.TarArchiveEntry +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +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 +import java.io.BufferedOutputStream +import java.io.File +import java.io.FileOutputStream + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class ComponentImportTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + File(context.filesDir, "components").deleteRecursively() + LinuxRuntime.rootDir(context).deleteRecursively() + } + + @Test fun refusesOverwritingReferencedPackageWithDifferentContent() { + val wcpA = createWcp("src-a.wcp", "A") + val wcpB = createWcp("src-b.wcp", "B") + val shaA = Hashes.sha256(wcpA) + + ComponentsManager.importPackage(context, wcpA, "dxvk.wcp") + ComponentsManager.setGameComponent(context, "10", "dxvk", "dxvk.wcp") + + assertThrows(IllegalStateException::class.java) { + ComponentsManager.importPackage(context, wcpB, "dxvk.wcp") + } + + val stored = File(context.filesDir, "components/packages/dxvk.wcp") + assertEquals(shaA, Hashes.sha256(stored)) + assertFalse(File(context.filesDir, "components/packages/dxvk.wcp.part").exists()) + } + + @Test fun allowsReimportingIdenticalPackageWhileReferenced() { + val wcpA = createWcp("src-a.wcp", "A") + val shaA = Hashes.sha256(wcpA) + + ComponentsManager.importPackage(context, wcpA, "dxvk.wcp") + ComponentsManager.setGameComponent(context, "10", "dxvk", "dxvk.wcp") + + val reimported = ComponentsManager.importPackage(context, wcpA, "dxvk.wcp") + assertEquals("A", reimported.version) + assertEquals("dxvk.wcp", reimported.file) + + val stored = File(context.filesDir, "components/packages/dxvk.wcp") + assertEquals(shaA, Hashes.sha256(stored)) + assertFalse(File(context.filesDir, "components/packages/dxvk.wcp.part").exists()) + } + + @Test fun invalidatesUnpackedStoreWhenReplacingUnreferencedPackage() { + val wcpA = createWcp("src-a.wcp", "A") + val wcpB = createWcp("src-b.wcp", "B") + val shaB = Hashes.sha256(wcpB) + + ComponentsManager.importPackage(context, wcpA, "dxvk.wcp") + val unpacked = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/store/dxvk") + unpacked.mkdirs() + File(unpacked, ".complete").writeText("ok") + assertTrue(File(unpacked, ".complete").isFile) + + val replaced = ComponentsManager.importPackage(context, wcpB, "dxvk.wcp") + assertEquals("B", replaced.version) + + val stored = File(context.filesDir, "components/packages/dxvk.wcp") + assertEquals(shaB, Hashes.sha256(stored)) + assertFalse(unpacked.exists()) + } + + @Test fun deletingAPackageAGameProfileUsesClearsThatProfileEntry() { + val wcpA = createWcp("src-a.wcp", "A") + ComponentsManager.importPackage(context, wcpA, "dxvk.wcp") + writeGameProfile("10", "dxvk", "dxvk.wcp") + + ComponentsManager.deletePackage(context, "dxvk.wcp") + + assertFalse(File(context.filesDir, "components/packages/dxvk.wcp").exists()) + val state = JSONObject(File(context.filesDir, "components/state.json").readText()) + assertFalse(state.optJSONObject("profiles")?.optJSONObject("10")?.has("dxvk") == true) + } + + private fun writeGameProfile(scope: String, comp: String, file: String) { + val state = File(context.filesDir, "components/state.json") + state.parentFile!!.mkdirs() + state.writeText( + JSONObject() + .put("active", JSONObject()) + .put("queued", JSONObject()) + .put("profiles", JSONObject().put(scope, JSONObject().put(comp, file))) + .toString(), + ) + } + + private fun createWcp(fileName: String, version: String): File { + val out = File(context.cacheDir, fileName) + val profile = JSONObject() + .put("type", "DXVK-Linux") + .put("versionName", version) + .put("description", "DXVK $version") + .toString() + .toByteArray(Charsets.UTF_8) + val dll = "dxvk-dll-$version".toByteArray(Charsets.UTF_8) + + TarArchiveOutputStream(ZstdOutputStream(BufferedOutputStream(FileOutputStream(out)))).use { tar -> + tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX) + val profEntry = TarArchiveEntry("profile.json").apply { size = profile.size.toLong() } + tar.putArchiveEntry(profEntry) + tar.write(profile) + tar.closeArchiveEntry() + + val dllEntry = TarArchiveEntry("files/lib/wine/dxvk/aarch64-windows/d3d11.dll").apply { size = dll.size.toLong() } + tar.putArchiveEntry(dllEntry) + tar.write(dll) + tar.closeArchiveEntry() + } + return out + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/ComponentsCarryOverTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ComponentsCarryOverTest.kt new file mode 100644 index 0000000000..60c1104516 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/ComponentsCarryOverTest.kt @@ -0,0 +1,30 @@ +package com.droiddeck.launcher.session + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class ComponentsCarryOverTest { + @Test + fun swappedPackagesFollowTheBuildThatReplacesTheirProton() { + val state = JSONObject(""" + {"active": {"DroidDeck-Proton_11-11.2": { + "dxvk": {"file": "dxvk-2.7.wcp", "label": "2.7", "protonVersion": "11-11.2"}, + "vkd3d": {"file": "original 11-11.1", "label": "Original from 11-11.1"}, + "fex": {"file": "gone.wcp", "label": "old"}}}, + "queued": {"DroidDeck-Proton_11-11.2": { + "vkd3d": {"kind": "package", "file": "vkd3d-3.0.wcp", "label": "3.0"}, + "fex": {"kind": "original", "protonVersion": "11-11.1", "label": "Original 11-11.1"}}}} + """.trimIndent()) + val carried = ComponentsManager.carried(state, "DroidDeck-Proton_11-11.2") { it != "gone.wcp" } + assertEquals(setOf("dxvk", "vkd3d"), carried.keys) + assertEquals("package", carried.getValue("dxvk").getString("kind")) + assertEquals("dxvk-2.7.wcp", carried.getValue("dxvk").getString("file")) + assertEquals("2.7", carried.getValue("dxvk").getString("label")) + assertEquals("vkd3d-3.0.wcp", carried.getValue("vkd3d").getString("file")) + assertEquals(emptyMap<String, JSONObject>(), ComponentsManager.carried(state, "GE-Proton11-7") { true }) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt new file mode 100644 index 0000000000..74978ee30c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt @@ -0,0 +1,110 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.github.luben.zstd.ZstdOutputStream +import org.apache.commons.compress.archivers.tar.TarArchiveEntry +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream +import org.json.JSONObject +import org.junit.Assert.assertEquals +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 +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class ComponentsRepublishTest { + private val fex = "FEXCore-2610-d2rfix28-linux.wcp" + private val scope = "2596113170" + private val dll = "files/lib/wine/aarch64-windows/libwow64fex.dll" + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + File(context.filesDir, "components").deleteRecursively() + LinuxRuntime.rootDir(context).deleteRecursively() + } + + @Test fun aGameFexChoiceReachesAProtonInstalledAfterIt() { + proton("DroidDeck-Proton 11-11.7", "DroidDeck-Proton-11-11.7") + packageFile() + ComponentsManager.setGameComponent(context, scope, "fex", fex) + assertEquals(setOf("DroidDeck-Proton 11-11.7"), scopedTools()) + + proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8") + assertEquals(setOf("DroidDeck-Proton 11-11.7"), scopedTools()) + + assertTrue(ComponentsManager.republish(context)) + assertEquals(setOf("DroidDeck-Proton 11-11.7", "DroidDeck-Proton 11-11.8"), scopedTools()) + val row = rows().single { it[0] == scope && it[1] == "DroidDeck-Proton 11-11.8" && it[4] == dll } + assertEquals("DroidDeck-Proton-11-11.8", row[2]) + assertEquals("d2rfix28 wow64", File(LinuxRuntime.rootDir(context), row[6].removePrefix("/")).readText()) + assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"]) + } + + @Test fun nothingIsRewrittenWhileTheToolsAreUnchanged() { + proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8") + packageFile() + ComponentsManager.setGameComponent(context, scope, "fex", fex) + val published = launchState().readText() + val modified = launchState().lastModified() + + assertFalse(ComponentsManager.republish(context)) + assertEquals(published, launchState().readText()) + assertEquals(modified, launchState().lastModified()) + } + + @Test fun anUnreadableStateLeavesThePublishedSelectionsAlone() { + proton("DroidDeck-Proton 11-11.7", "DroidDeck-Proton-11-11.7") + packageFile() + ComponentsManager.setGameComponent(context, scope, "fex", fex) + val published = launchState().readText() + val state = File(context.filesDir, "components/state.json").apply { writeText("{\"active\": ") } + proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8") + + assertFalse(ComponentsManager.republish(context)) + assertEquals(published, launchState().readText()) + assertEquals("{\"active\": ", state.readText()) + } + + @Test fun withNoSelectionsNothingIsPublished() { + proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8") + + assertFalse(ComponentsManager.republish(context)) + assertFalse(launchState().exists()) + } + + private fun scopedTools() = rows().filter { it[0] == scope }.map { it[1] }.toSet() + + private fun rows() = launchState().readLines().filter { it.isNotEmpty() }.map { it.split('\t') } + + private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv") + + private fun proton(name: String, version: String) { + val dir = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name") + File(dir, "files/lib/wine").mkdirs() + File(dir, "proton").writeText("#!/bin/sh\n") + File(dir, "version").writeText("1 $version\n") + File(dir, dll).apply { parentFile!!.mkdirs(); writeText("bundled FEX $version") } + } + + private fun packageFile() { + val out = File(context.filesDir, "components/packages/$fex").apply { parentFile!!.mkdirs() } + val profile = JSONObject().put("type", "FEXCore-Linux").put("versionName", "2610-d2rfix28").toString().toByteArray() + val body = "d2rfix28 wow64".toByteArray() + TarArchiveOutputStream(ZstdOutputStream(out.outputStream())).use { tar -> + tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() }) + tar.write(profile) + tar.closeArchiveEntry() + tar.putArchiveEntry(TarArchiveEntry(dll).apply { size = body.size.toLong() }) + tar.write(body) + tar.closeArchiveEntry() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/ForcedPackageTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ForcedPackageTest.kt index 3f5e6e8e41..ba026b4742 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ForcedPackageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ForcedPackageTest.kt @@ -29,6 +29,18 @@ class ForcedPackageTest { LinuxRuntime.rootDir(context).deleteRecursively() } + @Test fun unpackedCacheNameCannotEscapeStoreDirectory() { + assertEquals("dxvk-2.7.1-linux", ComponentsManager.unpackedCacheKey(dxvk2)) + for (filename in listOf("..wcp", "...wcp")) { + try { + ComponentsManager.unpackedCacheKey(filename) + fail("Expected cache traversal name to be rejected: $filename") + } catch (_: IllegalArgumentException) { + // Expected: the derived path would be a dot segment. + } + } + } + @Test fun adreno6xxForcesDxvk2AndNothingElseDoes() { val rule = ComponentsManager.FORCED_PACKAGES.single { GpuInfo.Family.A6XX in it.families } assertEquals("dxvk", rule.comp) diff --git a/app/src/test/java/com/droiddeck/launcher/session/MemoryReadoutTest.kt b/app/src/test/java/com/droiddeck/launcher/session/MemoryReadoutTest.kt new file mode 100644 index 0000000000..a4e4951310 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/MemoryReadoutTest.kt @@ -0,0 +1,66 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class MemoryReadoutTest { + private val meminfo = """ + MemTotal: 11379920 kB + MemFree: 527864 kB + MemAvailable: 3235768 kB + Buffers: 1024 kB + SwapTotal: 16777212 kB + SwapFree: 10358080 kB + """.trimIndent() + + @Test fun memoryAndSwapInUseComeFromMeminfo() { + val device = MemoryReadout.parseMeminfo(meminfo)!! + assertEquals(11379920L - 3235768L, device.usedKb) + assertEquals(16777212L - 10358080L, device.swapUsedKb) + assertEquals("7.8", MemoryReadout.gb(device.usedKb)) + assertEquals("10.9", MemoryReadout.gb(device.totalKb)) + assertEquals(0L, MemoryReadout.parseMeminfo("MemTotal: 100 kB\nMemAvailable: 40 kB\n")!!.swapUsedKb) + assertNull(MemoryReadout.parseMeminfo("MemTotal: 100 kB\n")) + } + + @Test fun aProcessCountsItsResidentAnonymousAndSharedMemory() { + val status = """ + Name: Diablo IV.exe + VmRSS: 2000000 kB + RssAnon: 1500000 kB + RssFile: 400000 kB + RssShmem: 100000 kB + VmSwap: 300000 kB + """.trimIndent() + assertEquals(1600000L, MemoryReadout.residentKb(status)) + assertEquals(0L, MemoryReadout.residentKb("Name:\tkthreadd\n")) + } + + @Test fun theGameIsWhatRunsInAWinePrefix() { + fun env(vararg vars: String) = vars.joinToString("\u0000", postfix = "\u0000").toByteArray() + assertTrue(MemoryReadout.inWinePrefix(env("HOME=/root", "WINEPREFIX=/root/pfx", "DISPLAY=:0"))) + assertTrue(MemoryReadout.inWinePrefix("WINEPREFIX=/x".toByteArray())) + assertFalse(MemoryReadout.inWinePrefix(env("HOME=/root", "STEAM_COMPAT_DATA_PATH=/x", "MY_WINEPREFIX=/y"))) + assertFalse(MemoryReadout.inWinePrefix(ByteArray(0))) + } + + @Test fun androidIsWhatIsLeftOfTheMemoryInUse() { + val device = MemoryReadout.Device(totalKb = 10_000, availableKb = 3_000, swapTotalKb = 0, swapFreeKb = 0) + assertEquals(3_000L, MemoryReadout.androidKb(device, MemoryReadout.Split(gameKb = 2_000, droiddeckKb = 1_000, gpuKb = 1_000))) + assertEquals(4_000L, MemoryReadout.androidKb(device, MemoryReadout.Split(gameKb = 2_000, droiddeckKb = 1_000, gpuKb = null))) + assertEquals(0L, MemoryReadout.androidKb(device, MemoryReadout.Split(gameKb = 6_000, droiddeckKb = 2_000, gpuKb = 1_000))) + } + + @Test fun theLogLineSaysEveryPartInMegabytes() { + val device = MemoryReadout.Device(totalKb = 11_379_920, availableKb = 1_048_576, swapTotalKb = 16_777_212, swapFreeKb = 8_388_606) + val split = MemoryReadout.Split(gameKb = 2_097_152, droiddeckKb = 524_288, gpuKb = 3_145_728) + assertEquals( + "used 10089/11113 MB, available 1024 MB, swap 8191/16383 MB | game 2048, droiddeck 512, android 4457, gpu 3072 MB", + MemoryLog.line(device, split), + ) + assertTrue(MemoryLog.line(device, split.copy(gpuKb = null)).endsWith("gpu ? MB")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/NoSteamLaunchTest.kt b/app/src/test/java/com/droiddeck/launcher/session/NoSteamLaunchTest.kt index 84c995ee23..d0739df4ae 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/NoSteamLaunchTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/NoSteamLaunchTest.kt @@ -61,6 +61,8 @@ class NoSteamLaunchTest { listOf("--app", "2733369024", "--dir", game.guestDir, "--options", "-windowed", "--", game.guestExe), added.args, ) + val plain = NoSteamLaunch.addedCommand(AddedGames.Game(game.folder, game.name, game.exe, game.guestExe, game.guestDir, 2733369024L, 0L, emptyList(), source = "gog")) + assertEquals(listOf("--app", "2733369024", "--dir", game.guestDir, "--", game.guestExe), plain.args) assertNull(NoSteamLaunch.command(shortcut, null)) val steam = NoSteamLaunch.command(steamGame, null)!! assertEquals(listOf("--app", "413150"), steam.args) diff --git a/app/src/test/java/com/droiddeck/launcher/session/OrientationTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OrientationTest.kt index 5d67d041a2..1801ce756c 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/OrientationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/OrientationTest.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.session import android.content.Context import android.content.pm.ActivityInfo +import com.droiddeck.launcher.core.AppUiPrefs import org.junit.Assert.* import org.junit.Before import org.junit.Test @@ -17,15 +18,12 @@ class OrientationTest { @Before fun clearOrientation() { context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().clear().commit() } - @Test fun landscapeChoicesPersistGloballyAndCanRestoreAutomaticRotation() { + @Test fun sessionChoicesPersistGloballyWithLandscapeAsTheDefault() { assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context)) - for (value in listOf( - ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, - ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, - ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, - )) { + for ((value, _) in SessionPrefs.orientationOptions) { SessionPrefs.setOrientation(context, value) assertEquals(value, SessionPrefs.orientation(context.createConfigurationContext(context.resources.configuration))) } @@ -33,12 +31,61 @@ class OrientationTest { @Test fun invalidStoredOrientationFallsBackAndInvalidChoicePreservesTheSavedValue() { val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE) - prefs.edit().putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT).commit() + prefs.edit().putInt("orientation", 999).commit() assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context)) SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) assertThrows(IllegalArgumentException::class.java) { - SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) + SessionPrefs.setOrientation(context, 999) } assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context)) } + + @Test fun launcherFollowsDeviceRotationAndPortraitDoesNotChangeSessions() { + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, AppUiPrefs.orientation(context)) + for ((value, _) in AppUiPrefs.orientationOptions) { + AppUiPrefs.setOrientation(context, value) + assertEquals(value, AppUiPrefs.orientation(context)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context)) + } + AppUiPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) + SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, AppUiPrefs.orientation(context)) + AppUiPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) + SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, AppUiPrefs.orientation(context)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.orientation(context)) + } + + @Test fun explicitOrientationTakesPriorityOverLargeFollowScreenWindows() { + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, true, 700)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.windowOrientation(context, true, 400)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.windowOrientation(context, false, 700)) + for ((value, _) in SessionPrefs.orientationOptions) { + SessionPrefs.setOrientation(context, value) + assertEquals(value, SessionPrefs.windowOrientation(context, true, 700)) + } + } + + @Test fun sessionPortraitUsesItsOwnLockOrTheCurrentRotation() { + val config = android.content.res.Configuration(context.resources.configuration) + config.orientation = android.content.res.Configuration.ORIENTATION_PORTRAIT + val portrait = context.createConfigurationContext(config) + config.orientation = android.content.res.Configuration.ORIENTATION_LANDSCAPE + val landscape = context.createConfigurationContext(config) + assertFalse(SessionPrefs.portrait(portrait)) + SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) + assertTrue(SessionPrefs.portrait(landscape)) + SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_USER) + assertTrue(SessionPrefs.portrait(portrait)) + assertFalse(SessionPrefs.portrait(landscape)) + } + + @Test fun invalidLauncherOrientationFallsBackAndInvalidChoicePreservesPreference() { + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", 999).commit() + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, AppUiPrefs.orientation(context)) + AppUiPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) + assertThrows(IllegalArgumentException::class.java) { AppUiPrefs.setOrientation(context, 999) } + assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, AppUiPrefs.orientation(context)) + } + } diff --git a/app/src/test/java/com/droiddeck/launcher/session/OutputPacingTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OutputPacingTest.kt new file mode 100644 index 0000000000..bd7dc380f5 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/OutputPacingTest.kt @@ -0,0 +1,14 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Test + +class OutputPacingTest { + @Test fun phoneOutputIsUnpaced() { + assertEquals(SessionPrefs.FPS_UNPACED, SessionPrefs.compositorFpsLimit(0)) + } + + @Test fun mirroringKeepsTheGlassesRate() { + assertEquals(60, SessionPrefs.compositorFpsLimit(60)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/PerfHudGraphTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PerfHudGraphTest.kt new file mode 100644 index 0000000000..bf607d3678 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/PerfHudGraphTest.kt @@ -0,0 +1,18 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Test + +class PerfHudGraphTest { + @Test fun theGraphShowsOnlyFramesFromThisHudRun() { + val samples = floatArrayOf(9f, 9f, 9f, 9f, 9f, 16.7f, 33.4f, 16.6f) + assertArrayEquals(floatArrayOf(16.7f, 33.4f, 16.6f), PerfHud.recent(samples, 105, 102), 0f) + assertEquals(0, PerfHud.recent(samples, 103, 102).size) + } + + @Test fun anEarlySessionShowsWhatWasShownSoFar() { + val samples = floatArrayOf(16.6f, 16.7f, 120f, 0f, 0f, 0f) + assertArrayEquals(floatArrayOf(16.6f, 16.7f, 50f), PerfHud.recent(samples, 3, 0), 0f) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/ProtonDefaultTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ProtonDefaultTest.kt index fcf85ddb99..5f0651bf25 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ProtonDefaultTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ProtonDefaultTest.kt @@ -103,4 +103,28 @@ class ProtonDefaultTest { assertNull(ProtonDefault.gameSelectedId(context, "42", listOf(proton("GE-Proton11-7", false)))) assertEquals(ProtonDefault.GameChoice(false, "GE-Proton9-1"), ProtonDefault.parseGames(file.readText())["42"]) } + + @Test + fun aReplacedBuildsPerGamePicksMoveToTheNewest() { + val old = ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-11.2") + val ge = ProtonDefault.GameChoice(false, "GE-Proton11-7") + val valve = ProtonDefault.GameChoice(true, "DroidDeck-Proton 11-11.2") + val moved = ProtonDefault.movedGames(mapOf("42" to old, "43" to ge, "44" to null, "45" to valve), setOf("DroidDeck-Proton 11-11.2"), "DroidDeck-Proton 11-11.4") + assertEquals(mapOf("42" to ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-11.4"), "43" to ge, "44" to null, "45" to valve), moved) + assertNull(ProtonDefault.movedGames(mapOf("43" to ge, "44" to null), setOf("DroidDeck-Proton 11-11.2"), "DroidDeck-Proton 11-11.4")) + } + + @Test + fun movingPicksRewritesTheGamesFile() { + val context = RuntimeEnvironment.getApplication() + val file = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat/games.json") + file.parentFile?.deleteRecursively() + ProtonDefault.requestGame(context, "42", proton("DroidDeck-Proton 11-11.2", false)) + ProtonDefault.requestGame(context, "43", null) + ProtonDefault.moveGames(context, setOf("DroidDeck-Proton 11-11.2"), "DroidDeck-Proton 11-11.4") + val games = ProtonDefault.parseGames(file.readText()) + assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-11.4"), games["42"]) + assertTrue(games.containsKey("43")) + assertNull(games["43"]) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt index 63dc1efd61..411268ef69 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt @@ -198,4 +198,35 @@ class ProtonExtrasTest { ComponentsManager.forgetProton(context, kept.name) assertTrue(File(originals, "GE-Proton11-8/GE-Proton11-8/dxvk.wcp").isFile) } + + @Test + fun anUpdateKeepsTheUsersProtonSettingsFile() { + val context = RuntimeEnvironment.getApplication() + val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d") + tools.deleteRecursively() + File(installTool(tools, "DroidDeck-Proton 11-11.1"), "user_settings.py").writeText("old") + File(installTool(tools, "DroidDeck-Proton 11-11.4"), "user_settings.py").writeText("mine") + installTool(tools, "DroidDeck-Proton 11-11.5") + ProtonExtras.tidy(context) + assertEquals(listOf("DroidDeck-Proton 11-11.5"), ProtonExtras.installedAll(context, tool("droiddeck"))) + assertEquals("mine", File(tools, "DroidDeck-Proton 11-11.5/user_settings.py").readText()) + } + + @Test + fun droidDeckProtonIsFetchedWhenMissingUnlessTheUserRemovedIt() { + val context = RuntimeEnvironment.getApplication() + val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d") + tools.deleteRecursively() + File(context.filesDir, "proton-latest.json").writeText( + """{"droiddeck":{"tag":"DroidDeck-Proton-11-11.4","at":1},"ge":{"tag":"GE-Proton11-7","at":1}}""") + ProtonExtras.setDeclined(context, false) + assertEquals("DroidDeck-Proton-11-11.4", ProtonExtras.missing(context, tool("droiddeck"))) + assertNull(ProtonExtras.missing(context, tool("ge"))) + ProtonExtras.setDeclined(context, true) + assertNull(ProtonExtras.missing(context, tool("droiddeck"))) + ProtonExtras.setDeclined(context, false) + installTool(tools, "DroidDeck-Proton 11-11.2") + assertNull(ProtonExtras.missing(context, tool("droiddeck"))) + assertEquals("DroidDeck-Proton-11-11.4", ProtonExtras.update(context, tool("droiddeck"))) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt index 8c5361aec1..78741888d3 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt @@ -115,6 +115,22 @@ class RumbleComponentTest { assertFalse(pad.vibrating) } + @Test fun quietingStopsAHeldEffectAndDropsEffectsUntilLifted() { + val pad = FakeMotors() + rumble.controllerMotors = { pad } + activeController(PAD_ID) + effect(strong = 40000, weak = 20000, ms = RumbleComponent.HOLD_MS) + rumble.quiet(true) + assertFalse(pad.vibrating) + idle(RumbleComponent.KEEPALIVE_MS * 4 + 100) + assertEquals("the keepalive restarted the motors while quiet", 1, pad.played.size) + effect(strong = 40000, weak = 20000) + assertFalse("an effect played while quiet", pad.vibrating) + rumble.quiet(false) + effect(strong = 40000, weak = 20000) + assertTrue(pad.vibrating) + } + @Test fun aHeldEffectFollowsTheGamesNewStrength() { val pad = FakeMotors() rumble.controllerMotors = { pad } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt index 48d77d0b0d..5d51028b05 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt @@ -4,6 +4,23 @@ import org.junit.Assert.* import org.junit.Test class SessionDisplayTest { + @Test fun portraitPresetsSwapTheOutputAndRetainTheResolutionCap() { + assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, "720p", portrait = true)) + assertEquals(900 to 1600, SessionDisplay.resolveChoice(1080 to 1920, "900p", portrait = true)) + assertEquals(720 to 1280, SessionDisplay.resolveChoice(1440 to 1080, "720p", portrait = true)) + assertEquals(720 to 1600, SessionDisplay.resolveChoice(2400 to 1080, "720p", portrait = true)) + assertEquals(1080 to 1920, SessionDisplay.resolveChoice(1921 to 1081, SessionDisplay.MATCH_SCREEN, portrait = true)) + assertEquals(1080 to 2400, SessionDisplay.resolveChoice(2400 to 1080, SessionDisplay.FOLLOW_SCREEN, portrait = true)) + assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, "invalid", portrait = true)) + } + + @Test fun customDimensionsStayExplicitInEitherOrientation() { + for (portrait in listOf(false, true)) { + assertEquals(1280 to 720, SessionDisplay.resolveChoice(1920 to 1080, "1280x720", portrait)) + assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, "720x1280", portrait)) + } + } + @Test fun fixedSizesAndMatchScreenResolveWithoutAnyAspectSetting() { assertEquals(1280 to 720, SessionDisplay.resolveChoice(1440 to 1080, "1280x720")) assertEquals(1600 to 900, SessionDisplay.resolveChoice(1280 to 720, "1600x900")) @@ -35,6 +52,7 @@ class SessionDisplayTest { } @Test fun unfoldedControlsKeepTheGameSixteenByNineAcrossTheWidth() { + assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920)) assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848)) assertEquals(1038, SessionDisplay.unfoldedGameHeight(1848, 2448)) assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080)) @@ -67,6 +85,18 @@ class SessionDisplayTest { assertFalse(SessionDisplay.unfoldedControlsWanted(true, true, true, true, true, false, 0, 1848, 700)) } + @Test fun portraitControlsWorkOnHandheldsAndPhonesWithoutAHinge() { + fun wanted(width: Int = 1080, height: Int = 1920, controller: Boolean = false, + keep: Boolean = false, pad: Boolean = true, pip: Boolean = false) = + SessionDisplay.unfoldedControlsWanted(true, false, controller, keep, pad, pip, width, height, 393) + assertTrue(wanted()) + assertFalse(wanted(width = 1920, height = 1080)) + assertFalse(wanted(controller = true)) + assertTrue(wanted(controller = true, keep = true)) + assertFalse(wanted(pad = false)) + assertFalse(wanted(pip = true)) + } + @Test fun followScreenKeepsTheWindowShapeAndSkipsTinyWindows() { assertEquals(2520 to 1080, SessionDisplay.resolveChoice(1080 to 2520, SessionDisplay.FOLLOW_SCREEN)) @@ -75,6 +105,13 @@ class SessionDisplayTest { assertNull(SessionDisplay.followSize(640, 360)) } + @Test fun aPhoneCanFollowTheShortGameAreaAboveItsControls() { + assertNull(SessionDisplay.followSize(720, 404)) + assertEquals(720 to 404, SessionDisplay.followSize(720, 404, controlsBelow = true)) + assertNull(SessionDisplay.followSize(320, 180, controlsBelow = true)) + assertNull(SessionDisplay.followSize(720, 0, controlsBelow = true)) + } + @Test fun resolutionCapsPreserveTheSelectedShapeWithoutExceedingPanelHeight() { assertEquals(1280 to 720, SessionDisplay.resolve(1920 to 1080, 720, SessionPrefs.SHAPE_AUTO)) assertEquals(960 to 720, SessionDisplay.resolve(1440 to 1080, 720, SessionPrefs.SHAPE_EXACT)) @@ -96,7 +133,10 @@ class SessionDisplayTest { @Test fun gameStretchAvailabilityMatchesTheRuntimeIncludingRounding() { assertTrue(SessionDisplay.canStretch16x9(960 to 720)) assertFalse(SessionDisplay.canStretch16x9(1280 to 720)) - assertFalse(SessionDisplay.canStretch16x9(1600 to 720)) + assertTrue(SessionDisplay.canStretch16x9(1600 to 720)) + assertTrue(SessionDisplay.canStretch16x9(2400 to 1080)) + assertFalse(SessionDisplay.canStretch16x9(1920 to 1080)) + assertFalse(SessionDisplay.canStretch16x9(1366 to 768)) val wide = SessionDisplay.resolve(1440 to 1080, 0, SessionPrefs.SHAPE_WIDE) assertFalse(SessionDisplay.canStretch16x9(wide)) } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt index 95893adde6..012d2a916d 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt @@ -50,6 +50,34 @@ class SessionLogShareZipTest { assertFalse(zip.exists()) } + @Test fun battleNetAndBlizzardLogsComeAlongScrubbedAndNewestFirst() { + val session = File(LinuxRuntime.logDir(app), "2026-10-25-05-battle-net").apply { mkdirs() } + File(session, "session.log").writeText("droiddeck-battlenet: open (from the menu)\n") + val root = LinuxRuntime.rootDir(app) + File(root, "root/.cache/droiddeck/battlenet").apply { mkdirs() }.apply { + resolve("battlenet.log").writeText("launching WoW\n") + resolve("other.log").writeText("other\n") + } + val drive = File(com.droiddeck.launcher.runtime.BattleNet.prefix(app), "pfx/drive_c") + val client = File(drive, "users/steamuser/AppData/Local/Battle.net/Logs").apply { mkdirs() } + val now = System.currentTimeMillis() + for (i in 1..8) client.resolve("battle.net-$i.log").apply { writeText("client $i accountId=1:0:5ca1ab1e\n"); setLastModified(now - i * 60_000L) } + client.resolve("battle.net-old.log").apply { writeText("old\n"); setLastModified(now - 30L * 86_400_000L) } + File(drive, "ProgramData/Battle.net/Agent/Agent.9824/Logs").apply { mkdirs() }.resolve("Agent-1.log").writeText("agent someone@example.com\n") + File(drive, "ProgramData/Battle.net/Agent/Agent.9900/Logs").apply { mkdirs() }.resolve("Agent-1.log").writeText("agent 9900\n") + File(drive, "ProgramData/Battle.net/Setup/bna_2/Logs").apply { mkdirs() }.resolve("battle.net-setup-1.log").writeText("setup\n") + + val zip = SessionLogShare.zipFolder(app, session)!! + val text = ZipFile(zip).use { z -> z.entries().toList().associate { e -> e.name to z.getInputStream(e).bufferedReader().readText() } } + assertTrue(text.keys.containsAll(listOf("battlenet/droiddeck/battlenet.log", "battlenet/agent/Agent.9824/Agent-1.log", "battlenet/agent/Agent.9900/Agent-1.log", "battlenet/setup/bna_2/battle.net-setup-1.log"))) + assertFalse(text.containsKey("battlenet/droiddeck/other.log")) + assertEquals((1..6).map { "battlenet/client/battle.net-$it.log" }.toSet(), text.keys.filter { it.startsWith("battlenet/client/") }.toSet()) + val all = text.values.joinToString("\n") + assertFalse(all.contains("5ca1ab1e")) + assertFalse(all.contains("someone@example.com")) + SessionLogShare.clear(app) + } + @Test fun theSharePassChangesNothingInACleanLine() { val line = "dxvk: Device 0x5 (Adreno 750) https://github.com/doitsujin/dxvk/releases code 403" assertEquals(line, com.droiddeck.launcher.core.LogRedactor.redactForShare(line)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt index 03a3243910..de082c7fe9 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt @@ -13,6 +13,16 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [28], manifest = Config.NONE) class SessionScalingPrefsTest { + @Test fun legacyAutomaticResolutionsRemainRotatablePresets() { + val context = RuntimeEnvironment.getApplication() + val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE) + prefs.edit().putString("shape", SessionPrefs.SHAPE_AUTO).putInt("resolutionCap.steam", 900).commit() + assertEquals("900p", SessionPrefs.resolutionChoice(context, "steam", 1920 to 1080)) + val desktop = SessionPrefs.resolutionChoice(context, "lxqt", 1920 to 1080) + assertEquals("720p", desktop) + assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, desktop, portrait = true)) + } + @Before fun clearSettings() { RuntimeEnvironment.getApplication().getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt index e73905cbe6..c37f59c9ce 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt @@ -27,9 +27,10 @@ class SettingsResetTest { @Test fun settingsGoBackToTheirDefaults() { SessionPrefs.setTheme(app, "ocean") + SessionPrefs.setBackDoubleTapMs(app, 100) SessionPrefs.setUnfoldedControlsWithController(app, true) SessionPrefs.setNoXalia(app, false) - SessionPrefs.setFpsLimit(app, SessionService.MODE_STEAM, 30) + session.edit().putInt("fpsLimit.steam", 30).commit() SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true) SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800") SessionPrefs.setGuestHostname(app, "MyDeck") @@ -46,9 +47,10 @@ class SettingsResetTest { assertTrue(SettingsReset.resetAll(app, gameProfiles = false)) assertEquals("graphite", SessionPrefs.theme(app)) + assertEquals(500, SessionPrefs.backDoubleTapMs(app)) assertFalse(SessionPrefs.unfoldedControlsWithController(app)) assertTrue(SessionPrefs.noXalia(app)) - assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM)) + assertFalse(session.contains("fpsLimit.steam")) assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP)) assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM)) assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/WineProcessesTest.kt b/app/src/test/java/com/droiddeck/launcher/session/WineProcessesTest.kt new file mode 100644 index 0000000000..ee591d7134 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/WineProcessesTest.kt @@ -0,0 +1,23 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class WineProcessesTest { + private fun argv(vararg args: String) = args.joinToString("\u0000", postfix = "\u0000").toByteArray() + + @Test fun aWineserverIsKnownByItsProgramOrItsName() { + assertTrue(WineProcesses.isWineserver(argv("/root/.local/share/droiddeck-esync/dist/valve-11/files/bin-arm64/wineserver"), "wineserver\n")) + assertTrue(WineProcesses.isWineserver(argv("wineserver", "-p0"), null)) + assertTrue(WineProcesses.isWineserver(null, "wineserver\n")) + assertTrue(WineProcesses.isWineserver(ByteArray(0), "wineserver")) + } + + @Test fun nothingElseIs() { + assertFalse(WineProcesses.isWineserver(argv("C:\\windows\\system32\\services.exe"), "services.exe\n")) + assertFalse(WineProcesses.isWineserver(argv("/usr/bin/python3", "/x/files/bin-arm64/wineserver"), "python3\n")) + assertFalse(WineProcesses.isWineserver(argv("/opt/wineserver-helper"), "wineserver-help")) + assertFalse(WineProcesses.isWineserver(null, null)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavePathsTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavePathsTest.kt index a88c8b9548..675c1e009e 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavePathsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavePathsTest.kt @@ -47,4 +47,34 @@ class CloudSavePathsTest { File(profile, "AppData/Local/My-Game").mkdirs() assertEquals(File(profile, "AppData/Local/My-Game").path, CloudSavePaths.epic("{AppData}/MyGame", prefix, install, "acc", "app")!!.path) } + + @Test fun gogGalaxySdkEmptyLocationsUseDefaultLocation() { + val loc = CloudSavePaths.gogSaveFromRemote(true, emptyList(), "1")!! + assertEquals( + "%LocalAppData%/GOG.com/Galaxy/Applications/1/Storage/Shared/Files", + loc.template, + ) + assertEquals(CloudSavePaths.GOG_DEFAULT_NAMESPACE, loc.name) + val dir = CloudSavePaths.gog(loc.template, prefix, install) + assertEquals( + File(profile, "AppData/Local/GOG.com/Galaxy/Applications/1/Storage/Shared/Files").path, + dir!!.path, + ) + } + + @Test fun gogCloudDisabledOrUnknownClientIsNone() { + assertNull(CloudSavePaths.gogSaveFromRemote(false, emptyList(), "1")) + assertNull(CloudSavePaths.gogSaveFromRemote(true, emptyList(), "")) + assertNull(CloudSavePaths.gogSaveFromRemote(true, listOf("saves" to ""), "")) + } + + @Test fun gogNamedLocationKeepsItsNameAndPreferSaves() { + val loc = CloudSavePaths.gogSaveFromRemote( + true, + listOf("other" to "<?SAVED_GAMES?>/A", "Saves" to "<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN"), + "1", + )!! + assertEquals("<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN", loc.template) + assertEquals("Saves", loc.name) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesMigrationTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesMigrationTest.kt new file mode 100644 index 0000000000..ea4e953e0d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesMigrationTest.kt @@ -0,0 +1,76 @@ +package com.droiddeck.launcher.stores + +import java.io.File +import java.nio.file.Files +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class CloudSavesMigrationTest { + private val dir = Files.createTempDirectory("cloud-migrate").toFile() + private fun entry(bytes: ByteArray) = CloudPlan.Entry(CloudSaves.md5(bytes), null, 1000L) + + private fun nested(name: String, path: String, text: String): File = + File(dir, "$name/$path").apply { parentFile?.mkdirs(); writeText(text) } + + @Test fun movesOnlyFilesTheOldBaselineOwns() { + val a = "old save".toByteArray() + val game = "game wrote this".toByteArray() + nested("saves", "a.dat", String(a)) + nested("saves", "game.dat", String(game)) + val base = mapOf("saves/a.dat" to entry(a)) + val result = CloudSaves.migrateNested(dir, "saves", base)!! + assertEquals(1, result.moved) + assertEquals(0, result.cleaned) + assertEquals(String(a), File(dir, "a.dat").readText()) + assertEquals(String(game), File(dir, "saves/game.dat").readText()) + assertTrue("saves/a.dat" !in result.baseline) + assertEquals(entry(a), result.baseline["a.dat"]) + } + + @Test fun anIdenticalLeftoverIsRemovedAndItsBaselineKeyRewritten() { + val a = "old save".toByteArray() + File(dir, "a.dat").writeText(String(a)) + nested("saves", "a.dat", String(a)) + val result = CloudSaves.migrateNested(dir, "saves", mapOf("saves/a.dat" to entry(a)))!! + assertEquals(0, result.moved) + assertEquals(1, result.cleaned) + assertFalse(File(dir, "saves").exists()) + assertEquals(entry(a), result.baseline["a.dat"]) + assertTrue("saves/a.dat" !in result.baseline) + } + + @Test fun aDifferentDestinationKeepsTheGameFileAndTheBaseline() { + val a = "old save".toByteArray() + File(dir, "a.dat").writeText("newer game save") + nested("saves", "a.dat", String(a)) + val base = mapOf("saves/a.dat" to entry(a)) + val result = CloudSaves.migrateNested(dir, "saves", base)!! + assertEquals(0, result.moved) + assertEquals(0, result.cleaned) + assertEquals("newer game save", File(dir, "a.dat").readText()) + assertEquals(String(a), File(dir, "saves/a.dat").readText()) + assertEquals(base, result.baseline) + } + + @Test fun aSymlinkedAncestorIsNotMigrated() { + val outside = Files.createTempDirectory("cloud-outside").toFile() + File(outside, "a.dat").writeText("outside") + File(dir, "saves").mkdirs() + Files.createSymbolicLink(File(dir, "saves/link").toPath(), outside.toPath()) + val result = CloudSaves.migrateNested(dir, "saves", + mapOf("saves/link/a.dat" to entry("outside".toByteArray())))!! + assertEquals(0, result.moved) + assertEquals(0, result.cleaned) + assertTrue(File(outside, "a.dat").isFile) + } + + @Test fun aLocationNameThatCanLeaveTheFolderIsRefused() { + nested("saves", "a.dat", "x") + assertNull(CloudSaves.migrateNested(dir, "../saves", emptyMap())) + assertNull(CloudSaves.migrateNested(dir, "..", emptyMap())) + assertNull(CloudSaves.migrateNested(dir, "saves/..", emptyMap())) + } +} 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 0c30447430..0b80032627 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt @@ -4,6 +4,7 @@ import java.io.File import java.util.concurrent.Executor import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith @@ -77,12 +78,22 @@ class CloudSavesTest { assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId)) CloudSaves.uploadAllDirty(app, "recovery", running = true) assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId)) - com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_template_$gameId", "").apply() + com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit() + .putString("cloud_template_$gameId", "none") + .putLong("cloud_template_at_$gameId", System.currentTimeMillis()) + .apply() assertEquals("no-cloud-saves", CloudSaves.uploadDirty(app, Store.GOG, gameId, "exit")!!.reason) assertTrue(CloudSaves.dirty(app).none { it.second == gameId }) assertEquals(null, CloudSaves.uploadDirty(app, Store.GOG, gameId, "session-end")) } + @Test fun aNegativeCloudTemplateIsRetriedAfterADay() { + val now = 1_000_000L + assertTrue(CloudSaves.noneTemplateIsCurrent(now, now + 60_000L)) + assertFalse(CloudSaves.noneTemplateIsCurrent(now, now + CloudSaves.TEMPLATE_NONE_TTL_MS)) + assertFalse(CloudSaves.noneTemplateIsCurrent(0L, now)) + } + @Test fun aFirstLaunchWithoutAPrefixIsDeferredNotBlocked() { val deferred = ArrayList<Runnable>() val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN").apply { mkdirs() } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt new file mode 100644 index 0000000000..df7ba8f2ba --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt @@ -0,0 +1,61 @@ +package com.droiddeck.launcher.stores + +import java.io.ByteArrayOutputStream +import java.util.zip.GZIPOutputStream +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class GogCloudKeysTest { + @Test fun defaultLocationIsStrippedLikeAnyNamedLocation() { + val files = listOf(CloudFile("__default/savegame0.sav", 1L), CloudFile("saves/slot0.sav", 2L)) + val (chosen, relative) = gogRelativeNames(files, "__default") + assertEquals("__default", chosen) + assertEquals(listOf("savegame0.sav"), relative.map { it.name }) + } + + @Test fun gzipGogPutMatchesPythonGzipCompressLevel6Mtime0() { + val raw = "savegame0".toByteArray() + val expected = "1f8b08000000000000032b4e2c4b4d4fcc4d35000065fc333209000000".hex() + assertArrayEquals(expected, gzipGogPut(raw)) + assertArrayEquals(raw, gunzip(expected)) + } + + @Test fun contentEncodingGzipIsPeeledOnce() { + val raw = "savegame0".toByteArray() + val gz = ByteArrayOutputStream().also { GZIPOutputStream(it).use { z -> z.write(raw) } }.toByteArray() + assertArrayEquals(raw, gogDecodeCloudBody(gz, "gzip")) + assertArrayEquals(raw, gogDecodeCloudBody(raw, "gzip")) + } + + @Test fun corruptDeclaredGzipIsRejected() { + val corrupt = gzipGogPut("savegame0".toByteArray()).dropLast(2).toByteArray() + assertTrue(isGzip(corrupt)) + assertTrue(runCatching { gogDecodeCloudBody(corrupt, "gzip") }.isFailure) + } + + @Test fun isoDateHonorsOffsetAndFractionalSeconds() { + val expected = java.time.Instant.parse("2024-01-02T01:04:05.123Z").toEpochMilli() + assertEquals(expected, isoDate("2024-01-02T03:04:05.123+02:00")) + assertEquals(expected, isoDate("2024-01-02T01:04:05.123")) + } + + @Test fun gogPutWrappedBodyWithoutEncodingIsPeeled() { + val raw = "savegame0".toByteArray() + assertArrayEquals(raw, gogDecodeCloudBody(gzipGogPut(raw), null)) + assertArrayEquals(raw, gogDecodeCloudBody(raw, null)) + } + + @Test fun gzipThatIsTheSaveIsLeftIntact() { + val raw = "savegame0".toByteArray() + val gameGz = ByteArrayOutputStream().also { GZIPOutputStream(it).use { z -> z.write(raw) } }.toByteArray() + assertTrue(isGzip(gameGz)) + assertFalse(gzipGogPut(raw).contentEquals(gameGz)) + assertArrayEquals(gameGz, gogDecodeCloudBody(gameGz, null)) + } +} + +private fun String.hex() = chunked(2).map { it.toInt(16).toByte() }.toByteArray() diff --git a/app/src/test/java/com/droiddeck/launcher/stores/GogCloudNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/GogCloudNamesTest.kt new file mode 100644 index 0000000000..33959c7314 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/GogCloudNamesTest.kt @@ -0,0 +1,52 @@ +package com.droiddeck.launcher.stores + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class GogCloudNamesTest { + private fun files(vararg names: String) = names.map { CloudFile(it, 1000L) } + + @Test fun silksongLocationIsDroppedFromThePath() { + val (location, mapped) = gogRelativeNames( + files("saves/user1.dat", "saves/shared.dat", "saves/Restore_Points1/restoreData2.dat"), "saves") + assertEquals("saves", location) + assertEquals(listOf("user1.dat", "shared.dat", "Restore_Points1/restoreData2.dat"), mapped.map { it.name }) + } + + @Test fun anotherLocationIsFilteredOut() { + val (_, mapped) = gogRelativeNames(files("saves/a.dat", "__default/settings.ini"), "saves") + assertEquals(listOf("a.dat"), mapped.map { it.name }) + } + + @Test fun theOnlyLocationIsInferredWhenItsNameWasNotCached() { + val (location, mapped) = gogRelativeNames(files("saves/a.dat", "saves/b.dat"), null) + assertEquals("saves", location) + assertEquals(listOf("a.dat", "b.dat"), mapped.map { it.name }) + } + + @Test fun namesWithoutALocationPrefixAreLeftAlone() { + val (location, mapped) = gogRelativeNames(files("a.dat", "b.dat"), null) + assertNull(location) + assertEquals(listOf("a.dat", "b.dat"), mapped.map { it.name }) + } + + @Test fun aConfiguredLocationDoesNotYieldToAnotherLocation() { + val (location, mapped) = gogRelativeNames(files("__default/settings.ini"), "saves") + assertEquals("saves", location) + assertTrue(mapped.isEmpty()) + } + + @Test fun aMixedListingWithOneSubfolderIsLeftAlone() { + val (location, mapped) = gogRelativeNames(files("a.dat", "sub/b.dat"), "saves") + assertNull(location) + assertEquals(listOf("a.dat", "sub/b.dat"), mapped.map { it.name }) + } + + @Test fun aMissingCachedLocationDoesNotHideUnprefixedNames() { + val (location, mapped) = gogRelativeNames(files("a.dat"), "saves") + assertNull(location) + assertEquals(listOf("a.dat"), mapped.map { it.name }) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt index 78e9bbc0d0..126001797d 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt @@ -5,7 +5,10 @@ import com.droiddeck.launcher.session.SessionPrefs import java.io.File import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +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 @@ -18,6 +21,12 @@ import org.robolectric.shadows.ShadowStatFs class StoreInstallRootTest { private val app get() = RuntimeEnvironment.getApplication() + @Before fun resetStoragePreferences() { + SessionPrefs.setDefaultStorageFolder(app, "", "") + SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_ASK) + SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "") + } + @Test fun theDefaultRootIsInternalWhateverTheSteamLibrarySettingSays() { val card = File(app.filesDir, "fake-card/steam").apply { mkdirs() } SessionPrefs.setGameStorage(app, card.path, "Card") @@ -26,6 +35,72 @@ class StoreInstallRootTest { assertFalse(StoreInstallRoot.targets(app).first().removable) } + @Test fun defaultStoragePicksTheInternalOrTheConfiguredExternalTarget() { + val library = File(app.filesDir, "default-card/steam").apply { mkdirs() } + SessionPrefs.setGameStorage(app, library.path, "Card") + val external = File(library, "Games") + + SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_INTERNAL) + assertEquals(StoreInstallRoot.internalRoot(app).absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath) + + SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL) + assertEquals(external.absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath) + + SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_ASK) + assertNull(StoreInstallRoot.defaultTarget(app)) + + SessionPrefs.setDefaultStorage(app, "bogus") + assertEquals(SessionPrefs.DEFAULT_STORAGE_ASK, SessionPrefs.defaultStorage(app)) + } + + @Test fun defaultExternalStorageFallsBackToTheInstallDialogWhenNoCardIsPresent() { + SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "") + SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL) + assertNull(StoreInstallRoot.defaultTarget(app)) + } + + @Test fun aChosenFolderIsUsedForDefaultExternalStorage() { + val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() } + assertNull(StoreInstallRoot.prepareDefaultFolder(app, folder)) + val root = File(folder, "Games") + assertTrue(root.isDirectory) + SessionPrefs.setDefaultStorageFolder(app, folder.path, "SSD") + SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL) + + assertEquals(root.absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath) + assertTrue(StoreInstallRoot.targets(app).any { it.root.absolutePath == root.absolutePath && it.folder }) + assertTrue(StoreInstallRoot.roots(app).any { it.absolutePath == root.absolutePath }) + assertTrue(StoreInstallRoot.externalRoots(app).any { it.first.absolutePath == root.absolutePath }) + assertFalse(File(root, ".droiddeck-write-probe").exists()) + } + + @Test fun aDisconnectedChosenFolderDoesNotFallBackToAnotherTarget() { + val card = File(app.filesDir, "card/steam").apply { mkdirs() } + SessionPrefs.setGameStorage(app, card.path, "Card") + val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() } + SessionPrefs.setDefaultStorageFolder(app, folder.path, "SSD") + SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL) + assertNotNull(StoreInstallRoot.defaultTarget(app)) + + assertTrue(folder.delete()) + assertNull(StoreInstallRoot.defaultTarget(app)) + assertEquals(File(card, "Games").absolutePath, StoreInstallRoot.detectedExternalTarget(app)?.root?.absolutePath) + } + + @Test fun filesOnAChosenFolderAreMappedIntoTheGuest() { + val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() } + SessionPrefs.setDefaultStorageFolder(app, folder.path, "SSD") + val game = File(folder, "Games/GOG/Test/game.exe").apply { + parentFile?.mkdirs() + writeText("MZ") + } + + val guest = StoreInstallRoot.externalGuestPath(app, game) + assertNotNull(guest) + assertTrue(guest!!.startsWith(StoreInstallRoot.GUEST_EXTERNAL + "/")) + assertTrue(guest.endsWith("/GOG/Test/game.exe")) + } + @Test fun theSteamLibraryFolderIsOfferedAsAnInstallTarget() { val library = File(app.filesDir, "Documents/Games").apply { mkdirs() } SessionPrefs.setGameStorage(app, library.path, "Games") diff --git a/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstallTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstallTest.kt new file mode 100644 index 0000000000..027a1db73b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstallTest.kt @@ -0,0 +1,87 @@ +package com.droiddeck.launcher.stores.battlenet + +import com.droiddeck.launcher.runtime.BattleNet +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.Store +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.nio.file.Files +import java.util.Locale + +class BattleNetInstallTest { + private val buildInfo = """ + Branch!STRING:0|Active!DEC:1|Build Key!HEX:16|CDN Key!HEX:16|Install Key!HEX:16|IM Size!DEC:4|Version!STRING:0|Product!STRING:0 + eu|0|11111111111111111111111111111111|db0583272ed15286569b5f24ce516876|||16.1.1.1|gryphon + us|1|e474008a3535d8ea978949a90d9873e6|db0583272ed15286569b5f24ce516876|||16.1.2.119725|gryphon + """.trimIndent() + + private val versions = """ + Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16 + ## seqn = 4048130 + us|f00d008a3535d8ea978949a90d9873e6|db0583272ed15286569b5f24ce516876||119800|16.1.3.119800|f6a454799d25791e5a37a7547d75ce49 + eu|e474008a3535d8ea978949a90d9873e6|db0583272ed15286569b5f24ce516876||119725|16.1.2.119725|f6a454799d25791e5a37a7547d75ce49 + """.trimIndent() + + @Test fun theActiveRowGivesTheRegionAndBuildOnDisk() { + assertEquals("us" to "e474008a3535d8ea978949a90d9873e6", BattleNetInstall.buildKey(buildInfo)) + assertNull(BattleNetInstall.buildKey("Branch!STRING:0|Active!DEC:1\n")) + assertNull(BattleNetInstall.buildKey("Branch!STRING:0|Active!DEC:1|Build Key!HEX:16\nus|1|not-a-key\n")) + } + + @Test fun theLiveBuildIsReadForTheSameRegion() { + assertEquals("f00d008a3535d8ea978949a90d9873e6", BattleNetInstall.latestBuild(versions, "us")) + assertEquals("e474008a3535d8ea978949a90d9873e6", BattleNetInstall.latestBuild(versions, "eu")) + assertNull(BattleNetInstall.latestBuild(versions, "kr")) + assertNull(BattleNetInstall.latestBuild("", "us")) + } + + @Test fun theDeviceLanguagePicksABlizzardLocale() { + assertEquals("enUS", BattleNetInstall.locale(Locale.US)) + assertEquals("enGB", BattleNetInstall.locale(Locale.UK)) + assertEquals("enUS", BattleNetInstall.locale(Locale("en", "AU"))) + assertEquals("deDE", BattleNetInstall.locale(Locale.GERMANY)) + assertEquals("ptBR", BattleNetInstall.locale(Locale("pt", "BR"))) + assertEquals("ptPT", BattleNetInstall.locale(Locale("pt", "PT"))) + assertEquals("zhTW", BattleNetInstall.locale(Locale.forLanguageTag("zh-Hant-HK"))) + assertEquals("zhCN", BattleNetInstall.locale(Locale.SIMPLIFIED_CHINESE)) + assertEquals("enUS", BattleNetInstall.locale(Locale("nl", "NL"))) + } + + @Test fun theCountryIsSentInBothForms() { + assertEquals("DEU" to "DE", BattleNetInstall.country(Locale.GERMANY)) + assertEquals("USA" to "US", BattleNetInstall.country(Locale("en"))) + } + + @Test fun everyStoreTitleWithAProductInstallsHeadless() { + val products = BattleNet.TITLES.mapNotNull { it.product } + assertTrue(products.all { Regex("[a-z0-9_]{1,32}").matches(it) }) + assertTrue(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "gryphon", "Warcraft Rumble", null))) + assertEquals("hsb", BattleNetInstall.product("hs_beta")) + assertEquals("d3", BattleNetInstall.product("diablo3_enus")) + assertFalse(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "d3cn", "Diablo III", null))) + assertFalse(BattleNetInstall.headless(CatalogItem(Store.EPIC, "gryphon", "Warcraft Rumble", null))) + } + + @Test fun aCheckThatCouldNotRunIsTriedAgainNextTime() { + val folder = Files.createTempDirectory("bnet").toFile() + try { + BattleNetInstall.check("gryphon", folder, false) + BattleNetInstall.checks.submit {}.get() + assertFalse(synchronized(BattleNetInstall.checkedAt) { "gryphon" in BattleNetInstall.checkedAt }) + } finally { + folder.deleteRecursively() + } + } + + @Test fun theAgentStatusPicksTheDownloadStep() { + assertEquals(BattleNetInstall.Step.PREPARING, BattleNetInstall.step(1008, 0, 0, 0)) + assertEquals(BattleNetInstall.Step.PREPARING, BattleNetInstall.step(1003, 500, 0, 0)) + assertEquals(BattleNetInstall.Step.DOWNLOADING, BattleNetInstall.step(1003, 500, 31405777, 6746574227)) + assertEquals(BattleNetInstall.Step.APPLYING, BattleNetInstall.step(1003, 500, 6746574227, 6746574227)) + assertEquals(BattleNetInstall.Step.APPLYING, BattleNetInstall.step(1003, 2000, 1, 9)) + assertEquals(BattleNetInstall.Step.APPLYING, BattleNetInstall.step(1004, 1000, 0, 0)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt new file mode 100644 index 0000000000..f1141a8715 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt @@ -0,0 +1,38 @@ +package com.droiddeck.launcher.stores.battlenet + +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 + +class BattleNetRequestTest { + @get:Rule val tmp = TemporaryFolder() + + @Test fun requestsLeftBeforeThePollAreAllKeptInOrder() { + val root = tmp.root + assertTrue(BattleNetClient.request(root, listOf("install-game", "wow"))) + assertTrue(BattleNetClient.request(root, listOf("install-game", "fenris"))) + assertTrue(BattleNetClient.request(root, listOf("launch", "OSI"))) + val names = root.list()!!.sorted() + assertEquals(3, names.size) + assertTrue(names.all { Regex("battlenet-request\\.\\d{20}").matches(it) }) + assertEquals(listOf("install-game\nwow\n", "install-game\nfenris\n", "launch\nOSI\n"), names.map { java.io.File(root, it).readText() }) + } + + @Test fun aLineBreakInAnArgumentIsRefused() { + assertFalse(BattleNetClient.request(tmp.root, listOf("launch", "OSI\nreboot"))) + assertEquals(0, tmp.root.list()!!.size) + } + + @Test fun aNewSessionClearsEveryLeftRequest() { + val root = tmp.root + BattleNetClient.request(root, listOf("launch", "WTCG")) + java.io.File(root, "battlenet-request").writeText("launch\nPro\n") + java.io.File(root, "battlenet-request.1.tmp").writeText("launch\nPro\n") + java.io.File(root, "battlenet-fex.request").writeText("x") + BattleNetClient.clearRequests(root) + assertEquals(listOf("battlenet-fex.request"), root.list()!!.toList()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BlizzardArtTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BlizzardArtTest.kt new file mode 100644 index 0000000000..415c6c7cfe --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BlizzardArtTest.kt @@ -0,0 +1,30 @@ +package com.droiddeck.launcher.stores.battlenet + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class BlizzardArtTest { + @Test fun theShopsKeyArtIsUsed() { + val page = """<meta property="og:image" content="https://blz-contentstack-images.akamaized.net/v3/assets/a/b/c/art.png">""" + assertEquals("https://blz-contentstack-images.akamaized.net/v3/assets/a/b/c/art.png", BlizzardArt.imageUrl(page)) + } + + @Test fun aVideoStillFallsBackToTheFirstThumbnailThatIsNotABundle() { + val page = """<meta property="og:image" content="https://img.youtube.com/vi/x/maxresdefault.jpg">""" + + """\"imageUrl\":\"//catalog.blzstatic.com//ff9/a-prod-thumb_bundle.jpg\",""" + + """\"imageUrl\":\"//catalog.blzstatic.com//feb/b-prod-thumb.jpg\"""" + assertEquals("https://catalog.blzstatic.com//feb/b-prod-thumb.jpg", BlizzardArt.imageUrl(page)) + } + + @Test fun anOpenGraphImageFromAnotherHostFallsBackToTheThumbnail() { + val page = """<meta property="og:image" content="https://example.com/art.png">""" + + """\"imageUrl\":\"//catalog.blzstatic.com//feb/b-prod-thumb.jpg\"""" + assertEquals("https://catalog.blzstatic.com//feb/b-prod-thumb.jpg", BlizzardArt.imageUrl(page)) + } + + @Test fun artFromOtherHostsIsRefused() { + assertNull(BlizzardArt.imageUrl("""<meta property="og:image" content="https://example.com/art.png">""")) + assertNull(BlizzardArt.imageUrl("""\"imageUrl\":\"//catalog.blzstatic.com//ff9/a-prod-thumb_bundle.jpg\"""")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicClientTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicClientTest.kt index f5ba463843..60df152e05 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicClientTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicClientTest.kt @@ -456,4 +456,26 @@ class EpicClientTest { settings.writeText("""{"defaultInstallDir":"/mnt/droiddeck-sd/Stores/Epic"}""") assertEquals("/root/Games/Stores/Epic", EpicClient.prepareInstallDir(context)) } + + @Test fun aDisconnectedDefaultFolderKeepsTheLauncherInstallDir() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val previousStorage = com.droiddeck.launcher.session.SessionPrefs.defaultStorage(context) + val previousFolder = com.droiddeck.launcher.session.SessionPrefs.defaultStorageFolder(context) + val previousLabel = com.droiddeck.launcher.session.SessionPrefs.defaultStorageFolderLabel(context) + val settings = File(EpicClient.dataDir(context), "settings/app-settings.json").apply { parentFile!!.mkdirs() } + val current = "/mnt/droiddeck-stores/1234/Epic" + settings.writeText("""{"defaultInstallDir":"$current"}""") + com.droiddeck.launcher.session.SessionPrefs.setDefaultStorage( + context, com.droiddeck.launcher.session.SessionPrefs.DEFAULT_STORAGE_EXTERNAL) + com.droiddeck.launcher.session.SessionPrefs.setDefaultStorageFolder( + context, File(context.filesDir, "missing-${System.nanoTime()}").path, "SSD") + try { + assertEquals(current, EpicClient.prepareInstallDir(context)) + assertEquals(current, org.json.JSONObject(settings.readText()).getString("defaultInstallDir")) + } finally { + com.droiddeck.launcher.session.SessionPrefs.setDefaultStorage(context, previousStorage) + if (previousFolder.isBlank()) com.droiddeck.launcher.session.SessionPrefs.clearDefaultStorageFolder(context) + else com.droiddeck.launcher.session.SessionPrefs.setDefaultStorageFolder(context, previousFolder, previousLabel) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gog/GogInstallerPartsTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogInstallerPartsTest.kt new file mode 100644 index 0000000000..e60775b0e3 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogInstallerPartsTest.kt @@ -0,0 +1,90 @@ +package com.droiddeck.launcher.stores.gog + +import java.io.File +import java.io.IOException +import java.nio.file.Files +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +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 GogInstallerPartsTest { + private fun downloads(json: String) = JSONObject("""{"downloads":$json}""").getJSONObject("downloads") + + @Test fun everyFileOfTheWindowsInstallerIsKeptAndThePartsAreNamedAfterItsSetup() { + val parts = GogDownloadManager.installerParts( + downloads( + """{"installers":[ + {"os":"windows","language":"en","files":[ + {"id":"en1installer0","size":1048576,"downlink":"https://api.gog.com/products/1947927225/downlink/installer/en1installer0"}, + {"id":"en1installer1","size":3786407936,"downlink":"https://api.gog.com/products/1947927225/downlink/installer/en1installer1"} + ]}, + {"os":"linux","files":[{"downlink":"https://example.invalid/linux"}]} + ]}""", + ), + "1947927225", + ) + assertEquals(listOf("setup_1947927225.exe", "setup_1947927225-1.bin"), parts.map { it.filename }) + assertEquals(listOf(1048576L, 3786407936L), parts.map { it.size }) + assertTrue(parts[1].url.endsWith("en1installer1")) + } + + @Test fun explicitNamesAreKeptAndUnnamedPartsFollowTheFirstSetupExe() { + val parts = GogDownloadManager.installerParts( + downloads( + """{"installers":[{"os":"windows","files":[ + {"filename":"setup_witcher_2.1.0.exe","downlink":"https://example.invalid/setup"}, + {"downlink":"https://example.invalid/data"}, + {"filename":"readme.bin","downlink":"https://example.invalid/readme"} + ]}]}""", + ), + "1207658924", + ) + assertEquals(listOf("setup_witcher_2.1.0.exe", "setup_witcher_2.1.0-1.bin", "readme.bin"), parts.map { it.filename }) + } + + @Test fun aSingleManualInstallerIsNamedForTheGameAndSanitised() { + val parts = GogDownloadManager.installerParts( + downloads("""{"installers":[{"os":"windows","manualUrl":"https://example.invalid/setup","total_size":42}]}"""), + "../game id", + ) + assertEquals(1, parts.size) + assertEquals("setup_.._game_id.exe", parts[0].filename) + assertEquals(42L, parts[0].size) + } + + @Test fun installerPartsStayInsideTheGameFolder() { + val root = kotlin.io.path.createTempDirectory("gog-installer").toFile() + try { + assertEquals( + File(root, "setup_1.exe").canonicalFile, + GogDownloadManager.installerDestination(root, "setup_1.exe"), + ) + assertThrows(IOException::class.java) { + GogDownloadManager.installerDestination(root, "../outside.exe") + } + val outside = File(root.parentFile, "outside-${System.nanoTime()}.bin").apply { writeText("x") } + try { + Files.createSymbolicLink(File(root, "setup_1-1.bin").toPath(), outside.toPath()) + assertThrows(IOException::class.java) { + GogDownloadManager.installerDestination(root, "setup_1-1.bin") + } + } finally { + outside.delete() + } + } finally { + root.deleteRecursively() + } + } + + @Test fun anotherPlatformOrNoDownloadsAddsNothing() { + assertEquals(0, GogDownloadManager.installerParts(downloads("""{"installers":[{"os":"linux","manualUrl":"https://example.invalid/x"}]}"""), "1").size) + assertEquals(0, GogDownloadManager.installerParts(downloads("{}"), "1").size) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/itch/ItchCollectionsTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/itch/ItchCollectionsTest.kt new file mode 100644 index 0000000000..77fe2b2d71 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/itch/ItchCollectionsTest.kt @@ -0,0 +1,31 @@ +package com.droiddeck.launcher.stores.itch + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Test + +@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) +@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class) +class ItchCollectionsTest { + @Test fun collectionsKeepTheirIdTitleAndCount() { + val body = JSONArray() + .put(JSONObject().put("id", 8356509).put("title", "library").put("games_count", 12)) + .put(JSONObject().put("id", 7).put("title", "").put("games_count", 3)) + .put(JSONObject().put("title", "no id")) + val list = ItchCollections.parseCollections(body) + assertEquals(listOf("8356509"), list.map { it.id }) + assertEquals("library", list.single().title) + assertEquals(12, list.single().count) + } + + @Test fun collectionGamesReadBothKeyStylesAndSkipRowsWithoutAGame() { + val game = JSONObject().put("id", 99).put("title", "Celeste 64").put("url", "https://noel.itch.io/celeste64") + val snake = JSONObject().put("collection_games", JSONArray().put(JSONObject().put("game", game)).put(JSONObject().put("position", 1))) + val camel = JSONObject().put("collectionGames", JSONArray().put(JSONObject().put("game", game))) + assertEquals(listOf("noel.itch.io/celeste64"), ItchCollections.parseGames(snake).map { it.id }) + assertEquals(1, ItchCollections.parseGames(camel).size) + assertEquals(false, ItchCollections.parseGames(snake).single().owned) + assertEquals(0, ItchCollections.parseGames(JSONObject()).size) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/itch/ItchGameTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/itch/ItchGameTest.kt new file mode 100644 index 0000000000..1b7d8336f7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/itch/ItchGameTest.kt @@ -0,0 +1,66 @@ +package com.droiddeck.launcher.stores.itch + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) +@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class) +class ItchGameTest { + private fun upload(id: String, filename: String, vararg traits: String, type: String = "default", storage: String = "hosted", demo: Boolean = false, updated: String = "2026-09-16T02:26:06Z") = + JSONObject().put("id", id).put("filename", filename).put("size", 1000).put("type", type).put("storage", storage) + .put("demo", demo).put("traits", JSONArray(traits.toList())).put("updated_at", updated) + + @Test fun theGameNumberComesFromThePageMeta() { + assertEquals("1576684", ItchGame.idFromPage("""<head><meta name="itch:path" content="games/1576684"></head>""")) + assertEquals("1576684", ItchGame.idFromPage("""<meta content="games/1576684" name="itch:path">""")) + assertNull(ItchGame.idFromPage("<html>no meta here</html>")) + } + + @Test fun platformsComeFromTheTraits() { + assertEquals(setOf("windows"), ItchUploads.platforms(upload("1", "a.zip", "p_windows"))) + assertEquals(setOf("linux", "osx"), ItchUploads.platforms(upload("2", "a.zip", "p_linux", "p_osx"))) + assertEquals(setOf("android"), ItchUploads.platforms(upload("3", "a.apk", "p_android"))) + assertEquals(setOf("web"), ItchUploads.platforms(upload("4", "a.zip", type = "html"))) + } + + @Test fun anUploadWithNoPlatformIsTreatedAsWindows() { + assertEquals(setOf("windows"), ItchUploads.platforms(upload("5", "a.zip"))) + } + + @Test fun platformsAlsoReadTheFlagObject() { + val flags = JSONObject().put("windows", false).put("linux", true) + assertEquals(setOf("linux"), ItchUploads.platforms(JSONObject().put("platforms", flags))) + } + + @Test fun buildsSkipExternalUploadsAndPutWindowsFirst() { + val uploads = JSONArray() + .put(upload("10", "linux.tar.gz", "p_linux", updated = "2026-10-01T00:00:00Z")) + .put(upload("11", "win.zip", "p_windows", updated = "2026-09-01T00:00:00Z")) + .put(upload("12", "site", "p_windows", storage = "external")) + val builds = ItchGame.builds(uploads) + assertEquals(listOf("11", "10"), builds.map { it.uploadId }) + assertTrue(builds[0].installable) + assertFalse(builds[1].installable) + } + + @Test fun aDemoIsFlagged() { + assertTrue(ItchGame.builds(JSONArray().put(upload("20", "demo.zip", "p_windows", demo = true))).single().demo) + } + + @Test fun anUploadIsFoundById() { + val uploads = JSONArray().put(upload("30", "a.zip")).put(upload("31", "b.zip")) + assertEquals("b.zip", ItchUploads.byId(uploads, "31")?.optString("filename")) + assertNull(ItchUploads.byId(uploads, "99")) + assertNull(ItchUploads.byId(uploads, "")) + } + + @Test fun noDownloadKeyMeansNoKeyInTheAddress() { + assertEquals("https://api.itch.io/uploads/13619666/download", ItchApi.downloadUrl("13619666", "")) + assertEquals("https://api.itch.io/uploads/13619666/download?download_key_id=7", ItchApi.downloadUrl("13619666", "7")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/FexVersionTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/FexVersionTest.kt index 3d4600f8c1..0ee00d3ad4 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/FexVersionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/FexVersionTest.kt @@ -20,8 +20,8 @@ class FexVersionTest { } @Test fun theShippedLauncherHasOne() { - val script = java.io.File("../tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64").takeIf { it.isFile } - ?: java.io.File("tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64") + val script = java.io.File("../tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update").takeIf { it.isFile } + ?: java.io.File("tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update") assertEquals(true, fexVersionOf(script.readText()) != null) } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/FocusGlideRenderingTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/FocusGlideRenderingTest.kt new file mode 100644 index 0000000000..8938e90938 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/FocusGlideRenderingTest.kt @@ -0,0 +1,121 @@ +package com.droiddeck.launcher.ui + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.view.View +import androidx.compose.foundation.background +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.RectangleShape +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.session.SessionPrefs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w960dp-h540dp-land") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class FocusGlideRenderingTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun largeJumpCollapsesIntoABallAndExpandsAtTheDestination() { + val context = RuntimeEnvironment.getApplication() + SessionPrefs.setAnimationsEnabled(context, true) + Motion.refresh(context) + compose.mainClock.autoAdvance = false + lateinit var view: View + val from = FocusRequester() + val to = FocusRequester() + compose.setContent { + view = LocalView.current + FocusGlideHost(Modifier.fillMaxSize().background(Color.Black)) { + Box(Modifier.offset(10.dp, 10.dp).size(80.dp, 40.dp).focusRequester(from) + .focusGlide(RectangleShape, Color.White).focusable()) + Box(Modifier.offset(650.dp, 400.dp).size(80.dp, 40.dp).focusRequester(to) + .focusGlide(RectangleShape, Color.White).focusable()) + } + } + fun ringBounds(): Rect = compose.runOnIdle { + val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) + view.draw(Canvas(bitmap)) + var left = view.width + var top = view.height + var right = 0 + var bottom = 0 + for (y in 0 until bitmap.height) for (x in 0 until bitmap.width) { + if (android.graphics.Color.red(bitmap.getPixel(x, y)) > 200) { + left = minOf(left, x); top = minOf(top, y) + right = maxOf(right, x + 1); bottom = maxOf(bottom, y + 1) + } + } + bitmap.recycle() + Rect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat()) + } + compose.runOnIdle { from.requestFocus() } + compose.mainClock.advanceTimeBy(1_000) + assertTrue(ringBounds().width > 60f) + compose.runOnIdle { to.requestFocus() } + compose.mainClock.advanceTimeBy(160) + val ball = ringBounds() + assertTrue("Ball bounds: $ball", ball.width in 8f..16f && ball.height in 8f..16f) + compose.mainClock.advanceTimeBy(1_500) + val landed = ringBounds() + assertTrue("Landed bounds: $landed", landed.width > 60f && landed.left > 600f) + } + + @Test fun hollowGlideKeepsItsOutlineWithoutTintingTheContent() { + val context = RuntimeEnvironment.getApplication() + SessionPrefs.setAnimationsEnabled(context, false) + Motion.refresh(context) + try { + lateinit var view: View + var bounds = Rect.Zero + var hollow by mutableStateOf(true) + compose.setContent { + view = LocalView.current + FocusGlideHost { + Box(Modifier.size(120.dp).background(Color.Black) + .glideBorder(true, RectangleShape, Color.White, hotFillAlpha = if (hollow) 0f else 0.14f) + .onGloballyPositioned { bounds = it.boundsInRoot() }) + } + } + fun sample(): Pair<Int, Int> = compose.runOnIdle { + val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) + view.draw(Canvas(bitmap)) + val center = bitmap.getPixel(bounds.center.x.toInt(), bounds.center.y.toInt()) + val edge = bitmap.getPixel(bounds.left.toInt(), bounds.center.y.toInt()) + bitmap.recycle() + center to edge + } + val (center, edge) = sample() + assertEquals(android.graphics.Color.BLACK, center) + assertEquals(android.graphics.Color.WHITE, edge) + compose.runOnIdle { hollow = false } + assertTrue(android.graphics.Color.red(sample().first) > 0) + } finally { + SessionPrefs.setAnimationsEnabled(context, true) + Motion.refresh(context) + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/FocusGlideWindowsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/FocusGlideWindowsTest.kt new file mode 100644 index 0000000000..66c741eb1e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/FocusGlideWindowsTest.kt @@ -0,0 +1,152 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Slider +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalView +import com.droiddeck.launcher.stores.xbox.XboxMenuEntry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w960dp-h540dp-land") +class FocusGlideWindowsTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun standaloneThemedControlsShareTheGlide() { + lateinit var glide: FocusGlide + val focus = List(6) { FocusRequester() } + compose.setContent { + DroidDeckTheme { + glide = LocalFocusGlide.current!! + Column { + TextButton(onClick = {}, modifier = Modifier.focusRequester(focus[0]).focusGlide()) { Text("Action") } + IconButton(onClick = {}, modifier = Modifier.focusRequester(focus[1]).focusGlide()) { Text("Icon") } + Switch(false, {}, modifier = Modifier.focusRequester(focus[2]).focusGlide()) + Slider(0.5f, {}, modifier = Modifier.focusRequester(focus[3]).focusGlide()) + OutlinedTextField("Value", {}, modifier = Modifier.focusRequester(focus[4]).focusGlide()) + XboxMenuEntry("Xbox action", null, focus = focus[5], onClick = {}) + } + } + } + var previous: GlideSource? = null + for (requester in focus) { + compose.runOnIdle { requester.requestFocus() } + compose.runOnIdle { + val source = glide.current + assertNotNull(source) + assertNotSame(previous, source) + assertEquals(1, glide.hot.size) + assertNotNull(glide.boundsOf(source!!)) + previous = source + } + } + } + + @Test fun alertDialogButtonsShareTheirOwnWindowGlide() { + lateinit var parent: FocusGlide + lateinit var dialog: FocusGlide + val focus = List(2) { FocusRequester() } + compose.setContent { + DroidDeckTheme { + parent = LocalFocusGlide.current!! + GlideAlertDialog( + onDismissRequest = {}, + title = { Text("Dialog") }, + confirmButton = { + dialog = LocalFocusGlide.current!! + val view = LocalView.current + SideEffect { assertSame(view, dialog.view) } + TextButton(onClick = {}, modifier = Modifier.focusRequester(focus[0]).focusGlide()) { Text("Confirm") } + }, + dismissButton = { + TextButton(onClick = {}, modifier = Modifier.focusRequester(focus[1]).focusGlide()) { Text("Cancel") } + }, + ) + } + } + assertNotSame(parent, dialog) + assertWindowHandoff(dialog, focus) + } + + @Test fun customDialogsHaveAHostInsideTheirWindow() { + lateinit var parent: FocusGlide + lateinit var dialog: FocusGlide + val focus = List(2) { FocusRequester() } + compose.setContent { + DroidDeckTheme { + parent = LocalFocusGlide.current!! + GlideDialog(onDismissRequest = {}) { + dialog = LocalFocusGlide.current!! + Column { + SecondaryButton("First", modifier = Modifier.focusRequester(focus[0])) {} + SecondaryButton("Second", modifier = Modifier.focusRequester(focus[1])) {} + } + } + } + } + assertNotSame(parent, dialog) + assertWindowHandoff(dialog, focus) + } + + @Test fun dropdownItemsShareTheirOwnWindowGlide() { + lateinit var parent: FocusGlide + lateinit var menu: FocusGlide + val focus = List(2) { FocusRequester() } + var expanded by mutableStateOf(true) + compose.setContent { + DroidDeckTheme { + parent = LocalFocusGlide.current!! + GlideDropdownMenu(expanded = expanded, onDismissRequest = {}) { + menu = LocalFocusGlide.current!! + for (i in focus.indices) DropdownMenuItem( + text = { Text("Item $i") }, onClick = {}, + modifier = Modifier.focusRequester(focus[i]).focusGlide(), + ) + } + } + } + assertNotSame(parent, menu) + assertWindowHandoff(menu, focus) + compose.runOnIdle { expanded = false } + compose.waitForIdle() + compose.runOnIdle { expanded = true } + compose.waitForIdle() + assertWindowHandoff(menu, focus) + } + + private fun assertWindowHandoff(glide: FocusGlide, focus: List<FocusRequester>) { + var previous: GlideSource? = null + for (requester in focus) { + compose.runOnIdle { requester.requestFocus() } + compose.runOnIdle { + assertNotNull(glide.host) + val current = glide.current + assertNotNull(current) + assertNotSame(previous, current) + assertTrue(glide.boundsOf(current!!)!!.width > 0f) + previous = current + } + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GameResourcesRowTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GameResourcesRowTest.kt new file mode 100644 index 0000000000..5793b394fa --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/GameResourcesRowTest.kt @@ -0,0 +1,63 @@ +package com.droiddeck.launcher.ui + +import android.content.Intent +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.input.InputModeManager +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsFocused +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.test.requestFocus +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.Library +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@OptIn(androidx.compose.ui.test.ExperimentalTestApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class) +class GameResourcesRowTest { + @get:Rule val compose = createRobolectricComposeRule() + private val ctx get() = RuntimeEnvironment.getApplication() + private val game = Library.SteamGame(292030, "The Witcher 3", null, "/steam") + + @Test fun everyResourceIsReachableOnANarrowPageAndOpensTheExpectedBrowserUrl() { + compose.setContent { DroidDeckTheme { GameResourcesRow(game.name, game) } } + for (link in gameResources(game.name, game)) { + compose.onNodeWithText(ctx.getString(link.label)).assertIsDisplayed().performClick() + val intent = shadowOf(ctx).nextStartedActivity + assertEquals(Intent.ACTION_VIEW, intent.action) + assertEquals(link.url, intent.dataString) + } + } + + @Test fun controllerCanMoveBetweenLinksAndOpenAResource() { + lateinit var inputMode: InputModeManager + compose.setContent { DroidDeckTheme { + inputMode = LocalInputModeManager.current + GameResourcesRow(game.name, game) + } } + compose.runOnIdle { inputMode.requestInputMode(InputMode.Keyboard) } + compose.onNodeWithText(ctx.getString(R.string.game_resource_pcgw)).requestFocus().assertIsFocused().performKeyInput { pressKey(Key.DirectionRight) } + compose.onNodeWithText(ctx.getString(R.string.game_resource_guides)).assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } + assertEquals(gameResources(game.name, game)[1].url, shadowOf(ctx).nextStartedActivity.dataString) + } + + @Test @Config(qualifiers = "w640dp-h360dp-land") + fun shortLandscapeWindowsKeepEveryResourceVisible() { + compose.setContent { DroidDeckTheme { GameResourcesRow(game.name, game) } } + for (link in gameResources(game.name, game)) { + compose.onNodeWithText(ctx.getString(link.label)).assertIsDisplayed() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GameResourcesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GameResourcesTest.kt new file mode 100644 index 0000000000..3fd423e595 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/GameResourcesTest.kt @@ -0,0 +1,43 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.Library +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.net.URI +import java.net.URLDecoder + +class GameResourcesTest { + @Test fun searchesPreserveUnicodeAndEscapeQueryDelimiters() { + val title = "Ōkami HD & friends + 100% #1?" + val links = gameResources(" $title ", null) + assertEquals(3, links.size) + links.forEach { link -> + val uri = URI(link.url) + assertEquals("https", uri.scheme) + assertEquals(null, uri.fragment) + assertEquals(title, URLDecoder.decode(uri.rawQuery.substringAfter('='), "UTF-8")) + } + } + + @Test fun onlySteamClientGamesGetAppSpecificSteamResources() { + val steam = Library.SteamGame(292030, "The Witcher 3", null, "/steam") + val links = gameResources(steam.name, steam) + assertEquals("https://www.protondb.com/app/292030", links.single { it.label == R.string.game_resource_protondb }.url) + assertEquals("https://store.steampowered.com/account/remotestorageapp/?appid=292030", links.single { it.label == R.string.game_resource_steam_cloud }.url) + val others = listOf( + Library.SteamGame(292030, steam.name, null, Library.ADDED), + Library.SteamGame(292030, steam.name, null, Library.ADDED, source = "gog", storeId = "292030"), + Library.SteamGame(292030, steam.name, null, Library.XBOX_CLOUD, source = "xbox"), + Library.SteamGame(-1, steam.name, null, "/steam"), + ) + others.forEach { game -> + assertEquals(3, gameResources(game.name, game).size) + } + } + + @Test fun loadingPagesHaveNoResourcesUntilTheyHaveATitle() { + assertTrue(gameResources(" ", null).isEmpty()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt index e60f12f444..06f4dedfd7 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt @@ -13,6 +13,9 @@ class GamepadGeometryTest { } private val panels = listOf( + Panel("Thor portrait", 1080, 1920, 369 / 160f), + Panel("720p phone portrait", 720, 1280, 2f), + Panel("Phone portrait", 1080, 2400, 2.75f), Panel("Fold 8 upright", 1848, 2448, 2.625f), Panel("Fold 8 as a tablet", 2448, 1848, 2.625f), Panel("Pixel Fold upright", 1840, 2208, 2.625f), @@ -26,10 +29,15 @@ class GamepadGeometryTest { private fun boxes(panel: Panel) = GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density) + private val grips = setOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4) + private val portraitPanels get() = panels.take(3) + Panel("312dp phone portrait", 720, 1280, 369 / 160f) + private fun portraitBoxes(panel: Panel) = + GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, portraitDock = true) + @Test fun everyControlIsPlacedAndPanelsOnlyWhenUpright() { for (panel in panels) { val upright = panel.height > panel.width - val expected = Slot.values().toSet() - if (upright) emptySet() else setOf(Slot.PANELS) + val expected = Slot.values().toSet() - grips - if (upright) emptySet() else setOf(Slot.PANELS) assertEquals(panel.name, expected, boxes(panel).keys) } } @@ -81,4 +89,56 @@ class GamepadGeometryTest { assertTrue(panel.name, before(Slot.STEAM, Slot.QAM)) } } + + @Test fun portraitDockPlacesAllControlsWithinThePanel() { + for (panel in portraitPanels) { + val b = portraitBoxes(panel) + assertEquals(panel.name, Slot.values().toSet(), b.keys) + for ((slot, box) in b) { + val where = "${panel.name}: $slot $box" + assertTrue(where, box.left >= 0f && box.top >= 0f) + assertTrue(where, box.right <= panel.width && box.bottom <= panel.controlsHeight) + assertTrue(where, box.width >= 44 * panel.density - 1 && box.height >= 44 * panel.density - 1) + } + } + } + + @Test fun portraitDockControlsDoNotOverlap() { + for (panel in portraitPanels) { + val placed = portraitBoxes(panel).entries.toList() + for (i in placed.indices) for (j in i + 1 until placed.size) { + assertFalse("${panel.name}: ${placed[i].key} overlaps ${placed[j].key}", + placed[i].value.overlaps(placed[j].value)) + } + } + } + + @Test fun portraitDockUsesMoreSpaceForTheThumbSurfaces() { + for (panel in portraitPanels) { + val old = boxes(panel) + val b = portraitBoxes(panel) + for (slot in listOf(Slot.LEFT_MAIN, Slot.RIGHT_MAIN, Slot.LEFT_SECOND, Slot.RIGHT_SECOND)) { + assertTrue("${panel.name}: $slot", b.getValue(slot).width >= old.getValue(slot).width * 1.2f) + } + assertEquals(panel.name, b.getValue(Slot.LEFT_MAIN).cx, b.getValue(Slot.LEFT_SECOND).cx, 0.5f) + assertEquals(panel.name, panel.width - b.getValue(Slot.LEFT_MAIN).cx, b.getValue(Slot.RIGHT_MAIN).cx, 0.5f) + } + } + + @Test fun portraitDockMovesUtilitiesAndGripsAboveTheGamepad() { + for (panel in portraitPanels) { + val b = portraitBoxes(panel) + assertEquals(panel.name, 8 * panel.density, b.getValue(Slot.VIEW).top, 0.5f) + assertTrue(panel.name, b.getValue(Slot.MENU).bottom < b.getValue(Slot.L4).top) + assertTrue(panel.name, b.getValue(Slot.L4).bottom < b.getValue(Slot.LEFT_OUTER_SHOULDER).top) + assertTrue(panel.name, b.getValue(Slot.LEFT_OUTER_SHOULDER).bottom < b.getValue(Slot.LEFT_SECOND).top) + } + } + + @Test fun shortPanelsKeepTheExistingLayoutEvenWhenPortraitDockIsRequested() { + for ((width, height, density) in listOf(Triple(1920f, 1080f, 2f), Triple(720f, 600f, 2.3f))) { + assertEquals(GamepadGeometry.layout(width, height, density), + GamepadGeometry.layout(width, height, density, portraitDock = true)) + } + } } 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 b64986a1e4..62c90ce94a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt @@ -144,7 +144,7 @@ class GlobalGlassesSettingsTest { onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> }, - ), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}) + ), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {}) } } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt index 65a3a72b0a..d703d09bec 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt @@ -3,6 +3,7 @@ package com.droiddeck.launcher.ui import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -36,11 +37,56 @@ class LibraryEntriesTest { assertTrue(entries.single().installed) } + @Test fun aSavedCloudGameStaysNotInstalledAndKeepsItsLicenseFilters() { + val game = Library.SteamGame(-20, "Cloud game", null, Library.XBOX_CLOUD, source = "xbox", storeId = "cloud") + val product = owned(Store.XBOX, "cloud").copy(subscription = true, extra = mapOf("cloud" to "1")) + val entries = libraryEntries(listOf(game), mapOf(Store.XBOX to listOf(product)), emptySet()) + val entry = entries.single() + assertFalse(entry.installed) + for (filter in XboxLibraryFilter.ALL_FILTERS) assertTrue(filter, keepsXbox(filter, entry)) + assertEquals(listOf("local", entry.key), installedFirst(listOf(entry, LibraryEntry("local", "steam", "Local", null, null, true))).map { it.key }) + } + + @Test fun anInstalledPcCopyTakesPrecedenceOverTheSavedCloudRow() { + val local = Library.SteamGame(-5, "PC game", null, Library.ADDED, source = "xbox", storeId = "same") + val cloud = Library.SteamGame(-20, "PC game", null, Library.XBOX_CLOUD, source = "xbox", storeId = "same") + val entries = libraryEntries(listOf(cloud, local), mapOf(Store.XBOX to listOf(owned(Store.XBOX, "same"))), setOf("xbox:same")) + assertEquals(1, entries.size) + assertEquals(local, entries.single().game) + assertTrue(entries.single().installed) + } + + @Test fun aSavedCloudGameWithoutACatalogStillAppearsInTheCloudFilter() { + val cloud = Library.SteamGame(-20, "Cloud game", null, Library.XBOX_CLOUD, source = "xbox", storeId = "cloud") + val entry = libraryEntries(listOf(cloud), emptyMap(), emptySet()).single() + assertFalse(entry.installed) + assertTrue(keepsXbox(XboxLibraryFilter.CLOUD, entry)) + assertFalse(keepsXbox(XboxLibraryFilter.OWNED, entry)) + } + + @Test fun distinctLocalShortcutsForTheSameProductArePreserved() { + val first = Library.SteamGame(-5, "First install", null, Library.ADDED, source = "xbox", storeId = "same") + val second = Library.SteamGame(-6, "Second install", null, Library.ADDED, source = "xbox", storeId = "same") + val cloud = Library.SteamGame(-20, "Cloud game", null, Library.XBOX_CLOUD, source = "xbox", storeId = "same") + val entries = libraryEntries(listOf(cloud, first, second), mapOf(Store.XBOX to listOf(owned(Store.XBOX, "same"))), setOf("xbox:same")) + assertEquals(listOf(first, second), entries.map { it.game }) + } + @Test fun installedGamesComeFirstKeepingTheirSortedOrder() { val entries = listOf("a", "b", "c", "d").map { LibraryEntry(it, "steam", it, null, null, installed = it == "b" || it == "d") } assertEquals(listOf("b", "d", "a", "c"), installedFirst(entries).map { it.key }) } + @Test fun librarySourcesFollowTheConfiguredStoreOrderWithSteamFirstAndAddedLast() { + val entries = listOf("added", "gog", "steam", "epic", "xbox").map { LibraryEntry(it, it, it, null, null, true) } + assertEquals(listOf("steam", "xbox", "epic", "gog", "added"), librarySources(entries, listOf("xbox", "epic", "gog"))) + } + + @Test fun librarySourcesIgnoreUnknownAndDuplicateOrderEntriesAndAppendNewStores() { + val entries = listOf("epic", "gog", "battlenet").map { LibraryEntry(it, it, it, null, null, false) } + assertEquals(listOf("epic", "gog", "battlenet"), librarySources(entries, listOf("missing", "epic", "epic", "amazon"))) + } + @Test fun gameKeysNameEitherAnAppOrAStoreProduct() { GameRef.parse("app:440").let { assertEquals(440, it.appId); assertNull(it.store) } GameRef.parse("app:-12").let { assertEquals(-12, it.appId) } @@ -48,4 +94,23 @@ class LibraryEntriesTest { GameRef.parse("xbox:9NBLGGH4R315").let { assertEquals(Store.XBOX, it.store); assertEquals("9NBLGGH4R315", it.storeId) } GameRef.parse("app:nope:1").let { assertNull(it.store); assertNull(it.appId) } } + + @Test fun aCollectionKeepsItsInstalledGamesAndListsTheRestAsNotInstalled() { + val games = listOf( + Library.SteamGame(440, "Team Fortress 2", null, "Steam library"), + Library.SteamGame(-5, "Celeste", null, Library.ADDED, source = "itch", storeId = "a/celeste"), + Library.SteamGame(-6, "Other", null, Library.ADDED, source = "itch", storeId = "a/other"), + ) + val library = mapOf(Store.ITCH to listOf(owned(Store.ITCH, "a/celeste"), owned(Store.ITCH, "a/other"), owned(Store.ITCH, "b/owned"))) + val all = libraryEntries(games, library, setOf("itch:a/celeste", "itch:a/other")) + val collection = listOf(owned(Store.ITCH, "a/celeste"), owned(Store.ITCH, "b/owned"), owned(Store.ITCH, "c/new")) + val out = collectionEntries(all, collection) + assertEquals(listOf("app:-5", "app:itch:b/owned", "app:itch:c/new"), out.map { it.key }) + assertEquals(listOf(true, false, false), out.map { it.installed }) + } + + @Test fun anEmptyCollectionHidesEveryGame() { + val all = libraryEntries(listOf(Library.SteamGame(440, "Team Fortress 2", null, "Steam library")), emptyMap(), emptySet()) + assertEquals(emptyList<String>(), collectionEntries(all, emptyList()).map { it.key }) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt new file mode 100644 index 0000000000..f6085e5126 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt @@ -0,0 +1,219 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.CredentialCipher +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreAccounts +import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import javax.crypto.spec.SecretKeySpec + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w1200dp-h752dp-land", application = android.app.Application::class) +class LibraryVisibilityTest { + @get:Rule val compose = createRobolectricComposeRule() + private val ctx get() = RuntimeEnvironment.getApplication() + private var generation by mutableIntStateOf(0) + + @Before fun prepare() { + StoreAccounts.keys = CredentialCipher.KeyProvider { SecretKeySpec(ByteArray(32) { 7 }, "AES") } + StoreAccounts.keystoreFailed = false + ctx.getSharedPreferences("session", 0).edit().clear().commit() + LibraryView.source = LIBRARY_ALL + LibraryView.query = "" + LibraryView.focusFirst = false + StoresState.library.clear() + StoresState.accounts.clear() + for (store in listOf(Store.GOG, Store.EPIC)) { + StoreAccounts.write(ctx, store, JSONObject().put("access_token", "test-only").put("display_name", "Library test")) + StoresState.accounts[store] = "Library test" + StoresState.library[store] = listOf(CatalogItem(store, "owned", "Uninstalled ${store.shortLabel}", null, owned = true, sizeBytes = 1024)) + } + } + + @After fun clear() { + Steps.drop() + XboxLibraryFilter.set(ctx, XboxLibraryFilter.ALL) + for (store in listOf(Store.GOG, Store.EPIC)) StoreAccounts.clear(ctx, store) + StoreAccounts.keys = CredentialCipher.Keystore + StoreAccounts.keystoreFailed = false + StoresState.library.clear() + StoresState.accounts.clear() + ctx.getSharedPreferences("session", 0).edit().clear().commit() + LibraryView.source = LIBRARY_ALL + LibraryView.query = "" + LibraryView.focusFirst = false + } + + @Test fun uninstalledGamesAreHiddenUntilSelectedInTheFilterAndTheChoiceSurvivesReopeningLibrary() { + show() + compose.onNodeWithText("Installed Steam game").assertExists() + compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() + chooseVisibility(true) + compose.onNodeWithText("Uninstalled GOG").assertExists() + assertTrue(SessionPrefs.libraryShowUninstalled(ctx)) + compose.runOnIdle { generation++; Snapshot.sendApplyNotifications() } + compose.mainClock.advanceTimeBy(2_000) + compose.onNodeWithText("Uninstalled GOG").assertExists() + chooseVisibility(false) + compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() + assertFalse(SessionPrefs.libraryShowUninstalled(ctx)) + } + + @Test fun theFilterExpandsBesideSortWithoutChangingTheSelectionOnOpen() { + show() + val filter = compose.onNodeWithContentDescription("Filter · Installed only") + val sort = compose.onNodeWithContentDescription("Sort") + assertTrue(filter.fetchSemanticsNode().boundsInRoot.right <= sort.fetchSemanticsNode().boundsInRoot.left) + filter.performClick() + compose.mainClock.advanceTimeBy(2_000) + compose.onNodeWithText("Installed only").assertIsDisplayed() + compose.onNodeWithText("All owned games").assertIsDisplayed() + compose.onAllNodesWithText("Filter").assertCountEquals(1) + compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() + assertFalse(SessionPrefs.libraryShowUninstalled(ctx)) + compose.runOnIdle { Steps.fold(); Snapshot.sendApplyNotifications() } + compose.mainClock.advanceTimeBy(1_000) + sort.performClick() + compose.mainClock.advanceTimeBy(2_000) + compose.onAllNodesWithText("Sort").assertCountEquals(1) + compose.onNodeWithText("Recently played").assertIsDisplayed() + } + + @Test fun theXboxAccessChoicesShareTheLibraryFilter() { + StoreAccounts.write(ctx, Store.XBOX, JSONObject().put("username", "Library test")) + StoresState.accounts[Store.XBOX] = "Library test" + StoresState.library[Store.XBOX] = listOf(CatalogItem(Store.XBOX, "owned", "Uninstalled Xbox", null, owned = true)) + LibraryView.source = Store.XBOX.id + try { + show() + compose.onNodeWithContentDescription("Filter · Installed only").performClick() + compose.mainClock.advanceTimeBy(2_000) + compose.onNodeWithText("Installed only").assertIsDisplayed() + compose.onNodeWithText("All owned games").assertIsDisplayed() + compose.onNodeWithText("Game Pass").assertIsDisplayed().performClick() + compose.mainClock.advanceTimeBy(1_000) + assertEquals(XboxLibraryFilter.GAME_PASS, XboxLibraryFilter.current) + assertFalse(SessionPrefs.libraryShowUninstalled(ctx)) + } finally { + StoreAccounts.clear(ctx, Store.XBOX) + } + } + + @Test fun aSearchWithOnlyUninstalledMatchesOffersToRevealThem() { + LibraryView.query = "Uninstalled GOG" + show() + compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() + compose.onNodeWithTag("library-browse-owned").performClick() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Uninstalled GOG").assertExists() + assertEquals("Uninstalled GOG", LibraryView.query) + } + + @Test fun aHiddenStoreRemainsReachableInLibraryInItsConfiguredOrder() { + SessionPrefs.setStoresTabOrder(ctx, listOf("epic", "gog")) + SessionPrefs.setStoresTabHidden(ctx, setOf("gog")) + show() + val steam = compose.onNodeWithTag("library-source-steam").fetchSemanticsNode().boundsInRoot.left + val epic = compose.onNodeWithTag("library-source-epic").fetchSemanticsNode().boundsInRoot.left + val gog = compose.onNodeWithTag("library-source-gog").fetchSemanticsNode().boundsInRoot.left + assertTrue(steam < epic && epic < gog) + compose.onNodeWithTag("library-source-gog").performClick() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithTag("library-browse-owned").assertIsDisplayed().performClick() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Uninstalled GOG").assertExists() + } + + @Test fun theStoresOwnedGamesLinkRevealsOwnedGamesDespiteTheSavedInstalledOnlyView() { + assertFalse(SessionPrefs.libraryShowUninstalled(ctx)) + LibraryView.showOwned(ctx, Store.GOG) + show() + compose.onNodeWithText("Uninstalled GOG").assertExists() + compose.onNodeWithText("Installed Steam game").assertDoesNotExist() + } + + @Test fun theStoresOwnedGamesLinkUpdatesALibraryPageThatIsStillComposed() { + LibraryView.source = Store.GOG.id + show() + compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() + compose.runOnIdle { LibraryView.showOwned(ctx, Store.GOG); Snapshot.sendApplyNotifications() } + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Uninstalled GOG").assertExists() + } + + private fun show() { + compose.mainClock.autoAdvance = false + compose.setContent { key(generation) { + DroidDeckTheme { + CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) { + FocusGlideHost { Box(Modifier.fillMaxSize()) { + LibraryPage(state(), actions(), "games", {}, Modifier.fillMaxSize()) + StepsLayer(Offset.Zero) + } } + } + } + } } + compose.mainClock.advanceTimeBy(2_000) + } + + private fun chooseVisibility(show: Boolean) { + compose.onNodeWithContentDescription("Filter · " + if (SessionPrefs.libraryShowUninstalled(ctx)) "All owned games" else "Installed only") + .performClick() + compose.mainClock.advanceTimeBy(2_000) + assertTrue(Steps.open) + compose.onNodeWithText(if (show) "All owned games" else "Installed only") + .performClick() + compose.mainClock.advanceTimeBy(1_000) + assertEquals(show, SessionPrefs.libraryShowUninstalled(ctx)) + } + + private fun state() = FrontEndState( + installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1, + desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "", + romsDir = null, logsEnabled = false, + steamGames = listOf(Library.SteamGame(440, "Installed Steam game", null, "internal")), + emulators = emptyList(), running = null, + ) + + private fun actions() = FrontEndActions( + onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, + onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, + 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/PortraitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt new file mode 100644 index 0000000000..e1210893f0 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt @@ -0,0 +1,137 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.* +import androidx.compose.ui.unit.dp +import org.junit.Assert.* +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w960dp-h900dp-mdpi") +class PortraitLayoutTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Before fun freezeAnimations() { + compose.mainClock.autoAdvance = false + Hops.railPreview = null + } + + @Test fun navigationSitsAtBottomAndRotatingPreservesContentState() { + val portrait = mutableStateOf(true) + compose.setContent { + DroidDeckTheme { + LauncherLayout(portrait.value, Color.Gray, + Modifier.size(if (portrait.value) 480.dp else 800.dp, if (portrait.value) 800.dp else 480.dp).testTag("launcher"), + navigation = { + if (portrait.value) BottomBar(state, "steam", {}, {}, actions, Modifier) + else SideRail(state, "steam", {}, {}, actions, Modifier.fillMaxHeight()) + }, + ) { + var count by remember { mutableIntStateOf(0) } + Box(Modifier.fillMaxSize().testTag("pane")) { + TextButton(onClick = { count++ }) { Text("Count $count") } + } + } + } + } + compose.mainClock.advanceTimeBy(1_000) + val root = compose.onNodeWithTag("launcher").getUnclippedBoundsInRoot() + val pane = compose.onNodeWithTag("pane").getUnclippedBoundsInRoot() + val steam = compose.onNodeWithTag("rail-steam").getUnclippedBoundsInRoot() + assertEquals(root.left, pane.left) + assertEquals(root.right, pane.right) + assertTrue(steam.top >= pane.bottom) + assertEquals(root.bottom - 4.dp, steam.bottom) + compose.onNodeWithText("Count 0").performClick() + compose.runOnIdle { portrait.value = false } + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Count 1").assertExists() + val landscapePane = compose.onNodeWithTag("pane").getUnclippedBoundsInRoot() + val rail = compose.onNodeWithTag("rail-steam").getUnclippedBoundsInRoot() + assertTrue(landscapePane.left > rail.right) + assertEquals(0.dp, landscapePane.top) + compose.runOnIdle { portrait.value = true } + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Count 1").assertExists() + } + + @Test fun narrowBottomBarScrollsToEveryDestinationWithAppsAndResumeVisible() { + val selected = mutableStateOf("steam") + compose.setContent { + DroidDeckTheme { + BottomBar(stateWithAppsAndSession, selected.value, { selected.value = it }, {}, actions, Modifier.size(320.dp, 64.dp)) + } + } + compose.mainClock.advanceTimeBy(1_000) + for (key in listOf("games", "stores", "desktop", "components", "android-apps", "setup", "updates", "steam")) { + compose.onNodeWithTag("rail-$key").performScrollTo() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithTag("rail-$key").assertIsDisplayed().performClick() + compose.mainClock.advanceTimeBy(1_000) + compose.runOnIdle { assertEquals(key, selected.value); assertNull(Hops.railPreview) } + compose.onNodeWithTag("rail-$key").assertIsSelected().assertHeightIsAtLeast(48.dp).assertWidthIsAtLeast(48.dp) + } + compose.onNodeWithContentDescription("Resume Steam").assertIsDisplayed() + } + + @Test fun compactHeaderKeepsAllActionsReachable() { + compose.setContent { + DroidDeckTheme { + CompositionLocalProvider(LocalNarrowPane provides true) { + Box(Modifier.size(320.dp, 240.dp)) { + ModeHeader("Library", "", {}, "Search library") { + for (label in listOf("Filter", "Sort", "View", "Frontend files", "Add game")) { + SecondaryButton(label) {} + } + } + } + } + } + } + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Add game").performScrollTo() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Add game").assertIsDisplayed() + compose.onNodeWithText("Filter").performScrollTo() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Filter").assertIsDisplayed() + } + + private fun state(home: Boolean = false, running: String? = null) = FrontEndState( + installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1, + desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "", + romsDir = null, logsEnabled = false, steamGames = emptyList(), emulators = emptyList(), running = running, + isHomeApp = home, + ) + private val state get() = state() + private val stateWithAppsAndSession get() = state(home = true, running = "Steam") + + private val actions = FrontEndActions( + onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, + onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, + onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, + onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, + onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, + ) +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonFocusContrastTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonFocusContrastTest.kt index 51da840cb2..f5c47bdfa4 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonFocusContrastTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonFocusContrastTest.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.layout.Column import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalView @@ -9,7 +10,9 @@ import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performSemanticsAction import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertSame import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -21,7 +24,7 @@ import org.robolectric.annotation.Config class PrimaryButtonFocusContrastTest { @get:Rule val compose = createRobolectricComposeRule() - @Test fun focusedPrimaryButtonDoesNotClaimAColorOverlayAboveItsLabel() { + @Test fun focusedPrimaryButtonClaimsTheGlideWithoutAColorOverlayAboveItsLabel() { lateinit var glide: FocusGlide var clicks = 0 compose.setContent { @@ -36,11 +39,51 @@ class PrimaryButtonFocusContrastTest { val button = compose.onNodeWithText("Play") button.performSemanticsAction(SemanticsActions.RequestFocus) button.assertIsFocused() - compose.runOnIdle { assertNull(glide.current) } + compose.runOnIdle { + assertNotNull(glide.current) + assertEquals(0f, glide.current!!.fillAlpha) + } button.performClick() compose.runOnIdle { assertEquals(1, clicks) - assertNull(glide.current) + assertNotNull(glide.current) + assertEquals(0f, glide.current!!.fillAlpha) + } + } + + @Test fun focusCanGlideIntoAndBackOutOfPrimaryButtons() { + lateinit var glide: FocusGlide + val focus = FrontFocus() + compose.setContent { + val view = LocalView.current + glide = remember(view) { FocusGlide(view) } + DroidDeckTheme { + CompositionLocalProvider(LocalFocusGlide provides glide, LocalFrontFocus provides focus) { + Column { + SecondaryButton("Tab") {} + PrimaryButton("Play Steam", main = true, large = true) {} + } + } + } + } + val tab = compose.onNodeWithText("Tab") + val play = compose.onNodeWithText("Play Steam") + tab.performSemanticsAction(SemanticsActions.RequestFocus) + tab.assertIsFocused() + val tabSource = compose.runOnIdle { glide.current!! } + compose.runOnIdle { focus.primary.requestFocus() } + play.assertIsFocused() + compose.runOnIdle { + assertNotNull(glide.current) + assertNotSame(tabSource, glide.current) + assertEquals(0f, glide.current!!.fillAlpha) + assertEquals(1, glide.hot.size) + } + tab.performSemanticsAction(SemanticsActions.RequestFocus) + tab.assertIsFocused() + compose.runOnIdle { + assertSame(tabSource, glide.current) + assertEquals(1, glide.hot.size) } } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt index 735632e61b..d4c5aa4b2b 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -98,6 +98,33 @@ class SessionSecondScreenTest { } } + @Test + @Config(sdk = [34], shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class]) + fun drawerShortcutsConsumeRepeatsAndReleasesAfterClosing() { + val device = InputDeviceBuilder.newBuilder().setId(43).setName("Drawer shortcut test pad") + .setDescriptor("drawer-shortcut-pad").setExternal(true).setSources(InputDevice.SOURCE_GAMEPAD).build() + shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device) + SessionState.mode = SessionService.MODE_STEAM + val activity = Robolectric.buildActivity(SessionActivity::class.java).get() + val open: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerOpen\$delegate") + val controller: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerControllerActive\$delegate") + controller.value = true + for (button in listOf(KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.KEYCODE_BUTTON_START)) { + fun event(action: Int, repeat: Int = 0) = KeyEvent(0L, 0L, action, button, repeat, 0, + device.id, 0, 0, InputDevice.SOURCE_GAMEPAD) + open.value = true + assertTrue(activity.dispatchKeyEvent(event(KeyEvent.ACTION_DOWN))) + assertEquals(false, open.value) + open.value = true + assertTrue(activity.dispatchKeyEvent(event(KeyEvent.ACTION_DOWN, 1))) + assertEquals(true, open.value) + open.value = false + assertTrue(activity.dispatchKeyEvent(event(KeyEvent.ACTION_UP))) + val held: Set<Pair<Int, Int>> = ReflectionHelpers.getField(activity, "drawerShortcutKeysDown") + assertTrue(held.isEmpty()) + } + } + @Test fun sessionMicrophoneCanBeTurnedOff() { val changes = mutableListOf<Boolean>() compose.setContent { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt new file mode 100644 index 0000000000..b11fbd2fe1 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt @@ -0,0 +1,93 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import com.droiddeck.launcher.core.SteamIntegration +import com.droiddeck.launcher.core.SteamIntegration.Feature +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], qualifiers = "w960dp-h540dp-land") +class SteamIntegrationGroupTest { + @get:Rule val compose = createRobolectricComposeRule() + private val state = mutableStateOf(SteamIntegration.State()) + private val requests = mutableListOf<Feature>() + private var appInfo = 0 + private var location = 0 + + private fun stateIs(value: String) = SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, value) + + private fun show() = compose.setContent { + DroidDeckTheme { + SteamIntegrationGroup(state.value, onFeature = { requests.add(it) }, onAppInfo = { appInfo++ }, onLocation = { location++ }) + } + } + + @Test fun everySwitchRequestsOnlyItsOwnFeature() { + state.value = SteamIntegration.State(home = true) + show() + 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) + } + + @Test fun switchesReflectAndroidGrants() { + state.value = SteamIntegration.State(brightness = true, home = true, shortcuts = true) + show() + 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() + } + + @Test fun shortcutsWaitForHome() { + show() + compose.onNodeWithTag("integration-action-shortcuts").assertIsNotEnabled() + compose.onNodeWithText("Needs DroidDeck as Home").assertExists() + compose.runOnIdle { state.value = state.value.copy(home = true) } + compose.onNodeWithTag("integration-action-shortcuts").assertIsEnabled() + } + + @Test fun restrictedShortcutsPointToAppInfo() { + state.value = SteamIntegration.State(home = true, shortcutsRestricted = true) + show() + compose.onNodeWithTag("integration-action-shortcuts").assertIsNotEnabled() + compose.onNodeWithText("App info").performClick() + assertEquals(1, appInfo) + compose.runOnIdle { state.value = state.value.copy(shortcutsRestricted = false) } + compose.onNodeWithText("App info").assertDoesNotExist() + compose.onNodeWithTag("integration-action-shortcuts").assertIsEnabled() + } + + @Test fun unconfirmedRestrictionOffersAppInfoAfterAnAttempt() { + state.value = SteamIntegration.State(home = true) + show() + compose.onNodeWithText("App info").assertDoesNotExist() + compose.runOnIdle { state.value = state.value.copy(shortcutsTried = true) } + compose.onNodeWithTag("integration-action-shortcuts").assertIsEnabled() + compose.onNodeWithText("App info").performClick() + assertEquals(1, appInfo) + } + + @Test fun deniedLocationPointsToAppInfoWithoutTogglingWifi() { + state.value = SteamIntegration.State(locationBlocked = true) + show() + compose.onNodeWithText("Location denied · allow it in App info").assertExists() + compose.onNodeWithText("App info").performClick() + assertEquals(1, location) + assertTrue(requests.isEmpty()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt new file mode 100644 index 0000000000..4f914f0b55 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt @@ -0,0 +1,151 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.Text +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.InstalledStoreGame +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreGameSidecar +import com.droiddeck.launcher.stores.StoreInstallRoot +import com.droiddeck.launcher.stores.StoreSizes +import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.download.DownloadEntry +import com.droiddeck.launcher.stores.download.DownloadState +import com.droiddeck.launcher.stores.xbox.XboxBackend +import com.droiddeck.launcher.stores.xbox.XboxContent +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w1200dp-h752dp-land", application = android.app.Application::class) +class StoreRestorationTest { + @get:Rule val compose = createRobolectricComposeRule() + private val ctx get() = RuntimeEnvironment.getApplication() + private val product = CatalogItem(Store.XBOX, "9NBLGGH4R315", "Test game", null, owned = true, sizeBytes = 10_485_760L, extra = mapOf("cloud" to "1")) + private val cloud = Library.SteamGame(-20, product.title, null, Library.XBOX_CLOUD, source = "xbox", storeId = product.id) + + @After fun clear() { + StoresState.publishDownloads(emptyList()) + StoresState.unfinished = emptyList() + StoreSizes.onDisk.clear() + XboxContent.dismiss() + } + + @Test fun manageContentReportsItsResultWithoutComposingTheStoresPage() { + val base = InstalledStoreGame(StoreGameSidecar(Store.XBOX, product.id, product.title, "game.exe"), File(ctx.cacheDir, "missing-xbox-manifest")) + compose.mainClock.autoAdvance = false + compose.setContent { + DroidDeckTheme { FrontEndScreen(state(), actions(), page = { Text("Library game page") }) } + } + compose.mainClock.advanceTimeBy(2_000) + compose.runOnIdle { XboxContent.manage(ctx, base) } + compose.waitUntil(5_000) { + shadowOf(android.os.Looper.getMainLooper()).idle() + XboxContent.plan != null + } + compose.mainClock.advanceTimeBy(100) + compose.onNodeWithText(ctx.getString(R.string.stores_xbox_content_title)).assertExists() + compose.onNodeWithText("Missing or ambiguous MicrosoftGame.config.").assertExists() + compose.onNodeWithText(ctx.getString(android.R.string.ok)).performClick() + compose.runOnIdle { assertNull(XboxContent.plan) } + } + + @Test fun packageChoicesRenderOutsideTheStoresPage() { + val choices = (1..24).map { JSONObject().put("title", "Package $it").put("kind", "Game") } + val pending = XboxBackend.PackageChoice(product, ctx.cacheDir, choices) + compose.setContent { DroidDeckTheme { XboxStoreDialogs(content = null, pending = pending) } } + compose.onNodeWithText(ctx.getString(R.string.stores_xbox_choose_content)).assertExists() + choices.forEach { compose.onNodeWithText(ctx.getString(R.string.stores_xbox_choice, it.getString("title"), "Game")).performScrollTo().assertIsDisplayed() } + compose.onNodeWithText(ctx.getString(android.R.string.cancel)).assertExists() + } + + @Test fun everyContentOfferCanBeReachedInALandscapeDialog() { + val base = InstalledStoreGame(StoreGameSidecar(Store.XBOX, product.id, product.title, "game.exe"), ctx.cacheDir) + val offers = (1..24).map { XboxContent.Offer(product.copy(id = "dlc-$it", title = "Content $it"), installed = false) } + val plan = XboxContent.Plan(base, offers) + compose.setContent { DroidDeckTheme { XboxStoreDialogs(content = plan, pending = null) } } + offers.forEach { compose.onNodeWithText(ctx.getString(R.string.stores_xbox_content_install, it.item.title)).performScrollTo().assertIsDisplayed() } + } + + @Test fun libraryCardsShowDownloadAndInstalledSizes() { + val owned = LibraryEntry("owned", "xbox", product.title, null, product, false) + val installed = LibraryEntry("installed", "xbox", product.title, null, product.copy(id = "installed"), true) + StoreSizes.onDisk["xbox:installed"] = 20_971_520L + compose.setContent { DroidDeckTheme { Column { + LibraryMarker(owned, null) + LibraryMarker(installed, null) + } } } + compose.onNodeWithText("10.0 MB").assertExists() + compose.onNodeWithText("20.0 MB").assertExists() + } + + @Test fun aSavedCloudGamesDownloadKeepsPauseResumeCancelAndFailureRecovery() { + val entry = DownloadEntry(Store.XBOX, product.id, product.title, state = DownloadState.RUNNING) + StoresState.publishDownloads(listOf(entry)) + compose.setContent { DroidDeckTheme { GameActions(Store.XBOX, product.id, cloud, product, null, state(), actions(), Modifier) } } + compose.onNodeWithText(ctx.getString(R.string.stores_dl_pause)).assertExists() + compose.onNodeWithText(ctx.getString(R.string.stores_dl_cancel)).assertExists() + compose.onNodeWithText(ctx.getString(R.string.game_stream)).assertExists() + compose.runOnIdle { StoresState.publishDownloads(listOf(entry.copy(state = DownloadState.PAUSED))) } + compose.onNodeWithText(ctx.getString(R.string.stores_dl_resume)).assertExists() + compose.onNodeWithText(ctx.getString(R.string.stores_dl_cancel)).assertExists() + compose.runOnIdle { StoresState.publishDownloads(listOf(entry.copy(state = DownloadState.FAILED))) } + compose.onNodeWithText(ctx.getString(R.string.stores_dl_resume)).assertExists() + compose.onNodeWithText(ctx.getString(R.string.stores_dl_clear)).assertExists() + compose.onNodeWithText(ctx.getString(R.string.game_stream)).assertExists() + } + + @Test fun aConsoleOnlyCloudGameDoesNotOfferAPcInstall() { + compose.setContent { DroidDeckTheme { GameActions(Store.XBOX, product.id, cloud, product.copy(sizeBytes = 0, extra = mapOf("pc" to "0", "cloud" to "1")), null, state(), actions(), Modifier) } } + compose.onNodeWithText(ctx.getString(R.string.game_stream)).assertExists() + compose.onNodeWithText(ctx.getString(R.string.stores_install)).assertDoesNotExist() + } + + @Test fun anInterruptedCloudDownloadCanBeClearedAfterItsLicenseOrPcMetadataChanges() { + StoresState.unfinished = listOf(StoreInstallRoot.Unfinished(Store.XBOX, product.id, File(ctx.cacheDir, "partial"))) + var item by mutableStateOf(product) + compose.setContent { DroidDeckTheme { GameActions(Store.XBOX, product.id, cloud, item, null, state(), actions(), Modifier) } } + compose.onNodeWithText(ctx.getString(R.string.stores_resume_install)).assertExists() + for (changed in listOf(product.copy(owned = false), product.copy(extra = mapOf("pc" to "0", "cloud" to "1")))) { + compose.runOnIdle { item = changed } + compose.onNodeWithText(ctx.getString(R.string.stores_dl_clear)).assertExists() + compose.onNodeWithText(ctx.getString(R.string.stores_resume_install)).assertDoesNotExist() + } + } + + private fun state() = FrontEndState( + installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1, + desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "", + romsDir = null, logsEnabled = false, steamGames = emptyList(), emulators = emptyList(), running = null, + pageKey = "test-game", navigate = "games", + ) + + private fun actions() = FrontEndActions( + onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, + onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, + onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, + onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, + onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, + ) +} diff --git a/docs/agent-control.md b/docs/agent-control.md index b3ec1c0736..5dc16253ed 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -113,6 +113,10 @@ tools/droiddeckctl env set DXVK_HUD=fps tools/droiddeckctl env list tools/droiddeckctl env clear [next|persistent|all] tools/droiddeckctl override gamescope ./gamescope +tools/droiddeckctl override libblfastpath.so ./libblfastpath.so +tools/droiddeckctl proot-profile enable --slow-us 1000 +tools/droiddeckctl proot-profile disable +tools/droiddeckctl proot-profile report ./session.log --sort wall tools/droiddeckctl prefs get session tools/droiddeckctl prefs set session some_key true --type bool @@ -367,3 +371,14 @@ sees it, and quits it: the test that catches a game left behind Steam's loading shows up in some fraction of launches. A game with a launcher of its own needs the launcher pressed through first, since the launcher window carries the game's app id too: `tools/scenarios/skyrim-launcher-focus.json` taps Skyrim's Play before checking. + +## PRoot performance experiments + +`proot-profile enable` queues handler profiling for the next session using the existing debugging +consent gate. Counters and bounded slow samples appear in `session.log`; `proot-profile report` +ranks a saved local log without ADB. This measures PRoot handler work, not full syscall latency. +`override libblfastpath.so FILE` selects a glibc ARM64 shared library in the next session's preload +list, reports its SHA-256, and refuses installation until the current session stops. It lasts for +one session; the next session stages the bundled library again. See +[the profiling workflow](development/proot-performance.md#finding-the-next-fast-path) for timing +boundaries, build commands, path diagnostics, and A/B validation. diff --git a/docs/development/dd-fg.md b/docs/development/dd-fg.md new file mode 100644 index 0000000000..81cb43a9ea --- /dev/null +++ b/docs/development/dd-fg.md @@ -0,0 +1,38 @@ +# DD-FG flow resources + +DD-FG keeps seven luminance pyramid levels for both input frames. Its performance +preset chooses the finest level at which optical flow is solved: + +| Preset | Finest solved level | Allocated flow levels | +|---|---:|---| +| 0 | 1 | 1 through 6 | +| 1 | 2 | 2 through 6 | +| 2 (the app default) | 3 | 3 through 6 | + +Only those solved levels need RGBA16F flow images, flow UBOs and flow descriptor +sets. The vectors keep their original level indices; unused entries are null. +The full luminance pyramids, full-resolution expanded flow images, regularization +and synthesis are unchanged. + +At the default preset this avoids three flow images, three uniform buffers and +three descriptor sets. The removed image payload is +`8 * (width * height + (width >> 1) * (height >> 1) + (width >> 2) * (height >> 2))` +bytes for dimensions at least four pixels: + +| Input size | Removed image payload | +|---|---:| +| 1280 x 720 | 9,676,800 bytes | +| 1920 x 1080 | 21,772,800 bytes | +| 2560 x 1440 | 38,707,200 bytes | + +These are pixel payloads, not driver allocation sizes or measured FPS gains. + +## Validation + +Run `python3 -m unittest discover -s tools/tests -p 'test_ddfg_flow_levels.py'`. +The host test needs a C++17 compiler and system Vulkan headers or an Android NDK +selected through the usual SDK/NDK environment variables. It compiles the actual +DD-FG chain against a mock Vulkan dispatch table and checks resource counts, +dispatch order and sizes, valid descriptor bindings, both models, every preset, +2x/3x/4x generation, small/odd extents, resize and live preset changes. +It does not execute shaders on a GPU or replace on-device validation. diff --git a/docs/development/focus-glide.md b/docs/development/focus-glide.md new file mode 100644 index 0000000000..e84027a8a0 --- /dev/null +++ b/docs/development/focus-glide.md @@ -0,0 +1,27 @@ +# Focus transitions + +Focusable app controls participate in the shared focus glide. Nearby moves stretch +the outline; jumps over 360 dp collapse it into a ball before expanding at the +destination. Rapid repeats keep the faster outline movement. Disabling animations +places the outline directly at the focused control. + +`DroidDeckTheme` supplies the host for standalone Compose interfaces. Custom +controls use `glideBorder` with their focus interaction state. Material controls +use `Modifier.focusGlide(shape)` before their focus target. Match the control's +shape, and keep existing selection borders separate from the focus outline. +Filled primary buttons use `hotFillAlpha = 0f` to preserve label contrast. + +Use `GlideDialog`, `GlideAlertDialog`, `GlidePopup`, and `GlideDropdownMenu` for app +windows. Android dialogs and popups have separate views and coordinate spaces; +they need their own host. The wrappers preserve the underlying Material layouts +and keep all controls in each window on the same animation. Dropdown hosts also +handle recreation of the popup view after closing. + +Touch dismiss backdrops and controller shortcut hints should have +`canFocus = false`. Controls with a larger touch target can register the visible +shape separately, as the toggle switch and pause/resume orb do. Web content, +Android system UI, and native game input surfaces retain their own focus behavior. + +`FocusGlideWindowsTest` checks Material controls, Xbox menu entries, dialog focus +handoffs, and dropdown reopening. `FocusGlideRenderingTest` checks the large-jump +ball animation and outline-only rendering with animations disabled. diff --git a/docs/development/game-environment.md b/docs/development/game-environment.md index 62530ca48d..bebd67ce66 100644 --- a/docs/development/game-environment.md +++ b/docs/development/game-environment.md @@ -98,7 +98,7 @@ custom components can support a different set of options. Android Wine wrapper, ALSA-server, Box64 and patched async-DXVK options are identified in the editor as requiring a different/custom component; custom entries remain allowed. The old `DXVK_FRAME_RATE` environment variable was removed from current DXVK, so it is -not offered as a suggestion. Prefer the session frame limiter for ordinary play. +not offered as a suggestion. Prefer Steam's Quick Access menu frame limiter for ordinary play. ## Launch path and references diff --git a/docs/development/itch-collections.md b/docs/development/itch-collections.md new file mode 100644 index 0000000000..9a2f1419aa --- /dev/null +++ b/docs/development/itch-collections.md @@ -0,0 +1,26 @@ +# itch.io collections + +On the Library's itch tab a Collections button in the header lists the collections of the signed-in +itch account. Picking one hides every game that is not in it; the games of the collection that are not +installed show in the existing "Not installed" section, and All brings the full library back. The button +exists only while the itch chip is selected. + +## Data + +`ItchCollections` (`stores/itch/ItchCollections.kt`) asks itch with the account's API key: + +``` +GET /profile/collections -> collections[{id, title, games_count}] +GET /collections/<id>/collection-games?page=N -> collection_games[{game{...}}] +``` + +Pages are read until one comes back empty. Each game goes through `ItchLibrary.item`, the reader the +library and shelves share, so it looks the same everywhere. The selection and the loaded games live in +memory; the list is asked again whenever the itch tab opens. Counts are logged +(`itch.io: <n> collections`, `itch.io: collection <id> has <n> games`). + +## Filtering + +`collectionEntries` keeps the itch entries whose store key is in the collection, then adds the +collection games the library has no entry for as not installed ones. Their game page resolves through +`StoresState.detailItem`, which also looks at the collection games. diff --git a/docs/development/itch-install.md b/docs/development/itch-install.md new file mode 100644 index 0000000000..3db9fde5d4 --- /dev/null +++ b/docs/development/itch-install.md @@ -0,0 +1,21 @@ +# itch.io install and version picker + +Installing an itch.io game opens a version picker first. It lists the game's uploads from `/games/{id}/uploads`, with the platform, size and date of each. + +- Windows builds install. A game with a single Windows build skips the picker and installs at once. +- Other builds (macOS, Android, web) open the game's page on itch.io. +- Linux builds are listed but cannot be installed yet. + +## Free games + +A free game does not need to be in the library. The game's number is read from the `itch:path` meta tag of its page (`games/<id>`), and both the upload list and the download work with the API key alone and no download key. This was checked against a live free game: the upload list answered 200 and a one-byte range request on the download answered 206. + +A game that costs money and has no download key in the library is still refused. + +## Pieces + +`ItchGame` finds the game number and turns the upload list into builds. `ItchUploads.platforms` reads the platform from the upload's flags or `p_*` traits, and treats an upload with none as Windows. `ItchBuildPicker` is the pop-up. The chosen upload is carried in the item's `extra` as `uploadId`, and `ItchInstaller` downloads that upload. + +If the upload the user chose is no longer in the game's list when the install starts, the install fails with "No Windows download for this game" and does not pick another build. Only an install with no chosen upload falls back to the newest Windows build. The saved queue keeps whether a game is free, so an interrupted free-game install resumes after a restart. + +Before an install extracts, a leftover partial install of the same game (a folder whose marker said "installing" with this game's ID when the install started) is emptied, so a different build chosen after an interruption never mixes with files from the first. A finished or updating install, or another game's unfinished folder that happens to share the folder name, is never emptied. diff --git a/docs/development/proot-performance.md b/docs/development/proot-performance.md index 217650b53f..bcf3424c1e 100644 --- a/docs/development/proot-performance.md +++ b/docs/development/proot-performance.md @@ -314,3 +314,93 @@ it needs `patches/0014`, enabled with `PROOT_FASTPATH=1`. and `PROOT_FP_STATS` hit rates for steam, steamwebhelper, wine and wineserver. - **FEX**, inside Proton as a DLL, translates x86 path syscalls through glibc's `syscall()`, not the wrappers, so they still trap. A `syscall()` hook could route `openat` and `newfstatat` there too. + +## Finding the next fast path + +The prototype notes above describe the original experiments. Main now includes the fast path, +expanded wrappers, FEX raw-open routing ([#1283](https://github.com/Droid-Deck/DroidDeck/pull/1283)), +and SD-library bind-name resolution ([#1331](https://github.com/Droid-Deck/DroidDeck/pull/1331)). +Those fixes show why wrapper hit rates alone are insufficient: a caller can bypass the wrappers, +or repeatedly hit a path the wrappers cannot resolve. + +### Opt-in tracer profiling + +With **Setup > Diagnostics > Debugging tools** enabled, queue profiling for one session: + +```sh +tools/droiddeckctl proot-profile enable --slow-us 1000 +tools/droiddeckctl start steam --wait +# Reproduce the startup, game load, or streaming workload. +tools/droiddeckctl stop +tools/droiddeckctl logs latest ./profile-run +tools/droiddeckctl proot-profile report ./profile-run/session.log --sort wall +# Also inspect --sort cpu and --sort calls. +``` + +`PROOT_PROFILE=1` is forwarded from the session environment to the host tracer. Patch 0018 records +entry/exit **handler visits**, including PRoot's chained calls, by portable syscall name. It emits +`proot-profile` JSON lines to the existing `session.log`: cumulative totals every five seconds while +handling calls, totals at normal exit, and up to 32 slow-handler samples per five-second window exceeding `PROOT_PROFILE_SLOW_US` +(default 1,000 microseconds). The report uses each counter's last snapshot rather than adding +snapshots together and retains the most recent 128 slow samples. Logs can be pulled and reported while the session is running; final totals can +be lost if the tracer is killed. An empty report (`hasCounters: false`) is not evidence of zero +PRoot cost: check for the `start` record and that the installed PRoot pack contains patch 0018. + +**What the clocks mean:** handler wall time includes PRoot's path translation, filesystem waits +inside the tracer, and time the tracer is descheduled inside the handler. Thread CPU time measures +CPU used by that handler. Neither clock includes the tracee's subsequent kernel syscall, the +wake-up/queue delay before handler entry, or work outside `translate_syscall` (such as standalone +SIGSYS emulation, signal delivery, and process-event handling). Fast-path calls that avoid PRoot +are absent. Counts are handler visits, not a count of all guest syscalls. No extra ptrace stops or +syscall-exit interception are enabled for profiling. Profiling still costs clock reads, counters, +and log output; turn it off for final performance measurements. + +Rank cumulative time and frequency before chasing individual outliers. High handler CPU suggests +translation work; high handler wall with low CPU suggests filesystem or scheduling waits. Neither +proves how much a new fast path would save. Reproduce with the same app/PRoot/library build, +workload, storage, CPU policy, and cache state, then alternate A/B runs and measure the real load +milestone without profiling too. Keep `PROOT_FP_OFF=1` runs for correctness comparisons. + +For path context, the existing `PROOT_FP_LOG=/tmp/fastpath-misses.log` logs wrapper fallbacks and +`PROOT_FP_STATS=1` prints per-process hit/miss counts at normal exit. These are separate opt-ins: +miss logging writes on every fallback, may contain personal paths, and cannot see callers that +bypass the wrappers. Capture it separately from the session artifact folder. The new profiler +records syscall names, numeric IDs, and timings without paths or arguments. + +### Test a replacement library without rebuilding the APK + +Build a **glibc ARM64** library using the same toolchain as the shipped fast path: + +```sh +docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" \ + -v "$PWD:/src" -w /src droiddeck-local-cross:24.04-v3 \ + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ + -o /src/libblfastpath.so tools/proot/fastpath/fastpath.c -ldl + +tools/droiddeckctl stop +tools/droiddeckctl override libblfastpath.so ./libblfastpath.so +tools/droiddeckctl proot-profile enable +tools/droiddeckctl start steam --wait +``` + +The existing override bridge now recognizes `libblfastpath.so`: it checks ELF class, endianness, +type, and machine, reports SHA-256, and selects that file in `/etc/ld.so.preload` for one session. +It rejects installation while a session is active. This is an architecture check, not validation +of libc compatibility or the library's behavior. The fast path still requires its normal enabled +setting and the patched PRoot pack. Its basename stays `libblfastpath.so`, so `libblsession`'s FEX +routing finds it. Guest-command restaging retains the active selection. After stopping, the next +session stages the bundled preload again; `env clear all` cancels queued overrides. + +This replaces a library **for a fresh session**. It does not rebind already-resolved symbols in +running Wine/FEX processes, unload old code, or load arbitrary plug-ins through a new ABI. True +in-process patching would need an explicit dispatch API and synchronization across every process. +[The dynamic loader](https://man7.org/linux/man-pages/man3/dlopen.3.html) resolves symbols within each process. +For now, restarting the session avoids those lifetime and binding problems while removing APK +build/install time from a fast-path iteration. Changes to the trampoline/filter contract still +require a matching PRoot build, not just a library swap. The profiler itself also needs a new +PRoot pack; CI builds and pins that pack alongside the APK. + +The next useful extensions are bounded path sampling tied to handler time, separate process/signal +stop counters, and scenario reports that compare the same game-load milestone across builds. +Keep candidate fast paths behind equivalence tests: a slow symlink, `/proc` lookup, unsupported +flag, or ambiguous bind must retain PRoot's semantics. diff --git a/docs/development/stores.md b/docs/development/stores.md index 0d35745b6d..1209b7c478 100644 --- a/docs/development/stores.md +++ b/docs/development/stores.md @@ -29,9 +29,11 @@ Library pages are `app:<appId>` for an installed game and `app:<store>:<id>` for ``` The default root is the app's internal storage - the runtime's tree, `/root/Games/Stores`, no bind -needed - whatever the session's Game storage setting says. When a card the app may write is in the -device (`GameStorage.options`), Install asks "Install to" (internal / the card, free space shown; -the last pick is only the dialog's default). A card's root is `<card app folder>/Games`; when the +needed - whatever the session's Game storage setting says. **Setup > Storage > Default storage** +can send new installs straight to internal storage or the first external target; with **Ask every +time**, Install asks "Install to" when more than one target exists (internal / the card, free space +shown; the last pick is only the dialog's default). An existing install is always resumed in place, +and changing the default does not move it. A card's root is `<card app folder>/Games`; when the card is the Steam library the library's bind (`/mnt/droiddeck-sd`) already covers it, otherwise `SessionService` binds the root at `/mnt/droiddeck-stores/<volume uuid>`, so a shortcut's guest path - and its appid - is the same from one session to the next. Every root is @@ -268,7 +270,20 @@ the prefix's user folder appears, within a minute. Every path logs `CloudSaveFolder`, e.g. `{AppData}/Game/Saved/SaveGames`. `CloudSavePaths` expands it inside the game's prefix (`compatdata/<shortcut appid>/pfx/drive_c/users/steamuser`) or its install folder, case-insensitively, and refuses a path that leaves its boundary. A game whose store gives none - has no cloud saves. + has no cloud saves; a cached none is retried after a day. +- **Galaxy SDK saves:** `cloudStorage.enabled` with an empty `locations` list is Galaxy SDK + IStorage, whose objects live under a location named `__default` in + `%LocalAppData%/GOG.com/Galaxy/Applications/<clientId>/Storage/Shared/Files`. It goes through the + same location-qualified handling below. GET peels gzip when `Content-Encoding` is gzip, or when + the object round-trips as GOG's PUT gzip (deflate 6, mtime 0); a gzip-format save is left intact. +- **GOG names are location-qualified:** the cloud API lists `saves/user1.dat`, where `saves` is the + `name` of the selected `cloudStorage.locations` entry and the folder is that entry's `location` + (`.../Hollow Knight Silksong/default`). `GogCloud` strips the location segment for the local path + and puts it back for `HEAD`/`GET`/`PUT`; files from other locations are ignored. Builds before + this wrote `<location>/...` one folder too deep (`default/saves/user1.dat`); `migrateGogNested` + moves those copies up, deletes byte-identical leftovers and rewrites their baseline keys. The + migration runs once per game (`cloud_layout_<id>`), so a game that legitimately keeps a folder + named like the location is not relocated again; a non-prefixed listing is left unchanged. - **The services:** GOG `cloudstorage.gog.com/v1/<user>/<client>` with a token issued to the game's own client (the client secret is kept at install; the Galaxy token is the fallback); Epic's savesync data storage with signed read and write links (`EpicCloud` → `EpicSaveSync` → the Rust diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index b3e2c5caf9..cf25613687 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -210,16 +210,17 @@ alone would then read as an installed client. build fails when a program in the package needs a library that is neither bundled nor listed in `tools/fex/runtime-libs.txt`). They were built and published in The412Banner/DroidDeck; up to r3 their tags point at that repository's `main`, from r4 at the commit each was built from. Later builds are versions on the single - `fex` release; `fex-2610-r5` stays published as the build `droiddeck-steam-x64` pins. + `fex` release; `fex-2610-r5` stays published as the build `droiddeck-fex-update` pins. - **Where the app gets it.** The app downloads FEX from Droid-Deck/DroidDeck-Components, where nothing is - uploaded by hand. The app follows its `fex.json`: while the x86-64 client is selected it reads it from - Components' `main` (directly, at most every ten minutes) and keeps the last copy, and a session passes - that build to `droiddeck-steam-x64` (`BL_FEX_TAG`, `BL_FEX_SHA256`, `BL_FEX_URLS` with the download + uploaded by hand. The app follows its `fex.json`: it reads it from + Components' `main` (directly, at most every ten minutes) and keeps the last copy, and every session passes + that build to `droiddeck-fex-update` (`BL_FEX_TAG`, `BL_FEX_SHA256`, `BL_FEX_URLS` with the download source's mirrors). The script installs a build only after its archive matches the sha256 and every program in it loads (`ld-linux --list`); the files it replaces are kept aside until the installed copy loads too and put back otherwise, and the tag is written last. Otherwise it keeps the installed one while that still loads, then falls back to `FEX_TAG`/`FEX_SHA256` built in, which stay the first-start default when no copy - of `fex.json` has been read. Publishing a FEX build therefore takes a Components run only; a + of `fex.json` has been read. Components' `watch-fex.yml` starts that run by itself every six hours once FEX-Emu + tags a release or `tools/fex` changes on `main`. Publishing a FEX build therefore takes a Components run only; a replaced archive cannot be pointed back to, so undoing a build means building an earlier ref. The rootfs is FEX-Emu's own image, unmodified: `fex-rootfs.json` there names its rootfs.fex-emu.gg link, sha256 and size, and `mirror-upstream.yml` fetches it into the catalog's release only when both match. A newer diff --git a/docs/smart-glasses-support.md b/docs/smart-glasses-support.md index 416b0c3f48..19f59c2009 100644 --- a/docs/smart-glasses-support.md +++ b/docs/smart-glasses-support.md @@ -1,6 +1,6 @@ # Smart-glasses support -This describes the integrations implemented in DroidDeck as of 2026-10-17. A recognized product name alone does not establish that every firmware, phone, cable, or adapter supports every mode. Controls become available from the connected device's capabilities and the display modes Android actually exposes. +This describes the integrations implemented in DroidDeck as of 2026-10-24. A recognized product name alone does not establish that every firmware, phone, cable, or adapter supports every mode. Controls become available from the connected device's capabilities and the display modes Android actually exposes. **3DoF** tracks head rotation: turn, tilt, and roll around a virtual screen. **6DoF** also tracks head position, so leaning or moving changes the view. Both apply to DroidDeck menus, non-Steam launchers, desktop sessions, and games when the tracked virtual screen is enabled. Direct SteamVR rendering uses the corresponding headset pose instead of the virtual-screen layout. @@ -23,10 +23,10 @@ This describes the integrations implemented in DroidDeck as of 2026-10-17. A rec | 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** | **Experimental**; exact USB identity plus the device's USB-Ethernet control/IMU connection | Yes, when that connection is ready | No | No | -| Rokid Max; Rokid Air under the same USB identity | Integrated Rokid USB transport (vendor control requests and HID IMU reports) | Yes | 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; 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 | -RayNeo's Air-series recognition uses its known USB identity or a RayNeo/TCL Air name under the accepted vendor IDs; it is not a per-model certification list. The GT vendor path requires the specific supported product ID. Rokid recognition requires USB 04d2:162f plus a Rokid product name, since that vendor ID is shared with unrelated devices; it was verified on a Rokid Max, and the Air follows the same published protocol untested. XREAL support currently targets **1S only**: One, One Pro, Air-family devices, and recovery-mode products are not enabled by the 1S transport. VITURE Pro 2 is identified through SDK validation rather than a guessed product ID. A dock does not supply the connected glasses' sensors by itself. +RayNeo's Air-series recognition uses its known USB identity or a RayNeo/TCL Air name under the accepted vendor IDs; it is not a per-model certification list. The GT vendor path requires the specific supported product ID. Rokid recognition requires USB 04d2:162f (Max/Air) or 04d2:2002 (Max 2), plus a Rokid product name, since that vendor ID is shared with unrelated devices. Max 2 reports the USB product name "Rokid Max2". Hardware checks cover the Max and Max 2; the Air follows the same published protocol untested. XREAL support currently targets **1S only**: One, One Pro, Air-family devices, and recovery-mode products are not enabled by the 1S transport. VITURE Pro 2 is identified through SDK validation rather than a guessed product ID. A dock does not supply the connected glasses' sensors by itself. The final column refers specifically to Luma Ultra's stereo tracking cameras. DroidDeck's separate phone-camera and physical-controller features are independent of this matrix. @@ -43,7 +43,7 @@ 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 | -| Rokid Max | 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 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 | DroidDeck saves separate **2D resolution**, **3D resolution**, and **VR resolution** preferences. Unsupported saved choices fall back to the connected model's automatic behavior. Native **30 Hz** is offered only when Android advertises a matching mode and glasses presentation output is enabled. Higher refresh selections are constrained by the active 2D/SBS layout and model; a firmware-rejected switch is not treated as successful until the physical display confirms it. diff --git a/tools/aaudio-sink/android-volume.h b/tools/aaudio-sink/android-volume.h new file mode 100644 index 0000000000..6a31befeb1 --- /dev/null +++ b/tools/aaudio-sink/android-volume.h @@ -0,0 +1,103 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +#include <stdio.h> +#include <pulsecore/core-rtclock.h> +#include <pulsecore/core-subscribe.h> + +struct android_volume { + pa_sink *sink; + char *directory; + pa_time_event *timer; +}; + +static bool android_volume_read(const char *directory, unsigned *level, unsigned *maximum, unsigned *muted) { + char *path = pa_sprintf_malloc("%s/volume.state", directory); + FILE *file = fopen(path, "r"); + pa_xfree(path); + if (!file) return false; + int fields = fscanf(file, "%u %u %u", level, maximum, muted); + fclose(file); + return fields == 3 && *maximum > 0 && *level <= *maximum && *muted <= 1; +} + +static void android_volume_request(pa_sink *sink, const char *name, unsigned value) { + struct userdata *u = sink->userdata; + if (!u->android_volume || sink->state == PA_SINK_INIT) return; + char *path = pa_sprintf_malloc("%s/%s.request", u->android_volume->directory, name); + char *staged = pa_sprintf_malloc("%s.tmp", path); + FILE *file = fopen(staged, "w"); + if (file) { + fprintf(file, "%u\n", value); + if (fclose(file) == 0 && rename(staged, path) < 0) pa_log_warn("Could not publish Android %s", name); + } + pa_xfree(staged); + pa_xfree(path); +} + +static void android_volume_set(pa_sink *sink) { + struct userdata *u = sink->userdata; + unsigned level, maximum, muted; + if (!u->android_volume || !android_volume_read(u->android_volume->directory, &level, &maximum, &muted)) return; + unsigned requested = PA_MIN(pa_cvolume_max(&sink->real_volume), PA_VOLUME_NORM); + level = ((uint64_t)requested * maximum + PA_VOLUME_NORM / 2) / PA_VOLUME_NORM; + pa_cvolume_set(&sink->real_volume, sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum); + /* Android applies media gain to both PulseAudio and DirectAudio streams. */ + pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels); + android_volume_request(sink, "volume", level); +} + +static void android_volume_mute(pa_sink *sink) { + android_volume_request(sink, "mute", sink->muted ? 1 : 0); +} + +static void android_volume_refresh(pa_mainloop_api *api, pa_time_event *event, const struct timeval *tv, void *userdata) { + struct android_volume *bridge = userdata; + unsigned level, maximum, muted; + char *request = pa_sprintf_malloc("%s/volume.request", bridge->directory); + char *mute_request = pa_sprintf_malloc("%s/mute.request", bridge->directory); + char *processing = pa_sprintf_malloc("%s.processing", request); + char *mute_processing = pa_sprintf_malloc("%s.processing", mute_request); + if (access(request, F_OK) != 0 && access(mute_request, F_OK) != 0 && + access(processing, F_OK) != 0 && access(mute_processing, F_OK) != 0 && + android_volume_read(bridge->directory, &level, &maximum, &muted)) { + pa_cvolume volume; + if (bridge->sink->n_volume_steps != maximum + 1) { + bridge->sink->n_volume_steps = maximum + 1; + pa_subscription_post(bridge->sink->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, bridge->sink->index); + } + pa_cvolume_set(&volume, bridge->sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum); + if (!pa_cvolume_equal(&volume, &bridge->sink->real_volume)) pa_sink_volume_changed(bridge->sink, &volume); + if (bridge->sink->muted != !!muted) pa_sink_mute_changed(bridge->sink, !!muted); + } + pa_xfree(request); + pa_xfree(mute_request); + pa_xfree(processing); + pa_xfree(mute_processing); + pa_core_rttime_restart(bridge->sink->core, event, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC); +} + +static struct android_volume *android_volume_new(pa_sink *sink, const char *directory) { + unsigned level, maximum, muted; + if (!directory) return NULL; + struct android_volume *bridge = pa_xnew0(struct android_volume, 1); + bridge->sink = sink; + bridge->directory = pa_xstrdup(directory); + if (android_volume_read(directory, &level, &maximum, &muted)) { + pa_cvolume_set(&sink->real_volume, sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum); + sink->reference_volume = sink->real_volume; + sink->muted = !!muted; + sink->n_volume_steps = maximum + 1; + } + pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels); + pa_sink_set_set_volume_callback(sink, android_volume_set); + pa_sink_set_set_mute_callback(sink, android_volume_mute); + bridge->timer = pa_core_rttime_new(sink->core, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC, + android_volume_refresh, bridge); + return bridge; +} + +static void android_volume_free(struct android_volume *bridge) { + if (!bridge) return; + bridge->sink->core->mainloop->time_free(bridge->timer); + pa_xfree(bridge->directory); + pa_xfree(bridge); +} diff --git a/tools/aaudio-sink/module-aaudio-sink.c b/tools/aaudio-sink/module-aaudio-sink.c index 619bd26733..e79a20a54a 100644 --- a/tools/aaudio-sink/module-aaudio-sink.c +++ b/tools/aaudio-sink/module-aaudio-sink.c @@ -42,6 +42,7 @@ PA_MODULE_USAGE( "channels=<number of channels> " "channel_map=<channel map> " "volume=<initial volume, linear, 1.0 = full> " + "control_dir=<Android media volume bridge directory> " "performance_mode=<0 none, 1 low latency, 2 power saving> " "adaptive=<grow the buffer after underruns: 0 or 1> " "buffer_frames=<initial buffer size in frames, 0 = two bursts> " @@ -56,6 +57,7 @@ PA_MODULE_USAGE( #define STATS_EVERY_USEC (30 * PA_USEC_PER_SEC) static const char* const valid_modargs[] = { + "control_dir", "sink_name", "sink_properties", "format", @@ -70,7 +72,10 @@ static const char* const valid_modargs[] = { NULL }; +struct android_volume; + struct userdata { + struct android_volume *android_volume; pa_core *core; pa_module *module; pa_sink *sink; @@ -100,6 +105,9 @@ struct userdata { int32_t xruns_reported; }; +#include "android-volume.h" + + static pa_usec_t frames_to_usec(const struct userdata *u, int64_t frames) { return (pa_usec_t) (frames * (int64_t) PA_USEC_PER_SEC / (int64_t) u->ss.rate); } @@ -472,6 +480,7 @@ int pa__init(pa_module *m) { goto fail; } + u->android_volume = android_volume_new(u->sink, pa_modargs_get_value(ma, "control_dir", NULL)); pa_sink_put(u->sink); pa_modargs_free(ma); return 0; @@ -498,6 +507,8 @@ void pa__done(pa_module *m) { if (!(u = m->userdata)) return; + android_volume_free(u->android_volume); + u->android_volume = NULL; if (u->sink) pa_sink_unlink(u->sink); if (u->thread) { diff --git a/tools/device-smoke.sh b/tools/device-smoke.sh index bec8fed81b..80a8838050 100755 --- a/tools/device-smoke.sh +++ b/tools/device-smoke.sh @@ -10,7 +10,7 @@ # 5. on a foldable cycles the device state (half-opened, and with --closed also closed) through # `cmd device_state`, then puts the original state back; # 6. reads the newest session folder of a debug build: first frame, last frame rate, the -# memory page size and the last process exits. +# memory page size, the proot that session ran, and the last process exits. # # Usage: tools/device-smoke.sh [--serial SERIAL] [--apk FILE] [--pkg PACKAGE] # [--no-density] [--no-size] [--no-fold] [--closed] @@ -279,6 +279,16 @@ else ev=$(sh_ run-as "$pkg" cat "files/logs/$dir/events.jsonl" 2>/dev/null) echo "$ev" | grep -q '"frame.first"' && ok "first frame was drawn" || note "no frame.first in $dir" echo "$ev" | grep -q '"session.failed"' && bad "session.failed: $(echo "$ev" | grep '"session.failed"' | tail -1 | cut -c1-160)" + report=$(sh_ run-as "$pkg" cat "files/logs/$dir/device.txt" 2>/dev/null) + proot_line=$(echo "$report" | grep 'proot binary' | head -1) + case $proot_line in + *"rootfs fallback"*|*"missing"*) bad "session proot is not the patched binary ($proot_line)" ;; + *"apk"*|*"add-on pack"*) ok "patched proot ($proot_line)" ;; + *) note "device report has no proot binary line (build from before the check)" ;; + esac + app_log=$(sh_ run-as "$pkg" cat "files/logs/$dir/app.log" 2>/dev/null) + echo "$app_log" | grep -Fq 'proot: fast path on (' && ok "proot fast path was on" \ + || note "proot fast path activation was not recorded ($(echo "$report" | grep 'proot fast path' | tr '\n' '; '))" fps=$(sh_ run-as "$pkg" cat "files/logs/$dir/app.log" 2>/dev/null | grep 'last 10 s:' | tail -1 | sed 's/.*last 10 s: //' | cut -c1-70) [ -n "$fps" ] && echo " last stats $fps" sh_ run-as "$pkg" cat "files/logs/$dir/device.txt" 2>/dev/null | grep -E 'Memory page size|^Kernel' | sed 's/^/ report /' diff --git a/tools/directaudio/sink/module-directaudio-native-sink.c b/tools/directaudio/sink/module-directaudio-native-sink.c index ca3eb01cc5..3b6e5f6c9c 100644 --- a/tools/directaudio/sink/module-directaudio-native-sink.c +++ b/tools/directaudio/sink/module-directaudio-native-sink.c @@ -59,6 +59,7 @@ PA_MODULE_DESCRIPTION("Android audio output: DirectAudio's AAudio engine, in-pro PA_MODULE_VERSION(PACKAGE_VERSION); PA_MODULE_LOAD_ONCE(false); PA_MODULE_USAGE( + "control_dir=<Android media volume bridge directory> " "sink_name=<name for the sink> " "sink_properties=<properties for the sink> " "volume=<initial volume, linear, 1.0 = full> " @@ -91,11 +92,15 @@ PA_MODULE_USAGE( #define DA_FADE_FRAMES 64 static const char* const valid_modargs[] = { + "control_dir", "sink_name", "sink_properties", "volume", "performance_mode", "buffer_ms", "max_ms", "ring_ms", "adaptive", "decay", "limiter", "watchdog", NULL }; +struct android_volume; + struct userdata { + struct android_volume *android_volume; pa_core *core; pa_module *module; pa_sink *sink; @@ -136,6 +141,9 @@ struct userdata { unsigned int opens; }; +#include "../../aaudio-sink/android-volume.h" + + static uint64_t now_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); @@ -774,6 +782,7 @@ int pa__init(pa_module *m) { pa_log("Failed to create thread."); goto fail; } + u->android_volume = android_volume_new(u->sink, pa_modargs_get_value(ma, "control_dir", NULL)); pa_sink_put(u->sink); pa_modargs_free(ma); return 0; @@ -799,6 +808,8 @@ void pa__done(pa_module *m) { pa_assert(m); if (!(u = m->userdata)) return; + android_volume_free(u->android_volume); + u->android_volume = NULL; if (u->sink) pa_sink_unlink(u->sink); if (u->thread) { diff --git a/tools/docker_preflight.py b/tools/docker_preflight.py index b4e9232755..b9cb3dbd97 100644 --- a/tools/docker_preflight.py +++ b/tools/docker_preflight.py @@ -17,7 +17,7 @@ if __name__ == '__main__': sys.exit('Docker is unavailable: ' + engine.stderr.strip()) image = run('image', 'inspect', sys.argv[1]) if image.returncode: - if 'No such image' not in image.stderr: + if 'No such image' not in image.stderr and 'image not known' not in image.stderr: # Docker, Podman sys.exit('Cannot inspect the build image: ' + image.stderr.strip()) repo = Path(__file__).resolve().parents[1] subprocess.run(['docker', 'build', '--platform', 'linux/amd64', '-t', sys.argv[1], diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 9544e65c7d..b3a6c2d5b7 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -21,6 +21,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from adb_device import DeviceResolutionError, resolve_serial +from proot_profile import report as proot_profile_report # tools/release/variants.txt: the same app also ships as other packages (e.g. com.antutu.benchmark.full). @@ -37,6 +38,13 @@ class ControlError(RuntimeError): self.code = code +def profile_slow_us(value: str) -> int: + number = int(value) + if not 1 <= number <= 1_000_000_000: + raise argparse.ArgumentTypeError("--slow-us must be between 1 and 1000000000") + return number + + def adb_path(configured: str | None) -> str: if configured: return configured @@ -628,6 +636,10 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict: request["text"] = args.text return add_serial(checked(provider_call(adb, serial, "ui", request=request), "UI_FAILED"), serial) + if command == "proot-profile": + lines = ["PROOT_PROFILE=1", f"PROOT_PROFILE_SLOW_US={args.slow_us}"] if args.profile_op == "enable" else ["PROOT_PROFILE=0"] + return add_serial(checked(provider_call(adb, serial, "env", request={"op": "set", "lines": lines, "persistent": False}), "ENV_FAILED"), serial) + if command == "env": if args.env_op == "set": request = {"op": "set", "lines": args.lines, "persistent": args.persistent} @@ -828,6 +840,16 @@ def build_parser() -> argparse.ArgumentParser: if name == "set-text": op.add_argument("--text", required=True) + profile = commands.add_parser("proot-profile", help="profile PRoot syscall handlers in the next session, or rank a saved log") + profile_ops = profile.add_subparsers(dest="profile_op", required=True) + profile_enable = profile_ops.add_parser("enable", help="enable counters and bounded slow samples for the next session") + profile_enable.add_argument("--slow-us", type=profile_slow_us, default=1000, metavar="US") + profile_ops.add_parser("disable", help="disable profiling for the next session") + profile_report = profile_ops.add_parser("report", help="read a local session.log without a device") + profile_report.add_argument("path", type=Path) + profile_report.add_argument("--sort", choices=["wall", "cpu", "calls"], default="wall") + profile_report.add_argument("--limit", type=int, default=20) + env = commands.add_parser("env", help="session environment lines (debugging tools)") env_ops = env.add_subparsers(dest="env_op", required=True) env_ops.add_parser("list") @@ -837,7 +859,7 @@ def build_parser() -> argparse.ArgumentParser: env_clear = env_ops.add_parser("clear") env_clear.add_argument("scope", nargs="?", choices=["next", "persistent", "all"], default="next") - override = commands.add_parser("override", help="put a binary first on the next session's PATH (debugging tools)") + override = commands.add_parser("override", help="override a program or libblfastpath.so for the next session (debugging tools)") override.add_argument("name", help="the program name, e.g. gamescope") override.add_argument("path", help="the local file to push") @@ -941,6 +963,15 @@ def main(argv: list[str] | None = None) -> int: try: if not PACKAGE_NAME.fullmatch(PACKAGE): # it reaches the device shell through `am start` and `content call` raise ControlError(f"DROIDDECK_PACKAGE is not an Android package name: {PACKAGE!r}", "INVALID_REQUEST") + if args.command == "proot-profile" and args.profile_op == "report": + if args.limit < 1: + raise ControlError("--limit must be positive", "INVALID_ARGUMENTS") + try: + result = proot_profile_report(args.path.expanduser(), args.sort, args.limit) + except OSError as exc: + raise ControlError(str(exc), "FILE_IO") from exc + print(json.dumps(result, indent=2, sort_keys=True)) + return 0 adb = adb_path(args.adb) serial = resolve_serial(adb, args.serial, log=True) result = execute(args, adb, serial) diff --git a/tools/fex/patches/0004-auxv-at-platform.patch b/tools/fex/patches/0004-auxv-at-platform.patch new file mode 100644 index 0000000000..f8b2de587b --- /dev/null +++ b/tools/fex/patches/0004-auxv-at-platform.patch @@ -0,0 +1,12 @@ +diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h ++++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +@@ -640,7 +640,7 @@ + AuxVariables.emplace_back(auxv_t {16, HWCap}); // AT_HWCAP + AuxVariables.emplace_back(auxv_t {26, HWCap2}); // AT_HWCAP2 + AuxVariables.emplace_back(auxv_t {51, CalculateSignalStackSize()}); // AT_MINSIGSTKSZ +- AuxPlatform = &AuxVariables.emplace_back(auxv_t {24, ~0ULL}); // AT_PLATFORM ++ AuxPlatform = &AuxVariables.emplace_back(auxv_t {15, ~0ULL}); // AT_PLATFORM + AuxExecFN = &AuxVariables.emplace_back(auxv_t {AT_EXECFN, ~0ULL}); // AT_EXECFN + + if (Is64BitMode()) { diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index a34e97e356..0d79564569 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -85,3 +85,99 @@ the patched component retained 1/20, then 0 after destruction. The unassigned control retained 20/20 and then 0. In Backpack Battles, two batches of ten touch drags leaked 188 and 197 SHM descriptors before the fix; the same batches added zero after the fix (112 total descriptors before and after each batch). + +## 0117 WSI: cache the present-time Xwayland bypass check + +`QueuePresentKHR` in the WSI layer calls `canBypassXWayland` for every swapchain on +every present. Each call makes several synchronous X requests (window geometry, +`_WINE_ALLOW_FLIP`, parent window, a child-window scan, the toplevel window). At +high frame rates that is thousands of round trips a second: on an AYANEO Pocket FIT +running AIO Graphics Test uncapped, Xwayland used 24-32% of a core and the game's +present thread sat about half idle. + +The patch can keep the result for `DROIDDECK_WSI_BYPASS_CHECK_MS` milliseconds. Unset +or 0 keeps the per-present check; the app sets 100. With 100, a window resize or a flip/obscure change is seen up to 100 ms +later than before; surface creation and capability queries still check every time. + +## 0118 Wayland: preserve signed plane positions + +Fill scaling and Steam magnification can place the image at negative x/y coordinates. +The Wayland backend converted these signed positions through an unsigned size helper: +at host scale 120, -120 became 35791275 and the image moved off-screen while overlays +could remain visible. A separate signed conversion uses a 64-bit intermediate and +retains the existing ceiling convention; viewport sizes keep their original helper. + +The component build runs `wayland_scaling` for negative crop offsets, positive/zero +positions, fractional host scales and wide intermediates. This patch may be worth +upstreaming: the same unsigned position calls were present in ValveSoftware/gamescope +3.16.29 and master `d175688ad4ec490dc7b0695c5c62f8807684a1f1` when checked on +2026-10-26. Carry it here until an upstream release containing the fix is adopted. + +Device validation on AYN Thor (1280x720 session, 1920x1080 Android output): +800x600 and 1600x600 source windows retained their image through Auto, Fit, +Stretch, Fill, Integer and 2x Steam magnification, including returning to Fit. +The old component lost the image in Fill and magnification. The tested executable +matches the pinned p14 archive and the locally assembled APK. Hardware checks used +native Gamescope properties; the physical Back+LB shortcut was not independently +confirmed. The original APK and runtime were restored after validation. + +## 0119 WSI: default image count while the frame limiter runs + +The app sets `GAMESCOPE_WSI_MIN_IMAGE_COUNT=8` so an uncapped game keeps drawing while +gamescope turns its buffers around. With Steam's Frame Limit on, gamescope forces FIFO, +and the layer always hands the driver MAILBOX, so a game with eight images could queue +up to seven frames inside gamescope before it blocked: each one adds a frame of input +latency at the limited rate. + +While the limiter forces FIFO, the layer now reports and enforces its default minimum +of 3 images instead of the raised count; with the limiter off it uses the raised count +as before. DXVK and VKD3D-Proton already recreate their swapchain when the limiter +changes (the layer returns `VK_ERROR_OUT_OF_DATE_KHR`), so their image count follows +the Quick Access menu. Other apps keep their swapchain on a limiter change; they now +get `VK_SUBOPTIMAL_KHR` while their image count no longer matches, unless the layer +marks them as not taking it (`NoSuboptimal`). + +## 0120 Wayland: nested refresh follows the host + +`-r` fixes the refresh gamescope paces at, and the frame limiter and Steam's Frame Limit +slider use the same value. The app passes the panel refresh at session start, so a +panel switched to another mode during the session (for example in the device's own +quick settings) left gamescope pacing at the old rate until the next session; only the +reported output refresh changed. + +With `GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST=1`, a refresh the host compositor reports +through presentation feedback replaces the `-r` value, so pacing and the limiter switch +with the panel. `-r` still sets the starting rate, which avoids gamescope assuming +60 Hz until the first frame is shown. When the refresh changes, gamescope also sends +its `gamescope_control` display information to Steam again; Steam otherwise reads it +only when it binds. + +A host mode switch can report a passing rate for a few frames (72 Hz between 144 and +120 Hz on the AYANEO Pocket FIT), so with following on a new rate is taken once it has +been reported for 300 ms. Without the variable the reported rate is taken at once, as +upstream does. + +The rate comes from the feedback of a frame gamescope presents, so with nothing moving +on screen no feedback arrived and the old rate stayed. With following on, gamescope +presents once when the host's `wl_output` mode changes (DroidDeck's compositor sends +the new mode) and keeps presenting while a new rate is pending (since p16). + +## 0121 Xwayland: skip the X tree walk for a repeated window override + +The WSI layer sends `override_window_content` on every present of an X11 swapchain. +gamescope first walked from that window to its top-level window with `XQueryTree`, one +blocking X round trip per level under the wlserver lock, and only then noticed that the +same swapchain already overrides that window. At thousands of frames per second that is +thousands of round trips to Xwayland every second. + +The override now remembers the window it was asked for. When the same swapchain and +surface ask for the same window again within 100 ms, the request returns at once; after +100 ms the walk runs again, so a window that moved to another top level is still found. + +## 0122 Wayland: wake steamcompmgr after reading host events + +Backport of upstream commit 2962992 by Matthew Schwartz (ValveSoftware/gamescope). +The nested Wayland backend's input thread reads the host display, but steamcompmgr +does not watch that file descriptor, so buffer releases and presentation feedback +queued by that read could wait up to one refresh for steamcompmgr's next poll. The +input thread now wakes steamcompmgr after each read. diff --git a/tools/gamescope/build-in-arch.sh b/tools/gamescope/build-in-arch.sh index 2853e593ab..ba3b1605db 100755 --- a/tools/gamescope/build-in-arch.sh +++ b/tools/gamescope/build-in-arch.sh @@ -39,7 +39,7 @@ else fi PREP makepkg -A -s --noconfirm --skipchecksums --skippgpcheck -meson test -C src/build --no-rebuild --print-errorlogs cursor_routing +meson test -C src/build --no-rebuild --print-errorlogs cursor_routing wayland_scaling ls -l *.pkg.tar.* " cd "$WORK" @@ -49,7 +49,11 @@ tar --use-compress-program=unzstd -xf "$PKG" -C out --strip-components=2 usr/bin mv out/gamescope out/usr/local/bin/gamescope chmod 755 out/usr/local/bin/gamescope strip --strip-unneeded out/usr/local/bin/gamescope || true -NEEDED=$(readelf -d out/usr/local/bin/gamescope | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p') +# The WSI layer carries patches too (0117); the runtime's stock copy is replaced. +mkdir -p out/usr/lib +tar --use-compress-program=unzstd -xf "$PKG" -C out usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so +strip --strip-unneeded out/usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so || true +NEEDED=$(for f in out/usr/local/bin/gamescope out/usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so; do readelf -d "$f" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p'; done | sort -u) echo "NEEDED: $NEEDED" MISSING="" for lib in $NEEDED; do grep -qx "$lib" tools/gamescope/runtime-sonames.txt || MISSING="$MISSING $lib"; done diff --git a/tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch b/tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch new file mode 100644 index 0000000000..7ce0ec48d1 --- /dev/null +++ b/tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch @@ -0,0 +1,55 @@ +--- a/layer/VkLayer_FROG_gamescope_wsi.cpp 2026-10-25 07:56:48.179978889 +0000 ++++ b/layer/VkLayer_FROG_gamescope_wsi.cpp 2026-10-25 07:56:48.207978889 +0000 +@@ -23,6 +23,8 @@ + #include <optional> + + #include <poll.h> ++#include <time.h> ++#include <cstdlib> + #include <sys/stat.h> + // For limiter file. + #include <time.h> +@@ -476,6 +478,34 @@ + // Cached for comparison. + std::optional<VkRect2D> cachedWindowRect; + ++ // canBypassXWayland costs several X round trips; at present time it is refreshed at most ++ // every DROIDDECK_WSI_BYPASS_CHECK_MS (default 0 = every present; DroidDeck's Performance mode sets 100). ++ std::optional<bool> presentBypass; ++ bool presentBypassHdr = false; ++ uint64_t presentBypassNs = 0; ++ ++ static uint64_t presentBypassIntervalNs() { ++ static const uint64_t interval = [] { ++ const char *v = getenv("DROIDDECK_WSI_BYPASS_CHECK_MS"); ++ return uint64_t(v && *v ? strtoull(v, nullptr, 10) : 0) * 1000000ull; ++ }(); ++ return interval; ++ } ++ ++ bool canBypassXWaylandAtPresent(bool hdrColorspace) { ++ if (isWayland()) ++ return true; ++ timespec ts; ++ clock_gettime(CLOCK_MONOTONIC, &ts); ++ const uint64_t now = uint64_t(ts.tv_sec) * 1000000000ull + uint64_t(ts.tv_nsec); ++ if (!presentBypass || presentBypassHdr != hdrColorspace || now - presentBypassNs >= presentBypassIntervalNs()) { ++ presentBypass = canBypassXWayland(hdrColorspace); ++ presentBypassHdr = hdrColorspace; ++ presentBypassNs = now; ++ } ++ return *presentBypass; ++ } ++ + bool isWayland() const { + // Is native Wayland? + return connection == nullptr; +@@ -1597,7 +1627,7 @@ + continue; + } + +- const bool canBypass = gamescopeSurface->canBypassXWayland(gamescopeSwapchain->isHdrColorspace); ++ const bool canBypass = gamescopeSurface->canBypassXWaylandAtPresent(gamescopeSwapchain->isHdrColorspace); + if (canBypass != gamescopeSwapchain->isBypassingXWayland) { + if (canBypass) { + if (!(gamescopeSurface->flags & GamescopeLayerClient::Flag::NoSuboptimal)) diff --git a/tools/gamescope/patches/0118-wayland-signed-plane-positions.patch b/tools/gamescope/patches/0118-wayland-signed-plane-positions.patch new file mode 100644 index 0000000000..d66ca56e04 --- /dev/null +++ b/tools/gamescope/patches/0118-wayland-signed-plane-positions.patch @@ -0,0 +1,106 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index d00644f..40164ba 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -11,6 +11,7 @@ + #include "waitable.h" + #include "Utils/TempFiles.h" + #include "Utils/CursorRouting.h" ++#include "Utils/WaylandScaling.h" + + #include <cstring> + #include <unordered_map> +@@ -1618,8 +1619,8 @@ namespace gamescope + { + wl_subsurface_set_position( + m_pSubsurface, +- WaylandScaleToLogical( oState->nDestX, uScale ), +- WaylandScaleToLogical( oState->nDestY, uScale ) ); ++ gamescope::WaylandPositionToLogical( oState->nDestX, uScale ), ++ gamescope::WaylandPositionToLogical( oState->nDestY, uScale ) ); + } + // The x/y here does nothing? Why? What is it for... + // Use the subsurface set_position thing instead. +diff --git a/src/Utils/WaylandScaling.h b/src/Utils/WaylandScaling.h +new file mode 100644 +index 0000000..d488e39 +--- /dev/null ++++ b/src/Utils/WaylandScaling.h +@@ -0,0 +1,12 @@ ++#pragma once ++ ++#include <cstdint> ++ ++namespace gamescope ++{ ++ constexpr int32_t WaylandPositionToLogical( int32_t nValue, uint32_t uFactor ) ++ { ++ const int64_t nScaled = int64_t( nValue ) * 120; ++ return int32_t( nScaled / uFactor + ( nScaled % uFactor > 0 ) ); ++ } ++} +diff --git a/tests/meson.build b/tests/meson.build +index 1ccdf7d..d86bf9e 100644 +--- a/tests/meson.build ++++ b/tests/meson.build +@@ -8,7 +8,7 @@ endforeach + + gamescope_tests = executable( + 'gamescope_tests', +- unittest_src + ['test_convar.cpp', 'test_cursor_routing.cpp', 'test_focus_placement.cpp', 'test_mangoapp_config.cpp', 'test_mangoapp_control.cpp', 'test_process.cpp', 'test_upscale.cpp', 'test_utils_parsers.cpp', 'test_utils_string.cpp', 'test_vrclient_detect.cpp'], ++ unittest_src + ['test_convar.cpp', 'test_cursor_routing.cpp', 'test_focus_placement.cpp', 'test_mangoapp_config.cpp', 'test_mangoapp_control.cpp', 'test_process.cpp', 'test_upscale.cpp', 'test_utils_parsers.cpp', 'test_utils_string.cpp', 'test_vrclient_detect.cpp', 'test_wayland_scaling.cpp'], + include_directories: [srcdir, sol2_include], + dependencies: [catch2_dep, luajit_dep, cap_dep, drm_dep, glm_dep, wlroots_dep], + cpp_args: gamescope_cpp_args, +@@ -18,6 +18,7 @@ reaper_test_helper = executable('reaper_test_helper', 'reaper_test_helper.cpp') + + test('convar', gamescope_tests, args: ['[convar]']) + test('cursor_routing', gamescope_tests, args: ['[cursor_routing]']) ++test('wayland_scaling', gamescope_tests, args: ['[wayland_scaling]']) + test('focus_placement', gamescope_tests, args: ['[focus_placement]']) + test('mangoapp_config', gamescope_tests, args: ['[mangoapp_config]']) + test('mangoapp_control', gamescope_tests, args: ['[mangoapp_control]']) +diff --git a/tests/test_wayland_scaling.cpp b/tests/test_wayland_scaling.cpp +new file mode 100644 +index 0000000..498f55b +--- /dev/null ++++ b/tests/test_wayland_scaling.cpp +@@ -0,0 +1,38 @@ ++#include <catch2/catch_test_macros.hpp> ++ ++#include "Utils/WaylandScaling.h" ++ ++#include <cmath> ++#include <limits> ++ ++using namespace gamescope; ++ ++TEST_CASE("cropped Wayland planes retain negative positions", "[wayland_scaling]") ++{ ++ REQUIRE( WaylandPositionToLogical( -120, 120 ) == -120 ); ++ REQUIRE( WaylandPositionToLogical( -640, 120 ) == -640 ); ++ REQUIRE( WaylandPositionToLogical( -360, 120 ) == -360 ); ++ REQUIRE( WaylandPositionToLogical( 0, 120 ) == 0 ); ++ REQUIRE( WaylandPositionToLogical( 160, 120 ) == 160 ); ++} ++ ++TEST_CASE("Wayland positions round up at fractional host scales", "[wayland_scaling]") ++{ ++ const int32_t positions[] = { -100000000, -1000000, -640, -120, -1, 0, 1, 120, 640, 1000000, 100000000 }; ++ const uint32_t scales[] = { 120, 150, 180, 240, 360, 480 }; ++ for ( uint32_t uScale : scales ) ++ { ++ for ( int32_t nPosition : positions ) ++ { ++ CAPTURE( nPosition, uScale ); ++ const int32_t nExpected = int32_t( std::ceil( (long double)( nPosition ) * 120 / uScale ) ); ++ REQUIRE( WaylandPositionToLogical( nPosition, uScale ) == nExpected ); ++ } ++ } ++} ++ ++TEST_CASE("Wayland position conversion widens before multiplying", "[wayland_scaling]") ++{ ++ REQUIRE( WaylandPositionToLogical( std::numeric_limits<int32_t>::min(), 120 ) == std::numeric_limits<int32_t>::min() ); ++ REQUIRE( WaylandPositionToLogical( std::numeric_limits<int32_t>::max(), 120 ) == std::numeric_limits<int32_t>::max() ); ++} diff --git a/tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch b/tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch new file mode 100644 index 0000000000..78f2837ca6 --- /dev/null +++ b/tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch @@ -0,0 +1,59 @@ +diff --git a/layer/VkLayer_FROG_gamescope_wsi.cpp b/layer/VkLayer_FROG_gamescope_wsi.cpp +index ea4ba84..46d086c 100644 +--- a/layer/VkLayer_FROG_gamescope_wsi.cpp ++++ b/layer/VkLayer_FROG_gamescope_wsi.cpp +@@ -201,6 +201,13 @@ namespace GamescopeWSILayer { + return s_minImageCount; + } + ++ // The raised count keeps an uncapped game drawing while gamescope turns its buffers around. ++ // Under the frame limiter's FIFO the extra images only queue frames ahead of the screen, ++ // so a limited swapchain gets the default count. ++ static uint32_t getMinImageCount(bool forcingFifo) { ++ return forcingFifo ? std::min(getMinImageCount(), 3u) : getMinImageCount(); ++ } ++ + static bool getEnsureMinImageCount() { + static bool s_ensureMinImageCount = []() -> bool { + if (auto ensure = parseEnv<bool>("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT")) { +@@ -984,7 +991,7 @@ namespace GamescopeWSILayer { + + pSurfaceCapabilities->currentExtent = rect->extent; + } +- pSurfaceCapabilities->minImageCount = getMinImageCount(); ++ pSurfaceCapabilities->minImageCount = getMinImageCount(gamescopeIsForcingFifo(gamescopeSurface->waylandObjects)); + + return VK_SUCCESS; + } +@@ -1027,7 +1034,7 @@ namespace GamescopeWSILayer { + + pSurfaceCapabilities->surfaceCapabilities.currentExtent = rect->extent; + } +- pSurfaceCapabilities->surfaceCapabilities.minImageCount = getMinImageCount(); ++ pSurfaceCapabilities->surfaceCapabilities.minImageCount = getMinImageCount(gamescopeIsForcingFifo(gamescopeSurface->waylandObjects)); + + return VK_SUCCESS; + } +@@ -1305,7 +1312,7 @@ namespace GamescopeWSILayer { + + uint32_t minImageCount = swapchainInfo.minImageCount; + if (getEnsureMinImageCount()) +- minImageCount = std::max(getMinImageCount(), minImageCount); ++ minImageCount = std::max(getMinImageCount(gamescopeIsForcingFifo(gamescopeSurface->waylandObjects)), minImageCount); + swapchainInfo.minImageCount = minImageCount; + + fprintf(stderr, "[Gamescope WSI] Creating swapchain for xid: 0x%0x - oldSwapchain: %p - provided minImageCount: %u - minImageCount: %u - format: %s - colorspace: %s - flip: %s\n", +@@ -1627,6 +1634,13 @@ namespace GamescopeWSILayer { + continue; + } + ++ // Other apps keep their swapchain when the limiter changes; ask them to recreate it so ++ // the image count follows the limiter as well. ++ if (!frameLimiterAware && gamescopeSwapchain->forceFifo != forceFifo && ++ getMinImageCount(true) != getMinImageCount(false) && ++ !(gamescopeSurface->flags & GamescopeLayerClient::Flag::NoSuboptimal)) ++ UpdateSwapchainResult(VK_SUBOPTIMAL_KHR); ++ + const bool canBypass = gamescopeSurface->canBypassXWaylandAtPresent(gamescopeSwapchain->isHdrColorspace); + if (canBypass != gamescopeSwapchain->isBypassingXWayland) { + if (canBypass) { diff --git a/tools/gamescope/patches/0120-nested-refresh-follows-host.patch b/tools/gamescope/patches/0120-nested-refresh-follows-host.patch new file mode 100644 index 0000000000..83ed73b74b --- /dev/null +++ b/tools/gamescope/patches/0120-nested-refresh-follows-host.patch @@ -0,0 +1,108 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 40164ba..1b85e63 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -1698,6 +1698,52 @@ namespace gamescope + } + } + ++ // -r sets the refresh gamescope starts with. With GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST=1 a refresh ++ // the host compositor reports later replaces it, so pacing and the frame limiter follow a panel ++ // switched to another mode during the session. ++ static bool NestedRefreshFollowsHost() ++ { ++ static const bool s_bFollow = [] ++ { ++ const char *pszFollow = getenv( "GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST" ); ++ return pszFollow && atoi( pszFollow ) != 0; ++ }(); ++ return s_bFollow; ++ } ++ ++ // A mode switch on the host can report a passing rate for a few frames (72 Hz between 144 and ++ // 120 on an AYANEO Pocket FIT); a new rate is taken once it has been reported for 300 ms. ++ // Until then gamescope keeps presenting, so a still screen also gets the feedback that takes it. ++ static bool HostRefreshChanged( int32_t nRefreshmHz, uint64_t ulPresentedNs ) ++ { ++ static int32_t s_nPendingmHz = 0; ++ static uint64_t s_ulPendingSinceNs = 0; ++ if ( !nRefreshmHz || nRefreshmHz == g_nOutputRefresh ) ++ { ++ s_nPendingmHz = 0; ++ return false; ++ } ++ if ( !NestedRefreshFollowsHost() ) ++ return true; ++ if ( nRefreshmHz != s_nPendingmHz ) ++ { ++ s_nPendingmHz = nRefreshmHz; ++ s_ulPendingSinceNs = ulPresentedNs; ++ } ++ if ( ulPresentedNs - s_ulPendingSinceNs >= 300'000'000ul ) ++ return true; ++ force_repaint(); ++ return false; ++ } ++ ++ static void FollowHostRefresh( int32_t nRefreshmHz ) ++ { ++ if ( !NestedRefreshFollowsHost() || !g_nNestedRefresh || g_nNestedRefresh == nRefreshmHz ) ++ return; ++ xdg_log.infof( "Nested refresh follows the host: %.3fhz", ConvertmHzToHz( (float) nRefreshmHz ) ); ++ g_nNestedRefresh = nRefreshmHz; ++ } ++ + void CWaylandPlane::UpdateVRRRefreshRate() + { + if ( m_pParent ) +@@ -1724,6 +1770,7 @@ namespace gamescope + // TODO(strategy): We should pick the largest refresh rate. + xdg_log.infof( "Changed refresh to: %.3fhz", ConvertmHzToHz( (float) nLargestRefreshRateMhz ) ); + g_nOutputRefresh = nLargestRefreshRateMhz; ++ FollowHostRefresh( nLargestRefreshRateMhz ); + } + } + +@@ -1794,10 +1841,11 @@ namespace gamescope + if ( uRefreshCycle ) + { + int32_t nRefresh = RefreshCycleTomHz( uRefreshCycle ); +- if ( nRefresh && nRefresh != g_nOutputRefresh ) ++ if ( HostRefreshChanged( nRefresh, ulTime ) ) + { + xdg_log.infof( "Changed refresh to: %.3fhz", ConvertmHzToHz( (float) nRefresh ) ); + g_nOutputRefresh = nRefresh; ++ FollowHostRefresh( nRefresh ); + } + + m_pConnector->SetHostCompositorIsCurrentlyVRR( false ); +@@ -2636,6 +2684,9 @@ namespace gamescope + } + void CWaylandBackend::Wayland_Output_Mode( wl_output *pOutput, uint32_t uFlags, int32_t nWidth, int32_t nHeight, int32_t nRefresh ) + { ++ // The followed rate comes from presentation feedback, so a still screen presents once for it. ++ if ( NestedRefreshFollowsHost() && m_pOutputs[ pOutput ].nRefresh != nRefresh ) ++ force_repaint(); + m_pOutputs[ pOutput ].nRefresh = nRefresh; + } + void CWaylandBackend::Wayland_Output_Done( wl_output *pOutput ) +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 6c9299d..5fb9086 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -9254,6 +9254,15 @@ void update_vrr_atoms(xwayland_ctx_t *root_ctx, bool force, bool* needs_flush = + g_nCurrentRefreshRate_CachedValue = g_nOutputRefresh; + if (needs_flush) + *needs_flush = true; ++ ++ // Steam reads the display's refresh rates from gamescope_control when it binds; send them again. ++ if ( !force ) ++ { ++ wlserver_lock(); ++ for ( const auto &control : wlserver.gamescope_controls ) ++ wlserver_send_gamescope_control( control ); ++ wlserver_unlock(); ++ } + } + + // Don't update this in-sync with DRM vrr usage. diff --git a/tools/gamescope/patches/0121-override-content-skip-toplevel-walk.patch b/tools/gamescope/patches/0121-override-content-skip-toplevel-walk.patch new file mode 100644 index 0000000000..016ae5af37 --- /dev/null +++ b/tools/gamescope/patches/0121-override-content-skip-toplevel-walk.patch @@ -0,0 +1,55 @@ +diff --git a/src/wlserver.cpp b/src/wlserver.cpp +index 9a027a2..e6d8e31 100644 +--- a/src/wlserver.cpp ++++ b/src/wlserver.cpp +@@ -98,6 +98,8 @@ struct wlserver_content_override { + uint32_t x11_window; + struct wl_listener surface_destroy_listener; + struct wl_resource *gamescope_swapchain; ++ uint32_t requested_window; ++ uint64_t ulCheckedNs; + }; + + std::mutex g_wlserver_xdg_shell_windows_lock; +@@ -800,6 +802,20 @@ static void gamescope_swapchain_destroy_co( struct wl_resource *resource ); + + void gamescope_xwayland_server_t::handle_override_window_content( struct wl_client *client, struct wl_resource *gamescope_swapchain_resource, struct wlr_surface *surface, uint32_t x11_window ) + { ++ // The WSI layer sends this on every present. Finding the top level walks the X tree with a ++ // round trip per level, so a swapchain repeating the same window skips it for 100 ms. ++ const uint64_t ulNow = get_time_in_nanos(); ++ if ( gamescope_swapchain_resource ) ++ { ++ for ( const auto &[ window, existing ] : content_overrides ) ++ { ++ if ( existing->gamescope_swapchain == gamescope_swapchain_resource && existing->surface == surface && ++ existing->requested_window == x11_window && ulNow - existing->ulCheckedNs < 100'000'000ul ) ++ return; ++ } ++ } ++ ++ const uint32_t requested_window = x11_window; + x11_window = x11_find_toplevel_for_xid( this->ctx->dpy, x11_window ); + + wlserver_x11_surface_info *x11_surface = lookup_x11_surface_info_from_xid( this, x11_window ); +@@ -813,7 +829,11 @@ void gamescope_xwayland_server_t::handle_override_window_content( struct wl_clie + + if ( content_overrides.count( x11_window ) ) { + if ( content_overrides[x11_window]->gamescope_swapchain == gamescope_swapchain_resource ) ++ { ++ content_overrides[x11_window]->requested_window = requested_window; ++ content_overrides[x11_window]->ulCheckedNs = ulNow; + return; ++ } + #ifdef GAMESCOPE_SWAPCHAIN_DEBUG + wl_log.infof( "handle_override_window_content: (2) DESTROYING x11_window: 0x%x old_swapchain: %p new_swapchain: %p", x11_window, content_overrides[x11_window]->gamescope_swapchain, gamescope_swapchain_resource ); + #endif +@@ -830,6 +850,8 @@ void gamescope_xwayland_server_t::handle_override_window_content( struct wl_clie + co->surface = surface; + co->x11_window = x11_window; + co->gamescope_swapchain = gamescope_swapchain_resource; ++ co->requested_window = requested_window; ++ co->ulCheckedNs = ulNow; + co->surface_destroy_listener.notify = content_override_handle_surface_destroy; + wl_signal_add( &surface->events.destroy, &co->surface_destroy_listener ); + content_overrides[ x11_window ] = co; diff --git a/tools/gamescope/patches/0122-wayland-wake-after-host-events.patch b/tools/gamescope/patches/0122-wayland-wake-after-host-events.patch new file mode 100644 index 0000000000..0be39bf16c --- /dev/null +++ b/tools/gamescope/patches/0122-wayland-wake-after-host-events.patch @@ -0,0 +1,14 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 1b85e63..370661d 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -2977,6 +2977,9 @@ namespace gamescope + LogDisplayError( "Failed to read events on input thread", m_pBackend->GetDisplay() ); + abort(); + } ++ ++ // Reading also queues releases and presentation feedback for steamcompmgr. ++ nudge_steamcompmgr(); + } + } + diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index 1e741f4aa0..b8aaf70cba 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,3 +1,3 @@ GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components -GAMESCOPE_TAG=gamescope-3.16.29-p12 -GAMESCOPE_SHA256=07b69944a1ebf2741d4a867afa6327dcc63ec458f432a8f7483089dce2197010 +GAMESCOPE_TAG=gamescope-3.16.29-p17 +GAMESCOPE_SHA256=18e2b65407c5775301abdbc9f0db7df6b0e653923afcebdaa0f1ea3b9d5d5bb4 diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index 71377fed64..83b67d6225 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -12,6 +12,9 @@ export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1 export MOZ_SHM_NO_SEALS=1 export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe [ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null +for conf in client client-rt; do + mkdir -p "/etc/pipewire/$conf.conf.d" && printf 'context.properties = {\n module.rt = false\n}\n' >"/etc/pipewire/$conf.conf.d/droiddeck-rt.conf" +done 2>/dev/null export DROIDDECK_NESTED_SCALE=1 export DROIDDECK_GLTHREAD=${mesa_glthread:-} unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2 mesa_glthread diff --git a/tools/linuxfs/desktop/droiddeck-gpu b/tools/linuxfs/desktop/droiddeck-gpu index 40a346085b..f759d3ad01 100644 --- a/tools/linuxfs/desktop/droiddeck-gpu +++ b/tools/linuxfs/desktop/droiddeck-gpu @@ -6,21 +6,42 @@ if [ -n "${BL_DEBUG_DIR:-}" ]; then fi width=${BL_WIDTH:-1280} height=${BL_HEIGHT:-720} -args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height") +window=0 +if [ "${BL_DESKTOP_GPU_WINDOW:-1}" != 0 ] && [ -n "${WAYLAND_DISPLAY:-}" ] && [ "$WAYLAND_DISPLAY" != wayland-0 ]; then + window=1 + parent=$WAYLAND_DISPLAY + args=(--backend sdl --expose-wayland -W "$width" -H "$height" -w "$width" -h "$height") +else + args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height") +fi if [ "${BL_FPS:-0}" -gt 0 ]; then args+=(-r "$BL_FPS") elif [ "${BL_REFRESH:-0}" -gt 0 ]; then args+=(-r "$BL_REFRESH") fi [ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled) -echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on wayland-0)" -export WAYLAND_DISPLAY=wayland-0 +if [ "$window" = 1 ]; then + echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} in a window on $parent)" +else + echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on wayland-0)" + export WAYLAND_DISPLAY=wayland-0 +fi export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11 unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND KWIN_COMPOSE +wsi=",${MESA_VK_WSI_DEBUG:-}," +while [[ $wsi == *,sw,* ]]; do wsi=${wsi//,sw,/,}; done +wsi=${wsi#,}; wsi=${wsi%,} +if [ -n "$wsi" ]; then export MESA_VK_WSI_DEBUG=$wsi; else unset MESA_VK_WSI_DEBUG; fi +export BL_DESKTOP_GPU_CHILD=1 export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true [ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD export APPIMAGE_EXTRACT_AND_RUN=1 -gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@" +if [ "$window" = 1 ]; then + export BL_GPU_CHILD_WSI=${MESA_VK_WSI_DEBUG:-} + SDL_VIDEODRIVER=wayland MESA_VK_WSI_DEBUG=sw gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@" +else + gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@" +fi rc=$? echo "== droiddeck-gpu $(date -u +%H:%M:%S): exited $rc" exit $rc diff --git a/tools/linuxfs/innoextract/linuxfs/usr/local/bin/droiddeck-innoextract b/tools/linuxfs/innoextract/linuxfs/usr/local/bin/droiddeck-innoextract new file mode 100755 index 0000000000..217878a368 --- /dev/null +++ b/tools/linuxfs/innoextract/linuxfs/usr/local/bin/droiddeck-innoextract @@ -0,0 +1,7 @@ +#!/bin/sh +# Runs DroidDeck's bundled innoextract with its own boost libraries. The guest's +# env -i startup has no LD_LIBRARY_PATH, and the rootfs must not grow a second +# copy of boost for the installer fallback. +LD_LIBRARY_PATH=/usr/local/lib/droiddeck-inno +export LD_LIBRARY_PATH +exec /usr/local/lib/droiddeck-inno/innoextract "$@" diff --git a/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/innoextract b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/innoextract new file mode 100755 index 0000000000..ef18119f42 Binary files /dev/null and b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/innoextract differ diff --git a/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0 b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0 new file mode 100755 index 0000000000..c7ea48d83a Binary files /dev/null and b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0 differ diff --git a/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0 b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0 new file mode 100755 index 0000000000..cb8712b8d5 Binary files /dev/null and b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0 differ diff --git a/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0 b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0 new file mode 100755 index 0000000000..aceb212bde Binary files /dev/null and b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0 differ diff --git a/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0 b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0 new file mode 100755 index 0000000000..bfa0bb6f7d Binary files /dev/null and b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0 differ diff --git a/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0 b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0 new file mode 100755 index 0000000000..a8ea175947 Binary files /dev/null and b/tools/linuxfs/innoextract/linuxfs/usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0 differ diff --git a/tools/linuxfs/innoextract/linuxfs/usr/local/share/licenses/droiddeck-inno/LICENSE.boost b/tools/linuxfs/innoextract/linuxfs/usr/local/share/licenses/droiddeck-inno/LICENSE.boost new file mode 100644 index 0000000000..36b7cd93cd --- /dev/null +++ b/tools/linuxfs/innoextract/linuxfs/usr/local/share/licenses/droiddeck-inno/LICENSE.boost @@ -0,0 +1,23 @@ +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +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, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN 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/innoextract/linuxfs/usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract b/tools/linuxfs/innoextract/linuxfs/usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract new file mode 100644 index 0000000000..446f0c7829 --- /dev/null +++ b/tools/linuxfs/innoextract/linuxfs/usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract @@ -0,0 +1,18 @@ + +Copyright (C) 2011-2020 Daniel Scharrer <daniel@constexpr.org> + +This software is provided 'as-is', without any express or implied +warranty. In no event will the author(s) be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet new file mode 100755 index 0000000000..3e70593909 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -0,0 +1,1318 @@ +#!/usr/bin/python3 +import fcntl +import http.client +import json +import math +import os +import re +import shutil +import signal +import subprocess +import sys +import threading +import time +import urllib.request + +HOME = os.environ.get("HOME") or "/root" +BIN = "/usr/local/bin" +PROTON_RUN = os.path.join(BIN, "droiddeck-proton-run") +APP_ID = "2596113170" +INSTALLER_URL = "https://downloader.battle.net/download/getInstallerForGame?os=win&gameProgram=BATTLENET_APP&version=Live" +CLIENT_DIR = ("Program Files (x86)", "Battle.net") +LAUNCHER = "Battle.net Launcher.exe" +CLIENT = "Battle.net.exe" +CONFIG = ("users", "steamuser", "AppData", "Roaming", "Battle.net", "Battle.net.config") +DEFAULT_CONFIG = {"Client": {"HardwareAcceleration": "false", "Streaming": {"StreamingEnabled": "false"}}} +LAUNCH_BEHAVIOR = ("GameLaunchWindowBehavior", "2") +CLIENT_32_BIT = ("s1",) +CACHE = os.path.join(HOME, ".cache", "droiddeck", "battlenet") +MENU = "/usr/local/share/applications/droiddeck-battlenet.desktop" +WALLPAPER_DIR = ("users", "steamuser", "AppData", "Local", "DroidDeck") +DESKTOP_KEY = "[Control Panel\\\\Desktop]" +COLORS_KEY = "[Control Panel\\\\Colors]" +WALLPAPER_EDGE = (4, 6, 11) +WALLPAPER_MAX = (1280, 720) +FEX_REQUEST = "battlenet-fex.request" +FEX_RESULT = "battlenet-fex.result" +FEX_WAIT = 120 +START_GRACE = 90 +POLL = 2 +STOP_WAIT = 5 +CLOSE_GRACE = 15 +HANDOFF_WAIT = 120 +GAME_SETTLE = 20 +AGENT_GONE = 30 +AGENT = "agent.exe" +CODE = re.compile(r"[A-Za-z0-9_]{1,16}") +GAME_UID = re.compile(r"[a-z0-9_]{1,32}") +HANDOVER_WAIT = 1800 +CLIENT_READY = 5 +READY_SETTLE = 5 +CLIENT_WAIT = 300 +GAME_GRACE = 15 +LAUNCH_WAIT = 15 +LAUNCH_ASKS = 3 +CLIENT_PATH = re.compile(r"[a-z]:\\(program files \(x86\)|programdata)\\battle\.net\\") +IDLE = {"agent.exe", "conhost.exe", "explorer.exe", "lsass.exe", "plugplay.exe", "rpcss.exe", "services.exe", + "start.exe", "steam.exe", "svchost.exe", "tabtip.exe", "winedevice.exe", "wineserver"} +NOT_GAME = IDLE | {"rundll32.exe", "wineboot.exe", "winemenubuilder.exe"} +MIN_INSTALLER = 1 << 20 +SETUP = "Battle.net-Setup.exe" +REQUEST = "battlenet-request" +REQUEST_FILE = re.compile(re.escape(REQUEST) + r"\.\d+") +LIBRARY = None +WOW_UID = re.compile(r"--uid=wow[a-z0-9_]*", re.I) +GAMEPAD_SETTING = re.compile(r"(?im)^\s*SET\s+GamePadEnable\s") +GX_API_SETTING = re.compile(r"(?im)^[ \t]*SET[ \t]+gxApi[ \t].*$") +GX_API_MARK = ".droiddeck-d3d11" +STEAM_CLIENT = {"steam", "steamwebhelper"} +LOG = os.path.join(CACHE, "battlenet.log") +AGENT_DIR = ("ProgramData", "Battle.net", "Agent") +AGENT_BUILD = re.compile(r"Agent\.(\d+)") +AGENT_PORT = re.compile(r"\d{2,5}") +AGENT_START = 90 +AGENT_HELPER = "agent.js" +AGENT_RUNTIME = "agent-runtime" +AGENT_LOG = "agent.log" +AGENT_LOG_LIMIT = 4 << 20 +HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"] +PRODUCT = re.compile(r"[a-z0-9_]{1,32}") +LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}") +COUNTRY = re.compile(r"[A-Z]{3}") +REGION = re.compile(r"[A-Z]{2}") +REPORT = "BNET" +ETA_LIMIT = 30 * 86400 +DONE_STATE = 1004 +REPORTED = ("progress", "playable_progress", "download_rate", "download_remaining", "estimated_time_in_sec", "state", + "playable", "paused", "download_complete", "installed", "error") +AGENT_SCRIPT = r"""var a = WScript.Arguments, port = a(0), action = a(1), uid = a(2), product = a(3), dir = a(4); +var lang = a(5), country = a(6), region = a(7), out = a(8), token = ""; +var fso = new ActiveXObject("Scripting.FileSystemObject"); + +function save(name, text) { + var f = fso.CreateTextFile(out + name + ".tmp", true, true); + f.Write(text); + f.Close(); + if (fso.FileExists(out + name)) fso.DeleteFile(out + name); + fso.MoveFile(out + name + ".tmp", out + name); +} + +function call(method, path, body) { + var r = new ActiveXObject("WinHttp.WinHttpRequest.5.1"); + r.SetTimeouts(10000, 10000, 30000, 30000); + r.Open(method, "http://127.0.0.1:" + port + path, false); + r.SetRequestHeader("User-Agent", "phoenix-agent/1.0"); + if (token) r.SetRequestHeader("Authorization", token); + r.Send(body || ""); + return r.ResponseText; +} + +function field(text, name) { + var m = new RegExp('"' + name + '"\\s*:\\s*"([^"]*)"').exec(text); + return m ? m[1] : ""; +} + +function install() { + var form = call("POST", "/install", '{"uid":"' + uid + '","instructions_patch_url":"http://' + zone + '.patch.battle.net:1119/' + + product + '","instructions_product":"NGDP","monitor_pid":12345,"priority":{"insert_at_head":true,"value":900}}'); + save(".form", form); + if (form.indexOf('"' + lang + '"') < 0) lang = "enUS"; + var locale = lang.toLowerCase(); + call("POST", "/install/" + uid, '{"account_country":"' + country + '","finalized":true,"game_dir":"' + dir + '","geo_ip_country":"' + + region + '","language":["' + locale + '"],"selected_asset_locale":"' + locale + '","selected_locale":"' + locale + + '","shortcut":"none","tome_torrent":""}'); + watch("/install/" + uid); +} + +function watch(path) { + var started = false; + for (var i = 0; ; i++) { + var s = call("GET", path); + save(".json", s); + if (/"error"\s*:\s*[1-9]/.test(s)) break; + var state = /"state"\s*:\s*(\d+)/.exec(s.replace(/"extended_status"\s*:\s*\{[^}]*\}/, "")), complete = /"download_complete"\s*:\s*true/.test(s); + state = state ? +state[1] : 0; + if (state == 1000 || state == 1003 || !complete) started = true; + if (started && (state == 1004 || complete && /"playable"\s*:\s*true/.test(s))) break; + if (!started && state == 1004 && i >= 20) break; + if (!started && i >= 180) { + if (/"playable"\s*:\s*true/.test(call("GET", "/game/" + uid))) break; + throw new Error("the agent did not start the " + action); + } + WScript.Sleep(1000); + } + save(".game", call("GET", "/game/" + uid)); +} + +function update() { + save(".form", call("POST", "/update", '{"uid":"' + uid + '","priority":{"insert_at_head":true,"value":900}}')); + watch("/update/" + uid); +} + +function uninstall() { + save(".json", call("POST", "/uninstall", '{"uid":"' + uid + '","run_compaction":true}')); + for (var i = 0; i < 900; i++) { + var s = call("GET", "/game/" + uid); + save(".game", s); + if (!/"installed"\s*:\s*true/.test(s)) break; + WScript.Sleep(1000); + } +} + +var zone = "us"; +try { + var agent = call("GET", "/agent"); + token = field(agent, "authorization"); + zone = field(agent, "region") || "us"; + if (!token) throw new Error("no authorization from the agent"); + if (action == "install") install(); else if (action == "update") update(); else uninstall(); +} catch (e) { + save(".error", e.message || "the agent stopped answering"); + WScript.Quit(1); +} +""" +LOG_LIMIT = 512 << 10 + + +def say(message): + line = "droiddeck-battlenet: %s" % message + print(line, file=sys.stderr, flush=True) + try: + os.makedirs(CACHE, exist_ok=True) + if os.path.exists(LOG) and os.path.getsize(LOG) > LOG_LIMIT: + os.replace(LOG, LOG + ".1") + with open(LOG, "a", encoding="utf-8") as f: + f.write("%s [%d] %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), os.getpid(), message)) + except OSError: + pass + + +def notify(title, body, icon="dialog-information"): + if not os.environ.get("DBUS_SESSION_BUS_ADDRESS") or not shutil.which("notify-send"): + return + try: + subprocess.run(["notify-send", "-a", "DroidDeck", "-i", icon, title, body], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5) + except (OSError, subprocess.SubprocessError): + pass + + +def steam_root(): + return os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or os.path.join(HOME, ".local", "share", "Steam") + + +def prefix(root): + return os.path.join(root, "steamapps", "compatdata", APP_ID) + + +def drive_c(root): + return os.path.join(prefix(root), "pfx", "drive_c") + + +def client_dir(root): + return os.path.join(drive_c(root), *CLIENT_DIR) + + +def launcher(root): + return os.path.join(client_dir(root), LAUNCHER) + + +def installed(root): + return os.path.isfile(launcher(root)) + + +def install_path(library): + return "Z:" + library.rstrip("/") + + +def write_config(root, library=None): + path = os.path.join(drive_c(root), *CONFIG) + key, value = LAUNCH_BEHAVIOR + try: + with open(path, encoding="utf-8-sig") as f: + config = json.load(f) + except FileNotFoundError: + config = None + except (OSError, ValueError): + return None + first = config is None + if first: + config = json.loads(json.dumps(DEFAULT_CONFIG)) + elif not (isinstance(config, dict) and isinstance(config.setdefault("Client", {}), dict)): + return None + client = config["Client"] + changes = [] + if client.get(key) != value: + client[key] = value + changes.append("launch") + if client.get("HardwareAcceleration") != "false": + client["HardwareAcceleration"] = "false" + changes.append("acceleration") + if library and isinstance(client.setdefault("Install", {}), dict) \ + and str(client["Install"].get("DefaultInstallPath", "")).rstrip("/\\") != install_path(library): + client["Install"]["DefaultInstallPath"] = install_path(library) + changes.append("library") + games = config.setdefault("Games", {}) + for uid in CLIENT_32_BIT if isinstance(games, dict) else (): + game = games.setdefault(uid, {}) + if isinstance(game, dict) and game.get("Run64BitSet") != "true": + game.update(Run64Bit="false", Run64BitSet="true") + changes.append("32-bit") + if not changes: + return None + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path + ".tmp", "w", encoding="utf-8") as f: + json.dump(config, f, indent=4) + os.replace(path + ".tmp", path) + return "first" if first else " ".join(changes) + + +def wallpaper_bmp(width, height): + scale = min(width / 1920.0, height / 1080.0) + ox, oy = (width - 1920 * scale) / 2, (height - 1080 * scale) / 2 + stops = ((0.0, (20, 33, 58)), (0.5, (10, 17, 32)), (1.0, WALLPAPER_EDGE)) + glow = (26, 159, 255) + logo_px = scale * 1.6 + + def background(u, v): + t = min(math.hypot(u - 960, v - 540) / 1150, 1.0) + (t0, c0), (t1, c1) = (stops[0], stops[1]) if t <= 0.5 else (stops[1], stops[2]) + f = (t - t0) / (t1 - t0) + color = [c0[i] + (c1[i] - c0[i]) * f for i in range(3)] + d = math.hypot(u - 947.21, v - 540) / 420 + if d < 1: + a = 0.22 * (1 - d) + color = [color[i] * (1 - a) + glow[i] * a for i in range(3)] + return color + + def box(x, y, x0, y0, x1, y1): + dx, dy = max(x0 - x, x - x1), max(y0 - y, y - y1) + return math.hypot(max(dx, 0), max(dy, 0)) + min(max(dx, dy), 0) + + def white(x, y): + half = max(math.hypot(x - 63.97, y - 111.86) - 111.86, 63.97 - x) + shape = min(box(x, y, -31.98, 0, 63.97, 223.72), half) + hole = min(math.hypot(x - 63.98, y - 111.86) - 71.81, + box(x, y, 56.055, -1, 71.885, 45), box(x, y, 56.055, 178.72, 71.885, 225)) + return max(shape, -hole) + + rows = [] + pad = b"\0" * ((4 - width * 3 % 4) % 4) + for y in range(height - 1, -1, -1): + v = (y + 0.5 - oy) / scale + ly = (v - 361.02) / 1.6 + row = bytearray() + for x in range(width): + u = (x + 0.5 - ox) / scale + color = background(u, v) + lx = (u - 844.84) / 1.6 + if -40 < lx < 185 and -8 < ly < 232: + for sd, ink in ((white(lx, ly), (255, 255, 255)), (math.hypot(lx - 63.98, ly - 111.86) - 55.98, glow)): + cover = min(max(0.5 - sd * logo_px, 0.0), 1.0) + if cover: + color = [color[i] * (1 - cover) + ink[i] * cover for i in range(3)] + row += bytes((int(color[2] + 0.5), int(color[1] + 0.5), int(color[0] + 0.5))) + rows.append(bytes(row) + pad) + pixels = b"".join(rows) + header = b"BM" + (54 + len(pixels)).to_bytes(4, "little") + b"\0\0\0\0" + (54).to_bytes(4, "little") + info = (40).to_bytes(4, "little") + width.to_bytes(4, "little") + height.to_bytes(4, "little") + \ + (1).to_bytes(2, "little") + (24).to_bytes(2, "little") + b"\0" * 4 + len(pixels).to_bytes(4, "little") + \ + (2835).to_bytes(4, "little") * 2 + b"\0" * 8 + return header + info + pixels + + +def reg_value(reg, key, name, value): + line = '"%s"="%s"' % (name, value.replace("\\", "\\\\").replace('"', '\\"')) + try: + with open(reg, encoding="utf-8", errors="replace") as f: + rows = f.read().splitlines() + except OSError: + return False + inside, last = False, None + for row in rows: + if row.startswith("["): + inside = row.startswith(key + " ") or row == key + elif inside and row.startswith('"%s"=' % name): + last = row + if last != line: + with open(reg, "a", encoding="utf-8") as out: + out.write("\n%s %d\n%s\n" % (key, int(time.time()), line)) + return True + + +def desktop_size(): + width, height = os.environ.get("BL_WIDTH", ""), os.environ.get("BL_HEIGHT", "") + if width.isdigit() and height.isdigit() and 0 < int(width) <= 7680 and 0 < int(height) <= 4320: + return int(width), int(height) + return 1280, 720 + + +def wallpaper(root): + width, height = desktop_size() + shrink = min(1.0, WALLPAPER_MAX[0] / width, WALLPAPER_MAX[1] / height) + width, height = max(1, round(width * shrink)), max(1, round(height * shrink)) + name = "wallpaper-%dx%d.bmp" % (width, height) + folder = os.path.join(drive_c(root), *WALLPAPER_DIR) + path = os.path.join(folder, name) + reg = os.path.join(prefix(root), "pfx", "user.reg") + if not os.path.isfile(reg): + return False + if not os.path.isfile(path): + os.makedirs(folder, exist_ok=True) + with open(path + ".tmp", "wb") as f: + f.write(wallpaper_bmp(width, height)) + os.replace(path + ".tmp", path) + say("drew DroidDeck's wallpaper for Battle.net's %dx%d desktop" % (width, height)) + windows = "C:\\" + "\\".join(WALLPAPER_DIR + (name,)) + reg_value(reg, DESKTOP_KEY, "Wallpaper", windows) + reg_value(reg, DESKTOP_KEY, "TileWallpaper", "0") + reg_value(reg, DESKTOP_KEY, "WallpaperStyle", "2" if shrink < 1 else "0") + reg_value(reg, COLORS_KEY, "Background", "%d %d %d" % WALLPAPER_EDGE) + return True + + +def windows_path(root, path): + found = re.match(r"(?i)^([cz]):[\\/](.*)$", path.strip()) + if not found: + return None + parts = [part for part in re.split(r"[\\/]+", found.group(2)) if part] + if not parts or ".." in parts: + return None + return os.path.join(drive_c(root) if found.group(1).lower() == "c" else "/", *parts) + + +def wow_folders(root): + try: + with open(os.path.join(prefix(root), "pfx", "system.reg"), encoding="utf-8", errors="replace") as f: + rows = f.read().splitlines() + except OSError: + return [] + folders, location, wow = [], None, False + for row in rows + ["["]: + if row.startswith("["): + if wow and location: + folders.append(location) + location, wow = None, False + elif row.startswith('"InstallLocation"='): + location = windows_path(root, row.split("=", 1)[1].strip().strip('"').replace("\\\\", "\\")) + elif row.startswith('"UninstallString"=') and WOW_UID.search(row): + wow = True + return [folder for folder in dict.fromkeys(folders) if os.path.isdir(folder)] + + +def wow_settings(root): + changed = [] + for folder in wow_folders(root): + try: + flavors = sorted(name for name in os.listdir(folder) if len(name) > 2 and name.startswith("_") and name.endswith("_")) + except OSError: + continue + for name in flavors: + if not os.path.isdir(os.path.join(folder, name)): + continue + wtf = os.path.join(folder, name, "WTF") + path = os.path.join(wtf, "Config.wtf") + mark = os.path.join(wtf, GX_API_MARK) + try: + with open(path, encoding="utf-8", errors="replace") as f: + text = f.read() + except FileNotFoundError: + text = "" + except OSError: + continue + updated, notes = text, [] + if not GAMEPAD_SETTING.search(updated): + updated += ("\n" if updated and not updated.endswith("\n") else "") + 'SET GamePadEnable "1"\n' + notes.append("controller support on") + first = not os.path.exists(mark) + if first: + before = updated + updated, found = GX_API_SETTING.subn('SET gxApi "D3D11"', updated) + if not found: + updated += ("\n" if updated and not updated.endswith("\n") else "") + 'SET gxApi "D3D11"\n' + if updated != before: + notes.append("DirectX 11") + if updated == text and not first: + continue + try: + os.makedirs(wtf, exist_ok=True) + if updated != text: + with open(path + ".tmp", "w", encoding="utf-8") as f: + f.write(updated) + os.replace(path + ".tmp", path) + if first: + with open(mark, "w", encoding="utf-8"): + pass + except OSError as error: + say("World of Warcraft's settings not written in %s: %s" % (path, error)) + continue + if notes: + changed.append(path) + say("World of Warcraft's settings in %s: %s" % (path, ", ".join(notes))) + return changed + + +def steam_running(proc="/proc"): + try: + pids = [p for p in os.listdir(proc) if p.isdigit()] + except OSError: + return False + for pid in pids: + try: + with open(os.path.join(proc, pid, "cmdline"), "rb") as f: + argv = [os.path.basename(a.decode("utf-8", "replace")) for a in f.read().split(b"\0")[:2] if a] + except OSError: + continue + if argv[:1] and argv[0] in ("FEX", "FEXInterpreter"): + argv = argv[1:] + if argv[:1] and argv[0] in STEAM_CLIENT: + return True + return False + + +def proton_env(): + env = dict(os.environ) + if not steam_running(): + env.setdefault("PROTON_SPOOF_STEAMINPUT_VIDPID", "1") + return env + + +def configure(root, library=None): + if library: + try: + os.makedirs(library, exist_ok=True) + except OSError as error: + say("%s not made: %s" % (library, error)) + try: + change = write_config(root, library) + except OSError as error: + say("Battle.net's config not written: %s" % error) + return + try: + wallpaper(root) + except OSError as error: + say("Battle.net's desktop wallpaper not set: %s" % error) + wow_settings(root) + if change == "first": + say("wrote Battle.net's first config: hardware acceleration off, streaming off, closing itself as it launches a game, " + "StarCraft on its 32-bit client") + elif change: + if "launch" in change: + say("Battle.net's config: closing itself as it launches a game") + if "library" in change: + say("Battle.net's config: games install to %s" % library) + if "acceleration" in change: + say("Battle.net's config: browser hardware acceleration off") + if "32-bit" in change: + say("Battle.net's config: StarCraft starts its 32-bit client") + + +def write_menu(path=MENU): + body = ("[Desktop Entry]\nType=Application\nName=Battle.net\nComment=Blizzard's games and launcher\n" + "Exec=%s\nIcon=applications-games\nTerminal=false\nCategories=Network;\n" + % os.path.join(BIN, "droiddeck-battlenet")) + try: + with open(path, encoding="utf-8") as f: + if f.read() == body: + return + except OSError: + pass + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path + ".tmp", "w", encoding="utf-8") as f: + f.write(body) + os.replace(path + ".tmp", path) + except OSError as error: + say("menu entry not written: %s" % error) + + +def ask_fex(launch_dir, wait=FEX_WAIT): + if not launch_dir or not os.path.isdir(launch_dir): + say("not inside a DroidDeck session; FEX stays as Components has it") + return None + result = os.path.join(launch_dir, FEX_RESULT) + request = os.path.join(launch_dir, FEX_REQUEST) + try: + os.unlink(result) + except OSError: + pass + with open(request + ".tmp", "w", encoding="utf-8") as f: + f.write("appid=%s\n" % APP_ID) + os.replace(request + ".tmp", request) + deadline = time.monotonic() + wait + while time.monotonic() < deadline: + try: + with open(result, encoding="utf-8") as f: + answer = f.read().strip() + except OSError: + time.sleep(0.5) + continue + os.unlink(result) + return answer + return None + + +def wine_processes(pfx, proc="/proc"): + want = os.path.realpath(pfx).rstrip("/") + found = [] + try: + pids = [p for p in os.listdir(proc) if p.isdigit()] + except OSError: + return found + for pid in pids: + try: + with open(os.path.join(proc, pid, "environ"), "rb") as f: + env = f.read().split(b"\0") + with open(os.path.join(proc, pid, "cmdline"), "rb") as f: + argv = [a.decode("utf-8", "replace") for a in f.read().split(b"\0") if a] + except OSError: + continue + for item in env: + if item.startswith(b"WINEPREFIX="): + value = item[len(b"WINEPREFIX="):].decode("utf-8", "replace") + if os.path.realpath(value).rstrip("/") == want: + found.append((int(pid), argv)) + break + return found + + +def program(argv): + return re.split(r"[\\/]", argv[0])[-1].lower() if argv else "" + + +def is_client(argv): + return program(argv) == CLIENT.lower() + + +def idle(processes): + return all(program(argv) in IDLE for _, argv in processes) + + +def running(pfx): + return any(is_client(argv) for _, argv in wine_processes(pfx)) + + +def is_battlenet(argv): + return bool(argv) and bool(CLIENT_PATH.match(argv[0].replace("/", "\\").lower())) + + +def is_game(argv): + if not argv or program(argv) in NOT_GAME or not re.match(r"[A-Za-z]:[\\/]", argv[0]): + return False + return not is_battlenet(argv) + + +def launched(argv): + return is_game(argv) and "-uid" in (arg.lower() for arg in argv[1:]) + + +def shares_sign_in(argv): + return "-sso" in (arg.lower() for arg in argv[1:]) + + +def agent_up(processes): + return any(is_client(argv) for _, argv in processes) and any(program(argv) == AGENT for _, argv in processes) + + +class Tidy: + + def __init__(self, settle=None, gone=None): + self.settle = GAME_SETTLE if settle is None else settle + self.gone = AGENT_GONE if gone is None else gone + self.game_since = None + self.closed_for_game = False + self.agent_seen = False + self.agent_lost = None + + def __call__(self, processes, now): + own = [(pid, argv) for pid, argv in processes if is_battlenet(argv)] + games = [argv for _, argv in processes if launched(argv)] + if games: + self.game_since = self.game_since if self.game_since is not None else now + if own and not self.closed_for_game and now - self.game_since >= self.settle: + self.closed_for_game, self.agent_seen, self.agent_lost = True, False, None + if any(is_client(argv) for _, argv in own) and any(shares_sign_in(argv) for argv in games): + say("Battle.net stayed open beside a game signing in with its token: left open") + return False + say("the game is up: closing what is left of Battle.net (%d process(es)) to leave it their memory" % len(own)) + stop(own) + return True + return False + self.game_since, self.closed_for_game = None, False + if not any(is_client(argv) for _, argv in processes): + self.agent_seen, self.agent_lost = False, None + elif agent_up(processes): + self.agent_seen, self.agent_lost = True, None + elif self.agent_seen: + self.agent_lost = self.agent_lost if self.agent_lost is not None else now + if now - self.agent_lost >= self.gone: + say("Battle.net has outlived its Agent: closing it (%d process(es))" % len(own)) + stop(own) + notify("Battle.net was closed", "It had lost Blizzard's update service. Open it again to reconnect.", + "dialog-warning") + self.agent_seen, self.agent_lost = False, None + return True + return False + + +def desktop_gpu(): + if os.environ.get("BL_DESKTOP") != "1" or os.environ.get("BL_DESKTOP_GPU_CHILD"): + return None + if os.environ.get("BL_DESKTOP_GPU", "on").strip().lower() in ("off", "0", "no", "false"): + return None + gpu = os.path.join(BIN, "droiddeck-gpu") + return gpu if os.access(gpu, os.X_OK) else None + + +def proton_options(): + if os.environ.get("BL_DESKTOP") == "1" and not os.environ.get("BL_DESKTOP_GPU_CHILD"): + return ["--window"] + width, height = os.environ.get("BL_WIDTH", ""), os.environ.get("BL_HEIGHT", "") + options = ["--desktop", "%sx%s" % (width, height)] if width.isdigit() and height.isdigit() else [] + game = os.environ.get("SteamGameId", "") + return options + (["--game-id", game] if game.isdigit() and game != "0" else []) + + +def stop(processes, wait=STOP_WAIT): + pids = [pid for pid, _ in processes] + for sig in (signal.SIGTERM, signal.SIGKILL): + for pid in pids: + try: + os.kill(pid, sig) + except OSError: + pass + deadline = time.monotonic() + wait + while time.monotonic() < deadline: + pids = [pid for pid in pids if os.path.exists("/proc/%d" % pid)] + if not pids: + return + time.sleep(0.2) + + +def queued_requests(launch_dir): + try: + names = os.listdir(launch_dir) + except OSError: + return [] + return sorted(name for name in names if REQUEST_FILE.fullmatch(name)) + + +def serve_requests(pfx, processes=None, launch_dir=None): + launch_dir = launch_dir or os.environ.get("BL_LAUNCH_DIR") + names = queued_requests(launch_dir) if launch_dir else [] + if not names or not agent_up(wine_processes(pfx) if processes is None else processes): + return False + client = os.path.join(pfx, "drive_c", *CLIENT_DIR, CLIENT) + served = False + for name in names: + path = os.path.join(launch_dir, name) + try: + with open(path, encoding="utf-8") as f: + args = [line for line in f.read().splitlines() if line] + os.unlink(path) + except OSError: + continue + if len(args) == 2 and args[0] == "install-game" and GAME_UID.fullmatch(args[1]): + spawn(client, "run", ["--install", "--game=%s" % args[1]]) + elif len(args) == 2 and args[0] == "launch" and CODE.fullmatch(args[1]): + spawn(client, "run", ["--exec=launch %s" % args[1]]) + else: + say("not a request: %s" % " ".join(args)) + continue + say("the app asked for %s" % " ".join(args)) + served = True + return served + + +def wait_while_open(pfx, grace, poll=None): + deadline = time.monotonic() + grace + seen = False + while True: + serve_requests(pfx) + if running(pfx): + seen = True + elif seen or time.monotonic() >= deadline: + return seen + time.sleep(POLL if poll is None else poll) + + +def proton(exe, args=(), verb=None, watch=None, poll=None, close_grace=None, tidy=None): + cmd = [PROTON_RUN] + proton_options() + ["--prefix", APP_ID] + (["--verb", verb] if verb else []) + [exe] + list(args) + say(" ".join(cmd)) + try: + process = subprocess.Popen(cmd, env=proton_env()) + except OSError as error: + say("%s: %s" % (PROTON_RUN, error)) + return 127, False + seen = False + closed_at = None + grace = CLOSE_GRACE if close_grace is None else close_grace + tidy = Tidy() if tidy is None else tidy + while True: + try: + status = process.wait(timeout=POLL if poll is None else poll) + return status, seen + except subprocess.TimeoutExpired: + pass + if watch is None: + continue + processes = wine_processes(watch) + serve_requests(watch, processes) + now = time.monotonic() + if tidy(processes, now): + seen = True + processes = wine_processes(watch) + if any(is_client(argv) for _, argv in processes): + seen, closed_at = True, None + elif seen and idle(processes): + closed_at = closed_at if closed_at is not None else now + if now - closed_at >= grace: + say("Battle.net closed; stopping %d process(es) it left in its prefix" % len(processes)) + stop(processes) + closed_at = None + else: + closed_at = None + + +def setup_ready(path): + try: + with open(path, "rb") as f: + return f.read(2) == b"MZ" and os.path.getsize(path) >= MIN_INSTALLER + except OSError: + return False + + +def download(url=INSTALLER_URL, folder=CACHE): + os.makedirs(folder, exist_ok=True) + dest = os.path.join(folder, SETUP) + if setup_ready(dest): + return dest + part = dest + ".part" + try: + try: + request = urllib.request.Request(url, headers={"User-Agent": "DroidDeck"}) + with urllib.request.urlopen(request, timeout=60) as response, open(part, "wb") as f: + shutil.copyfileobj(response, f) + length = response.headers.get("Content-Length", "") + if length.isdigit() and f.tell() != int(length): + raise OSError("the download ended early") + except (OSError, http.client.HTTPException) as error: + if not shutil.which("curl"): + raise + say("download through Python failed (%s); trying curl" % error) + if subprocess.call(["curl", "-fsSL", "--max-time", "300", "-o", part, url]) != 0: + raise OSError("curl could not download it") + if not setup_ready(part): + raise OSError("not a Windows program") + os.replace(part, dest) + except (OSError, http.client.HTTPException) as error: + say("installer download failed: %s" % error) + try: + os.unlink(part) + except OSError: + pass + return dest if os.path.isfile(dest) else None + + +def install(root, pfx, verb=None): + setup = download() + if setup is None: + notify("Battle.net could not be downloaded", "Check the connection and try again.", "dialog-error") + return False, False + configure(root, LIBRARY) + notify("Installing Battle.net", "Blizzard's installer opens in a window. It can take a few minutes.") + _, seen = proton(setup, verb=verb, watch=pfx) + return installed(root), seen + + +def acquire(folder=CACHE): + os.makedirs(folder, exist_ok=True) + handle = open(os.path.join(folder, "battlenet.lock"), "w") + try: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + handle.close() + return None + return handle + + +def status(root): + pfx = os.path.join(prefix(root), "pfx") + return {"appid": int(APP_ID), "prefix": prefix(root), "installed": installed(root), + "launcher": launcher(root), "running": running(pfx)} + + +def spawn(program, verb, args=()): + cmd = [PROTON_RUN] + proton_options() + ["--prefix", APP_ID, "--verb", verb, program] + list(args) + say(" ".join(cmd)) + try: + os.makedirs(CACHE, exist_ok=True) + with open(os.path.join(CACHE, "spawned.log"), "ab") as log: + child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, env=proton_env()) + threading.Thread(target=child.wait, daemon=True).start() + except OSError as error: + say("%s: %s" % (PROTON_RUN, error)) + return 127 + return 0 + + +def show(root, wait=None, poll=None, args=()): + pfx = os.path.join(prefix(root), "pfx") + client = os.path.join(client_dir(root), CLIENT) + deadline = time.monotonic() + (HANDOFF_WAIT if wait is None else wait) + while True: + processes = wine_processes(pfx) + if any(is_client(argv) for _, argv in processes) and os.path.isfile(client) \ + and (agent_up(processes) or time.monotonic() >= deadline): + spawn(client, "run", args) + return None + lock = acquire() + if lock is not None: + say("the other start has ended; opening Battle.net") + return lock + if time.monotonic() >= deadline: + say("the other start neither opened Battle.net nor ended") + notify("Battle.net is busy", "Another start is still running; try again in a moment.", "dialog-warning") + return None + time.sleep(POLL if poll is None else poll) + + +def stop_leftovers(pfx): + processes = wine_processes(pfx) + if not processes: + return True + if not idle(processes): + say("the prefix is in use (%s); Battle.net starts beside it" % ", ".join(sorted({program(a) for _, a in processes} - IDLE))) + return False + say("stopping %d process(es) a closed Battle.net left in its prefix" % len(processes)) + stop(processes) + return True + + +def open_client(root, reinstall=False): + pfx = os.path.join(prefix(root), "pfx") + write_menu() + answer = ask_fex(os.environ.get("BL_LAUNCH_DIR")) + say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) + if running(pfx): + say("Battle.net is already running in its prefix; waiting for it to close") + wait_while_open(pfx, grace=0) + return 0 + verb = None if stop_leftovers(pfx) else "run" + if reinstall or not installed(root): + done, seen = install(root, pfx, verb) + if not done: + notify("Battle.net did not install", "The session's desktop.log says why.", "dialog-error") + return 1 + if wait_while_open(pfx, grace=0 if seen else START_GRACE) or seen: + return 0 + verb = None if stop_leftovers(pfx) else "run" + configure(root, LIBRARY) + status_code, seen = proton(launcher(root), verb=verb, watch=pfx) + say("Proton returned %d; Battle.net %s" % (status_code, "ran" if seen else "has not been seen yet")) + if not (wait_while_open(pfx, grace=0 if seen else START_GRACE) or seen): + say("Battle.net did not start (the launcher exited with %d)" % status_code) + notify("Battle.net did not start", "The session's desktop.log says why.", "dialog-error") + return status_code or 1 + say("Battle.net closed") + return 0 + + +def start(exe, verb=None): + cmd = [PROTON_RUN] + proton_options() + ["--prefix", APP_ID] + (["--verb", verb] if verb else []) + [exe] + say(" ".join(cmd)) + try: + return subprocess.Popen(cmd, env=proton_env()) + except OSError as error: + say("%s: %s" % (PROTON_RUN, error)) + return None + + +def wait_ready(pfx, wait=None, poll=None, settle=None): + deadline = time.monotonic() + (CLIENT_WAIT if wait is None else wait) + while True: + count = sum(1 for _, argv in wine_processes(pfx) if is_client(argv)) + if count >= CLIENT_READY: + time.sleep(READY_SETTLE if settle is None else settle) + return True + if time.monotonic() >= deadline: + return count > 0 + time.sleep(POLL if poll is None else poll) + + +def follow(pfx, poll=None, grace=None, tidy=None, ask=None): + seen, gone_at = False, None + asked, asks = None, 1 + grace = GAME_GRACE if grace is None else grace + tidy = Tidy() if tidy is None else tidy + while True: + processes = wine_processes(pfx) + serve_requests(pfx, processes) + now = time.monotonic() + if tidy(processes, now): + processes = wine_processes(pfx) + games = sorted({program(argv) for _, argv in processes if is_game(argv)}) + if games: + if not seen: + say("game running: %s" % ", ".join(games)) + seen, gone_at = True, None + elif seen or not any(is_client(argv) for _, argv in processes): + gone_at = gone_at if gone_at is not None else now + if now - gone_at >= grace: + say("the game has exited" if seen else "Battle.net closed before a game started") + return seen + else: + gone_at = None + asked = now if asked is None else asked + if ask is not None and asks < LAUNCH_ASKS and now - asked >= LAUNCH_WAIT: + say("Battle.net has not started the game yet; asking again") + ask() + asked, asks = now, asks + 1 + time.sleep(POLL if poll is None else poll) + + +def launch(root, code): + pfx = os.path.join(prefix(root), "pfx") + client = os.path.join(client_dir(root), CLIENT) + if not installed(root) or not os.path.isfile(client): + say("Battle.net is not installed; %s is not launched" % code) + notify("Battle.net is not installed", "Install it from its tile on DroidDeck's Desktop tab.", "dialog-error") + return 1 + lock = acquire() + try: + own = None + if lock is not None and not running(pfx): + answer = ask_fex(os.environ.get("BL_LAUNCH_DIR")) + say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) + verb = None if stop_leftovers(pfx) else "run" + configure(root, LIBRARY) + own = start(launcher(root), verb) + if own is None: + return 127 + if not wait_ready(pfx): + say("Battle.net did not open; %s is not launched" % code) + notify("Battle.net did not start", "The session's desktop.log says why.", "dialog-error") + return 1 + if code.lower().startswith("wow"): + wow_settings(root) + say("launching %s" % code) + spawn(client, "run", ["--exec=launch %s" % code]) + played = follow(pfx, ask=lambda: spawn(client, "run", ["--exec=launch %s" % code])) + if own is not None: + leftovers = wine_processes(pfx) + say("stopping what the Battle.net opened for %s left: %d process(es)" % (code, len(leftovers))) + stop(leftovers) + try: + own.wait(timeout=STOP_WAIT * 4) + except subprocess.TimeoutExpired: + say("its Proton is still ending") + return 0 if played else 1 + finally: + if lock is not None: + lock.close() + + +def hand_over(root, args, wait=None): + if not wait_ready(os.path.join(prefix(root), "pfx"), wait=HANDOVER_WAIT if wait is None else wait): + say("Battle.net did not come up; %s not asked for" % " ".join(args)) + return False + spawn(os.path.join(client_dir(root), CLIENT), "run", args) + return True + + +def install_game(root, uid): + args = ["--install", "--game=%s" % uid] + if installed(root) and agent_up(wine_processes(os.path.join(prefix(root), "pfx"))): + say("asking the open Battle.net to install %s" % uid) + spawn(os.path.join(client_dir(root), CLIENT), "run", args) + return 0 + lock = acquire() + if lock is None: + say("another start holds the lock") + lock = show(root, args=args) + if lock is None: + return 0 + threading.Thread(target=hand_over, args=(root, args), daemon=True).start() + with lock: + return open_client(root) + + +def agent_exe(root): + folder = os.path.join(drive_c(root), *AGENT_DIR) + try: + names = os.listdir(folder) + except OSError: + return None + builds = sorted(((int(m.group(1)), name) for name in names for m in [AGENT_BUILD.fullmatch(name)] if m), reverse=True) + for _, name in builds: + exe = os.path.join(folder, name, "Agent.exe") + if os.path.isfile(exe): + return exe + return None + + +def agent_port(root): + try: + with open(os.path.join(drive_c(root), *AGENT_DIR, "Agent.dat"), encoding="ascii", errors="replace") as f: + text = f.read().strip() + except OSError: + return None + return int(text) if AGENT_PORT.fullmatch(text) else None + + +def answers(port, timeout=2): + try: + conn = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout) + try: + conn.request("GET", "/agent", headers={"User-Agent": "phoenix-agent/1.0"}) + conn.getresponse().read() + finally: + conn.close() + return True + except (OSError, http.client.HTTPException): + return False + + +def agent_env(): + env = proton_env() + env["PROTON_USE_XALIA"] = "0" + return env + + +def agent_failed(status, reason): + say(reason) + try: + with open(status.replace("\\", "/")[2:] + ".error", "w", encoding="utf-8") as f: + f.write(reason) + except OSError: + pass + + +def agent_serve(root, args, wait=None, poll=None): + exe = agent_exe(root) + if exe is None: + agent_failed(args[-1], "no Blizzard Agent in the Battle.net prefix") + return 3 + cmd = [PROTON_RUN, "--prefix", APP_ID, "--verb", "run"] + say("starting Blizzard's Agent on its own: %s" % exe) + try: + agent = subprocess.Popen(cmd + [exe, "--internalclienttools"], stdin=subprocess.DEVNULL, env=agent_env()) + except OSError as error: + say("%s: %s" % (PROTON_RUN, error)) + return 127 + deadline = time.monotonic() + (AGENT_START if wait is None else wait) + port = None + while time.monotonic() < deadline: + port = agent_port(root) + if port and answers(port): + break + if agent.poll() is not None and not any(program(argv) == AGENT for _, argv in wine_processes(os.path.join(prefix(root), "pfx"))): + agent_failed(args[-1], "the Agent exited before it answered") + return 4 + port = None + time.sleep(POLL if poll is None else poll) + if port is None: + agent_failed(args[-1], "the Agent did not answer in time") + return 4 + helper = os.path.join(CACHE, AGENT_HELPER) + with open(helper, "w", encoding="utf-8") as f: + f.write(AGENT_SCRIPT) + cscript = os.path.join(drive_c(root), "windows", "system32", "cscript.exe") + say("the Agent answers on port %d; %s %s" % (port, args[0], args[1])) + return subprocess.call(cmd + [cscript, "//nologo", "Z:" + helper.replace("/", "\\"), str(port)] + list(args), env=agent_env()) + + +def emit(kind, value=""): + print(("%s_%s %s" % (REPORT, kind, value)).rstrip(), flush=True) + + +def read_status(path): + try: + with open(path, "rb") as f: + data = f.read() + except OSError: + return None + for encoding in ("utf-16", "utf-8-sig"): + try: + value = json.loads(data.decode(encoding)) + except (UnicodeDecodeError, ValueError): + continue + if isinstance(value, dict): + return value + return None + + +def summary(status): + out = {key: status[key] for key in REPORTED if key in status} + for key in ("download_current", "download_total"): + value = status.get(key) + if isinstance(value, list) and value and isinstance(value[0], (int, float)): + out[key] = value[0] + phase = (status.get("extended_status") or {}).get("state") + if isinstance(phase, int): + out["phase"] = phase + eta = out.get("estimated_time_in_sec") + if not isinstance(eta, int) or not 0 <= eta <= ETA_LIMIT: + out.pop("estimated_time_in_sec", None) + return out + + +def agent_job(root, action, uid, product="", folder="", locale="enUS", country="USA", region="US", poll=None, wait=None): + pfx = os.path.join(prefix(root), "pfx") + if not installed(root) or agent_exe(root) is None: + emit("ERROR", "client") + return 3 + windows = "" + if action == "install": + if not folder.startswith("/") or any(c in folder for c in '"\\\n'): + emit("ERROR", "folder") + return 2 + try: + os.makedirs(folder, exist_ok=True) + except OSError as error: + say("%s not made: %s" % (folder, error)) + emit("ERROR", "folder") + return 2 + windows = "Z:" + folder + told = None + while True: + processes = wine_processes(pfx) + busy = bool(processes) and not idle(processes) + lock = None if busy else acquire() + if lock is not None: + break + state = "waiting" if busy else "queued" + if told != state: + say("%s; the %s of %s waits for it" % ("Battle.net or a game is open" if busy else "another Battle.net job holds the prefix", + action, uid)) + emit("STATE", state) + told = state + time.sleep(POLL if poll is None else poll) + with lock: + stop_leftovers(pfx) + emit("STATE", "starting") + base = os.path.join(CACHE, "agent-%s" % uid) + for suffix in (".json", ".game", ".form", ".error"): + try: + os.unlink(base + suffix) + except OSError: + pass + runtime = os.path.join(CACHE, AGENT_RUNTIME) + os.makedirs(runtime, mode=0o700, exist_ok=True) + env = agent_env() + for name in ("DISPLAY", "WAYLAND_DISPLAY"): + env.pop(name, None) + env["XDG_RUNTIME_DIR"] = runtime + cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-", + windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")] + say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd))) + output = os.path.join(CACHE, AGENT_LOG) + try: + if os.path.getsize(output) > AGENT_LOG_LIMIT: + os.replace(output, output + ".1") + except OSError: + pass + with open(output, "ab") as log: + try: + child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env) + except OSError as error: + emit("ERROR", "stopped gamescope: %s" % error) + return 1 + seen = None + while True: + done = child.poll() is not None + status = read_status(base + ".json") + if status is not None and action != "uninstall": + brief = summary(status) + if brief != seen: + emit("PROGRESS", json.dumps(brief, sort_keys=True)) + seen = brief + if done: + break + time.sleep(POLL if poll is None else poll) + leftovers = wine_processes(pfx) + if leftovers and idle(leftovers): + stop(leftovers) + answer = read_status(base + ".game") + game = answer or {} + status = read_status(base + ".json") or {} + try: + with open(base + ".error", "rb") as f: + data = f.read() + reason = data.decode("utf-16" if data[:2] in (b"\xff\xfe", b"\xfe\xff") else "utf-8", "replace").strip() \ + or "the agent stopped answering" + except OSError: + reason = None + code = status.get("error") + if reason is None and isinstance(code, int) and code > 0: + emit("ERROR", "agent %d" % code) + say("the %s of %s stopped: Agent error %d" % (action, uid, code)) + return 5 + if reason is None and action != "uninstall" and game.get("installed") is True \ + and (game.get("playable") is True or status.get("state") == DONE_STATE): + binary = ((game.get("binaries") or {}).get("game") or {}).get("relative_path", "") + emit("DONE", json.dumps({"install_dir": game.get("install_dir", windows), "exe": binary, + "version": game.get("local_version", "")}, sort_keys=True)) + say("%s %s in %s" % (uid, "updated" if action == "update" else "installed", game.get("install_dir", windows))) + return 0 + if reason is None and action == "uninstall" and (game.get("installed") is False or answer == {}): + emit("DONE", json.dumps({"uninstalled": uid})) + say("%s uninstalled" % uid) + return 0 + reason = reason or "exit %d" % child.returncode + say("the %s of %s stopped: %s" % (action, uid, reason)) + emit("ERROR", "stopped %s" % reason.replace("\n", " ")) + return 1 + + +def main(argv): + global LIBRARY + argv = list(argv) + if len(argv) >= 2 and argv[0] == "--library": + if not argv[1].startswith("/") or "\n" in argv[1]: + say("%s is not a folder" % argv[1]) + return 2 + LIBRARY = os.path.normpath(argv[1]) + argv = argv[2:] + action = argv[0] if argv else "open" + if action == "agent-serve" and len(argv) == 9: + return agent_serve(steam_root(), argv[1:]) + if action == "agent-install" and len(argv) == 7 and GAME_UID.fullmatch(argv[1]) and PRODUCT.fullmatch(argv[2]) and argv[3].startswith("/") \ + and LOCALE.fullmatch(argv[4]) and COUNTRY.fullmatch(argv[5]) and REGION.fullmatch(argv[6]): + return agent_job(steam_root(), "install", argv[1], argv[2], os.path.normpath(argv[3]), argv[4], argv[5], argv[6]) + if action in ("agent-update", "agent-uninstall") and len(argv) == 2 and GAME_UID.fullmatch(argv[1]): + return agent_job(steam_root(), action[len("agent-"):], argv[1]) + launching = action == "launch" and len(argv) == 2 and CODE.fullmatch(argv[1]) + getting = action == "install-game" and len(argv) == 2 and GAME_UID.fullmatch(argv[1]) + if not (launching or getting) and (action not in ("open", "install", "status") or len(argv) > 1): + say("usage: droiddeck-battlenet [--library DIR] [open | install | status | launch CODE | install-game ID | " + "agent-install ID PRODUCT DIR LOCALE COUNTRY REGION | agent-update ID | agent-uninstall ID]") + return 2 + root = steam_root() + if action == "status": + print(json.dumps(status(root))) + return 0 + gpu = desktop_gpu() + if gpu: + say("the desktop starts Battle.net on the GPU") + os.execv(gpu, [gpu, os.path.abspath(sys.argv[0])] + list(sys.argv[1:])) + os.environ["BL_BATTLENET"] = "1" + if launching: + say("launch %s" % argv[1]) + return launch(root, argv[1]) + if getting: + say("install-game %s" % argv[1]) + return install_game(root, argv[1]) + say("%s (%s)" % (action, "from the menu" if not sys.stderr.isatty() else "from a terminal")) + lock = acquire() + if lock is None: + say("another start holds the lock") + lock = show(root) + if lock is None: + return 0 + with lock: + return open_client(root, reinstall=action == "install") + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index 6ca792143d..7db59b048c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -11,6 +11,7 @@ import shutil import struct import subprocess import sys +import time HOME = os.environ.get("HOME") or "/root" STEAM_ROOT = os.path.join(HOME, ".local", "share", "Steam") @@ -27,6 +28,8 @@ PRELOADS = "/usr/local/lib/droiddeck-fex" URUNTIME = "/usr/local/lib/droiddeck/uruntime" HOST_PRELOAD = "/etc/ld.so.preload" FEX_APPID = "3127680" +OWN_FEX = "/usr/local" +OWN_FEX_TAG = os.path.join(OWN_FEX, "share", "fex-emu", ".droiddeck-tag") SNIPER_APPID = "1628350" SLR4_APPID = "4183110" INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper", SLR4_APPID: "SteamLinuxRuntime_4"} @@ -152,8 +155,52 @@ def first_dir(prefix, candidates): return None +def own_fex_loads(): + for name in ("FEX", "FEXServer"): + binary = os.path.join(OWN_FEX, "bin", name) + if not os.access(binary, os.X_OK): + return False + try: + listed = subprocess.run(["/usr/lib/ld-linux-aarch64.so.1", "--list", binary], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=20) + except (OSError, subprocess.TimeoutExpired): + return False + if listed.returncode != 0 or b"not found" in listed.stdout: + return False + return True + + +def update_own_fex(): + wanted = os.environ.get("BL_FEX_TAG") + if not wanted: + return + if (read_text(OWN_FEX_TAG) or "").strip() == wanted and own_fex_loads(): + return + failed = os.path.join(STATE, "update-failed") + try: + if (read_text(failed) or "").strip() == wanted and time.time() - os.path.getmtime(failed) < 3600: + return + except OSError: + pass + say("installing DroidDeck's FEX build %s" % wanted) + try: + code = subprocess.call([os.path.join(BIN_DIR, "droiddeck-fex-update")], stdout=sys.stderr) + except OSError: + code = 1 + if code == 0: + with contextlib.suppress(OSError): + os.remove(failed) + return + with contextlib.suppress(OSError): + with open(failed, "w", encoding="utf-8") as handle: + handle.write(wanted + "\n") + say("DroidDeck's FEX build %s did not install; using the FEX already here" % wanted) + + def fex_install(): prefixes = [] + if os.path.isfile(OWN_FEX_TAG) and own_fex_loads(): + prefixes.append((OWN_FEX, False)) tool = app_dir(FEX_APPID) if tool: prefixes += [(os.path.join(tool, sub), True) for sub in ("usr", "", "files/usr", "files")] @@ -445,6 +492,7 @@ def describe(fex, platform, graphics=None): def prepare(app=SNIPER_APPID): with locked(): + update_own_fex() fex = fex_install() platform = runtime_platform(app) status = describe(fex, platform) @@ -730,6 +778,7 @@ def extracted(): def want_fex(): with locked(): + update_own_fex() status = describe(fex_install(), runtime_platform(), graphics_platform()) if not status["ready"]: request_install() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update new file mode 100755 index 0000000000..3611978f54 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update @@ -0,0 +1,81 @@ +#!/bin/bash +FEX_TAG=fex-2610-r5 +FEX_SHA256=0fc1ca2ba13817ad70d1ea157119a75c9c02446b57d166e6d676cce0807c19c4 +FEX_URL=https://github.com/Droid-Deck/DroidDeck-Components/releases/download/$FEX_TAG/fex.tzst + +# Whether every program in the FEX tree at $1 finds its libraries (r4 did not without libxxhash). +fex_loads() { + local b out + for b in FEX FEXServer unsquashfs; do + out=$(/usr/lib/ld-linux-aarch64.so.1 --list "$1/usr/local/bin/$b" 2>&1) && ! grep -q "not found" <<<"$out" && continue + echo "== FEX check: $b: $(grep -E "not found|error" <<<"$out" | tr -s '\t ' ' ' | tr '\n' ';')" >&2 + return 1 + done +} + +# Installs one FEX build only once its archive matches the sha256 and it loads. The files it replaces are kept +# until the installed copy loads too, and put back otherwise; the tag is written last. +fex_install() { + local tag=$1 sha=$2 urls=$3 dst=/ tmp u f + tmp=$(mktemp -d) + for u in $urls; do + curl -fsSL --retry 2 --connect-timeout 20 --speed-limit 1024 --speed-time 60 "$u" -o "$tmp/fex.tzst" && echo "$sha $tmp/fex.tzst" | sha256sum -c --quiet >/dev/null 2>&1 && break + rm -f "$tmp/fex.tzst" + done + if [ ! -s "$tmp/fex.tzst" ]; then + echo "== FEX $tag: no source gave the archive with sha256 ${sha:0:12}" >&2 + rm -rf "$tmp" + return 1 + fi + if ! { mkdir "$tmp/root" && zstd -dc "$tmp/fex.tzst" | tar -C "$tmp/root" -x && fex_loads "$tmp/root"; }; then + rm -rf "$tmp" + return 1 + fi + (cd "$tmp/root" && find . ! -type d) > "$tmp/files" + mkdir "$tmp/old" + while IFS= read -r f; do + f=${f#./} + if [ -e "$dst$f" ] || [ -L "$dst$f" ]; then + cp -a --parents "$dst$f" "$tmp/old" || { echo "== FEX $tag: could not keep $dst$f aside" >&2; rm -rf "$tmp"; return 1; } + fi + done < "$tmp/files" + if tar -C "$tmp/root" -c . | tar -C "$dst" -x && fex_loads "$dst" && + mkdir -p "${dst}usr/local/share/fex-emu" && echo "$tag" > "${dst}usr/local/share/fex-emu/.droiddeck-tag"; then + rm -rf "$tmp" + return 0 + fi + echo "== FEX $tag: the installed copy did not load or its tag was not written; putting the previous files back" >&2 + while IFS= read -r f; do + f=${f#./} + [ -e "$tmp/old/$dst$f" ] || [ -L "$tmp/old/$dst$f" ] || rm -f "$dst$f" + done < "$tmp/files" + tar -C "$tmp/old$dst" -c . | tar -C "$dst" -x || echo "== FEX $tag: could not put the previous files back" >&2 + rm -rf "$tmp" + return 1 +} + +# The build DroidDeck-Components' fex.json names (the app passes it as BL_FEX_*) comes first, then a working +# installed one, then FEX_TAG above. Sets FEX_NOW and FEX_FROM. +fex_ready() { + local have ok= + have=$(cat /usr/local/share/fex-emu/.droiddeck-tag 2>/dev/null || true) + [ -x /usr/local/bin/FEX ] && fex_loads / && ok=1 + if [ -n "${BL_FEX_TAG:-}" ]; then + if [ -n "$ok" ] && [ "$have" = "$BL_FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=catalog; return 0; fi + step "downloading FEX ($BL_FEX_TAG)" + if fex_install "$BL_FEX_TAG" "${BL_FEX_SHA256:-}" "${BL_FEX_URLS:-}"; then FEX_NOW=$BL_FEX_TAG FEX_FROM=catalog; return 0; fi + if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $BL_FEX_TAG did not install"; return 0; fi + fi + if [ -n "$ok" ] && [ "$have" = "$FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=built-in; return 0; fi + step "downloading FEX ($FEX_TAG)" + if fex_install "$FEX_TAG" "$FEX_SHA256" "$FEX_URL"; then FEX_NOW=$FEX_TAG FEX_FROM=built-in; return 0; fi + if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $FEX_TAG did not install"; return 0; fi + return 1 +} + +if [ "${BASH_SOURCE[0]}" = "$0" ]; then + set -eu + step() { echo "== STEP $*" >&2; } + fex_ready || exit 1 + echo "$FEX_NOW ($FEX_FROM)" +fi diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup b/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup index 24806fa2e8..534a4f7d38 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup @@ -3,6 +3,7 @@ set -u export LANG=C.UTF-8 step() { echo "== STEP $*"; } fail() { echo "== FAIL $*"; exit 1; } +[ "$(id -u)" = 0 ] || fail "needs root: install Flatpak from the launcher's Store, which runs this as root" PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy" while read -r pkg probe; do @@ -24,6 +25,7 @@ NEEDS WORK=/var/cache/droiddeck-flatpak CONF=$WORK/pacman.conf mkdir -p "$WORK/pkg" "$WORK/db" || fail "cannot create $WORK" +exec 9>"$WORK/setup.lock" && flock -n 9 || fail "another Flatpak setup is still running" OVERSEAS="https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org" MAINLAND="" @@ -48,10 +50,14 @@ if [ ! -f /etc/pacman.d/gnupg/pubring.gpg ] && [ ! -f /etc/pacman.d/gnupg/pubrin fi step "Reading the package lists" -pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy >/dev/null 2>&1 \ - || pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1 | tail -3 \ - || fail "could not reach the Arch Linux ARM mirrors" -[ -f "$WORK/db/sync/extra.db" ] || fail "could not reach the Arch Linux ARM mirrors" +rm -f "$WORK/db/db.lck" +sync_log=$(pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1) \ + || sync_log=$(pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1) +if [ ! -f "$WORK/db/sync/extra.db" ]; then + printf '%s\n' "$sync_log" | tail -3 + reason=$(printf '%s\n' "$sync_log" | grep -m1 -i '^error' | cut -c1-160) + fail "could not reach the Arch Linux ARM mirrors${reason:+ ($reason)}" +fi step "Downloading Flatpak" out=$(pacman --config "$CONF" --dbpath "$WORK/db" --cachedir "$WORK/pkg" --noconfirm -Sw -dd $PACKAGES 2>&1) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 505b75e02c..288c8d57c2 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -103,10 +103,19 @@ def godot_vulkan(game): @fix def godot_sentry(game): sentry = sorted(n[:-4] for n in game.files if n.startswith("libsentry.windows.") and n.endswith(".dll")) - if is_godot(game) and sentry: + if is_godot(game) and sentry and ("coreclr.dll" in game.files or "godotsharp.dll" in game.files): return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off" +@fix +def d3dgear_hook(game): + """D3DGear's capture DLL left beside a game (The Crew 2) is loaded by it and hooks the DXGI swapchain; + under Wine the hook faults over a thousand times within seconds and the game never presents again: + black screen while the sound keeps playing.""" + if "d3dgear64.dll" in game.files: + return {"WINEDLLOVERRIDES": "d3dgear64=d"}, [], "D3DGear capture hook off (it stops the game drawing)" + + @fix def deep_rock_gdk_raytracing(game): if game.stem == "fsd-wingdk-shipping" and not any(game.has_arg(arg) for arg in ("-raytracing", "-noraytracing")): @@ -122,12 +131,32 @@ def arkham_city_x87(game): +@fix +def protonfixes_off(game): + if game.stem in ("blackops3", "darksoulsremastered"): + return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)" + + @fix def caravan_sandwitch_feature_level(game): if "caravansandwitch.exe" in game.files or game.stem == "caravansandwitch-win64-shipping": return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "Caravan SandWitch: D3D12 feature level 12_1 (12_2 hands it mesh shader pipelines vkd3d-proton cannot build)" +@fix +def robocop_rogue_city_feature_level(game): + """vkd3d-proton turns mesh shaders off on Adreno, but 12_2 still advertises them, and UE5 then builds mesh + pipelines with no pipeline layout that crash Turnip on launch.""" + if "robocop.exe" in game.files or game.stem == "robocop-win64-shipping": + return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "RoboCop: Rogue City: D3D12 feature level 12_1" + + +@fix +def reskate_feature_level(game): + if "skate.exe" in game.files and "reskate.dll" in game.files: + return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "ReSkate (skate.): D3D12 feature level 12_1" + + @fix def cyberpunk_feature_level(game): if game.stem == "cyberpunk2077" or ( @@ -240,7 +269,10 @@ def engine_fixes(exe, args): for check in FIXES: found = check(game) if found: - env.update(found[0]) + for name, value in found[0].items(): + if name == "WINEDLLOVERRIDES" and env.get(name): + value = env[name] + ";" + value + env[name] = value extra += found[1] notes.append(found[2]) return env, extra, notes @@ -273,6 +305,78 @@ def game_gpu(env): return result +def vram_cap(env): + """Puts the session's VRAM cap ahead of the game's own DXVK settings, so a game profile can still raise it.""" + value = env.get("BL_VRAM_MB", "") + if not re.fullmatch(r"[1-9][0-9]{0,6}", value): + return env + result = env.copy() + cap = "dxgi.maxDeviceMemory = %d" % int(value) + own = result.get("DXVK_CONFIG", "").strip().strip(";").strip() + result["DXVK_CONFIG"] = cap + "; " + own if own else cap + return result + + +def parse_cores(text): + """CPU numbers from a list such as "0-3,6"; None when the text is not one.""" + cores = set() + for part in text.replace(" ", "").split(","): + match = re.fullmatch(r"(\d{1,3})(?:-(\d{1,3}))?", part) + if not match: + return None + first, last = int(match.group(1)), int(match.group(2) or match.group(1)) + if last < first: + return None + cores.update(range(first, last + 1)) + return cores or None + + +def online_cores(): + try: + with open("/sys/devices/system/cpu/online") as f: + cores = parse_cores(f.read().strip()) + except OSError: + cores = None + return cores or os.sched_getaffinity(0) | set(range(os.cpu_count() or 0)) + + +def game_cores(env): + """Pins the game to the cores its profile names, in place of the session's game cores.""" + text = env.get("DROIDDECK_GAME_CORES", "").strip() + if not text: + return + cores = parse_cores(text) + chosen = cores & online_cores() if cores else None + if not chosen: + print("droiddeck-game-env: ignoring game cores %r" % text, file=sys.stderr) + return + try: + os.sched_setaffinity(0, chosen) + print("droiddeck-game-env: game cores %s" % ",".join(map(str, sorted(chosen))), file=sys.stderr) + except OSError as error: + print("droiddeck-game-env: could not use game cores %r (%s)" % (text, error), file=sys.stderr) + + +def cpu_topology(env): + if "PROTON_CPU_TOPOLOGY" in env: + return + if "WINE_CPU_TOPOLOGY" in env: + if env["WINE_CPU_TOPOLOGY"]: + env["PROTON_CPU_TOPOLOGY"] = env["WINE_CPU_TOPOLOGY"] + return + if not (env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("BL_GAME_CPUS", "").strip()): + return + try: + cores = sorted(os.sched_getaffinity(0)) + except OSError: + return + online = online_cores() + if not cores or set(cores) >= online or cores[-1] >= len(online): + return + env["WINE_CPU_TOPOLOGY"] = env["PROTON_CPU_TOPOLOGY"] = "%d:%s" % (len(cores), ",".join(map(str, cores))) + print("droiddeck-game-env: Windows sees %d cores (%s)" % (len(cores), env["WINE_CPU_TOPOLOGY"]), file=sys.stderr) + + def apply_config(env, config, app_id, fixes=None): if config.get("version") != 1: raise ValueError("unsupported environment configuration") @@ -546,7 +650,10 @@ def main(): command = offline_without_anticheat(command, env) if mic_enabled == "0": env["BANNER_AUDIO_DIRECT_MIC"] = "0" + env = vram_cap(env) env = force_ssbs(command, env) + game_cores(env) + cpu_topology(env) try: xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox"))) except Exception as error: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-gpu-window b/tools/linuxfs/overlay/usr/local/bin/droiddeck-gpu-window index f5cb4007cb..0c1c9818f6 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-gpu-window +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-gpu-window @@ -45,6 +45,13 @@ def advertise_compositing(): if __name__ == '__main__': if len(sys.argv) < 2: raise SystemExit('usage: droiddeck-gpu-window <program> [args...]') + if 'BL_GPU_CHILD_WSI' in os.environ: + wsi = os.environ.pop('BL_GPU_CHILD_WSI') + if wsi: + os.environ['MESA_VK_WSI_DEBUG'] = wsi + else: + os.environ.pop('MESA_VK_WSI_DEBUG', None) + os.environ['SDL_VIDEODRIVER'] = 'x11' os.environ.setdefault('GTK_CSD', '1') try: connection = advertise_compositing() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-open b/tools/linuxfs/overlay/usr/local/bin/droiddeck-open index 0809a228f7..2fc023e041 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-open +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-open @@ -9,9 +9,9 @@ Add an app does) when that holds native programs or libraries. A Steam library's droiddeck-open --exec FILE [ARGS...] an exec the kernel refused (libblsession) droiddeck-open --install the Run entries and default handlers -The desktop composites in software, so a program started from it goes full screen on the GPU -(droiddeck-gpu), as the menu's games do: --window keeps it in a desktop window instead, --terminal -runs it in Konsole. A plain script stays on the desktop, and an exec whose output is read (a terminal, +The desktop composites in software, so a program started from it runs on the GPU in a window of its +own (droiddeck-gpu), as the menu's games do: --window keeps it on the desktop's software drawing +instead, --terminal runs it in Konsole. A plain script stays on the desktop, and an exec whose output is read (a terminal, a pipe, a file) stays where it was started. """ import fcntl @@ -337,7 +337,7 @@ def unattended(env): def placed(cmd, what, mode, env): - """[cmd] where it shows: full screen on the GPU from the desktop, else where it was started.""" + """[cmd] where it shows: on the GPU from the desktop, else where it was started.""" if mode == "terminal" and what not in ("windows", "steam") and shutil.which("konsole"): return ["konsole", "--hold", "-e"] + cmd if mode == "window" or what in ("script", "steam") or not on_desktop(env): diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-proton-run b/tools/linuxfs/overlay/usr/local/bin/droiddeck-proton-run index 5d59829bf1..624d420741 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-proton-run +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-proton-run @@ -1,7 +1,7 @@ #!/usr/bin/python3 """Runs a Windows program with the Proton the Steam client has chosen for it. - droiddeck-proton-run [--window] PROGRAM [ARGS...] + droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...] droiddeck-proton-run --app ID [--dir FOLDER] [--options TEXT] [PROGRAM [ARGS...]] The program belongs to an installed Steam game when it sits in one's folder, to a prefix when it @@ -10,10 +10,15 @@ its own, under the id the client gives a new shortcut. That title's CompatToolMa config.vdf picks the tool, else the client's default for all other titles ("0"). The tool is started as the client starts it - its toolmanifest's command line, the waitforexitandrun verb and the STEAM_COMPAT_* environment - so its wrapper applies the game's settings, components and audio. ---window keeps the program in the desktop's own window, drawn with WineD3D. +--window keeps the program in the desktop's own window, drawn with WineD3D on the desktop's software +GL (llvmpipe): KWin there composites in software, and the session's zink finds no device. +--prefix ID puts the program in compatdata/ID whatever it is. --verb run starts it beside what already +runs in the prefix, which waitforexitandrun would wait for; the wrapper's launch-time steps are skipped. +--game-id ID keeps the id of the launch it runs for: gamescope shows the windows that carry the id Steam launched. --app starts one game without the Steam client (its Start without Steam): a Steam game's default Windows launch option from appinfo.vdf when no program is given, else the program in that -shortcut's own prefix, started in --dir with the shortcut's launch options (--options). +shortcut's own prefix, started in --dir with the shortcut's launch options (--options). Without +--options it takes the launch options set in the client's Properties for that game or shortcut. """ import json import os @@ -30,7 +35,10 @@ BIN_DIR = os.path.dirname(os.path.abspath(__file__)) STATE = os.path.join(HOME, ".local", "share", "droiddeck-compat", "state.json") EXTRA_LIBRARIES = ("/mnt/droiddeck", "/mnt/droiddeck-sd") SYSTEM_TOOLS = ("/usr/share/steam/compatibilitytools.d", "/usr/local/share/steam/compatibilitytools.d") +DESKTOP_GL = {"LIBGL_ALWAYS_SOFTWARE": "1", "GALLIUM_DRIVER": "llvmpipe"} +NOT_DESKTOP_GL = ("MESA_LOADER_DRIVER_OVERRIDE", "LIBGL_KOPPER_DRI2") VERB = "waitforexitandrun" +VERBS = (VERB, "run") SHORTCUT_BIT = 0x80000000 STEAM_APP_LIMIT = 2 ** 31 @@ -185,9 +193,9 @@ def steam_game(program, libs): def prefix_of(program): for folder, below in ancestors(program): parent = os.path.dirname(folder) - if below == "pfx" and os.path.basename(parent) == "compatdata" and os.path.basename(folder).isdigit(): + if below == "pfx" and os.path.basename(parent) == "compatdata" and re.fullmatch(r"-?[0-9]+", os.path.basename(folder)): library = os.path.dirname(os.path.dirname(parent)) - return Target(os.path.basename(folder), folder, os.path.dirname(program), library, "prefix") + return Target(str(int(os.path.basename(folder)) % 2 ** 32), folder, os.path.dirname(program), library, "prefix") return None @@ -230,10 +238,68 @@ def shortcut_entries(root): return entries +def prefix_folder(root, appid): + """The prefix folder the client made for [appid], under either spelling of the id.""" + folder = os.path.join(root, "steamapps", "compatdata") + try: + names = sorted(os.listdir(folder)) + except OSError: + names = [] + candidates = [] + for name in names: + if not re.fullmatch(r"-?[0-9]+", name): + continue + try: + matches = int(name) % 2 ** 32 == appid % 2 ** 32 + except ValueError: + continue + match = os.path.join(folder, name) + if matches and os.path.isdir(match): + candidates.append((os.path.isdir(os.path.join(match, "pfx")), + name == str(appid % 2 ** 32), name, match)) + if candidates: + return min(candidates, key=lambda item: (not item[0], not item[1], item[2]))[3] + return os.path.join(folder, str(appid % 2 ** 32)) + + +def vdf_string(token): + return re.sub(r'\\(.)', r'\1', token[1:-1]) if token.startswith('"') else "" + + +def steam_options(app, root): + """The launch options the client keeps for a game (localconfig.vdf) or a shortcut (shortcuts.vdf).""" + try: + tool = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-steam-shortcuts")) + account = tool["account_dir"](root) + if not account: + return "" + if int(app) >= STEAM_APP_LIMIT: + with open(os.path.join(account, "config", "shortcuts.vdf"), "rb") as f: + shortcuts = tool["parse"](f.read()).get("shortcuts", {}) + for value in shortcuts.values(): + if isinstance(value, dict) and (value.get("appid", value.get("AppId")) or 0) & 0xFFFFFFFF == int(app): + options = value.get("LaunchOptions", value.get("launchoptions", "")) + return options if isinstance(options, str) else "" + return "" + tokens = compat()["tokenize"](read_text(os.path.join(account, "config", "localconfig.vdf")) or "") + start = compat()["find_block"](tokens, ["UserLocalConfigStore", "Software", "Valve", "Steam", "apps", app]) + if start is None: + return "" + end, depth = compat()["block_end"](tokens, start), 0 + for i in range(start + 1, end): + if tokens[i] in ("{", "}"): + depth += 1 if tokens[i] == "{" else -1 + elif depth == 0 and tokens[i].lower() == '"launchoptions"' and i + 1 < end: + return vdf_string(tokens[i + 1]) + except (OSError, ValueError, IndexError, KeyError, TypeError, AttributeError, struct.error): + pass + return "" + + def shortcut(program, root): for appid, exe, start in shortcut_entries(root): if same_file(program, exe): - return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), + return Target(appid, prefix_folder(root, appid), os.path.dirname(program), root, "shortcut", start if os.path.isdir(start) else None) return None @@ -250,10 +316,19 @@ def locate(program, root): if found: return found appid = own_id(program) - return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), + return Target(appid, prefix_folder(root, appid), os.path.dirname(program), root, "own") +def fixed(program, root, appid): + return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), + os.path.dirname(program), root, "fixed") + + +def prefix_id(value): + return value if value.isdigit() and not value.startswith("0") and int(value) <= 0xFFFFFFFF else None + + def split_words(text): try: return shlex.split(text or "") @@ -325,7 +400,8 @@ def steam_launch(appid, root): def shortcut_target(appid, program, start, root): - return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), os.path.dirname(program), root, + appid = int(appid) % 2 ** 32 + return Target(str(appid), prefix_folder(root, appid), os.path.dirname(program), root, "shortcut", start if start and os.path.isdir(start) else None) @@ -337,7 +413,7 @@ def steam_launches(target, program, root): return os.path.relpath(program, target.install).replace(os.sep, "/").lower() in entry.get("launch", ()) -def environment(env, target, tool_folder, root, window=False): +def environment(env, target, tool_folder, root, window=False, game_id=None): env = dict(env) steamapps = [os.path.join(lib, "steamapps") for lib in libraries(root)] env.update({ @@ -355,28 +431,52 @@ def environment(env, target, tool_folder, root, window=False): else: game = str(number << 32 | 0x02000000) env.update(SteamAppId="0", STEAM_COMPAT_APP_ID="0", SteamGameId=game, SteamOverlayGameId=game) + if game_id: + env.update(SteamGameId=game_id, SteamOverlayGameId=game_id) if window: env.setdefault("PROTON_USE_WINED3D", "1") + env.update(DESKTOP_GL) + for name in NOT_DESKTOP_GL: + env.pop(name, None) return env -def windows_path(path): +def windows_path(path, compatdata=None): + if compatdata: + drive = os.path.join(compatdata, "pfx", "drive_c") + inside = os.path.relpath(path, drive) + if inside != "." and not inside.startswith(".."): + return "C:\\" + inside.replace("/", "\\") return "Z:" + path.replace("/", "\\") -def arguments(program, args): +def arguments(program, args, desktop=None, compatdata=None): if program.lower().endswith(".msi"): return ["msiexec", "/i", windows_path(program)] + args + if desktop: + return ["explorer.exe", "/desktop=droiddeck,%s" % desktop, windows_path(program, compatdata)] + args return [program] + args def main(argv): window = False - app, start, options = None, None, "" + prefix = None + verb = VERB + game_id = None + desktop = None + app, start, options = None, None, None while argv and argv[0].startswith("--"): option = argv.pop(0) if option == "--window": window = True + elif option == "--prefix" and argv and prefix_id(argv[0]): + prefix = argv.pop(0) + elif option == "--verb" and argv and argv[0] in VERBS: + verb = argv.pop(0) + elif option == "--game-id" and argv and argv[0].isdigit() and argv[0] != "0": + game_id = argv.pop(0) + elif option == "--desktop" and argv and re.fullmatch(r"[1-9][0-9]{2,4}x[1-9][0-9]{2,4}", argv[0]): + desktop = argv.pop(0) elif option in ("--app", "--dir", "--options") and argv: value = argv.pop(0) if option == "--app": @@ -394,9 +494,11 @@ def main(argv): say("%s is not an app id" % app) return 2 if not argv and app is None: - say("usage: droiddeck-proton-run [--window] PROGRAM [ARGS...]") + say("usage: droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]") return 2 root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or STEAM_ROOT + if options is None: + options = steam_options(app, root) if app is not None else "" extra, args = split_options(options) if not argv: if int(app) >= STEAM_APP_LIMIT: @@ -416,6 +518,8 @@ def main(argv): args = args + argv[1:] if app is not None and int(app) >= STEAM_APP_LIMIT: target = shortcut_target(app, program, start, root) + elif prefix: + target = fixed(program, root, prefix) else: target = locate(program, root) available = tools(root) @@ -425,7 +529,7 @@ def main(argv): return 69 folder, command = available[name] os.makedirs(target.compatdata, exist_ok=True) - env = environment(os.environ, target, folder, root, window) + env = environment(os.environ, target, folder, root, window, game_id) env.update(extra) say("%s with %s (%s), %s prefix %s%s" % (program, name, why, target.kind, target.compatdata, ", without the Steam client" if app is not None else "")) @@ -434,7 +538,7 @@ def main(argv): except OSError: os.chdir(os.path.dirname(program)) entry = os.path.join(folder, command) - os.execve(entry, [entry, VERB] + arguments(program, args), env) + os.execve(entry, [entry, verb] + arguments(program, args, desktop, target.compatdata), env) if __name__ == "__main__": diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index e95a7a940a..ada9cba2ec 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -16,7 +16,7 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then fi exec > >({ dd of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1 echo "== droiddeck-session $(date) mode=$mode $*" - echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} fps=${BL_FPS:-0} icd=${VK_ICD_FILENAMES:-none}" + echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}" echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)" echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)" fi @@ -211,13 +211,19 @@ if [ -z "${BL_INSIDE:-}" ]; then width=${BL_WIDTH:-1280} height=${BL_HEIGHT:-720} nested=$width + nested_h=$height if [ "${BL_FOLLOW_OUTPUT:-0}" = 1 ]; then echo "== gamescope: the output follows the screen (${width}x${height} to start)" elif [ "$mode" = steam ] && [ "${BL_GAMESCOPE_STRETCH_16X9:-0}" = 1 ]; then wide=$(( (height * 16 + 4) / 9 / 2 * 2 )) + tall=$(( (width * 9 + 8) / 16 / 2 * 2 )) if [ "$wide" -gt "$width" ]; then nested=$wide - echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output" + elif [ "$tall" -gt "$height" ]; then + nested_h=$tall + fi + if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then + echo "== gamescope: games at ${nested}x${nested_h} stretched to the ${width}x${height} output" fi fi # Off unless Performance asks for it. Compositing the cursor here adds a second @@ -225,12 +231,15 @@ if [ -z "${BL_INSIDE:-}" ]; then if [ "$mode" = steam ] && [ "${BL_CURSOR_COMPOSITE:-0}" = 1 ]; then export gamescope_cursor_composite=2 fi - args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height") - [ "$nested" != "$width" ] && args+=(-S stretch) && export BL_STRETCHED=1 - if [ "${BL_FPS:-0}" -gt 0 ]; then - args+=(-r "$BL_FPS") - elif [ "${BL_REFRESH:-0}" -gt 0 ]; then + args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h") + if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then + args+=(-S stretch) + export BL_STRETCHED=1 + fi + if [ "${BL_REFRESH:-0}" -gt 0 ]; then args+=(-r "$BL_REFRESH") + # -r is the starting rate; gamescope follows the panel when it switches modes later. + export GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST=1 fi [ "$mode" = steam ] && [ "${BL_STEAM_UI:-}" != desktop ] && args+=(-e) if [ "$mode" = steam ] && [ "${BL_XWAYLAND_COUNT:-2}" -gt 1 ]; then @@ -249,6 +258,10 @@ if [ -z "${BL_INSIDE:-}" ]; then echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)" fi export BL_INSIDE=1 + # A fixed path: left to itself gamescope creates a new limiter state file on every start. + rm -f "${XDG_RUNTIME_DIR:-/tmp}"/gamescope-limiter-* + export GAMESCOPE_LIMITER_FILE="${XDG_RUNTIME_DIR:-/tmp}/droiddeck-gamescope-limiter" + rm -f "$GAMESCOPE_LIMITER_FILE" if [ "$mode" = steam ]; then if /usr/local/bin/droiddeck-pipewire start; then eval "$(/usr/local/bin/droiddeck-pipewire env)" @@ -446,49 +459,172 @@ case $mode in fi if [ "${BL_ZRAM:-0}" = 1 ]; then step "zRAM compression: on" + [ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam is not compressed while games run (turned off in Performance)" + _bl_ram_cap=0 + case ${BL_RAM_CAP_MB:-} in + ''|0) ;; + *[!0-9]*|0*|???????*) step "RAM cap: ignored invalid value '$BL_RAM_CAP_MB'" ;; + *) _bl_ram_cap=$((BL_RAM_CAP_MB * 1024)); step "RAM cap: ${BL_RAM_CAP_MB} MB" ;; + esac ( bl_zram_scan() { - _bl_game=0 _bl_pids=() + _bl_game=0 _bl_pids=() _bl_others=() _bl_apps= + local _d _c _args _name _a _id for _d in /proc/[0-9]*; do - # Under FEX the program is FEX's first argument. - { IFS= read -r -d '' _c && case ${_c##*/} in FEX|FEXInterpreter) IFS= read -r -d '' _c ;; esac; } \ - 2>/dev/null < "$_d/cmdline" || continue - case ${_c##*/} in - reaper) _bl_game=1 ;; - steam|steamwebhelper) _bl_pids+=("${_d#/proc/}") ;; + [ "${_d##*/}" != "$BASHPID" ] || continue + _args=() + # Under FEX the program is FEX's first argument. AppId= is its own argument. + while IFS= read -r -d '' _c; do _args+=("$_c"); done 2>/dev/null < "$_d/cmdline" || true + [ "${#_args[@]}" -gt 0 ] || continue + _name=${_args[0]} + if [ "${#_args[@]}" -gt 1 ]; then + case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} ;; esac + fi + case ${_name##*/} in + reaper) + for _a in "${_args[@]}"; do + case $_a in + AppId=769) ;; + AppId=[0-9]*) + _id=${_a#AppId=} + case $_id in *[!0-9]*) ;; *) _bl_game=1; _bl_apps="$_bl_apps $_id" ;; esac + ;; + esac + done + ;; + steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;; + *) _bl_others+=("${_d##*/}") ;; esac done } bl_zram_usage() { local _p _k _v _u _rss=0 _swap=0 - for _p in "${_bl_pids[@]}"; do + for _p in "$@"; do while read -r _k _v _u; do case $_k in VmRSS:) _rss=$((_rss + _v)) ;; VmSwap:) _swap=$((_swap + _v)) ;; esac done 2>/dev/null < "/proc/$_p/status" done - echo "${#_bl_pids[@]} processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB" + _bl_rss=$_rss + echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB" + } + # Only processes that loaded libblsession are the session's own and answer SIGURG. + bl_session_others() { + local _p + _bl_session=() + for _p in "${_bl_others[@]}"; do + grep -q -m1 '/libblsession\.so$' "/proc/$_p/maps" 2>/dev/null && _bl_session+=("$_p") + done + } + bl_zram_pick() { + if [ "$1" = session ]; then + bl_session_others + _pids=("${_bl_session[@]}") + else + _pids=("${_bl_pids[@]}") + fi + } + # Same protocol as SessionSuspendController: an empty ack when the page-out starts, a byte when it is done. + # A process whose SIGURG handler was replaced never acks, so it is not waited for after the first 2 s. + bl_zram_wait() { + local _p _left _start=$SECONDS + while [ $((SECONDS - _start)) -lt 12 ]; do + _left=0 + for _p in "$@"; do + [ -s "/tmp/.bl-zram.ack.$_p" ] && continue + [ -d "/proc/$_p" ] || continue + [ $((SECONDS - _start)) -ge 2 ] && [ ! -e "/tmp/.bl-zram.ack.$_p" ] && continue + _left=1 + done + [ "$_left" = 1 ] || break + nap 0.2 + done + for _p in "$@"; do rm -f "/tmp/.bl-zram.ack.$_p"; done } bl_zram_send() { - step "zRAM: $2 ($(bl_zram_usage))" - printf '%s' "$1" > /tmp/.bl-zram - [ "${#_bl_pids[@]}" = 0 ] || kill -URG "${_bl_pids[@]}" 2>/dev/null - nap 5 + local _mode=$1 _what=$2 _which=$3 _pids _p + bl_zram_pick "$_which" + step "zRAM: $_what ($(bl_zram_usage "${_pids[@]}"))" + for _p in "${_pids[@]}"; do rm -f "/tmp/.bl-zram.ack.$_p"; done + printf '%s' "$_mode" > /tmp/.bl-zram + [ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null + if [ "$_mode" = 1 ]; then bl_zram_wait "${_pids[@]}"; else nap 5; fi bl_zram_scan - step "zRAM: done ($(bl_zram_usage))" + bl_zram_pick "$_which" + step "zRAM: done ($(bl_zram_usage "${_pids[@]}"))" } - _bl_since=-1 _bl_packed=-1 + # Proton starts its reaper before the game window; compressing during launch stalls it. + # Desktop Steam has no focus.json, so it still uses the game process as its trigger. + # A configured RAM cap can still force compression while a game is launching. + bl_game_focused() { + if [ "${BL_DESKTOP:-}" = 1 ] || [ -z "${BL_LAUNCH_DIR:-}" ]; then + return 0 + fi + local id + id=$(sed -n 's/.*"focusedApp"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' \ + "$BL_LAUNCH_DIR/agent/focus.json" 2>/dev/null | head -1) + [ -n "$id" ] || return 1 + case " ${_bl_apps-} " in + *" $id "*) return 0 ;; + esac + return 1 + } + bl_over_cap() { + [ "$_bl_ram_cap" -gt 0 ] || return 1 + _bl_measured=$SECONDS + bl_session_others + bl_zram_usage "${_bl_pids[@]}" "${_bl_session[@]}" > /dev/null + [ "$_bl_rss" -gt "$_bl_ram_cap" ] + } + bl_cap_due() { + [ "$_bl_ram_cap" -gt 0 ] && { [ "$_bl_measured" -lt 0 ] || [ $((SECONDS - _bl_measured)) -ge 30 ]; } + } + _bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30 while kill -0 $$ 2>/dev/null; do bl_zram_scan - if [ "$_bl_game" = 1 ]; then - [ "$_bl_since" -ge 0 ] || _bl_since=$SECONDS - if [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] && + if bl_cap_due; then + if bl_over_cap; then + # A cap below the game's working set cannot be met; paging out again every 30 s only churns. + if [ "$_bl_capped" -lt 0 ] || [ $((SECONDS - _bl_capped)) -ge "$_bl_backoff" ]; then + bl_zram_usage "${_bl_pids[@]}" > /dev/null + if [ "$_bl_rss" -ge $((512 * 1024)) ]; then + bl_zram_send 1 "over the ${BL_RAM_CAP_MB} MB RAM cap, compressing the client" client + [ "$_bl_game" = 1 ] && _bl_packed=$SECONDS + else + step "RAM cap: over, client already small ($((_bl_rss / 1024)) MB resident), skipping it" + fi + bl_over_cap && bl_zram_send 1 "still over the RAM cap, compressing the rest of the session" session + if bl_over_cap; then + _bl_backoff=$((_bl_backoff * 2 > 600 ? 600 : _bl_backoff * 2)) + step "RAM cap: still over after paging out, next try in ${_bl_backoff} s" + else + _bl_backoff=30 + fi + _bl_capped=$SECONDS + fi + else + _bl_backoff=30 + if [ "$_bl_unpack" = 1 ] && [ "$_bl_game" = 0 ]; then + bl_zram_send 0 "back under the RAM cap, reading the client back" client + _bl_unpack=0 + fi + fi + fi + if [ "$_bl_game" = 1 ] && bl_game_focused; then + if [ "$_bl_since" -lt 0 ] || [ "$_bl_since_apps" != "$_bl_apps" ]; then + _bl_since=$SECONDS _bl_since_apps=$_bl_apps + fi + if [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] && { [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 300 ]; }; then - bl_zram_send 1 "compressing the client" + bl_zram_send 1 "compressing the client" client _bl_packed=$SECONDS fi - elif [ "$_bl_since" -ge 0 ]; then - [ "$_bl_packed" -lt 0 ] || bl_zram_send 0 "game closed, reading the client back" + elif [ "$_bl_game" != 1 ]; then + if [ "$_bl_packed" -ge 0 ]; then + if bl_over_cap; then _bl_unpack=1; else bl_zram_send 0 "game closed, reading the client back" client; _bl_unpack=0; fi + fi _bl_since=-1 _bl_packed=-1 + else + _bl_since=-1 fi nap 5 done @@ -808,7 +944,11 @@ BUSCONF echo "== steam: devtools port $BL_CDP_PORT, guest processes only" fi [ -n "${BL_LAUNCH_DIR:-}" ] && mkdir -p "$BL_LAUNCH_DIR/agent" && echo "$BL_CDP_PORT" > "$BL_LAUNCH_DIR/agent/cdp-port" - [ "$steam_x64" = 1 ] || { "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & } + if [ "$steam_x64" = 1 ]; then + { droiddeck-steam-compat --files-only "$steam_root" 2>&1 & } + else + { "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & } + fi _bl_ui=(-gamepadui) [ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=() _bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle=vulkan) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index 73bf29c3e1..ee24ff5829 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat @@ -2,6 +2,7 @@ import base64 import ctypes import json +import math import os import runpy import select @@ -15,6 +16,50 @@ import time HERE = os.path.dirname(os.path.realpath(__file__)) COMPAT = runpy.run_path(os.path.join(HERE, "steam-compatibility")) BINDING = "droiddeckCompatChanged" +BRIGHTNESS_BINDING = "droiddeckBrightnessChanged" +CONTROLS_DIR = "/etc/droiddeck-device-controls" +BRIGHTNESS_JS = r""" +(() => { + if (window.__droiddeckBrightness) return "present"; + const display = SteamClient.System?.Display; + if (!display?.RegisterForBrightnessChanges || !display?.SetBrightness) return "unavailable"; + const self = { expected: null, updating: true, revision: 0 }; + self.set = value => { + if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return; + if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return; + self.expected = value; + self.updating = true; + const revision = ++self.revision; + setTimeout(() => { if (self.revision === revision) self.updating = false; }, 500); + display.SetBrightness(value); + }; + self.subscription = display.RegisterForBrightnessChanges(state => { + const value = state?.flBrightness; + if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1 || self.expected === null) return; + if (Math.abs(value - self.expected) < 0.0001) { self.updating = false; return; } + if (self.updating) { self.updating = false; return; } + self.expected = value; + if (typeof window.__BINDING__ === "function") window.__BINDING__(String(value)); + }); + window.__droiddeckBrightness = self; + return "installed"; +})() +""".replace("__BINDING__", BRIGHTNESS_BINDING) + + +def brightness_request(payload, directory=CONTROLS_DIR): + try: + value = float(payload) + if not math.isfinite(value) or not 0 <= value <= 1: + return + path = os.path.join(directory, "brightness.request") + with open(path + ".tmp", "w") as target: + target.write(str(value) + "\n") + os.replace(path + ".tmp", path) + except (ValueError, TypeError, OSError): + return + + INSTALL_JS = r""" (() => { if (window.__droiddeckCompat) return "present"; @@ -196,6 +241,74 @@ TOUR_JS = r""" return "off"; })() """ +# Steam keeps the Quick Access Frame Limit as the client setting gamescope_app_target_framerate +# (CMsgClientSettings field 21002) and offers the values gamescope's display state lists in +# active_display_info.supported_frame_rates. When the panel's refresh rate changes, a remembered +# limit that is not one of the new values leaves the slider on its first value while the game runs +# at the old limit. The limit is kept when it is still offered and moved to the highest value +# otherwise. Choices are read once they have been unchanged for a moment, since a mode switch can +# report a passing rate first. +FRAME_LIMIT_JS = r""" +(() => { + if (window.__droiddeckFrameLimit) return "present"; + const settings = window.settingsStore; + let service = null; + try { + // Steam's webpack does not expose its module cache; the gamescope service client is found by + // the calls its module makes and loaded by id. + let require; + window.webpackChunksteamui.push([[Symbol("droiddeck-frame-limit")], {}, r => { require = r; }]); + for (const id of Object.keys(require.m || {})) { + const source = String(require.m[id]); + if (!source.includes("SetBlurParams") || !source.includes("RegisterForNotifyStateChanged")) continue; + let exports; + try { exports = require(id); } catch (e) { continue; } + if (!exports || typeof exports !== "object") continue; + service = Object.values(exports).find(value => value && typeof value.GetState === "function" && + typeof value.RegisterForNotifyStateChanged === "function" && typeof value.SetBlurParams === "function"); + if (service) break; + } + } catch (e) { + service = null; + } + if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable"; + const self = { timer: null }; + const write = value => { + const bytes = []; + for (let n of [21002 * 8, value]) { + while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); } + bytes.push(n); + } + return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes))); + }; + self.check = async () => { + let rates; + try { + const reply = await service.GetState({}); + if (!reply.BSuccess()) return; + rates = reply.Body().toObject().state?.active_display_info?.supported_frame_rates; + } catch (e) { + return; + } + if (!Array.isArray(rates) || rates.length === 0) return; + const current = settings.clientSettings; + if (!current.gamescope_enable_app_target_framerate || rates.includes(current.gamescope_app_target_framerate)) return; + try { + await write(Math.max(...rates)); + } catch (e) { + } + }; + self.schedule = () => { + clearTimeout(self.timer); + self.timer = setTimeout(self.check, 1500); + }; + self.subscription = service.RegisterForNotifyStateChanged(self.schedule); + self.interval = setInterval(self.schedule, 5000); + self.schedule(); + window.__droiddeckFrameLimit = self; + return "installed"; +})() +""" FILE_BINDING = "droiddeckOpenFileDialog" FILE_JS = r""" (() => { @@ -620,10 +733,11 @@ class Watcher: class Helper: - def __init__(self, steam_root, port, steamos=False): + def __init__(self, steam_root, port, steamos=False, files_only=False): self.steam_root = steam_root self.port = port self.steamos = steamos + self.files_only = files_only self.page = None self.known = set() self.installed = None @@ -632,6 +746,44 @@ class Helper: self.tools_checked = None self.vr_launch = None self.chooser = None + self.controls_state = None + self.controls_installed = False + self.frame_limit_state = None + self.frame_limit_retry = 0 + + def sync_controls(self): + try: + with open(os.path.join(CONTROLS_DIR, "state.json")) as source: + state = json.load(source) + value = state.get("brightness") + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 1: + return + if not self.controls_installed: + self.page.call("Runtime.addBinding", {"name": BRIGHTNESS_BINDING}) + self.controls_installed = self.page.evaluate(BRIGHTNESS_JS) in ("installed", "present") + if not self.controls_installed: + return + if state != self.controls_state: + if self.page.evaluate("!!window.__droiddeckBrightness && (window.__droiddeckBrightness.set(%s), true)" % json.dumps(value)) is True: + self.controls_state = state + else: + self.controls_installed = False + self.controls_state = None + except (OSError, ValueError, TypeError): + pass + + def sync_frame_limit(self): + # Steam can still be loading its settings and gamescope state when the helper attaches. + if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry: + return + try: + state = self.page.evaluate(FRAME_LIMIT_JS) + except RuntimeError as e: + state = "failed (%s)" % e + if state != self.frame_limit_state: + say("frame limit sync: %s" % state) + self.frame_limit_state = state + self.frame_limit_retry = time.monotonic() + 10 def open_chooser(self, payload): try: @@ -647,9 +799,14 @@ class Helper: self.finish_chooser(ident, None) return command = [sys.executable, os.path.realpath(__file__), "--choose-file"] - reaper = os.path.join(self.steam_root, "steamrtarm64", "reaper") - if os.access(reaper, os.X_OK): - command = [reaper, "SteamLaunch", "AppId=769", "--"] + command + # Gamescope shows the dialog over the client by the AppId on a reaper above it; the x86-64 client has no + # native reaper, so the arm64 client's is borrowed when it is installed. + data = os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share") + for root in (self.steam_root, os.path.join(data, "Steam")): + reaper = os.path.join(root, "steamrtarm64", "reaper") + if os.access(reaper, os.X_OK): + command = [reaper, "SteamLaunch", "AppId=769", "--"] + command + break try: proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, start_new_session=True) @@ -699,6 +856,14 @@ class Helper: try: if page.evaluate("typeof SteamClient === 'object' && typeof SteamClient.WebUITransport === 'object'") is not True: raise LookupError("SteamClient is not ready") + if self.files_only: + page.call("Runtime.addBinding", {"name": FILE_BINDING}) + page.evaluate(FILE_JS) + self.page = page + self.controls_state = None + self.controls_installed = False + self.sync_controls() + return True page.call("Runtime.addBinding", {"name": BINDING}) page.call("Runtime.addBinding", {"name": VR_BINDING}) page.evaluate(VR_JS) @@ -717,6 +882,11 @@ class Helper: page.ws.close() raise self.page = page + self.controls_state = None + self.controls_installed = False + self.frame_limit_state = None + self.frame_limit_retry = 0 + self.sync_controls() return True def reconcile(self): @@ -843,21 +1013,40 @@ class Helper: say("preparing SteamVR for library app(s): " + ", ".join(sorted(vr_games))) self.vr_launch = launch_steamvr() for e in events: + if called(e, BRIGHTNESS_BINDING): + brightness_request(e.get("params", {}).get("payload")) if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str): self.open_chooser(e["params"]["payload"]) return events + def serve_files(self): + say("attached to the client on port %d for its file dialogs" % self.port) + while True: + self.sync_controls() + sources = [self.page.ws] + ([self.chooser[1].stdout] if self.chooser is not None else []) + queued = self.page.ws.pending() or bool(self.page.events) + ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0] + if self.chooser is not None and self.chooser[1].stdout in ready: + self.chooser_done() + if self.page.ws in ready or self.page.events: + self.drain() + def serve(self, watcher): + if self.files_only: + return self.serve_files() with open(COMPAT["state_path"]("live.pid"), "w") as f: f.write("%d\n" % os.getpid()) say("attached to the client on port %d" % self.port) self.reconcile() self.ensure_tools() while True: + self.sync_controls() + self.sync_frame_limit() sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else []) if self.chooser is not None: sources.append(self.chooser[1].stdout) - ready = [self.page.ws] if self.page.ws.pending() else select.select(sources, [], [], 30 if watcher.fileno() >= 0 else 2)[0] + queued = self.page.ws.pending() or bool(self.page.events) + ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0] if self.chooser is not None and self.chooser[1].stdout in ready: self.chooser_done() due = False @@ -903,12 +1092,29 @@ def chooser_main(): def main(): - steam_root = sys.argv[1] + files_only = sys.argv[1:2] == ["--files-only"] + steam_root = sys.argv[2 if files_only else 1] try: port = int(os.environ.get("BL_CDP_PORT", "")) except ValueError: say("no devtools port for this session; the client's mapping is kept through config.vdf") return 0 + if files_only: + helper = Helper(steam_root, port, files_only=True) + failures = 0 + while True: + try: + helper.attach() + failures = 0 + helper.serve(None) + except Exception as e: + helper.close_chooser() + if helper.page is not None: + say("lost the client (%s); reattaching" % e) + helper.page.ws.close() + helper.page = None + failures += 1 + time.sleep(min(2 * max(failures, 1), 10)) os.makedirs(COMPAT["COMPAT_DIR"], exist_ok=True) watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json")] + [os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")]) @@ -943,4 +1149,5 @@ if __name__ == "__main__": try: sys.exit(main()) finally: - detach() + if sys.argv[1:2] != ["--files-only"]: + detach() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 index 8461fdf8a6..17d4490f17 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 @@ -1,8 +1,5 @@ #!/bin/bash set -eu -FEX_TAG=fex-2610-r5 -FEX_SHA256=0fc1ca2ba13817ad70d1ea157119a75c9c02446b57d166e6d676cce0807c19c4 -FEX_URL=https://github.com/Droid-Deck/DroidDeck-Components/releases/download/$FEX_TAG/fex.tzst ROOTFS_URL=https://github.com/Droid-Deck/DroidDeck-Components/releases/download/fex-rootfs-ubuntu-24.04-2026-08-11/Ubuntu_24_04.sqsh ROOTFS_SHA256=2854b06d3ff1b8f6e526135bfb6dd5b7b30ab3ab73e79ae933a3d9fed959a178 CDN=https://client-update.fastly.steamstatic.com @@ -18,6 +15,7 @@ ARM_STEAM=${XDG_DATA_HOME:-$REAL_HOME/.local/share}/Steam LOG=$X64_HOME/steam-x64.log mkdir -p "$X64_HOME" step() { echo "== STEP $(date -u +%H:%M:%S) $*" | tee -a "$LOG"; } +. "${BASH_SOURCE[0]%/*}/droiddeck-fex-update" x64_default_dir() { local d @@ -319,76 +317,6 @@ print("droiddeck-steam-x64: %d Linux title(s) on DroidDeck direct (%d on the new PY } -# Whether every program in the FEX tree at $1 finds its libraries (r4 did not without libxxhash). -fex_loads() { - local b out - for b in FEX FEXServer unsquashfs; do - out=$(/usr/lib/ld-linux-aarch64.so.1 --list "$1/usr/local/bin/$b" 2>&1) && ! grep -q "not found" <<<"$out" && continue - echo "== FEX check: $b: $(grep -E "not found|error" <<<"$out" | tr -s '\t ' ' ' | tr '\n' ';')" >&2 - return 1 - done -} - -# Installs one FEX build only once its archive matches the sha256 and it loads. The files it replaces are kept -# until the installed copy loads too, and put back otherwise; the tag is written last. -fex_install() { - local tag=$1 sha=$2 urls=$3 dst=/ tmp u f - tmp=$(mktemp -d) - for u in $urls; do - curl -fsSL --retry 2 "$u" -o "$tmp/fex.tzst" && echo "$sha $tmp/fex.tzst" | sha256sum -c --quiet >/dev/null 2>&1 && break - rm -f "$tmp/fex.tzst" - done - if [ ! -s "$tmp/fex.tzst" ]; then - echo "== FEX $tag: no source gave the archive with sha256 ${sha:0:12}" >&2 - rm -rf "$tmp" - return 1 - fi - if ! { mkdir "$tmp/root" && zstd -dc "$tmp/fex.tzst" | tar -C "$tmp/root" -x && fex_loads "$tmp/root"; }; then - rm -rf "$tmp" - return 1 - fi - (cd "$tmp/root" && find . ! -type d) > "$tmp/files" - mkdir "$tmp/old" - while IFS= read -r f; do - f=${f#./} - if [ -e "$dst$f" ] || [ -L "$dst$f" ]; then - cp -a --parents "$dst$f" "$tmp/old" || { echo "== FEX $tag: could not keep $dst$f aside" >&2; rm -rf "$tmp"; return 1; } - fi - done < "$tmp/files" - if tar -C "$tmp/root" -c . | tar -C "$dst" -x && fex_loads "$dst" && - mkdir -p "${dst}usr/local/share/fex-emu" && echo "$tag" > "${dst}usr/local/share/fex-emu/.droiddeck-tag"; then - rm -rf "$tmp" - return 0 - fi - echo "== FEX $tag: the installed copy did not load or its tag was not written; putting the previous files back" >&2 - while IFS= read -r f; do - f=${f#./} - [ -e "$tmp/old/$dst$f" ] || [ -L "$tmp/old/$dst$f" ] || rm -f "$dst$f" - done < "$tmp/files" - tar -C "$tmp/old$dst" -c . | tar -C "$dst" -x || echo "== FEX $tag: could not put the previous files back" >&2 - rm -rf "$tmp" - return 1 -} - -# The build DroidDeck-Components' fex.json names (the app passes it as BL_FEX_*) comes first, then a working -# installed one, then FEX_TAG above. Sets FEX_NOW and FEX_FROM. -x64_fex() { - local have ok= - have=$(cat /usr/local/share/fex-emu/.droiddeck-tag 2>/dev/null || true) - [ -x /usr/local/bin/FEX ] && fex_loads / && ok=1 - if [ -n "${BL_FEX_TAG:-}" ]; then - if [ -n "$ok" ] && [ "$have" = "$BL_FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=catalog; return 0; fi - step "downloading FEX ($BL_FEX_TAG)" - if fex_install "$BL_FEX_TAG" "${BL_FEX_SHA256:-}" "${BL_FEX_URLS:-}"; then FEX_NOW=$BL_FEX_TAG FEX_FROM=catalog; return 0; fi - if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $BL_FEX_TAG did not install"; return 0; fi - fi - if [ -n "$ok" ] && [ "$have" = "$FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=built-in; return 0; fi - step "downloading FEX ($FEX_TAG)" - if fex_install "$FEX_TAG" "$FEX_SHA256" "$FEX_URL"; then FEX_NOW=$FEX_TAG FEX_FROM=built-in; return 0; fi - if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $FEX_TAG did not install"; return 0; fi - return 1 -} - # A resumable download that reports every tenth of its size as a step. x64_fetch() { local url=$1 out=$2 label=$3 total pid rc=0 last=-1 pct @@ -406,7 +334,7 @@ x64_fetch() { } x64_prepare() { -x64_fex || { step "FEX could not be installed; see $LOG"; exit 1; } +fex_ready || { step "FEX could not be installed; see $LOG"; exit 1; } step "FEX ready ($FEX_NOW, $FEX_FROM)" # The client's opt-in to its SteamRT3 build; without it, it re-executes through steam.sh, whose checks fail under proot. mkdir -p "$STEAM_X64" && : > "$STEAM_X64/.steam-enable-steamrt64-client" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch index f59c560523..718498dff8 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -25,6 +25,8 @@ Android: an EOS sign-in step that falls back to a browser (a consent Epic asks f is finished there. An EOS overlay pointer (HKCU\Software\Epic Games\EOS "OverlayPath") an earlier build wrote is removed - with it the game exited while loading. +Battle.net.exe in Battle.net's prefix is handed to droiddeck-battlenet, which runs the whole launch. + droiddeck-store-launch <the arguments Steam gave the compat tool> """ @@ -291,6 +293,27 @@ def create_prefix(compat_data, proton, timeout=120): CLOUD_TIMEOUT = 15.0 CLOUD_STORES = ("gog", "epic") STORE_GAME = 10 +RAN = 11 +RAN_FAILED = 12 +BATTLENET = "/usr/local/bin/droiddeck-battlenet" +BATTLENET_EXE = re.compile(r"(?i)/compatdata/2596113170/pfx/drive_c/Program Files \(x86\)/Battle\.net/Battle\.net\.exe$") +BATTLENET_LAUNCH = re.compile(r'(?i)^--exec=\s*"?launch\s+([A-Za-z0-9_]{1,16})"?$') + + +def battlenet(argv, env=os.environ): + if env.get("BL_BATTLENET"): + return None + exe, code = False, None + for raw in argv: + arg = raw.strip().strip('"').strip("'") + if BATTLENET_EXE.search(arg.replace("\\", "/")): + exe = True + found = BATTLENET_LAUNCH.match(arg) + if found: + code = found.group(1) + if not exe: + return None + return [BATTLENET, "launch", code] if code else [BATTLENET, "open"] def cloud_on(sidecar): @@ -511,6 +534,10 @@ def main(argv): pass rest = rest[2:] return exited(rest, code) + command = battlenet(argv) + if command is not None: + log("battlenet " + " ".join(command[1:])) + return RAN if subprocess.call(command) == 0 else RAN_FAILED found = find_store_game(argv) if found is None: return 0 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox index f8aaff7b1b..9382f2deba 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox @@ -27,6 +27,7 @@ CLASSES = { 'Windows.Storage.Streams.DataWriter'), } CLASS_KEY = 'Software\\Microsoft\\WindowsRuntime\\ActivatableClassId\\' +VIEW_DRIVES = 'xwvutsrqponmlkjihgfe' def bridge(upstream): @@ -137,6 +138,29 @@ def register_classes(proton, prefix, env): print('droiddeck-xbox: Windows Runtime class registration failed; launching without it', file=sys.stderr) +def view_drive(prefix, exe): + path = Path(exe) + view = next((parent for parent in path.parents if parent.name.startswith('droiddeck-xbox-')), None) + if not path.is_absolute() or view is None: + return exe, None + devices = prefix / 'dosdevices' + for letter in VIEW_DRIVES: + link = devices / (letter + ':') + staged = devices / ('.%s-%s' % (letter, secrets.token_hex(4))) + try: + if os.path.lexists(link) and (os.path.exists(link) or not os.readlink(link).startswith(str(view.parent.parent) + '/')): + continue + devices.mkdir(parents=True, exist_ok=True) + staged.symlink_to(view) + os.replace(staged, link) + except OSError: + if os.path.lexists(staged): + staged.unlink() + continue + return letter.upper() + ':\\' + str(path.relative_to(view)).replace('/', '\\'), link + return exe, None + + def wine(argv, source_env=None): source_env = os.environ if source_env is None else source_env with open(source_env['DROIDDECK_XBOX_COMMAND_FILE'], encoding='utf-8') as file: @@ -163,7 +187,15 @@ def wine(argv, source_env=None): register_classes(command[0], prefix, env) overrides = ';'.join(name[:-4] + '=n' for name in DLLS if name != 'libnghttp2.dll') env['WINEDLLOVERRIDES'] = overrides + ';' + env.get('WINEDLLOVERRIDES', '') - return subprocess.call([*command[:2], argv[0], *command[3:]], env=env) + exe, drive = view_drive(prefix, argv[0]) + try: + return subprocess.call([*command[:2], exe, *command[3:]], env=env) + finally: + if drive is not None: + try: + drive.unlink() + except OSError: + pass def renew_lease(ask, channel, product, lease, stopped): diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index 29fe4f8e43..b1864dfadf 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -69,7 +69,10 @@ bl_store_launch() { fi [ -x /usr/local/bin/droiddeck-store-launch ] || return 0 /usr/local/bin/droiddeck-store-launch "$@" - [ $? -eq 10 ] && BL_STORE_EXIT=1 + rc=$? + [ $rc -eq 10 ] && BL_STORE_EXIT=1 + [ $rc -eq 11 ] && exit 0 + [ $rc -eq 12 ] && exit 1 return 0 } @@ -87,6 +90,34 @@ bl_run() { } """ +BL_DESKTOP_GPU_SETUP = """ +bl_desktop_gpu() { + local name saved gpu=/usr/local/bin/droiddeck-gpu + local names=(LD_PRELOAD LD_LIBRARY_PATH ENABLE_VK_LAYER_VALVE_steam_overlay_1 ENABLE_VK_LAYER_VALVE_steam_fossilize_1) + if [ -n "${BL_DESKTOP_GPU_CHILD:-}" ]; then + for name in "${names[@]}"; do + saved=BL_GPU_SAVED_$name + [ -n "${!saved+x}" ] || continue + export "$name=${!saved}" + unset "$saved" + done + return 0 + fi + [ "${BL_DESKTOP:-}" = 1 ] && [ "${verb:-}" = waitforexitandrun ] && [ -x "$gpu" ] || return 0 + local choice=${BL_DESKTOP_GPU:-on} + case "${choice,,}" in off | 0 | no | false) return 0 ;; esac + case " $* " in *iscriptevaluator*) return 0 ;; esac + local clear=() + for name in "${names[@]}"; do + [ -n "${!name+x}" ] || continue + export "BL_GPU_SAVED_$name=${!name}" + clear+=(-u "$name") + done + echo "droiddeck-gpu: the desktop starts this game on the GPU" >&2 + exec env "${clear[@]}" "$gpu" "$0" "$verb" "$@" +} +bl_desktop_gpu "$@" +""" BL_COMPONENTS_SETUP = """ bl_components() { base=$1 @@ -377,7 +408,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH def launcher_sh(sources=SOURCES): return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace( - "verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP + "verb=$1; shift", "verb=$1; shift\n" + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP + BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1) @@ -466,7 +497,7 @@ verb=$1; shift case $verb in getcompatpath | getnativepath) printf '%s\\n' "$1"; exit 0 ;; esac -""" + BL_GAME_CPUS_SETUP + """ +""" + BL_DESKTOP_GPU_SETUP + BL_GAME_CPUS_SETUP + """ bl_game_cpus if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "$verb"; then exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@" @@ -649,7 +680,7 @@ def adopt_extras(tools): try: body = (EXTRA_WRAPPER_SH % entry_point).replace( 'here=$(dirname "$0")', - 'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP + 'here=$(dirname "$0")\n' + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP + BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1) write_changed(wrapper, body, 0o755) write_changed(manifest, EXTRA_MANIFEST_VDF) @@ -1219,6 +1250,32 @@ def requested_games(requests, catalog, runnable=None): return resolved +OWN_PROTON = "DroidDeck-Proton" +ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64") + + +def own_builds(tools): + return [t for t in tools if isinstance(t, dict) and not t.get("valve") and + isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")] + + +def build_key(name): + return [int(n) for n in re.findall(r"\d+", ARCH_WORDS.sub(" ", name))] + + +def own_proton_moves(state, catalog): + names = {t["name"] for t in catalog} + before = state.get("tools") if isinstance(state.get("tools"), list) else () + seen = state.get("own_builds") if isinstance(state.get("own_builds"), list) else [] + known = {n for n in seen if isinstance(n, str)} | {t["name"] for t in own_builds(before)} | {t["name"] for t in own_builds(catalog)} + state["own_builds"] = sorted(known) + builds = own_builds(catalog) + if not builds: + return None, set() + newest = max(builds, key=lambda t: (build_key(t["dir"]), t["dir"]))["name"] + return newest, known - names + + def now_ms(): import time return int(time.time() * 1000) @@ -1379,11 +1436,26 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non catalog = tool_catalog(os.path.dirname(os.path.dirname(os.path.abspath(config_path))), dict(protect) if isinstance(protect, dict) else {name: name for name in protect}) names = [t["name"] for t in catalog] + newest, gone = own_proton_moves(state, catalog) + previous, applied, chosen = state.get("default"), state.get("applied"), state.get("seq") if default is None: if settle: default, state = choose_default(current.get("0", ""), state, read_json(state_path("request.json", directory)), catalog) else: default = state.get("default") if state.get("default") in names else TOOL + if settle and newest and default == TOOL and state.get("applied") == applied and state.get("seq") == chosen and ( + previous in gone or not state.get("own_proton")): + default = newest + state.update(default=newest, seq=now_ms(), source="update") + if settle and newest: + state["own_proton"] = True + if newest: + for app, name in list(current.items()): + if app != "0" and name in gone: + set_mapping(tokens, mapping, app, newest) + current[app] = newest + if isinstance(state.get("auto"), dict): + state["auto"] = {app: newest if name in gone else name for app, name in state["auto"].items()} steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path))) requests = settled_game_requests(state, current, catalog, not steam_running(), directory) overrides = requested_games(requests or {}, catalog) diff --git a/tools/linuxfs/preload/netif.c b/tools/linuxfs/preload/netif.c index 1782d0f0d1..872a877e11 100644 --- a/tools/linuxfs/preload/netif.c +++ b/tools/linuxfs/preload/netif.c @@ -407,6 +407,7 @@ int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); int bl_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); +int bl_vdec_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, void *caller, int *rc) __attribute__((visibility("hidden"))); int bl_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, @@ -423,6 +424,7 @@ int ioctl(int fd, unsigned long request, ...) { int rc; if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc; if (bl_venc_ioctl(fd, request, arg, &rc)) return rc; + if (bl_vdec_ioctl(fd, request, arg, &rc)) return rc; if (bl_drm_gem_close(fd, request, arg, &rc)) return rc; if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl"); if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc; diff --git a/tools/linuxfs/preload/ntsync.c b/tools/linuxfs/preload/ntsync.c index d49bb42b74..4fa0d6c2c5 100644 --- a/tools/linuxfs/preload/ntsync.c +++ b/tools/linuxfs/preload/ntsync.c @@ -1459,10 +1459,12 @@ ssize_t recvmsg(int fd, struct msghdr *msg, int flags) { void bl_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden"))); void bl_venc_closed(int fd) __attribute__((visibility("hidden"))); +void bl_vdec_closed(int fd) __attribute__((visibility("hidden"))); int close(int fd) { if (fd >= 0) bl_fsync_fds_closed((unsigned int)fd, (unsigned int)fd); bl_venc_closed(fd); + bl_vdec_closed(fd); uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE); if (t && fd >= 0 && fd < NS_FDS && __atomic_load_n(&t[fd], __ATOMIC_ACQUIRE)) ns_forget(fd); return ns_close_fd(fd); diff --git a/tools/linuxfs/preload/opens.c b/tools/linuxfs/preload/opens.c index 269f013913..332f9d89a5 100644 --- a/tools/linuxfs/preload/opens.c +++ b/tools/linuxfs/preload/opens.c @@ -15,6 +15,7 @@ int bl_status_without_tracer(const char *path, int flags, const void *caller) __ int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden"))); int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden"))); int bl_venc_open(const char *path, int flags) __attribute__((visibility("hidden"))); +int bl_vdec_open(const char *path, int flags) __attribute__((visibility("hidden"))); int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden"))); @@ -55,6 +56,7 @@ int open(const char *path, int flags, ...) { if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd; if ((fd = bl_ntsync_open(path, flags)) != -2) return fd; if ((fd = bl_venc_open(path, flags)) != -2) return fd; + if ((fd = bl_vdec_open(path, flags)) != -2) return fd; if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open"); if (real_open == NULL) { errno = ENOSYS; @@ -81,6 +83,7 @@ int openat(int dirfd, const char *path, int flags, ...) { if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd; if ((fd = bl_ntsync_open(path, flags)) != -2) return fd; if ((fd = bl_venc_open(path, flags)) != -2) return fd; + if ((fd = bl_vdec_open(path, flags)) != -2) return fd; if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat"); if (real_openat == NULL) { errno = ENOSYS; diff --git a/tools/linuxfs/preload/vdec.c b/tools/linuxfs/preload/vdec.c new file mode 100644 index 0000000000..9a0abbe504 --- /dev/null +++ b/tools/linuxfs/preload/vdec.c @@ -0,0 +1,978 @@ +#define _GNU_SOURCE +#include <dlfcn.h> +#include <errno.h> +#include <poll.h> +#include <stddef.h> + +#if defined(__aarch64__) || defined(BL_VDEC_ANY_ARCH) + +#include <fcntl.h> +#include <linux/videodev2.h> +#include <pthread.h> +#include <stdarg.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/ioctl.h> +#include <sys/mman.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include <time.h> +#include <unistd.h> + +#include "../../../app/src/main/cpp/venc/venc_proto.h" + +#define VDEC_DEVICE "/dev/video-dec0" +#define VDEC_INSTANCES 4 +#define VDEC_BUFFERS 16 +#define VDEC_BITSTREAM_SIZE (4u << 20) +#define VDEC_PADDING 64 +#define VDEC_DUMB 64 + +struct vd_dma_heap_alloc { + uint64_t len; + uint32_t fd; + uint32_t fd_flags; + uint64_t heap_flags; +}; +#define VD_DMA_HEAP_IOCTL_ALLOC _IOWR('H', 0x0, struct vd_dma_heap_alloc) + +struct vd_dma_buf_sync { + uint64_t flags; +}; +#define VD_DMA_BUF_SYNC_WRITE 2u +#define VD_DMA_BUF_SYNC_START 0u +#define VD_DMA_BUF_SYNC_END 4u +#define VD_DMA_BUF_IOCTL_SYNC _IOW('b', 0, struct vd_dma_buf_sync) + +struct vd_create_dumb { + uint32_t height, width, bpp, flags, handle, pitch; + uint64_t size; +}; +struct vd_destroy_dumb { + uint32_t handle; +}; +struct vd_prime_handle { + uint32_t handle, flags; + int32_t fd; +}; +#define VD_IOCTL_MODE_CREATE_DUMB _IOWR('d', 0xB2, struct vd_create_dumb) +#define VD_IOCTL_MODE_DESTROY_DUMB _IOWR('d', 0xB4, struct vd_destroy_dumb) +#define VD_IOCTL_PRIME_HANDLE_TO_FD _IOWR('d', 0x2d, struct vd_prime_handle) + +struct vd_mode_info { + uint32_t clock; + uint16_t hdisplay, hsync_start, hsync_end, htotal, hskew; + uint16_t vdisplay, vsync_start, vsync_end, vtotal, vscan; + uint32_t vrefresh, flags, type; + char name[32]; +}; +struct vd_res { + int count_fbs; + uint32_t *fbs; + int count_crtcs; + uint32_t *crtcs; + int count_connectors; + uint32_t *connectors; + int count_encoders; + uint32_t *encoders; + uint32_t min_width, max_width, min_height, max_height; +}; +struct vd_connector { + uint32_t connector_id, encoder_id, connector_type, connector_type_id; + int connection; + uint32_t mm_width, mm_height; + int subpixel; + int count_modes; + struct vd_mode_info *modes; + int count_props; + uint32_t *props; + uint64_t *prop_values; + int count_encoders; + uint32_t *encoders; +}; +struct vd_encoder { + uint32_t encoder_id, encoder_type, crtc_id, possible_crtcs, possible_clones; +}; +struct vd_crtc { + uint32_t crtc_id, buffer_id, x, y, width, height; + int mode_valid; + struct vd_mode_info mode; + int gamma_size; +}; +struct vd_device { + char **nodes; + int available_nodes; + int bustype; + void *businfo; + void *deviceinfo; +}; + +struct vd_capture { + int fd; + ino_t ino; + uint8_t *map; + size_t len; +}; + +struct vd_done { + uint32_t index; + struct timeval timestamp; +}; + +struct vdec { + int used, fd; + uint32_t fourcc, width, height; + uint32_t cap_width, cap_height, bpl, cap_size; + uint8_t *bitstream; + uint32_t out_count; + uint32_t out_done[VDEC_BUFFERS], n_out_done; + struct vd_capture cap[VDEC_BUFFERS]; + uint32_t cap_count; + uint32_t cap_queue[VDEC_BUFFERS], n_cap_queue; + struct vd_done cap_done[VDEC_BUFFERS]; + uint32_t n_cap_done; + int out_on, cap_on; + int sock, hw, hw_failed; + int64_t pts; + void *ctx, *packet, *frame; + uint8_t *packet_data; + size_t packet_capacity; + int last; + uint32_t frames, slow; + double decode_ms; +}; + +static struct { + void *(*find_decoder_by_name)(const char *); + void *(*alloc_context3)(const void *); + int (*open2)(void *, const void *, void **); + void (*free_context)(void **); + int (*send_packet)(void *, const void *); + int (*receive_frame)(void *, void *); + void (*flush_buffers)(void *); + void *(*packet_alloc)(void); + void (*packet_free)(void **); + void *(*frame_alloc)(void); + void (*frame_free)(void **); + void (*frame_unref)(void *); + int (*dict_set)(void **, const char *, const char *, int); + void (*dict_free)(void **); + const char *(*pix_fmt_name)(int); +} av; + +static pthread_mutex_t vd_lock = PTHREAD_MUTEX_INITIALIZER; +static struct vdec vd_all[VDEC_INSTANCES]; +static int vd_open_count; +static int vd_state; +static int vd_ffmpeg; +static int vd_heap = -1; +static int vd_dumb_fd[VDEC_DUMB]; +static char vd_drm_handle; + +static void vd_log(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +static void vd_log(const char *fmt, ...) { + va_list ap; + char line[256]; + va_start(ap, fmt); + int n = vsnprintf(line, sizeof line - 1, fmt, ap); + va_end(ap); + if (n < 0) return; + if (n > (int)sizeof line - 2) n = sizeof line - 2; + line[n++] = '\n'; + if (write(2, "droiddeck-vdec: ", 16) < 0 || write(2, line, n) < 0) return; +} + +static int vd_load_ffmpeg(void) { + void *codec = dlopen("libavcodec.so.62", RTLD_LAZY | RTLD_LOCAL); + void *util = codec ? dlopen("libavutil.so.60", RTLD_LAZY | RTLD_LOCAL) : NULL; + if (codec == NULL || util == NULL) { + vd_log("FFmpeg 8 is not available (%s), Remote Play decoding stays off", dlerror()); + return 0; + } +#define VD_SYM(lib, field, name) \ + if ((*(void **)&av.field = dlsym(lib, name)) == NULL) { \ + vd_log("FFmpeg has no %s, Remote Play decoding stays off", name); \ + return 0; \ + } + VD_SYM(codec, find_decoder_by_name, "avcodec_find_decoder_by_name") + VD_SYM(codec, alloc_context3, "avcodec_alloc_context3") + VD_SYM(codec, open2, "avcodec_open2") + VD_SYM(codec, free_context, "avcodec_free_context") + VD_SYM(codec, send_packet, "avcodec_send_packet") + VD_SYM(codec, receive_frame, "avcodec_receive_frame") + VD_SYM(codec, flush_buffers, "avcodec_flush_buffers") + VD_SYM(codec, packet_alloc, "av_packet_alloc") + VD_SYM(codec, packet_free, "av_packet_free") + VD_SYM(util, frame_alloc, "av_frame_alloc") + VD_SYM(util, frame_free, "av_frame_free") + VD_SYM(util, frame_unref, "av_frame_unref") + VD_SYM(util, dict_set, "av_dict_set") + VD_SYM(util, dict_free, "av_dict_free") + VD_SYM(util, pix_fmt_name, "av_get_pix_fmt_name") +#undef VD_SYM + return 1; +} + +static int vd_have_ffmpeg(void) { + if (vd_ffmpeg == 0) vd_ffmpeg = vd_load_ffmpeg() ? 1 : -1; + return vd_ffmpeg > 0; +} + +__attribute__((visibility("hidden"))) int bl_venc_connect(void); + +static int vd_enabled(void) { + pthread_mutex_lock(&vd_lock); + if (vd_state == 0) { + const char *flag = getenv("BL_REMOTE_PLAY_DECODE"), *socket = getenv("BL_VENC_SOCKET"); + vd_state = -1; + if (strcmp(program_invocation_short_name, "streaming_client") == 0 && (flag == NULL || strcmp(flag, "0") != 0)) { + vd_heap = open("/dev/dma_heap/system", O_RDONLY | O_CLOEXEC); + if (vd_heap < 0) vd_log("no /dev/dma_heap/system (%s), Remote Play decoding stays off", strerror(errno)); + else if ((socket && *socket) || vd_have_ffmpeg()) vd_state = 1; + for (int i = 0; i < VDEC_DUMB; i++) vd_dumb_fd[i] = -1; + } + } + int on = vd_state > 0; + pthread_mutex_unlock(&vd_lock); + return on; +} + +static struct vdec *vd_find(int fd) { + if (fd < 0 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return NULL; + for (int i = 0; i < VDEC_INSTANCES; i++) if (vd_all[i].used && vd_all[i].fd == fd) return &vd_all[i]; + return NULL; +} + +__attribute__((visibility("hidden"))) int bl_vdec_open(const char *path, int flags) { + (void)flags; + if (path == NULL || strcmp(path, VDEC_DEVICE) != 0 || !vd_enabled()) return -2; + int fd = memfd_create("droiddeck-vdec", 0); + if (fd < 0) return -1; + pthread_mutex_lock(&vd_lock); + struct vdec *v = NULL; + for (int i = 0; i < VDEC_INSTANCES && v == NULL; i++) if (!vd_all[i].used) v = &vd_all[i]; + if (v == NULL) { + pthread_mutex_unlock(&vd_lock); + close(fd); + errno = EBUSY; + return -1; + } + memset(v, 0, sizeof *v); + v->used = 1; + v->fd = fd; + v->fourcc = V4L2_PIX_FMT_H264; + v->last = -1; + v->sock = -1; + for (int i = 0; i < VDEC_BUFFERS; i++) v->cap[i].fd = -1; + __atomic_add_fetch(&vd_open_count, 1, __ATOMIC_RELEASE); + pthread_mutex_unlock(&vd_lock); + return fd; +} + +static void vd_close_decoder(struct vdec *v) { + if (v->frames) { + vd_log("%u frames, %.1f ms each on average, %u over 25 ms", v->frames, v->decode_ms / v->frames, v->slow); + } + if (v->sock >= 0) close(v->sock); + v->sock = -1; + v->hw = 0; + if (v->ctx) av.free_context(&v->ctx); + if (v->packet) av.packet_free(&v->packet); + if (v->frame) av.frame_free(&v->frame); + free(v->packet_data); + v->packet_data = NULL; + v->packet_capacity = 0; + v->frames = v->slow = 0; + v->decode_ms = 0; + v->last = -1; +} + +static int vd_send(int sock, const void *msg, size_t len, int fd) { + struct iovec iov = { .iov_base = (void *)msg, .iov_len = len }; + char control[CMSG_SPACE(sizeof(int))]; + struct msghdr m = { .msg_iov = &iov, .msg_iovlen = 1 }; + if (fd >= 0) { + memset(control, 0, sizeof control); + m.msg_control = control; + m.msg_controllen = sizeof control; + struct cmsghdr *c = CMSG_FIRSTHDR(&m); + c->cmsg_level = SOL_SOCKET; + c->cmsg_type = SCM_RIGHTS; + c->cmsg_len = CMSG_LEN(sizeof(int)); + memcpy(CMSG_DATA(c), &fd, sizeof fd); + } + return sendmsg(sock, &m, MSG_NOSIGNAL) == (ssize_t)len ? 0 : -1; +} + +static void vd_send_capture(struct vdec *v, uint32_t index) { + struct vdec_capture c = { .type = VDEC_CAPTURE, .index = index, .size = (uint32_t)v->cap[index].len }; + if (v->sock >= 0 && v->cap[index].map && vd_send(v->sock, &c, sizeof c, v->cap[index].fd) != 0) + vd_log("could not hand capture buffer %u to the app: %s", index, strerror(errno)); +} + +static int vd_open_hardware(struct vdec *v) { + if (v->hw_failed) return -1; + int sock = bl_venc_connect(); + 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, + .stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE, + }; + struct vdec_result r; + if (vd_send(sock, &c, sizeof c, v->fd) != 0 || recv(sock, &r, sizeof r, 0) != (ssize_t)sizeof r || + r.type != VDEC_RESULT || r.status != 0) { + vd_log("the app has no %s decoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height); + close(sock); + v->hw_failed = 1; + return -1; + } + v->sock = sock; + v->hw = 1; + for (uint32_t i = 0; i < v->cap_count; i++) vd_send_capture(v, i); + vd_log("decoding %s %ux%u with the app's MediaCodec into %ux%u NV12 dma-bufs", + c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height, v->cap_width, v->cap_height); + return 0; +} + +static int vd_open_decoder(struct vdec *v) { + if (vd_open_hardware(v) == 0) return 0; + if (!vd_have_ffmpeg()) return -1; + const char *name = v->fourcc == V4L2_PIX_FMT_HEVC ? "hevc" : "h264"; + const void *codec = av.find_decoder_by_name(name); + if (codec == NULL) { + vd_log("FFmpeg has no %s decoder", name); + return -1; + } + v->ctx = av.alloc_context3(codec); + v->packet = av.packet_alloc(); + v->frame = av.frame_alloc(); + void *options = NULL; + long cores = sysconf(_SC_NPROCESSORS_ONLN); + char threads[8]; + snprintf(threads, sizeof threads, "%ld", cores > 4 ? 4L : cores < 1 ? 1L : cores); + av.dict_set(&options, "threads", threads, 0); + av.dict_set(&options, "thread_type", "slice", 0); + av.dict_set(&options, "flags", "+low_delay", 0); + av.dict_set(&options, "flags2", "+fast", 0); + int r = v->ctx && v->packet && v->frame ? av.open2(v->ctx, codec, &options) : -1; + av.dict_free(&options); + if (r < 0) { + vd_log("could not open the %s decoder (%d)", name, r); + vd_close_decoder(v); + return -1; + } + vd_log("decoding %s %ux%u in software into %ux%u NV12 dma-bufs", v->fourcc == V4L2_PIX_FMT_HEVC ? "HEVC" : "H.264", + v->width, v->height, v->cap_width, v->cap_height); + return 0; +} + +static void vd_unmap_capture(struct vdec *v) { + for (uint32_t i = 0; i < VDEC_BUFFERS; i++) { + if (v->cap[i].map) munmap(v->cap[i].map, v->cap[i].len); + v->cap[i] = (struct vd_capture){ .fd = -1 }; + } + v->cap_count = v->n_cap_queue = v->n_cap_done = 0; + v->last = -1; +} + +static void vd_sync(int fd, uint64_t flags) { + struct vd_dma_buf_sync s = { .flags = flags | VD_DMA_BUF_SYNC_WRITE }; + ioctl(fd, VD_DMA_BUF_IOCTL_SYNC, &s); +} + +static void vd_blank(struct vdec *v, struct vd_capture *c) { + size_t luma = (size_t)v->bpl * v->cap_height; + if (luma + luma / 2 > c->len) return; + vd_sync(c->fd, VD_DMA_BUF_SYNC_START); + memset(c->map, 16, luma); + memset(c->map + luma, 128, luma / 2); + vd_sync(c->fd, VD_DMA_BUF_SYNC_END); +} + +static int vd_map_capture(struct vdec *v, uint32_t index, int fd) { + struct stat st; + if (fd < 0 || fstat(fd, &st) != 0) return -EINVAL; + struct vd_capture *c = &v->cap[index]; + if (c->map && c->ino == st.st_ino) { + c->fd = fd; + return 0; + } + if (c->map) { + munmap(c->map, c->len); + *c = (struct vd_capture){ .fd = -1 }; + if (v->last == (int)index) v->last = -1; + } + off_t len = lseek(fd, 0, SEEK_END); + if (len < (off_t)v->cap_size) return -EINVAL; + void *p = mmap(NULL, (size_t)len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) { + vd_log("could not map capture buffer %u: %s", index, strerror(errno)); + *c = (struct vd_capture){ .fd = -1 }; + return -EINVAL; + } + *c = (struct vd_capture){ .fd = fd, .ino = st.st_ino, .map = p, .len = (size_t)len }; + vd_blank(v, c); + if (v->hw) vd_send_capture(v, index); + return 0; +} + +static int vd_write_frame(struct vdec *v, struct vd_capture *c) { + uint8_t **data = (uint8_t **)v->frame; + int *linesize = (int *)((uint8_t *)v->frame + 64); + int width = *(int *)((uint8_t *)v->frame + 104), height = *(int *)((uint8_t *)v->frame + 108); + const char *format = av.pix_fmt_name(*(int *)((uint8_t *)v->frame + 116)); + if (format == NULL || width <= 0 || height <= 0) return -1; + int nv12 = strcmp(format, "nv12") == 0; + if (!nv12 && strcmp(format, "yuv420p") != 0 && strcmp(format, "yuvj420p") != 0) { + static int warned; + if (!warned++) vd_log("cannot show %s frames", format); + return -1; + } + uint32_t w = (uint32_t)width < v->bpl ? (uint32_t)width : v->bpl; + uint32_t h = (uint32_t)height < v->cap_height ? (uint32_t)height : v->cap_height; + uint8_t *y = c->map, *uv = c->map + (size_t)v->bpl * v->cap_height; + vd_sync(c->fd, VD_DMA_BUF_SYNC_START); + for (uint32_t row = 0; row < h; row++) memcpy(y + (size_t)row * v->bpl, data[0] + (size_t)row * linesize[0], w); + for (uint32_t row = 0; row < (h + 1) / 2; row++) { + uint8_t *dst = uv + (size_t)row * v->bpl; + if (nv12) { + memcpy(dst, data[1] + (size_t)row * linesize[1], w & ~1u); + continue; + } + const uint8_t *u = data[1] + (size_t)row * linesize[1], *vv = data[2] + (size_t)row * linesize[2]; + for (uint32_t x = 0; x < w / 2; x++) { + dst[2 * x] = u[x]; + dst[2 * x + 1] = vv[x]; + } + } + vd_sync(c->fd, VD_DMA_BUF_SYNC_END); + return 0; +} + +static void vd_copy_last(struct vdec *v, struct vd_capture *c) { + if (v->last < 0 || v->cap[v->last].map == NULL || &v->cap[v->last] == c) return; + size_t size = v->cap_size < c->len ? v->cap_size : c->len; + vd_sync(c->fd, VD_DMA_BUF_SYNC_START); + memcpy(c->map, v->cap[v->last].map, size); + vd_sync(c->fd, VD_DMA_BUF_SYNC_END); +} + +static double vd_now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6; +} + +static void vd_deliver(struct vdec *v, int written, double start, struct timeval timestamp) { + uint32_t target = v->cap_queue[0]; + if (!written) { + if (v->last < 0) return; + vd_copy_last(v, &v->cap[target]); + } + double ms = vd_now_ms() - start; + v->frames++; + v->decode_ms += ms; + if (ms > 25.0) v->slow++; + memmove(v->cap_queue, v->cap_queue + 1, --v->n_cap_queue * sizeof v->cap_queue[0]); + v->cap_done[v->n_cap_done++] = (struct vd_done){ .index = target, .timestamp = timestamp }; + v->last = (int)target; +} + +static void vd_decode_hardware(struct vdec *v, uint32_t index, uint32_t bytes, struct timeval timestamp) { + double start = vd_now_ms(); + v->pts += 16667; + struct vdec_packet p = { .type = VDEC_PACKET, .input = index, .bytes = bytes, .capture = v->cap_queue[0], .pts_us = v->pts }; + struct vdec_result r; + if (vd_send(v->sock, &p, sizeof p, -1) != 0 || recv(v->sock, &r, sizeof r, 0) != (ssize_t)sizeof r || + r.type != VDEC_RESULT) { + vd_log("lost the app's decoder (%s), switching to software", strerror(errno)); + vd_close_decoder(v); + v->hw_failed = 1; + return; + } + vd_deliver(v, r.status == 0 && r.frame, start, timestamp); +} + +static void vd_decode(struct vdec *v, uint32_t index, uint32_t bytes, struct timeval timestamp) { + if (!v->cap_on || v->n_cap_queue == 0) return; + if (v->ctx == NULL && !v->hw && vd_open_decoder(v) != 0) return; + if (v->hw) { + vd_decode_hardware(v, index, bytes, timestamp); + return; + } + if (v->packet_capacity < bytes + VDEC_PADDING) { + free(v->packet_data); + v->packet_capacity = bytes + VDEC_PADDING + (64u << 10); + v->packet_data = malloc(v->packet_capacity); + if (v->packet_data == NULL) { + v->packet_capacity = 0; + return; + } + } + memcpy(v->packet_data, v->bitstream + (size_t)index * VDEC_BITSTREAM_SIZE, bytes); + memset(v->packet_data + bytes, 0, VDEC_PADDING); + *(uint8_t **)((uint8_t *)v->packet + 24) = v->packet_data; + *(int *)((uint8_t *)v->packet + 32) = (int)bytes; + double start = vd_now_ms(); + uint32_t target = v->cap_queue[0]; + struct vd_capture *c = &v->cap[target]; + int written = 0; + if (av.send_packet(v->ctx, v->packet) >= 0) { + while (av.receive_frame(v->ctx, v->frame) >= 0) { + if (vd_write_frame(v, c) == 0) written = 1; + av.frame_unref(v->frame); + } + } + *(uint8_t **)((uint8_t *)v->packet + 24) = NULL; + *(int *)((uint8_t *)v->packet + 32) = 0; + vd_deliver(v, written, start, timestamp); +} + +static int is_output(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || type == V4L2_BUF_TYPE_VIDEO_OUTPUT; } +static int is_capture(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE || type == V4L2_BUF_TYPE_VIDEO_CAPTURE; } + +static void vd_fill_format(struct vdec *v, struct v4l2_format *f) { + struct v4l2_pix_format_mplane *p = &f->fmt.pix_mp; + memset(p, 0, sizeof *p); + p->field = V4L2_FIELD_NONE; + p->num_planes = 1; + p->colorspace = V4L2_COLORSPACE_REC709; + if (is_output(f->type)) { + p->width = v->width; + p->height = v->height; + p->pixelformat = v->fourcc; + p->plane_fmt[0].sizeimage = VDEC_BITSTREAM_SIZE; + } else { + p->width = v->cap_width; + p->height = v->cap_height; + p->pixelformat = V4L2_PIX_FMT_NV12; + p->plane_fmt[0].bytesperline = v->bpl; + p->plane_fmt[0].sizeimage = v->cap_size; + } +} + +static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) { + struct v4l2_pix_format_mplane *p = &f->fmt.pix_mp; + if (f->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE && f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL; + struct vdec t = *v; + if (is_output(f->type)) { + if (p->pixelformat != V4L2_PIX_FMT_H264 && p->pixelformat != V4L2_PIX_FMT_HEVC) return -EINVAL; + t.fourcc = p->pixelformat; + t.width = p->width; + t.height = 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 < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL; + t.cap_width = (w + 15) & ~15u; + t.cap_height = (h + 15) & ~15u; + t.bpl = t.cap_width; + t.cap_size = t.bpl * t.cap_height * 3 / 2; + } + 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; + } + vd_fill_format(&t, f); + return 0; +} + +static int vd_reqbufs(struct vdec *v, struct v4l2_requestbuffers *r) { + uint32_t n = r->count > VDEC_BUFFERS ? VDEC_BUFFERS : r->count; + if (r->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE && r->memory == V4L2_MEMORY_MMAP) { + if (v->bitstream) munmap(v->bitstream, (size_t)v->out_count * VDEC_BITSTREAM_SIZE); + v->bitstream = NULL; + v->out_count = v->n_out_done = 0; + if (n && ftruncate(v->fd, (off_t)n * VDEC_BITSTREAM_SIZE) != 0) return -ENOMEM; + if (n) { + void *p = mmap(NULL, (size_t)n * VDEC_BITSTREAM_SIZE, PROT_READ, MAP_SHARED, v->fd, 0); + if (p == MAP_FAILED) return -ENOMEM; + v->bitstream = p; + } + v->out_count = n; + } else if (r->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE && r->memory == V4L2_MEMORY_DMABUF) { + if (v->hw) vd_close_decoder(v); + vd_unmap_capture(v); + v->cap_count = n; + } else { + return -EINVAL; + } + r->count = n; + r->capabilities = r->memory == V4L2_MEMORY_MMAP ? V4L2_BUF_CAP_SUPPORTS_MMAP : V4L2_BUF_CAP_SUPPORTS_DMABUF; + return 0; +} + +static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) { + if (b->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || b->index >= v->out_count || b->m.planes == NULL || b->length < 1) + return -EINVAL; + b->memory = V4L2_MEMORY_MMAP; + b->flags = V4L2_BUF_FLAG_MAPPED; + b->length = 1; + b->m.planes[0].length = VDEC_BITSTREAM_SIZE; + b->m.planes[0].m.mem_offset = b->index * VDEC_BITSTREAM_SIZE; + return 0; +} + +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); + 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; + int r = vd_map_capture(v, b->index, b->m.planes[0].m.fd); + if (r < 0) return r; + for (uint32_t i = 0; i < v->n_cap_queue; i++) if (v->cap_queue[i] == b->index) return 0; + if (v->n_cap_queue >= VDEC_BUFFERS) return -EINVAL; + v->cap_queue[v->n_cap_queue++] = b->index; + } else { + return -EINVAL; + } + b->flags |= V4L2_BUF_FLAG_QUEUED; + return 0; +} + +static int vd_dqbuf(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 (v->n_out_done == 0) return -EAGAIN; + b->index = v->out_done[0]; + memmove(v->out_done, v->out_done + 1, --v->n_out_done * sizeof v->out_done[0]); + b->memory = V4L2_MEMORY_MMAP; + b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_MAPPED; + b->length = 1; + b->m.planes[0].bytesused = 0; + b->m.planes[0].length = VDEC_BITSTREAM_SIZE; + b->m.planes[0].m.mem_offset = b->index * VDEC_BITSTREAM_SIZE; + 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); + b->index = d.index; + b->memory = V4L2_MEMORY_DMABUF; + b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY; + b->field = V4L2_FIELD_NONE; + b->timestamp = d.timestamp; + b->length = 1; + b->m.planes[0].bytesused = v->cap_size; + b->m.planes[0].length = v->cap_size; + b->m.planes[0].m.fd = v->cap[d.index].fd; + return 0; +} + +static int vd_ioctl(struct vdec *v, unsigned long req, void *arg) { + switch (req) { + case VIDIOC_QUERYCAP: { + struct v4l2_capability *c = arg; + memset(c, 0, sizeof *c); + strcpy((char *)c->driver, "droiddeck_vdec"); + strcpy((char *)c->card, "DroidDeck video decoder"); + strcpy((char *)c->bus_info, "platform:droiddeck-vdec"); + c->version = 0x00060000; + c->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; + c->capabilities = c->device_caps | V4L2_CAP_DEVICE_CAPS; + return 0; + } + case VIDIOC_ENUM_FMT: { + struct v4l2_fmtdesc *d = arg; + static const uint32_t coded[] = { V4L2_PIX_FMT_H264, V4L2_PIX_FMT_HEVC }; + if (is_capture(d->type) && d->index == 0) { + d->pixelformat = V4L2_PIX_FMT_NV12; + strcpy((char *)d->description, "Y/CbCr 4:2:0"); + d->flags = 0; + } else if (is_output(d->type) && d->index < 2) { + d->pixelformat = coded[d->index]; + strcpy((char *)d->description, d->index ? "HEVC" : "H.264"); + d->flags = V4L2_FMT_FLAG_COMPRESSED; + } else { + return -EINVAL; + } + return 0; + } + case VIDIOC_G_FMT: { + struct v4l2_format *f = arg; + if (!is_output(f->type) && !is_capture(f->type)) return -EINVAL; + vd_fill_format(v, f); + return 0; + } + case VIDIOC_S_FMT: return vd_set_format(v, arg, 1); + case VIDIOC_TRY_FMT: return vd_set_format(v, arg, 0); + case VIDIOC_REQBUFS: return vd_reqbufs(v, arg); + case VIDIOC_QUERYBUF: return vd_querybuf(v, arg); + case VIDIOC_QBUF: return vd_qbuf(v, arg); + case VIDIOC_DQBUF: return vd_dqbuf(v, arg); + case VIDIOC_STREAMON: + case VIDIOC_STREAMOFF: { + uint32_t type = *(uint32_t *)arg; + int on = req == VIDIOC_STREAMON; + if (is_output(type)) { + v->out_on = on; + if (!on) { + v->n_out_done = 0; + if (v->ctx) av.flush_buffers(v->ctx); + } + } else if (is_capture(type)) { + v->cap_on = on; + if (!on) v->n_cap_queue = v->n_cap_done = 0; + } else { + return -EINVAL; + } + if (v->out_on && v->cap_on && v->ctx == NULL && !v->hw && v->out_count && v->cap_size) vd_open_decoder(v); + return 0; + } + case VIDIOC_SUBSCRIBE_EVENT: + case VIDIOC_UNSUBSCRIBE_EVENT: + case VIDIOC_DECODER_CMD: + case VIDIOC_TRY_DECODER_CMD: + return 0; + case VIDIOC_DQEVENT: + return -ENOENT; + default: + vd_log("unhandled ioctl 0x%lx", req); + return -ENOTTY; + } +} + +__attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) { + struct vdec *v = vd_find(fd); + if (v == NULL) return 0; + pthread_mutex_lock(&vd_lock); + int r = arg ? vd_ioctl(v, req, arg) : -EFAULT; + pthread_mutex_unlock(&vd_lock); + if (r < 0) { + errno = -r; + *rc = -1; + } else { + *rc = 0; + } + return 1; +} + +__attribute__((visibility("hidden"))) void bl_vdec_closed(int fd) { + struct vdec *v = vd_find(fd); + if (v == NULL) return; + pthread_mutex_lock(&vd_lock); + vd_close_decoder(v); + vd_unmap_capture(v); + if (v->bitstream) munmap(v->bitstream, (size_t)v->out_count * VDEC_BITSTREAM_SIZE); + v->bitstream = NULL; + v->used = 0; + __atomic_sub_fetch(&vd_open_count, 1, __ATOMIC_RELEASE); + pthread_mutex_unlock(&vd_lock); +} + +__attribute__((visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, + int (*real)(struct pollfd *, nfds_t, int), int *ret) { + if (n != 1 || vd_find(fds[0].fd) == NULL) return 0; + struct vdec *v = vd_find(fds[0].fd); + pthread_mutex_lock(&vd_lock); + short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0); + pthread_mutex_unlock(&vd_lock); + fds[0].revents = ready & fds[0].events; + if (fds[0].revents == 0 && timeout_ms != 0) real(NULL, 0, timeout_ms < 0 || timeout_ms > 1000 ? 1000 : timeout_ms); + *ret = fds[0].revents ? 1 : 0; + return 1; +} + +static int drm_get_devices2(uint32_t flags, struct vd_device **devices, int max) { + (void)flags; + static char *nodes[3] = { "/dev/null", NULL, NULL }; + static struct vd_device device = { .nodes = nodes, .available_nodes = 1 }; + if (devices == NULL || max < 1) return 1; + devices[0] = &device; + return 1; +} + +static void drm_free_devices(struct vd_device **devices, int count) { (void)devices; (void)count; } + +static struct vd_mode_info drm_mode = { + .clock = 148500, .hdisplay = 1920, .hsync_start = 2008, .hsync_end = 2052, .htotal = 2200, + .vdisplay = 1080, .vsync_start = 1084, .vsync_end = 1089, .vtotal = 1125, .vrefresh = 60, .name = "1920x1080", +}; +static uint32_t drm_crtc_ids[1] = { 1 }, drm_connector_ids[1] = { 2 }, drm_encoder_ids[1] = { 3 }; + +static struct vd_res *drm_get_resources(int fd) { + (void)fd; + static struct vd_res res = { + .count_crtcs = 1, .crtcs = drm_crtc_ids, .count_connectors = 1, .connectors = drm_connector_ids, + .count_encoders = 1, .encoders = drm_encoder_ids, .max_width = 8192, .max_height = 8192, + }; + return &res; +} + +static struct vd_connector *drm_get_connector(int fd, uint32_t id) { + (void)fd; + static struct vd_connector connector = { + .connector_id = 2, .encoder_id = 3, .connector_type = 14, .connection = 1, .count_modes = 1, + .modes = &drm_mode, .count_encoders = 1, .encoders = drm_encoder_ids, + }; + return id == 2 ? &connector : NULL; +} + +static struct vd_encoder *drm_get_encoder(int fd, uint32_t id) { + (void)fd; + static struct vd_encoder encoder = { .encoder_id = 3, .encoder_type = 8, .crtc_id = 1, .possible_crtcs = 1 }; + return id == 3 ? &encoder : NULL; +} + +static struct vd_crtc *drm_get_crtc(int fd, uint32_t id) { + (void)fd; + static struct vd_crtc crtc; + if (id != 1) return NULL; + crtc = (struct vd_crtc){ .crtc_id = 1, .width = 1920, .height = 1080, .mode_valid = 1, .mode = drm_mode }; + return &crtc; +} + +static void drm_free(void *p) { (void)p; } +static void *drm_null(void) { return NULL; } +static int drm_fail(void) { return -EINVAL; } + +static int drm_dumb_slot(uint32_t handle) { return handle >= 1 && handle <= VDEC_DUMB ? (int)handle - 1 : -1; } + +static int drm_ioctl(int fd, unsigned long request, void *arg) { + (void)fd; + int r = -EINVAL; + pthread_mutex_lock(&vd_lock); + if (request == VD_IOCTL_MODE_CREATE_DUMB && arg) { + struct vd_create_dumb *c = arg; + uint64_t pitch = ((uint64_t)c->width * c->bpp + 7) / 8; + uint64_t size = (pitch * c->height + 4095) & ~4095ull; + int slot = -1; + for (int i = 0; i < VDEC_DUMB && slot < 0; i++) if (vd_dumb_fd[i] < 0) slot = i; + struct vd_dma_heap_alloc a = { .len = size, .fd_flags = O_RDWR | O_CLOEXEC }; + if (slot < 0 || size == 0 || size > (512ull << 20)) { + r = -ENOMEM; + } else if (ioctl(vd_heap, VD_DMA_HEAP_IOCTL_ALLOC, &a) != 0) { + r = -errno; + vd_log("dma-heap allocation of %llu bytes failed: %s", (unsigned long long)size, strerror(errno)); + } else { + vd_dumb_fd[slot] = (int)a.fd; + c->handle = (uint32_t)slot + 1; + c->pitch = (uint32_t)pitch; + c->size = size; + r = 0; + } + } else if (request == VD_IOCTL_PRIME_HANDLE_TO_FD && arg) { + struct vd_prime_handle *h = arg; + int slot = drm_dumb_slot(h->handle); + int dup_fd = slot >= 0 && vd_dumb_fd[slot] >= 0 ? fcntl(vd_dumb_fd[slot], F_DUPFD_CLOEXEC, 0) : -1; + if (dup_fd >= 0) { + h->fd = dup_fd; + r = 0; + } else { + r = slot >= 0 ? -errno : -ENOENT; + } + } else if (request == VD_IOCTL_MODE_DESTROY_DUMB && arg) { + int slot = drm_dumb_slot(((struct vd_destroy_dumb *)arg)->handle); + if (slot >= 0 && vd_dumb_fd[slot] >= 0) { + close(vd_dumb_fd[slot]); + vd_dumb_fd[slot] = -1; + r = 0; + } else { + r = -ENOENT; + } + } + pthread_mutex_unlock(&vd_lock); + if (r < 0) { + errno = -r; + return -1; + } + return 0; +} + +static const struct { + const char *name; + void *fn; +} drm_table[] = { + { "drmGetDevices2", (void *)drm_get_devices2 }, + { "drmFreeDevices", (void *)drm_free_devices }, + { "drmSetMaster", (void *)drm_fail }, + { "drmSetClientCap", (void *)drm_fail }, + { "drmModeGetResources", (void *)drm_get_resources }, + { "drmModeFreeResources", (void *)drm_free }, + { "drmModeGetConnector", (void *)drm_get_connector }, + { "drmModeFreeConnector", (void *)drm_free }, + { "drmModeGetEncoder", (void *)drm_get_encoder }, + { "drmModeFreeEncoder", (void *)drm_free }, + { "drmModeGetCrtc", (void *)drm_get_crtc }, + { "drmModeSetCrtc", (void *)drm_fail }, + { "drmModeFreeCrtc", (void *)drm_free }, + { "drmModeGetPlaneResources", (void *)drm_null }, + { "drmModeFreePlaneResources", (void *)drm_free }, + { "drmModeGetPlane", (void *)drm_null }, + { "drmModeFreePlane", (void *)drm_free }, + { "drmModeObjectGetProperties", (void *)drm_null }, + { "drmModeFreeObjectProperties", (void *)drm_free }, + { "drmModeGetProperty", (void *)drm_null }, + { "drmModeFreeProperty", (void *)drm_free }, + { "drmModeAddFB2", (void *)drm_fail }, + { "drmModeAddFB2WithModifiers", (void *)drm_fail }, + { "drmModeRmFB", (void *)drm_fail }, + { "drmModeAtomicAlloc", (void *)drm_null }, + { "drmModeAtomicFree", (void *)drm_free }, + { "drmModeAtomicAddProperty", (void *)drm_fail }, + { "drmModeAtomicCommit", (void *)drm_fail }, + { "drmIoctl", (void *)drm_ioctl }, +}; + +void *SDL_LoadObject(const char *name) { + static void *(*real)(const char *); + if (name && strcmp(name, "libdrm.so.2") == 0 && vd_enabled()) return &vd_drm_handle; + if (!real) real = (void *(*)(const char *))dlsym(RTLD_NEXT, "SDL_LoadObject"); + return real ? real(name) : NULL; +} + +void *SDL_LoadFunction(void *handle, const char *name) { + static void *(*real)(void *, const char *); + if (handle == &vd_drm_handle) { + for (size_t i = 0; name && i < sizeof drm_table / sizeof drm_table[0]; i++) + if (strcmp(drm_table[i].name, name) == 0) return drm_table[i].fn; + return NULL; + } + if (!real) real = (void *(*)(void *, const char *))dlsym(RTLD_NEXT, "SDL_LoadFunction"); + return real ? real(handle, name) : NULL; +} + +void SDL_UnloadObject(void *handle) { + static void (*real)(void *); + if (handle == &vd_drm_handle) return; + if (!real) real = (void (*)(void *))dlsym(RTLD_NEXT, "SDL_UnloadObject"); + if (real) real(handle); +} + +#else + +__attribute__((visibility("hidden"))) int bl_vdec_open(const char *path, int flags) { + (void)path; + (void)flags; + return -2; +} + +__attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) { + (void)fd; + (void)req; + (void)arg; + (void)rc; + return 0; +} + +__attribute__((visibility("hidden"))) void bl_vdec_closed(int fd) { (void)fd; } + +__attribute__((visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, + int (*real)(struct pollfd *, nfds_t, int), int *ret) { + (void)fds; + (void)n; + (void)timeout_ms; + (void)real; + (void)ret; + return 0; +} + +#endif diff --git a/tools/linuxfs/preload/venc.c b/tools/linuxfs/preload/venc.c index ca610e85c3..9480e88126 100644 --- a/tools/linuxfs/preload/venc.c +++ b/tools/linuxfs/preload/venc.c @@ -625,9 +625,14 @@ static int vn_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(str return r + ready; } +__attribute__((weak, visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, + int (*real)(struct pollfd *, nfds_t, int), int *ret); + int poll(struct pollfd *fds, nfds_t n, int timeout_ms) { static int (*real)(struct pollfd *, nfds_t, int); if (!real) real = (int (*)(struct pollfd *, nfds_t, int))dlsym(RTLD_NEXT, "poll"); + int ret; + if (bl_vdec_poll && bl_vdec_poll(fds, n, timeout_ms, real, &ret)) return ret; if (__atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return real(fds, n, timeout_ms); return vn_poll(fds, n, timeout_ms, real); } diff --git a/tools/packs/proot/release.env b/tools/packs/proot/release.env new file mode 100644 index 0000000000..7a23b27997 --- /dev/null +++ b/tools/packs/proot/release.env @@ -0,0 +1,6 @@ +# Published proot pack for a build that did not compile libproot.so into the APK. +# CI builds embed the binary and publish their own pack; this pin is what a source +# build downloads. Tag on DroidDeck-Components: pack-proot-<first 16 hex of the digest>. +# Update both lines when source builds should pick up a newer proot. +PROOT_PACK_SHA256=5a2b7284e6357f88a14a790abd54e61effbe5f202c63b6aaba9b974c559649c3 +PROOT_PACK_SIZE=96643 diff --git a/tools/proot/PATCHES.md b/tools/proot/PATCHES.md index f379b4d7dc..a0faf47043 100644 --- a/tools/proot/PATCHES.md +++ b/tools/proot/PATCHES.md @@ -124,3 +124,11 @@ Old kernel fixes: by the kernel instead. The original clone flags are preserved. When the kernel supplies a valid ID in the notification, normal setup is unchanged. No timers or background polling are added. Completely missing notifications and ambiguous matches for separate processes are not recovered. + +Development diagnostics: + +- `0018-syscall-handler-profile.patch` - `PROOT_PROFILE=1` enables per-syscall entry/exit handler + counts, wall/CPU time, periodic cumulative JSON totals, and bounded slow-handler samples on + stderr. `profile.h` is copied into the source tree by `build.sh`. It adds no ptrace stops; + handler timing excludes tracee kernel time and scheduling before handler entry. See + `docs/development/proot-performance.md` for the capture and library-override workflow. diff --git a/tools/proot/build.sh b/tools/proot/build.sh index 718190552c..5b76dd38f0 100755 --- a/tools/proot/build.sh +++ b/tools/proot/build.sh @@ -31,6 +31,7 @@ fetch() { fetch proot.tar.gz "https://github.com/termux/proot/archive/${PROOT_COMMIT}.tar.gz" "$PROOT_SHA256" fetch talloc.tar.gz "https://www.samba.org/ftp/talloc/talloc-${TALLOC_VERSION}.tar.gz" "$TALLOC_SHA256" cp "$HERE/statx_mnt_id.h" "$WORK/proot/src/tracee/statx_mnt_id.h" +cp "$HERE/profile.h" "$WORK/proot/src/syscall/profile.h" for patch in "$HERE"/patches/*.patch; do patch -d "$WORK/proot" -p1 --forward --quiet < "$patch" done diff --git a/tools/proot/fastpath/fastpath.c b/tools/proot/fastpath/fastpath.c index 811b0057c8..bd3fc0d210 100644 --- a/tools/proot/fastpath/fastpath.c +++ b/tools/proot/fastpath/fastpath.c @@ -875,19 +875,84 @@ int __fxstat(int ver, int fd, struct stat *st) { } int __fxstat64(int ver, int fd, struct stat64 *st) { return __fxstat(ver, fd, (struct stat *)st); } +#ifndef STATX__RESERVED +#define STATX__RESERVED 0x80000000U +#endif + +static int statx_missing; + +static unsigned int dev_major(unsigned long long dev) { + return ((dev >> 8) & 0xfff) | ((unsigned int)(dev >> 32) & ~0xfffU); +} +static unsigned int dev_minor(unsigned long long dev) { + return (dev & 0xff) | ((unsigned int)(dev >> 12) & ~0xffU); +} + +static void fill_statx(struct statx *out, const struct stat *st) { + memset(out, 0, sizeof *out); + out->stx_mask = STATX_BASIC_STATS; + out->stx_blksize = st->st_blksize; + out->stx_nlink = st->st_nlink; + out->stx_uid = st->st_uid; + out->stx_gid = st->st_gid; + out->stx_mode = st->st_mode; + out->stx_ino = st->st_ino; + out->stx_size = st->st_size; + out->stx_blocks = st->st_blocks; + out->stx_atime.tv_sec = st->st_atim.tv_sec; + out->stx_atime.tv_nsec = st->st_atim.tv_nsec; + out->stx_ctime.tv_sec = st->st_ctim.tv_sec; + out->stx_ctime.tv_nsec = st->st_ctim.tv_nsec; + out->stx_mtime.tv_sec = st->st_mtim.tv_sec; + out->stx_mtime.tv_nsec = st->st_mtim.tv_nsec; + out->stx_rdev_major = dev_major(st->st_rdev); + out->stx_rdev_minor = dev_minor(st->st_rdev); + out->stx_dev_major = dev_major(st->st_dev); + out->stx_dev_minor = dev_minor(st->st_dev); +} + +/* Emulate statx on older kernels < 4.11 */ +static long statx_call(int dirfd, const char *path, int flags, unsigned mask, struct statx *out) { + struct stat st; + long rs; + if ((flags & ~(AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT | AT_STATX_SYNC_TYPE)) || + (flags & AT_STATX_SYNC_TYPE) == AT_STATX_SYNC_TYPE) + return -EINVAL; + if (!statx_missing) { + rs = sc(SYS_statx, dirfd, (long)path, flags, mask, (long)out); + if (rs != -ENOSYS) return rs; + statx_missing = 1; + } + if (flags & AT_STATX_SYNC_TYPE) return -ENOSYS; + rs = sc(SYS_newfstatat, dirfd, (long)path, (long)&st, + flags & (AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT), 0); + if (rs < 0) return rs; + fill_statx(out, &st); + return 0; +} + int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *out) { REAL(statx, int (*)(int, const char *, int, unsigned, struct statx *)); struct res r; long rs; + if (mask & STATX__RESERVED) { errno = EINVAL; return -1; } +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull-compare" + if (!out) { errno = EFAULT; return -1; } + if (!path) { + if (!(flags & AT_EMPTY_PATH)) { errno = EFAULT; return -1; } + return real_statx ? real_statx(dirfd, path, flags, mask, out) : ret(sc(SYS_statx, dirfd, (long)path, flags, mask, (long)out)); + } +#pragma GCC diagnostic pop if ((flags & AT_EMPTY_PATH) && !path[0] && fp_ready()) { hits++; - return ret(sc(SYS_statx, dirfd, (long)"", flags, mask, (long)out)); + return ret(statx_call(dirfd, "", flags, mask, out)); } rs = (flags & ~(AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT | AT_STATX_SYNC_TYPE)) ? FP_SLOW : resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r); if (rs == 1) rs = -ENOENT; if (rs == 0 || rs == UNSEEN) - rs = sc(SYS_statx, AT_FDCWD, (long)r.host, flags | (rs == 0 && !r.magic ? AT_SYMLINK_NOFOLLOW : 0), mask, (long)out); + rs = statx_call(AT_FDCWD, r.host, flags | (rs == 0 && !r.magic ? AT_SYMLINK_NOFOLLOW : 0), mask, out); ANSWER(rs, dirfd, path, real_statx(dirfd, path, flags, mask, out)); } diff --git a/tools/proot/patches/0018-syscall-handler-profile.patch b/tools/proot/patches/0018-syscall-handler-profile.patch new file mode 100644 index 0000000000..20d4859c5a --- /dev/null +++ b/tools/proot/patches/0018-syscall-handler-profile.patch @@ -0,0 +1,38 @@ +--- a/src/syscall/syscall.c ++++ b/src/syscall/syscall.c +@@ -32,6 +32,7 @@ + #include "tracee/reg.h" + #include "tracee/mem.h" + #include "cli/note.h" ++#include "syscall/profile.h" + + /** + * Copy in @path a C string (PATH_MAX bytes max.) from the @tracee's +@@ -100,7 +101,7 @@ + return set_sysarg_data(tracee, path, strlen(path) + 1, reg); + } + +-void translate_syscall(Tracee *tracee) ++static void translate_syscall_impl(Tracee *tracee) + { + const bool is_enter_stage = IS_IN_SYSENTER(tracee); + int status; +@@ -283,3 +284,18 @@ + else + print_current_regs(tracee, 4, "sysexit end"); + } ++ ++void translate_syscall(Tracee *tracee) ++{ ++ if (!dd_profile_enabled()) { ++ translate_syscall_impl(tracee); ++ return; ++ } ++ int saved = errno; ++ const bool entering = IS_IN_SYSENTER(tracee); ++ uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC); ++ uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID); ++ errno = saved; ++ translate_syscall_impl(tracee); ++ dd_profile_record(get_sysnum(tracee, ORIGINAL), entering, tracee->pid, wall, cpu); ++} diff --git a/tools/proot/profile.h b/tools/proot/profile.h new file mode 100644 index 0000000000..71173b31e8 --- /dev/null +++ b/tools/proot/profile.h @@ -0,0 +1,99 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef DROIDDECK_PROOT_PROFILE_H +#define DROIDDECK_PROOT_PROFILE_H + +#include <errno.h> +#include <inttypes.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +struct dd_profile_counter { + uint64_t calls, wall_ns, cpu_ns, max_ns; +}; +static struct dd_profile_counter dd_profile_counts[PR_NB_SYSNUM][2]; +static int dd_profile_on = -1; +static uint64_t dd_profile_id, dd_profile_next, dd_profile_slow_ns = 1000000; +static unsigned dd_profile_samples; + +static uint64_t dd_profile_clock(clockid_t clock) +{ + struct timespec ts; + if (clock_gettime(clock, &ts) != 0) return 0; + return (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; +} + +static void dd_profile_flush(void) +{ + int saved = errno; + for (unsigned nr = 0; nr < PR_NB_SYSNUM; nr++) { + for (unsigned stage = 0; stage < 2; stage++) { + const struct dd_profile_counter *c = &dd_profile_counts[nr][stage]; + if (!c->calls) continue; + fprintf(stderr, "proot-profile {\"type\":\"total\",\"tracer\":%d,\"id\":%" PRIu64 + ",\"syscall\":\"%s\",\"stage\":\"%s\",\"calls\":%" PRIu64 + ",\"wall_ns\":%" PRIu64 ",\"cpu_ns\":%" PRIu64 ",\"max_ns\":%" PRIu64 "}\n", + getpid(), dd_profile_id, stringify_sysnum(nr), stage ? "exit" : "enter", + c->calls, c->wall_ns, c->cpu_ns, c->max_ns); + } + } + errno = saved; +} + +static int dd_profile_enabled(void) +{ + if (dd_profile_on >= 0) return dd_profile_on; + int saved = errno; + const char *value = getenv("PROOT_PROFILE"); + dd_profile_on = value && strcmp(value, "1") == 0; + if (dd_profile_on) { + value = getenv("PROOT_PROFILE_SLOW_US"); + if (value && *value) { + char *end; + unsigned long long us = strtoull(value, &end, 10); + if (!*end && us > 0 && us <= 1000000000ULL) dd_profile_slow_ns = us * 1000; + } + dd_profile_id = dd_profile_clock(CLOCK_MONOTONIC); + dd_profile_next = dd_profile_id + 5000000000ULL; + atexit(dd_profile_flush); + fprintf(stderr, "proot-profile {\"type\":\"start\",\"tracer\":%d,\"id\":%" PRIu64 + ",\"slow_ns\":%" PRIu64 ",\"sample_limit\":32,\"sample_window_ms\":5000,\"scope\":\"syscall-handler\"}\n", + getpid(), dd_profile_id, dd_profile_slow_ns); + } + errno = saved; + return dd_profile_on; +} + +static void dd_profile_record(unsigned nr, int entering, pid_t pid, + uint64_t start_wall, uint64_t start_cpu) +{ + int saved = errno; + uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID); + uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC); + if (nr >= PR_NB_SYSNUM) nr = PR_void; + if (!start_wall || !start_cpu || wall < start_wall || cpu < start_cpu) goto done; + uint64_t elapsed = wall - start_wall, used = cpu - start_cpu; + struct dd_profile_counter *c = &dd_profile_counts[nr][!entering]; + c->calls++; + c->wall_ns += elapsed; + c->cpu_ns += used; + if (elapsed > c->max_ns) c->max_ns = elapsed; + if (wall >= dd_profile_next) { + dd_profile_flush(); + dd_profile_next = wall + 5000000000ULL; + dd_profile_samples = 0; + } + if (elapsed >= dd_profile_slow_ns && dd_profile_samples < 32) { + dd_profile_samples++; + fprintf(stderr, "proot-profile {\"type\":\"slow\",\"tracer\":%d,\"id\":%" PRIu64 + ",\"pid\":%d,\"syscall\":\"%s\",\"stage\":\"%s\",\"wall_ns\":%" PRIu64 + ",\"cpu_ns\":%" PRIu64 "}\n", getpid(), dd_profile_id, pid, + stringify_sysnum(nr), entering ? "enter" : "exit", elapsed, used); + } + done: + errno = saved; +} +#endif diff --git a/tools/proot_profile.py b/tools/proot_profile.py new file mode 100644 index 0000000000..bfe4418f42 --- /dev/null +++ b/tools/proot_profile.py @@ -0,0 +1,56 @@ +"""Read cumulative PRoot handler counters from a session log without double counting snapshots.""" +from __future__ import annotations + +import json +from collections import deque +from pathlib import Path + +PREFIX = "proot-profile " + + +def report(path: Path, sort: str = "wall", limit: int = 20) -> dict: + latest = {} + starts = set() + samples = deque(maxlen=128) + malformed = 0 + with path.open(errors="replace") as stream: + for line in stream: + if PREFIX not in line: + continue + try: + row = json.loads(line.split(PREFIX, 1)[1]) + identity = (int(row["tracer"]), int(row["id"])) + if row["type"] == "start": + starts.add(identity) + elif row["type"] in {"total", "slow"}: + if row["stage"] not in {"enter", "exit"} or not isinstance(row["syscall"], str): + raise ValueError("invalid syscall/stage") + fields = ("calls", "wall_ns", "cpu_ns", "max_ns") if row["type"] == "total" else ("wall_ns", "cpu_ns", "pid") + if any(type(row[key]) is not int or row[key] < 0 for key in fields): + raise ValueError("invalid counter") + if row["type"] == "total": + latest[identity + (row["syscall"], row["stage"])] = row + else: + samples.append(row) + except (ValueError, TypeError, KeyError): + malformed += 1 + groups = {} + for (_, _, syscall, stage), row in latest.items(): + total = groups.setdefault((syscall, stage), dict(syscall=syscall, stage=stage, calls=0, wall_ns=0, cpu_ns=0, max_ns=0)) + for key in ("calls", "wall_ns", "cpu_ns"): + total[key] += row[key] + total["max_ns"] = max(total["max_ns"], row["max_ns"]) + for row in groups.values(): + row["wallMs"] = round(row["wall_ns"] / 1_000_000, 3) + row["cpuMs"] = round(row["cpu_ns"] / 1_000_000, 3) + row["meanUs"] = round(row["wall_ns"] / max(row["calls"], 1) / 1000, 3) + row["maxUs"] = round(row["max_ns"] / 1000, 3) + rows = sorted(groups.values(), key=lambda row: row[{"wall": "wall_ns", "cpu": "cpu_ns", "calls": "calls"}[sort]], reverse=True) + return dict(ok=True, command="proot-profile", scope="syscall-handler", + note="Handler wall time includes tracer descheduling and filesystem waits; it excludes tracee kernel time and wake-up/queue delay before the handler. Counts are handler visits, including chained calls, not unique syscalls.", + path=str(path), tracers=len(starts | {key[:2] for key in latest}), + handlerCalls=sum(row["calls"] for row in rows), + handlerWallNs=sum(row["wall_ns"] for row in rows), + handlerCpuNs=sum(row["cpu_ns"] for row in rows), + malformedRecords=malformed, totals=rows[:limit], slowSamples=list(samples), + hasCounters=bool(latest)) diff --git a/tools/release/report-build.sh b/tools/release/report-build.sh index 75b16f666f..835bb6c65e 100644 --- a/tools/release/report-build.sh +++ b/tools/release/report-build.sh @@ -13,11 +13,8 @@ MARK="<!-- droiddeck-pr-build -->" echo echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key." echo - if [ "$SAME_REPO" = true ]; then - echo "After the parallel regression tests pass, a release-signed tester build that installs over Stable or Preview will be published and will appear in DroidDeck's **Test builds** list. Label the PR \`no-test-build\` to skip that." - else - echo "**Maintainer:** add the \`publish-test\` label to publish a release-signed tester build that installs over Stable or Preview and appears in DroidDeck's **Test builds** list. The label is removed automatically after publishing." - fi + echo "Same-repository PRs and PRs opened by contributors listed in \`.github/trusted-test-builds.txt\` are eligible for automatic release-signed test builds after the full build passes. Label the PR \`no-test-build\` to skip that." + echo "For other PRs, a maintainer can add the \`publish-test\` label to request a signed build." echo echo "Fallback: [open **PR Release Publish**]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/workflows/pr-release-publish.yml) on \`main\` and enter PR \`$PR\`." ;; diff --git a/tools/release/sign-apk.sh b/tools/release/sign-apk.sh index 2cf46c551e..c0fd0ace68 100755 --- a/tools/release/sign-apk.sh +++ b/tools/release/sign-apk.sh @@ -27,6 +27,7 @@ if [ "$pkg" = "$P" ]; then else python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \ "$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \ + "$P.pairingguide=$pkg.pairingguide" "$P.pin=$pkg.pin" \ "$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \ "$P.vr_recovery=$pkg.vr_recovery" \ "$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" diff --git a/tools/release/validate_apk.py b/tools/release/validate_apk.py index 8ed51ebf19..5969b1ae8e 100644 --- a/tools/release/validate_apk.py +++ b/tools/release/validate_apk.py @@ -34,6 +34,22 @@ def documentation_only(sha): return all(path.endswith(b".md") or path in (b"LICENSE", b".gitignore") for path in paths if path) +def trusted_list_violation(repo, pr, sha): + changed = subprocess.run( + ["git", "diff", "--no-renames", "--quiet", f"origin/main...{sha}", "--", ".github/trusted-test-builds.txt"], + check=False, + ) + if changed.returncode not in (0, 1): + raise RuntimeError("Could not check trusted contributor changes") + if changed.returncode == 0: + return [] + opener = pr["user"]["login"] + permission = api(f"repos/{repo}/collaborators/{opener}/permission") + if permission["permission"] != "admin" and permission.get("role_name") != "maintain": + return [f"Only a maintainer may open a PR changing .github/trusted-test-builds.txt (opened by @{opener})"] + return [] + + def main(): with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as source: event = json.load(source) @@ -76,6 +92,7 @@ def main(): commits, errors = check_revision(sha) if pr: errors.extend(event_violations({"pull_request": pr})) + errors.extend(trusted_list_violation(repo, pr, sha)) if errors: raise RuntimeError("\n".join(errors)) print(f"Source and metadata validated for {len(commits)} commits") diff --git a/tools/tests/ddfg_flow_levels_harness.cpp b/tools/tests/ddfg_flow_levels_harness.cpp new file mode 100644 index 0000000000..e5cf7bf701 --- /dev/null +++ b/tools/tests/ddfg_flow_levels_harness.cpp @@ -0,0 +1,359 @@ +#include "framegen.hpp" +#include <algorithm> +#include <cassert> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <map> +#include <memory> +#include <string> +#include <vector> + +namespace { + +constexpr int levels = 7; +constexpr VkImageUsageFlags flow_usage = + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; +enum Pipeline { LUMA, DOWNSAMPLE, FLOW3, FLOW4, EXPAND3, EXPAND4, GLOBAL_MOTION, PREWARP, FLOW_REG, SYNTH }; +struct Image { VkExtent3D extent; VkFormat format; VkImageUsageFlags usage; }; +struct Allocation { VkDeviceSize size; std::unique_ptr<uint8_t[]> data; }; +struct Binding { VkDescriptorType type; VkImageView view; VkBuffer buffer; VkDeviceSize range; }; +struct Dispatch { unsigned pipeline; uint32_t x, y, z; }; +std::map<VkImage, Image> images; +std::map<VkImageView, VkImage> views; +std::map<VkBuffer, VkBufferCreateInfo> buffers; +std::map<VkDeviceMemory, Allocation> allocations; +std::map<VkBuffer, VkDeviceMemory> buffer_memory; +std::map<VkDescriptorSet, std::map<uint32_t, Binding>> descriptors; +std::map<VkPipeline, unsigned> pipelines; +std::map<VkImage, unsigned> image_ids; +std::map<VkBuffer, unsigned> buffer_ids; +std::vector<Dispatch> dispatches; +uintptr_t serial = 100; +unsigned buffer_creates, set_creates; +VkPipeline bound_pipeline; +VkDescriptorSet bound_set; +uint64_t command_hash = 14695981039346656037ull; + +template<class T> T handle() { return reinterpret_cast<T>(++serial); } + +void hash(uint64_t value) { + for (unsigned i = 0; i < 8; i++) { + command_hash = (command_hash ^ (value & 255)) * 1099511628211ull; + value >>= 8; + } +} + +void hash_image(VkImage image) { + assert(images.count(image)); + if (!image_ids.count(image)) image_ids[image] = static_cast<unsigned>(image_ids.size() + 1); + const auto &info = images.at(image); + hash(image_ids.at(image)); + hash(info.extent.width); hash(info.extent.height); hash(info.format); hash(info.usage); +} + +template<class Info, class Out> +VkResult VKAPI_CALL create(VkDevice, const Info *, const VkAllocationCallbacks *, Out *out) { + *out = handle<Out>(); + return VK_SUCCESS; +} +template<class T> void VKAPI_CALL destroy(VkDevice, T, const VkAllocationCallbacks *) {} + +VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo *info, + const VkAllocationCallbacks *, VkImage *out) { + *out = handle<VkImage>(); + images[*out] = {info->extent, info->format, info->usage}; + return VK_SUCCESS; +} +VkResult VKAPI_CALL create_view(VkDevice, const VkImageViewCreateInfo *info, + const VkAllocationCallbacks *, VkImageView *out) { + assert(images.count(info->image)); + *out = handle<VkImageView>(); + views[*out] = info->image; + return VK_SUCCESS; +} +void VKAPI_CALL destroy_image(VkDevice, VkImage image, const VkAllocationCallbacks *) { + assert(images.erase(image) == 1); +} +void VKAPI_CALL destroy_view(VkDevice, VkImageView view, const VkAllocationCallbacks *) { + assert(views.erase(view) == 1); +} +VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info, + const VkAllocationCallbacks *, VkBuffer *out) { + *out = handle<VkBuffer>(); + buffers[*out] = *info; + buffer_creates++; + return VK_SUCCESS; +} +void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks *) { + assert(buffers.erase(buffer) == 1); + buffer_memory.erase(buffer); +} +void VKAPI_CALL image_requirements(VkDevice, VkImage image, VkMemoryRequirements *out) { + const auto &info = images.at(image); + const uint64_t bytes = info.format == VK_FORMAT_R32_SFLOAT ? 4 : 8; + *out = {uint64_t(info.extent.width) * info.extent.height * bytes, 1, 1}; +} +void VKAPI_CALL buffer_requirements(VkDevice, VkBuffer buffer, VkMemoryRequirements *out) { + *out = {buffers.at(buffer).size, 1, 1}; +} +VkResult VKAPI_CALL allocate(VkDevice, const VkMemoryAllocateInfo *info, + const VkAllocationCallbacks *, VkDeviceMemory *out) { + *out = handle<VkDeviceMemory>(); + allocations[*out].size = info->allocationSize; + return VK_SUCCESS; +} +void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks *) { + assert(allocations.erase(memory) == 1); +} +VkResult VKAPI_CALL bind_image(VkDevice, VkImage image, VkDeviceMemory memory, VkDeviceSize) { + assert(images.count(image) && allocations.count(memory)); + return VK_SUCCESS; +} +VkResult VKAPI_CALL bind_buffer(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) { + assert(buffers.count(buffer) && allocations.count(memory)); + buffer_memory[buffer] = memory; + return VK_SUCCESS; +} +VkResult VKAPI_CALL map_memory(VkDevice, VkDeviceMemory memory, VkDeviceSize offset, + VkDeviceSize size, VkMemoryMapFlags, void **out) { + auto &allocation = allocations.at(memory); + assert(offset == 0 && size <= allocation.size); + allocation.data = std::make_unique<uint8_t[]>(allocation.size); + *out = allocation.data.get(); + return VK_SUCCESS; +} +void VKAPI_CALL unmap(VkDevice, VkDeviceMemory memory) { assert(allocations.count(memory)); } +VkResult VKAPI_CALL idle(VkDevice) { return VK_SUCCESS; } +void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties *out) { + *out = {}; + out->memoryTypeCount = 1; + out->memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; +} +VkResult VKAPI_CALL allocate_sets(VkDevice, const VkDescriptorSetAllocateInfo *info, VkDescriptorSet *out) { + for (uint32_t i = 0; i < info->descriptorSetCount; i++) { + out[i] = handle<VkDescriptorSet>(); + descriptors[out[i]] = {}; + set_creates++; + } + return VK_SUCCESS; +} +VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool, VkDescriptorPoolResetFlags) { + descriptors.clear(); + return VK_SUCCESS; +} +void VKAPI_CALL update_sets(VkDevice, uint32_t count, const VkWriteDescriptorSet *writes, + uint32_t, const VkCopyDescriptorSet *) { + for (uint32_t i = 0; i < count; i++) { + const auto &write = writes[i]; + assert(descriptors.count(write.dstSet) && write.descriptorCount == 1); + Binding binding{write.descriptorType, VK_NULL_HANDLE, VK_NULL_HANDLE, 0}; + if (write.pImageInfo) { + binding.view = write.pImageInfo->imageView; + assert(views.count(binding.view)); + } else { + binding.buffer = write.pBufferInfo->buffer; + binding.range = write.pBufferInfo->range; + assert(buffers.count(binding.buffer)); + } + descriptors.at(write.dstSet)[write.dstBinding] = binding; + } +} +VkResult VKAPI_CALL create_pipelines(VkDevice, VkPipelineCache, uint32_t count, + const VkComputePipelineCreateInfo *, const VkAllocationCallbacks *, + VkPipeline *out) { + for (uint32_t i = 0; i < count; i++) { + const auto index = static_cast<unsigned>(pipelines.size()); + out[i] = handle<VkPipeline>(); + pipelines[out[i]] = index; + } + return VK_SUCCESS; +} +void VKAPI_CALL bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline pipeline) { + assert(pipelines.count(pipeline)); + bound_pipeline = pipeline; +} +void VKAPI_CALL bind_sets(VkCommandBuffer, VkPipelineBindPoint, VkPipelineLayout, + uint32_t, uint32_t count, const VkDescriptorSet *sets, + uint32_t, const uint32_t *) { + assert(count == 1 && descriptors.count(sets[0])); + bound_set = sets[0]; +} +void VKAPI_CALL dispatch(VkCommandBuffer, uint32_t x, uint32_t y, uint32_t z) { + const unsigned pipeline = pipelines.at(bound_pipeline); + dispatches.push_back({pipeline, x, y, z}); + hash(1); hash(pipeline); hash(x); hash(y); hash(z); + for (const auto &[slot, binding] : descriptors.at(bound_set)) { + hash(slot); hash(binding.type); + if (binding.view) { + hash_image(views.at(binding.view)); + } else { + if (!buffer_ids.count(binding.buffer)) + buffer_ids[binding.buffer] = static_cast<unsigned>(buffer_ids.size() + 1); + const auto &allocation = allocations.at(buffer_memory.at(binding.buffer)); + const auto size = binding.range == VK_WHOLE_SIZE ? allocation.size : binding.range; + assert(allocation.data && size <= allocation.size); + hash(buffer_ids.at(binding.buffer)); hash(size); + for (VkDeviceSize i = 0; i < size; i++) hash(allocation.data[i]); + } + } +} +void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags src, VkPipelineStageFlags dst, + VkDependencyFlags flags, uint32_t nm, const VkMemoryBarrier *memory, + uint32_t nb, const VkBufferMemoryBarrier *, uint32_t ni, + const VkImageMemoryBarrier *image) { + assert(nb == 0); + hash(2); hash(src); hash(dst); hash(flags); hash(nm); hash(ni); + for (uint32_t i = 0; i < nm; i++) { + hash(memory[i].srcAccessMask); hash(memory[i].dstAccessMask); + } + for (uint32_t i = 0; i < ni; i++) { + hash_image(image[i].image); + hash(image[i].oldLayout); hash(image[i].newLayout); + hash(image[i].srcAccessMask); hash(image[i].dstAccessMask); + hash(image[i].srcQueueFamilyIndex); hash(image[i].dstQueueFamilyIndex); + } +} +void VKAPI_CALL clear_image(VkCommandBuffer, VkImage image, VkImageLayout layout, + const VkClearColorValue *color, uint32_t count, const VkImageSubresourceRange *) { + assert(count == 1); + hash(3); hash_image(image); hash(layout); + for (unsigned i = 0; i < 4; i++) hash(color->uint32[i]); +} +void VKAPI_CALL copy_image(VkCommandBuffer, VkImage src, VkImageLayout sl, VkImage dst, + VkImageLayout dl, uint32_t count, const VkImageCopy *region) { + assert(count == 1); + hash(4); hash_image(src); hash(sl); hash_image(dst); hash(dl); + hash(region->extent.width); hash(region->extent.height); hash(region->extent.depth); +} + +uint32_t dimension(uint32_t full, int level) { return std::max(full >> level, 1u); } + +void check_images(uint32_t width, uint32_t height, int finest) { + assert(images.size() == static_cast<size_t>(32 - 2 * finest)); + for (int level = finest; level < levels; level++) { + const auto w = dimension(width, level), h = dimension(height, level); + assert(std::any_of(images.begin(), images.end(), [=](const auto &entry) { + const auto &image = entry.second; + return image.format == VK_FORMAT_R16G16B16A16_SFLOAT && image.usage == flow_usage && + image.extent.width == w && image.extent.height == h; + })); + } +} + +VkImageView external_image(uint32_t width, uint32_t height) { + VkImage image = handle<VkImage>(); + VkImageView view = handle<VkImageView>(); + images[image] = {{width, height, 1}, VK_FORMAT_R8G8B8A8_UNORM, + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT}; + views[view] = image; + return view; +} + +void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsigned generations) { + const auto previous = external_image(width, height), current = external_image(width, height); + const auto first = dispatches.size(); + for (unsigned i = 0; i < generations; i++) + fg.record(reinterpret_cast<VkCommandBuffer>(1), previous, current, external_image(width, height), + float(i + 1) / float(generations + 1), 0, i, i != 0); + std::vector<Dispatch> expected; + auto add = [&](unsigned pipeline, int level) { + expected.push_back({pipeline, (dimension(width, level) + 15) / 16, + (dimension(height, level) + 15) / 16, 1}); + }; + add(LUMA, 0); add(LUMA, 0); + for (int level = 1; level < levels; level++) { add(DOWNSAMPLE, level); add(DOWNSAMPLE, level); } + expected.push_back({GLOBAL_MOTION, 8, 1, 1}); + for (int level = fg.flowFinest(); level < levels; level++) add(PREWARP, level); + for (int level = levels - 1; level >= fg.flowFinest(); level--) add(model == 4 ? FLOW4 : FLOW3, level); + for (int i = 0; i < 4; i++) add(FLOW_REG, fg.flowFinest()); + add(model == 4 ? EXPAND4 : EXPAND3, 0); + for (unsigned i = 0; i < generations; i++) add(SYNTH, 0); + assert(dispatches.size() - first == expected.size()); + for (size_t i = 0; i < expected.size(); i++) { + const auto &actual = dispatches[first + i], &want = expected[i]; + assert(actual.pipeline == want.pipeline && actual.x == want.x && actual.y == want.y && actual.z == want.z); + } + for (auto it = views.begin(); it != views.end();) { + if (images.at(it->second).format == VK_FORMAT_R8G8B8A8_UNORM) { + images.erase(it->second); + it = views.erase(it); + } else ++it; + } +} + +} + +int main(int argc, char **argv) { + assert(argc == 8); + const std::string mode = argv[1]; + const int model = std::atoi(argv[2]), preset = std::atoi(argv[3]); + uint32_t width = static_cast<uint32_t>(std::atoi(argv[4])); + uint32_t height = static_cast<uint32_t>(std::atoi(argv[5])); + const unsigned generations = static_cast<unsigned>(std::atoi(argv[6])); + const unsigned repeats = static_cast<unsigned>(std::atoi(argv[7])); + assert((model == 3 || model == 4) && preset >= 0 && preset <= 2); + assert(width && height && generations >= 1 && generations <= 3 && repeats > 0); + ddfg::DeviceDispatch dd; + ddfg::InstanceDispatch id; + id.GetPhysicalDeviceMemoryProperties = memory_properties; + dd.CreateImage = create_image; dd.DestroyImage = destroy_image; + dd.CreateImageView = create_view; dd.DestroyImageView = destroy_view; + dd.CreateBuffer = create_buffer; dd.DestroyBuffer = destroy_buffer; + dd.GetImageMemoryRequirements = image_requirements; dd.GetBufferMemoryRequirements = buffer_requirements; + dd.AllocateMemory = allocate; dd.FreeMemory = free_memory; + dd.BindImageMemory = bind_image; dd.BindBufferMemory = bind_buffer; + dd.MapMemory = map_memory; dd.UnmapMemory = unmap; dd.DeviceWaitIdle = idle; + dd.CreateSampler = create<VkSamplerCreateInfo, VkSampler>; dd.DestroySampler = destroy<VkSampler>; + dd.CreateShaderModule = create<VkShaderModuleCreateInfo, VkShaderModule>; + dd.DestroyShaderModule = destroy<VkShaderModule>; + dd.CreateDescriptorSetLayout = create<VkDescriptorSetLayoutCreateInfo, VkDescriptorSetLayout>; + dd.DestroyDescriptorSetLayout = destroy<VkDescriptorSetLayout>; + dd.CreatePipelineLayout = create<VkPipelineLayoutCreateInfo, VkPipelineLayout>; + dd.DestroyPipelineLayout = destroy<VkPipelineLayout>; + dd.CreateDescriptorPool = create<VkDescriptorPoolCreateInfo, VkDescriptorPool>; + dd.DestroyDescriptorPool = destroy<VkDescriptorPool>; dd.ResetDescriptorPool = reset_pool; + dd.AllocateDescriptorSets = allocate_sets; dd.UpdateDescriptorSets = update_sets; + dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy<VkPipeline>; + dd.CmdBindPipeline = bind_pipeline; dd.CmdBindDescriptorSets = bind_sets; dd.CmdDispatch = dispatch; + dd.CmdPipelineBarrier = barrier; dd.CmdClearColorImage = clear_image; dd.CmdCopyImage = copy_image; + ddfg::FrameGen fg; + assert(fg.init(&dd, &id, reinterpret_cast<VkPhysicalDevice>(1), reinterpret_cast<VkDevice>(2), + 0, reinterpret_cast<VkQueue>(3))); + ddfg::Config cfg; + cfg.enabled = true; cfg.model = model; cfg.perfPreset = preset; cfg.flowScale = 0.6f; + fg.configure(cfg); + assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + assert(mode == "resources" || mode == "record" || mode == "resize" || mode == "preset"); + for (unsigned repeat = 0; repeat < repeats; repeat++) { + const auto old_buffers = buffer_creates, old_sets = set_creates; + if (mode != "record") check_images(width, height, fg.flowFinest()); + record(fg, model, width, height, generations); + if (mode != "record") { + assert(buffer_creates - old_buffers == static_cast<unsigned>(15 - fg.flowFinest())); + assert(set_creates - old_sets == static_cast<unsigned>(54 - 4 * fg.flowFinest())); + } + if (repeat + 1 == repeats) break; + if (mode == "resize") { + width += 17; height += 9; + assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + } else if (mode == "preset") { + cfg.perfPreset = (cfg.perfPreset + 1) % 3; + fg.configure(cfg); + } else { + assert(mode == "record"); + } + } + uint64_t bytes = 0; + for (const auto &[image, info] : images) { + (void)image; + bytes += uint64_t(info.extent.width) * info.extent.height * + (info.format == VK_FORMAT_R32_SFLOAT ? 4 : 8); + } + std::printf("PASS images=%zu bytes=%llu buffers=%u sets=%u dispatches=%zu trace=%016llx\n", + images.size(), static_cast<unsigned long long>(bytes), buffer_creates, set_creates, + dispatches.size(), static_cast<unsigned long long>(command_hash)); + fg.destroy(); + assert(images.empty() && views.empty()); +} diff --git a/tools/tests/test_android_volume.py b/tools/tests/test_android_volume.py new file mode 100644 index 0000000000..8246f34fe1 --- /dev/null +++ b/tools/tests/test_android_volume.py @@ -0,0 +1,101 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +@unittest.skipUnless(shutil.which("cc"), "C compiler required") +class AndroidVolumeTest(unittest.TestCase): + def test_missing_or_invalid_initial_state_recovers_without_restarting_the_sink(self): + header = Path(__file__).resolve().parents[1] / "aaudio-sink/android-volume.h" + harness = r''' +#define _GNU_SOURCE +#include <assert.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <stdarg.h> +#include <stdlib.h> +#include <string.h> +#include <sys/time.h> +#include <unistd.h> +#define PA_VOLUME_NORM 65536U +#define PA_USEC_PER_MSEC 1000 +#define PA_SINK_INIT 0 +#define PA_SUBSCRIPTION_EVENT_SINK 1 +#define PA_SUBSCRIPTION_EVENT_CHANGE 2 +#define PA_MIN(a,b) ((a)<(b)?(a):(b)) +#define pa_xnew0(type,n) ((type*)calloc(n,sizeof(type))) +#define pa_xstrdup strdup +#define pa_xfree free +#define pa_log_warn(...) ((void)0) +typedef struct { unsigned value; } pa_cvolume; +typedef struct pa_time_event { int value; } pa_time_event; +typedef struct pa_mainloop_api { void (*time_free)(pa_time_event*); } pa_mainloop_api; +typedef struct { pa_mainloop_api *mainloop; } pa_core; +typedef struct pa_sink { + void *userdata; int state; bool muted; unsigned n_volume_steps, index; + struct { unsigned channels; } sample_spec; + pa_cvolume real_volume, reference_volume, soft_volume; + pa_core *core; + void (*set_volume)(struct pa_sink*), (*set_mute)(struct pa_sink*); +} pa_sink; +struct android_volume; +struct userdata { struct android_volume *android_volume; }; +static int restarts, frees; +static char *pa_sprintf_malloc(const char *format, ...) { + va_list ap; va_start(ap,format); char *result; assert(vasprintf(&result,format,ap)>=0); va_end(ap); return result; +} +static void pa_cvolume_set(pa_cvolume *volume, unsigned channels, unsigned value) { volume->value=value; } +static unsigned pa_cvolume_max(const pa_cvolume *volume) { return volume->value; } +static void pa_cvolume_reset(pa_cvolume *volume, unsigned channels) { volume->value=PA_VOLUME_NORM; } +static bool pa_cvolume_equal(const pa_cvolume *a, const pa_cvolume *b) { return a->value==b->value; } +static void pa_sink_volume_changed(pa_sink *sink, const pa_cvolume *volume) { sink->real_volume=*volume; } +static void pa_sink_mute_changed(pa_sink *sink, bool muted) { sink->muted=muted; } +static void pa_sink_set_set_volume_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_volume=callback; } +static void pa_sink_set_set_mute_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_mute=callback; } +static void pa_subscription_post(pa_core *core, int event, unsigned index) {} +static uint64_t pa_rtclock_now(void) { return 0; } +static void pa_core_rttime_restart(pa_core *core, pa_time_event *event, uint64_t time) { restarts++; } +static pa_time_event *pa_core_rttime_new(pa_core *core, uint64_t time, + void (*callback)(pa_mainloop_api*,pa_time_event*,const struct timeval*,void*), void *userdata) { + return calloc(1,sizeof(pa_time_event)); +} +static void free_timer(pa_time_event *event) { frees++; free(event); } +#include "android-volume.h" +static void state(const char *directory, const char *text) { + char *path=pa_sprintf_malloc("%s/volume.state",directory); + FILE *f=fopen(path,"w"); assert(f); fputs(text,f); fclose(f); free(path); +} +int main(int argc, char **argv) { + pa_mainloop_api api={.time_free=free_timer}; pa_core core={.mainloop=&api}; + struct userdata userdata={0}; + pa_sink sink={.userdata=&userdata,.core=&core,.state=1,.sample_spec={.channels=2},.real_volume={PA_VOLUME_NORM}}; + userdata.android_volume=android_volume_new(&sink,argv[1]); + assert(userdata.android_volume && userdata.android_volume->timer && sink.set_volume && sink.set_mute); + state(argv[1],"invalid\n"); + android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume); + assert(sink.real_volume.value==PA_VOLUME_NORM && restarts==1); + state(argv[1],"3 15 1\n"); + android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume); + assert(sink.real_volume.value==3*PA_VOLUME_NORM/15 && sink.muted && sink.n_volume_steps==16); + assert(sink.soft_volume.value==PA_VOLUME_NORM && restarts==2); + sink.real_volume.value=2*PA_VOLUME_NORM/3; sink.set_volume(&sink); + char *request=pa_sprintf_malloc("%s/volume.request",argv[1]); + FILE *f=fopen(request,"r"); unsigned level; assert(f && fscanf(f,"%u",&level)==1 && level==10); fclose(f); free(request); + android_volume_free(userdata.android_volume); assert(frees==1); + return 0; +} +''' + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "pulsecore").mkdir() + for name in ("core-rtclock.h", "core-subscribe.h"): + (root / "pulsecore" / name).touch() + source = root / "test.c" + source.write_text(harness) + binary = root / "test" + subprocess.run(["cc", "-std=c11", "-I", str(root), "-I", str(header.parent), + str(source), "-o", str(binary)], check=True, capture_output=True) + subprocess.run([str(binary), str(root)], check=True, capture_output=True) diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py new file mode 100644 index 0000000000..aed66699ed --- /dev/null +++ b/tools/tests/test_battlenet.py @@ -0,0 +1,1275 @@ +import contextlib +import json +import os +from pathlib import Path +import re +import runpy +import shutil +import tempfile +import threading +import time +import unittest +from unittest import mock +import zlib + +REPO = Path(__file__).resolve().parents[2] +BIN = REPO / "tools/linuxfs/overlay/usr/local/bin" +BNET = runpy.run_path(str(BIN / "droiddeck-battlenet"))["main"].__globals__ +BNET["CACHE"] = tempfile.mkdtemp(prefix="bnet-test-cache-") +BNET["LOG"] = os.path.join(BNET["CACHE"], "battlenet.log") +RUN = runpy.run_path(str(BIN / "droiddeck-proton-run"))["main"].__globals__ +STORE = runpy.run_path(str(BIN / "droiddeck-store-launch"))["main"].__globals__ +KOTLIN = REPO / "app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt" + + +class Temp(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + + def write(self, relative, data, mode=0o644): + path = self.tmp / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data if isinstance(data, bytes) else data.encode()) + path.chmod(mode) + return path + + +class LogTest(Temp): + def test_each_line_is_kept_and_a_long_log_rotates(self): + log = self.tmp / "battlenet.log" + with open(os.devnull, "w") as null, \ + mock.patch.dict(BNET, {"CACHE": str(self.tmp), "LOG": str(log), "LOG_LIMIT": 64}), \ + mock.patch.object(BNET["sys"], "stderr", null): + BNET["say"]("first line, long enough to pass the limit of sixty-four bytes") + BNET["say"]("second") + self.assertIn("first line", (self.tmp / "battlenet.log.1").read_text()) + self.assertRegex(log.read_text(), r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d \[\d+\] second\n$") + + +class IdTest(unittest.TestCase): + def test_the_prefix_id_is_the_shortcut_id_the_app_names(self): + self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000) + found = re.search(r"const val APP_ID = (\d+)L", KOTLIN.read_text()) + self.assertEqual(found.group(1), BNET["APP_ID"]) + for name in ("FEX_REQUEST", "FEX_RESULT"): + self.assertIn('const val %s = "%s"' % (name, BNET[name]), KOTLIN.read_text()) + + +class ProtonRunOptionsTest(Temp): + def setUp(self): + super().setUp() + self.root = self.tmp / "Steam" + folder = self.root / "compatibilitytools.d/droiddeck-proton-arm64" + self.write("Steam/compatibilitytools.d/droiddeck-proton-arm64/compatibilitytool.vdf", + '"compatibilitytools"\n{\n "compat_tools"\n {\n "droiddeck-proton-arm64"\n {\n' + ' "install_path" "."\n "display_name" "x"\n "from_oslist" "windows"\n' + ' "to_oslist" "linux"\n }\n }\n}\n') + self.write("Steam/compatibilitytools.d/droiddeck-proton-arm64/toolmanifest.vdf", + '"manifest"\n{\n "commandline" "/droiddeck-proton %verb%"\n}\n') + self.write("Steam/compatibilitytools.d/droiddeck-proton-arm64/droiddeck-proton", b"#!/bin/sh\n", 0o755) + self.entry = str(folder / "droiddeck-proton") + patcher = mock.patch.dict(RUN, {"EXTRA_LIBRARIES": (), "SYSTEM_TOOLS": (), "STATE": str(self.tmp / "state.json"), + "say": lambda message: None}) + patcher.start() + self.addCleanup(patcher.stop) + + def run_main(self, argv): + calls = [] + with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.root)}), \ + mock.patch.object(RUN["os"], "execve", lambda *a: calls.append(a)), mock.patch.object(RUN["os"], "chdir"): + status = RUN["main"](argv) + return status, calls + + def test_a_named_prefix_wins_over_where_the_program_lies(self): + setup = str(self.write("Download/Battle.net-Setup.exe", b"MZ")) + status, calls = self.run_main(["--window", "--prefix", "2596113170", setup]) + self.assertIsNone(status) + entry, argv, env = calls[0] + self.assertEqual(argv, [self.entry, "waitforexitandrun", setup]) + self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(self.root / "steamapps/compatdata/2596113170")) + self.assertEqual((env["SteamAppId"], env["SteamGameId"], env["PROTON_USE_WINED3D"]), + ("0", str(2596113170 << 32 | 0x02000000), "1")) + self.assertTrue((self.root / "steamapps/compatdata/2596113170").is_dir()) + + def test_run_starts_beside_what_runs_in_the_prefix(self): + client = str(self.write("Steam/steamapps/compatdata/2596113170/pfx/drive_c/Battle.net.exe", b"MZ")) + _, calls = self.run_main(["--verb", "run", client]) + self.assertEqual(calls[0][1], [self.entry, "run", client]) + + def test_a_launch_from_steam_keeps_its_game_id_for_gamescope(self): + client = str(self.write("Steam/steamapps/compatdata/2596113170/pfx/drive_c/Battle.net.exe", b"MZ")) + _, calls = self.run_main(["--prefix", "2596113170", "--game-id", "11151176786366644224", client]) + env = calls[0][2] + self.assertEqual((env["SteamGameId"], env["SteamOverlayGameId"]), ("11151176786366644224", "11151176786366644224")) + self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(self.root / "steamapps/compatdata/2596113170")) + self.assertNotIn("PROTON_USE_WINED3D", env) + self.assertEqual(self.run_main(["--game-id", "0", client]), (2, [])) + + def test_start_without_steam_has_droiddeck_battlenet_launch_a_games_shortcut(self): + client = str(self.write("Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe", b"MZ")) + prefix = str(self.root / "steamapps/compatdata/2596113170") + options = 'STEAM_COMPAT_DATA_PATH=%s %%command%% --exec="launch Fen"' % prefix + status, calls = self.run_main(["--app", "3000000000", "--dir", os.path.dirname(client), "--options", options, "--", client]) + self.assertIsNone(status) + _, argv, env = calls[0] + self.assertEqual(argv, [self.entry, "waitforexitandrun", client, "--exec=launch Fen"]) + self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], prefix) + self.assertEqual(STORE["battlenet"](argv[2:], env={}), [STORE["BATTLENET"], "launch", "Fen"]) + + def test_a_bad_prefix_or_verb_is_refused(self): + setup = str(self.write("Download/setup.exe", b"MZ")) + for argv in (["--prefix", "0", setup], ["--prefix", "07", setup], ["--prefix", "4294967296", setup], + ["--prefix", "abc", setup], ["--prefix"], ["--verb", "getcompatpath", setup]): + with self.subTest(argv): + self.assertEqual(self.run_main(list(argv)), (2, [])) + + +class ConfigAndMenuTest(Temp): + def config_path(self): + return self.tmp / ("steamapps/compatdata/%s/pfx/drive_c/users/steamuser/AppData/Roaming/Battle.net/Battle.net.config" + % BNET["APP_ID"]) + + def test_the_config_keeps_browser_hardware_acceleration_off(self): + root = str(self.tmp) + self.assertEqual(BNET["write_config"](root), "first") + path = self.config_path() + config = json.loads(path.read_text()) + self.assertEqual(config["Client"]["HardwareAcceleration"], "false") + self.assertEqual(config["Client"]["Streaming"]["StreamingEnabled"], "false") + self.assertEqual(config["Client"]["GameLaunchWindowBehavior"], "2") + self.assertIsNone(BNET["write_config"](root)) + path.write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "0"}, "Games": {"osi": {}}}') + self.assertEqual(BNET["write_config"](root), "launch 32-bit") + config = json.loads(path.read_text()) + self.assertEqual(config, {"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "2"}, + "Games": {"osi": {}, "s1": {"Run64Bit": "false", "Run64BitSet": "true"}}}) + path.write_text('{"Client": {"HardwareAcceleration": "true", "GameLaunchWindowBehavior": "2"}}') + self.assertEqual(BNET["write_config"](root), "acceleration 32-bit") + self.assertEqual(json.loads(path.read_text())["Client"]["HardwareAcceleration"], "false") + + def test_starcraft_starts_its_32_bit_client_until_a_player_picks_one(self): + root = str(self.tmp) + BNET["write_config"](root) + self.assertEqual(json.loads(self.config_path().read_text())["Games"], {"s1": {"Run64Bit": "false", "Run64BitSet": "true"}}) + self.config_path().write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "2"}, ' + '"Games": {"s1": {"ServerUid": "s1", "Run64Bit": "true"}}}') + self.assertEqual(BNET["write_config"](root), "32-bit") + self.assertEqual(json.loads(self.config_path().read_text())["Games"]["s1"], + {"ServerUid": "s1", "Run64Bit": "false", "Run64BitSet": "true"}) + self.config_path().write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "2"}, ' + '"Games": {"s1": {"Run64Bit": "true", "Run64BitSet": "true"}}}') + self.assertIsNone(BNET["write_config"](root)) + self.config_path().write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "2"}, "Games": []}') + self.assertIsNone(BNET["write_config"](root)) + + def test_games_install_to_the_chosen_library(self): + root = str(self.tmp) + BNET["write_config"](root) + self.assertEqual(BNET["write_config"](root, "/root/Games/Stores/Battle.net"), "library") + config = json.loads(self.config_path().read_text()) + self.assertEqual(config["Client"]["Install"]["DefaultInstallPath"], "Z:/root/Games/Stores/Battle.net") + self.assertIsNone(BNET["write_config"](root, "/root/Games/Stores/Battle.net/")) + config["Client"]["Install"]["DefaultInstallPath"] = "Z:/root/Games/Stores/Battle.net/" + self.config_path().write_text(json.dumps(config)) + self.assertIsNone(BNET["write_config"](root, "/root/Games/Stores/Battle.net")) + self.assertEqual(BNET["write_config"](root, "/mnt/droiddeck-sd/Games/Battle.net"), "library") + + def test_a_config_that_is_not_json_is_left_alone(self): + path = self.config_path() + path.parent.mkdir(parents=True) + for text in ("{not json", "[1, 2]", '{"Client": "x"}'): + with self.subTest(text): + path.write_text(text) + self.assertIsNone(BNET["write_config"](str(self.tmp))) + self.assertEqual(path.read_text(), text) + + def test_the_menu_entry_is_a_window_not_a_game(self): + path = self.tmp / "applications/droiddeck-battlenet.desktop" + BNET["write_menu"](str(path)) + text = path.read_text() + self.assertIn("Exec=/usr/local/bin/droiddeck-battlenet\n", text) + self.assertIn("Name=Battle.net\n", text) + self.assertNotIn("Game", re.search(r"^Categories=(.*)$", text, re.M).group(1)) + self.assertNotIn("StartupWMClass", text) + mtime = path.stat().st_mtime_ns + time.sleep(0.01) + BNET["write_menu"](str(path)) + self.assertEqual(path.stat().st_mtime_ns, mtime) + + +class GamepadTest(Temp): + def registry(self, *entries): + rows = ["WINE REGISTRY Version 2"] + for name, uid, location in entries: + rows += ["", "[Software\\\\Wow6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\%s] 1" % name, + '"InstallLocation"="%s"' % location.replace("\\", "\\\\"), + '"UninstallString"="\\"C:\\\\ProgramData\\\\Battle.net\\\\Agent\\\\Blizzard Uninstaller.exe\\" --uid=%s"' % uid] + self.write("Steam/steamapps/compatdata/%s/pfx/system.reg" % BNET["APP_ID"], "\n".join(rows) + "\n") + + def z(self, path): + return "Z:" + str(path).replace("/", "\\") + + def test_every_world_of_warcraft_flavor_gets_controllers_on(self): + wow = self.tmp / "Games/World of Warcraft" + retail = self.write("Games/World of Warcraft/_retail_/WTF/Config.wtf", 'SET gxApi "D3D11"') + (wow / "_classic_era_").mkdir(parents=True) + (wow / "Data").mkdir() + self.registry(("World of Warcraft", "wow", self.z(wow))) + with mock.patch.dict(BNET, {"say": lambda message: None}): + self.assertEqual(len(BNET["wow_settings"](str(self.tmp / "Steam"))), 2) + self.assertEqual(BNET["wow_settings"](str(self.tmp / "Steam")), []) + self.assertEqual(retail.read_text(), 'SET gxApi "D3D11"\nSET GamePadEnable "1"\n') + self.assertEqual((wow / "_classic_era_/WTF/Config.wtf").read_text(), 'SET GamePadEnable "1"\nSET gxApi "D3D11"\n') + self.assertFalse((wow / "Data/WTF").exists()) + + def test_directx_11_is_set_once_and_a_later_pick_is_kept(self): + wow = self.tmp / "Games/World of Warcraft" + retail = self.write("Games/World of Warcraft/_retail_/WTF/Config.wtf", 'SET GxApi "D3D12"\nSET GamePadEnable "1"\nSET vsync "1"\n') + self.registry(("World of Warcraft", "wow", self.z(wow))) + with mock.patch.dict(BNET, {"say": lambda message: None}): + self.assertEqual(len(BNET["wow_settings"](str(self.tmp / "Steam"))), 1) + self.assertEqual(retail.read_text(), 'SET gxApi "D3D11"\nSET GamePadEnable "1"\nSET vsync "1"\n') + self.assertTrue((wow / "_retail_/WTF/.droiddeck-d3d11").exists()) + retail.write_text('SET gxApi "d3d12"\nSET GamePadEnable "1"\nSET vsync "1"\n') + self.assertEqual(BNET["wow_settings"](str(self.tmp / "Steam")), []) + self.assertEqual(retail.read_text(), 'SET gxApi "d3d12"\nSET GamePadEnable "1"\nSET vsync "1"\n') + + def test_a_players_own_choice_and_other_games_are_left_alone(self): + wow = self.tmp / "Games/World of Warcraft Classic" + config = self.write("Games/World of Warcraft Classic/_anniversary_/WTF/Config.wtf", 'SET GamePadEnable "0"\n') + other = self.tmp / "Games/Diablo IV" + (other / "_retail_").mkdir(parents=True) + self.registry(("World of Warcraft Classic", "wow_classic_anniversary", self.z(wow)), ("Diablo IV", "fenris", self.z(other))) + with mock.patch.dict(BNET, {"say": lambda message: None}): + self.assertEqual(len(BNET["wow_settings"](str(self.tmp / "Steam"))), 1) + self.assertEqual(config.read_text(), 'SET GamePadEnable "0"\nSET gxApi "D3D11"\n') + self.assertFalse((other / "_retail_/WTF").exists()) + + def test_pads_look_like_an_xbox_360_pad_only_without_the_steam_client(self): + proc = self.tmp / "proc" + self.write("proc/10/cmdline", b"/usr/bin/python3\0/usr/local/bin/droiddeck-battlenet\0") + self.write("proc/11/cmdline", b"c:\\windows\\system32\\steam.exe\0") + self.assertFalse(BNET["steam_running"](str(proc))) + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("PROTON_SPOOF_STEAMINPUT_VIDPID", None) + with mock.patch.dict(BNET, {"steam_running": lambda: False}): + self.assertEqual(BNET["proton_env"]()["PROTON_SPOOF_STEAMINPUT_VIDPID"], "1") + with mock.patch.dict(BNET, {"steam_running": lambda: True}): + self.assertNotIn("PROTON_SPOOF_STEAMINPUT_VIDPID", BNET["proton_env"]()) + os.environ["PROTON_SPOOF_STEAMINPUT_VIDPID"] = "0" + with mock.patch.dict(BNET, {"steam_running": lambda: False}): + self.assertEqual(BNET["proton_env"]()["PROTON_SPOOF_STEAMINPUT_VIDPID"], "0") + self.write("proc/12/cmdline", b"/usr/bin/FEX\0/root/.local/share/Steam/ubuntu12_32/steam\0-silent\0") + self.assertTrue(BNET["steam_running"](str(proc))) + + +class ProcessTest(Temp): + def proc(self, pid, argv, prefix=None): + env = b"HOME=/root\0" + (("WINEPREFIX=%s\0" % prefix).encode() if prefix else b"") + self.write("proc/%d/environ" % pid, env) + self.write("proc/%d/cmdline" % pid, b"\0".join(a.encode() for a in argv) + b"\0") + + def test_the_prefixs_processes_are_found_by_their_wineprefix(self): + pfx = self.tmp / "compatdata/2596113170/pfx" + pfx.mkdir(parents=True) + self.proc(10, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe", "--from-launcher"], str(pfx) + "/") + self.proc(11, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.9142\\Agent.exe"], str(pfx)) + self.proc(12, ["C:\\Games\\Other.exe"], str(self.tmp / "compatdata/42/pfx")) + self.proc(13, ["/usr/bin/bash"]) + self.write("proc/self/environ", b"") + found = BNET["wine_processes"](str(pfx), str(self.tmp / "proc")) + self.assertEqual(sorted(pid for pid, _ in found), [10, 11]) + self.assertEqual([pid for pid, argv in found if BNET["is_client"](argv)], [10]) + + def test_only_battle_net_itself_counts_as_open(self): + self.assertTrue(BNET["is_client"](["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"])) + self.assertTrue(BNET["is_client"](["/root/.local/share/Steam/x/Battle.net.exe", "--x"])) + self.assertTrue(BNET["is_client"](["battle.net.exe"])) + self.assertFalse(BNET["is_client"](["C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"])) + self.assertFalse(BNET["is_client"](["C:\\users\\steamuser\\Temp\\Battle.net-Setup.exe"])) + self.assertFalse(BNET["is_client"]([])) + + def test_battle_nets_own_processes_are_those_under_its_folders(self): + for argv in (["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe", "--type=renderer"], + ["C:/ProgramData/Battle.net/Agent/Agent.9824/Agent.exe"], + ["C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"]): + with self.subTest(argv): + self.assertTrue(BNET["is_battlenet"](argv)) + for argv in (["Z:\\root\\.cache\\droiddeck\\battlenet\\Battle.net-Setup.exe"], + ["Z:\\root\\Games\\Stores\\Battle.net\\Hearthstone\\Hearthstone.exe"], + ["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe"], ["C:\\windows\\system32\\services.exe"], []): + with self.subTest(argv): + self.assertFalse(BNET["is_battlenet"](argv)) + + def test_a_game_battle_net_launched_carries_its_uid(self): + self.assertTrue(BNET["launched"](["C:\\Program Files (x86)\\Diablo II Resurrected\\D2R.exe", "-uid", "osi"])) + self.assertTrue(BNET["launched"](["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe", "-launch", "-UID", "fenris"])) + for argv in (["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe"], + ["C:\\Program Files (x86)\\Diablo IV\\vc_redist.x64.exe", "/quiet"], + ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe", "-uid", "battle.net"]): + with self.subTest(argv): + self.assertFalse(BNET["launched"](argv)) + + def test_a_game_that_signs_in_with_battle_nets_token_says_so(self): + self.assertTrue(BNET["shares_sign_in"](["Diablo IV.exe", "-nostreamline", "-sso", "-launch", "-uid", "fenris"])) + self.assertFalse(BNET["shares_sign_in"](["D2R.exe", "-uid", "osi"])) + self.assertFalse(BNET["shares_sign_in"](["-sso.exe"])) + + def test_battle_net_takes_work_once_its_agent_is_up(self): + client = (1, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"]) + agent = (2, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.9824\\Agent.exe"]) + self.assertTrue(BNET["agent_up"]([client, agent])) + self.assertFalse(BNET["agent_up"]([client])) + self.assertFalse(BNET["agent_up"]([agent])) + + def test_open_is_waited_for_then_closed(self): + states = iter([False, False, True, True, False]) + with mock.patch.dict(BNET, {"running": lambda pfx: next(states)}), mock.patch.object(BNET["time"], "sleep"): + self.assertTrue(BNET["wait_while_open"]("/pfx", grace=60, poll=0)) + with mock.patch.dict(BNET, {"running": lambda pfx: False}): + self.assertFalse(BNET["wait_while_open"]("/pfx", grace=0, poll=0)) + + +class ProtonWaitTest(Temp): + class Process: + def __init__(self, test, waits): + self.test, self.waits = test, waits + + def wait(self, timeout=None): + self.waits -= 1 + if self.test.stopped or self.waits < 0: + return 0 + raise BNET["subprocess"].TimeoutExpired("proton", timeout) + + def setUp(self): + super().setUp() + self.stopped = [] + + def run_proton(self, states, close_grace=0, waits=100): + states = iter(states) + last = [] + + def processes(pfx, proc="/proc"): + last[:] = next(states, last) + return list(last) + + with mock.patch.dict(BNET, {"wine_processes": processes, "say": lambda message: None, + "stop": lambda found, wait=0: self.stopped.extend(pid for pid, _ in found)}), \ + mock.patch.object(BNET["subprocess"], "Popen", lambda cmd, **kw: self.Process(self, waits)): + return BNET["proton"]("launcher.exe", watch="/pfx", poll=0, close_grace=close_grace) + + def test_agent_and_wine_left_behind_are_stopped_once_battle_net_closed(self): + client = (1, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"]) + agent = (2, ["C:/ProgramData/Battle.net/Agent/Agent.9824/Agent.exe", "--locale=enUS"]) + wine = (3, ["C:\\windows\\system32\\services.exe"]) + self.assertEqual(self.run_proton([[client, agent, wine], [agent, wine], [agent, wine]]), (0, True)) + self.assertEqual(sorted(self.stopped), [2, 3]) + + def test_nothing_is_stopped_while_a_game_still_runs(self): + client = (1, ["Battle.net.exe"]) + game = (4, ["C:\\Games\\Diablo IV\\Diablo IV.exe"]) + self.assertEqual(self.run_proton([[client, game]] + [[game]] * 5, waits=6), (0, True)) + self.assertEqual(self.stopped, []) + + def test_a_restart_to_update_is_not_a_close(self): + client = (1, ["Battle.net.exe"]) + agent = (2, ["Agent.exe"]) + states = [[client, agent], [agent], [client, agent], [agent]] + with mock.patch.object(BNET["time"], "monotonic", side_effect=[0, 0, 5, 5, 10, 10, 30, 30, 30, 30]): + self.run_proton(states, close_grace=15) + self.assertEqual(self.stopped, [2]) + + def test_battle_net_is_closed_once_a_game_is_up_and_what_is_left_once_it_exits(self): + client = (1, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"]) + agent = (2, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.9824\\Agent.exe"]) + wine = (3, ["C:\\windows\\system32\\services.exe"]) + game = (4, ["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe", "-launch", "-uid", "fenris"]) + tidy = BNET["Tidy"](settle=0, gone=60) + states = [[client, agent, wine], [client, agent, wine, game], [wine, game], [wine, game], [wine], [wine]] + with mock.patch.dict(BNET, {"notify": lambda *a, **k: self.fail("notified")}): + self.assertEqual(self.run_proton_tidy(states, tidy), (0, True)) + self.assertEqual(self.stopped, [1, 2, 3]) + + def run_proton_tidy(self, states, tidy): + states = iter(states) + last = [] + test = self + + def processes(pfx, proc="/proc"): + last[:] = next(states, last) + return list(last) + + class Process: + def wait(self, timeout=None): + if 3 in test.stopped: + return 0 + raise BNET["subprocess"].TimeoutExpired("proton", timeout) + + with mock.patch.dict(BNET, {"wine_processes": processes, "say": lambda message: None, + "stop": lambda found, wait=0: self.stopped.extend(pid for pid, _ in found)}), \ + mock.patch.object(BNET["subprocess"], "Popen", lambda cmd, **kw: Process()): + return BNET["proton"]("launcher.exe", watch="/pfx", poll=0, close_grace=0, tidy=tidy) + + def test_only_wine_and_agent_are_idle(self): + self.assertTrue(BNET["idle"]([(1, ["C:\\windows\\system32\\explorer.exe", "/desktop"]), + (2, ["/x/files/bin/wineserver"]), (3, ["c:\\windows\\system32\\steam.exe", "a"])])) + self.assertFalse(BNET["idle"]([(1, ["Battle.net.exe"])])) + self.assertFalse(BNET["idle"]([(1, ["Z:\\root\\.cache\\droiddeck\\battlenet\\Battle.net-Setup.exe"])])) + + +class RequestTest(Temp): + UP = [(1, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"]), + (2, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.9437\\Agent.exe"])] + + def test_the_apps_request_waits_for_battle_net_then_goes_to_it(self): + (self.tmp / "battlenet-request.00000000000000000001").write_text("install-game\nhs_beta\n") + calls = [] + with mock.patch.dict(BNET, {"spawn": lambda exe, verb, args=(): calls.append((exe, verb, list(args))) or 0}): + self.assertFalse(BNET["serve_requests"]("/p/pfx", self.UP[:1], str(self.tmp))) + self.assertTrue((self.tmp / "battlenet-request.00000000000000000001").exists()) + self.assertTrue(BNET["serve_requests"]("/p/pfx", self.UP, str(self.tmp))) + (self.tmp / "battlenet-request.00000000000000000002").write_text("launch\nWTCG\n") + self.assertTrue(BNET["serve_requests"]("/p/pfx", self.UP, str(self.tmp))) + (self.tmp / "battlenet-request.00000000000000000003").write_text("launch\nWTCG;reboot\n") + self.assertFalse(BNET["serve_requests"]("/p/pfx", self.UP, str(self.tmp))) + client = "/p/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe" + self.assertEqual(calls, [(client, "run", ["--install", "--game=hs_beta"]), (client, "run", ["--exec=launch WTCG"])]) + self.assertEqual(list(self.tmp.iterdir()), []) + + def test_requests_left_before_the_poll_are_all_served_in_order(self): + (self.tmp / "battlenet-request.00000000000000000020").write_text("launch\nOSI\n") + (self.tmp / "battlenet-request.00000000000000000010").write_text("install-game\nwow\n") + (self.tmp / "battlenet-request.00000000000000000030.tmp").write_text("install-game\nfenris\n") + calls = [] + with mock.patch.dict(BNET, {"spawn": lambda exe, verb, args=(): calls.append(list(args)) or 0}): + self.assertTrue(BNET["serve_requests"]("/p/pfx", self.UP, str(self.tmp))) + self.assertEqual(calls, [["--install", "--game=wow"], ["--exec=launch OSI"]]) + self.assertEqual([p.name for p in self.tmp.iterdir()], ["battlenet-request.00000000000000000030.tmp"]) + + +class TidyTest(unittest.TestCase): + CLIENT = (1, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"]) + PAGE = (2, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe", "--type=renderer"]) + AGENT = (3, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.9824\\Agent.exe"]) + WINE = (4, ["C:\\windows\\system32\\services.exe"]) + GAME = (5, ["C:\\Program Files (x86)\\Diablo II Resurrected\\D2R.exe", "-uid", "osi"]) + + def setUp(self): + self.stopped = [] + self.notified = [] + patcher = mock.patch.dict(BNET, { + "say": lambda message: None, + "stop": lambda found, wait=0: self.stopped.append(sorted(pid for pid, _ in found)), + "notify": lambda title, body, icon=None: self.notified.append(title), + }) + patcher.start() + self.addCleanup(patcher.stop) + + def run_tidy(self, tidy, timeline): + return [tidy(processes, now) for now, processes in timeline] + + def test_battle_net_and_its_agent_close_once_the_game_has_run_a_while(self): + up = [self.CLIENT, self.PAGE, self.AGENT, self.WINE] + tidy = BNET["Tidy"](settle=20, gone=30) + closed = self.run_tidy(tidy, [(0, up), (5, up + [self.GAME]), (24, up + [self.GAME]), (25, up + [self.GAME]), + (40, up + [self.GAME])]) + self.assertEqual(closed, [False, False, False, True, False]) + self.assertEqual(self.stopped, [[1, 2, 3]]) + self.assertEqual(self.notified, []) + + def test_battle_net_beside_a_game_signing_in_with_its_token_is_left_open(self): + d4 = (6, ["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe", "-nostreamline", "-sso", "-launch", "-uid", "fenris"]) + up = [self.CLIENT, self.PAGE, self.AGENT] + tidy = BNET["Tidy"](settle=20, gone=30) + closed = self.run_tidy(tidy, [(0, up + [d4]), (25, up + [d4]), (30, [self.CLIENT, self.PAGE, d4]), + (100, [self.CLIENT, self.PAGE, d4])]) + self.assertEqual(closed, [False, False, False, False]) + self.assertEqual(self.stopped, []) + self.assertEqual(self.notified, []) + + def test_what_battle_net_left_beside_such_a_game_once_closed_itself_is_stopped(self): + d4 = (6, ["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe", "-sso", "-launch", "-uid", "fenris"]) + tidy = BNET["Tidy"](settle=20, gone=30) + self.run_tidy(tidy, [(0, [self.CLIENT, self.AGENT, d4]), (5, [self.AGENT, d4]), (20, [self.AGENT, d4])]) + self.assertEqual(self.stopped, [[3]]) + + def test_what_battle_net_did_not_launch_closes_nothing(self): + up = [self.CLIENT, self.AGENT] + redist = (6, ["C:\\Program Files (x86)\\Diablo IV\\vc_redist.x64.exe", "/install"]) + tidy = BNET["Tidy"](settle=0, gone=30) + self.assertEqual(self.run_tidy(tidy, [(0, up + [redist]), (100, up + [redist])]), [False, False]) + self.assertEqual(self.stopped, []) + + def test_a_game_that_exits_and_starts_again_counts_afresh(self): + tidy = BNET["Tidy"](settle=20, gone=30) + up = [self.CLIENT, self.AGENT] + self.run_tidy(tidy, [(0, up + [self.GAME]), (20, up + [self.GAME]), (30, up), (40, up + [self.GAME]), + (55, up + [self.GAME]), (60, up + [self.GAME])]) + self.assertEqual(self.stopped, [[1, 3], [1, 3]]) + + def test_battle_net_outliving_its_agent_is_closed(self): + tidy = BNET["Tidy"](settle=20, gone=30) + with_agent = [self.CLIENT, self.PAGE, self.AGENT, self.WINE] + without = [self.CLIENT, self.PAGE, self.WINE] + closed = self.run_tidy(tidy, [(0, with_agent), (10, without), (39, without), (40, without), (41, without)]) + self.assertEqual(closed, [False, False, False, True, False]) + self.assertEqual(self.stopped, [[1, 2]]) + self.assertEqual(self.notified, ["Battle.net was closed"]) + + def test_an_agent_back_within_the_grace_keeps_battle_net(self): + tidy = BNET["Tidy"](settle=20, gone=30) + with_agent = [self.CLIENT, self.AGENT] + without = [self.CLIENT] + self.run_tidy(tidy, [(0, with_agent), (10, without), (35, with_agent), (50, without), (79, without)]) + self.assertEqual(self.stopped, []) + + def test_a_battle_net_still_starting_its_agent_is_left_alone(self): + tidy = BNET["Tidy"](settle=20, gone=30) + self.run_tidy(tidy, [(0, [self.CLIENT]), (100, [self.CLIENT]), (1000, [self.CLIENT, self.WINE])]) + self.assertEqual(self.stopped, []) + + def test_a_closed_battle_net_starts_its_count_over(self): + tidy = BNET["Tidy"](settle=20, gone=30) + self.run_tidy(tidy, [(0, [self.CLIENT, self.AGENT]), (10, [self.AGENT]), (20, [self.CLIENT]), (100, [self.CLIENT])]) + self.assertEqual(self.stopped, []) + + +class FexRequestTest(Temp): + def answer(self, text, delay=0.2): + def respond(): + request = self.tmp / BNET["FEX_REQUEST"] + deadline = time.monotonic() + 5 + while not request.exists() and time.monotonic() < deadline: + time.sleep(0.02) + self.requested = request.read_text() + request.unlink() + time.sleep(delay) + (self.tmp / (BNET["FEX_RESULT"] + ".tmp")).write_text(text + "\n") + os.replace(self.tmp / (BNET["FEX_RESULT"] + ".tmp"), self.tmp / BNET["FEX_RESULT"]) + thread = threading.Thread(target=respond) + thread.start() + self.addCleanup(thread.join) + + def test_the_apps_answer_comes_back(self): + (self.tmp / BNET["FEX_RESULT"]).write_text("ok an-old-answer\n") + self.answer("ok FEXCore-2610-d2rfix28-linux.wcp") + self.assertEqual(BNET["ask_fex"](str(self.tmp), wait=5), "ok FEXCore-2610-d2rfix28-linux.wcp") + self.assertEqual(self.requested, "appid=%s\n" % BNET["APP_ID"]) + self.assertFalse((self.tmp / BNET["FEX_RESULT"]).exists()) + + def test_no_answer_or_no_session_starts_without_one(self): + with mock.patch.dict(BNET, {"say": lambda message: None}): + self.assertIsNone(BNET["ask_fex"](str(self.tmp), wait=0.3)) + self.assertIsNone(BNET["ask_fex"](None)) + self.assertIsNone(BNET["ask_fex"](str(self.tmp / "gone"))) + + +class OpenTest(Temp): + def setUp(self): + super().setUp() + self.root = str(self.tmp / "Steam") + self.calls = [] + self.alive = [] + self.menu = self.tmp / "droiddeck-battlenet.desktop" + patcher = mock.patch.dict(BNET, { + "ask_fex": lambda launch_dir, wait=0: "ok fex.wcp", + "say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])), + "wine_processes": lambda pfx, proc="/proc": list(self.alive), + "stop": lambda processes, wait=0: self.calls.append(("stop", [pid for pid, _ in processes])) or self.alive.clear(), + "write_menu": lambda path=None: self.calls.append(("menu",)), + "START_GRACE": 0, "POLL": 0, + }) + patcher.start() + self.addCleanup(patcher.stop) + + def client(self): + return self.write("Steam/steamapps/compatdata/%s/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe" + % BNET["APP_ID"], b"MZ") + + def proton(self, effects): + effects = iter(effects) + + def fake(program, args=(), verb=None, watch=None, poll=0): + status, seen, side = next(effects) + self.calls.append(("proton", os.path.basename(program), verb)) + if side: + side() + return status, seen + return fake + + def test_an_installed_client_opens_and_the_start_waits_for_it(self): + self.client() + with mock.patch.dict(BNET, {"proton": self.proton([(0, True, None)])}): + self.assertEqual(BNET["open_client"](self.root), 0) + self.assertEqual(self.calls, [("menu",), ("proton", "Battle.net Launcher.exe", None)]) + + def test_what_a_closed_battle_net_left_is_stopped_first(self): + self.client() + self.alive.append((40, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.exe"])) + with mock.patch.dict(BNET, {"proton": self.proton([(0, True, None)])}): + self.assertEqual(BNET["open_client"](self.root), 0) + self.assertEqual(self.calls[:2], [("menu",), ("stop", [40])]) + + def test_without_a_client_the_installer_runs_and_hands_over(self): + setup = self.write("cache/Battle.net-Setup.exe", b"MZ") + with mock.patch.dict(BNET, {"download": lambda: str(setup), "proton": self.proton([(0, True, self.client)])}): + self.assertEqual(BNET["open_client"](self.root), 0) + self.assertEqual([c for c in self.calls if c[0] != "notify"], [("menu",), ("proton", "Battle.net-Setup.exe", None)]) + config = Path(self.root) / ("steamapps/compatdata/%s/pfx/drive_c/users/steamuser/AppData/Roaming/Battle.net/Battle.net.config" + % BNET["APP_ID"]) + self.assertTrue(config.is_file()) + + def test_an_installer_that_did_not_start_it_is_followed_by_the_launcher(self): + setup = self.write("cache/Battle.net-Setup.exe", b"MZ") + effects = [(0, False, self.client), (0, True, None)] + with mock.patch.dict(BNET, {"download": lambda: str(setup), "proton": self.proton(effects)}): + self.assertEqual(BNET["open_client"](self.root), 0) + self.assertEqual([c[1] for c in self.calls if c[0] == "proton"], ["Battle.net-Setup.exe", "Battle.net Launcher.exe"]) + + def test_a_failed_install_says_so(self): + setup = self.write("cache/Battle.net-Setup.exe", b"MZ") + with mock.patch.dict(BNET, {"download": lambda: str(setup), "proton": self.proton([(1, False, None)])}): + self.assertEqual(BNET["open_client"](self.root), 1) + self.assertIn(("notify", "Battle.net did not install"), self.calls) + + def test_no_download_is_no_install(self): + with mock.patch.dict(BNET, {"download": lambda: None, "proton": self.proton([])}): + self.assertEqual(BNET["open_client"](self.root), 1) + self.assertIn(("notify", "Battle.net could not be downloaded"), self.calls) + self.assertEqual(self.calls[0], ("menu",)) + + def test_a_cut_off_installer_download_is_not_kept(self): + import http.client + import io + + class Response(io.BytesIO): + def __init__(self, body, length): + super().__init__(body) + self.headers = {"Content-Length": str(length)} + + folder = str(self.tmp / "dl") + body = b"MZ" + b"\0" * (BNET["MIN_INSTALLER"] + 10) + with mock.patch.object(BNET["urllib"].request, "urlopen", lambda *a, **k: Response(body, len(body) + 100)), \ + mock.patch.object(BNET["shutil"], "which", lambda name: None): + self.assertIsNone(BNET["download"]("https://example.invalid/setup.exe", folder)) + self.assertEqual(os.listdir(folder), []) + + def broken(*a, **k): + raise http.client.IncompleteRead(b"MZ") + with mock.patch.object(BNET["urllib"].request, "urlopen", broken), \ + mock.patch.object(BNET["shutil"], "which", lambda name: None): + self.assertIsNone(BNET["download"]("https://example.invalid/setup.exe", folder)) + self.assertEqual(os.listdir(folder), []) + + with mock.patch.object(BNET["urllib"].request, "urlopen", lambda *a, **k: Response(body, len(body))): + self.assertEqual(BNET["download"]("https://example.invalid/setup.exe", folder), os.path.join(folder, BNET["SETUP"])) + + def test_a_client_that_never_starts_is_reported(self): + self.client() + with mock.patch.dict(BNET, {"proton": self.proton([(3, False, None)])}): + self.assertEqual(BNET["open_client"](self.root), 3) + self.assertIn(("notify", "Battle.net did not start"), self.calls) + + def test_a_second_start_shows_the_open_window_and_returns(self): + client = self.write("Steam/steamapps/compatdata/%s/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe" + % BNET["APP_ID"], b"MZ") + self.alive.extend([(50, [str(client)]), (51, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.9824\\Agent.exe"])]) + started = [] + with mock.patch.object(BNET["subprocess"], "Popen", lambda cmd, **kw: started.append((cmd, kw)) or mock.Mock()), \ + mock.patch.dict(os.environ, {"BL_DESKTOP": "1"}), \ + mock.patch.dict(BNET, {"CACHE": str(self.tmp / "cache"), "acquire": lambda: self.fail("took the lock")}): + self.assertIsNone(BNET["show"](self.root, wait=60, poll=0)) + cmd, kw = started[0] + self.assertEqual(cmd, [BNET["PROTON_RUN"], "--window", "--prefix", BNET["APP_ID"], "--verb", "run", str(client)]) + self.assertTrue(kw["start_new_session"]) + self.assertEqual(kw["stdin"], BNET["subprocess"].DEVNULL) + self.assertEqual(kw["stdout"].name, str(self.tmp / "cache/spawned.log")) + self.assertIs(kw["stderr"], kw["stdout"]) + + def test_a_battle_net_without_its_agent_is_not_handed_the_start(self): + self.write("Steam/steamapps/compatdata/%s/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe" + % BNET["APP_ID"], b"MZ") + self.alive.append((50, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"])) + tries = iter([None, None, "the lock"]) + with mock.patch.dict(BNET, {"acquire": lambda: next(tries), "spawn": lambda *a, **k: self.fail("handed over")}): + self.assertEqual(BNET["show"](self.root, wait=60, poll=0), "the lock") + + def test_a_second_start_while_the_first_ends_opens_battle_net_itself(self): + tries = iter([None, None, "the lock"]) + with mock.patch.dict(BNET, {"acquire": lambda: next(tries)}): + self.assertEqual(BNET["show"](self.root, wait=60, poll=0), "the lock") + + def test_a_second_start_gives_up_when_the_first_neither_opens_nor_ends(self): + with mock.patch.dict(BNET, {"acquire": lambda: None}): + self.assertIsNone(BNET["show"](self.root, wait=0, poll=0)) + self.assertEqual(self.calls[-1], ("notify", "Battle.net is busy")) + + def test_a_game_in_the_prefix_is_left_running_and_battle_net_starts_beside_it(self): + self.client() + self.alive.append((41, ["C:\\Program Files (x86)\\Overwatch\\_retail_\\Overwatch.exe"])) + with mock.patch.dict(BNET, {"proton": self.proton([(0, True, None)])}): + self.assertEqual(BNET["open_client"](self.root), 0) + self.assertNotIn("stop", [c[0] for c in self.calls]) + self.assertIn(("proton", "Battle.net Launcher.exe", "run"), self.calls) + + def test_one_start_at_a_time(self): + first = BNET["acquire"](str(self.tmp / "lock")) + self.assertIsNotNone(first) + self.assertIsNone(BNET["acquire"](str(self.tmp / "lock"))) + first.close() + again = BNET["acquire"](str(self.tmp / "lock")) + self.assertIsNotNone(again) + again.close() + + def test_status_says_where_it_is(self): + self.client() + status = BNET["status"](self.root) + self.assertEqual((status["appid"], status["installed"], status["running"]), (int(BNET["APP_ID"]), True, False)) + self.assertTrue(status["launcher"].endswith("Battle.net/Battle.net Launcher.exe")) + + +class Harness(Temp): + CLIENT = ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"] + GAME = ["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe"] + AGENT = ["C:\\ProgramData\\Battle.net\\Agent\\Agent.9824\\Agent.exe"] + + class Lock: + def __init__(self): + self.closed = False + + def close(self): + self.closed = True + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + + class Proton: + def wait(self, timeout=None): + return 0 + + def setUp(self): + super().setUp() + env = mock.patch.dict(os.environ) + env.start() + self.addCleanup(env.stop) + self.root = str(self.tmp / "Steam") + self.calls = [] + self.lock = self.Lock() + self.states = [] + self.last = [] + patcher = mock.patch.dict(BNET, { + "ask_fex": lambda launch_dir, wait=0: self.calls.append(("fex",)) or "ok fex.wcp", + "say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])), + "wine_processes": self.processes, + "stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))), + "start": lambda exe, verb=None: self.calls.append(("start", os.path.basename(exe), verb)) or self.Proton(), + "spawn": lambda program, verb, args=(): self.calls.append(("spawn", os.path.basename(program), verb, list(args))), + "acquire": lambda folder=None: self.lock, + "POLL": 0, "READY_SETTLE": 0, "GAME_GRACE": 0, "CLIENT_WAIT": 0, + }) + patcher.start() + self.addCleanup(patcher.stop) + + def processes(self, pfx, proc="/proc"): + if self.states: + self.last = self.states.pop(0) + return list(self.last) + + def install(self): + for name in ("Battle.net Launcher.exe", "Battle.net.exe"): + self.write("Steam/steamapps/compatdata/%s/pfx/drive_c/Program Files (x86)/Battle.net/%s" % (BNET["APP_ID"], name), b"MZ") + + def clients(self, n=5, first=10): + return [(first + i, self.CLIENT + (["--type=renderer"] if i else [])) for i in range(n)] + +class LaunchTest(Harness): + def test_battle_net_is_opened_for_the_game_and_closed_after_it(self): + self.install() + up = self.clients() + [(30, self.AGENT)] + self.states = [[], [], up, up + [(40, self.GAME)], up, up] + self.assertEqual(BNET["launch"](self.root, "Fen"), 0) + self.assertEqual(self.calls, [ + ("fex",), ("start", "Battle.net Launcher.exe", None), + ("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]), + ("stop", [10, 11, 12, 13, 14, 30]), + ]) + self.assertTrue(self.lock.closed) + + def test_battle_net_is_closed_once_the_game_is_up(self): + self.install() + up = self.clients() + [(30, self.AGENT)] + game = (40, self.GAME + ["-launch", "-uid", "fenris"]) + wine = (50, ["C:\\windows\\system32\\services.exe"]) + self.states = [[], [], up, up + [game, wine], [game, wine], [game, wine], [wine], [wine]] + with mock.patch.dict(BNET, {"GAME_SETTLE": 0}): + self.assertEqual(BNET["launch"](self.root, "Fen"), 0) + self.assertEqual(self.calls, [ + ("fex",), ("start", "Battle.net Launcher.exe", None), + ("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]), + ("stop", [10, 11, 12, 13, 14, 30]), + ("stop", [50]), + ]) + + def test_a_battle_net_opened_for_a_game_closes_itself_as_it_launches_it(self): + self.install() + self.states = [[], [], [], []] + BNET["launch"](self.root, "Fen") + config = Path(self.root) / ("steamapps/compatdata/%s/pfx/drive_c/users/steamuser/AppData/Roaming/Battle.net/Battle.net.config" + % BNET["APP_ID"]) + self.assertEqual(json.loads(config.read_text())["Client"]["GameLaunchWindowBehavior"], "2") + + def test_battle_net_beside_a_game_signing_in_with_its_token_closes_only_after_it(self): + self.install() + up = self.clients() + [(30, self.AGENT)] + d4 = (40, self.GAME + ["-sso", "-launch", "-uid", "fenris"]) + self.states = [[], [], up, up + [d4], up + [d4], up + [d4], up, up] + with mock.patch.dict(BNET, {"GAME_SETTLE": 0}): + self.assertEqual(BNET["launch"](self.root, "Fen"), 0) + self.assertEqual([c for c in self.calls if c[0] == "stop"], [("stop", [10, 11, 12, 13, 14, 30])]) + + def test_battle_net_closing_itself_as_it_launches_the_game_is_not_an_end(self): + game = (40, self.GAME + ["-uid", "fenris"]) + self.states = [[], [game], [game], [], []] + times = iter([0, 5, 6, 10, 30]) + with mock.patch.object(BNET["time"], "monotonic", lambda: next(times)): + self.assertTrue(BNET["follow"]("/pfx", poll=0, grace=15)) + + def test_battle_net_that_only_selected_the_game_is_asked_again(self): + up = self.clients() + game = (40, self.GAME + ["-uid", "s1"]) + self.states = [up, up, up, up + [game], [game], [], []] + asks = [] + times = iter([0, 16, 32, 33, 34, 50, 70]) + with mock.patch.object(BNET["time"], "monotonic", lambda: next(times)): + self.assertTrue(BNET["follow"]("/pfx", poll=0, grace=15, ask=lambda: asks.append(1))) + self.assertEqual(len(asks), 2) + + def test_battle_net_is_asked_at_most_three_times(self): + up = self.clients() + self.states = [up] * 6 + [[], []] + asks = [] + times = iter([0, 20, 40, 60, 80, 100, 101, 130]) + with mock.patch.object(BNET["time"], "monotonic", lambda: next(times)): + self.assertFalse(BNET["follow"]("/pfx", poll=0, grace=15, ask=lambda: asks.append(1))) + self.assertEqual(len(asks), 2) + + def test_the_wallpaper_is_droiddecks_logo_on_its_dark_gradient(self): + bmp = BNET["wallpaper_bmp"](192, 108) + self.assertEqual(bmp[:2], b"BM") + self.assertEqual(int.from_bytes(bmp[2:6], "little"), len(bmp)) + self.assertEqual((int.from_bytes(bmp[18:22], "little"), int.from_bytes(bmp[22:26], "little")), (192, 108)) + + def pixel(x, y): + at = 54 + (107 - y) * 192 * 3 + x * 3 + return tuple(bmp[at + 2 - i] for i in range(3)) + self.assertEqual(pixel(95, 54), (26, 159, 255)) + self.assertTrue(all(c < 16 for c in pixel(0, 0))) + + def test_battle_nets_desktop_shows_the_wallpaper(self): + self.install() + pfx = Path(self.root) / ("steamapps/compatdata/%s/pfx" % BNET["APP_ID"]) + (pfx / "user.reg").write_text("WINE REGISTRY Version 2\n") + with mock.patch.dict(os.environ, {"BL_WIDTH": "160", "BL_HEIGHT": "90"}), \ + mock.patch.dict(BNET, {"wallpaper_bmp": lambda w, h: b"BM%dx%d" % (w, h)}): + self.assertTrue(BNET["wallpaper"](self.root)) + self.assertTrue(BNET["wallpaper"](self.root)) + image = pfx / "drive_c/users/steamuser/AppData/Local/DroidDeck/wallpaper-160x90.bmp" + self.assertEqual(image.read_bytes(), b"BM160x90") + reg = (pfx / "user.reg").read_text() + self.assertEqual(reg.count('"Wallpaper"="C:\\\\users\\\\steamuser\\\\AppData\\\\Local\\\\DroidDeck\\\\wallpaper-160x90.bmp"'), 1) + self.assertIn('[Control Panel\\\\Desktop]', reg) + self.assertIn('"Background"="4 6 11"', reg) + self.assertIn('"WallpaperStyle"="0"', reg) + + def test_a_large_desktop_gets_a_stretched_smaller_wallpaper(self): + self.install() + pfx = Path(self.root) / ("steamapps/compatdata/%s/pfx" % BNET["APP_ID"]) + (pfx / "user.reg").write_text("WINE REGISTRY Version 2\n") + with mock.patch.dict(os.environ, {"BL_WIDTH": "2560", "BL_HEIGHT": "1600"}), \ + mock.patch.dict(BNET, {"wallpaper_bmp": lambda w, h: b"BM%dx%d" % (w, h)}): + self.assertTrue(BNET["wallpaper"](self.root)) + image = pfx / "drive_c/users/steamuser/AppData/Local/DroidDeck/wallpaper-1152x720.bmp" + self.assertEqual(image.read_bytes(), b"BM1152x720") + self.assertIn('"WallpaperStyle"="2"', (pfx / "user.reg").read_text()) + + def test_an_open_battle_net_is_handed_the_game(self): + self.install() + up = self.clients() + self.states = [up, up, up + [(40, self.GAME)], up] + self.assertEqual(BNET["launch"](self.root, "OSI"), 0) + self.assertEqual(self.calls, [("spawn", "Battle.net.exe", "run", ["--exec=launch OSI"])]) + + def test_the_desktops_battle_net_holding_the_lock_is_handed_the_game(self): + self.install() + up = self.clients() + self.states = [up, up + [(40, self.GAME)], up] + with mock.patch.dict(BNET, {"acquire": lambda folder=None: None}): + self.assertEqual(BNET["launch"](self.root, "Pro"), 0) + self.assertEqual(self.calls, [("spawn", "Battle.net.exe", "run", ["--exec=launch Pro"])]) + + def test_battle_net_closed_before_the_game_started(self): + self.install() + up = self.clients() + self.states = [[], [], up, up, [(30, self.AGENT)], [(30, self.AGENT)]] + self.assertEqual(BNET["launch"](self.root, "Fen"), 1) + self.assertEqual(self.calls[-1], ("stop", [30])) + + def test_no_client_no_launch(self): + self.assertEqual(BNET["launch"](self.root, "Fen"), 1) + self.assertEqual(self.calls, [("notify", "Battle.net is not installed")]) + + def test_a_battle_net_that_never_opens_launches_nothing(self): + self.install() + self.states = [[], [], []] + self.assertEqual(BNET["launch"](self.root, "Fen"), 1) + self.assertNotIn("spawn", [c[0] for c in self.calls]) + self.assertIn(("notify", "Battle.net did not start"), self.calls) + + def test_a_game_is_a_windows_program_neither_wines_nor_battle_nets(self): + self.assertTrue(BNET["is_game"](self.GAME)) + self.assertTrue(BNET["is_game"](["c:/Program Files (x86)/Overwatch/_retail_/Overwatch.exe", "-uid", "prometheus"])) + self.assertTrue(BNET["is_game"](["C:\\Program Files (x86)\\Diablo IV\\BlizzardError\\BlizzardError.exe"])) + for argv in (self.CLIENT, self.AGENT, ["C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"], + ["C:\\windows\\system32\\services.exe"], ["C:\\windows\\system32\\lsass.exe"], ["C:\\windows\\system32\\rundll32.exe", "setupapi"], + ["c:\\windows\\system32\\steam.exe", "x"], ["/x/files/bin/wineserver"], ["/usr/bin/python3", "proton"], []): + with self.subTest(argv): + self.assertFalse(BNET["is_game"](argv)) + + def test_battle_net_shows_in_the_desktops_window_or_as_the_steam_launch(self): + with mock.patch.dict(os.environ, {"BL_DESKTOP": "1", "SteamGameId": "123"}): + self.assertEqual(BNET["proton_options"](), ["--window"]) + with mock.patch.dict(os.environ, {"SteamGameId": "11151176786366644224"}): + os.environ.pop("BL_DESKTOP", None) + self.assertEqual(BNET["proton_options"](), ["--game-id", "11151176786366644224"]) + os.environ["SteamGameId"] = "0" + self.assertEqual(BNET["proton_options"](), []) + + def test_on_the_desktop_battle_net_restarts_on_the_gpu_unless_turned_off(self): + with tempfile.TemporaryDirectory() as tmp: + gpu = os.path.join(tmp, "droiddeck-gpu") + with open(gpu, "w") as out: + out.write("#!/bin/sh\n") + os.chmod(gpu, 0o755) + with mock.patch.dict(BNET, {"BIN": tmp}), mock.patch.dict(os.environ, {"BL_DESKTOP": "1"}): + os.environ.pop("BL_DESKTOP_GPU", None) + os.environ.pop("BL_DESKTOP_GPU_CHILD", None) + self.assertEqual(BNET["desktop_gpu"](), gpu) + for choice in ("off", "0", "No", "false"): + os.environ["BL_DESKTOP_GPU"] = choice + self.assertIsNone(BNET["desktop_gpu"]()) + os.environ["BL_DESKTOP_GPU"] = "on" + os.environ["BL_DESKTOP_GPU_CHILD"] = "1" + self.assertIsNone(BNET["desktop_gpu"]()) + os.environ.pop("BL_DESKTOP_GPU_CHILD") + os.environ["BL_DESKTOP"] = "0" + self.assertIsNone(BNET["desktop_gpu"]()) + os.environ["BL_DESKTOP"] = "1" + os.chmod(gpu, 0o644) + self.assertIsNone(BNET["desktop_gpu"]()) + + def test_on_the_gpu_battle_net_fills_the_screen_instead_of_a_window(self): + with mock.patch.dict(os.environ, {"BL_DESKTOP": "1", "BL_DESKTOP_GPU_CHILD": "1", "BL_WIDTH": "1280", "BL_HEIGHT": "720", "SteamGameId": "0"}): + self.assertEqual(BNET["proton_options"](), ["--desktop", "1280x720"]) + + def test_under_gamescope_battle_net_gets_a_desktop_of_the_screens_size(self): + with mock.patch.dict(os.environ, {"BL_WIDTH": "1280", "BL_HEIGHT": "720", "SteamGameId": "0"}): + os.environ.pop("BL_DESKTOP", None) + self.assertEqual(BNET["proton_options"](), ["--desktop", "1280x720"]) + os.environ["BL_DESKTOP"] = "1" + self.assertEqual(BNET["proton_options"](), ["--window"]) + + def test_the_library_comes_before_the_action(self): + seen = [] + self.addCleanup(BNET.__setitem__, "LIBRARY", None) + with mock.patch.dict(BNET, {"launch": lambda root, code: seen.append((BNET["LIBRARY"], code)) or 0}): + self.assertEqual(BNET["main"](["--library", "/root/Games/Stores/Battle.net", "launch", "WTCG"]), 0) + self.assertEqual(BNET["main"](["--library", "Games", "launch", "WTCG"]), 2) + self.assertEqual(seen, [("/root/Games/Stores/Battle.net", "WTCG")]) + + def test_only_a_code_is_launched(self): + with mock.patch.dict(BNET, {"launch": lambda root, code: self.calls.append(("launch", code)) or 0}): + for argv in (["launch"], ["launch", "Fen;rm -rf /"], ["launch", "Fen", "x"], ["open", "x"], ["bogus"]): + with self.subTest(argv): + self.assertEqual(BNET["main"](argv), 2) + self.assertEqual(BNET["main"](["launch", "Fen"]), 0) + self.assertEqual(self.calls, [("launch", "Fen")]) + self.assertEqual(os.environ.get("BL_BATTLENET"), "1") + + +class InstallGameTest(Harness): + def setUp(self): + super().setUp() + BNET_PATCH = mock.patch.dict(BNET, { + "open_client": lambda root, reinstall=False: self.calls.append(("open",)) or 0, + "hand_over": lambda root, args, wait=None: self.calls.append(("hand_over", list(args))), + "show": lambda root, wait=None, poll=None, args=(): self.calls.append(("show", list(args))), + }) + BNET_PATCH.start() + self.addCleanup(BNET_PATCH.stop) + thread = mock.patch.object(BNET["threading"], "Thread", lambda target, args, daemon: mock.Mock(start=lambda: target(*args))) + thread.start() + self.addCleanup(thread.stop) + + def test_the_open_battle_net_is_asked(self): + self.install() + self.states = [self.clients() + [(30, self.AGENT)]] + self.assertEqual(BNET["install_game"](self.root, "fenris"), 0) + self.assertEqual(self.calls, [("spawn", "Battle.net.exe", "run", ["--install", "--game=fenris"])]) + self.assertFalse(self.lock.closed) + + def test_an_open_battle_net_without_its_agent_is_asked_once_it_has_one(self): + self.install() + self.states = [self.clients()] + with mock.patch.dict(BNET, {"acquire": lambda folder=None: None}): + self.assertEqual(BNET["install_game"](self.root, "fenris"), 0) + self.assertEqual(self.calls, [("show", ["--install", "--game=fenris"])]) + + def test_battle_net_is_opened_and_asked_once_it_is_up(self): + self.install() + self.assertEqual(BNET["install_game"](self.root, "osi"), 0) + self.assertEqual(self.calls, [("hand_over", ["--install", "--game=osi"]), ("open",)]) + + def test_without_battle_net_it_is_installed_first_then_asked(self): + self.assertEqual(BNET["install_game"](self.root, "hs_beta"), 0) + self.assertEqual(self.calls, [("hand_over", ["--install", "--game=hs_beta"]), ("open",)]) + + def test_another_start_holding_the_lock_hands_it_on(self): + with mock.patch.dict(BNET, {"acquire": lambda folder=None: None}): + self.assertEqual(BNET["install_game"](self.root, "prometheus"), 0) + self.assertEqual(self.calls, [("show", ["--install", "--game=prometheus"])]) + + def test_only_an_id_is_asked_for(self): + with mock.patch.dict(BNET, {"install_game": lambda root, uid: self.calls.append(("get", uid)) or 0}): + for argv in (["install-game"], ["install-game", "Fenris"], ["install-game", "osi;rm"], ["install-game", "osi", "x"]): + with self.subTest(argv): + self.assertEqual(BNET["main"](argv), 2) + self.assertEqual(BNET["main"](["install-game", "hs_beta"]), 0) + self.assertEqual(self.calls, [("get", "hs_beta")]) + + +class HandOverTest(Harness): + def test_once_battle_net_is_up_it_is_asked(self): + self.install() + self.states = [[], self.clients()] + self.assertTrue(BNET["hand_over"](self.root, ["--install", "--game=osi"], wait=60)) + self.assertEqual(self.calls, [("spawn", "Battle.net.exe", "run", ["--install", "--game=osi"])]) + + def test_a_battle_net_that_never_comes_up_is_not_asked(self): + self.install() + self.states = [[]] + self.assertFalse(BNET["hand_over"](self.root, ["--install", "--game=osi"], wait=0)) + self.assertEqual(self.calls, []) + + +class AgentTest(Temp): + def test_the_newest_agent_build_and_its_port_are_found(self): + root = str(self.tmp / "Steam") + agent = "Steam/steamapps/compatdata/%s/pfx/drive_c/ProgramData/Battle.net/Agent" % BNET["APP_ID"] + self.write(agent + "/Agent.9100/Agent.exe", b"MZ") + self.write(agent + "/Agent.9824/Agent.exe", b"MZ") + os.makedirs(self.tmp / agent / "Agent.9999") + self.write(agent + "/Agent.dat", "39211\n") + self.assertTrue(BNET["agent_exe"](root).endswith("Agent.9824/Agent.exe")) + self.assertEqual(BNET["agent_port"](root), 39211) + self.write(agent + "/Agent.dat", "not a port") + self.assertIsNone(BNET["agent_port"](root)) + + def test_progress_keeps_the_fields_the_app_reads(self): + status = {"progress": 0.35, "download_current": [2397, 0, 0], "download_total": [6746, 0, 0], "download_rate": 34076920, + "state": 1003, "build_config_kv_pairs": {"x": "y"}, "regional_version_info": {}, "estimated_time_in_sec": 120, + "extended_status": {"current": 1, "state": 500, "total": 2, "unit_type": "bytes"}} + self.assertEqual(BNET["summary"](status), {"progress": 0.35, "download_current": 2397, "download_total": 6746, + "download_rate": 34076920, "state": 1003, "estimated_time_in_sec": 120, "phase": 500}) + + def test_an_unknown_time_left_is_not_reported(self): + for eta in (18446744073709551615, -1, 1.5): + with self.subTest(eta): + self.assertNotIn("estimated_time_in_sec", BNET["summary"]({"estimated_time_in_sec": eta})) + + def test_the_driver_script_reads_its_arguments_in_the_order_they_are_passed(self): + script = BNET["AGENT_SCRIPT"] + self.assertIn("port = a(0), action = a(1), uid = a(2), product = a(3), dir = a(4)", script) + self.assertIn("lang = a(5), country = a(6), region = a(7), out = a(8)", script) + self.assertIn('"--internalclienttools"', (BIN / "droiddeck-battlenet").read_text()) + + +class AgentJobTest(Harness): + def setUp(self): + super().setUp() + self.lines = [] + self.files = {} + self.started = [] + self.envs = [] + test = self + + class Child: + def __init__(self, cmd, **kwargs): + test.started.append(cmd) + test.envs.append(kwargs.get("env") or {}) + base = cmd[-1][2:].replace("\\", "/") + for suffix, value in test.files.items(): + with open(base + suffix, "wb") as f: + f.write(value.encode("utf-16")) + self.returncode = 0 + + def poll(self): + return 0 + + patcher = mock.patch.dict(BNET, {"emit": lambda kind, value="": self.lines.append((kind, value)), + "stop_leftovers": lambda pfx: True, "CACHE": str(self.tmp / "cache")}) + patcher.start() + self.addCleanup(patcher.stop) + popen = mock.patch.object(BNET["subprocess"], "Popen", Child) + popen.start() + self.addCleanup(popen.stop) + + def install(self): + super().install() + self.write("Steam/steamapps/compatdata/%s/pfx/drive_c/ProgramData/Battle.net/Agent/Agent.9824/Agent.exe" % BNET["APP_ID"], b"MZ") + + def test_a_game_downloads_headless_and_reports_where_it_landed(self): + self.install() + folder = str(self.tmp / "Games/Battle.net/Warcraft Rumble") + self.files = { + ".json": json.dumps({"progress": 1.0, "download_complete": True, "state": 1004, "download_current": [6746, 0, 0], + "download_total": [6746, 0, 0]}), + ".game": json.dumps({"installed": True, "install_dir": "Z:" + folder, "local_version": "16.1.2.119725", + "binaries": {"game": {"relative_path": "WarcraftRumble.exe"}}}), + } + code = BNET["agent_job"](self.root, "install", "gryphon", "gryphon", folder, "enUS", "USA", "US", poll=0) + self.assertEqual(code, 0) + self.assertTrue(os.path.isdir(folder)) + cmd = self.started[0] + self.assertEqual(cmd[:6], ["gamescope", "--backend", "headless", "-w", "640", "-h"]) + self.assertEqual(cmd[cmd.index("--") + 2:-1], ["agent-serve", "install", "gryphon", "gryphon", "Z:" + folder, "enUS", "USA", "US"]) + self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"]) + self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"}) + + def test_an_agent_error_is_reported_with_its_code(self): + self.install() + self.files = {".json": json.dumps({"error": 2421, "progress": 0.0})} + self.assertEqual(BNET["agent_job"](self.root, "install", "fenris", "fenris", str(self.tmp / "D4"), "enUS", "USA", "US", poll=0), 5) + self.assertEqual(self.lines[-1], ("ERROR", "agent 2421")) + + def test_a_driver_failure_is_reported_with_its_reason(self): + self.install() + self.files = {".error": "the agent stopped answering"} + self.assertEqual(BNET["agent_job"](self.root, "update", "wow", poll=0), 1) + self.assertEqual(self.lines[-1], ("ERROR", "stopped the agent stopped answering")) + + def test_an_update_reports_the_new_version(self): + self.install() + self.files = {".json": json.dumps({"progress": 1.0}), + ".game": json.dumps({"installed": True, "playable": True, "install_dir": "Z:/g", "local_version": "2"})} + self.assertEqual(BNET["agent_job"](self.root, "update", "gryphon", poll=0), 0) + self.assertIn("agent-serve", self.started[0]) + self.assertEqual(json.loads(self.lines[-1][1])["version"], "2") + + def test_a_game_left_unplayable_is_not_reported_as_done(self): + self.install() + self.files = {".json": json.dumps({"state": 1008, "download_complete": True, "progress": 0.0}), + ".game": json.dumps({"installed": True, "playable": False, "install_dir": "Z:/g", "local_version": "2"})} + self.assertEqual(BNET["agent_job"](self.root, "update", "gryphon", poll=0), 1) + self.assertEqual(self.lines[-1][0], "ERROR") + + def test_the_driver_only_stops_once_the_agent_has_really_run(self): + script = BNET["AGENT_SCRIPT"] + self.assertIn("if (started && (state == 1004 || complete && /\"playable\"\\s*:\\s*true/.test(s))) break;", script) + self.assertNotIn('"progress"', script) + + def test_an_uninstall_is_done_once_the_agent_no_longer_lists_it(self): + self.install() + self.files = {".json": json.dumps({}), ".game": json.dumps({"installed": False})} + self.assertEqual(BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0), 0) + self.assertEqual(self.lines[-1], ("DONE", json.dumps({"uninstalled": "gryphon"}))) + + def test_a_gamescope_that_cannot_start_is_reported(self): + self.install() + + def missing(cmd, **kwargs): + raise FileNotFoundError("gamescope") + + with mock.patch.object(BNET["subprocess"], "Popen", missing): + self.assertEqual(BNET["agent_job"](self.root, "update", "gryphon", poll=0), 1) + self.assertEqual(self.lines[-1], ("ERROR", "stopped gamescope: gamescope")) + + def test_an_agent_answer_that_is_not_an_object_is_ignored(self): + path = self.tmp / "answer.json" + for value in ([1, 2], "text", 3, None): + with self.subTest(value): + path.write_bytes(json.dumps(value).encode("utf-16")) + self.assertIsNone(BNET["read_status"](str(path))) + path.write_bytes(json.dumps({"state": 1004}).encode("utf-8")) + self.assertEqual(BNET["read_status"](str(path)), {"state": 1004}) + + def test_a_large_agent_log_is_rotated_before_a_job(self): + self.install() + os.makedirs(self.tmp / "cache") + log = self.tmp / "cache" / "agent.log" + log.write_bytes(b"x" * (BNET["AGENT_LOG_LIMIT"] + 1)) + self.files = {".game": json.dumps({"installed": False})} + BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) + self.assertEqual((self.tmp / "cache" / "agent.log.1").stat().st_size, BNET["AGENT_LOG_LIMIT"] + 1) + self.assertEqual(log.stat().st_size, 0) + + def test_it_queues_behind_another_battle_net_job(self): + self.install() + self.files = {".game": json.dumps({"installed": False})} + locks = iter([None, contextlib.nullcontext()]) + with mock.patch.dict(BNET, {"acquire": lambda *a: next(locks)}): + self.assertEqual(BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0), 0) + self.assertEqual(self.lines[:2], [("STATE", "queued"), ("STATE", "starting")]) + + def test_an_uninstall_needs_the_agent_to_say_the_game_is_gone(self): + self.install() + self.files = {".game": json.dumps({"error": 2})} + self.assertEqual(BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0), 1) + self.assertEqual(self.lines[-1][0], "ERROR") + self.files = {".game": json.dumps({})} + self.assertEqual(BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0), 0) + self.assertEqual(self.lines[-1], ("DONE", json.dumps({"uninstalled": "gryphon"}))) + + def test_without_battle_net_nothing_starts(self): + self.assertEqual(BNET["agent_job"](self.root, "install", "gryphon", "gryphon", str(self.tmp / "g"), "enUS", "USA", "US", poll=0), 3) + self.assertEqual(self.lines, [("ERROR", "client")]) + self.assertEqual(self.started, []) + + def test_it_waits_while_battle_net_or_a_game_is_open(self): + self.install() + self.states = [self.clients() + [(40, self.GAME)], [(40, self.GAME)], []] + self.files = {".game": json.dumps({"installed": False})} + self.assertEqual(BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0), 0) + self.assertEqual(self.lines[0], ("STATE", "waiting")) + self.assertEqual(self.lines[1], ("STATE", "starting")) + + def test_gamescope_gets_no_display_but_the_agent_keeps_the_one_gamescope_gives_it(self): + self.install() + os.environ.update(DISPLAY=":5", WAYLAND_DISPLAY="wayland-1") + self.files = {".game": json.dumps({"installed": False})} + BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) + self.assertNotIn("DISPLAY", self.envs[0]) + self.assertNotIn("WAYLAND_DISPLAY", self.envs[0]) + self.assertEqual(self.envs[0]["PROTON_USE_XALIA"], "0") + os.environ["DISPLAY"] = ":0" + self.assertEqual(BNET["agent_env"]()["DISPLAY"], ":0") + + def test_only_valid_arguments_start_a_job(self): + calls = [] + with mock.patch.dict(BNET, {"agent_job": lambda *a, **k: calls.append(a[1:]) or 0}): + for argv in (["agent-install", "gryphon", "gryphon", "relative/dir", "enUS", "USA", "US"], + ["agent-install", "gryphon", "Gry phon", "/g", "enUS", "USA", "US"], + ["agent-install", "gryphon", "gryphon", "/g", "english", "USA", "US"], + ["agent-update"], ["agent-uninstall", "Gryphon"]): + with self.subTest(argv): + self.assertEqual(BNET["main"](argv), 2) + self.assertEqual(BNET["main"](["agent-install", "gryphon", "gryphon", "/g/../g/Rumble", "enUS", "USA", "US"]), 0) + self.assertEqual(BNET["main"](["agent-update", "wow_classic"]), 0) + self.assertEqual(calls, [("install", "gryphon", "gryphon", "/g/Rumble", "enUS", "USA", "US"), ("update", "wow_classic")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_client_zram_focus.py b/tools/tests/test_client_zram_focus.py new file mode 100644 index 0000000000..b35902e7ff --- /dev/null +++ b/tools/tests/test_client_zram_focus.py @@ -0,0 +1,169 @@ +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session' + + +def function_source(name): + source = SCRIPT.read_text() + start = source.index('%s() {' % name) + end = source.index('\n }', start) + return source[start:end + len('\n }')] + + +def run_bash(script, env=None): + return subprocess.run(['bash', '-c', script], capture_output=True, text=True, timeout=10, env=env) + + +class ClientZramFocusTest(unittest.TestCase): + def test_refocus_restarts_the_delay_and_game_exit_restores_a_packed_client(self): + source = SCRIPT.read_text() + start = source.index(' if [ "$_bl_game" = 1 ] && bl_game_focused; then') + stop = source.index(' nap 5', start) + body = source[start:stop] + harness = ''' +_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_apps=" 413150" +_bl_pids=(123) +bl_game_focused() { [ "$focused" = 1 ]; } +bl_over_cap() { return 1; } +bl_zram_send() { echo "send:$1"; } +tick() { + SECONDS=$1 _bl_game=$2 focused=$3 +''' + body + ''' +} +tick 0 1 1 +tick 5 1 0 +tick 30 1 1 +echo "refocus:$_bl_packed" +tick 49 1 1 +tick 50 1 1 +tick 55 1 0 +tick 60 0 0 +''' + result = run_bash(harness) + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['refocus:-1', 'send:1', 'send:0'], result.stdout.splitlines()) + + def monitor_harness(self): + source = SCRIPT.read_text() + start = source.index(' bl_zram_scan\n if bl_cap_due; then') + stop = source.index(' nap 5', start) + return ''' +_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30 +_bl_apps=" 413150" +_bl_pids=(123) +step() { :; } +bl_zram_scan() { :; } +bl_game_focused() { [ "$focused" = 1 ]; } +bl_cap_due() { [ "$cap_due" = 1 ]; } +bl_over_cap() { [ "$over_cap" = 1 ]; } +bl_zram_send() { echo "send:$1:$3"; } +tick() { + SECONDS=$1 _bl_game=$2 focused=$3 over_cap=$4 cap_due=$5 +''' + source[start:stop] + '\n}\n' + + def test_client_toggle_still_disables_automatic_compression(self): + result = run_bash(self.monitor_harness() + ''' +BL_ZRAM_CLIENT=0 +tick 0 1 1 0 0 +tick 25 1 1 0 0 +tick 30 0 0 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual('', result.stdout) + + def test_a_new_game_restarts_the_compression_delay(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +_bl_apps=" 413150 1245620" +tick 15 1 1 0 0 +tick 20 1 1 0 0 +echo "starting:$_bl_packed" +tick 34 1 1 0 0 +tick 35 1 1 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['starting:-1', 'send:1:client'], result.stdout.splitlines()) + + def test_ram_cap_can_still_compress_an_unfocused_client(self): + result = run_bash(self.monitor_harness() + ''' +BL_ZRAM_CLIENT=0 BL_RAM_CAP_MB=1024 +bl_zram_usage() { _bl_rss=$((768 * 1024)); } +tick 0 1 0 1 1 +echo "cap:$_bl_packed:$_bl_since:$_bl_backoff" +tick 5 0 0 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'send:1:session', 'cap:0:-1:60', 'send:0:client'], result.stdout.splitlines()) + + def test_game_exit_defers_restore_until_the_session_is_under_the_ram_cap(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +tick 20 1 1 0 0 +tick 25 1 0 0 0 +tick 30 0 0 1 0 +echo "deferred:$_bl_unpack:$_bl_packed" +tick 35 0 0 0 1 +echo "restored:$_bl_unpack" +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'deferred:1:-1', 'send:0:client', 'restored:0'], result.stdout.splitlines()) + + def test_scan_keeps_the_running_game_and_ignores_steams_own_reaper(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + root = Path(temp.name) + self.write_cmd(root, 10, ['/usr/lib/steam/reaper', 'SteamLaunch', 'AppId=769', '--']) + self.write_cmd(root, 20, ['/usr/bin/FEX', '/usr/lib/steam/reaper', 'SteamLaunch', 'AppId=1245620', '--']) + self.write_cmd(root, 30, ['/home/deck/.local/share/Steam/steamrtarm64/steam']) + self.write_cmd(root, 40, ['/usr/bin/wine', 'game.exe']) + self.write_cmd(root, 50, ['/usr/bin/FEXInterpreter', '/usr/bin/steamwebhelper']) + scan = function_source('bl_zram_scan').replace('for _d in /proc/[0-9]*', 'for _d in "$FAKE"/[0-9]*') + result = run_bash('FAKE=%s\n%s\nbl_zram_scan\necho "game=$_bl_game"\necho "apps=${_bl_apps# }"\necho "pids=${_bl_pids[*]}"\necho "others=${_bl_others[*]}"' % (root, scan)) + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual(['game=1', 'apps=1245620', 'pids=30 50', 'others=40'], result.stdout.splitlines()) + + def test_focus_must_be_the_running_game(self): + focus = function_source('bl_game_focused') + script = ''' +%s +check() { + BL_DESKTOP=$1 BL_LAUNCH_DIR=$2 _bl_apps=$3 + if bl_game_focused; then echo yes; else echo no; fi +} +check "" "$dir" " 413150" +check "" "$dir" " 1245620" +printf '%%s\\n' '{"focusedApp": 999}' > "$dir/agent/focus.json" +check "" "$dir" " 413150" +printf '%%s\\n' '{"focusedApp": 769}' > "$dir/agent/focus.json" +check "" "$dir" " 413150" +rm -f "$dir/agent/focus.json" +check 1 "$dir" " 413150" +check "" "" " 413150" +''' % focus + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + launch = Path(temp.name) + (launch / 'agent').mkdir() + (launch / 'agent' / 'focus.json').write_text('{"t": 1, "focusedApp": 413150}\n') + result = run_bash('dir=%s\n%s' % (launch, script)) + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual(['yes', 'no', 'no', 'no', 'yes', 'yes'], result.stdout.splitlines()) + + @staticmethod + def write_cmd(root, pid, args): + proc = root / str(pid) + proc.mkdir() + (proc / 'cmdline').write_bytes(b'\0'.join(arg.encode() for arg in args) + b'\0') + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_ddfg_flow_levels.py b/tools/tests/test_ddfg_flow_levels.py new file mode 100644 index 0000000000..d5efd6355d --- /dev/null +++ b/tools/tests/test_ddfg_flow_levels.py @@ -0,0 +1,102 @@ +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +CHAIN = ROOT / "app/src/main/cpp/framegen/ddfg" + + +class DdfgFlowLevelsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which(os.environ.get("CXX", "c++")) + if compiler is None: + raise unittest.SkipTest("A host C++ compiler is required") + candidates = [Path("/usr/include/vulkan"), Path("/opt/homebrew/include/vulkan")] + for key in ("ANDROID_NDK_HOME", "ANDROID_NDK_ROOT", "NDK_HOME"): + if os.environ.get(key): + candidates.extend(Path(os.environ[key]).glob("toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan")) + for sdk in {Path(os.environ.get("ANDROID_HOME", "/nonexistent")), + Path(os.environ.get("ANDROID_SDK_ROOT", "/nonexistent")), + Path.home() / "Library/Android/sdk", Path.home() / "Android/Sdk"}: + candidates.extend(sdk.glob("ndk/*/toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan")) + headers = next((p for p in candidates if (p / "vulkan.h").is_file()), None) + if headers is None: + raise unittest.SkipTest("Vulkan headers from the Android NDK or system SDK are required") + cls.temp = tempfile.TemporaryDirectory(prefix="droiddeck-ddfg-levels-") + cls.addClassCleanup(cls.temp.cleanup) + work = Path(cls.temp.name) + shutil.copytree(headers, work / "include/vulkan", ignore=shutil.ignore_patterns("*.hpp")) + if (headers.parent / "vk_video").is_dir(): + shutil.copytree(headers.parent / "vk_video", work / "include/vk_video") + cls.binary = work / "ddfg-flow-levels" + build = subprocess.run([ + compiler, "-std=c++17", "-O2", "-Wall", "-Wextra", + "-Wno-missing-field-initializers", "-Wno-misleading-indentation", + "-I" + str(work / "include"), "-I" + str(CHAIN), + str(ROOT / "tools/tests/ddfg_flow_levels_harness.cpp"), str(CHAIN / "framegen.cpp"), + "-o", str(cls.binary), + ], capture_output=True, text=True, timeout=120) + if build.returncode: + raise RuntimeError(build.stdout + build.stderr) + + def run_case(self, mode="resources", model=4, preset=2, width=1280, height=720, generations=1, repeats=1): + result = subprocess.run([ + str(self.binary), mode, str(model), str(preset), str(width), str(height), + str(generations), str(repeats), + ], capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertTrue(result.stdout.startswith("PASS "), result.stdout) + return dict(re.findall(r"(\w+)=(\w+)", result.stdout)) + + def test_each_model_and_preset_allocates_only_solved_flow_levels(self): + for model in (3, 4): + for preset, finest in enumerate((1, 2, 3)): + with self.subTest(model=model, preset=preset): + values = self.run_case(model=model, preset=preset) + self.assertEqual(int(values["images"]), 32 - 2 * finest) + self.assertEqual(int(values["buffers"]), 18 - finest) + self.assertEqual(int(values["sets"]), 54 - 4 * finest) + + def test_default_preset_saves_the_exact_high_resolution_flow_payload(self): + for width, height in ((1280, 720), (1920, 1080), (2560, 1440)): + with self.subTest(width=width, height=height): + values = self.run_case(width=width, height=height) + pixels = lambda level: max(width >> level, 1) * max(height >> level, 1) + luma_bytes = 4 * (2 * sum(pixels(l) for l in range(7)) + + sum(pixels(l) for l in range(3, 7))) + flow_bytes = 8 * (sum(pixels(l) for l in range(3, 7)) + + 2 * width * height + 2 * pixels(3)) + self.assertEqual(int(values["bytes"]), luma_bytes + flow_bytes) + + def test_small_and_odd_extents_keep_valid_bindings_and_dispatch_sizes(self): + for width, height in ((1, 1), (17, 9), (135, 73)): + for preset in range(3): + with self.subTest(width=width, height=height, preset=preset): + self.run_case(width=width, height=height, preset=preset) + + def test_two_three_and_four_times_generation_keep_the_same_dispatch_schedule(self): + for model in (3, 4): + for preset in range(3): + for generations in (1, 2, 3): + with self.subTest(model=model, preset=preset, generations=generations): + self.run_case("record", model=model, preset=preset, generations=generations, repeats=3) + + def test_resize_rebuilds_every_solved_level(self): + for preset in range(3): + with self.subTest(preset=preset): + self.run_case("resize", preset=preset, generations=3, repeats=3) + + def test_live_preset_changes_rebuild_the_level_range(self): + for model in (3, 4): + with self.subTest(model=model): + self.run_case("preset", model=model, generations=3, repeats=4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_desktop_gpu_window.py b/tools/tests/test_desktop_gpu_window.py new file mode 100644 index 0000000000..ba3bfc5492 --- /dev/null +++ b/tools/tests/test_desktop_gpu_window.py @@ -0,0 +1,74 @@ +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +TOOLS = Path(__file__).resolve().parents[1] +GPU = TOOLS / "linuxfs/desktop/droiddeck-gpu" +WINDOW = TOOLS / "linuxfs/overlay/usr/local/bin/droiddeck-gpu-window" +KEYS = ("MESA_VK_WSI_DEBUG", "SDL_VIDEODRIVER", "WAYLAND_DISPLAY", "BL_GPU_CHILD_WSI", "BL_DESKTOP_GPU_CHILD") + + +class DesktopGpuWindowTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.out = self.tmp / "gamescope.json" + fake = self.tmp / "gamescope" + fake.write_text("#!%s\nimport json, os, sys\njson.dump({'args': sys.argv[1:], 'env': {k: os.environ.get(k) for k in %r}}, open(%r, 'w'))\n" + % (sys.executable, KEYS, str(self.out))) + fake.chmod(0o755) + + def run_gpu(self, **env): + base = {k: v for k, v in os.environ.items() if k not in KEYS + ("BL_DEBUG_DIR", "BL_DESKTOP_GPU_WINDOW")} + base.update(PATH="%s:%s" % (self.tmp, os.environ["PATH"]), BL_WIDTH="1280", BL_HEIGHT="720", **env) + subprocess.run(["bash", str(GPU), "game.exe"], env=base, check=True, capture_output=True) + return json.loads(self.out.read_text()) + + def test_on_the_desktop_the_game_gets_a_window_of_its_own(self): + run = self.run_gpu(WAYLAND_DISPLAY="wayland-1", MESA_VK_WSI_DEBUG="sw,linear") + self.assertEqual(run["args"][:2], ["--backend", "sdl"]) + self.assertNotIn("-f", run["args"]) + self.assertEqual(run["args"][-2:], ["/usr/local/bin/droiddeck-gpu-window", "game.exe"]) + self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-1") + self.assertEqual(run["env"]["SDL_VIDEODRIVER"], "wayland") + self.assertEqual(run["env"]["MESA_VK_WSI_DEBUG"], "sw") + self.assertEqual(run["env"]["BL_GPU_CHILD_WSI"], "linear") + self.assertEqual(run["env"]["BL_DESKTOP_GPU_CHILD"], "1") + + def test_full_screen_stays_available(self): + for env in ({"WAYLAND_DISPLAY": "wayland-1", "BL_DESKTOP_GPU_WINDOW": "0"}, {"WAYLAND_DISPLAY": "wayland-0"}, {}): + run = self.run_gpu(**env) + self.assertEqual(run["args"][:2], ["--backend", "wayland"]) + self.assertIn("-f", run["args"]) + self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-0") + self.assertIsNone(run["env"]["MESA_VK_WSI_DEBUG"]) + self.assertIsNone(run["env"]["BL_GPU_CHILD_WSI"]) + + def test_the_game_inside_the_window_gets_its_own_settings_back(self): + script = "import json, os; print(json.dumps({k: os.environ.get(k) for k in %r}))" % (KEYS,) + for saved, expected in (("linear", "linear"), ("", None)): + env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DISPLAY",)} + env.update(BL_GPU_CHILD_WSI=saved, MESA_VK_WSI_DEBUG="sw", SDL_VIDEODRIVER="wayland") + out = subprocess.run([sys.executable, str(WINDOW), sys.executable, "-c", script], env=env, + check=True, capture_output=True, text=True).stdout + child = json.loads(out) + self.assertEqual(child["MESA_VK_WSI_DEBUG"], expected) + self.assertEqual(child["SDL_VIDEODRIVER"], "x11") + self.assertIsNone(child["BL_GPU_CHILD_WSI"]) + + def test_outside_a_window_the_game_keeps_its_settings(self): + script = "import os; print(os.environ.get('MESA_VK_WSI_DEBUG'), os.environ.get('SDL_VIDEODRIVER'))" + env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DISPLAY",)} + env.update(MESA_VK_WSI_DEBUG="linear", SDL_VIDEODRIVER="x11") + out = subprocess.run([sys.executable, str(WINDOW), sys.executable, "-c", script], env=env, + check=True, capture_output=True, text=True).stdout.split() + self.assertEqual(out, ["linear", "x11"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_desktop_open.py b/tools/tests/test_desktop_open.py index de98e75c6e..ef299963b7 100644 --- a/tools/tests/test_desktop_open.py +++ b/tools/tests/test_desktop_open.py @@ -456,6 +456,15 @@ class ProtonRunTest(Temp): ("0", "0", str(appid << 32 | 0x02000000), "1")) self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(self.root / ("steamapps/compatdata/%d" % appid))) + def test_a_window_draws_with_the_desktops_software_gl(self): + target = RUN["Target"]("2596113170", "/c", "/i", str(self.root), "fixed") + session = {"MESA_LOADER_DRIVER_OVERRIDE": "zink", "GALLIUM_DRIVER": "zink", "LIBGL_KOPPER_DRI2": "true"} + env = RUN["environment"](session, target, "/tool", str(self.root), window=True) + self.assertEqual((env["LIBGL_ALWAYS_SOFTWARE"], env["GALLIUM_DRIVER"]), ("1", "llvmpipe")) + self.assertNotIn("MESA_LOADER_DRIVER_OVERRIDE", env) + self.assertNotIn("LIBGL_KOPPER_DRI2", env) + self.assertEqual(RUN["environment"](session, target, "/tool", str(self.root))["GALLIUM_DRIVER"], "zink") + def test_a_steam_game_keeps_its_own_id(self): target = RUN["Target"]("413150", "/c", "/i", str(self.root), "steam") env = RUN["environment"]({"PROTON_USE_WINED3D": "0"}, target, "/tool", str(self.root), window=True) @@ -465,6 +474,13 @@ class ProtonRunTest(Temp): self.assertEqual(RUN["arguments"]("/root/x/setup.msi", ["/qn"]), ["msiexec", "/i", "Z:\\root\\x\\setup.msi", "/qn"]) self.assertEqual(RUN["arguments"]("/root/x/a.exe", ["-w"]), ["/root/x/a.exe", "-w"]) + def test_a_virtual_desktop_runs_the_program_by_its_windows_path(self): + pfx = "/root/Steam/steamapps/compatdata/2596113170" + self.assertEqual(RUN["arguments"](pfx + "/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe", [], "1280x720", pfx), + ["explorer.exe", "/desktop=droiddeck,1280x720", "C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"]) + self.assertEqual(RUN["arguments"]("/root/.cache/setup.exe", ["--lang=enUS"], "1920x1080", pfx), + ["explorer.exe", "/desktop=droiddeck,1920x1080", "Z:\\root\\.cache\\setup.exe", "--lang=enUS"]) + def test_a_games_own_program_is_left_to_steam(self): self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW})) self.assertEqual(RUN["compat"]()["launch_programs"](STARDEW["config"]), @@ -554,6 +570,50 @@ class ProtonRunTest(Temp): self.game("70", "Linux Game", "run.sh") self.assertEqual(self.run_main(["--app", "70"])[0], 2) + def test_without_steam_a_shortcut_reuses_a_signed_prefix_folder(self): + bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off") + start = self.tmp / "Games/Epic/Game/Binaries" + start.mkdir() + signed = self.root / "steamapps/compatdata/-1561598272" + signed.mkdir(parents=True) + code, calls, dirs = self.run_main(["--app", "2733369024", "--dir", str(start), "--", str(bat)]) + self.assertIsNone(code) + env = calls[0][2] + self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(signed)) + self.assertFalse((self.root / "steamapps/compatdata/2733369024").exists()) + + def test_prefix_folder_prefers_initialized_unsigned_over_empty_signed(self): + signed = self.root / "steamapps/compatdata/-1561598272" + signed.mkdir(parents=True) + initialized = self.root / "steamapps/compatdata/2733369024/pfx" + initialized.mkdir(parents=True) + + self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent)) + + def test_prefix_folder_prefers_initialized_signed_over_empty_unsigned(self): + unsigned = self.root / "steamapps/compatdata/2733369024" + unsigned.mkdir(parents=True) + initialized = self.root / "steamapps/compatdata/-1561598272/pfx" + initialized.mkdir(parents=True) + + self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent)) + + def test_prefix_folder_prefers_unsigned_when_initialization_ties(self): + unsigned = self.root / "steamapps/compatdata/2733369024/pfx" + unsigned.mkdir(parents=True) + signed = self.root / "steamapps/compatdata/-1561598272/pfx" + signed.mkdir(parents=True) + + self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(unsigned.parent)) + + def test_prefix_folder_skips_numeric_names_too_long_to_convert(self): + from unittest.mock import patch + folder = self.root / "steamapps/compatdata" + folder.mkdir(parents=True) + with patch.object(RUN["os"], "listdir", return_value=["9" * 5000]): + self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), + str(folder / "2733369024")) + def test_without_steam_a_shortcut_keeps_its_prefix_folder_and_launch_options(self): bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off") start = self.tmp / "Games/Epic/Game/Binaries" @@ -568,6 +628,43 @@ class ProtonRunTest(Temp): self.assertTrue((self.root / "steamapps/compatdata/2733369024").is_dir()) self.assertEqual(dirs, [str(start)]) + def write_account(self): + self.write("Steam/config/loginusers.vdf", + '"users"\n{\n\t"76561198352563669"\n\t{\n\t\t"MostRecent"\t\t"1"\n\t}\n}\n') + return "Steam/userdata/392297941/config/" + + def test_without_steam_and_options_a_game_takes_its_steam_launch_options(self): + config = self.write_account() + self.write(config + "localconfig.vdf", '"UserLocalConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n' + '\t\t\t"Steam"\n\t\t\t{\n\t\t\t\t"apps"\n\t\t\t\t{\n\t\t\t\t\t"413150"\n\t\t\t\t\t{\n' + '\t\t\t\t\t\t"cloud"\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t"LaunchOptions"\t\t"-wrong"\n\t\t\t\t\t\t}\n' + '\t\t\t\t\t\t"LaunchOptions"\t\t"DXVK_HUD=1 %command% -d3d9 \\"-name=Two Words\\""\n' + '\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n') + shortcuts = runpy.run_path(str(BIN / "droiddeck-steam-shortcuts")) + self.write(config + "shortcuts.vdf", shortcuts["write"]({"shortcuts": { + "0": {"appid": -1561598272, "AppName": "Batman", "LaunchOptions": "-d3d9"}, + "1": {"appid": -1, "AppName": "Other", "LaunchOptions": "-x"}, + }})) + root = str(self.root) + self.assertEqual(RUN["steam_options"]("413150", root), 'DXVK_HUD=1 %command% -d3d9 "-name=Two Words"') + self.assertEqual(RUN["steam_options"]("2733369024", root), "-d3d9") + self.assertEqual(RUN["steam_options"]("70", root), "") + self.assertEqual(RUN["steam_options"]("2733369025", root), "") + info = {"common": {"type": "Game"}, "config": {"launch": { + "0": {"executable": "Game.exe", "type": "default", "config": {"oslist": "windows"}}}}} + self.write("Steam/appcache/appinfo.vdf", appinfo({413150: info})) + program = self.game("413150", "Some Game", "Game.exe") + code, calls, _ = self.run_main(["--app", "413150"]) + self.assertIsNone(code) + _, argv, env = calls[0] + self.assertEqual(argv[1:], ["waitforexitandrun", str(program), "-d3d9", "-name=Two Words"]) + self.assertEqual(env["DXVK_HUD"], "1") + bat = self.write("Games/GOG/Batman/Batman.exe", b"MZ") + code, calls, _ = self.run_main(["--app", "2733369024", "--", str(bat)]) + self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat), "-d3d9"]) + code, calls, _ = self.run_main(["--app", "2733369024", "--options", "", "--", str(bat)]) + self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat)]) + def test_launch_options_split_like_steam_does(self): split = RUN["split_options"] self.assertEqual(split(""), ({}, [])) diff --git a/tools/tests/test_device_controls.py b/tools/tests/test_device_controls.py new file mode 100644 index 0000000000..736d62acba --- /dev/null +++ b/tools/tests/test_device_controls.py @@ -0,0 +1,172 @@ +import json +from pathlib import Path +import runpy +import subprocess +import tempfile +import unittest +from unittest import mock + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat")) + + +class DeviceControlsTest(unittest.TestCase): + def test_sync_controls_queued_notifications_are_processed_without_another_frame(self): + with tempfile.TemporaryDirectory() as directory: + Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1})) + helper = LIVE["Helper"]("/steam", 0) + helper.controls_installed = True + page = mock.Mock(events=[]) + page.ws.pending.return_value = False + helper.page = page + payload = json.dumps({"id": 1, "options": {"strTitle": "Pick a file"}}) + def evaluate(expression): + for name, value in [(LIVE["BRIGHTNESS_BINDING"], "0.4"), (LIVE["FILE_BINDING"], payload)]: + page.events.append({"method": "Runtime.bindingCalled", "params": {"name": name, "payload": value}}) + return True + def drain(): + events, page.events = page.events, [] + return events + page.evaluate.side_effect = evaluate + page.drain.side_effect = drain + helper.reconcile = mock.Mock() + helper.sync_frame_limit = mock.Mock() + helper.ensure_tools = mock.Mock(side_effect=[None, StopIteration]) + helper.open_chooser = mock.Mock() + watcher = mock.Mock() + watcher.fileno.return_value = -1 + watcher.changed.return_value = False + globals_ = LIVE["Helper"].serve.__globals__ + with mock.patch.dict(globals_, {"CONTROLS_DIR": directory, + "brightness_request": lambda value: LIVE["brightness_request"](value, directory)}), \ + mock.patch.dict(globals_["COMPAT"], {"state_path": lambda name: str(Path(directory, name))}), \ + mock.patch.object(globals_["select"], "select", return_value=([], [], [])) as select_: + with self.assertRaises(StopIteration): + helper.serve(watcher) + self.assertEqual(float(Path(directory, "brightness.request").read_text()), 0.4) + helper.open_chooser.assert_called_once_with(payload) + self.assertEqual(page.events, []) + select_.assert_not_called() + + def test_native_brightness_notifications_do_not_echo_android_readback(self): + harness = r""" +const assert = require('assert'); +globalThis.window = globalThis; +const requests = [], callbacks = []; +const timers = []; +globalThis.setTimeout = callback => timers.push(callback); +let current = 1; +window.droiddeckBrightnessChanged = value => requests.push(Number(value)); +globalThis.SteamClient = { System: { Display: { + RegisterForBrightnessChanges(cb) { callbacks.push(cb); cb({ flBrightness: 1 }); return {}; }, + SetBrightness(value) { + if (current === value) return; + current = value; + callbacks.forEach(cb => cb({ flBrightness: value })); + } +} } }; +const script = require('fs').readFileSync(process.argv[2], 'utf8'); +assert.strictEqual(eval(script), 'installed'); +assert.strictEqual(eval(script), 'present'); +const bridge = window.__droiddeckBrightness; +bridge.set(0.5); +bridge.set(0.5); +assert.deepStrictEqual(requests, []); +callbacks.forEach(cb => cb({ flBrightness: 0.8 })); +assert.deepStrictEqual(requests, [0.8]); +bridge.set(0.7992126); +assert.deepStrictEqual(requests, [0.8]); +for (const value of [NaN, Infinity, -1, 2, '0.5']) callbacks.forEach(cb => cb({ flBrightness: value })); +assert.deepStrictEqual(requests, [0.8]); +assert.strictEqual(callbacks.length, 1); +SteamClient.System.Display.SetBrightness = value => callbacks.forEach(cb => cb({ flBrightness: value + 0.1 })); +bridge.set(0.3); +assert.deepStrictEqual(requests, [0.8]); +callbacks.forEach(cb => cb({ flBrightness: 0.6 })); +assert.deepStrictEqual(requests, [0.8, 0.6]); +SteamClient.System.Display.SetBrightness = () => {}; +bridge.set(0.65); +timers.forEach(callback => callback()); +callbacks.forEach(cb => cb({ flBrightness: 0.7 })); +assert.deepStrictEqual(requests, [0.8, 0.6, 0.7]); +""" + with tempfile.TemporaryDirectory() as directory: + script = Path(directory) / "bridge.js" + script.write_text(LIVE["BRIGHTNESS_JS"]) + test = Path(directory) / "test.js" + test.write_text(harness) + result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_requests_reject_nonfinite_and_out_of_range_values(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "brightness.request" + for value in ["NaN", "Infinity", "-0.1", "1.1", "invalid", None]: + LIVE["brightness_request"](value, directory) + self.assertFalse(path.exists()) + LIVE["brightness_request"]("0.4", directory) + self.assertEqual(float(path.read_text()), 0.4) + + def test_failed_request_revision_republishes_the_actual_brightness(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_controls.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + helper = LIVE["Helper"]("/steam", 0) + calls = [] + helper.controls_installed = True + helper.page = type("Page", (), {"evaluate": lambda self, expression: calls.append(expression) or True})() + path = Path(directory) / "state.json" + path.write_text(json.dumps({"brightness": 0.5, "revision": 1})) + helper.sync_controls() + helper.sync_controls() + self.assertEqual(len(calls), 1) + path.write_text(json.dumps({"brightness": 0.5, "revision": 2})) + helper.sync_controls() + self.assertEqual(len(calls), 2) + finally: + globals_["CONTROLS_DIR"] = previous + + def test_display_bridge_retries_binding_and_install_before_caching_state(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_controls.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1})) + calls, installs, writes = [], ["unavailable", "installed", "present"], [] + class Page: + present = True + def call(self, method, params): + calls.append((method, params)) + def evaluate(self, expression): + if expression == LIVE["BRIGHTNESS_JS"]: + return installs.pop(0) + writes.append(expression) + return self.present + helper = LIVE["Helper"]("/steam", 0) + helper.page = Page() + helper.sync_controls() + self.assertIsNone(helper.controls_state) + self.assertFalse(writes) + helper.sync_controls() + helper.sync_controls() + self.assertEqual(len(calls), 2) + self.assertEqual(len(writes), 1) + self.assertEqual(calls[1], ("Runtime.addBinding", {"name": LIVE["BRIGHTNESS_BINDING"]})) + helper.page.present = False + Path(directory, "state.json").write_text(json.dumps({"brightness": 0.7, "revision": 2})) + helper.sync_controls() + self.assertIsNone(helper.controls_state) + self.assertFalse(helper.controls_installed) + helper.page.present = True + helper.sync_controls() + self.assertEqual(len(calls), 3) + self.assertEqual(helper.controls_state["brightness"], 0.7) + finally: + globals_["CONTROLS_DIR"] = previous + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_device_smoke.py b/tools/tests/test_device_smoke.py index 9afeb919f9..25478e0ab5 100644 --- a/tools/tests/test_device_smoke.py +++ b/tools/tests/test_device_smoke.py @@ -47,6 +47,8 @@ elif a[:1] == ["shell"]: s.setdefault("log_commands", []).append(a) p.write_text(json.dumps(s)) if "ls" in a: print(s["session"]) + elif a[-1].endswith("/device.txt"): print(s.get("report", "")) + elif a[-1].endswith("/app.log"): print(s.get("app_log", "")) else: print("package not debuggable") ''' @@ -112,6 +114,16 @@ class DeviceSmokeTest(unittest.TestCase): self.assertEqual(1, result.returncode, result.stdout) self.assertIn("could not launch", result.stdout) + def test_fast_path_requires_a_session_activation_log(self): + for active in (False, True): + with self.subTest(active=active): + result, _ = self.run_smoke( + session="session", report="proot fast path (eligible) true", + app_log="proot: fast path on (66 binds)" if active else "proot: fast path off - too many binds", + ) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + self.assertEqual(active, "PASS proot fast path was on" in result.stdout) + def test_session_name_remains_one_remote_argument(self): session = "x';id;#" result, state = self.run_smoke(session=session) diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index e65b21277e..456eec407d 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -48,6 +48,8 @@ class FexTestCase(unittest.TestCase): "HOST_PRELOAD": str(self.tmp / "ld.so.preload"), "DEVICE_FONTS": str(self.tmp / "android-fonts"), "FONT_RULES": str(self.tmp / "66-droiddeck-device-fonts.conf"), + "OWN_FEX": str(self.tmp / "own"), + "OWN_FEX_TAG": str(self.tmp / "own/share/fex-emu/.droiddeck-tag"), } patcher = mock.patch.dict(G, patches) patcher.start() @@ -202,6 +204,75 @@ class LocateTest(FexTestCase): self.assertEqual((fex["bin"], fex["server"], fex["portable"]), (str(tool / "usr/bin/FEX"), str(tool / "usr/bin/FEXServer"), True)) self.assertTrue(fex["host_thunks"].endswith("HostThunks") and fex["guest_thunks"].endswith("GuestThunks") and fex["thunks_db"]) + def own_fex(self, tag, loads=True): + own = self.tmp / "own" + self.write(own / "bin/FEX", mode=0o755) + self.write(own / "bin/FEXServer", mode=0o755) + self.write(own / "share/fex-emu/.droiddeck-tag", tag + "\n") + listing = b"libc.so.6 => /usr/lib/libc.so.6\n" if loads else b"libxxhash.so.0 => not found\n" + patcher = mock.patch.object(G["subprocess"], "run", lambda args, **kw: subprocess.CompletedProcess(args, 0, listing)) + patcher.start() + self.addCleanup(patcher.stop) + return own + + def test_an_own_build_that_no_longer_loads_is_installed_again_and_skipped(self): + tool = self.fex_tool(self.steam) + self.own_fex("fex-2610-r7", loads=False) + calls = [] + with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \ + mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 1): + FEX["update_own_fex"]() + self.assertEqual([[str(BIN / "droiddeck-fex-update")]], calls) + self.assertEqual(FEX["fex_install"]()["bin"], str(tool / "usr/bin/FEX")) + + def test_droiddeck_s_own_build_comes_before_the_steam_tool(self): + self.fex_tool(self.steam) + own = self.own_fex("fex-2610-r7") + fex = FEX["fex_install"]() + self.assertEqual((fex["bin"], fex["server"], fex["portable"]), (str(own / "bin/FEX"), str(own / "bin/FEXServer"), False)) + + def test_the_build_the_session_names_is_installed_once(self): + self.own_fex("fex-2610-r6") + calls = [] + with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \ + mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0): + FEX["update_own_fex"]() + self.write(self.tmp / "own/share/fex-emu/.droiddeck-tag", "fex-2610-r7\n") + FEX["update_own_fex"]() + self.assertEqual([[str(BIN / "droiddeck-fex-update")]], calls) + + def test_a_failed_build_waits_an_hour_unless_the_session_names_another(self): + self.own_fex("fex-2610-r6") + Path(G["STATE"]).mkdir(parents=True, exist_ok=True) + calls = [] + tag = {"BL_FEX_TAG": "fex-2610-r7"} + with mock.patch.dict(os.environ, tag), \ + mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(os.environ["BL_FEX_TAG"]) or 1): + FEX["update_own_fex"]() + FEX["update_own_fex"]() + failed = Path(G["STATE"]) / "update-failed" + os.utime(failed, (failed.stat().st_atime, failed.stat().st_mtime - 3601)) + FEX["update_own_fex"]() + os.environ["BL_FEX_TAG"] = "fex-2610-r8" + FEX["update_own_fex"]() + self.assertEqual(["fex-2610-r7", "fex-2610-r7", "fex-2610-r8"], calls) + + def test_a_missing_updater_falls_back_to_the_fex_already_here(self): + self.fex_tool(self.steam) + Path(G["STATE"]).mkdir(parents=True, exist_ok=True) + with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \ + mock.patch.object(G["subprocess"], "call", mock.Mock(side_effect=FileNotFoundError)): + FEX["update_own_fex"]() + self.assertEqual(FEX["fex_install"]()["bin"], str(self.steam / "steamapps/common/FEX-Emu/usr/bin/FEX")) + + def test_no_build_is_installed_without_one_from_the_session(self): + calls = [] + with mock.patch.dict(os.environ, {}, clear=False), \ + mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0): + os.environ.pop("BL_FEX_TAG", None) + FEX["update_own_fex"]() + self.assertEqual([], calls) + def test_library_folders_are_read(self): other = self.tmp / "other" (other / "steamapps/common").mkdir(parents=True) diff --git a/tools/tests/test_droiddeck_proton_default.py b/tools/tests/test_droiddeck_proton_default.py new file mode 100644 index 0000000000..6c0665d571 --- /dev/null +++ b/tools/tests/test_droiddeck_proton_default.py @@ -0,0 +1,95 @@ +import json +import runpy +import tempfile +import unittest +from pathlib import Path + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +COMPAT = runpy.run_path(str(BIN / "steam-compatibility")) +TOOL = COMPAT["TOOL"] +OLD = {"name": "DroidDeck-Proton-11-11.2", "display": "DroidDeck-Proton 11-11.2", "dir": "DroidDeck-Proton 11-11.2", "valve": False} +NEW = {"name": "DroidDeck-Proton-11-11.4", "display": "DroidDeck-Proton 11-11.4", "dir": "DroidDeck-Proton 11-11.4", "valve": False} +VALVE = {"name": TOOL, "display": "Proton Experimental ARM64", "dir": "Proton - Experimental (ARM64)", "valve": True} +GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False} + + +def config_text(entries): + mapping = "".join('"%s" { "name" "%s" "config" "" "priority" "%s" }' % (app, name, "75" if app == "0" else "250") for app, name in entries) + return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping + + +class DroidDeckProtonDefaultTest(unittest.TestCase): + def run_default(self, state, mapping, catalog, apps=(), request=None, settle=True): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + (directory / "state.json").write_text(json.dumps(state)) + if request is not None: + (directory / "request.json").write_text(json.dumps(request)) + config = directory / "config.vdf" + config.write_text(config_text(mapping)) + default = COMPAT["register_default"](str(config), list(apps), catalog=catalog, directory=str(directory), settle=settle) + return default, COMPAT["read_config_mapping"](str(config)), json.loads((directory / "state.json").read_text()) + + def test_a_replacement_seen_while_steam_runs_still_moves_the_default_later(self): + _, mapping, state = self.run_default( + {"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", OLD["name"])], [VALVE, NEW], settle=False) + self.assertEqual(state["tools"], [VALVE, NEW]) + self.assertIn(OLD["name"], state["own_builds"]) + default, mapping, state = self.run_default(state, [("0", OLD["name"])], [VALVE, NEW]) + self.assertEqual(default, NEW["name"]) + self.assertEqual(mapping, {"0": NEW["name"]}) + + def test_a_valve_default_picked_in_steam_after_a_replacement_is_kept(self): + default, mapping, _ = self.run_default( + {"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL)], [VALVE, NEW]) + self.assertEqual(default, TOOL) + self.assertEqual(mapping, {"0": TOOL}) + + def test_the_first_start_with_droiddeck_proton_makes_it_the_default_for_following_titles(self): + default, mapping, state = self.run_default( + {"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL), ("43", TOOL)], [VALVE, NEW], ["42", "43"]) + self.assertEqual(default, NEW["name"]) + self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": TOOL}) + self.assertEqual(state["default"], NEW["name"]) + self.assertTrue(state["own_proton"]) + + def test_a_default_picked_after_the_switch_is_kept(self): + default, mapping, state = self.run_default( + {"default": NEW["name"], "own_proton": True, "applied": 1, "tools": [VALVE, NEW]}, + [("0", NEW["name"])], [VALVE, NEW], request={"seq": 2, "valve": True, "dir": VALVE["dir"]}) + self.assertEqual(default, TOOL) + self.assertEqual(mapping, {"0": TOOL}) + default, mapping, state = self.run_default( + {"default": TOOL, "own_proton": True, "tools": [VALVE, NEW]}, [("0", TOOL)], [VALVE, NEW]) + self.assertEqual(default, TOOL) + self.assertEqual(mapping, {"0": TOOL}) + + def test_a_replaced_build_moves_its_default_and_titles_to_the_newest(self): + default, mapping, state = self.run_default( + {"default": OLD["name"], "own_proton": True, "auto": {"42": OLD["name"]}, "tools": [VALVE, OLD, GE]}, + [("0", OLD["name"]), ("42", OLD["name"]), ("43", OLD["name"]), ("44", GE["name"]), ("45", TOOL)], + [VALVE, NEW, GE], ["42", "43", "44", "45"]) + self.assertEqual(default, NEW["name"]) + self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": NEW["name"], "44": GE["name"], "45": TOOL}) + self.assertEqual(state["auto"], {"42": NEW["name"]}) + + def test_a_replaced_build_does_not_override_a_valve_default(self): + default, mapping, _ = self.run_default( + {"default": TOOL, "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL), ("43", OLD["name"])], [VALVE, NEW], ["43"]) + self.assertEqual(default, TOOL) + self.assertEqual(mapping, {"0": TOOL, "43": NEW["name"]}) + + def test_nothing_changes_without_droiddeck_proton(self): + default, mapping, state = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, GE]) + self.assertEqual(default, TOOL) + self.assertEqual(mapping, {"0": TOOL}) + self.assertNotIn("own_proton", state) + + def test_the_newest_build_is_found_by_version(self): + newest, gone = COMPAT["own_proton_moves"]({"tools": [OLD]}, [dict(NEW, name="a", dir="DroidDeck-Proton 11-9.10"), dict(NEW, name="b", dir="DroidDeck-Proton 11-11.1")]) + self.assertEqual(newest, "b") + self.assertEqual(gone, {OLD["name"]}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_droiddeckctl.py b/tools/tests/test_droiddeckctl.py index f6d29030a5..82ff7daa06 100644 --- a/tools/tests/test_droiddeckctl.py +++ b/tools/tests/test_droiddeckctl.py @@ -413,6 +413,21 @@ class DroiddeckctlTest(FakeAdbTest): self.assertEqual("Awake", out["wakefulness"]) self.assertIn(["shell", "input", "keyevent", "KEYCODE_WAKEUP"], [c["args"] for c in self.calls()]) + def test_proot_profile_queues_only_the_next_session(self): + self.configure({"env": {"ok": True}}) + code, out = self.run_ctl("proot-profile", "enable", "--slow-us", "250") + self.assertEqual(0, code, out) + self.assertEqual({"op": "set", "lines": ["PROOT_PROFILE=1", "PROOT_PROFILE_SLOW_US=250"], "persistent": False}, + self.calls("env")[0]["request"]) + + def test_proot_profile_report_needs_no_adb_or_device(self): + path = self.dir / "session.log" + path.write_text('ordinary log') + with unittest.mock.patch.object(ctl, "adb_path", side_effect=AssertionError("must stay offline")): + code, out = self.run_ctl("proot-profile", "report", str(path)) + self.assertEqual(0, code, out) + self.assertFalse(out["hasCounters"]) + def test_override_pushes_to_the_inbox_first(self): self.configure({ "access": {"ok": True, "commands": True, "inbox": "/sdcard/Android/data/x/files/agent-inbox"}, diff --git a/tools/tests/test_fex_install.py b/tools/tests/test_fex_install.py index 355b540381..51d5279e89 100644 --- a/tools/tests/test_fex_install.py +++ b/tools/tests/test_fex_install.py @@ -6,7 +6,7 @@ import tempfile import textwrap import unittest -SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64" +SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-fex-update" SOURCE = SCRIPT.read_text() START = SOURCE.index("fex_install() {") END = SOURCE.index("\n}\n", START) + 3 diff --git a/tools/tests/test_fex_select.py b/tools/tests/test_fex_select.py index 94008a1c70..3b351520e7 100644 --- a/tools/tests/test_fex_select.py +++ b/tools/tests/test_fex_select.py @@ -5,9 +5,9 @@ import tempfile import textwrap import unittest -SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64" +SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-fex-update" SOURCE = SCRIPT.read_text() -START = SOURCE.index("x64_fex() {") +START = SOURCE.index("fex_ready() {") END = SOURCE.index("\n}\n", START) + 3 X64_FEX = SOURCE[START:END] @@ -35,7 +35,7 @@ class FexSelectTest(unittest.TestCase): fex.chmod(0o755) body = (X64_FEX.replace("/usr/local/share/fex-emu/.droiddeck-tag", "$ROOT/tag") .replace("/usr/local/bin/FEX", "$ROOT/FEX")) - script = HARNESS + body + 'if x64_fex; then echo "NOW $FEX_NOW|$FEX_FROM"; else echo FAILED; fi\n' + script = HARNESS + body + 'if fex_ready; then echo "NOW $FEX_NOW|$FEX_FROM"; else echo FAILED; fi\n' env = dict(os.environ, ROOT=root, LOADS="1" if loads else "0", INSTALLABLE=" ".join(installable)) env.pop("BL_FEX_TAG", None) if catalog: diff --git a/tools/tests/test_flatpak_setup.py b/tools/tests/test_flatpak_setup.py new file mode 100644 index 0000000000..7de2d0f7aa --- /dev/null +++ b/tools/tests/test_flatpak_setup.py @@ -0,0 +1,67 @@ +import contextlib +import fcntl +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup" + + +class FlatpakSetupTest(unittest.TestCase): + def run_setup(self, uid, pacman, locked=False, busy=False): + with tempfile.TemporaryDirectory() as directory, contextlib.ExitStack() as held: + root = Path(directory) + if locked: + (root / "work/db").mkdir(parents=True) + (root / "work/db/db.lck").write_text("") + if busy: + holder = held.enter_context(open(root / "work/setup.lock", "w")) + fcntl.flock(holder, fcntl.LOCK_EX | fcntl.LOCK_NB) + bin_dir = root / "bin" + bin_dir.mkdir() + stubs = {"id": "echo %d" % uid, "curl": "exit 7", "pacman": pacman, "pacman-key": "exit 0"} + for name, body in stubs.items(): + (bin_dir / name).write_text("#!/bin/sh\n%s\n" % body) + (bin_dir / name).chmod(0o755) + script = root / "setup" + script.write_text(SCRIPT.read_text().replace("WORK=/var/cache/droiddeck-flatpak", "WORK=%s/work" % root) + .replace("/etc/pacman.d/gnupg/pubring.gpg", str(root / "pubring.gpg")) + .replace(" /etc/pacman.conf >", " %s >" % (root / "pacman.conf"))) + (root / "pacman.conf").write_text("[options]\n[core]\nInclude = /etc/pacman.d/mirrorlist\n") + (root / "pubring.gpg").write_text("") + env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ["PATH"])) + result = subprocess.run(["bash", str(script)], env=env, capture_output=True, text=True, timeout=30) + return result.returncode, result.stdout + + def test_a_manual_run_without_root_says_so(self): + code, out = self.run_setup(1000, "exit 0") + self.assertEqual(code, 1) + self.assertIn("== FAIL needs root", out) + self.assertNotIn("Reading the package lists", out) + + def test_an_unreachable_mirror_reports_pacmans_error(self): + code, out = self.run_setup(0, "echo \"error: failed retrieving file 'core.db' : Could not resolve host\" >&2; exit 1") + self.assertEqual(code, 1) + self.assertIn("== FAIL could not reach the Arch Linux ARM mirrors (error: failed retrieving file 'core.db' : " + "Could not resolve host)", out) + + SYNC = ("db=; while [ $# -gt 0 ]; do [ \"$1\" = --dbpath ] && db=$2; shift; done\n" + "[ -e \"$db/db.lck\" ] && { echo 'error: failed to synchronize all databases (unable to lock database)' >&2; exit 1; }\n" + "mkdir -p \"$db/sync\" && touch \"$db/sync/extra.db\"") + + def test_a_lock_left_by_an_interrupted_run_is_cleared(self): + code, out = self.run_setup(0, self.SYNC, locked=True) + self.assertNotIn("unable to lock database", out) + self.assertIn("== STEP Downloading Flatpak", out) + + def test_a_setup_that_is_still_running_keeps_its_lock(self): + code, out = self.run_setup(0, self.SYNC, locked=True, busy=True) + self.assertEqual(code, 1) + self.assertIn("== FAIL another Flatpak setup is still running", out) + self.assertNotIn("Reading the package lists", out) + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_frame_limit_sync.py b/tools/tests/test_frame_limit_sync.py new file mode 100644 index 0000000000..0cbdc18fb9 --- /dev/null +++ b/tools/tests/test_frame_limit_sync.py @@ -0,0 +1,139 @@ +"""The Quick Access Frame Limit follows the panel when its refresh rate changes.""" +from pathlib import Path +import runpy +import subprocess +import tempfile +import unittest +from unittest import mock + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat")) + +HARNESS = r""" +const assert = require('assert'); +globalThis.window = globalThis; +globalThis.btoa = text => Buffer.from(text, 'binary').toString('base64'); +let timers = new Map(), nextTimer = 0; +globalThis.setTimeout = (callback, ms) => { timers.set(++nextTimer, callback); return nextTimer; }; +globalThis.clearTimeout = id => timers.delete(id); +globalThis.setInterval = () => 0; +const fire = async () => { + const pending = [...timers.values()]; timers = new Map(); + for (const callback of pending) await callback(); +}; +let rates = [36, 48, 72, 144]; +const notify = []; +const service = { + GetState: async () => ({ BSuccess: () => true, + Body: () => ({ toObject: () => ({ state: { active_display_info: { supported_frame_rates: rates } } }) }) }), + RegisterForNotifyStateChanged(callback) { notify.push(callback); return {}; }, + SetBlurParams() {}, +}; +const writes = []; +globalThis.settingsStore = { clientSettings: { + gamescope_enable_app_target_framerate: true, gamescope_app_target_framerate: 120, gamescope_disable_framelimit: false } }; +const varints = bytes => { const out = []; let value = 0, shift = 0; + for (const b of bytes) { value += (b & 127) * 2 ** shift; shift += 7; if (b < 128) { out.push(value); value = 0; shift = 0; } } + return out; }; +globalThis.SteamClient = { Settings: { SetSetting(encoded) { + const [key, value] = varints([...Buffer.from(encoded, 'base64')]); + assert.strictEqual(key, 21002 * 8); + writes.push(value); + settingsStore.clientSettings.gamescope_app_target_framerate = value; +} } }; +const modules = { + 1: { source: () => 'RegisterForNotifyStateChanged only', exports: { other: { GetState() {} } } }, + 2: { source: () => 'n.MX.SetBlurParams(); n.MX.RegisterForNotifyStateChanged()', exports: { hooks: () => {} } }, + 3: { source: () => 'SetBlurParams RegisterForNotifyStateChanged GetState', exports: { MX: service } }, +}; +const webpack = modules => { const require = id => modules[id].exports; + require.m = Object.fromEntries(Object.entries(modules).map(([id, m]) => [id, { toString: m.source }])); + return require; }; +globalThis.webpackChunksteamui = { push([, , callback]) { callback(webpack(modules)); } }; +const script = require('fs').readFileSync(process.argv[2], 'utf8'); +const change = async next => { rates = next; notify.forEach(callback => callback()); }; +(async () => { + assert.strictEqual(eval(script), 'installed'); + assert.strictEqual(eval(script), 'present'); + await fire(); + assert.deepStrictEqual(writes, [144], 'a remembered limit the panel does not offer moves to the highest value'); + await fire(); + assert.deepStrictEqual(writes, [144], 'unchanged choices are not written again'); + settingsStore.clientSettings.gamescope_app_target_framerate = 72; + await change([24, 30, 40, 60, 120]); + await fire(); + assert.deepStrictEqual(writes, [144, 120], '72 is not offered at 120 Hz'); + settingsStore.clientSettings.gamescope_app_target_framerate = 60; + await change([12, 15, 20, 30, 60]); + await fire(); + assert.deepStrictEqual(writes, [144, 120], '60 is still offered at 60 Hz and is kept'); + await change([18, 24, 36, 72]); + await change([24, 30, 40, 60, 120]); + await fire(); + assert.deepStrictEqual(writes, [144, 120], 'a passing rate during a mode switch is not acted on'); + settingsStore.clientSettings.gamescope_enable_app_target_framerate = false; + settingsStore.clientSettings.gamescope_app_target_framerate = 72; + await change([36, 48, 144]); + await fire(); + assert.deepStrictEqual(writes, [144, 120], 'nothing changes while Steam has the frame limit turned off'); + settingsStore.clientSettings.gamescope_enable_app_target_framerate = true; + window.__droiddeckFrameLimit.schedule(); + await fire(); + assert.deepStrictEqual(writes, [144, 120, 144], 'turning the limit on after a rate change moves an unoffered value'); + settingsStore.clientSettings.gamescope_app_target_framerate = 72; + const setSetting = SteamClient.Settings.SetSetting; + SteamClient.Settings.SetSetting = () => { throw new Error('busy'); }; + window.__droiddeckFrameLimit.schedule(); + await fire(); + SteamClient.Settings.SetSetting = setSetting; + window.__droiddeckFrameLimit.schedule(); + await fire(); + assert.deepStrictEqual(writes, [144, 120, 144, 144], 'a failed write is tried again on the next check'); + settingsStore.clientSettings.gamescope_app_target_framerate = 72; + SteamClient.Settings.SetSetting = () => Promise.reject(new Error('busy')); + window.__droiddeckFrameLimit.schedule(); + await fire(); + SteamClient.Settings.SetSetting = setSetting; + window.__droiddeckFrameLimit.schedule(); + await fire(); + assert.deepStrictEqual(writes, [144, 120, 144, 144, 144], 'a rejected write is caught and tried again'); + delete window.__droiddeckFrameLimit; + webpackChunksteamui.push = ([, , callback]) => callback(webpack({ 1: modules[1], 2: modules[2] })); + assert.strictEqual(eval(script), 'unavailable'); +})().catch(error => { console.error(error); process.exit(1); }); +""" + + +class FrameLimitSyncTest(unittest.TestCase): + def test_limit_is_kept_when_offered_and_moved_to_the_highest_value_otherwise(self): + with tempfile.TemporaryDirectory() as directory: + script = Path(directory) / "frame_limit.js" + script.write_text(LIVE["FRAME_LIMIT_JS"]) + test = Path(directory) / "test.js" + test.write_text(HARNESS) + result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_install_is_retried_until_steam_is_ready_and_reported_once_per_state(self): + helper = LIVE["Helper"]("/steam", 0) + page = mock.Mock() + page.evaluate.side_effect = ["unavailable", "unavailable", "installed"] + helper.page = page + said = [] + clock = [100.0] + globals_ = LIVE["Helper"].sync_frame_limit.__globals__ + with mock.patch.dict(globals_, {"say": said.append}), mock.patch.object(globals_["time"], "monotonic", lambda: clock[0]): + helper.sync_frame_limit() + helper.sync_frame_limit() + clock[0] += 10 + helper.sync_frame_limit() + clock[0] += 10 + helper.sync_frame_limit() + clock[0] += 10 + helper.sync_frame_limit() + self.assertEqual(page.evaluate.call_count, 3) + self.assertEqual(said, ["frame limit sync: unavailable", "frame limit sync: installed"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index 208e4b1dd1..0b1bee1753 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -8,6 +8,7 @@ import shlex import subprocess import sys import tempfile +from unittest import mock import unittest BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" @@ -76,6 +77,35 @@ class GameEnvironmentTest(unittest.TestCase): env=env, text=True, capture_output=True, check=True) self.assertEqual(result.stdout.strip(), expected) + def test_desktop_games_restart_on_the_gpu_with_steams_preloads_handed_back(self): + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) + gpu = home / "gpu" + gpu.write_text("#!/bin/bash\necho \"gpu LD_PRELOAD=${LD_PRELOAD-unset}\"\nexport BL_DESKTOP_GPU_CHILD=1\nexec \"$@\"\n") + gpu.chmod(0o755) + launcher = home / "launcher" + setup = COMPAT["BL_DESKTOP_GPU_SETUP"].replace("/usr/local/bin/droiddeck-gpu", str(gpu)) + launcher.write_text("#!/bin/bash\nverb=$1; shift\n" + setup + "echo \"game $verb $* LD_PRELOAD=${LD_PRELOAD-unset} saved=${BL_GPU_SAVED_LD_PRELOAD-unset}\"\n") + launcher.chmod(0o755) + base = {key: value for key, value in os.environ.items() if not key.startswith("BL_")} + base["LD_PRELOAD"] = "overlay.so" + for extra, args, expected in ( + ({"BL_DESKTOP": "1"}, ["waitforexitandrun", "game.exe"], + ["gpu LD_PRELOAD=unset", "game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]), + ({"BL_DESKTOP": "1", "BL_DESKTOP_GPU": "Off"}, ["waitforexitandrun", "game.exe"], + ["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]), + ({"BL_DESKTOP": "1"}, ["run", "setup.exe"], + ["game run setup.exe LD_PRELOAD=overlay.so saved=unset"]), + ({"BL_DESKTOP": "1"}, ["waitforexitandrun", "iscriptevaluator.exe"], + ["game waitforexitandrun iscriptevaluator.exe LD_PRELOAD=overlay.so saved=unset"]), + ({}, ["waitforexitandrun", "game.exe"], + ["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]), + ): + with self.subTest(extra=extra, args=args): + result = subprocess.run([str(launcher)] + args, env=dict(base, **extra), + text=True, capture_output=True, check=True) + self.assertEqual(result.stdout.splitlines(), expected) + def test_the_install_script_evaluator_gets_its_scripts_marked_first(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) @@ -180,6 +210,14 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem") self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43")) + def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self): + cap = MODULE["vram_cap"] + self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096") + self.assertEqual(cap({"BL_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"], + "dxgi.maxDeviceMemory = 2048; dxvk.maxFrameRate = 60") + for off in ({}, {"BL_VRAM_MB": "0"}, {"BL_VRAM_MB": "lots"}, {"BL_VRAM_MB": "²"}, {"BL_VRAM_MB": "-1"}): + self.assertNotIn("DXVK_CONFIG", cap(off)) + def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self): env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"} config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}} @@ -264,6 +302,13 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d") self.assertEqual(extra, ["--rendering-driver", "vulkan"]) self.assertEqual(MODULE["engine_fixes"](str(game / "Game.exe"), ["--rendering-driver", "opengl3"])[1], []) + script = Path(tmp) / "GDScript Game" + script.mkdir() + for name in ("Game.exe", "Game.pck", "libsentry.windows.release.x86_64.dll"): + (script / name).touch() + env, extra, notes = MODULE["engine_fixes"](str(script / "Game.exe"), []) + self.assertNotIn("WINEDLLOVERRIDES", env) + self.assertEqual(extra, ["--rendering-driver", "vulkan"]) other = Path(tmp) / "Other" other.mkdir() (other / "Other.exe").touch() @@ -357,7 +402,95 @@ class GameEnvironmentTest(unittest.TestCase): (asylum / name).touch() self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], [])) - def test_caravan_sandwitch_and_cyberpunk_run_at_feature_level_12_1(self): + def test_d3dgear_capture_hook_beside_the_game_is_turned_off(self): + with tempfile.TemporaryDirectory() as tmp: + game = Path(tmp) / "The Crew 2" + game.mkdir() + for name in ("TheCrew2.exe", "TheCrew2_BE.exe", "d3dgear64.dll"): + (game / name).touch() + env, extra, notes = MODULE["engine_fixes"](str(game / "TheCrew2.exe"), []) + self.assertEqual((env, extra), ({"WINEDLLOVERRIDES": "d3dgear64=d"}, [])) + self.assertTrue(notes) + (game / "d3dgear64.dll").rename(game / "D3DGear64.DLL") + self.assertEqual(MODULE["engine_fixes"](str(game / "TheCrew2.exe"), [])[0], {"WINEDLLOVERRIDES": "d3dgear64=d"}) + (game / "D3DGear64.DLL").unlink() + self.assertEqual(MODULE["engine_fixes"](str(game / "TheCrew2.exe"), []), ({}, [], [])) + + def test_dll_overrides_from_several_fixes_are_all_kept(self): + with tempfile.TemporaryDirectory() as tmp: + for name in ("Game.exe", "Game.pck", "GodotSharp.dll", "libsentry.windows.release.x86_64.dll", "d3dgear64.dll"): + (Path(tmp) / name).touch() + env = MODULE["engine_fixes"](str(Path(tmp) / "Game.exe"), [])[0] + self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d;d3dgear64=d") + + def test_black_ops_iii_and_dark_souls_remastered_skip_protonfixes(self): + for exe in ("/game/Call of Duty Black Ops III/BlackOps3.exe", "/game/DARK SOULS REMASTERED/DarkSoulsRemastered.exe"): + env, extra, notes = MODULE["engine_fixes"](exe, []) + self.assertEqual((env, extra), ({"PROTONFIXES_DISABLE": "1"}, [])) + self.assertTrue(notes) + self.assertEqual(MODULE["engine_fixes"]("/game/Game/DarkSoulsII.exe", []), ({}, [], [])) + + def test_game_cores_are_parsed_from_lists_and_ranges(self): + parse = MODULE["parse_cores"] + self.assertEqual(parse("0-3,6"), {0, 1, 2, 3, 6}) + self.assertEqual(parse(" 4, 5 "), {4, 5}) + for bad in ("", "a", "3-1", "1,,2", "-1", "1-"): + self.assertIsNone(parse(bad), bad) + + def test_a_profiles_game_cores_pin_the_game_within_the_online_cores(self): + calls = [] + os_mod = MODULE["os"] + with mock.patch.dict(MODULE["game_cores"].__globals__, {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}}), \ + mock.patch.object(os_mod, "sched_setaffinity", side_effect=lambda pid, cores: calls.append(set(cores)), create=True): + MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "0-2,9"}) + MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "junk"}) + MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "12-13"}) + MODULE["game_cores"]({}) + self.assertEqual(calls, [{0, 1, 2}]) + self.assertEqual(MODULE["parse_cores"]("0,2-7"), {0, 2, 3, 4, 5, 6, 7}) + + def test_windows_games_see_only_the_cores_they_are_pinned_to(self): + os_mod = MODULE["os"] + online = {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}} + cases = [ + ({"BL_GAME_CPUS": "6,7"}, {6, 7}, "2:6,7", "2:6,7"), + ({"DROIDDECK_GAME_CORES": "0-2"}, {0, 1, 2}, "3:0,1,2", "3:0,1,2"), + ({"BL_GAME_CPUS": "0-7"}, set(range(8)), None, None), + ({}, {6, 7}, None, None), + ({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": "4:0,1,2,3"}, {6, 7}, "4:0,1,2,3", "4:0,1,2,3"), + ({"WINE_CPU_TOPOLOGY": "2:0,1"}, set(range(8)), "2:0,1", "2:0,1"), + ({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": ""}, {6, 7}, "", None), + ({"BL_GAME_CPUS": "6,7", "PROTON_CPU_TOPOLOGY": "1:7"}, {6, 7}, None, "1:7"), + ({"BL_GAME_CPUS": "9"}, {9}, None, None), + ] + for env, affinity, expected, proton in cases: + with mock.patch.dict(MODULE["cpu_topology"].__globals__, online), \ + mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True): + MODULE["cpu_topology"](env) + self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env) + self.assertEqual(env.get("PROTON_CPU_TOPOLOGY"), proton, env) + + def test_reskate_runs_at_feature_level_12_1(self): + with tempfile.TemporaryDirectory() as tmp: + reskate = Path(tmp) / "ReSkate" + reskate.mkdir() + for name in ("Skate.exe", "ReSkate.dll", "ReSkateLauncher.exe", "EAAntiCheat.GameServiceLauncher.exe"): + (reskate / name).touch() + for exe in ("ReSkateLauncher.exe", "Skate.exe"): + env, extra, notes = MODULE["engine_fixes"](str(reskate / exe), []) + self.assertEqual((env, extra), ({"VKD3D_FEATURE_LEVEL": "12_1"}, []), exe) + self.assertTrue(notes) + config = {"version": 1, "shared": {"VKD3D_FEATURE_LEVEL": "12_2"}} + self.assertEqual(MODULE["apply_config"]({}, config, "3354750", env)["VKD3D_FEATURE_LEVEL"], "12_1") + config["games"] = {"3354750": {"VKD3D_FEATURE_LEVEL": "12_2"}} + self.assertEqual(MODULE["apply_config"]({}, config, "3354750", env)["VKD3D_FEATURE_LEVEL"], "12_2") + skate = Path(tmp) / "Skate" + skate.mkdir() + for name in ("Skate.exe", "EAAntiCheat.GameServiceLauncher.exe"): + (skate / name).touch() + self.assertEqual(MODULE["engine_fixes"](str(skate / "EAAntiCheat.GameServiceLauncher.exe"), [])[:2], ({}, [])) + + def test_caravan_sandwitch_robocop_and_cyberpunk_run_at_feature_level_12_1(self): with tempfile.TemporaryDirectory() as tmp: caravan = Path(tmp) / "Caravan SandWitch" shipping = caravan / "CaravanSandWitch/Binaries/Win64" @@ -369,8 +502,13 @@ class GameEnvironmentTest(unittest.TestCase): (cyberpunk / "bin/x64").mkdir(parents=True) for name in ("REDprelauncher.exe", "bin/x64/Cyberpunk2077.exe"): (cyberpunk / name).touch() + robocop = Path(tmp) / "RoboCop Rogue City" + (robocop / "RoboCop/Binaries/Win64").mkdir(parents=True) + for name in ("RoboCop.exe", "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe"): + (robocop / name).touch() games = [caravan / "CaravanSandWitch.exe", caravan / ".droiddeck-launch.bat", shipping / "CaravanSandWitch-Win64-Shipping.exe", + robocop / "RoboCop.exe", robocop / "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe", cyberpunk / "REDprelauncher.exe", cyberpunk / "bin/x64/Cyberpunk2077.exe"] for exe in games: env, extra, notes = MODULE["engine_fixes"](str(exe), []) diff --git a/tools/tests/test_proot_profile.py b/tools/tests/test_proot_profile.py new file mode 100644 index 0000000000..9548705157 --- /dev/null +++ b/tools/tests/test_proot_profile.py @@ -0,0 +1,91 @@ +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +TOOLS = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(TOOLS)) +from proot_profile import report + +PROGRAM = r''' +#define _POSIX_C_SOURCE 200809L +#define PR_NB_SYSNUM 2 +#define PR_void 0 +static const char *stringify_sysnum(unsigned nr) { return nr ? "openat" : "void"; } +#include "profile.h" +int main(void) { + errno = EBUSY; + if (!dd_profile_enabled()) return errno != EBUSY; + if (errno != EBUSY) return 1; + for (int i = 0; i < 40; i++) { + uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC); + uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID); + struct timespec wait = {0, 2000000}; + nanosleep(&wait, 0); + errno = ENOENT; + dd_profile_record(1, 1, 123, wall, cpu); + if (errno != ENOENT) return 2; + if (i == 9) dd_profile_flush(); + } + dd_profile_next = 0; + uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC); + uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID); + struct timespec wait = {0, 2000000}; + nanosleep(&wait, 0); + dd_profile_record(1, 0, 123, wall, cpu); + return 0; +} +''' + + +class ProotProfileTest(unittest.TestCase): + def test_snapshots_replace_instead_of_adding_and_tracers_remain_separate(self): + with tempfile.TemporaryDirectory() as work: + path = Path(work) / 'session.log' + records = [dict(type='total', tracer=1, id=2, syscall='statx', stage='enter', + calls=n, wall_ns=n * 100, cpu_ns=n * 10, max_ns=100) for n in (3, 8)] + records.append(dict(records[-1], tracer=2, calls=2)) + records += [dict(type='total', tracer=1, id=3, syscall='openat', stage='enter', + calls=1, wall_ns=1000, cpu_ns=1000, max_ns=1000)] + path.write_text('unrelated log\n' + ''.join('prefix proot-profile ' + json.dumps(r) + '\n' for r in records) + + 'proot-profile {truncated\n' + 'proot-profile []\n') + result = report(path) + self.assertEqual(11, result['handlerCalls']) + self.assertEqual(3, result['tracers']) + self.assertEqual(2, result['malformedRecords']) + self.assertEqual('statx', result['totals'][0]['syscall']) + self.assertEqual('openat', report(path, 'cpu')['totals'][0]['syscall']) + + def test_empty_logs_do_not_claim_profiling_ran(self): + with tempfile.TemporaryDirectory() as work: + path = Path(work) / 'session.log' + path.write_text('ordinary log\n') + self.assertFalse(report(path)['hasCounters']) + + @unittest.skipUnless(shutil.which('cc'), 'C compiler required') + def test_real_clocks_bounded_samples_errno_and_periodic_counters(self): + with tempfile.TemporaryDirectory() as work: + source = Path(work) / 'profile.c' + binary = Path(work) / 'profile' + source.write_text(PROGRAM) + subprocess.run(['cc', '-Wall', '-Wextra', '-Werror', '-std=c99', '-I', str(TOOLS / 'proot'), + str(source), '-o', str(binary)], check=True) + for setting in ('0', ''): + result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE=setting), capture_output=True, check=True) + self.assertEqual(b'', result.stderr) + result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE='1', PROOT_PROFILE_SLOW_US='1'), + capture_output=True, check=True) + rows = [json.loads(line.split(b'proot-profile ', 1)[1]) for line in result.stderr.splitlines()] + self.assertEqual(33, sum(row['type'] == 'slow' for row in rows)) + self.assertEqual(32, sum(row['type'] == 'slow' and row['stage'] == 'enter' for row in rows)) + self.assertGreater(sum(row['type'] == 'total' for row in rows), 2) + log = Path(work) / 'session.log' + log.write_bytes(result.stderr) + counters = report(log) + self.assertEqual(41, counters['handlerCalls']) + self.assertGreater(counters['handlerWallNs'], counters['handlerCpuNs']) + self.assertEqual(40, counters['totals'][0]['calls']) diff --git a/tools/tests/test_session_guest_command.py b/tools/tests/test_session_guest_command.py index 9c319ce951..d6f352a8e9 100644 --- a/tools/tests/test_session_guest_command.py +++ b/tools/tests/test_session_guest_command.py @@ -22,7 +22,7 @@ PACKAGES = [line.split()[1] for line in VARIANTS.read_text().splitlines() def guest_prefix(package): source = SERVICE.read_text() before_environment = source.split("val guest = ArrayList<String>()", 1)[1].split( - "addClientEnvironment(guest, steamHere)", 1)[0] + "addClientEnvironment(guest,", 1)[0] environment = source.split("private fun addClientEnvironment(", 1)[1].split( 'guest.add("HOME=/root")', 1)[0] prefix = [] diff --git a/tools/tests/test_session_pacing.py b/tools/tests/test_session_pacing.py new file mode 100644 index 0000000000..84962fe9e6 --- /dev/null +++ b/tools/tests/test_session_pacing.py @@ -0,0 +1,64 @@ +"""Steam owns game caps; the nested compositor follows the output refresh rate.""" +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session' + + +class SessionPacingTest(unittest.TestCase): + def launch(self, refresh, **overrides): + source = SESSION.read_text() + start = source.index(' width=${BL_WIDTH:-1280}') + end = source.index('\nfi\n\nbl_displays()', start) + block = source[start:end].replace('/usr/local/bin/droiddeck-pipewire', 'pipewire_stub') + with tempfile.TemporaryDirectory() as directory: + env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH=str(refresh), + BL_MANGOAPP='0', BL_FPS='0', DROIDDECK_GAME_FRAME_LIMIT='0') + env.pop('GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST', None) + env.update(overrides) + script = ''' +set -u +mode=steam +pipewire_stub() { return 1; } +run_gamescope() { printf 'ARG:%s\\n' "$@"; printf 'FOLLOW:%s\\n' "${GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST:-}"; } +''' + block + result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, + text=True, timeout=5) + self.assertEqual(0, result.returncode, result.stderr) + self.follow = [line.removeprefix('FOLLOW:') for line in result.stdout.splitlines() + if line.startswith('FOLLOW:')] + return [line.removeprefix('ARG:') for line in result.stdout.splitlines() + if line.startswith('ARG:')] + + def test_display_refresh_sets_the_nested_compositor_rate(self): + for refresh in (60, 90, 120): + with self.subTest(refresh=refresh): + args = self.launch(refresh) + self.assertEqual(str(refresh), args[args.index('-r') + 1]) + self.assertIn('-e', args) + + def test_gamescope_follows_the_panel_after_the_starting_rate(self): + self.launch(144) + self.assertEqual(['1'], self.follow) + self.launch(0) + self.assertEqual([''], self.follow) + + def test_retired_cap_variables_do_not_override_the_display_rate(self): + for performance in ('0', '1'): + with self.subTest(performance=performance): + args = self.launch(120, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT=performance) + self.assertEqual('120', args[args.index('-r') + 1]) + self.assertNotIn('--framerate-limit', args) + + def test_retired_cap_cannot_set_the_rate_when_the_display_rate_is_unknown(self): + args = self.launch(0, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT='1') + self.assertNotIn('-r', args) + self.assertNotIn('--framerate-limit', args) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_steam_compat_environment.py b/tools/tests/test_steam_compat_environment.py index 273fbf6dde..5ecaba1772 100644 --- a/tools/tests/test_steam_compat_environment.py +++ b/tools/tests/test_steam_compat_environment.py @@ -69,6 +69,44 @@ class SteamCompatEnvironmentTest(unittest.TestCase): os.kill(helper_pid, 9) self.fail('droiddeck-steam-compat outlived the session') + def test_the_x86_64_client_gets_only_the_file_dialog_bridge(self): + source = (BIN / 'droiddeck-session').read_text() + start = source.index(' if [ "$steam_x64" = 1 ]; then\n { droiddeck-steam-compat --files-only') + block = source[start:source.index(' fi\n', start) + len(' fi\n')] + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + helper = root / 'droiddeck-steam-compat' + helper.write_text('#!/bin/sh\necho "$@" >> "$ARGS_FILE"\n') + helper.chmod(0o755) + for x64, expected in (('1', '--files-only /steam'), ('0', '/steam')): + with self.subTest(x64=x64): + args = root / ('args-' + x64) + env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], + ARGS_FILE=str(args), steam_root='/steam', steam_x64=x64) + subprocess.run(['bash', '-c', '_bl_compat_env=(env)\n' + block + 'wait\n'], env=env, timeout=10, check=True) + self.assertEqual(args.read_text().split('\n')[0], expected) + + def test_files_only_mode_installs_only_the_file_dialog_hook(self): + import runpy + compat = runpy.run_path(str(BIN / 'droiddeck-steam-compat')) + calls = [] + + class Page: + def __init__(self, port, path): + self.ws = None + def evaluate(self, expression): + calls.append(('evaluate', expression[:40])) + return True + def call(self, method, params): + calls.append((method, params['name'])) + + helper = compat['Helper']('/steam', 1234, files_only=True) + helper.attach.__globals__.update(shared_context=lambda port: '/devtools/page/1', Page=Page) + self.assertTrue(helper.attach()) + bindings = [name for method, name in calls if method == 'Runtime.addBinding'] + self.assertEqual(bindings, [compat['FILE_BINDING']]) + self.assertIn(('evaluate', compat['FILE_JS'][:40]), calls) + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_store_launch.py b/tools/tests/test_store_launch.py index 5da2972ed9..c42448424a 100644 --- a/tools/tests/test_store_launch.py +++ b/tools/tests/test_store_launch.py @@ -277,11 +277,40 @@ class CloudHooks(unittest.TestCase): for sh in (compat.LAUNCHER_SH, compat.EXTRA_WRAPPER_SH): self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh) self.assertNotIn('exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh) - self.assertIn('[ $? -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP) + self.assertIn('[ $rc -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP) self.assertIn('droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}"', compat.BL_STORE_SETUP) self.assertIn('exec "$@"', compat.BL_STORE_SETUP) +BNET_EXE = '/root/.local/share/Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe' + + +class BattleNet(unittest.TestCase): + def test_a_games_shortcut_is_handed_to_droiddeck_battlenet(self): + self.assertEqual([store.BATTLENET, 'launch', 'Fen'], store.battlenet(['waitforexitandrun', BNET_EXE, '--exec=launch Fen'], env={})) + self.assertEqual([store.BATTLENET, 'launch', 'OSI'], store.battlenet(['"%s"' % BNET_EXE, '--exec="launch OSI"'], env={})) + self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE], env={})) + + def test_anything_else_and_its_own_starts_are_left_alone(self): + other = BNET_EXE.replace('2596113170', '123') + self.assertIsNone(store.battlenet([other, '--exec=launch Fen'], env={})) + self.assertIsNone(store.battlenet(['/x/Diablo IV/Diablo IV.exe'], env={})) + self.assertIsNone(store.battlenet([BNET_EXE, '--exec=launch Fen'], env={'BL_BATTLENET': '1'})) + self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE, '--exec=launch Fen;rm'], env={})) + + def test_the_launch_runs_there_and_the_wrapper_ends_with_it(self): + with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=0) as call: + os.environ.pop('BL_BATTLENET', None) + self.assertEqual(store.RAN, store.main([BNET_EXE, '--exec=launch Pro'])) + call.assert_called_once_with([store.BATTLENET, 'launch', 'Pro']) + with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=1): + os.environ.pop('BL_BATTLENET', None) + self.assertEqual(store.RAN_FAILED, store.main([BNET_EXE, '--exec=launch Pro'])) + self.assertIn('[ $rc -eq 11 ] && exit 0', compat.BL_STORE_SETUP) + self.assertIn('[ $rc -eq 12 ] && exit 1', compat.BL_STORE_SETUP) + self.assertLess(compat.BL_STORE_SETUP.index('droiddeck-store-launch "$@"'), compat.BL_STORE_SETUP.index('[ $rc -eq 11 ] && exit 0')) + + class Launchers(unittest.TestCase): def test_both_proton_launchers_ask_before_proton_starts(self): sh = compat.LAUNCHER_SH diff --git a/tools/tests/test_validate_apk.py b/tools/tests/test_validate_apk.py index d197d74cff..448d969a91 100644 --- a/tools/tests/test_validate_apk.py +++ b/tools/tests/test_validate_apk.py @@ -28,7 +28,8 @@ class ValidateApkTest(unittest.TestCase): def git(self, *args): return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip() - def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt"): + def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write"): + (self.root / filename).parent.mkdir(parents=True, exist_ok=True) (self.root / filename).write_text(message) self.git("add", filename) self.git("commit", "--allow-empty", "-qm", message) @@ -42,6 +43,8 @@ class ValidateApkTest(unittest.TestCase): path.write_text(json.dumps(event)) def api(path, *args): + if path.endswith("/collaborators/human/permission"): + return {"permission": permission, "role_name": role_name} if "/statuses/" in path: self.statuses.append(dict(value.split("=", 1) for value in args if "=" in value)) return {} @@ -96,6 +99,19 @@ class ValidateApkTest(unittest.TestCase): self.validate(filename="README.md", result="pending") self.assertEqual(self.statuses[-1]["state"], "success") + def test_trusted_list_requires_maintainer_pr_opener(self): + with self.assertRaisesRegex(RuntimeError, "Only a maintainer"): + self.validate(filename=".github/trusted-test-builds.txt") + self.assertEqual(self.statuses[-1]["state"], "failure") + + def test_maintainer_can_change_trusted_list(self): + self.validate(filename=".github/trusted-test-builds.txt", permission="write", role_name="maintain") + self.assertEqual(self.statuses[-1]["state"], "success") + + def test_admin_can_change_trusted_list(self): + self.validate(filename=".github/trusted-test-builds.txt", permission="admin", role_name="admin") + self.assertEqual(self.statuses[-1]["state"], "success") + def test_renaming_code_to_documentation_still_requires_compilation(self): (self.root / "source.kt").write_text("source") self.git("add", "source.kt") diff --git a/tools/tests/test_vdec_emulator.py b/tools/tests/test_vdec_emulator.py new file mode 100644 index 0000000000..8f9fbd6445 --- /dev/null +++ b/tools/tests/test_vdec_emulator.py @@ -0,0 +1,282 @@ +import array +import mmap +import os +import socket +import struct +import subprocess +import tempfile +import threading +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +VDEC = ROOT / 'tools/linuxfs/preload/vdec.c' +VENC = ROOT / 'tools/linuxfs/preload/venc.c' + +DRIVER = r''' +#define _GNU_SOURCE +#include <dlfcn.h> +#include <errno.h> +#include <fcntl.h> +#include <linux/videodev2.h> +#include <poll.h> +#include <stdarg.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include <sys/ioctl.h> +#include <sys/mman.h> +#include <unistd.h> + +int bl_vdec_open(const char *path, int flags); +int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc); +void bl_vdec_closed(int fd); +void *SDL_LoadObject(const char *name); +void *SDL_LoadFunction(void *handle, const char *name); + +struct heap_alloc { uint64_t len; uint32_t fd, fd_flags; uint64_t heap_flags; }; +struct create_dumb { uint32_t height, width, bpp, flags, handle, pitch; uint64_t size; }; +struct prime_handle { uint32_t handle, flags; int32_t fd; }; +struct destroy_dumb { uint32_t handle; }; +struct drm_device { char **nodes; int available_nodes; }; + +static int heap = -1; + +int open(const char *path, int flags, ...) { + static int (*real)(const char *, int, ...); + va_list ap; + va_start(ap, flags); + int mode = va_arg(ap, int); + va_end(ap); + if (!real) real = dlsym(RTLD_NEXT, "open"); + if (strcmp(path, "/dev/dma_heap/system") == 0) return heap = memfd_create("heap", 0); + return real(path, flags, mode); +} + +int ioctl(int fd, unsigned long req, ...) { + static int (*real)(int, unsigned long, ...); + va_list ap; + va_start(ap, req); + void *arg = va_arg(ap, void *); + va_end(ap); + if (!real) real = dlsym(RTLD_NEXT, "ioctl"); + if (fd == heap && req == _IOWR('H', 0, struct heap_alloc)) { + struct heap_alloc *a = arg; + int buf = memfd_create("dmabuf", 0); + if (ftruncate(buf, (off_t)a->len) != 0) return -1; + a->fd = (uint32_t)buf; + return 0; + } + if (req == _IOW('b', 0, uint64_t)) return 0; + return real(fd, req, arg); +} + +static int vfd; +static int call(unsigned long req, void *arg) { + int rc; + if (!bl_vdec_ioctl(vfd, req, arg, &rc)) return -100; + return rc < 0 ? -errno : 0; +} + +int main(void) { + if (bl_vdec_open("/dev/video0", O_RDWR) != -2) return 2; + void *drm = SDL_LoadObject("libdrm.so.2"); + if (!drm) return 3; + int (*devices)(uint32_t, struct drm_device **, int) = SDL_LoadFunction(drm, "drmGetDevices2"); + int (*drm_ioctl)(int, unsigned long, void *) = SDL_LoadFunction(drm, "drmIoctl"); + if (!devices || !drm_ioctl || !SDL_LoadFunction(drm, "drmModeAtomicCommit")) return 4; + struct drm_device *dev[1]; + if (devices(0, NULL, 0) != 1 || devices(0, dev, 1) != 1 || !(dev[0]->available_nodes & 1)) return 5; + int card = open(dev[0]->nodes[0], O_RDWR | O_CLOEXEC); + if (card < 0) return 6; + + vfd = bl_vdec_open("/dev/video-dec0", O_RDWR); + if (vfd < 0) return 7; + struct v4l2_capability cap; + if (call(VIDIOC_QUERYCAP, &cap) || (cap.capabilities & 0x04004000) != 0x04004000) return 8; + struct v4l2_fmtdesc d = { .index = 1, .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE }; + if (call(VIDIOC_ENUM_FMT, &d) || d.pixelformat != V4L2_PIX_FMT_HEVC) return 9; + struct v4l2_format f = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE }; + f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 720; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_HEVC; + if (call(VIDIOC_S_FMT, &f)) return 10; + struct v4l2_requestbuffers r = { .count = 4, .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, .memory = V4L2_MEMORY_MMAP }; + if (call(VIDIOC_REQBUFS, &r) || r.count != 4) return 11; + unsigned char *in[4]; + for (int i = 0; i < 4; i++) { + struct v4l2_plane p = { 0 }; + struct v4l2_buffer b = { .index = i, .type = r.type, .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p }; + if (call(VIDIOC_QUERYBUF, &b)) return 12; + in[i] = mmap(NULL, p.length, PROT_READ | PROT_WRITE, MAP_SHARED, vfd, p.m.mem_offset); + if (in[i] == MAP_FAILED) return 13; + } + f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE }; + f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12; + if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14; + uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage; + if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15; + r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF }; + if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16; + int out[3]; + for (int i = 0; i < 3; i++) { + struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 }; + if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17; + struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC }; + if (drm_ioctl(card, 0xc00c642d, &h)) return 18; + struct destroy_dumb x = { .handle = c.handle }; + if (drm_ioctl(card, 0xc00464b4, &x)) return 19; + out[i] = h.fd; + } + unsigned types[2] = { V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE }; + if (call(VIDIOC_STREAMON, &types[0]) || call(VIDIOC_STREAMON, &types[1])) return 20; + for (int i = 0; i < 3; i++) { + struct v4l2_plane p = { .m.fd = out[i] }; + struct v4l2_buffer b = { .index = i, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &p }; + if (call(VIDIOC_QBUF, &b)) return 21; + } + struct pollfd pf = { .fd = vfd, .events = 0xc9 }; + if (poll(&pf, 1, 0) != 0) return 22; + for (int frame = 1; frame <= 5; frame++) { + int slot = frame % 4; + memset(in[slot], 'a' + frame, 100 + frame); + struct v4l2_plane p = { .bytesused = 100 + frame }; + struct v4l2_buffer b = { .index = slot, .type = types[0], .memory = V4L2_MEMORY_MMAP, .flags = 0x4008, .length = 1, .m.planes = &p }; + b.timestamp.tv_usec = frame; + if (call(VIDIOC_QBUF, &b)) return 23; + pf = (struct pollfd){ .fd = vfd, .events = 0xc9 }; + if (poll(&pf, 1, 30) != 1 || !(pf.revents & POLLIN)) return 24; + struct v4l2_plane cp = { 0 }; + struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp }; + if (call(VIDIOC_DQBUF, &cb)) return 25; + unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0); + printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size); + munmap(m, size); + pf = (struct pollfd){ .fd = vfd, .events = 0x306 }; + if (poll(&pf, 1, 0) != 1) return 26; + struct v4l2_plane op = { 0 }; + struct v4l2_buffer ob = { .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &op }; + if (call(VIDIOC_DQBUF, &ob) || ob.index != (unsigned)slot) return 27; + struct v4l2_plane rp = { .m.fd = out[cb.index] }; + struct v4l2_buffer rb = { .index = cb.index, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &rp }; + if (call(VIDIOC_QBUF, &rb)) return 28; + } + if (call(VIDIOC_STREAMOFF, &types[1])) return 29; + f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE }; + f.fmt.pix_mp.width = 1920; f.fmt.pix_mp.height = 1088; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12; + if (call(VIDIOC_S_FMT, &f)) return 30; + size = f.fmt.pix_mp.plane_fmt[0].sizeimage; + r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF }; + if (call(VIDIOC_REQBUFS, &r)) return 31; + struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 }; + if (drm_ioctl(card, 0xc02064b2, &big)) return 32; + struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC }; + if (drm_ioctl(card, 0xc00c642d, &bh)) return 33; + if (call(VIDIOC_STREAMON, &types[1])) return 34; + struct v4l2_plane bp = { .m.fd = bh.fd }; + struct v4l2_buffer bb = { .index = 0, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &bp }; + if (call(VIDIOC_QBUF, &bb)) return 35; + memset(in[2], 'z', 50); + struct v4l2_plane zp = { .bytesused = 50 }; + struct v4l2_buffer zb = { .index = 2, .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &zp }; + zb.timestamp.tv_usec = 6; + if (call(VIDIOC_QBUF, &zb)) return 36; + struct v4l2_plane dp = { 0 }; + struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp }; + if (call(VIDIOC_DQBUF, &db)) return 37; + unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0); + printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]); + bl_vdec_closed(vfd); + return 0; +} +''' + +CONFIG = struct.Struct('<IIIIIIII') +CAPTURE = struct.Struct('<III') +PACKET = struct.Struct('<IIII q') +RESULT = struct.Struct('<IiI') + + +class FakeDecoder(threading.Thread): + def __init__(self, path): + super().__init__(daemon=True) + self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) + self.listener.bind(path) + self.listener.listen(1) + self.configs, self.packets = [], [] + + def run(self): + while True: + try: + conn, _ = self.listener.accept() + except OSError: + return + threading.Thread(target=self.serve, args=(conn,), daemon=True).start() + + def serve(self, conn): + bitstream, captures, config = None, {}, None + while True: + fds = array.array('i') + msg, ancdata, _, _ = conn.recvmsg(256, socket.CMSG_LEN(4 * fds.itemsize)) + if not msg: + return + for level, kind, data in ancdata: + if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS: + fds.frombytes(data[:len(data) - len(data) % fds.itemsize]) + kind = struct.unpack_from('<I', msg)[0] + if kind == 6: + config = CONFIG.unpack(msg) + self.configs.append(config) + bitstream = mmap.mmap(fds[0], config[6] * config[7], prot=mmap.PROT_READ) + os.close(fds[0]) + conn.send(RESULT.pack(9, 0, 0)) + elif kind == 7: + _, index, size = CAPTURE.unpack(msg) + captures[index] = mmap.mmap(fds[0], size) + os.close(fds[0]) + elif kind == 8: + _, source, nbytes, target, pts = PACKET.unpack(msg) + self.packets.append((source, nbytes, target, pts)) + first = bitstream[source * config[7]] + frame = captures[target] + frame[0] = first + frame[config[4] * config[5]] = ord('u') + conn.send(RESULT.pack(9, 0, 1)) + + +class VdecEmulatorTest(unittest.TestCase): + def test_remote_play_client_decodes_through_the_app_socket(self): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + driver = tmp / 'driver.c' + driver.write_text(DRIVER) + binary = tmp / 'streaming_client' + subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(driver), str(VDEC), + str(VENC), '-ldl'], check=True) + sock = tmp / 'venc.sock' + server = FakeDecoder(str(sock)) + self.addCleanup(server.listener.close) + server.start() + done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock)), + capture_output=True, text=True, timeout=20) + self.assertEqual(done.returncode, 0, done.stdout + done.stderr) + self.assertEqual(done.stdout.split('\n')[:6], + ['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu']) + self.assertEqual([c[1:6] for c in server.configs], + [(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)]) + self.assertEqual([p[:3] for p in server.packets], + [(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)]) + + def test_other_programs_keep_the_real_libdrm(self): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / 'main.c').write_text( + 'void *SDL_LoadObject(const char *);\n' + 'int main(void) { return SDL_LoadObject("libdrm.so.2") != 0; }\n') + binary = tmp / 'steam' + subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(tmp / 'main.c'), + str(VDEC), str(VENC), '-ldl'], check=True) + done = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20) + self.assertEqual(done.returncode, 0, done.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_xbox_launch.py b/tools/tests/test_xbox_launch.py index 3ed2cf6c10..370c694dfd 100644 --- a/tools/tests/test_xbox_launch.py +++ b/tools/tests/test_xbox_launch.py @@ -136,6 +136,46 @@ class XboxLaunchTest(unittest.TestCase): self.assertNotIn('DROIDDECK_XBOX_COMMAND_FILE', child_env) self.assertEqual(child_env['XODUS_BRIDGE_KEY'], 'runtime-key') + def test_launch_view_runs_from_a_short_drive_letter(self): + with tempfile.TemporaryDirectory() as root: + root = Path(root) + prefix = root / 'compat/pfx' + prefix.mkdir(parents=True) + runtime = root / 'runtime/windows'; runtime.mkdir(parents=True) + for name in xbox['DLLS']: + (runtime / name).write_bytes(b'MZ-synthetic') + view = root / 'files/xbox-runtime/views/launch-4093691424/droiddeck-xbox-1ZpM3D' + (view / 'Bin').mkdir(parents=True) + command = root / 'command.json' + command.write_text(json.dumps(['/selected/proton', 'waitforexitandrun', '/encrypted/Game.exe'])) + env = {'STEAM_COMPAT_DATA_PATH': str(prefix.parent), 'DROIDDECK_XBOX_COMMAND_FILE': str(command)} + seen = [] + def call(argv, **kwargs): + seen.append((argv, os.readlink(prefix / 'dosdevices/x:'))) + return 0 + with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', side_effect=call): + initialize.return_value.returncode = 0 + self.assertEqual(xbox['wine']([str(view / 'Bin/Game.exe')]), 0) + self.assertEqual(seen, [(['/selected/proton', 'waitforexitandrun', 'X:\\Bin\\Game.exe'], str(view))]) + self.assertFalse(os.path.lexists(prefix / 'dosdevices/x:')) + + def test_view_drive_keeps_drives_in_use_and_reuses_a_stale_view(self): + with tempfile.TemporaryDirectory() as root: + root = Path(root) + devices = root / 'pfx/dosdevices'; devices.mkdir(parents=True) + views = root / 'views' + live = views / 'launch-1/droiddeck-xbox-live'; live.mkdir(parents=True) + view = views / 'launch-2/droiddeck-xbox-new'; view.mkdir(parents=True) + (devices / 'x:').symlink_to(live) + (devices / 'w:').symlink_to(root / 'games') + (devices / 'v:').symlink_to(views / 'launch-0/droiddeck-xbox-gone') + exe, link = xbox['view_drive'](root / 'pfx', str(view / 'Game.exe')) + self.assertEqual((exe, link), ('V:\\Game.exe', devices / 'v:')) + self.assertEqual(os.readlink(devices / 'v:'), str(view)) + self.assertEqual(os.readlink(devices / 'x:'), str(live)) + self.assertEqual(sorted(p.name for p in devices.iterdir()), ['v:', 'w:', 'x:']) + self.assertEqual(xbox['view_drive'](root / 'pfx', '/games/Game.exe'), ('/games/Game.exe', None)) + def test_missing_runtime_classes_are_registered_once(self): with tempfile.TemporaryDirectory() as root: prefix = Path(root)