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 76a02242b7..8290b3ef6a 100644 --- a/README.md +++ b/README.md @@ -61,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. 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`. 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. @@ -71,6 +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 6fdfe9c4b9..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') diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a1c126962a..091811b040 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -27,7 +27,10 @@ + + + @@ -56,6 +59,15 @@ + + + + + + + + @@ -125,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"> @@ -135,6 +158,18 @@ + + + + + + + @@ -185,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 0718623cfa..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,7 +284,7 @@ static struct wl_event_source *g_fallback_timer; static int g_fallback_armed; volatile int g_fps_limit; -/* fps limit -1 (Performance mode without a limit): replaced buffers go back to the client at once instead of once per refresh. */ +/* 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; @@ -624,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); @@ -646,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) { @@ -662,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; @@ -724,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; @@ -749,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(); } } } @@ -786,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)); } @@ -796,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) { @@ -830,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++; } } @@ -987,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); @@ -1051,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 = { @@ -1094,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); @@ -1962,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; @@ -2103,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 { @@ -2131,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; @@ -2150,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; @@ -3262,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 e6bb03027c..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); @@ -268,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; diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 18244ae660..157a8eb35d 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,9 +140,14 @@ 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) @@ -168,6 +179,7 @@ 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("") @@ -187,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() @@ -255,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, @@ -391,8 +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 performanceMode by mutableStateOf(false) private var upscaler by mutableStateOf(0) private var upscaleSharpness by mutableStateOf(75) private var hdrReason by mutableStateOf(null) @@ -426,6 +495,21 @@ class FrontEndActivity : ComponentActivity() { 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 { @@ -439,16 +523,15 @@ 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() 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 @@ -463,6 +546,10 @@ 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) @@ -474,6 +561,11 @@ class FrontEndActivity : ComponentActivity() { flood = null floodProgress = 0f com.droiddeck.launcher.ui.LaunchOrigin.flooding = null + if (!busy && !LinuxRuntimeInstaller.isBusy() && + (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 @@ -481,6 +573,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() || 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 @@ -542,7 +700,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 } @@ -654,7 +812,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 } @@ -762,6 +920,7 @@ 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 @@ -775,7 +934,8 @@ 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) @@ -827,6 +987,8 @@ class FrontEndActivity : ComponentActivity() { isHomeApp = homeAppSelected, homeScreenEnabled = homeScreenEnabled, defaultHomeLabel = defaultHomeLabel, + integration = integrationState, + integrationFocus = integrationFocus, androidApps = androidApps, secondScreenDisplays = secondScreenDisplays, packages = packageRows, @@ -844,6 +1006,7 @@ class FrontEndActivity : ComponentActivity() { phantomProcessStatus = phantomProcessStatus, showPhantomGate = showPhantomGate, orientation = orientation, + launcherOrientation = launcherOrientation, launcherFullscreen = launcherFullscreen, downloadSource = downloadSource, downloadMirror = downloadMirror, @@ -1026,6 +1189,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 -> @@ -1061,6 +1228,14 @@ class FrontEndActivity : ComponentActivity() { 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() @@ -1114,7 +1289,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) @@ -1210,12 +1390,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)) } } @@ -1244,6 +1435,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() @@ -1301,24 +1496,15 @@ class FrontEndActivity : ComponentActivity() { } } - override fun onUserInteraction() { - super.onUserInteraction() - com.droiddeck.launcher.ui.Ambient.poke() - } - - override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean { - if (event.actionMasked == android.view.MotionEvent.ACTION_UP || event.actionMasked == android.view.MotionEvent.ACTION_CANCEL) { - com.droiddeck.launcher.ui.Ambient.poke() - } - return super.dispatchTouchEvent(event) - } - - override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean { - com.droiddeck.launcher.ui.Ambient.poke() - return super.dispatchGenericMotionEvent(event) - } - 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) { @@ -1335,16 +1521,28 @@ 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.Ambient.poke() com.droiddeck.launcher.ui.QuitFlood.take()?.let { c -> returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn()) } @@ -1385,10 +1583,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) @@ -1401,6 +1609,7 @@ class FrontEndActivity : ComponentActivity() { else @Suppress("DEPRECATION") state.getParcelable(key) override fun onDestroy() { + cancelCompatLaunch() updates.unregister() super.onDestroy() } @@ -1408,6 +1617,8 @@ 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 @@ -1423,7 +1634,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() { @@ -1605,7 +1831,7 @@ class FrontEndActivity : ComponentActivity() { } private fun openBattleNet(args: List = emptyList()) { - 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 } @@ -1713,7 +1939,7 @@ class FrontEndActivity : ComponentActivity() { ModeSettings( mode = mode, resolution = resolution, panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this), - hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit, performanceMode = performanceMode, + hdr = hdrOn, hdrReason = hdrReason, upscaler = upscaler, upscaleSharpness = upscaleSharpness, gpuDrivers = drivers.summary(), touchMode = touchMode, @@ -1721,8 +1947,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, @@ -1748,11 +1973,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, @@ -1761,26 +1982,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 }, - onPerformanceMode = { on -> SessionPrefs.setPerformanceMode(this, mode, on); performanceMode = on }, onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m }, onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct }, onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t }, @@ -2031,8 +2238,6 @@ class FrontEndActivity : ComponentActivity() { runSteamAtStartup = SessionPrefs.runSteamAtStartup(this) loadBootMovie() hdrOn = SessionPrefs.hdr(this, mode) - fpsLimit = SessionPrefs.fpsLimit(this, mode) - performanceMode = SessionPrefs.performanceMode(this, mode) upscaler = SessionPrefs.upscaler(this) upscaleSharpness = SessionPrefs.upscaleSharpness(this) hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason @@ -2138,7 +2343,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({ @@ -2330,6 +2535,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 1d870a6bcb..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({ @@ -43,6 +53,7 @@ internal class ProtonMenu( }.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 @@ -60,6 +71,7 @@ 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({ @@ -98,6 +110,7 @@ internal class ProtonMenu( !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 diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 5d8ad8e393..b9597649ed 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 @@ -257,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 @@ -318,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) @@ -426,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 @@ -447,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() @@ -491,11 +508,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) { - val prefMode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) - SessionState.fpsLimit = SessionPrefs.fpsLimit(this, prefMode) - SessionState.performanceMode = SessionPrefs.performanceMode(this, prefMode) - } applyOutputPacing() if (!SessionState.running) SessionState.followScreen = followChoice() applyFollowOrientation(resources.configuration) @@ -526,6 +538,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 -> @@ -550,12 +563,18 @@ 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 (routedTouchMode == SessionPrefs.TOUCH_GESTURES && - !gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss + if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat()) onTouchEvent(event) } @@ -580,8 +599,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // game surface and on-screen buttons, in either finger-down order. root.isMotionEventSplittingEnabled = true surfaceView.setOnTouchListener { _, event -> - if (routedTouchMode != SessionPrefs.TOUCH_GESTURES) { - gestureTouchStreamGate.reset() + if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) { false } else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) { false @@ -775,6 +793,8 @@ 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() } @@ -1015,20 +1035,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 -> @@ -1092,7 +1111,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, @@ -1299,7 +1318,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) { @@ -1312,7 +1331,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() } @@ -1633,8 +1653,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { 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) } @@ -1795,9 +1815,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() @@ -1854,7 +1872,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") @@ -1886,15 +1904,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) @@ -1908,11 +1933,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 } @@ -1924,6 +1945,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { cancelTouchGestures() applyFollowOrientation(newConfig) applyUnfoldedControls() + resizeOutputForWindow(surfaceW, surfaceH) } override fun surfaceDestroyed(holder: SurfaceHolder) { @@ -1965,7 +1987,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 { @@ -1983,9 +2006,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun mirrorRefreshLimit(): Int = GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null) - private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit( - GlassesRendering.fpsLimit(SessionState.fpsLimit, mirrorRefreshLimit()), SessionState.performanceMode, - ) + private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit()) private fun applyOutputPacing() { Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit())) @@ -2082,7 +2103,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) @@ -2112,6 +2133,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } private fun releasePads() { + com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this) + backQamInput.cancel() padBridge?.releaseAll() joyConVr?.releaseButtons() } @@ -2145,6 +2168,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 { @@ -2181,8 +2210,28 @@ 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) @@ -2241,7 +2290,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) { @@ -2312,6 +2361,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) } @@ -2685,21 +2735,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { 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 @@ -2709,13 +2755,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() @@ -2960,6 +3012,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { 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 @@ -3151,7 +3208,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() } @@ -3170,6 +3227,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++ @@ -3184,6 +3244,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { started = false updateHandCamera() displayManager.unregisterDisplayListener(displayListener) + contentResolver.unregisterContentObserver(refreshSettingObserver) closeSecondScreen(reset = false) startedScreens = (startedScreens - 1).coerceAtLeast(0) updateGlassesScreen() @@ -3239,6 +3300,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() @@ -3250,7 +3320,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() @@ -3625,15 +3697,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) { @@ -3681,6 +3755,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onDestroy() { + com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) + backQamInput.cancel() steamVrRecovery.close() uiHandler.removeCallbacks(steamTouchRetry) if (runtimeRemovalBlocked) { super.onDestroy(); return } 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/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index 9d62261667..d587ecb7cc 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -261,6 +261,8 @@ object DeviceReport { 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/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/PhantomProcessLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt index 6ad5f89b64..6e67ff495d 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt @@ -60,14 +60,14 @@ object PhantomProcessLimit { if (usesDeviceConfig(sdk)) { val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false) val global = try { - Settings.Global.getString(context.contentResolver, SETTING) + GlobalSettings.read(context, SETTING) } catch (_: Exception) { null } return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY)) } val global = try { - Settings.Global.getString(context.contentResolver, SETTING) + GlobalSettings.read(context, SETTING) } catch (_: Exception) { return PhantomProcessStatus.UNREADABLE } diff --git a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt new file mode 100644 index 0000000000..982b609474 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt @@ -0,0 +1,72 @@ +package com.droiddeck.launcher.core + +import android.accessibilityservice.AccessibilityServiceInfo +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.Settings +import android.view.accessibility.AccessibilityManager +import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.input.HomeButtonService +import com.droiddeck.launcher.session.SessionPrefs + +object SteamIntegration { + const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION" + const val EXTRA_FEATURE = "integration_feature" + enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS } + + data class State( + val wifi: Boolean = false, + val locationPermission: Boolean = false, + val locationOn: Boolean = false, + val locationBlocked: Boolean = false, + val brightness: Boolean = false, + val home: Boolean = false, + val shortcuts: Boolean = false, + val shortcutsRestricted: Boolean = false, + val shortcutsTried: Boolean = false, + val suggested: Boolean = true, + ) + + fun read(context: Context) = State( + wifi = SessionPrefs.wifiDiscoveryEnabled(context), + locationPermission = WifiDiscovery.permissionGranted(context), + locationOn = WifiDiscovery.locationEnabled(context), + brightness = Settings.System.canWrite(context), + home = HomeApp.isDefault(context), + shortcuts = context.getSystemService(AccessibilityManager::class.java) + .getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any { + val service = it.resolveInfo.serviceInfo + ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java) + }, + shortcutsRestricted = restrictedSettings(context), + suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false), + ) + + // Android 13+ blocks accessibility services for sideloaded APKs until the user allows restricted settings in App info. + // MODE_DEFAULT is inconclusive on Android 15, so only an explicit denial counts here. + private fun restrictedSettings(context: Context): Boolean { + if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false + val mode = runCatching { + context.getSystemService(android.app.AppOpsManager::class.java) + .unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName) + }.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED) + return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED + } + + fun dismissSuggestion(context: Context) { + SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply() + } + + fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, + Uri.parse("package:${context.packageName}")) + + // ACCESSIBILITY_DETAILS_SETTINGS is restricted to system apps; the fragment args key highlights our entry in the list. + fun shortcutSettings(context: Context): Intent { + val service = ComponentName(context, HomeButtonService::class.java).flattenToString() + return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS) + .putExtra(":settings:fragment_args_key", service) + .putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) }) + } +} 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 8d60241c89..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 @@ -318,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)) } }, @@ -509,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)) } }, ) } @@ -532,6 +538,7 @@ fun FileManagerScreen( onValueChange = { newName = it }, label = { Text(stringResource(R.string.fm_new_name)) }, singleLine = true, + modifier = Modifier.focusGlide(), ) }, confirmButton = { @@ -539,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)) } }, ) } @@ -563,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)) } }, ) } @@ -611,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)) } }, ) } @@ -636,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) } @@ -648,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()) } } @@ -656,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( @@ -681,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)) @@ -693,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.UP) }, 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) } @@ -744,6 +754,7 @@ fun FileManagerScreen( ).show() } }, + modifier = Modifier.focusGlide(), ) } linuxRoot?.let { root -> @@ -754,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(), ) } } @@ -769,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 }, @@ -781,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)) @@ -798,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)) @@ -808,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 }) { @@ -836,6 +848,7 @@ fun FileManagerScreen( showSortMenu = false loadDirectory(currentDir, resetScroll = false) }, + modifier = Modifier.focusGlide(), ) } HorizontalDivider(color = MaterialTheme.colorScheme.outline) @@ -846,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)) }, @@ -855,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 { @@ -868,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) } } @@ -880,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(), ) } @@ -918,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 } @@ -935,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( @@ -946,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( @@ -957,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( @@ -964,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) } } } @@ -990,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) } } @@ -1021,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)) 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/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/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/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 index e4ad4f655d..68d5722d0a 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt @@ -4,7 +4,7 @@ import android.view.MotionEvent /** Keeps split Android touch targets from restarting one shared gesture recognizer. */ internal class GestureTouchStreamGate { - enum class Source { SURFACE, SCREEN_KEYS } + enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS } private var owner: Source? = 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 0811cab05e..7dd234daf1 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -53,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; @@ -61,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; @@ -129,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; @@ -150,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++) { @@ -165,6 +181,7 @@ public final class PadBridge { } systemGuidePressed = false; systemQamPressed = false; + backQamPressed = false; qamChordActive = false; chordButtonPressed = false; qamTapPressed = false; @@ -215,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 @@ -273,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; @@ -307,7 +333,8 @@ 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(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed); break; @@ -323,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(); @@ -352,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; @@ -382,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(); @@ -458,7 +489,11 @@ public final class PadBridge { } public synchronized void releaseAll() { + homeGuidePressed = false; + homeGuideSlot = -1; + clearBackQamWrites(); routedTouch.clear(); + backQamPressed = false; releaseBackPaddles(); state.clear(); publish(); @@ -479,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()) { @@ -557,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; } @@ -592,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; @@ -618,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(); @@ -674,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() { @@ -683,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/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/ScreenKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt index 4cc87ef0b8..c7a9291e9e 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt @@ -926,35 +926,7 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit) } private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) { - val indices = (0 until event.pointerCount).filter { index -> - pointerIdBits and (1 shl event.getPointerId(index)) != 0 - } - if (indices.isEmpty()) return - val actionIndex = indices.indexOf(event.actionIndex) - val action = when (event.actionMasked) { - MotionEvent.ACTION_DOWN -> if (actionIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE - MotionEvent.ACTION_POINTER_DOWN -> if (actionIndex >= 0) { - if (indices.size == 1) MotionEvent.ACTION_DOWN - else MotionEvent.ACTION_POINTER_DOWN or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) - } else MotionEvent.ACTION_MOVE - MotionEvent.ACTION_UP -> if (actionIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE - MotionEvent.ACTION_POINTER_UP -> if (actionIndex >= 0) { - if (indices.size == 1) MotionEvent.ACTION_UP - else MotionEvent.ACTION_POINTER_UP or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) - } else MotionEvent.ACTION_MOVE - else -> event.action - } - val properties = Array(indices.size) { MotionEvent.PointerProperties() } - val coordinates = Array(indices.size) { MotionEvent.PointerCoords() } - indices.forEachIndexed { target, source -> - event.getPointerProperties(source, properties[target]) - event.getPointerCoords(source, coordinates[target]) - } - val split = MotionEvent.obtain( - event.downTime, event.eventTime, action, indices.size, properties, coordinates, - event.metaState, event.buttonState, event.xPrecision, event.yPrecision, - event.deviceId, event.edgeFlags, event.source, event.flags, - ) + val split = event.pointerSubset(pointerIdBits) ?: return try { onTouchMiss?.invoke(split) } finally { 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 ca5157372a..2138f9c92b 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt @@ -103,6 +103,8 @@ class SteamTouchControls( 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() @@ -629,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) @@ -637,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) @@ -655,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() } @@ -673,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 index 5cd766a7b8..e3a64e9628 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt @@ -17,45 +17,45 @@ object BattleNet { 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) + 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"), - Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades"), - Title("wow_classic_era", "World of Warcraft Classic", "WoWC"), - Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC"), - Title("diablo3", "Diablo III", "D3", shop = "diablo-iii"), + 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"), - Title("s1", "StarCraft", "S1", shop = "starcraft-remastered"), - Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone"), - Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm"), - Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch"), - Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged"), - Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4"), - Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare"), - Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered"), - Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war"), - Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard"), - Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii"), - Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii"), - Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4"), - Title("osi", "Diablo II: Resurrected", "OSI"), - Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection"), - Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal"), - Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"), - Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"), - Title("d1", "Diablo", "D1", shop = "diablo"), - Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans"), - Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition"), - Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered"), - Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered"), - Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble"), - Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages"), - Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves"), - Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2"), - Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710), - Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed"), + 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" } @@ -104,7 +104,7 @@ object BattleNet { private val NOT_GAMES = setOf("agent", "bna", "battle.net") - class Game(val uid: String, val name: String, val code: String, val folder: File) { + 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) } @@ -161,8 +161,10 @@ object BattleNet { fun games(context: Context): List<Game> { val pfx = File(prefix(context), "pfx") - val entries = runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()) + - runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrDefault(emptyList()) + 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) @@ -172,11 +174,17 @@ object BattleNet { } 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) + 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('/') @@ -242,9 +250,9 @@ object BattleNet { return out.toString() } - internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>> { - val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrDefault(emptyList()).filter { it.first == 1 } - return installs.mapNotNull { (_, start, end) -> + 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) } @@ -253,8 +261,8 @@ object BattleNet { 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 - }.getOrNull() - } + }.getOrElse { return null } + }.filterNotNull() } private fun fields(bytes: ByteArray, from: Int, to: Int): List<Triple<Int, Int, Int>> = walk(bytes, from, to) { _, _ -> } @@ -352,6 +360,8 @@ object BattleNet { 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 } 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/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 cd8c6c44d4..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) { 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/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt index f10ab12448..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) { 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/NoSteamLaunch.kt b/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt index b8dab5de11..8d8070f875 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt @@ -51,7 +51,8 @@ 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) { 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/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 39ed2c43e9..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> { 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 0e10fca293..d9c59b1b88 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -81,6 +81,7 @@ object SessionFiles { "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", 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 ec502a279f..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>) { @@ -223,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) @@ -241,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" @@ -527,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 @@ -569,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) @@ -654,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}" } @@ -903,32 +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).coerceAtLeast(0) - - 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 } - - /** - * Performance mode: without a frame limit, buffers go back to the game as soon as they are replaced - * instead of once per refresh, and gamescope's WSI layer and winex11 reuse their per-present window checks. - */ - fun performanceMode(context: Context, mode: String): Boolean = prefs(context).getBoolean("performanceMode.$mode", false) - - fun setPerformanceMode(context: Context, mode: String, on: Boolean) { - prefs(context).edit().putBoolean("performanceMode.$mode", on).apply() - } - /** Compositor frame limit that releases buffers to the game unpaced. */ const val FPS_UNPACED = -1 - /** The limit handed to the compositor: Performance mode without a limit is unpaced, a chosen limit still paces. */ - fun compositorFpsLimit(limit: Int, performanceMode: Boolean): Int = if (performanceMode && limit <= 0) FPS_UNPACED else limit + /** + * 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", @@ -1117,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 1df7ea31b7..24e9ef553b 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 @@ -430,8 +431,30 @@ 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()) @@ -446,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)) @@ -453,6 +480,9 @@ 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) } @@ -462,7 +492,7 @@ class SessionService : Service() { 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) @@ -472,23 +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; 0 checks on every present. - val windowCheckMs = if (SessionState.performanceMode) 100 else 0 - guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=$windowCheckMs") - guest.add("WINE_OFFSCREEN_CHECK_MS=$windowCheckMs") - if (SessionPrefs.compositorFpsLimit(SessionState.fpsLimit, SessionState.performanceMode) == SessionPrefs.FPS_UNPACED) { - // gamescope turns buffers around slower than an unpaced game draws; more images keep it drawing. - guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8") - guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1") - } - Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off") + ", frame limit " + 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) @@ -602,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() @@ -749,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")) } @@ -782,8 +814,9 @@ class SessionService : Service() { private fun noSteamGame(): Boolean = 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 @@ -852,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) { @@ -1525,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() 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 5db2211a13..52544f2fc0 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -103,12 +103,6 @@ object SessionState { @Volatile var upscaleRatio: Float = 0f - @Volatile - var fpsLimit: Int = 0 - - @Volatile - var performanceMode = false - @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 c933229a88..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,7 +14,7 @@ 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", 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/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index e15f19dd48..3edac79a4b 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -130,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], ) @@ -191,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) @@ -236,7 +237,7 @@ object StoresState { fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) { val app = context.applicationContext val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app) - if (item.store == Store.BATTLENET) { + if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) { backends[item.store]?.install(app, item, targetRoot) return } @@ -273,7 +274,7 @@ 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) { + 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 } 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 index 945c75c7a6..737ba3b4ff 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetStore.kt @@ -189,9 +189,15 @@ object BattleNetBackend : StoreBackend { 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) = BattleNetClient.installGame(context, item.id, root) + 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) = BattleNetClient.open(emptyList()) + 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() 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 496691feec..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,6 +19,11 @@ 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" + keyQuery(downloadKeyId), key)?.optJSONArray("uploads") 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/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/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 a3c685b756..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 @@ -120,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, @@ -138,6 +141,7 @@ 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 = "", @@ -219,6 +223,7 @@ 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 = {}, @@ -234,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 = {}, @@ -245,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(), @@ -265,12 +277,6 @@ internal object Motion { if (scale == 0f) snap() else spring(damping, stiffness) } -internal object Ambient { - var poked by mutableStateOf(0L) - private set - fun poke() { poked = android.os.SystemClock.uptimeMillis() } -} - private val Shape10 = RoundedCornerShape(10.dp) internal val Shape12 = RoundedCornerShape(12.dp) @@ -392,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) @@ -406,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() @@ -415,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 @@ -423,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 @@ -467,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) @@ -492,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 } @@ -533,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 @@ -550,25 +601,39 @@ 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) @@ -595,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, @@ -624,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 1bf99f0697..7540949132 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -91,6 +91,7 @@ private const val LAUNCHER_TAB = 2 internal object SetupTabs { var openLauncher = false + var openOverview = false } private const val GLASSES_TAB = 5 @@ -140,6 +141,7 @@ internal fun SetupPanel( a: FrontEndActions, onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, + onPairWirelessDebugging: () -> Unit, ) { val host = rememberMenuHost() val ctx = LocalContext.current @@ -191,6 +193,7 @@ internal fun SetupPanel( 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 } @@ -201,6 +204,12 @@ 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 { } @@ -277,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 } } @@ -290,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) } } } @@ -341,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 @@ -398,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, ) @@ -501,7 +512,7 @@ internal fun SetupPanel( ) if (!s.adbPaired) ActionRow( stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint), - stringResource(R.string.setup_adb_pair_button), { onRequestWirelessAdb(false) }, + stringResource(R.string.setup_adb_pair_button), onPairWirelessDebugging, ) } } 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 7c9cdc74c2..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,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.boundsInRoot import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalConfiguration @@ -86,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 @@ -217,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 -> @@ -267,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) @@ -319,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, ) { @@ -328,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( @@ -366,7 +365,19 @@ private fun GameActions( } SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) } } - if (store == Store.BATTLENET) SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() } + 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) @@ -381,6 +392,19 @@ 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) @@ -408,6 +432,10 @@ private fun GameActions( 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) } } @@ -525,7 +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) return + 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] 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/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 773f44ce7f..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 } @@ -246,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 } @@ -254,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 }) { @@ -265,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 @@ -308,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" @@ -361,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) } } @@ -379,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) @@ -399,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( @@ -414,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) @@ -428,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) { @@ -506,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)) + } } } @@ -571,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() } @@ -588,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++ @@ -599,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 } @@ -612,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() @@ -641,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 @@ -651,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/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index fae0f318d2..c428b8b97d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -641,7 +641,11 @@ internal fun LiftHero( } @Composable -private fun handleBob(): Float { +internal fun Handle(height: Dp, above: Boolean = false) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val shape = if (above) RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp) else RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp) + val still = Motion.scale == 0f val bob = androidx.compose.animation.core.rememberInfiniteTransition(label = "handle") val lift by bob.animateFloat( 0f, 0f, @@ -656,16 +660,6 @@ private fun handleBob(): Float { ), label = "handleBob", ) - return lift -} - -@Composable -internal fun Handle(height: Dp, above: Boolean = false) { - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - val shape = if (above) RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp) else RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp) - val still = Motion.scale == 0f || !ambientAwake() - val lift = if (still) 0f else handleBob() Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.height(height).clip(shape).background(colors.surface) 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 393971446e..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,8 +60,6 @@ class ModeSettings( val hdr: Boolean, val hdrReason: String?, val gpuDrivers: String? = null, - val fpsLimit: Int = 0, - val performanceMode: Boolean = false, val upscaler: Int = 0, val upscaleSharpness: Int = 75, val touchMode: String, @@ -96,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, @@ -116,8 +111,6 @@ class ModeSettingsActions( val onResolution: (String) -> Unit, val onHdr: (Boolean) -> Unit, val onGpuDrivers: () -> Unit = {}, - val onFpsLimit: (Int) -> Unit = {}, - val onPerformanceMode: (Boolean) -> Unit = {}, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, val onTouch: (String) -> Unit, @@ -149,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 = {}, @@ -160,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]) } @@ -175,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() } @@ -209,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), @@ -242,12 +242,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: format = { "$it%" }, onChange = a.onUpscaleSharpness, ) } - SettingsGroup(stringResource(R.string.display_frame_rate)) { - ToggleRow(host, "performance", stringResource(R.string.mode_performance), stringResource(R.string.mode_performance_hint), - s.performanceMode, onChange = a.onPerformanceMode) - 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), @@ -309,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) { @@ -505,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 @@ -582,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)) } }, ) } @@ -624,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 = { @@ -632,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)) } } }, ) @@ -651,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 = { @@ -667,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( @@ -683,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(), ) } } @@ -692,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/PerformanceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt index 9c1424dd4f..2c0927bc88 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt @@ -212,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 index 3cb99d6051..94e1a5ff27 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyEditor.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyEditor.kt @@ -166,7 +166,7 @@ fun ScreenKeyEditor( keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), modifier = Modifier.fillMaxWidth().onFocusChanged { if (it.isFocused) onTextFocus() else onTextBlur() - }, + }.focusGlide(), ) if (text.isEmpty()) { Text( @@ -177,26 +177,26 @@ fun ScreenKeyEditor( } } if (button) { - IconButton(onClick = onBind, modifier = Modifier.width(38.dp)) { + 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)) { + 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)) { + 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)) { + 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)) { + IconButton(onClick = onDismiss, modifier = Modifier.width(34.dp).focusGlide(CircleShape)) { Icon(Icons.Default.Close, null, tint = p.onBackground) } } @@ -232,7 +232,7 @@ fun ScreenKeyEditor( 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)) + Switch(checked = toggle, onCheckedChange = onToggle, modifier = Modifier.height(30.dp).focusGlide()) } if (directions.isNotEmpty()) { Row( @@ -251,7 +251,7 @@ fun ScreenKeyEditor( 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)) + Switch(checked = labels, onCheckedChange = onLabels, modifier = Modifier.height(30.dp).focusGlide()) } } Row( @@ -294,7 +294,7 @@ private fun KeySlider( ) { Row(modifier, verticalAlignment = Alignment.CenterVertically) { Text(label, style = MaterialTheme.typography.bodySmall, maxLines = 1) - Slider(current, onChange, Modifier.weight(1f).height(28.dp), valueRange = min..max) + 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, @@ -317,7 +317,7 @@ private fun Chip( if (selected) p.primary.copy(alpha = 0.18f) else p.line2.copy(alpha = 0.28f), CircleShape, ) - .clickable(enabled = enabled, onClick = onClick) + .focusGlide(RoundedCornerShape(8.dp)).clickable(enabled = enabled, onClick = onClick) .padding(vertical = 6.dp), contentAlignment = Alignment.Center, ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyPicker.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyPicker.kt index 787854d080..e70249eef2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyPicker.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenKeyPicker.kt @@ -1,5 +1,6 @@ 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 @@ -41,7 +42,7 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import androidx.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.PC_KEYS @@ -86,7 +87,7 @@ fun ScreenKeyPicker( 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) { Icon(Icons.Default.Close, null) } + 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), @@ -136,7 +137,7 @@ fun ScreenKeyPicker( Button( onClick = { onAdd(picked) }, enabled = picked.isNotEmpty(), - modifier = Modifier.weight(1f), + modifier = Modifier.weight(1f).focusGlide(CircleShape), ) { Text(stringResource(R.string.screen_keys_add)) } @@ -155,7 +156,7 @@ private fun KeyCell(key: PcKey, selected: Boolean, modifier: Modifier, onClick: 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).clickable(onClick = onClick), + modifier = modifier.height(36.dp).focusGlide(RoundedCornerShape(8.dp)).clickable(onClick = onClick), ) { Box(Modifier.fillMaxSize().padding(horizontal = 2.dp), contentAlignment = Alignment.Center) { Text( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScreenLayoutPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScreenLayoutPanel.kt index 7e195d5e8c..7bc78f7105 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ScreenLayoutPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenLayoutPanel.kt @@ -1,5 +1,6 @@ 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 @@ -40,7 +41,7 @@ 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 androidx.compose.ui.window.Dialog +import com.droiddeck.launcher.ui.GlideDialog as Dialog import androidx.compose.ui.window.DialogProperties import com.droiddeck.launcher.R @@ -83,14 +84,14 @@ fun ScreenLayoutPanel( stringResource(R.string.screen_key_layout), Modifier.weight(1f), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, ) - IconButton(onClick = onDismiss) { Icon(Icons.Default.Close, null) } + 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 }) { Text(stringResource(R.string.screen_key_layout_save)) } - TextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "*/*")) }) { + 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") }) { + TextButton(onClick = { exporter.launch("droiddeck-layout.icp") }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.screen_key_layout_export)) } } @@ -101,7 +102,7 @@ fun ScreenLayoutPanel( layout, Modifier.weight(1f).clickable { onLoad(layout) }.padding(vertical = 14.dp), style = MaterialTheme.typography.bodyLarge, ) - TextButton(onClick = { onDelete(layout) }) { + TextButton(onClick = { onDelete(layout) }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete), color = p.error) } } @@ -121,12 +122,12 @@ fun ScreenLayoutPanel( ) { Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { OutlinedTextField( - name, { name = it.take(24) }, Modifier.fillMaxWidth(), singleLine = true, + 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 }) { Text(stringResource(R.string.common_cancel)) } - Button(onClick = { onSave(name.trim()); naming = false }, enabled = name.isNotBlank()) { + 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 cdde71b587..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 @@ -222,7 +223,7 @@ fun LoadingOverlay( .background(colors.background) .blockTouches(), ) { - CapsuleWall(games, driftMs = 65_000, modifier = Modifier.alpha(0.3f), pauseWhenIdle = false) + CapsuleWall(games, driftMs = 65_000, modifier = Modifier.alpha(0.3f)) Box( Modifier.fillMaxSize().drawBehind { drawRect( @@ -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 9f8ceb2708..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 @@ -213,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, @@ -256,10 +260,8 @@ 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, @@ -407,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)), @@ -422,14 +425,18 @@ 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.pipSupported) SteamActionPill( stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"), @@ -470,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)) } @@ -486,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)) { @@ -557,11 +564,13 @@ 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) { + SettingsRow(stringResource(R.string.screen_keys), null, stacked = narrow) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), @@ -602,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) @@ -612,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)) { @@ -807,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) } } @@ -901,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") @@ -918,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)) @@ -938,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() } } @@ -1387,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), @@ -1662,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 888d87e232..4a93056dda 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -5,6 +5,12 @@ import androidx.compose.foundation.layout.fillMaxWidth import com.droiddeck.launcher.R import androidx.compose.ui.res.stringResource import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.runtime.State +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.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -70,38 +76,6 @@ private const val WALL_MIN_GAMES = 4 private const val WALL_DISTINCT = 40 private const val DRIFT_STEP_NS = 15_000_000L -private const val AMBIENT_IDLE_NS = 20_000_000_000L - -@Composable -internal fun ambientAwake(): Boolean { - val poked = Ambient.poked - var awake by remember { mutableStateOf(true) } - LaunchedEffect(poked) { - awake = true - kotlinx.coroutines.delay(AMBIENT_IDLE_NS / 1_000_000) - awake = false - } - return awake -} - -@Composable -internal fun AmbientFrames(pauseWhenIdle: Boolean = true, step: (Long) -> Unit) { - val onStep = androidx.compose.runtime.rememberUpdatedState(step) - val poked = if (pauseWhenIdle) Ambient.poked else 0L - if (Motion.scale != 0f) LaunchedEffect(poked, pauseWhenIdle) { - var shown = 0L - var end = Long.MAX_VALUE - while (shown < end) withFrameNanos { now -> - if (shown == 0L) { - shown = now - if (pauseWhenIdle) end = now + AMBIENT_IDLE_NS - } else if (now - shown >= DRIFT_STEP_NS) { - onStep.value(now - shown) - shown = now - } - } - } -} @Composable internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) { @@ -154,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( @@ -167,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 -> @@ -205,7 +189,6 @@ internal fun CapsuleWall( modifier: Modifier = Modifier, owned: List<Pair<Int, java.io.File>> = emptyList(), featured: List<com.droiddeck.launcher.frontend.SteamFeatured.Game> = emptyList(), - pauseWhenIdle: Boolean = true, ) { val pal = LocalPalette.current val blank = remember(pal) { WallCapsule(Brush.linearGradient(listOf(pal.surface, pal.background)), edge = pal.line) } @@ -215,7 +198,7 @@ internal fun CapsuleWall( val store = if (owned.isEmpty()) featured.filter { shown.add(it.appId) }.map { it.name to it.art } else emptyList() (library + store).take((WALL_DISTINCT - games.size).coerceAtLeast(0)) } - TiltedWall(games.size + padding.size, driftMs, modifier, pauseWhenIdle = pauseWhenIdle) { i -> + TiltedWall(games.size + padding.size, driftMs, modifier) { i -> when { i < games.size -> WallCapsule(artBrush(hueOf(games[i].name)), games[i].art) i - games.size < padding.size -> padding[i - games.size].let { (seed, art) -> WallCapsule(artBrush(hueOf(seed)), art) } @@ -235,13 +218,20 @@ internal fun TiltedWall( capH: androidx.compose.ui.unit.Dp = 168.dp, gap: androidx.compose.ui.unit.Dp = 14.dp, corner: androidx.compose.ui.unit.Dp = 10.dp, - pauseWhenIdle: Boolean = true, capsule: (index: Int) -> WallCapsule, ) { val still = Motion.scale == 0f val drift = remember { mutableFloatStateOf(0f) } - AmbientFrames(pauseWhenIdle) { dt -> - drift.floatValue = ((drift.floatValue + dt / (driftMs * 1_000_000.0 * Motion.scale)) % 1.0).toFloat() + val period = androidx.compose.runtime.rememberUpdatedState(driftMs) + if (!still) LaunchedEffect(Unit) { + var shown = 0L + while (true) withFrameNanos { now -> + if (shown == 0L) shown = now + else if (now - shown >= DRIFT_STEP_NS) { + drift.floatValue = ((drift.floatValue + (now - shown) / (period.value * 1_000_000.0 * Motion.scale)) % 1.0).toFloat() + shown = now + } + } } val density = LocalDensity.current BoxWithConstraints(modifier.fillMaxSize()) { @@ -327,9 +317,10 @@ private fun DrawScope.drawCapsule(look: WallCapsule, art: Painter?, radius: Floa private fun CapsuleFan(games: List<Library.SteamGame>) { val pal = LocalPalette.current val density = LocalDensity.current - val clock = remember { androidx.compose.runtime.mutableLongStateOf(0L) } - AmbientFrames { clock.longValue += it } - val floatMs = listOf(9_000, 11_000, 13_000) + val transition = rememberInfiniteTransition(label = "fan") + val floats = listOf(9_000, 11_000, 13_000).map { ms -> + transition.animateFloat(0f, 1f, infiniteRepeatable(tween(ms, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "float") + } val still = Motion.scale == 0f val slots = listOf( FanSlot(0.54f, 0.14f, 0.62f, -9f), @@ -350,7 +341,7 @@ private fun CapsuleFan(games: List<Library.SteamGame>) { for (i in games.indices.reversed()) { val slot = slots[i] val h = maxHeight * slot.height - val ms = floatMs[i] + val v: State<Float> = floats[i] val look = WallCapsule(artBrush(hueOf(games[i].name)), games[i].art) val art = look.art?.let { rememberCapsuleArt(it, with(density) { Size((h * 2f / 3f).toPx(), h.toPx()) }, radius) } Spacer( @@ -358,10 +349,7 @@ private fun CapsuleFan(games: List<Library.SteamGame>) { .offset(x = maxWidth * slot.x, y = maxHeight * slot.y) .size(h * 2f / 3f, h) .graphicsLayer { - val t = if (still) 0f else { - val phase = (clock.longValue / (ms * 1_000_000.0 * Motion.scale)) % 2.0 - FastOutSlowInEasing.transform((if (phase < 1.0) phase else 2.0 - phase).toFloat()) - } + val t = if (still) 0f else v.value rotationZ = slot.lean + 2f * t translationY = -12.dp.toPx() * t shadowElevation = 24.dp.toPx() 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 e820ed8eed..badd3f1f4d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt @@ -47,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 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/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/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 23a996fb9d..92b118d54b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -150,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 { @@ -340,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) @@ -861,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() @@ -872,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 @@ -879,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 @@ -933,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() } @@ -941,7 +918,7 @@ private fun Storefront( Shelf(stringResource(R.string.stores_shelf_new), shelf(shelves?.whatsNew), card) Shelf(stringResource(R.string.stores_shelf_deals), shelf(shelves?.deals), card) Shelf(stringResource(R.string.stores_shelf_free), shelf(shelves?.free), card) - Shelf(stringResource(if (store == Store.BATTLENET) R.string.bnet_store else R.string.stores_shelf_trending), shelf(shelves?.trending), card) + Shelf(stringResource(R.string.stores_shelf_trending), shelf(shelves?.trending), card) if (shelves == null) Rise(4) { Box(Modifier.padding(top = 8.dp)) { Note(stringResource(R.string.stores_shelves_loading)) } } else if (shelves.isEmpty && store == Store.AMAZON) Rise(4) { Box(Modifier.padding(top = 8.dp)) { Note(stringResource(R.string.stores_amazon_no_catalog)) } } } @@ -976,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) } @@ -1094,36 +1071,61 @@ internal fun ModeHeader( if (query.isNotEmpty()) onQuery("") } BackHandler(enabled = searching && !clearSearchFocus) { close() } - 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 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) - } - } else SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } + 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) @@ -1421,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 a02eb8d365..352b29a544 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt @@ -170,7 +170,7 @@ fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCA LocalConfiguration provides configuration, ) { MaterialTheme(colorScheme = scheme, typography = ContentDirected) { - ProvideTextStyle(TextStyle(textDirection = TextDirection.Content), content) + FocusGlideHost { ProvideTextStyle(TextStyle(textDirection = TextDirection.Content), content) } } } } 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 c11d5874dc..dd73939a7d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt @@ -43,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 @@ -115,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)) @@ -139,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/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 fa1c13e5e5..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> @@ -2027,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> @@ -2081,6 +2078,13 @@ <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> @@ -3214,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 acbf053f10..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> @@ -1996,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> @@ -2049,6 +2046,13 @@ <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> @@ -3064,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 137b761f8b..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> @@ -1943,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> @@ -1997,6 +1994,13 @@ <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> @@ -3078,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 d12e8ff408..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> @@ -1985,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> @@ -2039,6 +2036,13 @@ <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> @@ -3146,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 caf758e572..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> @@ -1943,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> @@ -1997,6 +1994,13 @@ <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> @@ -3078,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 fbdf383abb..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> @@ -1935,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> @@ -1989,6 +1986,13 @@ <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> @@ -3078,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 7e21ae76cd..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> @@ -1943,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> @@ -1997,6 +1994,13 @@ <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> @@ -3078,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 1e3859f582..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> @@ -1966,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> @@ -2020,6 +2017,13 @@ <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> @@ -3114,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 30f3341610..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> @@ -1943,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> @@ -1997,6 +1994,13 @@ <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> @@ -3078,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 76bf5abc2c..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> @@ -1966,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> @@ -2020,6 +2017,13 @@ <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> @@ -3114,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 68cb4c185a..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> @@ -1943,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> @@ -1997,6 +1994,13 @@ <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> @@ -3078,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 a7e0ca9754..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> @@ -1943,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> @@ -1997,6 +1994,13 @@ <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> @@ -3078,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 d5fc612c3f..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> @@ -1922,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> @@ -1976,6 +1973,13 @@ <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> @@ -3068,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 d070b01e32..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> @@ -1956,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> @@ -2010,6 +2007,13 @@ <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> @@ -3112,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 9bb40dcd11..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> @@ -1924,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> @@ -1978,6 +1975,13 @@ <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> @@ -3055,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 b76da8d131..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> @@ -1924,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> @@ -1978,6 +1975,13 @@ <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> @@ -3055,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 e036753b5d..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> @@ -1922,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> @@ -1976,6 +1973,13 @@ <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> @@ -3053,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 a9f9489c15..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> @@ -1943,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> @@ -1997,6 +1994,13 @@ <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> @@ -3078,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 d74633be94..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> @@ -1943,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> @@ -1997,6 +1994,13 @@ <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> @@ -3078,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 121d781649..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> @@ -1985,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> @@ -2039,6 +2036,13 @@ <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> @@ -3149,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 61fe3b5ff4..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> @@ -1956,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> @@ -2010,6 +2007,13 @@ <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> @@ -3112,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 c9e1e7b1b7..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> @@ -1956,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> @@ -2010,6 +2007,13 @@ <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> @@ -3112,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 b8e3b4954c..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> @@ -1964,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> @@ -2018,6 +2015,13 @@ <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> @@ -3112,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 59e74118e7..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> @@ -1987,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> @@ -2041,6 +2038,13 @@ <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> @@ -3148,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 2c62e8b139..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> @@ -1943,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> @@ -1997,6 +1994,13 @@ <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> @@ -3078,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 38337b0fda..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> @@ -1922,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> @@ -1976,6 +1973,13 @@ <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> @@ -3053,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 c1bbb9d33d..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> @@ -1937,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> @@ -1991,6 +1988,13 @@ <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> @@ -3080,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 2cadb53c52..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> @@ -1985,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> @@ -2039,6 +2036,13 @@ <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> @@ -3146,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 b8a7da87a9..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> @@ -1922,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> @@ -1976,6 +1973,13 @@ <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> @@ -3053,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 2726014a0b..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> @@ -2002,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> @@ -2056,6 +2053,13 @@ <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> @@ -3057,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 cdcc40b76a..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> @@ -1925,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> @@ -1979,6 +1976,13 @@ <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> @@ -3056,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 43fb5e4434..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> @@ -1925,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> @@ -1979,6 +1976,13 @@ <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> @@ -3056,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 416e25e4e2..8979e00b69 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -94,7 +94,7 @@ <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> @@ -184,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> @@ -256,10 +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_performance">Performance mode</string> - <string name="mode_performance_hint">With no frame limit, games run as fast as they can: frames go back to the game without waiting for the screen. With a frame limit, frames stay paced to it. Either way, gamescope and Wine skip repeated window checks. Uses more power and runs warmer without a limit. Applies next session.</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> @@ -306,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> @@ -702,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> @@ -827,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> @@ -980,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> @@ -1065,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> @@ -1244,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> @@ -1275,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> @@ -1835,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> @@ -2038,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> @@ -2092,6 +2154,13 @@ <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> @@ -3181,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> @@ -3200,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/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 5f3dddf96c..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 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/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/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/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/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 index d23a2eac23..a2c5e483bb 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -212,8 +212,26 @@ class BattleNetTest { ) 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)) - assertEquals(emptyList<Pair<String, String>>(), BattleNet.productDbEntries(db.copyOf(db.size - 3))) - assertEquals(emptyList<Pair<String, String>>(), BattleNet.productDbEntries(byteArrayOf(0x0a, 0x7f, 0x01))) + 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() { @@ -229,9 +247,11 @@ class BattleNetTest { File(pfx, "drive_c/$folder").mkdirs() } val games = BattleNet.games(context) - assertEquals(listOf("Fen", "OSI", "WTCG", "WoWC"), games.map { it.code }) - assertEquals(listOf("Diablo IV", "Diablo II: Resurrected", "Hearthstone", "World of Warcraft Classic"), games.map { it.name }) - assertEquals(File(pfx, "drive_c/Games/Diablo II Resurrected"), games[1].folder) + 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")) 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/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/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/PerformanceModeTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PerformanceModeTest.kt deleted file mode 100644 index f59157c3be..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/session/PerformanceModeTest.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.Context -import org.junit.Assert.* -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment -import org.robolectric.annotation.Config - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [33]) -class PerformanceModeTest { - private val app get() = RuntimeEnvironment.getApplication() - private val session get() = app.getSharedPreferences("session", Context.MODE_PRIVATE) - - @Before fun clear() { session.edit().clear().commit() } - - @Test fun offByDefaultAndPerMode() { - assertFalse(SessionPrefs.performanceMode(app, SessionService.MODE_STEAM)) - SessionPrefs.setPerformanceMode(app, SessionService.MODE_STEAM, true) - assertTrue(SessionPrefs.performanceMode(app, SessionService.MODE_STEAM)) - assertFalse(SessionPrefs.performanceMode(app, SessionService.MODE_DESKTOP)) - } - - @Test fun offKeepsTodaysPacing() { - assertEquals(0, SessionPrefs.compositorFpsLimit(0, false)) - assertEquals(60, SessionPrefs.compositorFpsLimit(60, false)) - } - - @Test fun onWithoutALimitIsUnpacedAndAChosenLimitStillPaces() { - assertEquals(SessionPrefs.FPS_UNPACED, SessionPrefs.compositorFpsLimit(0, true)) - assertEquals(60, SessionPrefs.compositorFpsLimit(60, true)) - } - - @Test fun anOldUncappedFrameLimitReadsAsOff() { - session.edit().putInt("fpsLimit.steam", -1).commit() - assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM)) - assertFalse(SessionPrefs.fpsLimitChoices.any { it.first < 0 }) - } -} 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 7962ef6fc8..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)) 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/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/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/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/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/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/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/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/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 ab53e5ad99..0d79564569 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -96,6 +96,88 @@ running AIO Graphics Test uncapped, Xwayland used 24-32% of a core and the game' 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 only in Performance mode and 0 -otherwise. With 100, a window resize or a flip/obscure change is seen up to 100 ms +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 79d4fd8692..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" 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 a505f40a87..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-p13 -GAMESCOPE_SHA256=93c789dc9e08828496f1caa2849d56acdf205838de723a24b296547a29c0b6af +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/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index d3f3fd7707..3e70593909 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -67,6 +67,110 @@ 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 @@ -551,8 +655,17 @@ class Tidy: 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": + 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 [] @@ -924,6 +1037,234 @@ def install_game(root, uid): 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) @@ -934,15 +1275,27 @@ def main(argv): 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]") + 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]) 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 bd25b6089e..534a4f7d38 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup @@ -25,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="" @@ -49,6 +50,7 @@ if [ ! -f /etc/pacman.d/gnupg/pubring.gpg ] && [ ! -f /etc/pacman.d/gnupg/pubrin fi step "Reading the package lists" +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 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index f8b4acaebb..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")): @@ -142,6 +151,12 @@ def robocop_rogue_city_feature_level(game): 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 ( @@ -254,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 @@ -339,6 +357,26 @@ def game_cores(env): 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") @@ -615,6 +653,7 @@ def main(): 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-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index bc3febb332..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 @@ -236,10 +236,10 @@ if [ -z "${BL_INSIDE:-}" ]; then args+=(-S stretch) export BL_STRETCHED=1 fi - if [ "${BL_FPS:-0}" -gt 0 ]; then - args+=(-r "$BL_FPS") - elif [ "${BL_REFRESH:-0}" -gt 0 ]; then + 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 @@ -258,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)" @@ -464,16 +468,32 @@ case $mode in esac ( bl_zram_scan() { - _bl_game=0 _bl_pids=() _bl_others=() + _bl_game=0 _bl_pids=() _bl_others=() _bl_apps= + local _d _c _args _name _a _id for _d in /proc/[0-9]*; do - [ "${_d#/proc/}" != "$BASHPID" ] || continue - # 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/}") ;; - *) _bl_others+=("${_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 } @@ -532,6 +552,22 @@ case $mode in bl_zram_pick "$_which" step "zRAM: done ($(bl_zram_usage "${_pids[@]}"))" } + # 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 @@ -542,7 +578,7 @@ case $mode in bl_cap_due() { [ "$_bl_ram_cap" -gt 0 ] && { [ "$_bl_measured" -lt 0 ] || [ $((SECONDS - _bl_measured)) -ge 30 ]; } } - _bl_since=-1 _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=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_cap_due; then @@ -573,18 +609,22 @@ case $mode in fi fi fi - if [ "$_bl_game" = 1 ]; then - [ "$_bl_since" -ge 0 ] || _bl_since=$SECONDS + 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" client _bl_packed=$SECONDS fi - elif [ "$_bl_since" -ge 0 ]; then + 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 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index ba739235b1..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""" (() => { @@ -633,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: @@ -709,6 +860,9 @@ class Helper: 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}) @@ -728,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): @@ -854,6 +1013,8 @@ 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 @@ -861,15 +1022,14 @@ class Helper: 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, [], [], 30)[0] + 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: - for e in self.page.drain(): - if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str): - self.open_chooser(e["params"]["payload"]) + self.drain() def serve(self, watcher): if self.files_only: @@ -880,10 +1040,13 @@ class Helper: 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 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-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 09dd3dd02b..b1864dfadf 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -90,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 @@ -380,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) @@ -469,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" "$@" @@ -652,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) 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/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 index fe5aed7202..aed66699ed 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -1,3 +1,4 @@ +import contextlib import json import os from pathlib import Path @@ -947,6 +948,33 @@ class LaunchTest(Harness): 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) @@ -1037,5 +1065,211 @@ class HandOverTest(Harness): 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_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_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 index b5714b9a46..7de2d0f7aa 100644 --- a/tools/tests/test_flatpak_setup.py +++ b/tools/tests/test_flatpak_setup.py @@ -1,3 +1,5 @@ +import contextlib +import fcntl import os from pathlib import Path import subprocess @@ -9,9 +11,15 @@ SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/dr class FlatpakSetupTest(unittest.TestCase): - def run_setup(self, uid, pacman): - with tempfile.TemporaryDirectory() as directory: + 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"} @@ -40,6 +48,20 @@ class FlatpakSetupTest(unittest.TestCase): 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 3895ebc695..0b1bee1753 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -77,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) @@ -273,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() @@ -366,6 +402,27 @@ class GameEnvironmentTest(unittest.TestCase): (asylum / name).touch() self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], [])) + 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, []) @@ -392,6 +449,47 @@ class GameEnvironmentTest(unittest.TestCase): 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" 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_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)