mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 21:06:09 +00:00
fix(install): recheck cancellation after sha256 and wire package resume cancel
This commit is contained in:
commit
1b5cd6add9
399 files changed
+28516
-1432
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# GitHub PR openers trusted for automatic release-signed test builds.
|
||||
FX192
|
||||
K11MCH1
|
||||
kingokksa
|
||||
ovurrsl
|
||||
@@ -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:
|
||||
|
||||
@@ -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='<!-- droiddeck-pr-release -->'
|
||||
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.'
|
||||
|
||||
@@ -9,6 +9,10 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big
|
||||
|
||||
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.star-history.com/droid-deck/droiddeck"><img src="https://api.star-history.com/badge?repo=Droid-Deck/DroidDeck&type=rank&theme=dark" alt="Star History Rank" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
||||
@@ -57,7 +61,7 @@ Compatibility and performance vary by device; hardware validation is limited. De
|
||||
|
||||
## Credits and licence
|
||||
|
||||
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-<id>.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/<pid>/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/<pid>/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 [BedrockOnLinuLine truncated
|
||||
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-<id>.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/<pid>/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 userfaultLine truncated
|
||||
|
||||
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
|
||||
|
||||
@@ -67,4 +71,8 @@ Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge
|
||||
|
||||
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead.
|
||||
|
||||
Remote Play from a PC to the arm64 Steam client goes through a stand-in for the V4L2 decoder and the libdrm dumb buffers that Steam's `streaming_client` expects: each frame is decoded by Android's MediaCodec through the app, or by the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) that ships in Steam's own runtime, into dma-heap buffers that its Vulkan renderer imports. The Qualcomm low-latency decoder settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0).
|
||||
|
||||
Steam's Browse buttons open a GTK 3 file chooser through PyGObject (LGPL-2.1-or-later). It runs under Steam's own `reaper` with Steam's app ID, which [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) reads from the process tree (`GetAppIdFromReaper` in `src/Utils/Process.cpp`) to show it over Steam.
|
||||
|
||||
Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose fixes for them (`311210.py` sets ALSA audio, `570940.py` installs VC++ 2017) fail under ARM64 Proton.
|
||||
@@ -87,10 +87,18 @@ def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
|
||||
def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines()
|
||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
|
||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].collectEntries { name ->
|
||||
def pack = file("build/packs/${name}.tar.zst")
|
||||
if (!pack.isFile()) {
|
||||
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
|
||||
// A source build that did not compile proot still pins a published pack, so the app
|
||||
// downloads the patched binary instead of falling back to the rootfs copy.
|
||||
if (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) {
|
||||
return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]]
|
||||
}
|
||||
return [(name): [sha256: '', size: 0L]]
|
||||
}
|
||||
def digest = java.security.MessageDigest.getInstance('SHA-256')
|
||||
@@ -262,6 +270,7 @@ def runtimeAssetsDir = layout.buildDirectory.dir('runtimeAssets')
|
||||
def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
|
||||
dependsOn(stageSessionScripts)
|
||||
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
|
||||
from(rootProject.file('tools/linuxfs/innoextract'))
|
||||
from(layout.buildDirectory.dir('prepared-assets'))
|
||||
into(runtimeAssetsDir)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.content.pm.action.CONFIRM_INSTALL" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.content.pm.action.CONFIRM_PERMISSIONS" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
@@ -18,7 +27,10 @@
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
|
||||
@@ -47,6 +59,15 @@
|
||||
<meta-data android:name="android.game_mode_config" android:resource="@xml/game_mode_config" />
|
||||
<service android:name=".glasses.LumaRgbCaptureService" android:exported="false"
|
||||
android:process=":rgb_diagnostic" />
|
||||
<service android:name=".input.HomeButtonService"
|
||||
android:label="@string/integration_shortcuts_service"
|
||||
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.accessibilityservice.AccessibilityService" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
|
||||
</service>
|
||||
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
|
||||
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
|
||||
android:permission="android.permission.DUMP"
|
||||
@@ -61,10 +82,21 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".PairingGuideActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity="${applicationId}.pairingguide"
|
||||
android:excludeFromRecents="true"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".FrontEndActivity"
|
||||
android:exported="true"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
@@ -116,7 +148,7 @@
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity="${applicationId}.home"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
@@ -126,6 +158,18 @@
|
||||
</activity>
|
||||
|
||||
|
||||
<activity
|
||||
android:name=".PinRequestActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:taskAffinity="${applicationId}.pin"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
|
||||
<intent-filter>
|
||||
<action android:name="android.content.pm.action.CONFIRM_PIN_SHORTCUT" />
|
||||
<action android:name="android.content.pm.action.CONFIRM_PIN_APPWIDGET" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".input.ControllerEditorActivity"
|
||||
android:exported="false"
|
||||
@@ -137,14 +181,14 @@
|
||||
<activity
|
||||
android:name=".files.FileManagerActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".files.FilePickerActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
@@ -176,7 +220,7 @@
|
||||
<activity
|
||||
android:name=".stores.StoreLoginActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <jni.h>
|
||||
#include <media/NdkMediaCodec.h>
|
||||
#include <media/NdkMediaFormat.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
@@ -11,6 +12,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
@@ -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<int64_t>(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>((uint32_t)src_width_, config_.stride);
|
||||
uint32_t h = std::min<uint32_t>((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<Mapping> inputs_, outputs_;
|
||||
std::vector<uint8_t> header_;
|
||||
Decoder decoder_;
|
||||
};
|
||||
|
||||
std::atomic<int> g_listener{-1};
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -186,6 +186,9 @@ static void on_client_created(struct wl_listener *l, void *data) {
|
||||
|
||||
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP, ROLE_CURSOR };
|
||||
|
||||
#define DAMAGE_RECTS 8
|
||||
struct damage_list { int32_t r[DAMAGE_RECTS][4]; int n; };
|
||||
|
||||
struct surface {
|
||||
struct wl_resource *resource;
|
||||
struct wl_list link;
|
||||
@@ -204,9 +207,11 @@ struct surface {
|
||||
struct wl_resource *dmabuf;
|
||||
struct dmabuf_buffer *dmabuf_buf;
|
||||
struct wl_listener dmabuf_destroy;
|
||||
const void *last_dmabuf;
|
||||
int buf_w, buf_h, has_content;
|
||||
int buf_alpha;
|
||||
int opaque[4], pending_opaque[4], pending_opaque_set;
|
||||
struct damage_list damage_buf, pending_damage_buf, damage_local, pending_damage_local;
|
||||
int src_set, dst_set;
|
||||
float src[4];
|
||||
int dst[2];
|
||||
@@ -257,6 +262,21 @@ static struct wl_event_source *g_render_idle, *g_frame_timer;
|
||||
|
||||
|
||||
static int g_dirty;
|
||||
static int64_t g_dirty_since_ns;
|
||||
#define PACE_BUFFERS 32
|
||||
static struct {
|
||||
unsigned ticks, ticks_late_2ms, renders, null_attaches, reattaches, presented, replaced, undrawn, distinct;
|
||||
int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns;
|
||||
const void *buffers[PACE_BUFFERS];
|
||||
uint64_t game_frames_seen;
|
||||
} g_pace;
|
||||
|
||||
static void pace_note_buffer(const void *buffer) {
|
||||
for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++)
|
||||
if (g_pace.buffers[i] == buffer) return;
|
||||
if (g_pace.distinct < PACE_BUFFERS) g_pace.buffers[g_pace.distinct] = buffer;
|
||||
g_pace.distinct++;
|
||||
}
|
||||
static int64_t g_last_vsync_ns;
|
||||
static int64_t g_tick_vsync_ns;
|
||||
static int64_t g_refresh_ns = 16666667;
|
||||
@@ -264,6 +284,8 @@ static struct wl_event_source *g_fallback_timer;
|
||||
static int g_fallback_armed;
|
||||
|
||||
volatile int g_fps_limit;
|
||||
/* fps limit -1 (phone output, not mirrored): replaced buffers go back to the client at once instead of once per refresh. */
|
||||
volatile int g_release_unpaced;
|
||||
|
||||
volatile int g_hide_shell;
|
||||
|
||||
@@ -371,7 +393,7 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
|
||||
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
|
||||
const int limit = g_fps_limit;
|
||||
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
|
||||
if (interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
|
||||
if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
|
||||
int64_t now = now_ns();
|
||||
int64_t at = s->next_release_ns + interval;
|
||||
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
|
||||
@@ -622,6 +644,68 @@ static void fire_frames(struct wl_list *frames) {
|
||||
}
|
||||
}
|
||||
|
||||
static void scene_size(int *w, int *h);
|
||||
static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h);
|
||||
static struct surface *g_hud_surface, *g_hud_shm;
|
||||
static int64_t g_hud_shm_ns;
|
||||
static int64_t g_hud_last_ns, g_hud_alive_ns;
|
||||
static int g_hud_fresh;
|
||||
static int g_hud_new;
|
||||
#define HUD_TIMES 256
|
||||
static pthread_mutex_t g_hud_times_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static float g_hud_times[HUD_TIMES];
|
||||
static int64_t g_hud_times_total, g_hud_shown_ns;
|
||||
|
||||
static void hud_frame_shown(int64_t t) {
|
||||
const int64_t previous = g_hud_shown_ns;
|
||||
g_hud_shown_ns = t;
|
||||
if (!previous || t <= previous) return;
|
||||
pthread_mutex_lock(&g_hud_times_lock);
|
||||
g_hud_times[g_hud_times_total % HUD_TIMES] = (float)((t - previous) / 1e6);
|
||||
g_hud_times_total++;
|
||||
pthread_mutex_unlock(&g_hud_times_lock);
|
||||
}
|
||||
|
||||
static int tree_rank(const struct surface *s, const struct surface *want, int *rank, int depth) {
|
||||
const struct surface *c;
|
||||
if (depth > 8) return 0;
|
||||
wl_list_for_each(c, &s->children, child_link)
|
||||
if (c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
|
||||
if (s == want) return 1;
|
||||
(*rank)++;
|
||||
wl_list_for_each(c, &s->children, child_link)
|
||||
if (!c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int render_rank(const struct surface *want) {
|
||||
const struct surface *s;
|
||||
int rank = 0;
|
||||
if (g_desktop && tree_rank(g_desktop, want, &rank, 0)) return rank;
|
||||
wl_list_for_each(s, &g_toplevels, toplevel_link)
|
||||
if (tree_rank(s, want, &rank, 0)) return rank;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int below_surface(const struct surface *s, const struct surface *other) {
|
||||
const int a = render_rank(s), b = render_rank(other);
|
||||
return a >= 0 && b >= 0 && a < b;
|
||||
}
|
||||
|
||||
int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
|
||||
pthread_mutex_lock(&g_hud_times_lock);
|
||||
*total = g_hud_times_total;
|
||||
int64_t n = *total < len ? *total : len;
|
||||
if (n > HUD_TIMES) n = HUD_TIMES;
|
||||
for (int64_t i = 0; i < n; i++) out[i] = g_hud_times[(*total - n + i) % HUD_TIMES];
|
||||
pthread_mutex_unlock(&g_hud_times_lock);
|
||||
return (int)n;
|
||||
}
|
||||
static uint64_t g_game_frames;
|
||||
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
|
||||
extern void droiddeck_on_game_frame(void);
|
||||
extern void droiddeck_on_game_program(int pid, const char *program);
|
||||
|
||||
static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) {
|
||||
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
|
||||
int32_t stride = wl_shm_buffer_get_stride(shm);
|
||||
@@ -644,6 +728,33 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
||||
g_stat_shm++;
|
||||
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
||||
if (ci && ci->asked_feedback) ci->shm_frames++;
|
||||
int local_w, local_h;
|
||||
surface_size(s, &local_w, &local_h);
|
||||
const double region = s->src_set ? (double)s->src[2] * s->src[3] : (double)w * h;
|
||||
const int64_t local_max = damage_area(&s->damage_local, local_w, local_h);
|
||||
const int64_t local = local_w > 0 && local_h > 0
|
||||
? (int64_t)((double)local_max * region / ((double)local_w * local_h)) : local_max;
|
||||
const int64_t buffer_max = damage_area(&s->damage_buf, w, h);
|
||||
const int64_t area = (int64_t)w * h;
|
||||
int64_t damaged = buffer_max > local ? buffer_max : local;
|
||||
if (damaged > area) damaged = area;
|
||||
const int64_t now = now_ns();
|
||||
if (damaged * 16 >= area && (!g_hud_surface || now - g_hud_last_ns > 1000000000LL) &&
|
||||
(s == g_hud_shm || !g_hud_shm || now - g_hud_shm_ns > 1000000000LL)) {
|
||||
const struct surface *top = s;
|
||||
int scene_w, scene_h, top_w, top_h, depth = 0;
|
||||
while (top->parent && depth++ < 8) top = top->parent;
|
||||
scene_size(&scene_w, &scene_h);
|
||||
surface_size(top, &top_w, &top_h);
|
||||
int64_t shown = (int64_t)local_w * local_h;
|
||||
if ((int64_t)top_w * top_h > shown) shown = (int64_t)top_w * top_h;
|
||||
if (top->role == ROLE_TOPLEVEL && top->mapped && shown * 2 >= (int64_t)scene_w * scene_h) {
|
||||
g_hud_shm = s;
|
||||
g_hud_shm_ns = now;
|
||||
g_hud_new = 1;
|
||||
droiddeck_on_game_frame();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
|
||||
@@ -660,17 +771,12 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
|
||||
s->has_content = s->shm_img != NULL;
|
||||
}
|
||||
|
||||
static struct surface *g_hud_surface;
|
||||
static int64_t g_hud_last_ns, g_hud_alive_ns;
|
||||
static int g_hud_fresh;
|
||||
static uint64_t g_game_frames;
|
||||
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
|
||||
extern void droiddeck_on_game_frame(void);
|
||||
extern void droiddeck_on_game_program(int pid, const char *program);
|
||||
|
||||
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
|
||||
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
|
||||
if (!repeat) {
|
||||
if (!s->dmabuf && s->last_dmabuf == buffer) g_pace.reattaches++;
|
||||
s->last_dmabuf = buffer;
|
||||
pace_note_buffer(buffer);
|
||||
drop_dmabuf(s, 1);
|
||||
s->dmabuf = buffer;
|
||||
s->dmabuf_buf = b;
|
||||
@@ -722,8 +828,9 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
name, b->width, b->height, (unsigned long long)b->modifier);
|
||||
}
|
||||
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL ||
|
||||
(announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) ||
|
||||
(announced_now && !below_surface(g_hud_surface, s) &&
|
||||
(int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||
char name[160];
|
||||
describe(s, name, sizeof(name));
|
||||
g_hud_surface = s;
|
||||
@@ -747,7 +854,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
}
|
||||
if (s == g_hud_surface) {
|
||||
g_hud_alive_ns = now_ns();
|
||||
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_game_frames++; droiddeck_on_game_frame(); }
|
||||
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; droiddeck_on_game_frame(); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -784,8 +891,45 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r,
|
||||
wl_resource_add_destroy_listener(buffer, &s->pending_buffer_destroy);
|
||||
}
|
||||
}
|
||||
static int64_t rect_area(const int32_t *r, int bound_w, int bound_h) {
|
||||
int64_t x0 = r[0], y0 = r[1], x1 = (int64_t)r[0] + r[2], y1 = (int64_t)r[1] + r[3];
|
||||
if (bound_w > 0 && bound_h > 0) {
|
||||
if (x0 < 0) x0 = 0;
|
||||
if (y0 < 0) y0 = 0;
|
||||
if (x1 > bound_w) x1 = bound_w;
|
||||
if (y1 > bound_h) y1 = bound_h;
|
||||
}
|
||||
if (x1 <= x0 || y1 <= y0) return 0;
|
||||
const int64_t w = x1 - x0, h = y1 - y0;
|
||||
return (w < 65536 ? w : 65536) * (h < 65536 ? h : 65536);
|
||||
}
|
||||
static void note_damage(struct damage_list *d, int32_t x, int32_t y, int32_t w, int32_t h) {
|
||||
if (w <= 0 || h <= 0) return;
|
||||
const int32_t rect[4] = { x, y, w, h };
|
||||
int slot = d->n;
|
||||
if (slot == DAMAGE_RECTS) {
|
||||
slot = 0;
|
||||
for (int i = 1; i < DAMAGE_RECTS; i++)
|
||||
if (rect_area(d->r[i], 0, 0) < rect_area(d->r[slot], 0, 0)) slot = i;
|
||||
if (rect_area(rect, 0, 0) <= rect_area(d->r[slot], 0, 0)) return;
|
||||
} else {
|
||||
d->n++;
|
||||
}
|
||||
memcpy(d->r[slot], rect, sizeof(rect));
|
||||
}
|
||||
static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h) {
|
||||
int64_t max = 0;
|
||||
for (int i = 0; i < d->n; i++) {
|
||||
const int64_t area = rect_area(d->r[i], bound_w, bound_h);
|
||||
if (area > max) max = area;
|
||||
}
|
||||
return max;
|
||||
}
|
||||
static void surface_damage(struct wl_client *c, struct wl_resource *r,
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {}
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
note_damage(&s->pending_damage_local, x, y, w, h);
|
||||
}
|
||||
static void frame_callback_destroy(struct wl_resource *r) {
|
||||
wl_list_remove(wl_resource_get_link(r));
|
||||
}
|
||||
@@ -794,12 +938,15 @@ static void feedback_resource_destroy(struct wl_resource *r) {
|
||||
wl_list_remove(wl_resource_get_link(r));
|
||||
}
|
||||
|
||||
static void feedback_discard_all(struct wl_list *list) {
|
||||
static unsigned feedback_discard_all(struct wl_list *list) {
|
||||
struct wl_resource *fb, *tmp;
|
||||
unsigned n = 0;
|
||||
wl_resource_for_each_safe(fb, tmp, list) {
|
||||
wp_presentation_feedback_send_discarded(fb);
|
||||
wl_resource_destroy(fb);
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static uint32_t nominal_refresh_ns(void) {
|
||||
@@ -828,6 +975,7 @@ static void feedback_present_all(struct wl_list *list, int64_t t) {
|
||||
nominal_refresh_ns(), 0, 0,
|
||||
WP_PRESENTATION_FEEDBACK_KIND_VSYNC);
|
||||
wl_resource_destroy(fb);
|
||||
g_pace.presented++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -985,13 +1133,18 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
s->pending_opaque_set = 0;
|
||||
}
|
||||
|
||||
s->damage_buf = s->pending_damage_buf;
|
||||
s->damage_local = s->pending_damage_local;
|
||||
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
|
||||
if (s->pending_attach) {
|
||||
struct wl_resource *buffer = s->pending_buffer;
|
||||
struct dmabuf_buffer *db = get_dmabuf(buffer);
|
||||
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
|
||||
uint8_t pixel[4];
|
||||
|
||||
feedback_discard_all(&s->feedback);
|
||||
g_pace.replaced += feedback_discard_all(&s->feedback);
|
||||
if (!buffer) g_pace.null_attaches++;
|
||||
else if (!db) s->last_dmabuf = NULL;
|
||||
|
||||
if (buffer) {
|
||||
wl_list_remove(&s->pending_buffer_destroy.link);
|
||||
@@ -1049,7 +1202,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {}
|
||||
static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {}
|
||||
static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r,
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {}
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
note_damage(&s->pending_damage_buf, x, y, w, h);
|
||||
}
|
||||
static void surface_offset(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y) {}
|
||||
|
||||
static const struct wl_surface_interface surface_impl = {
|
||||
@@ -1092,6 +1248,7 @@ static void surface_resource_destroy(struct wl_resource *r) {
|
||||
droiddeck_text_input_surface_gone(r);
|
||||
if (g_desktop == s) { g_desktop = NULL; droiddeck_log("desktop", "the desktop closed"); }
|
||||
if (g_hud_surface == s) { g_hud_surface = NULL; droiddeck_on_game_surface(NULL, NULL); }
|
||||
if (g_hud_shm == s) g_hud_shm = NULL;
|
||||
constraints_surface_gone(s);
|
||||
|
||||
unmap_toplevel(s);
|
||||
@@ -1960,13 +2117,20 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) {
|
||||
unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
|
||||
|
||||
static void render_scene(void) {
|
||||
if (atomic_load(&g_stream_on)) { render_stream(); return; }
|
||||
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
|
||||
struct draw_list dl = {0};
|
||||
struct surface *s;
|
||||
int w, h;
|
||||
const int64_t t_scene = now_ns();
|
||||
int copy = 0;
|
||||
|
||||
if (g_dirty_since_ns) {
|
||||
const int64_t wait = t_scene - g_dirty_since_ns;
|
||||
g_pace.wait_ns += wait;
|
||||
if (wait > g_pace.wait_max_ns) g_pace.wait_max_ns = wait;
|
||||
g_pace.renders++;
|
||||
g_dirty_since_ns = 0;
|
||||
}
|
||||
g_dirty = 0;
|
||||
g_hud_fresh = 0;
|
||||
g_hdr_unimported = NULL;
|
||||
@@ -2101,9 +2265,13 @@ static void render_scene(void) {
|
||||
if (rendered) {
|
||||
int64_t t = presented_ns(t_scene);
|
||||
g_stat_frames++;
|
||||
if (g_hud_new) {
|
||||
g_hud_new = 0;
|
||||
hud_frame_shown(t);
|
||||
}
|
||||
wl_list_for_each(s, &g_surfaces, link) {
|
||||
if (s->drawn) feedback_present_all(&s->feedback, t);
|
||||
else feedback_discard_all(&s->feedback);
|
||||
else g_pace.undrawn += feedback_discard_all(&s->feedback);
|
||||
}
|
||||
fire_all_frames();
|
||||
} else {
|
||||
@@ -2129,6 +2297,7 @@ static int on_fallback_timer(void *data) {
|
||||
}
|
||||
|
||||
static void schedule_render(void) {
|
||||
if (!g_dirty && !g_dirty_since_ns) g_dirty_since_ns = now_ns();
|
||||
g_dirty = 1;
|
||||
if (!g_display) return;
|
||||
if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) return;
|
||||
@@ -2148,6 +2317,13 @@ static int scene_waits_for_game(int64_t now) {
|
||||
static void on_vsync(int64_t frame_time_ns) {
|
||||
int64_t now = now_ns();
|
||||
g_perf.ticks++;
|
||||
if (frame_time_ns > 0 && now >= frame_time_ns) {
|
||||
const int64_t late = now - frame_time_ns;
|
||||
g_pace.ticks++;
|
||||
g_pace.tick_late_ns += late;
|
||||
if (late > g_pace.tick_late_max_ns) g_pace.tick_late_max_ns = late;
|
||||
if (late > 2000000LL) g_pace.ticks_late_2ms++;
|
||||
}
|
||||
if (g_last_vsync_ns) {
|
||||
int64_t d = now - g_last_vsync_ns;
|
||||
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
|
||||
@@ -3260,6 +3436,24 @@ static int on_stats_timer(void *data) {
|
||||
#undef PERF_MS
|
||||
memset(&g_perf, 0, sizeof(g_perf));
|
||||
}
|
||||
const uint64_t game = g_game_frames - g_pace.game_frames_seen;
|
||||
if (g_pace.ticks || g_pace.renders || game || g_pace.reattaches || g_pace.null_attaches || g_pace.distinct ||
|
||||
g_pace.presented || g_pace.replaced || g_pace.undrawn) {
|
||||
droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | "
|
||||
"new frame waits %.2f/%.2f ms to be drawn (%u scenes) | %llu game frames, %u re-attached after an "
|
||||
"empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, "
|
||||
"%u not drawn",
|
||||
g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6,
|
||||
g_pace.ticks, g_pace.ticks_late_2ms,
|
||||
g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6,
|
||||
g_pace.renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct,
|
||||
g_pace.presented, g_pace.replaced, g_pace.undrawn);
|
||||
}
|
||||
{
|
||||
const uint64_t seen = g_game_frames;
|
||||
memset(&g_pace, 0, sizeof(g_pace));
|
||||
g_pace.game_frames_seen = seen;
|
||||
}
|
||||
g_stat_frames = g_stat_dmabuf = g_stat_shm = 0;
|
||||
droiddeck_color_stats_tick();
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ extern void droiddeck_wayland_send_pointer(int action, int x, int y);
|
||||
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
|
||||
extern int droiddeck_cursor_snapshot(int *out, int cap);
|
||||
extern int droiddeck_cursor_serial(void);
|
||||
extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total);
|
||||
extern void droiddeck_wayland_send_key(int evdev, int state);
|
||||
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
|
||||
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
|
||||
@@ -34,6 +35,7 @@ extern unsigned droiddeck_stream_frames(void);
|
||||
extern void droiddeck_wayland_output_resized(void);
|
||||
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
|
||||
extern volatile int g_fps_limit;
|
||||
extern volatile int g_release_unpaced;
|
||||
extern volatile int g_hide_shell;
|
||||
extern volatile int g_zero_copy;
|
||||
extern volatile unsigned g_zero_copy_last;
|
||||
@@ -267,6 +269,20 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
||||
return n;
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHudFrameTimes(JNIEnv *env, jclass clazz, jfloatArray out) {
|
||||
(void)clazz;
|
||||
if (!out) return 0;
|
||||
jint cap = (*env)->GetArrayLength(env, out);
|
||||
float *buf = cap > 0 ? malloc(sizeof(float) * (size_t)cap) : NULL;
|
||||
if (!buf) return 0;
|
||||
int64_t total = 0;
|
||||
int n = droiddeck_hud_frame_times(buf, cap, &total);
|
||||
if (n > 0) (*env)->SetFloatArrayRegion(env, out, 0, n, buf);
|
||||
free(buf);
|
||||
return (jlong)total;
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) {
|
||||
(void)env; (void)clazz;
|
||||
@@ -574,6 +590,7 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv *
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
|
||||
g_fps_limit = fps > 0 ? fps : 0;
|
||||
g_release_unpaced = fps < 0;
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "fps limit %d", fps);
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
|
||||
}
|
||||
|
||||
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
|
||||
|
||||
@@ -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<String?>(null)
|
||||
private var flood by mutableStateOf<PendingFlood?>(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<CompatLaunch?>(null)
|
||||
private var compatFlood by mutableStateOf<androidx.compose.ui.graphics.Color?>(null)
|
||||
private var compatLaunchPoll: Runnable? = null
|
||||
private var compatLaunchVisible = false
|
||||
private var returning by mutableStateOf<ReturningFlood?>(null)
|
||||
private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?)
|
||||
private var ready by mutableStateOf(false)
|
||||
@@ -134,11 +140,17 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
|
||||
private var catalogLoading by mutableStateOf(false)
|
||||
private var packageRows by mutableStateOf<List<PackageRow>?>(null)
|
||||
private var pkgId by mutableStateOf<String?>(null)
|
||||
private var pkgStage by mutableStateOf<String?>(null)
|
||||
private var pkgPercent by mutableIntStateOf(-1)
|
||||
private object PackageOperation {
|
||||
val id = mutableStateOf<String?>(null)
|
||||
val stage = mutableStateOf<String?>(null)
|
||||
val percent = mutableIntStateOf(-1)
|
||||
}
|
||||
private var pkgId by PackageOperation.id
|
||||
private var pkgStage by PackageOperation.stage
|
||||
private var pkgPercent by PackageOperation.percent
|
||||
private var desktopInstalled by mutableStateOf(false)
|
||||
private var desktopPresent by mutableStateOf(false)
|
||||
private var battleNetInstalled by mutableStateOf(false)
|
||||
private var offlineAccount by mutableStateOf<String?>(null)
|
||||
private var offline by mutableStateOf(false)
|
||||
private var showPerformance by mutableStateOf(false)
|
||||
@@ -152,6 +164,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var syncFallback by mutableStateOf(true)
|
||||
private var fsyncFirst by mutableStateOf(false)
|
||||
private var gamescopeRealtime by mutableStateOf(false)
|
||||
private var ramCapMb by mutableStateOf(0)
|
||||
private var zramClient by mutableStateOf(true)
|
||||
private var vramCapMb by mutableStateOf(0)
|
||||
private var gpuClockPin by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var prootFastPath by mutableStateOf(true)
|
||||
@@ -164,10 +179,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var picturePosition by mutableStateOf("center")
|
||||
private var stretch16x9 by mutableStateOf(false)
|
||||
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
||||
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||
private var launcherFullscreen by mutableStateOf(true)
|
||||
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
|
||||
private var downloadMirror by mutableStateOf("")
|
||||
private var downloadPrefix by mutableStateOf("")
|
||||
private var downloadProxy by mutableStateOf("")
|
||||
private var animationsEnabled by mutableStateOf(true)
|
||||
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
|
||||
private var gameStoresEnabled by mutableStateOf(true)
|
||||
@@ -182,6 +199,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var wifiDiscoveryLocation by mutableStateOf(false)
|
||||
private var wifiDiscoveryAsked by mutableStateOf(false)
|
||||
private var wifiDiscoveryBlocked by mutableStateOf(false)
|
||||
private var integrationState by mutableStateOf(SteamIntegration.State())
|
||||
private var integrationFocus by mutableStateOf<SteamIntegration.Feature?>(null)
|
||||
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
|
||||
override fun onReceive(context: android.content.Context?, intent: Intent?) {
|
||||
refreshWifiDiscovery()
|
||||
@@ -250,8 +269,65 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
}
|
||||
wifiDiscovery = SessionPrefs.wifiDiscoveryEnabled(this)
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
|
||||
private var shortcutsTried = false
|
||||
|
||||
private fun readIntegration() = SteamIntegration.read(this)
|
||||
.copy(locationBlocked = wifiDiscoveryBlocked, shortcutsTried = shortcutsTried)
|
||||
|
||||
private fun openIntegration(feature: SteamIntegration.Feature? = null) {
|
||||
SteamIntegration.dismissSuggestion(this)
|
||||
refreshWifiDiscovery()
|
||||
integrationState = readIntegration()
|
||||
integrationFocus = feature
|
||||
navRequest = "setup:integration"
|
||||
}
|
||||
|
||||
private fun readIntegrationIntent(incoming: Intent) {
|
||||
if (incoming.action != SteamIntegration.ACTION_SETUP) return
|
||||
openIntegration(incoming.getStringExtra(SteamIntegration.EXTRA_FEATURE)?.let {
|
||||
runCatching { SteamIntegration.Feature.valueOf(it) }.getOrNull()
|
||||
})
|
||||
}
|
||||
|
||||
private fun integrationSettings(intent: Intent, fallback: String = android.provider.Settings.ACTION_SETTINGS) {
|
||||
try { startActivity(intent) }
|
||||
catch (_: android.content.ActivityNotFoundException) { startActivity(Intent(fallback)) }
|
||||
catch (_: SecurityException) { startActivity(Intent(fallback)) }
|
||||
}
|
||||
|
||||
private fun configureIntegration(feature: SteamIntegration.Feature) {
|
||||
when (feature) {
|
||||
SteamIntegration.Feature.WIFI -> {
|
||||
if (wifiDiscovery && wifiDiscoveryPermission) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
} else if (wifiDiscoveryPermission) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, true)
|
||||
} else {
|
||||
SessionPrefs.setWifiDiscoveryAsked(this)
|
||||
wifiLocationPermission.launch(WifiDiscovery.permissions)
|
||||
}
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
|
||||
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else {
|
||||
HomeApp.setHomeScreenEnabled(this, true)
|
||||
refreshHomeAppState()
|
||||
manageHomeApp()
|
||||
}
|
||||
SteamIntegration.Feature.SHORTCUTS -> {
|
||||
if (!integrationState.shortcuts) shortcutsTried = true
|
||||
if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME)
|
||||
else integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun openAppInfo() =
|
||||
integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
|
||||
|
||||
private fun openWifiDiscoverySettings() {
|
||||
if (!WifiDiscovery.permissionGranted(this)) {
|
||||
wifiPermissionSettings.launch(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
@@ -386,7 +462,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var theme by mutableStateOf("graphite")
|
||||
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
|
||||
private var hdrOn by mutableStateOf(false)
|
||||
private var fpsLimit by mutableStateOf(0)
|
||||
private var upscaler by mutableStateOf(0)
|
||||
private var upscaleSharpness by mutableStateOf(75)
|
||||
private var hdrReason by mutableStateOf<String?>(null)
|
||||
@@ -411,11 +486,30 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var logsEnabled by mutableStateOf(true)
|
||||
private var vacDiagnostics by mutableStateOf(false)
|
||||
private var agentCommands by mutableStateOf(false)
|
||||
private var clearCachedApps by mutableStateOf(false)
|
||||
private var adbPaired by mutableStateOf(false)
|
||||
private var memoryHud by mutableStateOf(SessionPrefs.MEMORY_HUD_OFF)
|
||||
private var backgroundAppLimit by mutableStateOf(com.droiddeck.launcher.core.BackgroundAppLimit.OFF)
|
||||
private var showRoms by mutableStateOf(false)
|
||||
private var homeAppSelected by mutableStateOf(false)
|
||||
private var homeScreenEnabled by mutableStateOf(false)
|
||||
private var defaultHomeLabel by mutableStateOf<String?>(null)
|
||||
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(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<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
|
||||
override fun onPackagesUnavailable(packageNames: Array<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
|
||||
override fun onShortcutsChanged(packageName: String, shortcuts: MutableList<android.content.pm.ShortcutInfo>, user: android.os.UserHandle) {
|
||||
if (homeAppSelected) HomePins.refresh(this@FrontEndActivity)
|
||||
}
|
||||
}
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private lateinit var displayManager: DisplayManager
|
||||
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
|
||||
@@ -429,7 +523,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun startActivity(intent: Intent?) {
|
||||
val compat = protons.protonBusyId != null || ProtonExtras.installInProgress
|
||||
if (intent?.component?.className == SessionActivity::class.java.name) {
|
||||
if (compatLaunch != null) return
|
||||
when {
|
||||
busy || LinuxRuntimeInstaller.isBusy() -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
|
||||
@@ -439,10 +535,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
protons.protonBusyId != null || ProtonExtras.installInProgress -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_proton_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
compat -> Unit
|
||||
pkgStage != null -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
@@ -457,17 +550,26 @@ class FrontEndActivity : ComponentActivity() {
|
||||
return
|
||||
}
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
if (compat) {
|
||||
waitForCompat(intent)
|
||||
return
|
||||
}
|
||||
}
|
||||
super.startActivity(intent)
|
||||
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
|
||||
}
|
||||
|
||||
private fun launchFlooded(f: PendingFlood) {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null ||
|
||||
ProtonExtras.installInProgress || pkgStage != null) {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) ||
|
||||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
flood = null
|
||||
floodProgress = 0f
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
if (!busy && !LinuxRuntimeInstaller.isBusy() && !(SessionState.installing != null && !SessionState.running) &&
|
||||
(protons.protonBusyId != null || ProtonExtras.installInProgress)) {
|
||||
compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal
|
||||
waitForCompat(f.intent)
|
||||
}
|
||||
return
|
||||
}
|
||||
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
|
||||
@@ -475,6 +577,72 @@ class FrontEndActivity : ComponentActivity() {
|
||||
overridePendingTransition(0, 0)
|
||||
}
|
||||
|
||||
private fun waitForCompat(next: Intent, menuInstall: Boolean = protons.protonBusyId != null) {
|
||||
if (compatLaunch != null) return
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.take()
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
val waiting = CompatLaunch(Intent(next), com.droiddeck.launcher.session.LoadingState(this), menuInstall)
|
||||
compatLaunch = waiting
|
||||
val poll = object : Runnable {
|
||||
override fun run() {
|
||||
if (isDestroyed || isFinishing || compatLaunch !== waiting) return
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress) {
|
||||
waiting.menuInstall = waiting.menuInstall || protons.protonBusyId != null
|
||||
val percent = if (protons.protonBusyId != null) protons.protonPercent else -1
|
||||
val stage = protons.protonStage ?: getString(R.string.load_compat_wait)
|
||||
waiting.loading.say(if (percent >= 0) getString(R.string.load_compat_progress, stage, percent) else stage,
|
||||
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
|
||||
waiting.loading.percent = percent
|
||||
waiting.loading.tick()
|
||||
ui.postDelayed(this, 250)
|
||||
return
|
||||
}
|
||||
if (!compatLaunchVisible) { ui.postDelayed(this, 250); return }
|
||||
val problem = protons.protonProblem.takeIf { waiting.menuInstall }
|
||||
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || pkgStage != null)) {
|
||||
waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime),
|
||||
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
|
||||
waiting.loading.percent = if (pkgStage != null) pkgPercent else percent
|
||||
waiting.loading.tick()
|
||||
ui.postDelayed(this, 250)
|
||||
return
|
||||
}
|
||||
compatLaunchPoll = null
|
||||
if (problem != null) waiting.loading.showEnded(problem)
|
||||
else {
|
||||
compatLaunch = null
|
||||
startActivity(waiting.intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
compatLaunchPoll = poll
|
||||
poll.run()
|
||||
}
|
||||
|
||||
private fun cancelCompatLaunch() {
|
||||
compatLaunchPoll?.let(ui::removeCallbacks)
|
||||
compatLaunchPoll = null
|
||||
compatLaunch = null
|
||||
compatFlood = null
|
||||
}
|
||||
|
||||
private fun restoreCompatLaunch(state: Bundle) {
|
||||
savedIntent(state, KEY_COMPAT_LAUNCH)?.let { next ->
|
||||
val problem = state.getString(KEY_COMPAT_PROBLEM)
|
||||
if (problem == null) waitForCompat(next, state.getBoolean(KEY_COMPAT_MENU_INSTALL))
|
||||
else compatLaunch = CompatLaunch(next,
|
||||
com.droiddeck.launcher.session.LoadingState(this).apply { showEnded(problem) }, false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveCompatLaunch(state: Bundle) {
|
||||
compatLaunch?.let {
|
||||
state.putParcelable(KEY_COMPAT_LAUNCH, it.intent)
|
||||
state.putBoolean(KEY_COMPAT_MENU_INSTALL, it.menuInstall)
|
||||
if (it.loading.ended) state.putString(KEY_COMPAT_PROBLEM, it.loading.step)
|
||||
}
|
||||
}
|
||||
|
||||
private var shortcutPicker by mutableStateOf(false)
|
||||
private var shortcutLibraryScanning by mutableStateOf(false)
|
||||
@Volatile private var libraryScanGeneration = 0
|
||||
@@ -536,7 +704,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
if (pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
@@ -592,9 +760,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
|
||||
.putExtra(SessionService.EXTRA_PROGRAM, command.program)
|
||||
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, command.args.toTypedArray())
|
||||
.putExtra(SessionService.EXTRA_GAME_ID, com.droiddeck.launcher.session.NoSteamLaunch.scope(game))
|
||||
when {
|
||||
!SessionState.running -> startSessionOrWait(next)
|
||||
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
|
||||
command.program == com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET && handToBattleNet(command.args, returnHome) { pendingSwitch = next } -> {}
|
||||
SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args ->
|
||||
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
|
||||
.returnTo(returnHome)
|
||||
@@ -646,7 +816,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
android.widget.Toast.makeText(this, R.string.epic_client_uninstalling, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
if (pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
@@ -692,7 +862,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun startSessionOrWait(next: Intent): Boolean {
|
||||
val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL))
|
||||
val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL) ||
|
||||
next.getStringExtra(SessionService.EXTRA_PROGRAM) in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET))
|
||||
if (!started && (busy || LinuxRuntimeInstaller.isBusy())) android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return started
|
||||
}
|
||||
@@ -753,10 +924,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
if (savedInstanceState == null) readIntegrationIntent(intent)
|
||||
readGameIntent(intent)
|
||||
gameSyncFolder = GameFileSync.folder(this)
|
||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||
refreshPhantomStatus()
|
||||
if (!SessionState.running) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
|
||||
theme = SessionPrefs.theme(this)
|
||||
frameGenLabel = getString(R.string.frame_gen_off)
|
||||
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
|
||||
@@ -765,11 +938,13 @@ class FrontEndActivity : ComponentActivity() {
|
||||
steamGamesX64 = cachedX64
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
requestedOrientation = orientation
|
||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
requestedOrientation = launcherOrientation
|
||||
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
|
||||
downloadSource = DownloadSource.mode(this)
|
||||
downloadMirror = DownloadSource.mirror(this)
|
||||
downloadPrefix = DownloadSource.custom(this)
|
||||
downloadProxy = DownloadSource.proxyHostPort(this)
|
||||
DownloadSource.probe()
|
||||
animationsEnabled = SessionPrefs.animationsEnabled(this)
|
||||
LauncherIcon.repair(this, intent?.component)
|
||||
@@ -805,6 +980,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
offlineAccount = offlineAccount, offline = offline,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
||||
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
|
||||
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
|
||||
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
|
||||
frameGen = FrameGen.mode(this),
|
||||
lossless = lossless,
|
||||
@@ -815,6 +991,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
isHomeApp = homeAppSelected,
|
||||
homeScreenEnabled = homeScreenEnabled,
|
||||
defaultHomeLabel = defaultHomeLabel,
|
||||
integration = integrationState,
|
||||
integrationFocus = integrationFocus,
|
||||
androidApps = androidApps,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
packages = packageRows,
|
||||
@@ -823,6 +1001,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
packageStage = pkgStage,
|
||||
packagePercent = pkgPercent,
|
||||
sessionRunning = SessionState.running,
|
||||
battleNetInstalled = battleNetInstalled,
|
||||
backActionsInverted = backActionsInverted,
|
||||
buildLabel = BuildConfig.BUILD_LABEL,
|
||||
oscMode = oscMode,
|
||||
@@ -831,10 +1010,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
phantomProcessStatus = phantomProcessStatus,
|
||||
showPhantomGate = showPhantomGate,
|
||||
orientation = orientation,
|
||||
launcherOrientation = launcherOrientation,
|
||||
launcherFullscreen = launcherFullscreen,
|
||||
downloadSource = downloadSource,
|
||||
downloadMirror = downloadMirror,
|
||||
downloadPrefix = downloadPrefix,
|
||||
downloadProxy = downloadProxy,
|
||||
animationsEnabled = animationsEnabled,
|
||||
launcherIcon = launcherIcon,
|
||||
gameStoresEnabled = gameStoresEnabled,
|
||||
@@ -910,6 +1091,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
.putExtra(SessionService.EXTRA_PROGRAM, app.program)
|
||||
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray()))
|
||||
},
|
||||
onBattleNet = { openBattleNet() },
|
||||
onFlatpakApp = { id, name ->
|
||||
Library.flatpakNames[id] = name
|
||||
startActivity(Intent(this, SessionActivity::class.java)
|
||||
@@ -964,6 +1146,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this))
|
||||
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
||||
},
|
||||
onClearCachedApps = { on -> SessionPrefs.setClearCachedApps(this, on); clearCachedApps = on },
|
||||
onMemoryHud = { value -> SessionPrefs.setMemoryHud(this, value); memoryHud = value },
|
||||
onBackgroundAppLimit = { limit ->
|
||||
SessionPrefs.setBackgroundAppLimit(this, limit); backgroundAppLimit = limit
|
||||
if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
|
||||
},
|
||||
onShareLogs = {
|
||||
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
|
||||
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
|
||||
@@ -1005,6 +1193,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onOrientation = { value ->
|
||||
SessionPrefs.setOrientation(this, value)
|
||||
orientation = value
|
||||
},
|
||||
onLauncherOrientation = { value ->
|
||||
com.droiddeck.launcher.core.AppUiPrefs.setOrientation(this, value)
|
||||
launcherOrientation = value
|
||||
requestedOrientation = value
|
||||
},
|
||||
onLauncherFullscreen = { on ->
|
||||
@@ -1035,7 +1227,19 @@ class FrontEndActivity : ComponentActivity() {
|
||||
DownloadSource.setCustom(this, prefix)
|
||||
downloadPrefix = DownloadSource.custom(this)
|
||||
},
|
||||
onDownloadProxy = { value ->
|
||||
DownloadSource.setProxy(this, value)
|
||||
downloadProxy = DownloadSource.proxyHostPort(this)
|
||||
},
|
||||
onHomeApp = { manageHomeApp() },
|
||||
onSteamIntegration = ::openIntegration,
|
||||
onIntegration = { integrationFocus = null; configureIntegration(it) },
|
||||
onIntegrationAppInfo = ::openAppInfo,
|
||||
onIntegrationLocation = ::openWifiDiscoverySettings,
|
||||
onDismissIntegration = {
|
||||
SteamIntegration.dismissSuggestion(this)
|
||||
integrationState = readIntegration()
|
||||
},
|
||||
onHomeScreen = { on ->
|
||||
HomeApp.setHomeScreenEnabled(this, on)
|
||||
refreshHomeAppState()
|
||||
@@ -1089,7 +1293,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDismissPhantomGate = { showPhantomGate = false },
|
||||
onShowPhantomGate = {
|
||||
refreshPhantomStatus()
|
||||
showPhantomGate = true
|
||||
},
|
||||
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
|
||||
onStartPairingGuide = { displayId -> PairingGuideActivity.start(this, displayId) },
|
||||
onOpenNotificationSettings = {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
|
||||
@@ -1185,12 +1394,23 @@ class FrontEndActivity : ComponentActivity() {
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
}
|
||||
}
|
||||
androidx.activity.compose.BackHandler(compatLaunch != null) { cancelCompatLaunch() }
|
||||
compatLaunch?.loading?.let { loading ->
|
||||
if (!loading.ended) com.droiddeck.launcher.ui.VeilRing()
|
||||
com.droiddeck.launcher.ui.LoadingOverlay(
|
||||
loading.step, loading.percent, loading.elapsed, getString(R.string.load_compat_hint), loading.ended,
|
||||
loading.topic, loading.readable, title = getString(R.string.load_compat_title),
|
||||
onCancel = ::cancelCompatLaunch, onClose = ::cancelCompatLaunch,
|
||||
flood = compatFlood, onFlooded = { compatFlood = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
|
||||
else {
|
||||
restoreCompatLaunch(savedInstanceState)
|
||||
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
|
||||
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
|
||||
}
|
||||
@@ -1219,6 +1439,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
if (intent.action == SteamIntegration.ACTION_SETUP) {
|
||||
readIntegrationIntent(intent)
|
||||
return
|
||||
}
|
||||
readGameIntent(intent)
|
||||
refresh()
|
||||
startSteamAtStartupIfEnabled()
|
||||
@@ -1277,6 +1501,14 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (compatLaunch != null) {
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
|
||||
if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
|
||||
return true
|
||||
}
|
||||
if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
|
||||
}
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
|
||||
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
@@ -1293,13 +1525,27 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
|
||||
if (compatLaunch != null && !compatLaunch!!.loading.ended &&
|
||||
com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
compatLaunchVisible = false
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
compatLaunchVisible = true
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
requestedOrientation = orientation
|
||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
requestedOrientation = launcherOrientation
|
||||
refreshWifiDiscovery()
|
||||
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) }
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
|
||||
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
|
||||
@@ -1341,10 +1587,20 @@ class FrontEndActivity : ComponentActivity() {
|
||||
})
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
refreshSecondScreenDisplays()
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
|
||||
HomeWidgets.startListening(this)
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) return
|
||||
@Suppress("DEPRECATION")
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
saveCompatLaunch(outState)
|
||||
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
|
||||
switchingTo?.let {
|
||||
outState.putParcelable(KEY_SWITCHING_TO, it)
|
||||
@@ -1357,6 +1613,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
else @Suppress("DEPRECATION") state.getParcelable(key)
|
||||
|
||||
override fun onDestroy() {
|
||||
cancelCompatLaunch()
|
||||
updates.unregister()
|
||||
super.onDestroy()
|
||||
}
|
||||
@@ -1364,8 +1621,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onStop() {
|
||||
unregisterReceiver(wifiLocationReceiver)
|
||||
unregisterReceiver(mediaReceiver)
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
|
||||
HomeWidgets.stopListening(this)
|
||||
ui.removeCallbacks(mediaRefresh)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = null
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
|
||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||
flood = null
|
||||
returning = null
|
||||
@@ -1378,7 +1638,22 @@ class FrontEndActivity : ComponentActivity() {
|
||||
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
|
||||
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
|
||||
defaultHomeLabel = HomeApp.defaultLabel(this)
|
||||
androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList()
|
||||
refreshAndroidApps()
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
|
||||
private fun refreshAndroidApps() {
|
||||
if (!homeAppSelected) {
|
||||
++androidAppsListing
|
||||
androidApps = emptyList()
|
||||
return
|
||||
}
|
||||
val seq = ++androidAppsListing
|
||||
HomePins.refresh(this)
|
||||
Thread({
|
||||
val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList())
|
||||
ui.post { if (seq == androidAppsListing) androidApps = apps }
|
||||
}, "home-apps").start()
|
||||
}
|
||||
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
@@ -1559,6 +1834,50 @@ class FrontEndActivity : ComponentActivity() {
|
||||
desktopPresent = DesktopCatalog.desktopPresent(this)
|
||||
}
|
||||
|
||||
private fun openBattleNet(args: List<String> = emptyList()) {
|
||||
if (pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
val app = applicationContext
|
||||
Thread({
|
||||
val full = if (args.firstOrNull() == "--library") args else com.droiddeck.launcher.stores.battlenet.BattleNetClient.library(app) + args
|
||||
ui.post {
|
||||
if (isDestroyed) return@post
|
||||
val next = Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
|
||||
.putExtra(SessionService.EXTRA_PROGRAM, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET)
|
||||
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, full.toTypedArray())
|
||||
when {
|
||||
!SessionState.running -> startSessionOrWait(next)
|
||||
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
|
||||
handToBattleNet(full) { pendingSwitch = next } -> {}
|
||||
else -> pendingSwitch = next
|
||||
}
|
||||
}
|
||||
}, "battlenet-open").start()
|
||||
}
|
||||
|
||||
private fun handToBattleNet(args: List<String>, returnHome: Boolean = false, otherwise: () -> Unit): Boolean {
|
||||
if (SessionState.mode != SessionService.MODE_RUN || SessionState.program != com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET) return false
|
||||
val library = args.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
|
||||
val sessionLibrary = SessionState.programArgs.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
|
||||
if (library != null && sessionLibrary != null && library != sessionLibrary) return false
|
||||
val request = if (library != null) args.drop(2) else args
|
||||
val app = applicationContext
|
||||
Thread({
|
||||
val handed = request.isEmpty() || com.droiddeck.launcher.stores.battlenet.BattleNetClient.request(LinuxRuntime.sessionRoot(app), request)
|
||||
ui.post {
|
||||
if (isDestroyed) return@post
|
||||
if (!handed) otherwise()
|
||||
else startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
|
||||
.returnTo(returnHome)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
}
|
||||
}, "battlenet-request").start()
|
||||
return true
|
||||
}
|
||||
|
||||
private fun launchProgram(path: String) {
|
||||
startActivity(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
|
||||
@@ -1624,7 +1943,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
ModeSettings(
|
||||
mode = mode, resolution = resolution,
|
||||
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
||||
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit,
|
||||
hdr = hdrOn, hdrReason = hdrReason,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
gpuDrivers = drivers.summary(),
|
||||
touchMode = touchMode,
|
||||
@@ -1632,8 +1951,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
steamDownloadsInBackground = steamDownloadsInBackground,
|
||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
||||
pipAutoEnter = pipAutoEnter,
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
|
||||
com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null,
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM) unfoldedControls else null,
|
||||
unfoldedControlsWithController = unfoldedControlsWithController,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
@@ -1659,11 +1977,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
bootMovieCustomName = bootMovieCustomName,
|
||||
bootMovieImporting = bootMovieImporting,
|
||||
bootMovieProgress = bootMovieProgress,
|
||||
wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null,
|
||||
wifiDiscoveryPermission = wifiDiscoveryPermission,
|
||||
wifiDiscoveryLocation = wifiDiscoveryLocation,
|
||||
wifiDiscoveryAsked = wifiDiscoveryAsked,
|
||||
wifiDiscoveryBlocked = wifiDiscoveryBlocked,
|
||||
integration = if (mode == SessionService.MODE_STEAM) integrationState else null,
|
||||
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
|
||||
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyLatest else null,
|
||||
deckyBranch = decky.deckyBranch,
|
||||
@@ -1672,25 +1986,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
|
||||
),
|
||||
ModeSettingsActions(
|
||||
onWifiDiscovery = { on ->
|
||||
if (!on) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
refreshWifiDiscovery()
|
||||
} else if (WifiDiscovery.permissionGranted(this)) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, true)
|
||||
refreshWifiDiscovery()
|
||||
} else if (wifiDiscoveryBlocked) {
|
||||
openWifiDiscoverySettings()
|
||||
} else {
|
||||
SessionPrefs.setWifiDiscoveryAsked(this)
|
||||
wifiLocationPermission.launch(WifiDiscovery.permissions)
|
||||
}
|
||||
},
|
||||
onWifiDiscoverySettings = { openWifiDiscoverySettings() },
|
||||
onIntegration = ::configureIntegration,
|
||||
onIntegrationAppInfo = ::openAppInfo,
|
||||
onIntegrationLocation = ::openWifiDiscoverySettings,
|
||||
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
|
||||
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
|
||||
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
|
||||
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
|
||||
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
|
||||
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||
@@ -1785,6 +2086,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
fsyncFirst = fsyncFirst,
|
||||
gamescopeRealtime = gamescopeRealtime,
|
||||
gpuClockPin = gpuClockPin,
|
||||
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient,
|
||||
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
|
||||
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
|
||||
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
|
||||
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, cursorComposite = cursorComposite,
|
||||
guestHostname = guestHostname, phantomWarning = phantomWarning,
|
||||
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
||||
@@ -1798,6 +2103,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
|
||||
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
|
||||
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
|
||||
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
|
||||
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
|
||||
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
|
||||
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
|
||||
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
|
||||
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
|
||||
@@ -1934,7 +2242,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
|
||||
loadBootMovie()
|
||||
hdrOn = SessionPrefs.hdr(this, mode)
|
||||
fpsLimit = SessionPrefs.fpsLimit(this, mode)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
|
||||
@@ -1993,6 +2300,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
syncFallback = SessionPrefs.syncFallback(this)
|
||||
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
||||
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
|
||||
ramCapMb = SessionPrefs.ramCapMb(this)
|
||||
zramClient = SessionPrefs.zramClient(this)
|
||||
vramCapMb = SessionPrefs.vramCapMb(this)
|
||||
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||
prootFastPath = SessionPrefs.prootFastPath(this)
|
||||
@@ -2013,6 +2323,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
addedGamesArt = SessionPrefs.addedGamesArt(this)
|
||||
desktopInstalled = DesktopCatalog.desktopInstalled(this)
|
||||
desktopPresent = DesktopCatalog.desktopPresent(this)
|
||||
battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(this)
|
||||
offlineAccount = OfflineMode.account(this)
|
||||
offline = OfflineMode.enabled(this)
|
||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||
@@ -2023,6 +2334,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
||||
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
||||
clearCachedApps = SessionPrefs.clearCachedApps(this)
|
||||
adbPaired = WirelessAdbFix.hasSavedPairing(this)
|
||||
memoryHud = SessionPrefs.memoryHud(this)
|
||||
backgroundAppLimit = SessionPrefs.backgroundAppLimit(this)
|
||||
runningLabel = if (SessionState.running) when (SessionState.mode) {
|
||||
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop)
|
||||
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
|
||||
@@ -2032,7 +2347,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
val scanGeneration = ++libraryScanGeneration
|
||||
val artRefreshesAtStart = HashMap(steamArtRefreshes)
|
||||
if (shortcutPicker) shortcutLibraryScanning = true
|
||||
if (SessionPrefs.steamClientArch(this) == "x86_64" && !OfflineMode.enabled(this)) {
|
||||
if (!OfflineMode.enabled(this)) {
|
||||
Thread({ com.droiddeck.launcher.session.FexCatalog.refresh(this) }, "fex-catalog").start()
|
||||
}
|
||||
Thread({
|
||||
@@ -2124,6 +2439,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
private fun refreshPhantomStatus() {
|
||||
phantomProcessStatus = PhantomProcessLimit.read(this)
|
||||
adbPaired = WirelessAdbFix.hasSavedPairing(this)
|
||||
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
getString(
|
||||
R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus),
|
||||
@@ -2227,6 +2543,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private const val SESSION_SWITCH_WAIT_MS = 30_000L
|
||||
private const val SESSION_SWITCH_POLL_MS = 250L
|
||||
private const val KEY_PENDING_SWITCH = "pending_switch"
|
||||
private const val KEY_COMPAT_LAUNCH = "compat_launch"
|
||||
private const val KEY_COMPAT_MENU_INSTALL = "compat_menu_install"
|
||||
private const val KEY_COMPAT_PROBLEM = "compat_problem"
|
||||
private const val KEY_SWITCHING_TO = "switching_to"
|
||||
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
|
||||
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
|
||||
@@ -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<LaunchableApp> {
|
||||
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<ShortcutInfo> {
|
||||
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<ShortcutInfo> { 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 =
|
||||
|
||||
@@ -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<String>)
|
||||
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "folders"
|
||||
|
||||
var folders by mutableStateOf<List<Folder>>(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<Folder> =
|
||||
folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() }
|
||||
|
||||
private fun update(context: Context, next: List<Folder>) {
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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<Set<String>>(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()
|
||||
}
|
||||
}
|
||||
@@ -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<List<Pinned>>(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<Pinned> {
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@@ -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<List<Placed>>(emptyList())
|
||||
private set
|
||||
var providers by mutableStateOf<List<Provider>?>(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<Int, Int> {
|
||||
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<Int, Int> {
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -20,10 +20,19 @@ internal class ProtonMenu(
|
||||
private val ui: Handler,
|
||||
private val idle: () -> Boolean = { true },
|
||||
) {
|
||||
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
var protonBusyId by mutableStateOf<String?>(null)
|
||||
var protonStage by mutableStateOf<String?>(null)
|
||||
var protonPercent by mutableIntStateOf(-1)
|
||||
// Install workers and their results outlive the activity that starts them.
|
||||
private object Operation {
|
||||
val rows = mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
val busyId = mutableStateOf<String?>(null)
|
||||
val stage = mutableStateOf<String?>(null)
|
||||
val percent = mutableIntStateOf(-1)
|
||||
val problem = mutableStateOf<String?>(null)
|
||||
}
|
||||
var protonRows by Operation.rows
|
||||
var protonBusyId by Operation.busyId
|
||||
var protonStage by Operation.stage
|
||||
var protonPercent by Operation.percent
|
||||
var protonProblem by Operation.problem
|
||||
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
||||
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
|
||||
@@ -33,6 +42,7 @@ internal class ProtonMenu(
|
||||
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
|
||||
ProtonExtras.unqueue(activity, tool)
|
||||
protonBusyId = id
|
||||
protonProblem = null
|
||||
protonStage = activity.getString(R.string.store_starting)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
@@ -41,7 +51,9 @@ internal class ProtonMenu(
|
||||
ui.post { protonStage = label; protonPercent = value }
|
||||
}
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
||||
ui.post {
|
||||
protonProblem = problem
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
protonPercent = -1
|
||||
@@ -59,10 +71,12 @@ internal class ProtonMenu(
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
if (protonBusyId != null || SessionState.running) return
|
||||
protonBusyId = id
|
||||
protonProblem = null
|
||||
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
|
||||
if (tool.id == ProtonExtras.OWN && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true)
|
||||
ui.post {
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
@@ -94,9 +108,23 @@ internal class ProtonMenu(
|
||||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
|
||||
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
||||
protonBusyId = ProtonExtras.OWN
|
||||
protonProblem = null
|
||||
Thread({
|
||||
ProtonExtras.tidy(activity)
|
||||
val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
|
||||
ui.post {
|
||||
protonBusyId = null
|
||||
refreshProtons()
|
||||
if (tidied) ensureAutoUpdates()
|
||||
}
|
||||
}, "proton-tidy").start()
|
||||
return
|
||||
}
|
||||
val attempts = activity.getSharedPreferences("proton-auto-updates", android.content.Context.MODE_PRIVATE)
|
||||
val (tool, update) = ProtonExtras.tools.firstNotNullOfOrNull { tool ->
|
||||
val update = ProtonExtras.update(activity, tool) ?: return@firstNotNullOfOrNull null
|
||||
val update = ProtonExtras.update(activity, tool) ?: ProtonExtras.missing(activity, tool) ?: return@firstNotNullOfOrNull null
|
||||
val previous = attempts.getLong("${tool.id}.at", 0L)
|
||||
if (attempts.getString("${tool.id}.tag", null) != update || now - previous !in 0 until 15L * 60 * 1000) tool to update else null
|
||||
} ?: return
|
||||
|
||||
@@ -9,6 +9,7 @@ import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.database.ContentObserver
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
@@ -67,6 +68,7 @@ import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.input.EvdevKeys
|
||||
import com.droiddeck.launcher.input.HomeGuideInput
|
||||
import com.droiddeck.launcher.input.InputSpace
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
@@ -75,8 +77,10 @@ import com.droiddeck.launcher.input.OnScreenControls
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PadMouse
|
||||
import com.droiddeck.launcher.input.PadState
|
||||
import com.droiddeck.launcher.input.ScreenKeys
|
||||
import com.droiddeck.launcher.input.SteamControllerBle
|
||||
import com.droiddeck.launcher.input.DirectTouchHold
|
||||
import com.droiddeck.launcher.input.GestureTouchStreamGate
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplays
|
||||
@@ -155,6 +159,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var sessionOverlay: ComposeView
|
||||
private lateinit var loading: LoadingState
|
||||
private lateinit var hud: PerfHud
|
||||
private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud
|
||||
private var padBridge: PadBridge? = null
|
||||
private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null
|
||||
private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null
|
||||
@@ -198,10 +203,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
|
||||
private var gestureGame: String? = null
|
||||
private var gestureSettingsOpen by mutableStateOf(false)
|
||||
private var screenKeyPickerOpen by mutableStateOf(false)
|
||||
private var screenKeyBind: List<Int>? = null
|
||||
private var screenKeyDir: Int? = null
|
||||
private var screenKeyTextFocus = false
|
||||
private var screenKeyEdit by mutableStateOf<com.droiddeck.launcher.input.ScreenKey?>(null)
|
||||
private var screenLayoutsOpen by mutableStateOf(false)
|
||||
private var screenKeysShown by mutableStateOf(true)
|
||||
private var screenLayoutNames by mutableStateOf(listOf<String>())
|
||||
private var screenKeys: ScreenKeys? = null
|
||||
private var recognizedGesture by mutableStateOf<TouchscreenGestures.Gesture?>(null)
|
||||
private var gesturePointerX = 0f
|
||||
private var gesturePointerY = 0f
|
||||
private var gesturePointerReady = false
|
||||
private val gestureTouchStreamGate = GestureTouchStreamGate()
|
||||
private val clearRecognizedGesture = Runnable { recognizedGesture = null }
|
||||
private val gestureKeysDown = mutableSetOf<Int>()
|
||||
private lateinit var scrollTouch: ScrollTouchGestures
|
||||
@@ -244,6 +259,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false }
|
||||
private val uiHandler = Handler(Looper.getMainLooper())
|
||||
private var pendingBackAction: Runnable? = null
|
||||
private val backQamInput = com.droiddeck.launcher.input.BackQamInput(
|
||||
setPressed = { padBridge?.setBackQamPressed(it) },
|
||||
onTap = { performBackAction(double = it) },
|
||||
doubleTapMs = { backDoubleTapMs.toLong() },
|
||||
onCancel = { padBridge?.cancelBackQam() },
|
||||
)
|
||||
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
|
||||
private var drawerDirectionDownTime = 0L
|
||||
private var drawerDirectionDeviceId = -1
|
||||
@@ -270,6 +291,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
private val resumeKeysDown = mutableSetOf<Pair<Int, Int>>()
|
||||
private val drawerShortcutKeysDown = mutableSetOf<Pair<Int, Int>>()
|
||||
|
||||
private var drawerOpen by mutableStateOf(false)
|
||||
private var quitFrom by mutableStateOf<androidx.compose.ui.geometry.Rect?>(null)
|
||||
@@ -280,6 +302,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var drawerDefaultProton by mutableStateOf<String?>(null)
|
||||
private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) }
|
||||
private var drawerGameProfileId by mutableStateOf<Long?>(null)
|
||||
|
||||
private fun noSteamSession(): Boolean = SessionState.mode == SessionService.MODE_RUN &&
|
||||
SessionState.program in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.EPIC)
|
||||
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
|
||||
private var drawerGameInventoryRevision = 0L
|
||||
private var drawerGameFexPresetSaving by mutableStateOf(false)
|
||||
@@ -301,8 +326,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
|
||||
private var drawerControllerActive by mutableStateOf(false)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var lowLatencyController by mutableStateOf(false)
|
||||
private var lowLatencyTouch by mutableStateOf(false)
|
||||
private var backDoubleTapMs by mutableStateOf(500)
|
||||
private var lowLatency by mutableStateOf(true)
|
||||
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
|
||||
private var pcKeyboardOpen by mutableStateOf(false)
|
||||
private var achievementsInFront by mutableStateOf<AchievementsInFront?>(null)
|
||||
@@ -409,6 +434,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
// A higher refresh rate allowed in Android's settings does not change the display while this window
|
||||
// still asks for a lower mode, so the mode is chosen again when the setting changes.
|
||||
private val refreshSettingObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
|
||||
override fun onChange(selfChange: Boolean) {
|
||||
applyOutputPacing()
|
||||
}
|
||||
}
|
||||
|
||||
private fun followPanelRefresh(displayId: Int) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val output = glassesScreen?.display
|
||||
@@ -430,6 +463,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
override fun onInputDeviceRemoved(deviceId: Int) {
|
||||
Log.i(TAG, "input device $deviceId disconnected")
|
||||
backQamInput.onDeviceRemoved(deviceId)
|
||||
joyConVr?.refresh()
|
||||
padBridge?.onDeviceRemoved(deviceId)
|
||||
if (::padMouse.isInitialized) padMouse.reset()
|
||||
@@ -481,11 +515,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
if (!SessionState.running) {
|
||||
SessionState.fpsLimit = SessionPrefs.fpsLimit(
|
||||
this, SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM),
|
||||
)
|
||||
}
|
||||
applyOutputPacing()
|
||||
if (!SessionState.running) SessionState.followScreen = followChoice()
|
||||
applyFollowOrientation(resources.configuration)
|
||||
@@ -516,6 +545,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam)
|
||||
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
|
||||
padBridge = bridge
|
||||
bridge.setOnChordInput(backQamInput::onChordInput)
|
||||
SessionState.padBridge = bridge
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
val vr = com.droiddeck.launcher.input.JoyConVr(this, File(filesDir, ".wayland-rt/${com.droiddeck.launcher.input.JoyConVr.FILE}")) { taken, released ->
|
||||
@@ -540,7 +570,28 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
uiHandler.removeCallbacks(cursorHide)
|
||||
cursorVisible = false
|
||||
}
|
||||
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) }
|
||||
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { controls ->
|
||||
controls.onTouchMiss = miss@{ event ->
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
|
||||
event.offsetLocation(controls.left - surfaceView.left.toFloat(), controls.top - surfaceView.top.toFloat())
|
||||
onTouchEvent(event)
|
||||
}
|
||||
root.addView(controls)
|
||||
}
|
||||
screenKeysShown = com.droiddeck.launcher.input.ControllerPrefs.screenKeysShown(this)
|
||||
screenKeys = ScreenKeys(this) { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) }.also { keys ->
|
||||
keys.onTouchMiss = miss@{ event ->
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
|
||||
event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat())
|
||||
onTouchEvent(event)
|
||||
}
|
||||
keys.onAdd = { screenKeyPickerOpen = true }
|
||||
keys.onSelect = { codes -> screenKeyEdit = screenKeys?.stateOf(codes) }
|
||||
keys.onEditingChanged = { if (!it) screenKeyEdit = null }
|
||||
keys.steamStyle = { steamTouchControls?.style }
|
||||
keys.visibility = if (screenKeysShown) View.VISIBLE else View.GONE
|
||||
root.addView(keys)
|
||||
}
|
||||
keyboard = KeyboardHost(this).also { root.addView(it) }
|
||||
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
|
||||
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener) {
|
||||
@@ -555,7 +606,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// game surface and on-screen buttons, in either finger-down order.
|
||||
root.isMotionEventSplittingEnabled = true
|
||||
surfaceView.setOnTouchListener { _, event ->
|
||||
routedTouchMode == SessionPrefs.TOUCH_GESTURES && onTouchEvent(event)
|
||||
if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
false
|
||||
} else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) {
|
||||
false
|
||||
} else onTouchEvent(event)
|
||||
}
|
||||
padMouse = PadMouse(padMouseListener)
|
||||
bridge.setTouchRoute(object : PadBridge.TouchRoute {
|
||||
@@ -579,17 +634,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val needResume = !needRuntime && com.droiddeck.launcher.runtime.DesktopCatalog.interrupted(this).isNotEmpty()
|
||||
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
|
||||
(repair || !com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this))
|
||||
val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM &&
|
||||
com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
|
||||
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
val protonUser = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM ||
|
||||
program == com.droiddeck.launcher.runtime.BattleNet.PROGRAM || program == com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN
|
||||
val needProton = protonUser && com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
|
||||
if (needRuntime || needResume || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton, needResume)
|
||||
}
|
||||
hud = PerfHud(this)
|
||||
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
|
||||
hud.onPresentingWindowChanged = {
|
||||
if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() }
|
||||
}
|
||||
if (SessionState.running && SessionState.firstFrameSeen) {
|
||||
loading.visible = false
|
||||
hud.start()
|
||||
memoryHud.start()
|
||||
}
|
||||
readPrefs()
|
||||
|
||||
@@ -684,7 +743,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
|
||||
CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density,
|
||||
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
||||
if (hud.text.isNotEmpty() || hud.graph.size >= 2) HudText(hud.text, hud.graph, hudColor, hudOpacity)
|
||||
val hudLines = listOf(hud.text, memoryHud.text).filter { it.isNotEmpty() }
|
||||
if (hudLines.isNotEmpty() || hud.graph.size >= 2)
|
||||
HudText(hudLines.joinToString("\n"), hud.graph, hudColor, hudOpacity)
|
||||
val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen
|
||||
if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking)
|
||||
if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) {
|
||||
@@ -739,7 +800,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
|
||||
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
|
||||
backQamInput.cancel()
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
|
||||
cancelTouchGestures()
|
||||
screenKeys?.stopEditing()
|
||||
}
|
||||
}
|
||||
com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture)
|
||||
@@ -748,6 +812,84 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onDismiss = { gestureSettingsOpen = false },
|
||||
onSaved = { gestureSettingsOpen = false; refreshGestureConfig() },
|
||||
)
|
||||
if (screenKeyPickerOpen) {
|
||||
val dir = screenKeyDir
|
||||
com.droiddeck.launcher.ui.ScreenKeyPicker(
|
||||
initial = if (dir != null) {
|
||||
listOfNotNull((screenKeyEdit?.codes?.getOrNull(dir) ?: 0).takeIf { it != 0 })
|
||||
} else {
|
||||
screenKeyBind ?: emptyList()
|
||||
},
|
||||
onDismiss = { screenKeyPickerOpen = false; screenKeyBind = null; screenKeyDir = null },
|
||||
onAdd = { codes ->
|
||||
val bind = screenKeyBind
|
||||
if (dir != null && bind != null) {
|
||||
screenKeys?.setDirection(bind, dir, codes.lastOrNull() ?: 0)?.let { screenKeyEdit = it }
|
||||
} else if (bind != null) {
|
||||
screenKeys?.setCodes(bind, codes)?.let { screenKeyEdit = it }
|
||||
} else {
|
||||
screenKeys?.add(codes)
|
||||
screenKeyEdit = screenKeys?.stateOf(codes)
|
||||
}
|
||||
screenKeyPickerOpen = false
|
||||
screenKeyBind = null
|
||||
screenKeyDir = null
|
||||
},
|
||||
)
|
||||
}
|
||||
screenKeyEdit?.let { key ->
|
||||
com.droiddeck.launcher.ui.ScreenKeyEditor(
|
||||
codes = key.codes, keyY = key.y,
|
||||
size = key.size, opacity = key.opacity, shape = key.shape, toggle = key.toggle,
|
||||
labels = key.labels,
|
||||
text = key.text, hasImage = key.image.isNotEmpty(),
|
||||
onResize = { screenKeys?.resize(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
|
||||
onOpacity = { screenKeys?.setOpacity(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
|
||||
onShape = { screenKeys?.setShape(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
|
||||
onToggle = { on -> screenKeys?.setToggle(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) },
|
||||
onLabels = { on -> screenKeys?.setLabels(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) },
|
||||
onDirection = { index -> screenKeyBind = key.codes; screenKeyDir = index; screenKeyPickerOpen = true },
|
||||
onText = { screenKeys?.setText(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
|
||||
onImage = { screenKeys?.setImage(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
|
||||
onClearImage = { screenKeys?.setImage(key.codes, ""); screenKeyEdit = screenKeys?.stateOf(key.codes) },
|
||||
onBind = { screenKeyBind = key.codes; screenKeyDir = null; screenKeyPickerOpen = true },
|
||||
onTextFocus = { screenKeyTextFocus = true; keyboard?.hide() },
|
||||
onTextBlur = { screenKeyTextFocus = false },
|
||||
onRemove = { screenKeys?.remove(key.codes); screenKeyEdit = null },
|
||||
onDismiss = { screenKeyEdit = null; screenKeyTextFocus = false; screenKeys?.deselect() },
|
||||
)
|
||||
}
|
||||
if (screenLayoutsOpen) com.droiddeck.launcher.ui.ScreenLayoutPanel(
|
||||
layouts = screenLayoutNames,
|
||||
onSave = { name ->
|
||||
screenKeys?.let { keys ->
|
||||
com.droiddeck.launcher.input.ControllerPrefs.saveScreenLayout(this@SessionActivity, name, keys.export())
|
||||
}
|
||||
screenLayoutNames = layoutNames()
|
||||
},
|
||||
onLoad = { name ->
|
||||
com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this@SessionActivity)[name]?.let { screenKeys?.load(it) }
|
||||
screenLayoutsOpen = false
|
||||
},
|
||||
onDelete = { name ->
|
||||
com.droiddeck.launcher.input.ControllerPrefs.deleteScreenLayout(this@SessionActivity, name)
|
||||
screenLayoutNames = layoutNames()
|
||||
},
|
||||
onImport = { text ->
|
||||
val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels
|
||||
val keys = com.droiddeck.launcher.input.importScreenLayout(text, width, resources.displayMetrics.density)
|
||||
if (keys != null) {
|
||||
screenKeys?.load(com.droiddeck.launcher.input.ControllerPrefs.encodeScreenKeys(keys))
|
||||
screenLayoutsOpen = false
|
||||
}
|
||||
},
|
||||
exportText = {
|
||||
val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels
|
||||
val keys = com.droiddeck.launcher.input.ControllerPrefs.decodeScreenKeys(screenKeys?.export().orEmpty())
|
||||
com.droiddeck.launcher.input.exportScreenLayout(keys, width, resources.displayMetrics.density)
|
||||
},
|
||||
onDismiss = { screenLayoutsOpen = false },
|
||||
)
|
||||
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
|
||||
if (drawerOpen) {
|
||||
syncLossless()
|
||||
@@ -794,6 +936,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
)
|
||||
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
|
||||
steam = SessionState.mode == SessionService.MODE_STEAM,
|
||||
direct = noSteamSession(),
|
||||
title = if (SessionState.mode == SessionService.MODE_RUN)
|
||||
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null,
|
||||
isHomeApp = isHomeApp,
|
||||
@@ -899,20 +1042,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
padType = id
|
||||
},
|
||||
backActionsInverted = backActionsInverted,
|
||||
backDoubleTapMs = backDoubleTapMs,
|
||||
onBackDoubleTapMs = { ms ->
|
||||
SessionPrefs.setBackDoubleTapMs(this@SessionActivity, ms)
|
||||
backDoubleTapMs = ms
|
||||
},
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
lowLatencyController = lowLatencyController,
|
||||
lowLatencyTouch = lowLatencyTouch,
|
||||
onLowLatencyController = { on ->
|
||||
SessionPrefs.setLowLatencyController(this@SessionActivity, on)
|
||||
lowLatencyController = on
|
||||
applyLowLatency()
|
||||
},
|
||||
onLowLatencyTouch = { on ->
|
||||
SessionPrefs.setLowLatencyTouch(this@SessionActivity, on)
|
||||
lowLatencyTouch = on
|
||||
lowLatency = lowLatency,
|
||||
onLowLatency = { on ->
|
||||
SessionPrefs.setLowLatency(this@SessionActivity, on)
|
||||
lowLatency = on
|
||||
applyLowLatency()
|
||||
},
|
||||
onOsc = { v ->
|
||||
@@ -938,6 +1080,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
},
|
||||
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
||||
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
|
||||
onScreenKeys = { drawerOpen = false; screenKeys?.startEditing() },
|
||||
screenKeysShown = screenKeysShown,
|
||||
onScreenKeysShown = { shown ->
|
||||
screenKeysShown = shown
|
||||
com.droiddeck.launcher.input.ControllerPrefs.setScreenKeysShown(this@SessionActivity, shown)
|
||||
screenKeys?.stopEditing()
|
||||
screenKeys?.visibility = if (shown) View.VISIBLE else View.GONE
|
||||
},
|
||||
onScreenLayouts = {
|
||||
drawerOpen = false
|
||||
screenLayoutNames = layoutNames()
|
||||
screenLayoutsOpen = true
|
||||
},
|
||||
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
||||
onSecondScreenMode = ::selectSecondScreenMode,
|
||||
onSecondScreenDisplay = ::selectSecondScreenDisplay,
|
||||
@@ -963,7 +1118,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
pipAutoEnter = on
|
||||
pip.refresh(true)
|
||||
},
|
||||
unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null,
|
||||
unfoldedControls = unfoldedControls,
|
||||
onUnfoldedControls = ::chooseUnfoldedControls,
|
||||
unfoldedControlsWithController = unfoldedControlsWithController,
|
||||
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
|
||||
@@ -1170,7 +1325,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
performBackAction(double = false)
|
||||
}
|
||||
pendingBackAction = pending
|
||||
uiHandler.postDelayed(pending, 500L)
|
||||
uiHandler.postDelayed(pending, backDoubleTapMs.toLong())
|
||||
}
|
||||
|
||||
private fun performBackAction(double: Boolean) {
|
||||
@@ -1183,7 +1338,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return
|
||||
incoming.action = null
|
||||
setIntent(incoming)
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
|
||||
if (SessionState.suspended) SessionService.resume(this)
|
||||
else if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
|
||||
}
|
||||
|
||||
|
||||
@@ -1248,6 +1404,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val activeAppId = AgentGuest.activeSteamAppId(this, installedAppIds)
|
||||
val selectedSteamAppId = runCatching { AgentGuest.selectedSteamAppId(this) }
|
||||
AgentGuest.selectedOrActiveInstalledSteamAppId(selectedSteamAppId, activeAppId, installedAppIds)
|
||||
?: SessionState.gameId?.toLongOrNull()
|
||||
?: refresh.requestedAppId
|
||||
} else {
|
||||
refresh.requestedAppId
|
||||
@@ -1494,15 +1651,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (nextTouchMode == SessionPrefs.TOUCH_OFF || !usingTouchpad()) cursorVisible = false
|
||||
}
|
||||
touchMode = nextTouchMode
|
||||
routedTouchMode = effectiveTouchMode()
|
||||
val nextRoutedTouchMode = effectiveTouchMode()
|
||||
if (routedTouchMode != nextRoutedTouchMode) gestureTouchStreamGate.reset()
|
||||
routedTouchMode = nextRoutedTouchMode
|
||||
frameGen = FrameGen.mode(this)
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
lowLatencyController = SessionPrefs.lowLatencyController(this)
|
||||
lowLatencyTouch = SessionPrefs.lowLatencyTouch(this)
|
||||
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
|
||||
lowLatency = SessionPrefs.lowLatency(this)
|
||||
padType = SessionPrefs.steamController(this)
|
||||
}
|
||||
|
||||
@@ -1533,10 +1692,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime"
|
||||
}
|
||||
if (problem == null && resume && !SessionState.stopRequested) {
|
||||
SessionState.installing = "package"
|
||||
if (activeInstallWorker === worker) SessionState.installing = "package"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "package.resuming", mapOf("component" to "package"))
|
||||
problem = com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, progressAsIs())
|
||||
?.let { getString(R.string.session_package_resume_failed, it) }
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
problem = try {
|
||||
com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, cancellation, progressAsIs())
|
||||
?.let { getString(R.string.session_package_resume_failed, it) }
|
||||
} finally {
|
||||
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||
}
|
||||
if (problem == null) SessionEvents.record("package.ready") else failedComponent = "package"
|
||||
}
|
||||
if (problem == null && desktop && !SessionState.stopRequested) {
|
||||
@@ -1681,9 +1846,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val driverId = if (CompositorHost.isStarted) null else turnip.install()
|
||||
|
||||
val previous = SessionState.outputSize
|
||||
val live = if (SessionState.followScreen && !isInPictureInPictureMode)
|
||||
com.droiddeck.launcher.session.SessionDisplay.followSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
||||
else null
|
||||
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
||||
val size = live ?: if (SessionState.running) previous else glassesOutputSize() ?: outputSize()
|
||||
SessionState.outputSize = size
|
||||
if (!SessionState.running) SessionState.refreshHz = refreshHz()
|
||||
@@ -1740,7 +1903,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
)
|
||||
onOutputAttached(holder)
|
||||
if (SessionState.running && size != previous) {
|
||||
Log.i(TAG, "follow screen: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
|
||||
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
|
||||
WaylandCompositor.nativeResizeOutput(size.first, size.second)
|
||||
}
|
||||
if (!SessionState.running) SessionEvents.record("compositor.started")
|
||||
@@ -1752,6 +1915,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
intent.getStringExtra(SessionService.EXTRA_STEAM_UI),
|
||||
intent.getStringExtra(SessionService.EXTRA_STEAM_URL),
|
||||
intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS),
|
||||
intent.getStringExtra(SessionService.EXTRA_GAME_ID),
|
||||
sessionActivityDisplayId,
|
||||
)
|
||||
}
|
||||
@@ -1771,15 +1935,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
cancelTouchGestures()
|
||||
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
|
||||
CompositorHost.resize(holder.surface) { applyFrameGen() }
|
||||
followWindow(width, height)
|
||||
resizeOutputForWindow(width, height)
|
||||
}
|
||||
}
|
||||
|
||||
private fun followWindow(width: Int, height: Int) {
|
||||
if (!SessionState.followScreen || isInPictureInPictureMode || !CompositorHost.isStarted) return
|
||||
val size = com.droiddeck.launcher.session.SessionDisplay.followSize(width, height) ?: return
|
||||
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
|
||||
if (isInPictureInPictureMode || width <= 0 || height <= 0) return null
|
||||
return if (SessionState.followScreen)
|
||||
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, controlsBelowWanted())
|
||||
else if (glassesScreen == null) outputSize() else null
|
||||
}
|
||||
|
||||
private fun resizeOutputForWindow(width: Int, height: Int) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val size = windowOutputSize(width, height) ?: return
|
||||
if (size == SessionState.outputSize) return
|
||||
Log.i(TAG, "follow screen: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
|
||||
Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
|
||||
SessionState.outputSize = size
|
||||
val panel = panelBounds()
|
||||
SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1)
|
||||
@@ -1793,11 +1964,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun applyFollowOrientation(config: android.content.res.Configuration) {
|
||||
val wanted = if (SessionState.followScreen && config.smallestScreenWidthDp >= 600) {
|
||||
android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER
|
||||
} else {
|
||||
SessionPrefs.orientation(this)
|
||||
}
|
||||
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp)
|
||||
if (requestedOrientation != wanted) requestedOrientation = wanted
|
||||
}
|
||||
|
||||
@@ -1809,6 +1976,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
cancelTouchGestures()
|
||||
applyFollowOrientation(newConfig)
|
||||
applyUnfoldedControls()
|
||||
resizeOutputForWindow(surfaceW, surfaceH)
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
@@ -1850,7 +2018,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
|
||||
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
|
||||
else SessionPrefs.resolutionChoice(this, mode, panel)
|
||||
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice)
|
||||
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice,
|
||||
SessionPrefs.portrait(this) && !controlsBelowWanted())
|
||||
}
|
||||
|
||||
private fun refreshHz(): Float {
|
||||
@@ -1868,7 +2037,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun mirrorRefreshLimit(): Int =
|
||||
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
|
||||
|
||||
private fun outputFpsLimit(): Int = GlassesRendering.fpsLimit(SessionState.fpsLimit, mirrorRefreshLimit())
|
||||
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit())
|
||||
|
||||
private fun applyOutputPacing() {
|
||||
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit()))
|
||||
@@ -1965,7 +2134,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile)
|
||||
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
showEnded(status, hint)
|
||||
@@ -1987,12 +2156,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
repairOffered = hint?.repair == true
|
||||
loading.showEnded(
|
||||
hint?.text ?: stopped,
|
||||
getString(R.string.session_ended_detail, status, SessionState.logFile?.path ?: getString(R.string.session_ended_no_log)),
|
||||
getString(R.string.session_ended_detail, status,
|
||||
SessionState.logFile?.path?.let { android.text.BidiFormatter.getInstance().unicodeWrap(it, android.text.TextDirectionHeuristics.LTR) }
|
||||
?: getString(R.string.session_ended_no_log)),
|
||||
)
|
||||
focusEndedScreen()
|
||||
}
|
||||
|
||||
private fun releasePads() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
|
||||
backQamInput.cancel()
|
||||
padBridge?.releaseAll()
|
||||
joyConVr?.releaseButtons()
|
||||
}
|
||||
@@ -2026,6 +2199,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return EndHint(resources.getQuantityString(R.plurals.session_end_runtime_damaged, broken.size, broken.size, broken.first()), repair = true)
|
||||
}
|
||||
|
||||
private fun prootFailureHint(): EndHint? {
|
||||
if (SessionState.failureCode != "PROOT_MISSING") return null
|
||||
val message = SessionState.failureMessage ?: return null
|
||||
return EndHint(message)
|
||||
}
|
||||
|
||||
private fun sessionEndHint(log: File?): EndHint? {
|
||||
if (log == null || !log.isFile) return null
|
||||
return try {
|
||||
@@ -2062,10 +2241,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
|
||||
val steamVolume =
|
||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
|
||||
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
|
||||
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
||||
!gestureSettingsOpen && !screenKeyTextFocus && window.decorView.hasWindowFocus()
|
||||
if (steamVolume) {
|
||||
val audio = getSystemService(android.media.AudioManager::class.java)
|
||||
if (com.droiddeck.launcher.input.SteamVolumeKeys.dispatch(event, !audio.isVolumeFixed) { direction ->
|
||||
audio.adjustStreamVolume(android.media.AudioManager.STREAM_MUSIC, direction, 0)
|
||||
}) return true
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
}
|
||||
val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
|
||||
!SessionState.suspended && padBridge?.canHoldQam() == true
|
||||
if (backQamInput.onKeyEvent(event, backToQam)) {
|
||||
pendingBackAction?.let(uiHandler::removeCallbacks)
|
||||
pendingBackAction = null
|
||||
return true
|
||||
}
|
||||
if (pipUi) return true
|
||||
if (screenKeyTextFocus) return super.dispatchKeyEvent(event)
|
||||
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
|
||||
if (pad !== event) return dispatchKeyEvent(pad)
|
||||
val fromController = PadBridge.isControllerKeyEvent(event)
|
||||
@@ -2087,6 +2287,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
val drawerShortcutKey = event.deviceId to event.keyCode
|
||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) &&
|
||||
((drawerOpen && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
drawerShortcutKeysDown.add(drawerShortcutKey)
|
||||
if (event.repeatCount == 0) {
|
||||
releaseDrawerDirection()
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT) sendSteamGuide() else triggerSteamQam()
|
||||
}
|
||||
} else if (event.action == KeyEvent.ACTION_UP) {
|
||||
drawerShortcutKeysDown.remove(drawerShortcutKey)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (drawerOpen) {
|
||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
@@ -2107,7 +2321,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return true
|
||||
}
|
||||
val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START ||
|
||||
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || event.keyCode == KeyEvent.KEYCODE_HOME
|
||||
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || HomeGuideInput.isHome(event.keyCode)
|
||||
val resumeKeyId = event.deviceId to event.keyCode
|
||||
if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
@@ -2178,6 +2392,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (pipUi) return true
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
drawerControllerActive = false
|
||||
gestureTouchStreamGate.reset()
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
@@ -2253,9 +2468,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
private fun layoutNames(): List<String> =
|
||||
com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this).keys.sorted()
|
||||
|
||||
private fun refreshGestureConfig() {
|
||||
gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame)
|
||||
gestureTouchStreamGate.reset()
|
||||
if (::touchscreenGestures.isInitialized) touchscreenGestures.configure(gestureConfig)
|
||||
if (::directTouchHold.isInitialized) directTouchHold.configure(gestureConfig)
|
||||
gesturePointerReady = false
|
||||
recognizedGesture = null
|
||||
}
|
||||
@@ -2543,23 +2763,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun refreshControls() {
|
||||
applyUnfoldedControls()
|
||||
updateOnScreenControls()
|
||||
screenKeys?.refreshAppearance()
|
||||
}
|
||||
|
||||
private fun controlsBelowWanted(): Boolean {
|
||||
if (!::sessionRoot.isInitialized || glassesScreen != null || cardboard.enabled) return false
|
||||
return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height,
|
||||
pipUi || isInPictureInPictureMode)
|
||||
}
|
||||
|
||||
private fun applyUnfoldedControls() {
|
||||
if (!::sessionRoot.isInitialized) return
|
||||
val width = sessionRoot.width
|
||||
val height = sessionRoot.height
|
||||
val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted(
|
||||
enabled = unfoldedControls,
|
||||
foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this),
|
||||
controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected,
|
||||
keepWithController = unfoldedControlsWithController,
|
||||
steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad,
|
||||
pip = pipUi || isInPictureInPictureMode,
|
||||
width = width,
|
||||
height = height,
|
||||
smallestWidthDp = resources.configuration.smallestScreenWidthDp,
|
||||
)
|
||||
val wanted = controlsBelowWanted()
|
||||
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height)
|
||||
else FrameLayout.LayoutParams.MATCH_PARENT
|
||||
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
|
||||
@@ -2569,13 +2786,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
else "unfolded controls: game full screen")
|
||||
}
|
||||
var panel = unfoldedPanel
|
||||
if (panel != null && panel.deckControls != SessionState.deckPad) {
|
||||
sessionRoot.removeView(panel)
|
||||
unfoldedPanel = null
|
||||
panel = null
|
||||
}
|
||||
if (!wanted) {
|
||||
if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() }
|
||||
return
|
||||
}
|
||||
if (panel == null) {
|
||||
panel = com.droiddeck.launcher.ui.DeckControlsPanel(this, onClose = { chooseUnfoldedControls(false) },
|
||||
onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge)
|
||||
onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge,
|
||||
portraitDock = !com.droiddeck.launcher.session.SessionDisplay.foldable(this))
|
||||
sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1)
|
||||
unfoldedPanel = panel
|
||||
updateOnScreenControls()
|
||||
@@ -2628,6 +2851,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (::scrollTouch.isInitialized) scrollTouch.cancel()
|
||||
if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||
if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false
|
||||
gestureTouchStreamGate.reset()
|
||||
routedTouchMode = next
|
||||
}
|
||||
|
||||
@@ -2818,6 +3042,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
device.plugged = false
|
||||
uiHandler.postDelayed({ updateOnScreenControls() }, 700)
|
||||
}
|
||||
view.onStyle = { screenKeys?.refreshAppearance() }
|
||||
view.onTouchMiss = miss@{ event ->
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
|
||||
event.offsetLocation(view.left - surfaceView.left.toFloat(), view.top - surfaceView.top.toFloat())
|
||||
onTouchEvent(event)
|
||||
}
|
||||
root.addView(view, root.indexOfChild(onScreenControls) + 1)
|
||||
steamTouchControls = view
|
||||
steamTouchAvailable = true
|
||||
@@ -2848,6 +3078,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
controls.visibility = View.GONE
|
||||
steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE }
|
||||
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
|
||||
screenKeys?.followSteam = false
|
||||
applyTouchRouting()
|
||||
return
|
||||
}
|
||||
@@ -2876,6 +3107,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onScreenButtonsVisible = show
|
||||
val drawn = show && !keyboardCoversPad()
|
||||
if (steam != null) {
|
||||
screenKeys?.followSteam = drawn
|
||||
if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE }
|
||||
if (!drawn) steam.releaseAll()
|
||||
steam.visibility = if (drawn) View.VISIBLE else View.GONE
|
||||
@@ -2884,6 +3116,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden")
|
||||
return
|
||||
}
|
||||
screenKeys?.followSteam = false
|
||||
if (drawn == (controls.visibility == View.VISIBLE)) return
|
||||
if (!drawn) controls.releaseAll()
|
||||
controls.visibility = if (drawn) View.VISIBLE else View.GONE
|
||||
@@ -2969,6 +3202,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
pendingBackAction = null
|
||||
releaseDrawerDirection()
|
||||
onScreenControls?.releaseAll()
|
||||
screenKeys?.releaseAll()
|
||||
releasePads()
|
||||
touchpad.cancel()
|
||||
scrollTouch.cancel()
|
||||
@@ -3005,7 +3239,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
|
||||
super.onPictureInPictureModeChanged(inPip, newConfig)
|
||||
if (::pip.isInitialized) pip.changed(inPip)
|
||||
if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH)
|
||||
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
|
||||
applyUnfoldedControls()
|
||||
updateGlassesScreen()
|
||||
}
|
||||
@@ -3024,6 +3258,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = true
|
||||
refreshActivityDisplayId()
|
||||
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) {
|
||||
contentResolver.registerContentObserver(android.provider.Settings.System.getUriFor(name), false, refreshSettingObserver)
|
||||
}
|
||||
refreshSecondScreenDisplays()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
startedScreens++
|
||||
@@ -3038,6 +3275,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = false
|
||||
updateHandCamera()
|
||||
displayManager.unregisterDisplayListener(displayListener)
|
||||
contentResolver.unregisterContentObserver(refreshSettingObserver)
|
||||
closeSecondScreen(reset = false)
|
||||
startedScreens = (startedScreens - 1).coerceAtLeast(0)
|
||||
updateGlassesScreen()
|
||||
@@ -3081,6 +3319,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (!SessionState.suspended) pausedFrame = null
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
refreshHomeApp()
|
||||
if (::memoryHud.isInitialized && SessionState.running && SessionState.firstFrameSeen) memoryHud.refresh()
|
||||
if (intent?.action == SessionService.ACTION_RESUME) {
|
||||
intent.action = null
|
||||
SessionService.resume(this)
|
||||
@@ -3092,6 +3331,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onScreenControls?.reload()
|
||||
controllerSettings = ControllerPrefs.read(this)
|
||||
resumed = true
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this,
|
||||
enabled = {
|
||||
resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen &&
|
||||
!achievementsOpen && !gestureSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended &&
|
||||
SessionState.mode == SessionService.MODE_STEAM && padBridge != null
|
||||
},
|
||||
setPressed = { padBridge?.setHomeGuidePressed(it) },
|
||||
onCancel = { padBridge?.cancelHomeGuide() },
|
||||
)
|
||||
updatePointerCapture()
|
||||
if (!pipUi) sessionClipboard.start()
|
||||
updatePadMotion()
|
||||
@@ -3103,7 +3351,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
|
||||
if (runtimeRemovalBlocked) { super.onPause(); return }
|
||||
backQamInput.cancel()
|
||||
capturePausedFrame()
|
||||
sessionClipboard.stop()
|
||||
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
|
||||
@@ -3478,15 +3728,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun unbufferedSources() =
|
||||
if (lowLatencyTouch) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES
|
||||
if (lowLatency) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES
|
||||
|
||||
private fun applyLowLatency() {
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatencyController, lowLatencyTouch)
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatency)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) window.decorView.requestUnbufferedDispatch(unbufferedSources())
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
|
||||
if (!hasFocus) backQamInput.cancel()
|
||||
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
|
||||
if (runtimeRemovalBlocked) return
|
||||
if (!hasFocus) {
|
||||
@@ -3526,12 +3778,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionEvents.firstFrame()
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) SteamRepair.clientShown(this)
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
loading.visible = false
|
||||
hud.start()
|
||||
memoryHud.start()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
|
||||
backQamInput.cancel()
|
||||
steamVrRecovery.close()
|
||||
uiHandler.removeCallbacks(steamTouchRetry)
|
||||
if (runtimeRemovalBlocked) { super.onDestroy(); return }
|
||||
@@ -3545,6 +3801,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
glassesScreen?.let { screen -> glassesScreen = null; runCatching { screen.dismiss() } }
|
||||
headTracker?.stop()
|
||||
if (::hud.isInitialized) hud.stop()
|
||||
if (::memoryHud.isInitialized) memoryHud.stop()
|
||||
joyConVr?.close()
|
||||
joyConVr = null
|
||||
handCamera?.stop()
|
||||
|
||||
@@ -29,6 +29,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
private var pending: AppUpdates.Release? = null
|
||||
private var lastCheck = 0L
|
||||
private var request = 0
|
||||
@Volatile private var session = -1
|
||||
|
||||
fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission)
|
||||
|
||||
@@ -87,13 +88,14 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return }
|
||||
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
|
||||
error = null
|
||||
session = -1
|
||||
stage = activity.getString(R.string.upd_stage_downloading)
|
||||
percent = 0
|
||||
Thread({
|
||||
val result = runCatching {
|
||||
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
||||
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
|
||||
SelfInstaller.install(activity, file)
|
||||
SelfInstaller.install(activity, file) { id -> session = id }
|
||||
}
|
||||
result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } }
|
||||
}, "app-update-install").start()
|
||||
@@ -101,13 +103,15 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
|
||||
private val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1).let { it < 0 || it != session }) return
|
||||
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
|
||||
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
||||
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
|
||||
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
|
||||
if (confirm == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
|
||||
val safe = confirm?.let { SelfInstaller.safeConfirmIntent(activity, it) }
|
||||
if (safe == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
|
||||
stage = activity.getString(R.string.upd_stage_confirm)
|
||||
activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
if (runCatching { activity.startActivity(safe) }.isFailure) { stage = null; error = activity.getString(R.string.upd_not_offered) }
|
||||
}
|
||||
PackageInstaller.STATUS_SUCCESS -> stage = null
|
||||
else -> {
|
||||
|
||||
@@ -3,9 +3,13 @@ package com.droiddeck.launcher.agent
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
||||
import java.nio.file.StandardOpenOption.READ
|
||||
@@ -55,6 +59,9 @@ object AgentEnv {
|
||||
fun override(context: Context, name: String): JSONObject = synchronized(lock) {
|
||||
AgentAccess.requireCommands(context)
|
||||
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
|
||||
if (name == "libblfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) {
|
||||
throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library")
|
||||
}
|
||||
val source = File(inbox(context), name)
|
||||
if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file")
|
||||
if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first")
|
||||
@@ -67,6 +74,10 @@ object AgentEnv {
|
||||
staged.delete()
|
||||
throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
|
||||
}
|
||||
if (name == "libblfastpath.so" && !arm64SharedLibrary(staged)) {
|
||||
staged.delete()
|
||||
throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library")
|
||||
}
|
||||
if (!staged.setExecutable(true, false) || !staged.renameTo(target)) {
|
||||
staged.delete()
|
||||
throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs")
|
||||
@@ -76,6 +87,40 @@ object AgentEnv {
|
||||
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
|
||||
save(context, state)
|
||||
state.put("installed", "$GUEST_BIN/$name")
|
||||
if (name == "libblfastpath.so") {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
target.inputStream().use { input ->
|
||||
val buffer = ByteArray(65536)
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
digest.update(buffer, 0, count)
|
||||
}
|
||||
}
|
||||
state.put("sha256", digest.digest().joinToString("") { "%02x".format(it) })
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
fun fastPathLibrary(context: Context): String = synchronized(lock) {
|
||||
if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY
|
||||
if ("libblfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY
|
||||
val file = File(bin(context), "libblfastpath.so")
|
||||
if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY
|
||||
"$GUEST_BIN/libblfastpath.so"
|
||||
}
|
||||
|
||||
private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input ->
|
||||
val header = ByteArray(20)
|
||||
var count = 0
|
||||
while (count < header.size) {
|
||||
val read = input.read(header, count, header.size - count)
|
||||
if (read < 0) return@use false
|
||||
count += read
|
||||
}
|
||||
header.take(7) == listOf<Byte>(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1) &&
|
||||
header[16] == 3.toByte() && header[17] == 0.toByte() &&
|
||||
header[18] == 183.toByte() && header[19] == 0.toByte()
|
||||
}
|
||||
|
||||
fun beginSession(context: Context): List<String> = synchronized(lock) {
|
||||
@@ -86,13 +131,13 @@ object AgentEnv {
|
||||
val state = load(context)
|
||||
val active = strings(state.optJSONArray("pending"))
|
||||
val overrides = strings(state.optJSONArray("pendingOverrides"))
|
||||
state.put("active", JSONArray(active)).put("pending", JSONArray())
|
||||
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
|
||||
save(context, state)
|
||||
bin(context).listFiles()
|
||||
?.filter { it.name !in overrides }?.forEach { it.delete() }
|
||||
val lines = strings(state.optJSONArray("persistent")) + active
|
||||
val withPath = if (overrides.isEmpty()) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
|
||||
val withPath = if (overrides.none { it != "libblfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
|
||||
state.put("active", JSONArray(active)).put("pending", JSONArray())
|
||||
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
|
||||
save(context, state)
|
||||
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
|
||||
withPath
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
object BackgroundAppLimit {
|
||||
private const val TAG = "BackgroundAppLimit"
|
||||
const val OFF = -1
|
||||
val CHOICES = listOf(OFF, 4, 1, 0)
|
||||
private const val KEY = "max_cached_processes"
|
||||
private const val STATE = "background-app-limit"
|
||||
private const val APPLIED = "applied"
|
||||
private const val PREVIOUS = "previous"
|
||||
|
||||
private val worker = Executors.newSingleThreadExecutor { Thread(it, "background-app-limit").apply { isDaemon = true } }
|
||||
|
||||
internal fun readCommand() = "device_config get activity_manager $KEY"
|
||||
internal fun setCommand(limit: Int): String {
|
||||
require(limit in 0..1024)
|
||||
return "device_config put activity_manager $KEY $limit"
|
||||
}
|
||||
internal fun restoreCommand(previous: String?) =
|
||||
if (previous == null) "device_config delete activity_manager $KEY" else "device_config put activity_manager $KEY $previous"
|
||||
|
||||
internal fun parse(output: String): String? = output.trim().takeIf { it.toIntOrNull() != null }
|
||||
|
||||
private fun state(context: Context) = context.applicationContext.getSharedPreferences(STATE, Context.MODE_PRIVATE)
|
||||
|
||||
fun applied(context: Context): Boolean = state(context).getBoolean(APPLIED, false)
|
||||
|
||||
fun applyAsync(context: Context, limit: Int) {
|
||||
val app = context.applicationContext
|
||||
worker.execute {
|
||||
runCatching {
|
||||
if (!applied(app)) {
|
||||
val previous = parse(WirelessAdbFix.shell(app, readCommand()))
|
||||
check(state(app).edit().putBoolean(APPLIED, true).putString(PREVIOUS, previous).commit()) { "previous value not saved" }
|
||||
}
|
||||
WirelessAdbFix.shell(app, setCommand(limit))
|
||||
}.onSuccess { Log.i(TAG, "at most $limit cached app(s) while the session runs") }
|
||||
.onFailure { Log.w(TAG, "limit not set: ${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
fun restoreAsync(context: Context) {
|
||||
val app = context.applicationContext
|
||||
worker.execute {
|
||||
if (!applied(app)) return@execute
|
||||
val previous = state(app).getString(PREVIOUS, null)
|
||||
runCatching { WirelessAdbFix.shell(app, restoreCommand(previous)) }
|
||||
.onSuccess {
|
||||
state(app).edit().putBoolean(APPLIED, false).remove(PREVIOUS).commit()
|
||||
Log.i(TAG, "cached-app limit put back (${previous ?: "Android's own"})")
|
||||
}
|
||||
.onFailure { Log.w(TAG, "limit not put back yet: ${it.message}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,8 +256,13 @@ object DeviceReport {
|
||||
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
|
||||
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
||||
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
||||
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
|
||||
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
|
||||
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
|
||||
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
|
||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.core
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.Proxy
|
||||
import java.net.URL
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.CountDownLatch
|
||||
@@ -20,6 +22,7 @@ object DownloadSource {
|
||||
private const val KEY_MODE = "mode"
|
||||
private const val KEY_MIRROR = "mirror"
|
||||
private const val KEY_CUSTOM = "custom"
|
||||
private const val KEY_PROXY = "proxy"
|
||||
private const val KEY_FASTEST = "fastest"
|
||||
|
||||
private const val PROBE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/README.md"
|
||||
@@ -175,6 +178,22 @@ object DownloadSource {
|
||||
prefs(context)?.edit()?.putString(KEY_CUSTOM, normalizePrefix(prefix))?.apply()
|
||||
}
|
||||
|
||||
fun proxyHostPort(context: Context): String = prefs(context)?.getString(KEY_PROXY, "") ?: ""
|
||||
|
||||
fun setProxy(context: Context, value: String) {
|
||||
prefs(context)?.edit()?.putString(KEY_PROXY, normalizeProxy(value))?.apply()
|
||||
}
|
||||
|
||||
/** An HTTP proxy every Downloader connection uses, or null when none is configured. */
|
||||
fun httpProxy(): Proxy? = proxyOf(prefs()?.getString(KEY_PROXY, "") ?: "")
|
||||
|
||||
internal fun proxyOf(value: String): Proxy? {
|
||||
val host = value.substringBefore(':')
|
||||
val port = value.substringAfter(':', "").toIntOrNull() ?: return null
|
||||
if (host.isEmpty()) return null
|
||||
return Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port))
|
||||
}
|
||||
|
||||
fun reset(context: Context) {
|
||||
lastGood = null
|
||||
prefs(context)?.edit()?.clear()?.apply()
|
||||
@@ -205,4 +224,11 @@ object DownloadSource {
|
||||
if (trimmed.isEmpty() || trimmed.startsWith("http://")) return ""
|
||||
return if (trimmed.startsWith("https://")) trimmed else "https://$trimmed"
|
||||
}
|
||||
|
||||
internal fun normalizeProxy(value: String): String {
|
||||
val trimmed = value.trim().removePrefix("http://").trimEnd('/')
|
||||
val host = trimmed.substringBefore(':')
|
||||
val port = trimmed.substringAfter(':', "").toIntOrNull() ?: 0
|
||||
return if (host.isNotEmpty() && port in 1..65535) "$host:$port" else ""
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.Proxy;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
@@ -151,11 +152,16 @@ public final class Downloader {
|
||||
// A cancel is not a source failure: no other mirror, and no DownloadSource.failed().
|
||||
if (outcome == Outcome.CANCELLED) return false;
|
||||
if (outcome == Outcome.DONE) {
|
||||
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
if (!discardPartial(destination, identity)) return false;
|
||||
continue;
|
||||
if (expectedSha256 != null) {
|
||||
String actualSha256 = Hashes.sha256(destination);
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
if (!discardPartial(destination, identity)) return false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (isCancelled(cancelled)) return false;
|
||||
resumeFile(destination).delete();
|
||||
DownloadSource.INSTANCE.succeeded(source);
|
||||
if (progress != null) progress.accept(1f);
|
||||
@@ -384,7 +390,10 @@ public final class Downloader {
|
||||
}
|
||||
|
||||
private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
// An explicit Proxy routes the connection through the app setting instead of the system-wide proxy.
|
||||
Proxy proxy = DownloadSource.INSTANCE.httpProxy();
|
||||
HttpURLConnection connection = (HttpURLConnection) (proxy != null
|
||||
? new URL(url).openConnection(proxy) : new URL(url).openConnection());
|
||||
connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
|
||||
connection.setReadTimeout(readTimeoutMs);
|
||||
connection.setInstanceFollowRedirects(true);
|
||||
|
||||
@@ -14,6 +14,8 @@ object GameEnvironmentOptions {
|
||||
Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")),
|
||||
Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("PROTON_DXVK_D3D8", "1", R.string.game_env_dxvk_d3d8, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("WINE_D3D_CONFIG", "renderer=vulkan", R.string.game_env_wined3d_renderer, Type.CHOICE, listOf("renderer=vulkan", "renderer=gl")),
|
||||
Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")),
|
||||
@@ -32,6 +34,7 @@ object GameEnvironmentOptions {
|
||||
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
|
||||
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
|
||||
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
|
||||
Option("DROIDDECK_GAME_CORES", "", R.string.game_env_cores, Type.TEXT),
|
||||
Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("WINEDLLOVERRIDES", "", 0, Type.TEXT),
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -8,7 +8,11 @@ object HostProcess {
|
||||
private const val TAG = "HostProcess"
|
||||
|
||||
@JvmStatic
|
||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int {
|
||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int =
|
||||
start(command, env, dir, onExit, onLine, null)
|
||||
|
||||
@JvmStatic
|
||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?): Int {
|
||||
val argv = split(command)
|
||||
if (argv.isEmpty()) return -1
|
||||
return try {
|
||||
@@ -19,7 +23,10 @@ object HostProcess {
|
||||
if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1)
|
||||
}
|
||||
builder.redirectErrorStream(true)
|
||||
if (onLine == null) builder.redirectOutput(File("/dev/null"))
|
||||
if (onLine == null) {
|
||||
if (outputFile == null) builder.redirectOutput(File("/dev/null"))
|
||||
else builder.redirectOutput(ProcessBuilder.Redirect.appendTo(outputFile))
|
||||
}
|
||||
val process = builder.start()
|
||||
val pid = pidOf(process)
|
||||
Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)")
|
||||
|
||||
@@ -76,7 +76,7 @@ object LogRedactor {
|
||||
|
||||
private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
|
||||
private val ACCOUNT_KV = Regex(
|
||||
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|user[_-]?name|epicusername)" +
|
||||
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|account[_-]?id|user[_-]?name|epicusername)" +
|
||||
"([\"']?\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
|
||||
)
|
||||
private val LOGIN_KV = Regex(
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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) })
|
||||
}
|
||||
}
|
||||
@@ -182,25 +182,47 @@ object WirelessAdbFix {
|
||||
}
|
||||
|
||||
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
|
||||
withSavedPairing(context) { appContext, host, port -> setChildProcessLimit(appContext, host, port, enabled) }
|
||||
}
|
||||
|
||||
fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
|
||||
|
||||
fun clearCachedApps(context: Context) {
|
||||
shell(context, "am kill-all")
|
||||
}
|
||||
|
||||
fun shell(context: Context, command: String): String {
|
||||
var output = ""
|
||||
withSavedPairing(context) { appContext, host, port ->
|
||||
loadOrCreateIdentity(appContext)
|
||||
Kadb.create(host, port).use { adb ->
|
||||
val result = adb.shell(command)
|
||||
check(result.exitCode == 0) { result.allOutput.ifBlank { appContext.getString(R.string.adbfix_command_failed, result.exitCode) } }
|
||||
output = result.output
|
||||
}
|
||||
saveConnection(appContext, host, port)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
private fun withSavedPairing(context: Context, action: (Context, String, Int) -> Unit) {
|
||||
val appContext = context.applicationContext
|
||||
val saved = savedConnection(appContext)
|
||||
?: error(appContext.getString(R.string.adbfix_no_pairing))
|
||||
val cachedPort = saved.port
|
||||
if (cachedPort != null) {
|
||||
val cachedResult = runCatching {
|
||||
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
|
||||
}
|
||||
val cachedResult = runCatching { action(appContext, saved.host, cachedPort) }
|
||||
if (cachedResult.isSuccess) return
|
||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||
if (discoveredPort != null && discoveredPort != cachedPort) {
|
||||
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||
action(appContext, saved.host, discoveredPort)
|
||||
} else {
|
||||
cachedResult.getOrThrow()
|
||||
}
|
||||
} else {
|
||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||
?: error(appContext.getString(R.string.adbfix_enter_address))
|
||||
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||
action(appContext, saved.host, discoveredPort)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
@@ -19,6 +23,7 @@ import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
@@ -50,7 +55,7 @@ import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.SportsEsports
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -70,6 +75,7 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
@@ -99,7 +105,9 @@ import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.util.Date
|
||||
|
||||
private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK }
|
||||
private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK, UP }
|
||||
|
||||
private const val HISTORY_LIMIT = 50
|
||||
|
||||
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
|
||||
currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
||||
@@ -193,10 +201,17 @@ fun FileManagerScreen(
|
||||
var favTick by remember { mutableIntStateOf(0) }
|
||||
|
||||
var listingJob by remember { mutableStateOf<Job?>(null) }
|
||||
val history = remember { mutableStateListOf<Pair<File, File>>() }
|
||||
var shownRoot by remember { mutableStateOf(initialRoot) }
|
||||
|
||||
fun loadDirectory(dir: File, resetScroll: Boolean = true) {
|
||||
fun loadDirectory(dir: File, resetScroll: Boolean = true, record: Boolean = true) {
|
||||
if (cancellingNavigation) return
|
||||
if (record && dir != currentDir) {
|
||||
history.add(currentDir to shownRoot)
|
||||
if (history.size > HISTORY_LIMIT) history.removeAt(0)
|
||||
}
|
||||
currentDir = dir
|
||||
shownRoot = currentRoot
|
||||
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
|
||||
listingJob?.cancel()
|
||||
listingJob = scope.launch {
|
||||
@@ -251,6 +266,18 @@ fun FileManagerScreen(
|
||||
FileManagerNavigation.EXIT -> onExit?.invoke()
|
||||
FileManagerNavigation.RETURN_TO_START -> returnToStart()
|
||||
FileManagerNavigation.BACK -> {
|
||||
if (showFavorites) showFavorites = false
|
||||
else {
|
||||
while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
|
||||
val previous = history.removeLastOrNull()
|
||||
if (previous != null) {
|
||||
currentRoot = previous.second
|
||||
loadDirectory(previous.first, record = false)
|
||||
} else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) }
|
||||
else onExit?.invoke()
|
||||
}
|
||||
}
|
||||
FileManagerNavigation.UP -> {
|
||||
if (showFavorites) showFavorites = false
|
||||
else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it) }
|
||||
else onExit?.invoke()
|
||||
@@ -263,7 +290,7 @@ fun FileManagerScreen(
|
||||
if (isOperationActive()) pendingNavigation = action else navigate(action)
|
||||
}
|
||||
|
||||
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot) {
|
||||
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
|
||||
requestNavigation(FileManagerNavigation.BACK)
|
||||
}
|
||||
|
||||
@@ -296,10 +323,10 @@ fun FileManagerScreen(
|
||||
navigate(action)
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.fm_accept)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_accept)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { pendingNavigation = null }) {
|
||||
TextButton(onClick = { pendingNavigation = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.fm_decline))
|
||||
}
|
||||
},
|
||||
@@ -487,15 +514,16 @@ fun FileManagerScreen(
|
||||
onValueChange = { folderName = it },
|
||||
label = { Text(stringResource(R.string.fm_folder_name)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
showNewFolderDialog = false
|
||||
if (folderName.isNotBlank()) createFolder(currentDir, folderName)
|
||||
}) { Text(stringResource(R.string.fm_create)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_create)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -510,6 +538,7 @@ fun FileManagerScreen(
|
||||
onValueChange = { newName = it },
|
||||
label = { Text(stringResource(R.string.fm_new_name)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
@@ -517,9 +546,9 @@ fun FileManagerScreen(
|
||||
val file = renameTarget
|
||||
renameTarget = null
|
||||
if (file != null && newName.isNotBlank()) performRename(file, newName)
|
||||
}) { Text(stringResource(R.string.fm_rename)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_rename)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { renameTarget = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { renameTarget = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -541,9 +570,9 @@ fun FileManagerScreen(
|
||||
TextButton(onClick = {
|
||||
selectedEntry = null
|
||||
performDelete(file)
|
||||
}) { Text(stringResource(R.string.common_delete)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { selectedEntry = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -589,9 +618,9 @@ fun FileManagerScreen(
|
||||
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -614,6 +643,7 @@ fun FileManagerScreen(
|
||||
androidx.compose.material3.Checkbox(
|
||||
checked = conflictApplyToAll,
|
||||
onCheckedChange = { conflictApplyToAll = it },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp)
|
||||
}
|
||||
@@ -626,7 +656,7 @@ fun FileManagerScreen(
|
||||
ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip),
|
||||
).forEach { (choice, label) ->
|
||||
TextButton(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier.fillMaxWidth().focusGlide(CircleShape),
|
||||
onClick = { conflictChoice = choice; pendingConflict = null },
|
||||
) { Text(label, modifier = Modifier.fillMaxWidth()) }
|
||||
}
|
||||
@@ -634,13 +664,14 @@ fun FileManagerScreen(
|
||||
},
|
||||
confirmButton = {},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) {
|
||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
||||
Text(
|
||||
@@ -659,7 +690,7 @@ fun FileManagerScreen(
|
||||
onClick = { onPick?.invoke(currentDir) },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp).focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
@@ -671,9 +702,10 @@ fun FileManagerScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.surfaceContainer)
|
||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.BACK) }, enabled = canGoUp && !cancellingNavigation) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
|
||||
@@ -722,6 +754,7 @@ fun FileManagerScreen(
|
||||
).show()
|
||||
}
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
linuxRoot?.let { root ->
|
||||
@@ -732,6 +765,7 @@ fun FileManagerScreen(
|
||||
Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
},
|
||||
onClick = { showDriveMenu = false; openDrive(root) },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -747,10 +781,10 @@ fun FileManagerScreen(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
||||
)
|
||||
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (!compactToolbar) Spacer(Modifier.weight(1f))
|
||||
} else {
|
||||
Text(
|
||||
text = currentDir.name.ifBlank { currentDir.absolutePath },
|
||||
@@ -759,12 +793,12 @@ fun FileManagerScreen(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
if (launchDir != null) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
|
||||
@@ -776,7 +810,7 @@ fun FileManagerScreen(
|
||||
onClick = { showNewFolderDialog = true },
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
|
||||
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
|
||||
modifier = Modifier.height(32.dp),
|
||||
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(5.dp))
|
||||
@@ -786,18 +820,18 @@ fun FileManagerScreen(
|
||||
IconButton(onClick = {
|
||||
gridView = !gridView
|
||||
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
|
||||
}) {
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
||||
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) {
|
||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { showSortMenu = true }) {
|
||||
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
|
||||
@@ -814,6 +848,7 @@ fun FileManagerScreen(
|
||||
showSortMenu = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
||||
@@ -824,6 +859,7 @@ fun FileManagerScreen(
|
||||
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
|
||||
showSortMenu = false
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
|
||||
@@ -833,12 +869,13 @@ fun FileManagerScreen(
|
||||
showSortMenu = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
IconButton(onClick = { showFavorites = !showFavorites }) {
|
||||
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
if (showFavorites) {
|
||||
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
|
||||
} else {
|
||||
@@ -846,7 +883,7 @@ fun FileManagerScreen(
|
||||
}
|
||||
}
|
||||
if (!pickMode && onExit != null) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
@@ -858,7 +895,7 @@ fun FileManagerScreen(
|
||||
onValueChange = { searchQuery = it },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.fm_filter_folder), fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).focusGlide(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -896,13 +933,14 @@ fun FileManagerScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f))
|
||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.fm_selected_count, selectedPaths.size),
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontSize = 13.sp,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.padding(end = 12.dp) else Modifier.weight(1f),
|
||||
)
|
||||
val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths }
|
||||
val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths }
|
||||
@@ -913,6 +951,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -924,6 +963,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = emptySet()
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -935,6 +975,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = emptySet()
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -942,11 +983,13 @@ fun FileManagerScreen(
|
||||
onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } },
|
||||
contentPadding = selBarPadding,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
onClick = { selectionMode = false; selectedPaths = emptySet() },
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) }
|
||||
}
|
||||
}
|
||||
@@ -968,7 +1011,7 @@ fun FileManagerScreen(
|
||||
if (isCutOperation) stringResource(R.string.fm_paste_move_here, what) else stringResource(R.string.fm_paste_here, what),
|
||||
color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) {
|
||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
@@ -999,7 +1042,7 @@ fun FileManagerScreen(
|
||||
isOperationRunning = false
|
||||
operationDeterminate = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
}) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
@@ -1089,7 +1132,7 @@ fun FileManagerScreen(
|
||||
contentPadding = PaddingValues(8.dp),
|
||||
) {
|
||||
if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) {
|
||||
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) })
|
||||
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) })
|
||||
}
|
||||
items(shownEntries, key = { it.absolutePath }) { file ->
|
||||
val isFav = remember(file.absolutePath, favTick) {
|
||||
@@ -1155,7 +1198,7 @@ fun FileManagerScreen(
|
||||
} else
|
||||
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
|
||||
if (canGoUp) item(key = "..") {
|
||||
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) })
|
||||
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) })
|
||||
}
|
||||
if (entries.isEmpty()) {
|
||||
item {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -29,6 +29,50 @@ object StorageRoots {
|
||||
val seeds = LinkedHashSet<File>()
|
||||
}
|
||||
|
||||
private val EXTERNAL_MOUNT_TYPES = setOf(
|
||||
"vfat", "exfat", "texfat", "ntfs", "ntfs3", "fuseblk", "fuse", "sdcardfs",
|
||||
)
|
||||
|
||||
internal data class MountPoint(val target: File, val type: String)
|
||||
|
||||
internal fun parseMountPoints(mounts: String): List<MountPoint> {
|
||||
val out = ArrayList<MountPoint>()
|
||||
for (line in mounts.lineSequence()) {
|
||||
val parts = line.split(' ')
|
||||
if (parts.size < 3) continue
|
||||
out.add(MountPoint(File(parts[1].replace("\\040", " ")), parts[2].lowercase()))
|
||||
}
|
||||
return out.distinct()
|
||||
}
|
||||
|
||||
internal fun isExternalMount(mount: MountPoint): Boolean {
|
||||
val path = mount.target.path
|
||||
val name = when {
|
||||
path.startsWith("/storage/") -> path.removePrefix("/storage/")
|
||||
path.startsWith("/mnt/media_rw/") -> path.removePrefix("/mnt/media_rw/")
|
||||
path.startsWith("/mnt/") -> path.removePrefix("/mnt/")
|
||||
else -> return false
|
||||
}
|
||||
if ('/' in name || name.isEmpty() || name == "emulated" || name == "self") return false
|
||||
if (mount.type in EXTERNAL_MOUNT_TYPES) {
|
||||
if (path.startsWith("/mnt/") && !path.startsWith("/mnt/media_rw/")) {
|
||||
val lower = name.lowercase()
|
||||
if (!lower.contains("usb") && !lower.contains("otg") &&
|
||||
!lower.contains("udisk") && !lower.contains("disk")
|
||||
) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
// vold-managed locations only hold removable volumes, whatever the fstype is.
|
||||
return path.startsWith("/storage/") || path.startsWith("/mnt/media_rw/")
|
||||
}
|
||||
|
||||
internal fun parseExternalMounts(mounts: String): List<File> =
|
||||
parseMountPoints(mounts).filter(::isExternalMount).map { it.target }
|
||||
|
||||
fun externalMounts(): List<File> =
|
||||
runCatching { parseExternalMounts(File("/proc/mounts").readText()) }.getOrDefault(emptyList())
|
||||
|
||||
fun list(context: Context): List<StorageRoot> {
|
||||
val volumes = LinkedHashMap<String, Volume>()
|
||||
|
||||
@@ -44,21 +88,31 @@ object StorageRoots {
|
||||
val storageManager = context.getSystemService(StorageManager::class.java)
|
||||
|
||||
storageManager?.storageVolumes.orEmpty()
|
||||
.filter { isMounted(it.state) }
|
||||
.forEach { volume ->
|
||||
.filter { present(it.state) }
|
||||
.forEachIndexed { index, volume ->
|
||||
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
|
||||
val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: return@forEach)
|
||||
val dirName = volume.directory?.name?.takeIf { it.isNotBlank() }
|
||||
// Unmounted volumes often report neither uuid nor directory; never drop the
|
||||
// volume or a plugged-in drive stays invisible with no explanation.
|
||||
val descSlug = volume.getDescription(context)?.trim()
|
||||
?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
||||
?.replace(Regex("[^A-Za-z0-9._-]+"), "-")
|
||||
val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: dirName ?: descSlug ?: "volume-$index")
|
||||
entry.removable = !volume.isPrimary && volume.isRemovable
|
||||
if (entry.label == null) entry.label = labelFor(context, volume, uuid)
|
||||
if (entry.label == null) entry.label = labelFor(context, volume, uuid ?: dirName ?: descSlug)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
volume.directory?.let { entry.candidates += it }
|
||||
}
|
||||
if (uuid != null) {
|
||||
entry.candidates += File("/storage/$uuid")
|
||||
entry.candidates += File("/mnt/media_rw/$uuid")
|
||||
val name = uuid ?: dirName
|
||||
if (name != null) {
|
||||
entry.candidates += File("/storage/$name")
|
||||
entry.candidates += File("/mnt/media_rw/$name")
|
||||
// Only strict uuid matches own an app directory; a loose match would
|
||||
// attach another volume's folder to this entry.
|
||||
if (uuid != null) appDirs.filter { belongsTo(storageManager!!, it, volume) }
|
||||
.forEach { entry.seeds += it }
|
||||
}
|
||||
appDirs.filter { belongsTo(storageManager!!, it, volume) }.forEach { entry.seeds += it }
|
||||
}
|
||||
|
||||
File("/storage").listFiles().orEmpty().forEach { child ->
|
||||
@@ -68,6 +122,13 @@ object StorageRoots {
|
||||
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
|
||||
if (child.isDirectory) volumeOf(child.name).candidates += child
|
||||
}
|
||||
// USB OTG drives do not always appear as storage volumes or under /storage for
|
||||
// third-party apps, but their kernel mounts are still visible in /proc/mounts.
|
||||
for (mount in externalMounts()) {
|
||||
val entry = volumeOf(mount.name)
|
||||
if (entry.label == null) entry.label = mount.name
|
||||
entry.candidates += mount
|
||||
}
|
||||
|
||||
appDirs.forEach { dir ->
|
||||
val root = volumeRootOf(dir) ?: return@forEach
|
||||
@@ -141,15 +202,19 @@ object StorageRoots {
|
||||
|
||||
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
|
||||
if (volume.isPrimary) return context.getString(R.string.fm_drive_internal)
|
||||
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
|
||||
val description = volume.getDescription(context)?.trim()
|
||||
return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
||||
?: uuid
|
||||
if (!description.isNullOrBlank() && !description.equals("android", ignoreCase = true)) return description
|
||||
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
|
||||
return uuid
|
||||
?: context.getString(R.string.fm_drive_storage)
|
||||
}
|
||||
|
||||
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
|
||||
|
||||
private fun present(state: String?): Boolean =
|
||||
isMounted(state) || state == Environment.MEDIA_UNMOUNTED || state == Environment.MEDIA_CHECKING ||
|
||||
state == Environment.MEDIA_NOFS || state == Environment.MEDIA_UNMOUNTABLE
|
||||
|
||||
private fun isMounted(state: String?): Boolean =
|
||||
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.files.PeIconExtractor
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreArt
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import org.json.JSONObject
|
||||
@@ -75,14 +77,18 @@ object AddedGameArt {
|
||||
)
|
||||
}
|
||||
|
||||
private fun storeArt(context: Context, game: AddedGames.Game): BattleNet.Art? =
|
||||
if (game.source != Store.BATTLENET.id) null else game.storeId?.let(BattleNet::title)?.let { BattleNet.art(context, it) }
|
||||
|
||||
fun resolve(context: Context, game: AddedGames.Game): Art {
|
||||
val own = local(game)
|
||||
val cache = cacheDir(context, game)
|
||||
val store = storeArt(context, game)
|
||||
fun cached(name: String) = File(cache, name).takeIf { it.isFile }
|
||||
return Art(
|
||||
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
|
||||
header = chosen(cache, Slot.WIDE) ?: own.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
|
||||
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: cached("hero.jpg"),
|
||||
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: store?.cover ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
|
||||
header = chosen(cache, Slot.WIDE) ?: own.header ?: store?.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
|
||||
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: store?.header ?: cached("hero.jpg"),
|
||||
logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"),
|
||||
icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game),
|
||||
)
|
||||
@@ -91,15 +97,16 @@ object AddedGameArt {
|
||||
fun describe(context: Context, game: AddedGames.Game): List<SlotState> {
|
||||
val own = local(game)
|
||||
val cache = cacheDir(context, game)
|
||||
val store = storeArt(context, game)
|
||||
fun cached(name: String): Pair<File, String>? = File(cache, name).takeIf { it.isFile }?.let { f ->
|
||||
f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM)
|
||||
}
|
||||
return Slot.values().map { slot ->
|
||||
chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) }
|
||||
val auto: Pair<File, String>? = when (slot) {
|
||||
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
|
||||
Slot.WIDE -> own.header?.let { it to FOLDER } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
|
||||
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: cached("hero.jpg")
|
||||
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: store?.cover?.let { it to AUTO } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
|
||||
Slot.WIDE -> own.header?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
|
||||
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("hero.jpg")
|
||||
Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png")
|
||||
Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB }
|
||||
?: exeIcon(context, game)?.let { it to EXE }
|
||||
@@ -253,12 +260,13 @@ object AddedGameArt {
|
||||
internal fun missing(context: Context, game: AddedGames.Game): Set<Slot> {
|
||||
val own = local(game)
|
||||
val cache = cacheDir(context, game)
|
||||
val store = storeArt(context, game)
|
||||
fun has(slot: Slot, mine: File?, cached: String) = chosen(cache, slot) != null || mine != null || File(cache, cached).isFile
|
||||
return Slot.values().filterNot { slot ->
|
||||
when (slot) {
|
||||
Slot.COVER -> has(slot, own.portrait, "p.jpg")
|
||||
Slot.WIDE -> has(slot, own.header, "header.jpg")
|
||||
Slot.BACKGROUND -> has(slot, own.hero, "hero.jpg")
|
||||
Slot.COVER -> has(slot, own.portrait ?: store?.cover, "p.jpg")
|
||||
Slot.WIDE -> has(slot, own.header ?: store?.header, "header.jpg")
|
||||
Slot.BACKGROUND -> has(slot, own.hero ?: store?.header, "hero.jpg")
|
||||
Slot.LOGO -> has(slot, own.logo, "logo.png")
|
||||
Slot.ICON -> has(slot, own.icon, "icon-sgdb.png")
|
||||
}
|
||||
@@ -322,6 +330,10 @@ object AddedGameArt {
|
||||
}
|
||||
|
||||
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
|
||||
if (game.source == Store.BATTLENET.id) {
|
||||
val id = game.storeId?.let(BattleNet::title)?.steam
|
||||
return SteamMatch.Match(id, if (id == null) SteamMatch.Certainty.NONE else SteamMatch.Certainty.FILES, Store.BATTLENET.id, System.currentTimeMillis())
|
||||
}
|
||||
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
|
||||
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
|
||||
return match
|
||||
@@ -361,14 +373,14 @@ object AddedGameArt {
|
||||
.filter { it.second > 0 && it.first.isNotEmpty() }
|
||||
.maxByOrNull { it.second }?.first
|
||||
|
||||
private fun search(name: String): String? {
|
||||
internal fun search(name: String): String? {
|
||||
val term = name.replace(EDITION, " ").trim().ifEmpty { name }
|
||||
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
|
||||
val items = JSONObject(json).optJSONArray("items") ?: return null
|
||||
return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") })
|
||||
}
|
||||
|
||||
private fun download(id: String, cache: File, slots: Set<Slot>): Boolean {
|
||||
internal fun download(id: String, cache: File, slots: Set<Slot> = Slot.entries.toSet()): Boolean {
|
||||
var got = false
|
||||
for ((slot, remote, localName) in listOf(
|
||||
Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"),
|
||||
|
||||
@@ -79,6 +79,18 @@ object AddedGames {
|
||||
return null
|
||||
}
|
||||
|
||||
fun hostPath(context: Context, guest: String): File? {
|
||||
if (!guest.startsWith("/") || guest.split('/').any { it == ".." }) return null
|
||||
val mapped = roots(context).map { it.host to it.guest } + StoreInstallRoot.externalRoots(context) +
|
||||
listOfNotNull(GameStorage.effective(context)?.let { File(it.path) to LIBRARY }) +
|
||||
(android.os.Environment.getExternalStorageDirectory() to "/root/Storage")
|
||||
for ((host, root) in mapped.sortedByDescending { it.second.length }) {
|
||||
if (guest == root) return host
|
||||
if (guest.startsWith("$root/")) return File(host, guest.removePrefix("$root/"))
|
||||
}
|
||||
return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
|
||||
}
|
||||
|
||||
fun candidates(folder: File): List<File> = rank(folder).exes
|
||||
|
||||
fun rank(folder: File): GameExePicker.Ranking {
|
||||
@@ -177,6 +189,9 @@ object AddedGames {
|
||||
scanGame(context, folder, out, single = entry)
|
||||
}
|
||||
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
|
||||
for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
|
||||
if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
|
||||
}
|
||||
return out.distinctBy { it.folder.canonicalPath }
|
||||
}
|
||||
|
||||
|
||||
@@ -257,14 +257,18 @@ object AutoComponents {
|
||||
|
||||
|
||||
private const val FINDINGS = "wincomp-findings.json"
|
||||
private const val DETECTORS = "d3"
|
||||
|
||||
internal fun signature(context: Context, game: Library.SteamGame): String {
|
||||
val folder = game.gameFiles
|
||||
val parts = listOfNotNull(
|
||||
DETECTORS,
|
||||
folder?.lastModified(),
|
||||
folder?.let { SteamRedists.manifest(it, game.appId)?.lastModified() },
|
||||
folder?.let { StoreGameSidecar.file(it).lastModified() },
|
||||
folder?.let { File(it, "fuel.json").lastModified() },
|
||||
folder?.listFiles { f -> f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") } }
|
||||
?.maxOfOrNull { it.lastModified() },
|
||||
SteamAppInfo.appinfoFile(context).lastModified(),
|
||||
folder?.let { SteamMatch.get(context, it.path) }?.let { "${it.appId}/${it.certainty}" },
|
||||
steamAppOf(context, game)?.let { SteamAppInfo.state(context, it) },
|
||||
|
||||
@@ -11,7 +11,7 @@ object GameRemoval {
|
||||
enum class Kind { STORE, SHORTCUT, LAUNCHER }
|
||||
|
||||
fun kind(game: Library.SteamGame): Kind = when {
|
||||
game.library == Library.EPIC_LAUNCHER -> Kind.LAUNCHER
|
||||
game.library == Library.EPIC_LAUNCHER || game.library == Library.BATTLENET_LAUNCHER -> Kind.LAUNCHER
|
||||
game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT
|
||||
else -> Kind.STORE
|
||||
}
|
||||
|
||||
@@ -22,11 +22,16 @@ object Library {
|
||||
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo)
|
||||
|
||||
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
||||
val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
|
||||
val profileKey: String get() = when {
|
||||
source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
|
||||
library == ADDED -> java.lang.Integer.toUnsignedString(appId)
|
||||
else -> appId.toString()
|
||||
}
|
||||
}
|
||||
const val ADDED = "added"
|
||||
const val EPIC_LAUNCHER = "epic-launcher"
|
||||
const val EPIC_LAUNCHER_NAME = "Epic Games Launcher"
|
||||
const val BATTLENET_LAUNCHER = "battlenet-launcher"
|
||||
const val XBOX_CLOUD = "xbox-cloud"
|
||||
const val SOURCE_STEAM = "steam"
|
||||
|
||||
@@ -204,9 +209,24 @@ object Library {
|
||||
(runCatching { g.folder.canonicalPath }.getOrDefault(g.folder.absolutePath) !in claimed &&
|
||||
AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed })
|
||||
}
|
||||
return (steam + own.map { g -> addedGame(context, g, roots) }).distinctBy { it.gameId }
|
||||
val played = shortcutsLastPlayed(SessionPrefs.steamRoot(context, arch))
|
||||
return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) }).distinctBy { it.gameId }
|
||||
}
|
||||
|
||||
/** Steam's LastPlayTime for each non-Steam shortcut, by its unsigned shortcut app id. */
|
||||
internal fun shortcutsLastPlayed(root: File): Map<Long, Long> = runCatching {
|
||||
val config = AddedGames.accountConfig(root) ?: return emptyMap()
|
||||
val bytes = File(config, "shortcuts.vdf").takeIf { it.isFile }?.readBytes() ?: return emptyMap()
|
||||
val vdf = SteamAppInfo.readMap(java.nio.ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN), null)
|
||||
(vdf["shortcuts"] as? Map<*, *>)?.values?.filterIsInstance<Map<*, *>>()?.mapNotNull { s ->
|
||||
fun int(key: String) = s.entries.firstOrNull { (it.key as? String).equals(key, ignoreCase = true) }
|
||||
?.let { (it.value as? String)?.toLongOrNull() }?.and(0xFFFFFFFFL)
|
||||
val id = int("appid") ?: return@mapNotNull null
|
||||
val time = int("LastPlayTime")?.takeIf { it > 0L } ?: return@mapNotNull null
|
||||
id to time
|
||||
}?.toMap()
|
||||
}.getOrNull().orEmpty()
|
||||
|
||||
fun claimedFolders(steam: List<SteamGame>): Set<String> = steam.filter(::fromSteamClient).flatMap { g ->
|
||||
val dir = g.gameFiles ?: return@flatMap emptyList()
|
||||
listOfNotNull(
|
||||
@@ -215,12 +235,16 @@ object Library {
|
||||
)
|
||||
}.toSet()
|
||||
|
||||
fun addedGame(context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first }): SteamGame =
|
||||
fun addedGame(
|
||||
context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first },
|
||||
lastPlayed: Long = 0L,
|
||||
): SteamGame =
|
||||
AddedGameArt.resolve(context, g).let { art ->
|
||||
SteamGame(
|
||||
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
|
||||
hero = art.hero ?: art.header, gameFiles = g.folder,
|
||||
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
|
||||
hero = art.hero ?: art.header, lastPlayed = lastPlayed, gameFiles = g.folder,
|
||||
protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory }
|
||||
else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
|
||||
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
|
||||
source = g.source, storeId = g.storeId,
|
||||
logo = art.logo,
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
|
||||
/** Steam keeps a game's custom art in `userdata/<account>/config/grid`; this is where DroidDeck's choices and Steam's meet. */
|
||||
object SteamGrid {
|
||||
@@ -41,14 +42,42 @@ object SteamGrid {
|
||||
|
||||
private fun sigFile(context: Context, target: Target, slot: AddedGameArt.Slot) = File(target.artDir, sigName(context, slot.key))
|
||||
|
||||
private fun recorded(context: Context, target: Target, slot: AddedGameArt.Slot): String? =
|
||||
sigFile(context, target, slot).takeIf { it.isFile }?.readText()
|
||||
private const val GRID_ID = ".droiddeck-grid"
|
||||
private const val UNKNOWN_GRID = "?"
|
||||
|
||||
private fun record(context: Context, target: Target, slot: AddedGameArt.Slot, value: String) {
|
||||
target.artDir.mkdirs()
|
||||
sigFile(context, target, slot).writeText(value)
|
||||
/**
|
||||
* A random id kept in the grid folder, so a record made against another account's folder, or one wiped with the
|
||||
* runtime, reads as "not seen yet" instead of "removed in Steam". "?" never matches, so nothing is dropped.
|
||||
*/
|
||||
private fun gridId(grid: File): String = runCatching {
|
||||
val f = File(grid, GRID_ID)
|
||||
f.takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: UUID.randomUUID().toString().also { id ->
|
||||
grid.mkdirs()
|
||||
val tmp = File(grid, "$GRID_ID.tmp")
|
||||
tmp.writeText(id)
|
||||
if (f.isFile) f.delete()
|
||||
if (!tmp.renameTo(f)) error("grid id")
|
||||
}
|
||||
}.getOrDefault(UNKNOWN_GRID)
|
||||
|
||||
private fun readRecord(grid: File, file: File): String? {
|
||||
val text = file.takeIf { it.isFile }?.readText() ?: return null
|
||||
val cut = text.indexOf('\n')
|
||||
val id = gridId(grid)
|
||||
return if (cut > 0 && id != UNKNOWN_GRID && text.substring(0, cut) == id) text.substring(cut + 1) else null
|
||||
}
|
||||
|
||||
private fun writeRecord(grid: File, target: Target, file: File, value: String) {
|
||||
target.artDir.mkdirs()
|
||||
file.writeText("${gridId(grid)}\n$value")
|
||||
}
|
||||
|
||||
private fun recorded(context: Context, grid: File, target: Target, slot: AddedGameArt.Slot): String? =
|
||||
readRecord(grid, sigFile(context, target, slot))
|
||||
|
||||
private fun record(context: Context, grid: File, target: Target, slot: AddedGameArt.Slot, value: String) =
|
||||
writeRecord(grid, target, sigFile(context, target, slot), value)
|
||||
|
||||
private fun writtenByDroidDeck(grid: File): Set<String> = runCatching {
|
||||
val manifest = JSONObject(File(grid, MANIFEST).readText())
|
||||
manifest.keys().asSequence().filter { name -> File(grid, name).let { it.isFile && it.length() == manifest.optLong(name, -1L) } }.toSet()
|
||||
@@ -62,7 +91,7 @@ object SteamGrid {
|
||||
val grid = dir(context) ?: return true
|
||||
if (file == null) {
|
||||
if (files(grid, target.id, slot).map { it.delete() }.any { !it }) return false
|
||||
record(context, target, slot, "")
|
||||
record(context, grid, target, slot, "")
|
||||
return true
|
||||
}
|
||||
val ext = file.extension.lowercase().let { if (it == "jpeg") "jpg" else it }
|
||||
@@ -76,7 +105,7 @@ object SteamGrid {
|
||||
return false
|
||||
}
|
||||
if (files(grid, target.id, slot).filter { it != dst }.map { it.delete() }.any { !it }) return false
|
||||
record(context, target, slot, signature(placed))
|
||||
record(context, grid, target, slot, signature(placed))
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -90,13 +119,11 @@ object SteamGrid {
|
||||
/** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */
|
||||
fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION))
|
||||
|
||||
private fun positionRecorded(context: Context, target: Target): String? =
|
||||
File(target.artDir, sigName(context, POSITION_SIG)).takeIf { it.isFile }?.readText()
|
||||
private fun positionRecorded(context: Context, grid: File, target: Target): String? =
|
||||
readRecord(grid, File(target.artDir, sigName(context, POSITION_SIG)))
|
||||
|
||||
private fun recordPosition(context: Context, target: Target, value: String) {
|
||||
target.artDir.mkdirs()
|
||||
File(target.artDir, sigName(context, POSITION_SIG)).writeText(value)
|
||||
}
|
||||
private fun recordPosition(context: Context, grid: File, target: Target, value: String) =
|
||||
writeRecord(grid, target, File(target.artDir, sigName(context, POSITION_SIG)), value)
|
||||
|
||||
private fun storePosition(target: Target, value: LogoPosition.Value?): Boolean {
|
||||
val file = File(target.artDir, POSITION)
|
||||
@@ -119,7 +146,7 @@ object SteamGrid {
|
||||
val next = if (value == null) existing?.let(LogoPosition::without) else LogoPosition.toJson(value, existing ?: JSONObject())
|
||||
if (next == null) {
|
||||
if (file.isFile && !file.delete()) return false
|
||||
recordPosition(context, target, "")
|
||||
recordPosition(context, grid, target, "")
|
||||
return true
|
||||
}
|
||||
grid.mkdirs()
|
||||
@@ -129,7 +156,7 @@ object SteamGrid {
|
||||
tmp.delete()
|
||||
return false
|
||||
}
|
||||
recordPosition(context, target, signature(file))
|
||||
recordPosition(context, grid, target, signature(file))
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -144,16 +171,16 @@ object SteamGrid {
|
||||
if (hasUnknownPosition(file)) return
|
||||
val theirs = positionIn(file)
|
||||
val now = if (theirs != null) signature(file) else ""
|
||||
val before = positionRecorded(context, target)
|
||||
val before = positionRecorded(context, grid, target)
|
||||
val own = position(target)
|
||||
when {
|
||||
before == null && own != null && theirs == null -> placePosition(context, target, own)
|
||||
before == null || now != before -> {
|
||||
// Recorded only once the local side agrees, so a failed take-over is tried again on the next scan.
|
||||
if (theirs != null) {
|
||||
if (own == theirs || storePosition(target, theirs)) recordPosition(context, target, now)
|
||||
if (own == theirs || storePosition(target, theirs)) recordPosition(context, grid, target, now)
|
||||
} else {
|
||||
if (own == null || storePosition(target, null)) recordPosition(context, target, "")
|
||||
if (own == null || storePosition(target, null)) recordPosition(context, grid, target, "")
|
||||
}
|
||||
}
|
||||
own != null && own != theirs -> placePosition(context, target, own)
|
||||
@@ -173,20 +200,20 @@ object SteamGrid {
|
||||
val present = files(grid, target.id, slot)
|
||||
val theirs = present.filter { it.name !in ours }.maxByOrNull { it.lastModified() }
|
||||
val now = signature(theirs)
|
||||
val before = recorded(context, target, slot)
|
||||
val before = recorded(context, grid, target, slot)
|
||||
when {
|
||||
before == null && own != null && theirs == null -> write(context, target, slot, own)
|
||||
before == null || now != before -> {
|
||||
if (theirs != null) {
|
||||
if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(context, target, slot, now)
|
||||
if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(context, grid, target, slot, now)
|
||||
else if (AddedGameArt.store(target.artDir, slot, AddedGameArt.Option(AddedGameArt.STEAM, theirs.path, theirs.path))) {
|
||||
target.setSource(slot, AddedGameArt.STEAM + "|steam-client")
|
||||
record(context, target, slot, now)
|
||||
record(context, grid, target, slot, now)
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
if (own != null && present.isEmpty()) { own.delete(); target.setSource(slot, ""); changed = true }
|
||||
record(context, target, slot, "")
|
||||
record(context, grid, target, slot, "")
|
||||
}
|
||||
}
|
||||
own != null && theirs != null && now == before && own.length() != theirs.length() -> write(context, target, slot, own)
|
||||
|
||||
@@ -15,6 +15,11 @@ object SteamRedists {
|
||||
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
|
||||
"228990" to ("d3dx9" to "DirectX (June 2010)"),
|
||||
)
|
||||
/** Redists a game's own install script runs on Windows that its shared depots don't name. */
|
||||
val SCRIPTED = mapOf(
|
||||
72850 to listOf("xact" to "DirectX XACT audio"),
|
||||
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
|
||||
)
|
||||
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
||||
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
||||
|
||||
@@ -23,6 +28,17 @@ object SteamRedists {
|
||||
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
|
||||
}
|
||||
|
||||
/** Redists the game's own install script has Steam run on Windows, from its "Run Process" entries. */
|
||||
fun installScript(gameDir: File?): List<Pair<String, String>> =
|
||||
gameDir?.listFiles { f ->
|
||||
f.isFile && f.length() < 1L shl 20 && f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") }
|
||||
}.orEmpty().sortedBy { it.name }.flatMap { file ->
|
||||
val root = runCatching { com.droiddeck.launcher.input.KeyValues.parse(file.readText()) }.getOrNull() ?: return@flatMap emptyList()
|
||||
(root.child("InstallScript") ?: root).children("Run Process")
|
||||
.flatMap { run -> run.entries.mapNotNull { (it.second as? com.droiddeck.launcher.input.KeyValues.Node)?.string("process 1") } }
|
||||
.flatMap { path -> DependencyDetector.componentsFor(path).map { it to DependencyDetector.label(it) } }
|
||||
}.distinctBy { it.first }
|
||||
|
||||
fun detect(gameDir: File?, appId: Int): List<DependencyDetector.Recommendation> {
|
||||
val text = try {
|
||||
manifest(gameDir, appId)?.takeIf { it.length() < 1L shl 20 }?.readText() ?: return emptyList()
|
||||
|
||||
@@ -77,9 +77,10 @@ object WinCompSources {
|
||||
|
||||
fun steamList(context: Context, gameDir: File?, appId: Int, gameName: String, auto: Boolean): List<Finding> {
|
||||
val local = SteamRedists.detect(gameDir, appId)
|
||||
val pairs = if (local.isNotEmpty()) local.map { it.componentName to it.label }
|
||||
else SteamAppInfo.info(context, appId)?.let { steamDepots(it.sharedDepots) }.orEmpty()
|
||||
return pairs.map { (component, label) ->
|
||||
val pairs = (if (local.isNotEmpty()) local.map { it.componentName to it.label }
|
||||
else SteamAppInfo.info(context, appId)?.let { steamDepots(it.sharedDepots) }.orEmpty()) +
|
||||
SteamRedists.installScript(gameDir) + SteamRedists.SCRIPTED[appId].orEmpty()
|
||||
return pairs.distinctBy { it.first.removeSuffix("_dll") }.map { (component, label) ->
|
||||
Finding(component, label, if (auto) Origin.STEAM else Origin.STEAM_NAME, auto, listOf(label, gameName, appId.toString()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ package com.droiddeck.launcher.glasses
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** Rokid Air/Max share one USB identity; the product string distinguishes them. */
|
||||
/** Rokid Air/Max share one USB identity; Max 2 has a separate product ID. */
|
||||
internal class RokidModel private constructor(override val name: String, private val max: Boolean) : GlassesModel {
|
||||
override val controllable = true
|
||||
override val brightnessMax = BRIGHTNESS_STEPS
|
||||
@@ -33,6 +33,7 @@ internal class RokidModel private constructor(override val name: String, private
|
||||
companion object {
|
||||
const val VENDOR_ID = 0x04d2
|
||||
const val PRODUCT_ID = 0x162f
|
||||
const val MAX2_PRODUCT_ID = 0x2002
|
||||
const val BRIGHTNESS_STEPS = 10
|
||||
|
||||
// Vendor control requests, device recipient.
|
||||
@@ -52,9 +53,9 @@ internal class RokidModel private constructor(override val name: String, private
|
||||
|
||||
// 0x04d2 is a shared vendor ID, so the Rokid product string is required too.
|
||||
fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
|
||||
if (vid != VENDOR_ID || pid != PRODUCT_ID) return null
|
||||
if (vid != VENDOR_ID || (pid != PRODUCT_ID && pid != MAX2_PRODUCT_ID)) return null
|
||||
val product = name?.trim()?.takeIf { it.startsWith("Rokid", ignoreCase = true) } ?: return null
|
||||
return RokidModel(product, product.contains("Max", ignoreCase = true))
|
||||
return RokidModel(product, pid == MAX2_PRODUCT_ID || product.contains("Max", ignoreCase = true))
|
||||
}
|
||||
|
||||
fun isDisplay(name: String) = name.contains("Rokid", ignoreCase = true)
|
||||
|
||||
@@ -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<Int, Press>()
|
||||
private val cancelled = mutableSetOf<Int>()
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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() }),
|
||||
|
||||
@@ -157,6 +157,56 @@ object ControllerPrefs {
|
||||
prefs(context).edit().remove("layout.${width}x$height").apply()
|
||||
}
|
||||
|
||||
fun screenKeysShown(context: Context): Boolean = prefs(context).getBoolean("screenKeysShown", true)
|
||||
|
||||
fun setScreenKeysShown(context: Context, shown: Boolean) {
|
||||
prefs(context).edit().putBoolean("screenKeysShown", shown).apply()
|
||||
}
|
||||
|
||||
fun screenKeys(context: Context): List<ScreenKey> = decodeScreenKeys(prefs(context).getString("screenKeys", null).orEmpty())
|
||||
|
||||
fun setScreenKeys(context: Context, keys: List<ScreenKey>) {
|
||||
prefs(context).edit().putString("screenKeys", encodeScreenKeys(keys)).apply()
|
||||
}
|
||||
|
||||
fun encodeScreenKeys(keys: List<ScreenKey>): String = keys.joinToString(";") {
|
||||
"${it.codes.joinToString("+")}:${it.x},${it.y},${it.size}:${escape(it.glyph)}:${escape(it.text)}:${escape(it.image)}:${it.opacity}:${it.shape}:${if (it.toggle) 1 else 0}:${if (it.labels) 1 else 0}"
|
||||
}
|
||||
|
||||
fun decodeScreenKeys(raw: String): List<ScreenKey> = raw.split(';').mapNotNull { entry ->
|
||||
val parts = entry.split(':')
|
||||
if (parts.size < 2) return@mapNotNull null
|
||||
val keys = parts[0].split('+').mapNotNull { it.toIntOrNull() }.takeIf { it.isNotEmpty() } ?: return@mapNotNull null
|
||||
val nums = parts[1].split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 3 } ?: return@mapNotNull null
|
||||
ScreenKey(
|
||||
keys, nums[0], nums[1], nums[2].toInt(),
|
||||
parts.getOrNull(2)?.let(::unescape).orEmpty(),
|
||||
parts.getOrNull(3)?.let(::unescape).orEmpty(),
|
||||
parts.getOrNull(4)?.let(::unescape).orEmpty(),
|
||||
parts.getOrNull(5)?.toFloatOrNull()?.coerceIn(0.2f, 1f) ?: 1f,
|
||||
parts.getOrNull(6)?.toIntOrNull()?.coerceIn(SCREEN_KEY_PILL, SCREEN_KEY_STICK) ?: SCREEN_KEY_PILL,
|
||||
parts.getOrNull(7) == "1",
|
||||
parts.getOrNull(8) != "0",
|
||||
)
|
||||
}
|
||||
|
||||
fun screenLayouts(context: Context): Map<String, String> =
|
||||
prefs(context).all.mapNotNull { (key, value) ->
|
||||
if (!key.startsWith("screenLayout.") || value !is String) null else key.removePrefix("screenLayout.") to value
|
||||
}.toMap()
|
||||
|
||||
fun saveScreenLayout(context: Context, name: String, raw: String) {
|
||||
prefs(context).edit().putString("screenLayout.$name", raw).apply()
|
||||
}
|
||||
|
||||
fun deleteScreenLayout(context: Context, name: String) {
|
||||
prefs(context).edit().remove("screenLayout.$name").apply()
|
||||
}
|
||||
|
||||
private fun escape(value: String) = value.replace("%", "%25").replace(";", "%3B").replace(":", "%3A").replace(",", "%2C")
|
||||
|
||||
private fun unescape(value: String) = value.replace("%2C", ",").replace("%3A", ":").replace("%3B", ";").replace("%25", "%")
|
||||
|
||||
fun resetAll(context: Context) {
|
||||
prefs(context).edit().clear().putBoolean("rumble", true).apply()
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ class DirectTouchHold(
|
||||
private var y = 0f
|
||||
private var consumed = false
|
||||
private var pressed = false
|
||||
private var delayMs = 0L
|
||||
private val release = Runnable {
|
||||
if (pressed) listener.onButton(PointerGestures.BTN_RIGHT, false, x, y)
|
||||
pressed = false
|
||||
@@ -28,6 +29,11 @@ class DirectTouchHold(
|
||||
handler.postDelayed(release, 50L)
|
||||
}
|
||||
|
||||
fun configure(config: TouchGestureConfig) {
|
||||
cancel()
|
||||
delayMs = if (config.longPressEnabled) config.longPressDelay.toLong().coerceAtLeast(1L) else 0L
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
handler.removeCallbacks(hold)
|
||||
handler.removeCallbacks(release)
|
||||
@@ -40,7 +46,7 @@ class DirectTouchHold(
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
cancel()
|
||||
x = event.x; y = event.y
|
||||
handler.postDelayed(hold, 500L)
|
||||
if (delayMs > 0L) handler.postDelayed(hold, delayMs)
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> if (event.pointerCount > 1 ||
|
||||
abs(event.x - x) > slopPx || abs(event.y - y) > slopPx) handler.removeCallbacks(hold)
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.MotionEvent
|
||||
|
||||
/** Keeps split Android touch targets from restarting one shared gesture recognizer. */
|
||||
internal class GestureTouchStreamGate {
|
||||
enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS }
|
||||
|
||||
private var owner: Source? = null
|
||||
|
||||
fun accepts(source: Source, event: MotionEvent): Boolean {
|
||||
if (owner == null && event.actionMasked == MotionEvent.ACTION_DOWN) owner = source
|
||||
val accepted = owner == source
|
||||
if (accepted && (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL)) {
|
||||
owner = null
|
||||
}
|
||||
return accepted
|
||||
}
|
||||
|
||||
fun reset() { owner = null }
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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<Int>()
|
||||
private val cancelled = mutableSetOf<Int>()
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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 -> {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.input;
|
||||
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
@@ -52,6 +53,7 @@ public final class PadBridge {
|
||||
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
|
||||
private final PadState[] playerStates = new PadState[SLOTS];
|
||||
private final PadState effectiveState = new PadState();
|
||||
private final PadState homeGuideReport = new PadState();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private boolean open;
|
||||
private volatile boolean selectSteam;
|
||||
@@ -60,12 +62,21 @@ public final class PadBridge {
|
||||
private final PadState routedTouch = new PadState();
|
||||
private boolean systemGuidePressed;
|
||||
private boolean systemQamPressed;
|
||||
private boolean backQamPressed;
|
||||
private boolean homeGuidePressed;
|
||||
private int homeGuideSlot = -1;
|
||||
private final PadState lastBackQamReport = new PadState();
|
||||
private final PadState lastWrittenReport = new PadState();
|
||||
private boolean backQamAxesBlocked;
|
||||
private final java.util.Set<Runnable> backQamWrites = new java.util.HashSet<>();
|
||||
private long backQamDelayMs, backQamWriteAt;
|
||||
private boolean qamChordActive;
|
||||
private int chordButton = -1;
|
||||
private boolean chordButtonPressed;
|
||||
private boolean qamTapPressed;
|
||||
private int qamChordGeneration;
|
||||
private volatile Runnable onPlayerInput;
|
||||
private Runnable onChordInput;
|
||||
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
|
||||
private static final long STATS_WINDOW_MS = 10_000;
|
||||
@@ -128,9 +139,12 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
private void resetBuiltin() {
|
||||
homeGuidePressed = false;
|
||||
clearBackQamWrites();
|
||||
routedTouch.clear();
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
backQamPressed = false;
|
||||
qamTapPressed = false;
|
||||
qamChordActive = false;
|
||||
chordButtonPressed = false;
|
||||
@@ -149,6 +163,9 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
homeGuidePressed = false;
|
||||
homeGuideSlot = -1;
|
||||
clearBackQamWrites();
|
||||
releaseBackPaddles();
|
||||
activeControllerId = NO_CONTROLLER;
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
@@ -164,6 +181,7 @@ public final class PadBridge {
|
||||
}
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
backQamPressed = false;
|
||||
qamChordActive = false;
|
||||
chordButtonPressed = false;
|
||||
qamTapPressed = false;
|
||||
@@ -214,6 +232,7 @@ public final class PadBridge {
|
||||
case KeyEvent.KEYCODE_BACK:
|
||||
case KeyEvent.KEYCODE_MENU:
|
||||
case KeyEvent.KEYCODE_HOME:
|
||||
case KeyEvent.KEYCODE_MOVE_HOME:
|
||||
if (!isFromController(device)) return false;
|
||||
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|
||||
|| device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC
|
||||
@@ -272,6 +291,14 @@ public final class PadBridge {
|
||||
onPlayerInput = listener;
|
||||
}
|
||||
|
||||
public synchronized void setOnChordInput(Runnable listener) {
|
||||
onChordInput = listener;
|
||||
}
|
||||
|
||||
private void noteChordInput(int slot) {
|
||||
if (slot == 0 && onChordInput != null) onChordInput.run();
|
||||
}
|
||||
|
||||
private void notePlayerInput() {
|
||||
Runnable listener = onPlayerInput;
|
||||
if (listener == null || !playerInputPosted.compareAndSet(false, true)) return;
|
||||
@@ -306,12 +333,13 @@ public final class PadBridge {
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.press(9, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_MODE:
|
||||
case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break;
|
||||
case KeyEvent.KEYCODE_HOME:
|
||||
case KeyEvent.KEYCODE_MOVE_HOME: pad.press(PadState.GUIDE, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_Z:
|
||||
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(DeckControls.L4, pressed);
|
||||
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed);
|
||||
break;
|
||||
case KeyEvent.KEYCODE_BUTTON_C:
|
||||
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(DeckControls.R4, pressed);
|
||||
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.L4 : DeckControls.R4, pressed);
|
||||
break;
|
||||
case KeyEvent.KEYCODE_BUTTON_L2: pad.leftTrigger = pressed ? 1f : 0f; break;
|
||||
case KeyEvent.KEYCODE_BUTTON_R2: pad.rightTrigger = pressed ? 1f : 0f; break;
|
||||
@@ -322,6 +350,7 @@ public final class PadBridge {
|
||||
default: return false;
|
||||
}
|
||||
noteDevice(event.getDevice(), slot);
|
||||
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
|
||||
if (pressed) notePlayerInput();
|
||||
statButtons++;
|
||||
scheduleStats();
|
||||
@@ -351,6 +380,7 @@ public final class PadBridge {
|
||||
pad.rightX = x;
|
||||
pad.rightY = y;
|
||||
}
|
||||
if (x != 0f || y != 0f) noteChordInput(slot);
|
||||
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
|
||||
publish(slot);
|
||||
return true;
|
||||
@@ -381,6 +411,8 @@ public final class PadBridge {
|
||||
pad.up = hatY < -0.5f;
|
||||
pad.down = hatY > 0.5f;
|
||||
}
|
||||
if (pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|
||||
|| lt > 0f || rt > 0f || pad.up || pad.right || pad.down || pad.left) noteChordInput(slot);
|
||||
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|
||||
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
|
||||
notePlayerInput();
|
||||
@@ -457,7 +489,11 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void releaseAll() {
|
||||
homeGuidePressed = false;
|
||||
homeGuideSlot = -1;
|
||||
clearBackQamWrites();
|
||||
routedTouch.clear();
|
||||
backQamPressed = false;
|
||||
releaseBackPaddles();
|
||||
state.clear();
|
||||
publish();
|
||||
@@ -478,6 +514,146 @@ public final class PadBridge {
|
||||
return SessionState.getDeckPad() && FakeInputWriter.padHasQam();
|
||||
}
|
||||
|
||||
public boolean canHoldQam() {
|
||||
return builtinPad && nativeQam();
|
||||
}
|
||||
|
||||
public synchronized void setHomeGuidePressed(boolean pressed) {
|
||||
int slot = pressed ? firstPlayerSlot() : homeGuideSlot;
|
||||
if (slot > 0) {
|
||||
homeGuideSlot = pressed ? slot : -1;
|
||||
publish(slot);
|
||||
return;
|
||||
}
|
||||
if (homeGuidePressed == pressed) return;
|
||||
homeGuidePressed = pressed;
|
||||
updateHeldModifier(PadState.GUIDE, pressed);
|
||||
}
|
||||
|
||||
public synchronized void cancelHomeGuide() {
|
||||
int slot = homeGuideSlot;
|
||||
if (slot > 0) {
|
||||
homeGuideSlot = -1;
|
||||
publish(slot);
|
||||
}
|
||||
if (!homeGuidePressed) return;
|
||||
clearBackQamWrites();
|
||||
homeGuidePressed = false;
|
||||
state.clear();
|
||||
publish();
|
||||
}
|
||||
|
||||
public synchronized void setBackQamPressed(boolean pressed) {
|
||||
if (pressed && !canHoldQam()) return;
|
||||
if (backQamPressed == pressed) return;
|
||||
backQamPressed = pressed;
|
||||
updateHeldModifier(PadState.QAM, pressed);
|
||||
}
|
||||
|
||||
private void updateHeldModifier(int button, boolean pressed) {
|
||||
if (pressed && (open || start())) {
|
||||
backQamAxesBlocked = false;
|
||||
long now = android.os.SystemClock.uptimeMillis();
|
||||
long modifierAt = Math.max(now, backQamWriteAt);
|
||||
backQamDelayMs = modifierAt - now + QAM_GUIDE_LEAD_MIN_MS;
|
||||
PadState modifier = new PadState();
|
||||
modifier.copyFrom(lastBackQamReport);
|
||||
modifier.press(button, true);
|
||||
writeBackQamReport(modifier, modifierAt);
|
||||
}
|
||||
if (!pressed && !backQamPressed && !homeGuidePressed) {
|
||||
backQamAxesBlocked = hasAxes(state);
|
||||
if (!backQamWrites.isEmpty()) {
|
||||
PadState neutral = new PadState();
|
||||
neutral.copyFrom(lastWrittenReport);
|
||||
clearAxes(neutral);
|
||||
writer.writePad(neutral);
|
||||
lastWrittenReport.copyFrom(neutral);
|
||||
}
|
||||
}
|
||||
publish();
|
||||
}
|
||||
|
||||
public synchronized void cancelBackQam() {
|
||||
if (!backQamPressed && backQamWrites.isEmpty()) return;
|
||||
clearBackQamWrites();
|
||||
backQamPressed = false;
|
||||
state.clear();
|
||||
publish();
|
||||
}
|
||||
|
||||
private void clearBackQamWrites() {
|
||||
for (Runnable pending : backQamWrites) mainHandler.removeCallbacks(pending);
|
||||
backQamWrites.clear();
|
||||
backQamDelayMs = backQamWriteAt = 0;
|
||||
lastBackQamReport.clear();
|
||||
lastWrittenReport.clear();
|
||||
backQamAxesBlocked = false;
|
||||
}
|
||||
|
||||
private void writeBackQamReport(PadState report, long at) {
|
||||
lastBackQamReport.copyFrom(report);
|
||||
if (backQamWrites.isEmpty() && at <= android.os.SystemClock.uptimeMillis()) {
|
||||
writeReport(report, false);
|
||||
return;
|
||||
}
|
||||
PadState queued = new PadState();
|
||||
queued.copyFrom(report);
|
||||
Runnable pending = new Runnable() {
|
||||
@Override public void run() {
|
||||
synchronized (PadBridge.this) {
|
||||
if (!backQamWrites.remove(this)) return;
|
||||
writeReport(queued, true);
|
||||
if (backQamWrites.isEmpty() && !hasButtons(lastBackQamReport)) backQamDelayMs = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
backQamWrites.add(pending);
|
||||
backQamWriteAt = at;
|
||||
mainHandler.postAtTime(pending, at);
|
||||
}
|
||||
|
||||
private void writePad(PadState report) {
|
||||
if (backQamAxesBlocked && !hasAxes(state)) backQamAxesBlocked = false;
|
||||
long at = android.os.SystemClock.uptimeMillis();
|
||||
// Steam must see the modifier before a partner; preserve quick press/release pairs in order.
|
||||
if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
|
||||
writeBackQamReport(report, at);
|
||||
}
|
||||
|
||||
private static boolean hasAxes(PadState pad) {
|
||||
return pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|
||||
|| pad.leftTrigger != 0f || pad.rightTrigger != 0f;
|
||||
}
|
||||
|
||||
private static void clearAxes(PadState pad) {
|
||||
pad.leftX = pad.leftY = pad.rightX = pad.rightY = pad.leftTrigger = pad.rightTrigger = 0f;
|
||||
}
|
||||
|
||||
private static boolean hasButtons(PadState pad) {
|
||||
for (int i = 0; i < 10; i++) if (pad.isDown(i)) return true;
|
||||
return pad.isDown(PadState.GUIDE) || pad.up || pad.right || pad.down || pad.left;
|
||||
}
|
||||
|
||||
private void writeReport(PadState report, boolean queued) {
|
||||
if (!queued && !backQamAxesBlocked) {
|
||||
lastWrittenReport.copyFrom(report);
|
||||
writer.writePad(report);
|
||||
return;
|
||||
}
|
||||
PadState live = new PadState();
|
||||
live.copyFrom(report);
|
||||
if (queued) {
|
||||
live.leftX = state.leftX; live.leftY = state.leftY;
|
||||
live.rightX = state.rightX; live.rightY = state.rightY;
|
||||
live.leftTrigger = state.leftTrigger; live.rightTrigger = state.rightTrigger;
|
||||
}
|
||||
boolean held = (backQamPressed && report.isDown(PadState.QAM)) || (homeGuidePressed && report.isDown(PadState.GUIDE));
|
||||
if ((queued && !held) || backQamAxesBlocked) clearAxes(live);
|
||||
lastWrittenReport.copyFrom(live);
|
||||
writer.writePad(live);
|
||||
}
|
||||
|
||||
public synchronized void triggerQam() {
|
||||
if (!builtinPad) return;
|
||||
if (!nativeQam()) {
|
||||
@@ -556,7 +732,9 @@ public final class PadBridge {
|
||||
slotJoyCons.set(slot * 2 + side, id);
|
||||
slotJoyCons.set(slot * 2 + 1 - side, owner.getId());
|
||||
if (slot == firstPlayerSlot()) releaseBackPaddles();
|
||||
if (slot == 0) clearBackQamWrites();
|
||||
stateFor(slot).clear();
|
||||
if (slot == 0) publish();
|
||||
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1));
|
||||
return slot;
|
||||
}
|
||||
@@ -573,6 +751,12 @@ public final class PadBridge {
|
||||
return slot == 0 ? state : playerStates[slot];
|
||||
}
|
||||
|
||||
private static boolean isNovaController(InputDevice device) {
|
||||
return "Retroid Pocket Nova".equalsIgnoreCase(Build.MODEL)
|
||||
&& device.getVendorId() == 0x2022
|
||||
&& (device.getProductId() == 0x3001 || device.getProductId() == 0x3002);
|
||||
}
|
||||
|
||||
private boolean isPrimary(KeyEvent event) {
|
||||
int id = event.getDevice().getId();
|
||||
int first = firstPlayerSlot();
|
||||
@@ -585,6 +769,7 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
private void leave(int slot, int id) {
|
||||
if (slot == 0) clearBackQamWrites();
|
||||
if (partners[slot] == NO_CONTROLLER) {
|
||||
free(slot);
|
||||
return;
|
||||
@@ -611,6 +796,7 @@ public final class PadBridge {
|
||||
partners[slot] = NO_CONTROLLER;
|
||||
clearJoyCons(slot);
|
||||
slotControllers.set(slot, NO_CONTROLLER);
|
||||
if (slot == homeGuideSlot) homeGuideSlot = -1;
|
||||
if (slot == firstPlayerSlot()) releaseBackPaddles();
|
||||
if (slot == 0) {
|
||||
state.clear();
|
||||
@@ -667,7 +853,13 @@ public final class PadBridge {
|
||||
}
|
||||
playerWriters[slot] = player;
|
||||
}
|
||||
player.writePad(playerStates[slot]);
|
||||
PadState report = playerStates[slot];
|
||||
if (slot == homeGuideSlot) {
|
||||
homeGuideReport.copyFrom(report);
|
||||
homeGuideReport.press(PadState.GUIDE, true);
|
||||
report = homeGuideReport;
|
||||
}
|
||||
player.writePad(report);
|
||||
}
|
||||
|
||||
private void publish() {
|
||||
@@ -676,17 +868,17 @@ public final class PadBridge {
|
||||
statDropped++;
|
||||
return;
|
||||
}
|
||||
boolean guide = systemGuidePressed || qamChordActive;
|
||||
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed);
|
||||
boolean guide = systemGuidePressed || qamChordActive || homeGuidePressed;
|
||||
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed || backQamPressed);
|
||||
if (!guide && !qam) {
|
||||
writer.writePad(state);
|
||||
writePad(state);
|
||||
return;
|
||||
}
|
||||
effectiveState.copyFrom(state);
|
||||
if (guide) effectiveState.press(PadState.GUIDE, true);
|
||||
if (qam) effectiveState.press(PadState.QAM, true);
|
||||
if (chordButtonPressed) effectiveState.press(chordButton, true);
|
||||
writer.writePad(effectiveState);
|
||||
writePad(effectiveState);
|
||||
}
|
||||
|
||||
public static boolean wiredXboxLayout(MotionEvent event) {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import androidx.annotation.StringRes
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
data class PcKey(
|
||||
val label: String,
|
||||
val code: Int,
|
||||
val weight: Float = 1f,
|
||||
val shifted: String? = null,
|
||||
@StringRes val labelRes: Int = 0,
|
||||
)
|
||||
|
||||
internal fun k(label: String, code: Int, weight: Float = 1f, shifted: String? = null) = PcKey(label, code, weight, shifted)
|
||||
|
||||
internal fun k(@StringRes labelRes: Int, code: Int, weight: Float = 1f) = PcKey("", code, weight, null, labelRes)
|
||||
|
||||
val PC_KEY_ROWS: List<List<PcKey>> = listOf(
|
||||
listOf(
|
||||
k(R.string.pckb_key_esc, 1), k("F1", 59), k("F2", 60), k("F3", 61), k("F4", 62), k("F5", 63), k("F6", 64),
|
||||
k("F7", 65), k("F8", 66), k("F9", 67), k("F10", 68), k("F11", 87), k("F12", 88),
|
||||
k(R.string.pckb_key_ins, 110), k(R.string.pckb_key_del, 111), k(R.string.pckb_key_home, 102), k(R.string.pckb_key_end, 107), k(R.string.pckb_key_pgup, 104), k(R.string.pckb_key_pgdn, 109),
|
||||
),
|
||||
listOf(
|
||||
k("`", 41, shifted = "~"), k("1", 2, shifted = "!"), k("2", 3, shifted = "@"), k("3", 4, shifted = "#"),
|
||||
k("4", 5, shifted = "$"), k("5", 6, shifted = "%"), k("6", 7, shifted = "^"), k("7", 8, shifted = "&"),
|
||||
k("8", 9, shifted = "*"), k("9", 10, shifted = "("), k("0", 11, shifted = ")"), k("-", 12, shifted = "_"),
|
||||
k("=", 13, shifted = "+"), k(R.string.pckb_key_backspace, 14, 2f),
|
||||
),
|
||||
listOf(
|
||||
k(R.string.pckb_key_tab, 15, 1.5f), k("q", 16), k("w", 17), k("e", 18), k("r", 19), k("t", 20), k("y", 21),
|
||||
k("u", 22), k("i", 23), k("o", 24), k("p", 25), k("[", 26, shifted = "{"), k("]", 27, shifted = "}"),
|
||||
k("\\", 43, 1.5f, shifted = "|"),
|
||||
),
|
||||
listOf(
|
||||
k(R.string.pckb_key_caps, 58, 1.75f), k("a", 30), k("s", 31), k("d", 32), k("f", 33), k("g", 34), k("h", 35),
|
||||
k("j", 36), k("k", 37), k("l", 38), k(";", 39, shifted = ":"), k("'", 40, shifted = "\""),
|
||||
k(R.string.pckb_key_enter, 28, 2.25f),
|
||||
),
|
||||
listOf(
|
||||
k(R.string.pckb_key_shift, 42, 2.25f), k("z", 44), k("x", 45), k("c", 46), k("v", 47), k("b", 48), k("n", 49),
|
||||
k("m", 50), k(",", 51, shifted = "<"), k(".", 52, shifted = ">"), k("/", 53, shifted = "?"),
|
||||
k(R.string.pckb_key_shift, 54, 1.75f), k("↑", 103),
|
||||
),
|
||||
listOf(
|
||||
k(R.string.pckb_key_ctrl, 29, 1.5f), k(R.string.pckb_key_super, 125, 1.25f), k(R.string.pckb_key_alt, 56, 1.25f), k(R.string.pckb_key_space, 57, 6.25f),
|
||||
k(R.string.pckb_key_altgr, 100, 1.25f), k(R.string.pckb_key_ctrl, 97, 1.25f), k("←", 105), k("↓", 108), k("→", 106),
|
||||
),
|
||||
)
|
||||
|
||||
val PC_MODIFIERS: Set<Int> = setOf(42, 54, 29, 97, 56, 100, 125)
|
||||
|
||||
val PC_KEYS: Map<Int, PcKey> = PC_KEY_ROWS.flatten().associateBy { it.code }
|
||||
|
||||
fun pcKeyLabel(context: Context, code: Int): String {
|
||||
val key = PC_KEYS[code] ?: return code.toString()
|
||||
val text = if (key.labelRes != 0) context.getString(key.labelRes) else key.label
|
||||
return if (text.length == 1 && text[0].isLetter()) text.uppercase() else text
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
|
||||
fun screenKeyLabel(context: Context, codes: List<Int>): String =
|
||||
codes.filter { it != 0 }.joinToString("+") { short(context, it) }
|
||||
|
||||
private fun short(context: Context, code: Int): String = when (code) {
|
||||
28 -> "⏎"
|
||||
14 -> "⌫"
|
||||
15 -> "Tab"
|
||||
57 -> "Space"
|
||||
58 -> "Caps"
|
||||
42, 54 -> "Shift"
|
||||
29, 97 -> "Ctrl"
|
||||
56 -> "Alt"
|
||||
100 -> "AltGr"
|
||||
125 -> "Super"
|
||||
else -> pcKeyLabel(context, code)
|
||||
}
|
||||
|
||||
const val SCREEN_KEY_PILL = 0
|
||||
const val SCREEN_KEY_ROUND = 1
|
||||
const val SCREEN_KEY_CIRCLE = 2
|
||||
const val SCREEN_KEY_RECT = 3
|
||||
const val SCREEN_KEY_TRIGGER = 4
|
||||
const val SCREEN_KEY_DPAD = 5
|
||||
const val SCREEN_KEY_STICK = 6
|
||||
|
||||
val SCREEN_KEY_DPAD_DIRS = listOf("↑", "→", "↓", "←")
|
||||
val SCREEN_KEY_STICK_DIRS = listOf("↑", "↗", "→", "↘", "↓", "↙", "←", "↖")
|
||||
|
||||
fun screenKeyDirections(shape: Int): List<String> = when (shape) {
|
||||
SCREEN_KEY_DPAD -> SCREEN_KEY_DPAD_DIRS
|
||||
SCREEN_KEY_STICK -> SCREEN_KEY_STICK_DIRS
|
||||
else -> emptyList()
|
||||
}
|
||||
|
||||
val SCREEN_KEY_SHAPES =
|
||||
listOf(
|
||||
SCREEN_KEY_PILL, SCREEN_KEY_ROUND, SCREEN_KEY_CIRCLE, SCREEN_KEY_RECT,
|
||||
SCREEN_KEY_TRIGGER, SCREEN_KEY_DPAD, SCREEN_KEY_STICK,
|
||||
)
|
||||
|
||||
data class ScreenKey(
|
||||
val codes: List<Int>,
|
||||
val x: Float,
|
||||
val y: Float,
|
||||
val size: Int,
|
||||
val glyph: String = "",
|
||||
val text: String = "",
|
||||
val image: String = "",
|
||||
val opacity: Float = 1f,
|
||||
val shape: Int = SCREEN_KEY_PILL,
|
||||
val toggle: Boolean = false,
|
||||
val labels: Boolean = true,
|
||||
) {
|
||||
fun shownLabel(context: Context): String = when {
|
||||
text.isNotEmpty() -> text
|
||||
glyph.isNotEmpty() -> glyph
|
||||
else -> screenKeyLabel(context, codes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
|
||||
object ScreenKeyIcons {
|
||||
fun has(code: Int): Boolean = code in SET
|
||||
|
||||
private val SET = setOf(28, 14, 15, 57, 42, 54, 29, 97, 125, 103, 108, 105, 106)
|
||||
|
||||
fun draw(canvas: Canvas, code: Int, cx: Float, cy: Float, box: Float, paint: Paint): Boolean {
|
||||
if (!has(code)) return false
|
||||
val h = box / 2f
|
||||
val stroke = box * 0.085f
|
||||
val path = Path()
|
||||
paint.style = Paint.Style.STROKE
|
||||
paint.strokeWidth = stroke
|
||||
paint.strokeCap = Paint.Cap.ROUND
|
||||
paint.strokeJoin = Paint.Join.ROUND
|
||||
when (code) {
|
||||
28 -> {
|
||||
path.moveTo(cx - 0.34f * h, cy - 0.22f * h)
|
||||
path.lineTo(cx + 0.30f * h, cy - 0.22f * h)
|
||||
path.lineTo(cx + 0.30f * h, cy + 0.24f * h)
|
||||
path.lineTo(cx - 0.04f * h, cy + 0.24f * h)
|
||||
canvas.drawPath(path, paint)
|
||||
path.reset()
|
||||
path.moveTo(cx + 0.12f * h, cy + 0.06f * h)
|
||||
path.lineTo(cx - 0.04f * h, cy + 0.24f * h)
|
||||
path.lineTo(cx + 0.12f * h, cy + 0.42f * h)
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
|
||||
14 -> {
|
||||
path.moveTo(cx - 0.72f * h, cy)
|
||||
path.lineTo(cx - 0.10f * h, cy - 0.50f * h)
|
||||
path.lineTo(cx + 0.74f * h, cy - 0.50f * h)
|
||||
path.lineTo(cx + 0.74f * h, cy + 0.50f * h)
|
||||
path.lineTo(cx - 0.10f * h, cy + 0.50f * h)
|
||||
path.close()
|
||||
canvas.drawPath(path, paint)
|
||||
path.reset()
|
||||
path.moveTo(cx + 0.10f * h, cy - 0.20f * h)
|
||||
path.lineTo(cx + 0.44f * h, cy + 0.20f * h)
|
||||
path.moveTo(cx + 0.44f * h, cy - 0.20f * h)
|
||||
path.lineTo(cx + 0.10f * h, cy + 0.20f * h)
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
|
||||
15 -> {
|
||||
path.moveTo(cx - 0.72f * h, cy)
|
||||
path.lineTo(cx + 0.44f * h, cy)
|
||||
path.moveTo(cx + 0.14f * h, cy - 0.30f * h)
|
||||
path.lineTo(cx + 0.46f * h, cy)
|
||||
path.lineTo(cx + 0.14f * h, cy + 0.30f * h)
|
||||
canvas.drawPath(path, paint)
|
||||
path.reset()
|
||||
path.moveTo(cx + 0.70f * h, cy - 0.48f * h)
|
||||
path.lineTo(cx + 0.70f * h, cy + 0.48f * h)
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
|
||||
57 -> {
|
||||
path.moveTo(cx - 0.64f * h, cy - 0.22f * h)
|
||||
path.lineTo(cx - 0.64f * h, cy + 0.20f * h)
|
||||
path.lineTo(cx + 0.64f * h, cy + 0.20f * h)
|
||||
path.lineTo(cx + 0.64f * h, cy - 0.22f * h)
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
|
||||
42, 54 -> {
|
||||
paint.style = Paint.Style.FILL
|
||||
path.moveTo(cx, cy - 0.55f * h)
|
||||
path.lineTo(cx + 0.62f * h, cy + 0.02f * h)
|
||||
path.lineTo(cx + 0.26f * h, cy + 0.02f * h)
|
||||
path.lineTo(cx + 0.26f * h, cy + 0.32f * h)
|
||||
path.lineTo(cx - 0.26f * h, cy + 0.32f * h)
|
||||
path.lineTo(cx - 0.26f * h, cy + 0.02f * h)
|
||||
path.lineTo(cx - 0.62f * h, cy + 0.02f * h)
|
||||
path.close()
|
||||
canvas.drawPath(path, paint)
|
||||
path.reset()
|
||||
path.moveTo(cx - 0.26f * h, cy + 0.44f * h)
|
||||
path.lineTo(cx + 0.26f * h, cy + 0.44f * h)
|
||||
path.lineTo(cx + 0.26f * h, cy + 0.58f * h)
|
||||
path.lineTo(cx - 0.26f * h, cy + 0.58f * h)
|
||||
path.close()
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
|
||||
29, 97 -> {
|
||||
path.moveTo(cx - 0.58f * h, cy + 0.26f * h)
|
||||
path.lineTo(cx, cy - 0.28f * h)
|
||||
path.lineTo(cx + 0.58f * h, cy + 0.26f * h)
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
|
||||
125 -> {
|
||||
paint.style = Paint.Style.FILL
|
||||
val gap = 0.07f * h
|
||||
val side = 0.34f * h
|
||||
for (dxi in -1..1 step 2) for (dyi in -1..1 step 2) {
|
||||
val left = cx + dxi * (gap + side / 2f) - side / 2f
|
||||
val top = cy + dyi * (gap + side / 2f) - side / 2f
|
||||
path.addRect(left, top, left + side, top + side, Path.Direction.CW)
|
||||
}
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
|
||||
103, 108, 105, 106 -> {
|
||||
paint.style = Paint.Style.FILL
|
||||
val r = 0.52f * h
|
||||
when (code) {
|
||||
103 -> {
|
||||
path.moveTo(cx, cy - r)
|
||||
path.lineTo(cx + r * 0.80f, cy + r * 0.55f)
|
||||
path.lineTo(cx - r * 0.80f, cy + r * 0.55f)
|
||||
}
|
||||
|
||||
108 -> {
|
||||
path.moveTo(cx, cy + r)
|
||||
path.lineTo(cx + r * 0.80f, cy - r * 0.55f)
|
||||
path.lineTo(cx - r * 0.80f, cy - r * 0.55f)
|
||||
}
|
||||
|
||||
105 -> {
|
||||
path.moveTo(cx - r, cy)
|
||||
path.lineTo(cx + r * 0.55f, cy - r * 0.80f)
|
||||
path.lineTo(cx + r * 0.55f, cy + r * 0.80f)
|
||||
}
|
||||
|
||||
else -> {
|
||||
path.moveTo(cx + r, cy)
|
||||
path.lineTo(cx - r * 0.55f, cy - r * 0.80f)
|
||||
path.lineTo(cx - r * 0.55f, cy + r * 0.80f)
|
||||
}
|
||||
}
|
||||
path.close()
|
||||
canvas.drawPath(path, paint)
|
||||
}
|
||||
}
|
||||
paint.style = Paint.Style.FILL
|
||||
paint.strokeCap = Paint.Cap.BUTT
|
||||
paint.strokeJoin = Paint.Join.MITER
|
||||
return true
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,140 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private val ICP_NAMES: Map<Int, String> = mapOf(
|
||||
103 to "KEY_UP", 106 to "KEY_RIGHT", 108 to "KEY_DOWN", 105 to "KEY_LEFT",
|
||||
28 to "KEY_ENTER", 1 to "KEY_ESC", 14 to "KEY_BKSP", 111 to "KEY_DEL", 15 to "KEY_TAB",
|
||||
57 to "KEY_SPACE", 29 to "KEY_CTRL_L", 97 to "KEY_CTRL_R", 110 to "KEY_INSERT",
|
||||
42 to "KEY_SHIFT_L", 54 to "KEY_SHIFT_R", 56 to "KEY_ALT_L", 100 to "KEY_ALT_R",
|
||||
102 to "KEY_HOME", 107 to "KEY_END", 99 to "KEY_PRTSCN", 104 to "KEY_PG_UP", 109 to "KEY_PG_DOWN",
|
||||
58 to "KEY_CAPS_LOCK", 69 to "KEY_NUM_LOCK", 41 to "KEY_GRAVE", 12 to "KEY_MINUS",
|
||||
11 to "KEY_0", 2 to "KEY_1", 3 to "KEY_2", 4 to "KEY_3", 5 to "KEY_4", 6 to "KEY_5",
|
||||
7 to "KEY_6", 8 to "KEY_7", 9 to "KEY_8", 10 to "KEY_9",
|
||||
30 to "KEY_A", 48 to "KEY_B", 46 to "KEY_C", 32 to "KEY_D", 18 to "KEY_E", 33 to "KEY_F",
|
||||
34 to "KEY_G", 35 to "KEY_H", 23 to "KEY_I", 36 to "KEY_J", 37 to "KEY_K", 38 to "KEY_L",
|
||||
50 to "KEY_M", 49 to "KEY_N", 24 to "KEY_O", 25 to "KEY_P", 16 to "KEY_Q", 19 to "KEY_R",
|
||||
31 to "KEY_S", 20 to "KEY_T", 22 to "KEY_U", 47 to "KEY_V", 17 to "KEY_W", 45 to "KEY_X",
|
||||
21 to "KEY_Y", 44 to "KEY_Z",
|
||||
26 to "KEY_BRACKET_LEFT", 27 to "KEY_BRACKET_RIGHT", 43 to "KEY_BACKSLASH", 53 to "KEY_SLASH",
|
||||
39 to "KEY_SEMICOLON", 51 to "KEY_COMMA", 52 to "KEY_PERIOD", 40 to "KEY_APOSTROPHE",
|
||||
59 to "KEY_F1", 60 to "KEY_F2", 61 to "KEY_F3", 62 to "KEY_F4", 63 to "KEY_F5", 64 to "KEY_F6",
|
||||
65 to "KEY_F7", 66 to "KEY_F8", 67 to "KEY_F9", 68 to "KEY_F10", 87 to "KEY_F11", 88 to "KEY_F12",
|
||||
79 to "KEY_KP_1", 80 to "KEY_KP_2", 81 to "KEY_KP_3", 75 to "KEY_KP_4", 76 to "KEY_KP_5",
|
||||
77 to "KEY_KP_6", 71 to "KEY_KP_7", 72 to "KEY_KP_8", 73 to "KEY_KP_9", 82 to "KEY_KP_0",
|
||||
)
|
||||
|
||||
private val ICP_CODES: Map<String, Int> = ICP_NAMES.entries.associate { (code, name) -> name to code }
|
||||
|
||||
private fun icpShape(shape: Int): String = when (shape) {
|
||||
SCREEN_KEY_CIRCLE -> "CIRCLE"
|
||||
SCREEN_KEY_RECT -> "RECT"
|
||||
SCREEN_KEY_ROUND -> "ROUND_RECT"
|
||||
SCREEN_KEY_DPAD -> "ROUND_RECT"
|
||||
SCREEN_KEY_STICK -> "ROUND_RECT"
|
||||
SCREEN_KEY_TRIGGER -> "ROUND_RECT"
|
||||
else -> "ROUND_RECT"
|
||||
}
|
||||
|
||||
private fun screenKeyShape(shape: String): Int = when (shape) {
|
||||
"CIRCLE" -> SCREEN_KEY_CIRCLE
|
||||
"RECT" -> SCREEN_KEY_RECT
|
||||
"SQUARE" -> SCREEN_KEY_ROUND
|
||||
else -> SCREEN_KEY_PILL
|
||||
}
|
||||
|
||||
fun exportScreenLayout(keys: List<ScreenKey>, widthPx: Int, density: Float): String {
|
||||
val snap = widthPx / 100f
|
||||
val elements = JSONArray()
|
||||
keys.forEach { key ->
|
||||
val binds = JSONArray()
|
||||
val directional = key.shape == SCREEN_KEY_DPAD || key.shape == SCREEN_KEY_STICK
|
||||
key.codes.forEach { code ->
|
||||
val name = ICP_NAMES[code]
|
||||
if (name != null) binds.put(name) else if (directional) binds.put("")
|
||||
}
|
||||
if (binds.length() == 0) return@forEach
|
||||
val shape = icpShape(key.shape)
|
||||
val sizePx = key.size * density
|
||||
val scale = when {
|
||||
key.shape == SCREEN_KEY_DPAD -> sizePx * 2.3f / (14f * snap)
|
||||
key.shape == SCREEN_KEY_STICK -> sizePx * 2.3f / (14f * snap)
|
||||
shape == "CIRCLE" -> sizePx / (6f * snap)
|
||||
else -> sizePx / (4f * snap)
|
||||
}
|
||||
elements.put(
|
||||
JSONObject()
|
||||
.put(
|
||||
"type",
|
||||
when (key.shape) {
|
||||
SCREEN_KEY_DPAD -> "D_PAD"
|
||||
SCREEN_KEY_STICK -> "STICK"
|
||||
else -> "BUTTON"
|
||||
},
|
||||
)
|
||||
.put("shape", shape)
|
||||
.put("customColor", 0)
|
||||
.put("bindings", binds)
|
||||
.put("scale", scale)
|
||||
.put("x", key.x)
|
||||
.put("y", key.y)
|
||||
.put("toggleSwitch", key.toggle)
|
||||
.put("swipeable", false)
|
||||
.put("text", key.text)
|
||||
.put("iconId", 0)
|
||||
.apply { if (key.opacity < 1f) put("opacity", key.opacity) },
|
||||
)
|
||||
}
|
||||
return JSONObject()
|
||||
.put("id", 0)
|
||||
.put("name", "DroidDeck")
|
||||
.put("cursorSpeed", 1.5f)
|
||||
.put("elements", elements)
|
||||
.toString()
|
||||
}
|
||||
|
||||
fun importScreenLayout(raw: String, widthPx: Int, density: Float): List<ScreenKey>? {
|
||||
val root = runCatching { JSONObject(raw) }.getOrNull() ?: return null
|
||||
val elements = root.optJSONArray("elements") ?: return null
|
||||
val snap = widthPx / 100f
|
||||
val keys = mutableListOf<ScreenKey>()
|
||||
for (i in 0 until elements.length()) {
|
||||
val element = elements.optJSONObject(i) ?: continue
|
||||
val type = element.optString("type", "BUTTON")
|
||||
if (type != "BUTTON" && type != "D_PAD" && type != "STICK") continue
|
||||
val binds = element.optJSONArray("bindings") ?: continue
|
||||
val raw = (0 until binds.length()).map { ICP_CODES[binds.optString(it)] ?: 0 }
|
||||
val codes = if (type == "D_PAD" || type == "STICK") {
|
||||
raw.dropLastWhile { it == 0 }.ifEmpty { listOf(0) }
|
||||
} else {
|
||||
raw.filter { it != 0 }
|
||||
}
|
||||
if (codes.isEmpty()) continue
|
||||
val dpad = type == "D_PAD"
|
||||
val stick = type == "STICK"
|
||||
val shape = when {
|
||||
dpad -> SCREEN_KEY_DPAD
|
||||
stick -> SCREEN_KEY_STICK
|
||||
else -> screenKeyShape(element.optString("shape"))
|
||||
}
|
||||
val scale = element.optDouble("scale", 1.0).toFloat().takeIf { it > 0f } ?: 1f
|
||||
val sizePx = when {
|
||||
dpad || stick -> 14f * snap * scale / 2.3f
|
||||
shape == SCREEN_KEY_CIRCLE -> 6f * snap * scale
|
||||
else -> 4f * snap * scale
|
||||
}
|
||||
keys += ScreenKey(
|
||||
codes = codes,
|
||||
x = element.optDouble("x", 0.5).toFloat().coerceIn(0f, 1f),
|
||||
y = element.optDouble("y", 0.5).toFloat().coerceIn(0f, 1f),
|
||||
size = (sizePx / density).roundToInt().coerceIn(ScreenKeys.MIN_SIZE, ScreenKeys.MAX_SIZE),
|
||||
text = element.optString("text").take(24),
|
||||
opacity = element.optDouble("opacity", 1.0).toFloat().coerceIn(0.2f, 1f),
|
||||
shape = shape,
|
||||
toggle = element.optBoolean("toggleSwitch"),
|
||||
)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
@@ -93,13 +93,18 @@ class SteamTouchControls(
|
||||
private var opened = 0
|
||||
private var elements: List<Element> = emptyList()
|
||||
private var tint = Color.WHITE
|
||||
private var alphaScale = 0.45f
|
||||
private var alphaScale = 0.99f
|
||||
var style: Pair<Int, Float> = Color.WHITE to 0.99f
|
||||
private set
|
||||
var onStyle: (() -> Unit)? = null
|
||||
|
||||
private class Visual(val ref: SteamTouchBindings.Ref?, val binding: SteamTouchBindings.Binding?)
|
||||
private var visuals: Map<Int, List<Visual>> = emptyMap()
|
||||
|
||||
private class Finger(val element: Element?, var x: Float, var y: Float, val toolbar: Int = -1)
|
||||
private val fingers = HashMap<Int, Finger>()
|
||||
private var forwardedPointerBits = 0
|
||||
var onTouchMiss: ((MotionEvent) -> Unit)? = null
|
||||
|
||||
private var editing = false
|
||||
private var editElements: MutableList<Element> = mutableListOf()
|
||||
@@ -191,6 +196,8 @@ class SteamTouchControls(
|
||||
private fun applyColor(color: FloatArray?) {
|
||||
tint = if (color != null) Color.rgb((color[0] * 255).toInt(), (color[1] * 255).toInt(), (color[2] * 255).toInt()) else Color.WHITE
|
||||
alphaScale = ((color?.get(3) ?: 0.45f) * 2.2f).coerceIn(0.15f, 1f)
|
||||
style = tint to alphaScale
|
||||
onStyle?.invoke()
|
||||
}
|
||||
|
||||
private fun rebuildVisuals() {
|
||||
@@ -624,7 +631,17 @@ class SteamTouchControls(
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
val e = hit(live(), x, y) ?: return event.actionMasked == MotionEvent.ACTION_POINTER_DOWN
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
|
||||
val e = hit(live(), x, y)
|
||||
if (e == null) {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) return false
|
||||
if (onTouchMiss != null) {
|
||||
forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(index))
|
||||
forwardPointers(event, forwardedPointerBits)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
fingers[event.getPointerId(index)] = Finger(e, x, y)
|
||||
if (feedback) performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
requestUnbufferedDispatch(event)
|
||||
@@ -632,6 +649,7 @@ class SteamTouchControls(
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
for (i in 0 until event.pointerCount) {
|
||||
val f = fingers[event.getPointerId(i)] ?: continue
|
||||
f.x = event.getX(i)
|
||||
@@ -650,12 +668,14 @@ class SteamTouchControls(
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
val id = event.getPointerId(index)
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
forwardedPointerBits = if (event.actionMasked == MotionEvent.ACTION_CANCEL) 0 else forwardedPointerBits and (1 shl id).inv()
|
||||
val f = fingers.remove(id)
|
||||
if (event.actionMasked == MotionEvent.ACTION_CANCEL) fingers.clear()
|
||||
val e = f?.element
|
||||
if (event.actionMasked != MotionEvent.ACTION_CANCEL && e != null && reach(e, event.getX(index), event.getY(index)) <= 1.3f) {
|
||||
when (e.type) {
|
||||
SteamTouchConfig.THUMB -> openMenu()
|
||||
SteamTouchConfig.THUMB -> { cancelForwarded(event); openMenu() }
|
||||
SteamTouchConfig.KEYBOARD -> onKeyboard()
|
||||
SteamTouchConfig.PASTE -> onPaste()
|
||||
}
|
||||
@@ -668,6 +688,25 @@ class SteamTouchControls(
|
||||
}
|
||||
|
||||
|
||||
private fun cancelForwarded(event: MotionEvent) {
|
||||
val split = event.pointerSubset(forwardedPointerBits).also { forwardedPointerBits = 0 } ?: return
|
||||
split.action = MotionEvent.ACTION_CANCEL
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
split.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
|
||||
val split = event.pointerSubset(pointerIdBits) ?: return
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
split.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
val isEditing get() = editing
|
||||
|
||||
fun startEditing() {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||
import java.io.File
|
||||
|
||||
object BattleNet {
|
||||
private const val TAG = "BattleNet"
|
||||
|
||||
const val APP_ID = 2596113170L
|
||||
|
||||
const val FEX_REQUEST = "battlenet-fex.request"
|
||||
const val FEX_RESULT = "battlenet-fex.result"
|
||||
|
||||
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
|
||||
|
||||
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null)
|
||||
|
||||
internal val TITLES = listOf(
|
||||
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow"),
|
||||
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic"),
|
||||
Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era"),
|
||||
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary"),
|
||||
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"),
|
||||
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
|
||||
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"),
|
||||
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered", product = "s1"),
|
||||
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone", product = "hsb"),
|
||||
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm", product = "hero"),
|
||||
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch", product = "pro"),
|
||||
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged", product = "w3"),
|
||||
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4", product = "viper"),
|
||||
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare", product = "odin"),
|
||||
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered", product = "lazr"),
|
||||
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war", product = "zeus"),
|
||||
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard", product = "fore"),
|
||||
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii", product = "auks"),
|
||||
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii", product = "pinta"),
|
||||
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4", product = "wlby"),
|
||||
Title("osi", "Diablo II: Resurrected", "OSI", product = "osi"),
|
||||
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection", product = "rtro"),
|
||||
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal", product = "anbs"),
|
||||
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
|
||||
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
|
||||
Title("d1", "Diablo", "D1", shop = "diablo", product = "drtl"),
|
||||
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans", product = "war1"),
|
||||
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition", product = "w2bn"),
|
||||
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered", product = "w1r"),
|
||||
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered", product = "w2r"),
|
||||
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble", product = "gryphon"),
|
||||
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages", product = "aris"),
|
||||
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves", product = "scor"),
|
||||
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2", product = "ark"),
|
||||
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710, product = "lbra"),
|
||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
|
||||
)
|
||||
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
|
||||
|
||||
fun notInstalled(title: Title, installedIds: Collection<String?>) =
|
||||
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
|
||||
|
||||
private const val COVER_RETRY_MS = 24 * 3600_000L
|
||||
|
||||
private fun coverDir(context: Context, title: Title) =
|
||||
File(context.filesDir, "battlenet-art/${(TITLES.firstOrNull { it.code == title.code } ?: title).uid}")
|
||||
|
||||
fun cover(context: Context, title: Title): File? = art(context, title).cover
|
||||
|
||||
private val coverLock = Any()
|
||||
|
||||
fun fetchCovers(context: Context, titles: List<Title> = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" }): Boolean = synchronized(coverLock) {
|
||||
val art = com.droiddeck.launcher.frontend.AddedGameArt
|
||||
val key = com.droiddeck.launcher.frontend.SteamGridDb.key(context)
|
||||
var got = false
|
||||
for (title in titles) {
|
||||
val dir = coverDir(context, title)
|
||||
val tried = File(dir, ".tried")
|
||||
val wide = File(dir, BLIZZARD)
|
||||
val done = File(dir, "p.jpg").isFile && (title.shop == null || wide.isFile)
|
||||
if (done || System.currentTimeMillis() - tried.lastModified() < COVER_RETRY_MS) continue
|
||||
dir.mkdirs()
|
||||
if (title.steam != null && runCatching { art.download(title.steam.toString(), dir) }.getOrDefault(false)) got = true
|
||||
if (title.shop != null && !wide.isFile) {
|
||||
val cover = File(dir, BLIZZARD_COVER).takeUnless { File(dir, "p.jpg").isFile }
|
||||
if (runCatching { com.droiddeck.launcher.stores.battlenet.BlizzardArt.fetch(title.shop, wide, cover) }
|
||||
.onFailure { Log.w(TAG, "Blizzard art for ${title.uid}: ${it.javaClass.simpleName}") }.getOrDefault(false)) got = true
|
||||
}
|
||||
if (!File(dir, "p.jpg").isFile && !File(dir, BLIZZARD_COVER).isFile && key.isNotEmpty()) {
|
||||
val id = runCatching { com.droiddeck.launcher.frontend.SteamGridDb.gameId(key, title.steam, title.name) }.getOrNull()
|
||||
if (id != null && runCatching { com.droiddeck.launcher.frontend.SteamGridDb.download(key, id, dir) }.getOrDefault(false)) got = true
|
||||
}
|
||||
runCatching { tried.writeText("") ; tried.setLastModified(System.currentTimeMillis()) }
|
||||
}
|
||||
got
|
||||
}
|
||||
|
||||
private val LOCALES = setOf(
|
||||
"enus", "engb", "dede", "eses", "esmx", "frfr", "itit", "kokr", "plpl", "ptbr", "ptpt", "ruru", "zhcn", "zhtw", "jajp", "thth", "trtr", "arsa",
|
||||
)
|
||||
|
||||
private val NOT_GAMES = setOf("agent", "bna", "battle.net")
|
||||
|
||||
class Game(val uid: String, val name: String, val code: String, val folder: File, val installUid: String = uid) {
|
||||
val title: Title get() = title(uid) ?: Title(uid, name, code)
|
||||
}
|
||||
|
||||
class Art(val cover: File?, val header: File?)
|
||||
|
||||
private const val BLIZZARD = "blizzard.jpg"
|
||||
private const val BLIZZARD_COVER = "p-blizzard.jpg"
|
||||
|
||||
fun art(context: Context, title: Title): Art {
|
||||
val dir = coverDir(context, title)
|
||||
fun first(vararg names: String) = names.map { File(dir, it) }.firstOrNull { it.isFile }
|
||||
return Art(first("p.jpg", BLIZZARD_COVER), first(BLIZZARD, "header.jpg"))
|
||||
}
|
||||
|
||||
fun prefix(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/compatdata/$APP_ID")
|
||||
|
||||
fun client(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe")
|
||||
|
||||
fun installed(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe").isFile
|
||||
|
||||
fun profile(context: Context): Pair<String, String>? =
|
||||
(APP_ID.toString() to context.getString(com.droiddeck.launcher.R.string.bnet_name)).takeIf { installed(context) }
|
||||
|
||||
fun icon(context: Context): File? {
|
||||
val out = File(context.filesDir, "battlenet-art/launcher/icon.png")
|
||||
if (out.isFile) return out
|
||||
val exe = client(context).takeIf { it.isFile } ?: return null
|
||||
val bitmap = runCatching { com.droiddeck.launcher.files.PeIconExtractor.extract(exe) }.getOrNull() ?: return null
|
||||
return runCatching {
|
||||
out.parentFile?.mkdirs()
|
||||
val tmp = File(out.path + ".tmp")
|
||||
tmp.outputStream().use { check(bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it)) }
|
||||
check(tmp.renameTo(out))
|
||||
out
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
fun launcherEntry(installed: Boolean, art: File? = null): com.droiddeck.launcher.frontend.Library.SteamGame? =
|
||||
if (!installed) null
|
||||
else com.droiddeck.launcher.frontend.Library.SteamGame(
|
||||
appId = APP_ID.toInt(), name = com.droiddeck.launcher.stores.Store.BATTLENET.label, art = art,
|
||||
library = com.droiddeck.launcher.frontend.Library.BATTLENET_LAUNCHER, gameId = APP_ID,
|
||||
source = com.droiddeck.launcher.stores.Store.BATTLENET.id,
|
||||
)
|
||||
|
||||
fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"]
|
||||
|
||||
internal fun title(uid: String): Title? {
|
||||
val id = uid.lowercase()
|
||||
TITLES.firstOrNull { it.uid == id }?.let { return it }
|
||||
val base = id.substringBeforeLast('_', "")
|
||||
return if (base.isNotEmpty() && id.substringAfterLast('_') in LOCALES) TITLES.firstOrNull { it.uid == base } else null
|
||||
}
|
||||
|
||||
fun games(context: Context): List<Game> {
|
||||
val pfx = File(prefix(context), "pfx")
|
||||
val entries = installs(
|
||||
runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()),
|
||||
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull(),
|
||||
)
|
||||
val found = LinkedHashMap<String, Game>()
|
||||
for ((uid, path) in entries) {
|
||||
val title = title(uid)
|
||||
if (title == null) {
|
||||
if (uid.lowercase() !in NOT_GAMES) Log.i(TAG, "not listed: $uid (no launch code known)")
|
||||
continue
|
||||
}
|
||||
if (title.code in found) continue
|
||||
val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue
|
||||
found[title.code] = Game(title.uid, title.name, title.code, folder, uid)
|
||||
}
|
||||
return found.values.toList()
|
||||
}
|
||||
|
||||
internal fun installs(registry: List<Pair<String, String>>, agent: List<Pair<String, String>>?): List<Pair<String, String>> {
|
||||
if (agent == null) return registry
|
||||
val tracked = agent.map { it.first.lowercase() }.toSet()
|
||||
return registry.filter { it.first.lowercase() in tracked } + agent
|
||||
}
|
||||
|
||||
internal fun hostFolder(context: Context, path: String): File? {
|
||||
val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
|
||||
val relative = drive.groupValues[2].replace('\\', '/').trim('/')
|
||||
if (relative.isEmpty() || relative.split('/').any { it == ".." }) return null
|
||||
return if (drive.groupValues[1].equals("c", ignoreCase = true)) File(prefix(context), "pfx/drive_c/$relative")
|
||||
else com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "/$relative")
|
||||
}
|
||||
|
||||
private val KEY = Regex("""^\[(.+)\](?:\s+\d+)?\s*$""")
|
||||
private val UNINSTALL = Regex("""(?i)\\CurrentVersion\\Uninstall\\[^\\]+$""")
|
||||
private val VALUE = Regex("""^"((?:[^"\\]|\\.)*)"=(?:str\(\d+\):)?"((?:[^"\\]|\\.)*)"\s*$""")
|
||||
private val UID = Regex("""--uid=([A-Za-z0-9_.-]+)""")
|
||||
|
||||
internal fun uninstallEntries(lines: Sequence<String>): List<Pair<String, String>> {
|
||||
val out = ArrayList<Pair<String, String>>()
|
||||
var inside = false
|
||||
var uid: String? = null
|
||||
var location: String? = null
|
||||
fun flush() {
|
||||
val u = uid
|
||||
val l = location
|
||||
if (u != null && l != null) out.add(u to l)
|
||||
uid = null
|
||||
location = null
|
||||
}
|
||||
for (line in lines) {
|
||||
if (line.startsWith("[")) {
|
||||
flush()
|
||||
inside = KEY.matchEntire(line)?.groupValues?.get(1)?.let { UNINSTALL.containsMatchIn(unescape(it)) } == true
|
||||
continue
|
||||
}
|
||||
if (!inside) continue
|
||||
val value = VALUE.matchEntire(line) ?: continue
|
||||
val text = unescape(value.groupValues[2])
|
||||
when (unescape(value.groupValues[1]).lowercase()) {
|
||||
"uninstallstring" -> if (text.contains("battle.net", ignoreCase = true)) uid = UID.find(text)?.groupValues?.get(1)
|
||||
"installlocation" -> location = text
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return out
|
||||
}
|
||||
|
||||
private fun unescape(s: String): String {
|
||||
val out = StringBuilder(s.length)
|
||||
var i = 0
|
||||
while (i < s.length) {
|
||||
val c = s[i++]
|
||||
if (c != '\\' || i >= s.length) { out.append(c); continue }
|
||||
when (val e = s[i++]) {
|
||||
'n' -> out.append('\n')
|
||||
'r' -> out.append('\r')
|
||||
't' -> out.append('\t')
|
||||
'0' -> out.append('\u0000')
|
||||
'x' -> {
|
||||
var end = i
|
||||
while (end < s.length && end - i < 4 && s[end].lowercaseChar() in "0123456789abcdef") end++
|
||||
if (end > i) { out.append(s.substring(i, end).toInt(16).toChar()); i = end } else out.append('x')
|
||||
}
|
||||
else -> out.append(e)
|
||||
}
|
||||
}
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? {
|
||||
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null
|
||||
return installs.map { (_, start, end) ->
|
||||
runCatching {
|
||||
val install = fields(bytes, start, end)
|
||||
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
|
||||
val path = install.firstOrNull { it.first == 3 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
|
||||
?.let { String(bytes, it.second, it.third - it.second) }
|
||||
val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
|
||||
?.let { s -> varints(bytes, s.second, s.third)[1] }
|
||||
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path
|
||||
}.getOrElse { return null }
|
||||
}.filterNotNull()
|
||||
}
|
||||
|
||||
private fun fields(bytes: ByteArray, from: Int, to: Int): List<Triple<Int, Int, Int>> = walk(bytes, from, to) { _, _ -> }
|
||||
|
||||
private fun varints(bytes: ByteArray, from: Int, to: Int): Map<Int, Long> =
|
||||
HashMap<Int, Long>().also { found -> walk(bytes, from, to) { field, value -> found.putIfAbsent(field, value) } }
|
||||
|
||||
private fun walk(bytes: ByteArray, from: Int, to: Int, varint: (Int, Long) -> Unit): List<Triple<Int, Int, Int>> {
|
||||
val out = ArrayList<Triple<Int, Int, Int>>()
|
||||
var i = from
|
||||
fun next(): Long {
|
||||
var value = 0L
|
||||
var shift = 0
|
||||
while (true) {
|
||||
require(i < to && shift < 64) { "truncated" }
|
||||
val b = bytes[i++].toInt() and 0xff
|
||||
value = value or ((b and 0x7f).toLong() shl shift)
|
||||
if (b < 0x80) return value
|
||||
shift += 7
|
||||
}
|
||||
}
|
||||
while (i < to) {
|
||||
val key = next()
|
||||
when ((key and 7).toInt()) {
|
||||
0 -> varint((key ushr 3).toInt(), next())
|
||||
1 -> { require(to - i >= 8) { "truncated" }; i += 8 }
|
||||
2 -> {
|
||||
val n = next()
|
||||
require(n in 0..(to - i).toLong()) { "truncated" }
|
||||
out.add(Triple((key ushr 3).toInt(), i, i + n.toInt()))
|
||||
i += n.toInt()
|
||||
}
|
||||
5 -> { require(to - i >= 4) { "truncated" }; i += 4 }
|
||||
else -> error("wire type ${key and 7}")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun shortcut(context: Context, game: Game): com.droiddeck.launcher.frontend.AddedGames.Game? {
|
||||
val added = com.droiddeck.launcher.frontend.AddedGames
|
||||
val client = client(context)
|
||||
val guestExe = added.guestPath(context, client) ?: return null
|
||||
val guestDir = added.guestPath(context, client.parentFile ?: return null) ?: return null
|
||||
val guestPrefix = added.guestPath(context, prefix(context)) ?: return null
|
||||
val crc = java.util.zip.CRC32().apply { update("\"$guestExe\"${game.name}".toByteArray()) }.value
|
||||
val appId = com.droiddeck.launcher.session.SessionPrefs.addedGameAppId(context, game.folder.path, crc or 0x80000000L)
|
||||
val exe = added.candidates(game.folder).firstOrNull() ?: client
|
||||
return com.droiddeck.launcher.frontend.AddedGames.Game(
|
||||
game.folder, game.name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, listOf(exe),
|
||||
source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = game.uid,
|
||||
launchOptions = "STEAM_COMPAT_DATA_PATH=$guestPrefix %command% --exec=\"launch ${game.code}\"",
|
||||
)
|
||||
}
|
||||
|
||||
fun remove(context: Context) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
com.droiddeck.launcher.core.FileUtils.delete(prefix(context))
|
||||
File(root, "usr/local/share/applications/droiddeck-battlenet.desktop").delete()
|
||||
com.droiddeck.launcher.core.FileUtils.delete(File(root, "root/.cache/droiddeck/battlenet"))
|
||||
ComponentsManager.clearGameComponents(context, APP_ID.toString())
|
||||
Log.i(TAG, "removed")
|
||||
}
|
||||
|
||||
private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""")
|
||||
|
||||
private const val LISTING_MAX_AGE = 6 * 3600L
|
||||
|
||||
private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b ->
|
||||
for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i])
|
||||
if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second)
|
||||
}
|
||||
|
||||
internal fun d2rfix(file: String): Pair<List<Long>, Long>? {
|
||||
val m = D2RFIX.matchEntire(file) ?: return null
|
||||
val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
|
||||
return version to (m.groupValues[2].toLongOrNull() ?: return null)
|
||||
}
|
||||
|
||||
internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? =
|
||||
items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } }
|
||||
.maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first
|
||||
|
||||
fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items }
|
||||
|
||||
@Synchronized
|
||||
internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String {
|
||||
val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing")
|
||||
val file = ComponentsManager.safeName(item.file)
|
||||
if (ComponentsManager.packages(context).none { it.file == file }) {
|
||||
Log.i(TAG, "downloading ${item.file}")
|
||||
ComponentsManager.download(context, item) {}
|
||||
}
|
||||
val scope = APP_ID.toString()
|
||||
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
|
||||
ComponentsManager.setGameComponent(context, scope, "fex", file)
|
||||
Log.i(TAG, "FEX for the Battle.net prefix: $file")
|
||||
} else if (ComponentsManager.republish(context)) {
|
||||
Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton")
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> {
|
||||
val cached = ComponentsManager.catalog(context, false)
|
||||
val age = System.currentTimeMillis() / 1000 - cached.fetchedAt
|
||||
if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items
|
||||
val fetched = runCatching { refresh(context) }
|
||||
.onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty()
|
||||
return if (newestD2rFix(fetched) != null) fetched else cached.items
|
||||
}
|
||||
|
||||
internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt()
|
||||
|
||||
internal fun videoMemoryOptions(megabytes: Int): String =
|
||||
"dxgi.maxDeviceMemory = $megabytes; dxgi.maxSharedMemory = $megabytes; d3d9.maxAvailableMemory = $megabytes"
|
||||
|
||||
fun ensureVideoMemory(context: Context): Boolean {
|
||||
val memory = ActivityManager.MemoryInfo()
|
||||
context.getSystemService(ActivityManager::class.java)?.getMemoryInfo(memory) ?: return false
|
||||
if (memory.totalMem <= 0) return false
|
||||
val options = videoMemoryOptions(videoMemory(memory.totalMem / (1024 * 1024)))
|
||||
val set = GameEnvironmentStore.setDefault(context, APP_ID.toString(), DXVK_CONFIG, options)
|
||||
if (set) Log.i(TAG, "DXVK_CONFIG for the Battle.net profile: $options")
|
||||
return set
|
||||
}
|
||||
|
||||
private const val DXVK_CONFIG = "DXVK_CONFIG"
|
||||
|
||||
fun ensureNoSteam(context: Context): Boolean {
|
||||
if (com.droiddeck.launcher.session.SessionPrefs.battleNetNoSteamSet(context)) return false
|
||||
GameEnvironmentStore.setGameNoSteam(context, APP_ID.toString(), true)
|
||||
com.droiddeck.launcher.session.SessionPrefs.setBattleNetNoSteamSet(context)
|
||||
Log.i(TAG, "Start without Steam for the Battle.net profile")
|
||||
return true
|
||||
}
|
||||
|
||||
fun answerFexRequest(context: Context, dir: File) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
|
||||
runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
|
||||
val answer = try {
|
||||
"ok " + ensureFex(app)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "FEX for the Battle.net prefix", e)
|
||||
"error " + (e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
Log.i(TAG, "FEX request: $answer")
|
||||
val result = File(dir, FEX_RESULT)
|
||||
val partial = File(dir, "$FEX_RESULT.tmp")
|
||||
runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) }
|
||||
}, "battlenet-fex").start()
|
||||
}
|
||||
}
|
||||
@@ -220,6 +220,7 @@ object BwrapSpawner {
|
||||
val binds = ArrayList<Bind>()
|
||||
val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } }
|
||||
env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":")
|
||||
File(rootfs, NET_LINK).takeIf { it.isFile }?.let { binds.add(Bind(it.path, "/$NET_LINK")) }
|
||||
env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev ->
|
||||
binds.addAll(bindsFor(session, rootfs, dev, dev))
|
||||
}
|
||||
@@ -227,6 +228,7 @@ object BwrapSpawner {
|
||||
}
|
||||
|
||||
private const val PRELOAD_DIR = "/run/droiddeck-preload"
|
||||
private const val NET_LINK = "etc/droiddeck-net"
|
||||
|
||||
private const val ZYPAK_SHIM = "#!/bin/sh\nprogram=\$1\nshift\nexec \"\$program\" --no-sandbox \"\$@\"\n"
|
||||
|
||||
|
||||
@@ -71,9 +71,22 @@ object DesktopCatalog {
|
||||
}
|
||||
|
||||
fun resumeInterrupted(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
|
||||
resumeInterrupted(context, null, listener)
|
||||
}
|
||||
|
||||
fun resumeInterrupted(
|
||||
context: Context,
|
||||
cancelled: Downloader.Cancellation?,
|
||||
listener: LinuxRuntimeInstaller.ProgressListener?,
|
||||
): String? = synchronized(installLock) {
|
||||
for (entry in interrupted(context)) {
|
||||
Log.w(TAG, "finishing the interrupted install of ${entry.id} ${entry.version}")
|
||||
install(context, entry, listener)?.let { return it }
|
||||
val problem = if (cancelled == null) {
|
||||
install(context, entry, listener)
|
||||
} else {
|
||||
install(context, entry, cancelled, listener)
|
||||
}
|
||||
if (problem != null) return problem
|
||||
}
|
||||
null
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,19 @@ package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import com.droiddeck.launcher.core.DownloadSource
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.session.OrphanReaper
|
||||
import com.droiddeck.launcher.session.SessionFiles
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object GuestCommand {
|
||||
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
||||
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, onLine: (String) -> Unit): Int {
|
||||
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
|
||||
onLine: (String) -> Unit): Int {
|
||||
val log = logName?.let {
|
||||
try {
|
||||
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
||||
@@ -19,14 +22,14 @@ object GuestCommand {
|
||||
}
|
||||
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
|
||||
try {
|
||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
} finally {
|
||||
log?.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
|
||||
fastPath: Boolean, onLine: (String) -> Unit): Int {
|
||||
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
SessionFiles.stage(context, root)
|
||||
@@ -45,6 +48,15 @@ object GuestCommand {
|
||||
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
|
||||
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
|
||||
)
|
||||
// The Steam client installer and the package tools inside the guest fetch over plain curl,
|
||||
// so the app proxy has to reach them through the environment proot starts them with.
|
||||
DownloadSource.proxyHostPort(context).takeIf { it.isNotEmpty() }?.let { hostPort ->
|
||||
cmd += listOf(
|
||||
"http_proxy=http://$hostPort", "https_proxy=http://$hostPort",
|
||||
"HTTP_PROXY=http://$hostPort", "HTTPS_PROXY=http://$hostPort",
|
||||
"no_proxy=localhost,127.0.0.1,::1", "NO_PROXY=localhost,127.0.0.1,::1",
|
||||
)
|
||||
}
|
||||
fastPathKey?.let { cmd += ProotFastPath.guestEnv(root, binds, it) }
|
||||
cmd += argv
|
||||
val builder = ProcessBuilder(cmd).directory(root).redirectErrorStream(true)
|
||||
@@ -56,13 +68,32 @@ object GuestCommand {
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
if (cancelled?.get() == true) return 130
|
||||
val process = builder.start()
|
||||
val pid = HostProcess.pidOf(process)
|
||||
OrphanReaper.keep(pid)
|
||||
val watcher = cancelled?.let { flag ->
|
||||
Thread({
|
||||
try {
|
||||
while (process.isAlive && !flag.get()) Thread.sleep(200)
|
||||
if (flag.get()) {
|
||||
// PRoot ignores SIGTERM; SIGQUIT makes it kill its tracees and exit cleanly.
|
||||
if (pid > 0) {
|
||||
runCatching { android.system.Os.kill(pid, android.system.OsConstants.SIGQUIT) }
|
||||
} else {
|
||||
process.destroy()
|
||||
}
|
||||
if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) process.destroyForcibly()
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
}
|
||||
}, "guest-cancel").apply { isDaemon = true; start() }
|
||||
}
|
||||
try {
|
||||
process.inputStream.bufferedReader().useLines { lines -> lines.forEach(onLine) }
|
||||
return process.waitFor()
|
||||
} finally {
|
||||
watcher?.interrupt()
|
||||
OrphanReaper.release(pid)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.util.Log;
|
||||
|
||||
|
||||
import com.droiddeck.launcher.R;
|
||||
import com.droiddeck.launcher.session.SessionPrefs;
|
||||
import com.droiddeck.launcher.core.ArchivePaths;
|
||||
import com.droiddeck.launcher.core.Downloader;
|
||||
import com.droiddeck.launcher.core.Hashes;
|
||||
@@ -262,7 +263,9 @@ public final class LinuxRuntimeInstaller {
|
||||
emptyTrash(LinuxRuntime.rootDir(context).getParentFile());
|
||||
String downloading = context.getString(R.string.rtinst_downloading);
|
||||
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
|
||||
if (!AddonPack.PROOT.await(context)) throw new IOException("Cannot download proot");
|
||||
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context)
|
||||
&& !SessionPrefs.allowStockProot(context))
|
||||
throw new IOException("Cannot download proot");
|
||||
if (!AddonPack.DIRECTAUDIO.await(context)) throw new IOException("Cannot download DirectAudio");
|
||||
boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> {
|
||||
if (listener != null) {
|
||||
@@ -299,27 +302,50 @@ public final class LinuxRuntimeInstaller {
|
||||
discard(staging, null);
|
||||
return false;
|
||||
}
|
||||
java.util.List<String> carryPaths = root.isDirectory()
|
||||
? RuntimeFileTree.existingUserPaths(root, staging) : java.util.Collections.emptyList();
|
||||
if (root.isDirectory() && !root.renameTo(old)) {
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
return false;
|
||||
}
|
||||
File carryMarker = new File(staging, CARRY_MARKER);
|
||||
java.util.List<String> encodedPaths = new java.util.ArrayList<>();
|
||||
for (String rel : carryPaths) encodedPaths.add(java.net.URLEncoder.encode(rel, "UTF-8"));
|
||||
if (!FileUtils.writeString(carryMarker, String.join("\n", encodedPaths))) {
|
||||
if (old.isDirectory() && !old.renameTo(root))
|
||||
Log.w(TAG, "could not restore the previous runtime; retained at " + old);
|
||||
discard(staging, null);
|
||||
return false;
|
||||
}
|
||||
|
||||
java.util.List<String> carried;
|
||||
try {
|
||||
RuntimeFileTree.carryHome(old, staging);
|
||||
carried = RuntimeFileTree.carryUserData(old, staging, false, carryPaths);
|
||||
} catch (IOException e) {
|
||||
Log.w(TAG, "could not carry root across the update; rolling back", e);
|
||||
old.renameTo(root);
|
||||
try { RuntimeFileTree.delete(staging, null); }
|
||||
catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); }
|
||||
Log.w(TAG, "could not carry user data across the update; rolling back", e);
|
||||
if (old.isDirectory() && !old.renameTo(root))
|
||||
Log.w(TAG, "could not restore the previous runtime; retained at " + old);
|
||||
if (e.getSuppressed().length == 0) {
|
||||
new File(staging, CARRY_MARKER).delete();
|
||||
try { RuntimeFileTree.delete(staging, null); }
|
||||
catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); }
|
||||
} else {
|
||||
Log.w(TAG, "incomplete rollback; retaining user data in " + staging);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!staging.renameTo(root)) {
|
||||
File keptTo = new File(staging, USER_DATA);
|
||||
if (keptTo.isDirectory() && old.isDirectory()) keptTo.renameTo(new File(old, USER_DATA));
|
||||
if (old.isDirectory()) old.renameTo(root);
|
||||
if (old.isDirectory()) {
|
||||
try {
|
||||
RuntimeFileTree.carryBack(staging, old, carried);
|
||||
new File(staging, CARRY_MARKER).delete();
|
||||
} catch (IOException e) { Log.w(TAG, "could not move all user data back after a failed swap", e); }
|
||||
old.renameTo(root);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
new File(root, CARRY_MARKER).delete();
|
||||
discard(old, null);
|
||||
return LinuxRuntime.isInstalled(context);
|
||||
} catch (Exception e) {
|
||||
@@ -330,17 +356,41 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
static final String CARRY_MARKER = ".droiddeck-carry";
|
||||
|
||||
static void recoverInterruptedSwap(File root, File staging, File old) throws IOException {
|
||||
if (!root.isDirectory() && old.isDirectory()) {
|
||||
if (!old.renameTo(root)) throw new IOException("Cannot restore the previous runtime at " + old);
|
||||
Log.w(TAG, "restored the previous runtime after an interrupted update");
|
||||
}
|
||||
File marker = new File(staging, CARRY_MARKER);
|
||||
if (!RuntimeFileTree.exists(marker.toPath())) return;
|
||||
File target = root.isDirectory() ? root : old;
|
||||
String markerContent = FileUtils.readString(marker);
|
||||
if (markerContent == null) throw new IOException("Cannot read runtime recovery marker: " + marker);
|
||||
if (!markerContent.equals("1")) {
|
||||
java.util.List<String> intended = new java.util.ArrayList<>();
|
||||
for (String rel : markerContent.split("\\n"))
|
||||
if (!rel.isEmpty()) intended.add(java.net.URLDecoder.decode(rel, "UTF-8"));
|
||||
if (target.isDirectory()) RuntimeFileTree.recoverCarriedPaths(staging, target, intended);
|
||||
if (staging.isDirectory() && RuntimeFileTree.hasPaths(staging, intended))
|
||||
throw new IOException("User data still needs recovery from " + staging);
|
||||
marker.delete();
|
||||
return;
|
||||
}
|
||||
File stagedHome = new File(staging, USER_DATA);
|
||||
File home = new File(target, USER_DATA);
|
||||
if (target.isDirectory() && stagedHome.isDirectory() && (!home.exists() || isEmptyDir(home))) {
|
||||
if (target.isDirectory() && stagedHome.isDirectory() && (!RuntimeFileTree.exists(home.toPath()) || isEmptyDir(home))) {
|
||||
RuntimeFileTree.carryHome(staging, target);
|
||||
Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update");
|
||||
}
|
||||
if (!root.isDirectory() && old.isDirectory() && old.renameTo(root)) {
|
||||
Log.w(TAG, "restored the previous runtime after an interrupted update");
|
||||
if (target.isDirectory() && staging.isDirectory()) {
|
||||
java.util.List<String> rest = RuntimeFileTree.carryUserData(staging, target, true);
|
||||
if (!rest.isEmpty()) Log.w(TAG, "recovered " + rest + " from an interrupted update");
|
||||
}
|
||||
if (staging.isDirectory() && RuntimeFileTree.hasUserData(staging, target))
|
||||
throw new IOException("User data still needs recovery from " + staging);
|
||||
new File(staging, CARRY_MARKER).delete();
|
||||
}
|
||||
|
||||
static final String TRASH = ".runtime-trash";
|
||||
@@ -364,9 +414,10 @@ public final class LinuxRuntimeInstaller {
|
||||
Log.i(TAG, "some runtime leftovers still cannot be deleted: " + trash);
|
||||
}
|
||||
|
||||
private static boolean isEmptyDir(File dir) {
|
||||
String[] names = dir.list();
|
||||
return dir.isDirectory() && names != null && names.length == 0;
|
||||
private static boolean isEmptyDir(File dir) throws IOException {
|
||||
try (java.nio.file.DirectoryStream<java.nio.file.Path> entries = java.nio.file.Files.newDirectoryStream(dir.toPath())) {
|
||||
return !entries.iterator().hasNext();
|
||||
}
|
||||
}
|
||||
|
||||
public static Removal beginUninstall(Context context) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -74,6 +74,163 @@ public final class RuntimeFileTree {
|
||||
throw new IOException("Cannot make directory removable: " + dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paths in a runtime tree that belong to the user: the home folder, imported AppImages and script apps, and catalog
|
||||
* AppImages with their menu entries and markers. Tar-kind catalog packages (the desktop) unpack over /usr and cannot
|
||||
* be carried.
|
||||
*/
|
||||
static java.util.List<String> userPaths(File tree) throws IOException {
|
||||
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps"));
|
||||
for (String n : children(new File(tree, "usr/local/share/applications"))) {
|
||||
if (n.endsWith(".desktop") && (n.startsWith("droiddeck-app-") || n.startsWith("droiddeck-appimage-")))
|
||||
paths.add("usr/local/share/applications/" + n);
|
||||
}
|
||||
for (String n : children(new File(tree, "opt/appimages"))) {
|
||||
if (!n.endsWith(".AppImage")) continue;
|
||||
String id = n.substring(0, n.length() - ".AppImage".length());
|
||||
java.util.Collections.addAll(paths, "opt/appimages/" + n,
|
||||
"usr/share/applications/droiddeck-" + id + ".desktop", ".droiddeck-pkg-" + id);
|
||||
}
|
||||
for (String n : children(new File(tree, "usr/share/applications"))) {
|
||||
if (!n.startsWith("droiddeck-") || !n.endsWith(".desktop")) continue;
|
||||
String id = n.substring("droiddeck-".length(), n.length() - ".desktop".length());
|
||||
if (!exists(new File(tree, "opt/appimages/" + id + ".AppImage").toPath()))
|
||||
paths.add("usr/share/applications/" + n);
|
||||
}
|
||||
for (String n : children(tree)) {
|
||||
if (!n.startsWith(".droiddeck-pkg-")) continue;
|
||||
String id = n.substring(".droiddeck-pkg-".length());
|
||||
boolean hasMenu = exists(new File(tree, "usr/share/applications/droiddeck-" + id + ".desktop").toPath());
|
||||
if (hasMenu && !exists(new File(tree, "opt/appimages/" + id + ".AppImage").toPath()))
|
||||
paths.add(n);
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
static java.util.List<String> existingUserPaths(File from, File to) throws IOException {
|
||||
java.util.List<String> paths = new java.util.ArrayList<>();
|
||||
for (String rel : userPaths(from, to)) if (exists(safePath(from, rel).toPath())) paths.add(rel);
|
||||
return paths;
|
||||
}
|
||||
|
||||
private static java.util.List<String> children(File dir) throws IOException {
|
||||
java.util.List<String> names = new java.util.ArrayList<>();
|
||||
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir.toPath())) {
|
||||
for (Path entry : entries) names.add(entry.getFileName().toString());
|
||||
} catch (NoSuchFileException e) {
|
||||
return names;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
static boolean exists(Path path) throws IOException {
|
||||
try { Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); return true; }
|
||||
catch (NoSuchFileException e) { return false; }
|
||||
}
|
||||
|
||||
private static java.util.Set<String> userPaths(File from, File to) throws IOException {
|
||||
java.util.Set<String> paths = new java.util.LinkedHashSet<>(userPaths(from));
|
||||
paths.addAll(userPaths(to));
|
||||
return paths;
|
||||
}
|
||||
|
||||
static boolean hasUserData(File from, File to) throws IOException {
|
||||
for (String rel : userPaths(from, to)) if (exists(new File(from, rel).toPath())) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves each user path that exists in {@code from} into {@code to}, replacing what {@code to} ships there. With
|
||||
* {@code onlyMissing}, a path already present in {@code to} is left alone. On failure the paths already moved go back
|
||||
* before the exception is thrown. Rollback failures are suppressed on that exception; callers must retain the source
|
||||
* of any incomplete rollback.
|
||||
* Returns the moved paths.
|
||||
*/
|
||||
static java.util.List<String> carryUserData(File from, File to, boolean onlyMissing) throws IOException {
|
||||
return carryUserData(from, to, onlyMissing, new java.util.ArrayList<>(userPaths(from, to)));
|
||||
}
|
||||
|
||||
static java.util.List<String> carryUserData(File from, File to, boolean onlyMissing, java.util.List<String> paths) throws IOException {
|
||||
java.util.List<String> moved = new java.util.ArrayList<>();
|
||||
try {
|
||||
for (String rel : paths) {
|
||||
File src = safePath(from, rel);
|
||||
if (!exists(src.toPath())) continue;
|
||||
File dst = safePath(to, rel);
|
||||
if (onlyMissing && exists(dst.toPath())) continue;
|
||||
move(from, to, rel);
|
||||
moved.add(rel);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
for (int i = moved.size() - 1; i >= 0; i--) {
|
||||
try { move(to, from, moved.get(i)); }
|
||||
catch (IOException back) { e.addSuppressed(back); }
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
/** Puts the given paths back from {@code from} into {@code to}; failures are collected, not stopped on. */
|
||||
static void carryBack(File from, File to, java.util.List<String> paths) throws IOException {
|
||||
IOException failed = null;
|
||||
for (int i = paths.size() - 1; i >= 0; i--) {
|
||||
try { move(from, to, paths.get(i)); }
|
||||
catch (IOException e) { if (failed == null) failed = e; else failed.addSuppressed(e); }
|
||||
}
|
||||
if (failed != null) throw failed;
|
||||
}
|
||||
|
||||
private static void move(File from, File to, String rel) throws IOException {
|
||||
File src = safePath(from, rel);
|
||||
File dst = safePath(to, rel);
|
||||
File parent = src.getParentFile();
|
||||
if (parent != null) makeWritable(parent);
|
||||
java.util.List<File> made = new java.util.ArrayList<>();
|
||||
for (File d = dst.getParentFile(); d != null; d = d.getParentFile()) {
|
||||
made.add(d);
|
||||
if (d.equals(to)) break;
|
||||
}
|
||||
for (int i = made.size() - 1; i >= 0; i--) {
|
||||
File d = made.get(i);
|
||||
if (!d.isDirectory() && !d.mkdirs()) throw new IOException("Cannot create " + d);
|
||||
makeWritable(d);
|
||||
}
|
||||
delete(dst, null);
|
||||
if (!src.renameTo(dst)) throw new IOException("Cannot carry " + rel + " across the update");
|
||||
}
|
||||
|
||||
static void recoverCarriedPaths(File staging, File target, java.util.List<String> paths) throws IOException {
|
||||
for (String rel : paths) {
|
||||
File src = safePath(staging, rel);
|
||||
if (!exists(src.toPath())) continue;
|
||||
File dst = safePath(target, rel);
|
||||
if (!exists(dst.toPath())) move(staging, target, rel);
|
||||
}
|
||||
}
|
||||
|
||||
static boolean hasPaths(File tree, java.util.List<String> paths) throws IOException {
|
||||
for (String rel : paths) if (exists(safePath(tree, rel).toPath())) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static File safePath(File tree, String rel) throws IOException {
|
||||
Path relative = java.nio.file.Paths.get(rel);
|
||||
if (relative.isAbsolute() || relative.getNameCount() == 0) throw new IOException("Invalid runtime path: " + rel);
|
||||
for (Path part : relative) if (part.toString().equals("..")) throw new IOException("Invalid runtime path: " + rel);
|
||||
Path current = tree.toPath();
|
||||
for (int i = 0; i < relative.getNameCount() - 1; i++) {
|
||||
current = current.resolve(relative.getName(i));
|
||||
try {
|
||||
BasicFileAttributes attrs = Files.readAttributes(current, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
|
||||
if (!attrs.isDirectory()) throw new IOException("Runtime path has a non-directory parent: " + current);
|
||||
} catch (NoSuchFileException ignored) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return tree.toPath().resolve(relative).toFile();
|
||||
}
|
||||
|
||||
static void carryHome(File old, File staging) throws IOException {
|
||||
File home = new File(old, "root");
|
||||
if (!home.isDirectory()) return;
|
||||
|
||||
@@ -56,8 +56,9 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L
|
||||
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING
|
||||
val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L
|
||||
// Android can keep reporting charging at 100%; Linux reports Full there, and Steam shows 99% until it does.
|
||||
val statusText = when (status) {
|
||||
BatteryManager.BATTERY_STATUS_CHARGING -> "Charging"
|
||||
BatteryManager.BATTERY_STATUS_CHARGING -> if (pct >= 100) "Full" else "Charging"
|
||||
BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging"
|
||||
BatteryManager.BATTERY_STATUS_FULL -> "Full"
|
||||
BatteryManager.BATTERY_STATUS_NOT_CHARGING -> "Not charging"
|
||||
|
||||
@@ -155,8 +155,7 @@ object ComponentsManager {
|
||||
if (staged.exists()) check(staged.delete()) { "Could not remove unpublished component selections" }
|
||||
}
|
||||
|
||||
private fun saveState(context: Context, state: JSONObject) {
|
||||
val prepared = prepareLaunchState(context, state)
|
||||
private fun saveState(context: Context, state: JSONObject, prepared: PreparedLaunchState = prepareLaunchState(context, state)) {
|
||||
val dir = launchDir(context)
|
||||
val tmp = File(dir, "desired.tsv.tmp")
|
||||
try {
|
||||
@@ -175,6 +174,17 @@ object ComponentsManager {
|
||||
?.forEach { it.deleteRecursively() }
|
||||
}
|
||||
|
||||
fun republish(context: Context): Boolean = synchronized(lock) {
|
||||
recoverState(context)
|
||||
val saved = stateFile(context)
|
||||
if (saved.exists() && runCatching { JSONObject(saved.readText()) }.isFailure) return false
|
||||
val state = loadState(context)
|
||||
val prepared = prepareLaunchState(context, state)
|
||||
if ((FileUtils.readString(File(launchDir(context), "desired.tsv")) ?: "") == prepared.text) return false
|
||||
saveState(context, state, prepared)
|
||||
true
|
||||
}
|
||||
|
||||
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
|
||||
|
||||
private fun rememberProfiledComponent(state: JSONObject, comp: String) {
|
||||
@@ -780,6 +790,64 @@ object ComponentsManager {
|
||||
true
|
||||
}
|
||||
|
||||
private fun checkPackageUnused(context: Context, state: JSONObject, name: String) {
|
||||
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
|
||||
for (key in listOf("queued", "active")) {
|
||||
val byProton = state.sub(key)
|
||||
for (pid in byProton.keys()) {
|
||||
val comps = byProton.optJSONObject(pid) ?: continue
|
||||
for (comp in comps.keys()) {
|
||||
val entry = comps.optJSONObject(comp) ?: continue
|
||||
check(entry.optString("file") != name || !liveSelection(key, entry, installed[pid])) {
|
||||
context.getString(R.string.cmgr_package_in_use, name, installed[pid]?.name ?: pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val profiles = state.sub("profiles")
|
||||
for (scope in profiles.keys()) {
|
||||
val profile = profiles.optJSONObject(scope) ?: continue
|
||||
check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) }
|
||||
}
|
||||
}
|
||||
|
||||
fun carryOver(context: Context, fromDir: String, toDir: String) {
|
||||
synchronized(lock) {
|
||||
val target = protons(context).firstOrNull { it.id == safeName(toDir) } ?: return
|
||||
val state = loadState(context)
|
||||
val wanted = carried(state, safeName(fromDir)) { File(packagesDir(context), it).isFile }
|
||||
val active = state.sub("active").optJSONObject(target.id)
|
||||
val queued = state.sub("queued").sub(target.id)
|
||||
var changed = false
|
||||
wanted.forEach { (comp, entry) ->
|
||||
if (active?.has(comp) != true && !queued.has(comp)) {
|
||||
queued.put(comp, entry)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (queued.length() == 0) state.sub("queued").remove(target.id)
|
||||
if (changed) saveState(context, state)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun carried(state: JSONObject, from: String, present: (String) -> Boolean): Map<String, JSONObject> = buildMap {
|
||||
state.optJSONObject("active")?.optJSONObject(from)?.let { active ->
|
||||
active.keys().forEach { comp ->
|
||||
val entry = active.optJSONObject(comp) ?: return@forEach
|
||||
val file = entry.optString("file")
|
||||
if (comp in COMPONENTS && file.endsWith(".wcp") && present(file)) {
|
||||
put(comp, JSONObject().put("kind", "package").put("file", file).put("label", entry.optString("label")))
|
||||
}
|
||||
}
|
||||
}
|
||||
state.optJSONObject("queued")?.optJSONObject(from)?.let { queued ->
|
||||
queued.keys().forEach { comp ->
|
||||
val entry = queued.optJSONObject(comp) ?: return@forEach
|
||||
if (comp in COMPONENTS && entry.optString("kind") == "package" && present(entry.optString("file"))) put(comp, entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun forgetProton(context: Context, dirName: String) {
|
||||
synchronized(lock) {
|
||||
val id = safeName(dirName)
|
||||
@@ -791,6 +859,33 @@ object ComponentsManager {
|
||||
}
|
||||
}
|
||||
|
||||
private fun storePackage(context: Context, part: File, dest: File) {
|
||||
try {
|
||||
if (dest.isFile && runCatching { Hashes.sha256(dest) }.getOrNull()?.equals(Hashes.sha256(part), true) == true) return
|
||||
if (dest.exists()) checkPackageUnused(context, loadState(context), dest.name)
|
||||
val store = File(launchDir(context), "store").canonicalFile
|
||||
val cacheKey = unpackedCacheKey(dest.name)
|
||||
val unpacked = File(store, cacheKey).canonicalFile
|
||||
check(unpacked.parentFile == store) { "Invalid unpacked component cache path for ${dest.name}" }
|
||||
val complete = File(unpacked, ".complete")
|
||||
if (complete.exists()) check(complete.delete()) { "Could not invalidate unpacked component ${dest.name}" }
|
||||
if (!part.renameTo(dest)) {
|
||||
dest.delete()
|
||||
check(part.renameTo(dest)) { "Could not store ${dest.name}" }
|
||||
}
|
||||
if (!unpacked.deleteRecursively() && unpacked.exists()) {
|
||||
check(!complete.exists()) { "Could not invalidate unpacked component ${dest.name}" }
|
||||
Log.w(TAG, "Could not remove stale unpacked files for ${dest.name}; cache marker is invalidated")
|
||||
}
|
||||
} finally {
|
||||
part.delete()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun unpackedCacheKey(filename: String): String = safeName(filename.removeSuffix(".wcp")).also {
|
||||
require(it != "." && it != "..") { "Invalid component cache name" }
|
||||
}
|
||||
|
||||
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
|
||||
val name = safeName(file)
|
||||
val state = loadState(context)
|
||||
@@ -840,7 +935,7 @@ object ComponentsManager {
|
||||
fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) {
|
||||
val info = packageInfo(context, source)
|
||||
val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" })
|
||||
source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest)
|
||||
storePackage(context, source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true), dest)
|
||||
info.copy(file = dest.name)
|
||||
}
|
||||
|
||||
@@ -863,6 +958,7 @@ object ComponentsManager {
|
||||
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
|
||||
}
|
||||
}
|
||||
if (items.length() == 0 && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) }
|
||||
val out = JSONObject().put("items", items).put("fetchedAt", System.currentTimeMillis() / 1000)
|
||||
val tmp = File(cache.parentFile, cache.name + ".tmp")
|
||||
tmp.writeText(out.toString()); tmp.renameTo(cache)
|
||||
@@ -992,7 +1088,7 @@ object ComponentsManager {
|
||||
}
|
||||
if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error(context.getString(R.string.cmgr_checksum_mismatch)) }
|
||||
val info = runCatching { packageInfo(context, part) }.getOrElse { part.delete(); throw it }
|
||||
synchronized(lock) { part.renameTo(dest) }
|
||||
synchronized(lock) { storePackage(context, part, dest) }
|
||||
return info.copy(file = dest.name)
|
||||
}
|
||||
}
|
||||
@@ -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}",
|
||||
|
||||
@@ -78,6 +78,14 @@ object GameEnvironmentStore {
|
||||
return config
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setDefault(context: Context, scope: String, name: String, value: String): Boolean {
|
||||
val config = read(context)
|
||||
if (GameEnvironment.hasOverride(config, scope, name)) return false
|
||||
save(context, GameEnvironment.withScopeValue(config, scope, name, value))
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||
|
||||
@@ -14,9 +14,12 @@ object GameStorage {
|
||||
|
||||
fun options(context: Context): List<Option> {
|
||||
val sm = context.getSystemService(StorageManager::class.java)
|
||||
val primary = context.getExternalFilesDir(null)?.absolutePath
|
||||
val primaryStorage = Environment.getExternalStorageDirectory()?.absolutePath
|
||||
return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir ->
|
||||
val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false }
|
||||
if (!removable) return@mapNotNull null
|
||||
// Non-primary app dirs are usable even when Android reports the volume as non-removable (USB SSDs often do).
|
||||
if (primary != null && dir.absolutePath == primary) return@mapNotNull null
|
||||
if (!primaryStorage.isNullOrBlank() && dir.absolutePath.startsWith("$primaryStorage/")) return@mapNotNull null
|
||||
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
|
||||
val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: context.getString(R.string.gstore_sd_card)
|
||||
Option(context.getString(R.string.gstore_volume_free, name, free(dir)), File(dir, "steam").absolutePath, name)
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
|
||||
internal object MemoryReadout {
|
||||
data class Device(val totalKb: Long, val availableKb: Long, val swapTotalKb: Long, val swapFreeKb: Long) {
|
||||
val usedKb get() = (totalKb - availableKb).coerceAtLeast(0)
|
||||
val swapUsedKb get() = (swapTotalKb - swapFreeKb).coerceAtLeast(0)
|
||||
}
|
||||
|
||||
data class Split(val gameKb: Long, val droiddeckKb: Long, val gpuKb: Long?)
|
||||
|
||||
fun parseMeminfo(text: String): Device? {
|
||||
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(text)?.groupValues?.get(1)?.toLongOrNull()
|
||||
val total = field("MemTotal") ?: return null
|
||||
val available = field("MemAvailable") ?: return null
|
||||
return Device(total, available, field("SwapTotal") ?: 0, field("SwapFree") ?: 0)
|
||||
}
|
||||
|
||||
fun residentKb(status: String): Long {
|
||||
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(status)?.groupValues?.get(1)?.toLongOrNull() ?: 0
|
||||
return field("RssAnon") + field("RssShmem")
|
||||
}
|
||||
|
||||
fun inWinePrefix(environ: ByteArray): Boolean {
|
||||
var start = 0
|
||||
val key = "WINEPREFIX=".toByteArray()
|
||||
for (i in 0..environ.size) {
|
||||
if (i == environ.size || environ[i] == 0.toByte()) {
|
||||
if (i - start >= key.size && (key.indices).all { environ[start + it] == key[it] }) return true
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun androidKb(device: Device, split: Split): Long =
|
||||
(device.usedKb - split.gameKb - split.droiddeckKb - (split.gpuKb ?: 0)).coerceAtLeast(0)
|
||||
|
||||
fun gb(kb: Long): String = String.format(Locale.US, "%.1f", kb / (1024.0 * 1024.0))
|
||||
|
||||
fun availableMb(): Long? = runCatching { parseMeminfo(File("/proc/meminfo").readText())?.availableKb?.div(1024) }.getOrNull()
|
||||
|
||||
fun device(): Device? = runCatching { parseMeminfo(File("/proc/meminfo").readText()) }.getOrNull()
|
||||
|
||||
fun split(root: Int = android.os.Process.myPid()): Split {
|
||||
val parents = HashMap<Int, Int>()
|
||||
File("/proc").listFiles()?.forEach { entry ->
|
||||
val pid = entry.name.toIntOrNull() ?: return@forEach
|
||||
parentOf(pid)?.let { parents[pid] = it }
|
||||
}
|
||||
val children = parents.entries.groupBy({ it.value }, { it.key })
|
||||
var game = 0L
|
||||
var droiddeck = 0L
|
||||
val queue = ArrayDeque<Int>().apply { add(root) }
|
||||
val seen = HashSet<Int>()
|
||||
while (queue.isNotEmpty()) {
|
||||
val pid = queue.removeFirst()
|
||||
if (!seen.add(pid)) continue
|
||||
val status = runCatching { File("/proc/$pid/status").readText() }.getOrNull()
|
||||
if (status != null) {
|
||||
val kb = residentKb(status)
|
||||
val windows = pid != root && runCatching { inWinePrefix(File("/proc/$pid/environ").readBytes()) }.getOrDefault(false)
|
||||
if (windows) game += kb else droiddeck += kb
|
||||
}
|
||||
children[pid]?.let(queue::addAll)
|
||||
}
|
||||
return Split(game, droiddeck, gpuKb())
|
||||
}
|
||||
|
||||
private fun parentOf(pid: Int): Int? {
|
||||
val stat = runCatching { File("/proc/$pid/stat").readText() }.getOrNull() ?: return null
|
||||
val close = stat.lastIndexOf(')')
|
||||
if (close < 0 || close + 2 >= stat.length) return null
|
||||
return stat.substring(close + 2).split(' ').getOrNull(1)?.toIntOrNull()
|
||||
}
|
||||
|
||||
private fun gpuKb(): Long? = runCatching {
|
||||
File("/sys/class/kgsl/kgsl/page_alloc").readText().trim().split(Regex("\\s+"))[0].toLong() / 1024
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
object MemoryLog {
|
||||
private const val TAG = "Memory"
|
||||
private const val PERIOD_MS = 10_000L
|
||||
@Volatile private var thread: Thread? = null
|
||||
|
||||
internal fun line(device: MemoryReadout.Device, split: MemoryReadout.Split): String =
|
||||
"used ${device.usedKb / 1024}/${device.totalKb / 1024} MB, available ${device.availableKb / 1024} MB, " +
|
||||
"swap ${device.swapUsedKb / 1024}/${device.swapTotalKb / 1024} MB | game ${split.gameKb / 1024}, " +
|
||||
"droiddeck ${split.droiddeckKb / 1024}, android ${MemoryReadout.androidKb(device, split) / 1024}, " +
|
||||
"gpu ${split.gpuKb?.div(1024) ?: "?"} MB"
|
||||
|
||||
@Synchronized
|
||||
fun start() {
|
||||
if (thread != null) return
|
||||
thread = Thread({
|
||||
while (!Thread.currentThread().isInterrupted) {
|
||||
runCatching { MemoryReadout.device()?.let { android.util.Log.i(TAG, line(it, MemoryReadout.split())) } }
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
}
|
||||
}, "memory-log").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun stop() {
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
}
|
||||
}
|
||||
|
||||
class MemoryHud(context: Context) {
|
||||
var text by mutableStateOf("")
|
||||
private set
|
||||
|
||||
private val context = context.applicationContext
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
@Volatile private var running = false
|
||||
@Volatile private var generation = 0
|
||||
private var thread: Thread? = null
|
||||
|
||||
fun refresh() {
|
||||
if (SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) stop() else start()
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (running || SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) return
|
||||
running = true
|
||||
val token = ++generation
|
||||
thread = Thread({
|
||||
while (running && generation == token) {
|
||||
val line = runCatching { sample() }.getOrDefault("")
|
||||
handler.post { if (running && generation == token) text = line }
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
}
|
||||
}, "memory-hud").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
running = false
|
||||
generation++
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
text = ""
|
||||
}
|
||||
|
||||
private fun sample(): String {
|
||||
val device = MemoryReadout.device() ?: return ""
|
||||
val memory = context.getString(
|
||||
R.string.memory_hud_simple,
|
||||
MemoryReadout.gb(device.usedKb), MemoryReadout.gb(device.totalKb),
|
||||
MemoryReadout.gb(device.swapUsedKb), MemoryReadout.gb(device.swapTotalKb),
|
||||
)
|
||||
if (SessionPrefs.memoryHud(context) != SessionPrefs.MEMORY_HUD_ADVANCED) return memory
|
||||
val split = MemoryReadout.split()
|
||||
val parts = context.getString(
|
||||
R.string.memory_hud_split,
|
||||
MemoryReadout.gb(split.gameKb), MemoryReadout.gb(split.droiddeckKb), MemoryReadout.gb(MemoryReadout.androidKb(device, split)),
|
||||
)
|
||||
val gpu = split.gpuKb?.let { context.getString(R.string.memory_hud_gpu, MemoryReadout.gb(it)) }
|
||||
return listOfNotNull(memory, parts, gpu).joinToString("\n")
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PERIOD_MS = 2000L
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,13 @@ import com.droiddeck.launcher.stores.epic.EpicClient
|
||||
object NoSteamLaunch {
|
||||
const val PROTON_RUN = "/usr/local/bin/droiddeck-proton-run"
|
||||
const val EPIC = "/usr/local/bin/droiddeck-epic"
|
||||
const val BATTLENET = com.droiddeck.launcher.runtime.BattleNet.PROGRAM
|
||||
|
||||
class Command(val program: String, val args: List<String>, val name: String)
|
||||
|
||||
fun scope(game: Library.SteamGame): String? = when {
|
||||
game.library == Library.EPIC_LAUNCHER -> EpicClient.shortcutAppId.toString()
|
||||
game.library == Library.BATTLENET_LAUNCHER -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
|
||||
game.library == Library.ADDED || game.appId > 0 -> game.profileKey
|
||||
else -> null
|
||||
}?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) }
|
||||
@@ -30,6 +32,8 @@ object NoSteamLaunch {
|
||||
|
||||
fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
|
||||
game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name)
|
||||
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id ->
|
||||
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.let { Command(BATTLENET, listOf("launch", it.code), game.name) }
|
||||
game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) }
|
||||
game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name)
|
||||
else -> null
|
||||
@@ -37,7 +41,9 @@ object NoSteamLaunch {
|
||||
|
||||
fun addedCommand(game: AddedGames.Game): Command = Command(
|
||||
PROTON_RUN,
|
||||
listOf("--app", (game.appId and 0xFFFFFFFFL).toString(), "--dir", game.guestDir, "--options", game.launchOptions, "--", game.guestExe),
|
||||
listOf("--app", (game.appId and 0xFFFFFFFFL).toString(), "--dir", game.guestDir) +
|
||||
(if (game.launchOptions.isEmpty()) emptyList() else listOf("--options", game.launchOptions)) +
|
||||
listOf("--", game.guestExe),
|
||||
game.name,
|
||||
)
|
||||
|
||||
@@ -45,11 +51,13 @@ object NoSteamLaunch {
|
||||
|
||||
fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? {
|
||||
val id = game.appId.toLong() and 0xFFFFFFFFL
|
||||
return AddedGames.scan(context).firstOrNull { settingsId(it) == id }
|
||||
val one = game.gameFiles?.let { AddedGames.single(context, it.path) }
|
||||
return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id }
|
||||
}
|
||||
|
||||
fun nameFor(program: String?, args: List<String>): String? = when (program) {
|
||||
EPIC -> Library.EPIC_LAUNCHER_NAME
|
||||
BATTLENET -> args.getOrNull(args.indexOf("launch") + 1)?.takeIf { args.contains("launch") }?.let { names[it] } ?: com.droiddeck.launcher.stores.Store.BATTLENET.label
|
||||
PROTON_RUN -> args.getOrNull(args.indexOf("--app") + 1)?.takeIf { args.contains("--app") }?.let { names[it] }
|
||||
else -> null
|
||||
}
|
||||
@@ -58,5 +66,6 @@ object NoSteamLaunch {
|
||||
|
||||
fun remember(command: Command) {
|
||||
if (command.program == PROTON_RUN) command.args.getOrNull(command.args.indexOf("--app") + 1)?.let { names[it] = command.name }
|
||||
if (command.program == BATTLENET) command.args.getOrNull(command.args.indexOf("launch") + 1)?.takeIf { command.args.contains("launch") }?.let { names[it] = command.name }
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -114,12 +114,19 @@ object ProtonDefault {
|
||||
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
||||
}
|
||||
|
||||
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
|
||||
if (choices.values.none { it != null && !it.valve && it.dir in from }) return null
|
||||
return choices.mapValues { (_, choice) -> if (choice != null && !choice.valve && choice.dir in from) GameChoice(false, to) else choice }
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
|
||||
require(GameEnvironment.validScope(scope))
|
||||
fun moveGames(context: Context, from: Set<String>, to: String) {
|
||||
val d = dir(context)
|
||||
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
|
||||
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
|
||||
val moved = movedGames(parseGames(read(File(d, GAMES))), from, to) ?: return
|
||||
writeGames(d, moved)
|
||||
}
|
||||
|
||||
private fun writeGames(d: File, choices: Map<String, GameChoice?>) {
|
||||
val games = JSONObject()
|
||||
choices.forEach { (id, choice) ->
|
||||
games.put(id, choice?.let { JSONObject().put("valve", it.valve).put("dir", it.dir) } ?: JSONObject.NULL)
|
||||
@@ -134,6 +141,15 @@ object ProtonDefault {
|
||||
Log.w(TAG, "could not write the per-game Proton request", e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
|
||||
require(GameEnvironment.validScope(scope))
|
||||
val d = dir(context)
|
||||
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
|
||||
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
|
||||
writeGames(d, choices)
|
||||
val state = state(context)
|
||||
val tool = proton?.let { selected -> state.tools.firstOrNull { it.valve == selected.valve && it.dir == selected.dir.name } }
|
||||
return if (SessionState.running && state.live && (proton == null || tool != null && state.pending != tool.name)) {
|
||||
|
||||
@@ -16,16 +16,20 @@ object ProtonExtras {
|
||||
private const val TAG = "ProtonExtras"
|
||||
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
|
||||
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
|
||||
const val CHECK_EVERY_MS = 6L * 60 * 60 * 1000
|
||||
const val CHECK_EVERY_MS = 60L * 60 * 1000
|
||||
@Volatile
|
||||
var installInProgress = false
|
||||
private set
|
||||
@Volatile
|
||||
private var replacing = false
|
||||
|
||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
||||
|
||||
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
||||
val sha256: String? = null)
|
||||
|
||||
const val OWN = "droiddeck"
|
||||
|
||||
val tools = listOf(
|
||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
||||
@@ -78,11 +82,23 @@ object ProtonExtras {
|
||||
|
||||
fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool))
|
||||
|
||||
fun missing(context: Context, tool: Tool): String? =
|
||||
if (tool.id == OWN && !declined(context) && installedAll(context, tool).isEmpty()) cachedLatest(context, tool) else null
|
||||
|
||||
private fun choices(context: Context) = context.getSharedPreferences("proton-auto-updates", Context.MODE_PRIVATE)
|
||||
|
||||
fun declined(context: Context): Boolean = choices(context).getBoolean("$OWN.declined", false)
|
||||
|
||||
fun setDeclined(context: Context, declined: Boolean) {
|
||||
choices(context).edit().putBoolean("$OWN.declined", declined).apply()
|
||||
}
|
||||
|
||||
fun cachedLatest(context: Context, tool: Tool): String? =
|
||||
readJson(latestFile(context)).optJSONObject(tool.id)?.optString("tag")?.ifEmpty { null }
|
||||
|
||||
private val checkLock = Any()
|
||||
private const val RETRY_MS = 15L * 60 * 1000
|
||||
private const val USER_SETTINGS = "user_settings.py"
|
||||
private var lastAttempt = 0L
|
||||
|
||||
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
||||
@@ -145,6 +161,44 @@ object ProtonExtras {
|
||||
}
|
||||
}
|
||||
|
||||
private fun replaceOlder(context: Context, tool: Tool) {
|
||||
val all = installedAll(context, tool)
|
||||
val newest = all.lastOrNull() ?: return
|
||||
val older = all.dropLast(1)
|
||||
if (older.isEmpty()) return
|
||||
replacing = true
|
||||
try {
|
||||
for (old in older.asReversed()) {
|
||||
if (SessionState.running) break
|
||||
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
|
||||
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
|
||||
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
|
||||
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
|
||||
else Log.w(TAG, "could not remove $old")
|
||||
}
|
||||
} finally {
|
||||
replacing = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun keepUserSettings(context: Context, old: String, newest: String) {
|
||||
val from = File(File(toolsDir(context), old), USER_SETTINGS)
|
||||
val to = File(File(toolsDir(context), newest), USER_SETTINGS)
|
||||
if (from.isFile && !to.exists()) from.copyTo(to)
|
||||
}
|
||||
|
||||
fun tidy(context: Context) {
|
||||
val tool = tools.firstOrNull { it.id == OWN } ?: return
|
||||
if (installedAll(context, tool).size > 1) replaceOlder(context, tool)
|
||||
}
|
||||
|
||||
fun awaitReplacement(timeoutMs: Long) {
|
||||
val until = System.currentTimeMillis() + timeoutMs
|
||||
while (replacing && System.currentTimeMillis() < until) {
|
||||
try { Thread.sleep(50) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return }
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||
@@ -246,6 +300,7 @@ object ProtonExtras {
|
||||
archive.delete()
|
||||
unqueue(context, tool)
|
||||
record(context, tool, placed, asset.tag)
|
||||
if (tool.id == OWN) replaceOlder(context, tool)
|
||||
if (EsyncPacks.enabled(context)) {
|
||||
onProgress(context.getString(R.string.esync_fetching), -1)
|
||||
try {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -17,12 +17,13 @@ object SessionDisplay {
|
||||
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
|
||||
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
|
||||
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> {
|
||||
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return screenSize(panel)
|
||||
presetHeight(choice)?.let { return resolve(panel, it, SessionPrefs.SHAPE_AUTO) }
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String, portrait: Boolean = false): Pair<Int, Int> {
|
||||
fun orient(size: Pair<Int, Int>) = if (portrait) size.second to size.first else size
|
||||
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return orient(screenSize(panel))
|
||||
presetHeight(choice)?.let { return orient(resolve(panel, it, SessionPrefs.SHAPE_AUTO)) }
|
||||
val parts = choice.split('x').map { it.toIntOrNull() }
|
||||
return if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
|
||||
else resolve(panel, 720, SessionPrefs.SHAPE_AUTO)
|
||||
else orient(resolve(panel, 720, SessionPrefs.SHAPE_AUTO))
|
||||
}
|
||||
|
||||
fun resolutionOptions(panel: Pair<Int, Int>): List<String> {
|
||||
@@ -31,8 +32,10 @@ object SessionDisplay {
|
||||
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN + FOLLOW_SCREEN
|
||||
}
|
||||
|
||||
fun followSize(width: Int, height: Int): Pair<Int, Int>? =
|
||||
if (minOf(width, height) < FOLLOW_MIN_SIDE) null else (width and 1.inv()) to (height and 1.inv())
|
||||
fun followSize(width: Int, height: Int, controlsBelow: Boolean = false): Pair<Int, Int>? =
|
||||
if (width <= 0 || height <= 0 ||
|
||||
(if (controlsBelow) width else minOf(width, height)) < FOLLOW_MIN_SIDE) null
|
||||
else (width and 1.inv()) to (height and 1.inv())
|
||||
|
||||
const val UNFOLDED_MAX_GAME_SHARE = 0.8f
|
||||
|
||||
@@ -49,13 +52,14 @@ object SessionDisplay {
|
||||
foldable: Boolean,
|
||||
controllerConnected: Boolean,
|
||||
keepWithController: Boolean,
|
||||
steamDeckPad: Boolean,
|
||||
gamepadAvailable: Boolean,
|
||||
pip: Boolean,
|
||||
width: Int,
|
||||
height: Int,
|
||||
smallestWidthDp: Int,
|
||||
): Boolean = enabled && foldable && (keepWithController || !controllerConnected) && steamDeckPad &&
|
||||
!pip && width > 0 && height > 0 && smallestWidthDp >= UNFOLDED_MIN_DP
|
||||
): Boolean = enabled && (keepWithController || !controllerConnected) && gamepadAvailable &&
|
||||
!pip && width > 0 && height > 0 &&
|
||||
(height > width || (foldable && smallestWidthDp >= UNFOLDED_MIN_DP))
|
||||
|
||||
|
||||
fun panelSize(context: Context): Pair<Int, Int> {
|
||||
@@ -79,5 +83,5 @@ object SessionDisplay {
|
||||
}
|
||||
|
||||
fun canStretch16x9(size: Pair<Int, Int>): Boolean =
|
||||
(size.second * 16 + 4) / 9 / 2 * 2 > size.first
|
||||
(size.second * 16 + 4) / 9 / 2 * 2 > size.first || (size.first * 9 + 8) / 16 / 2 * 2 > size.second
|
||||
}
|
||||
@@ -74,12 +74,14 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
|
||||
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
|
||||
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
|
||||
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
|
||||
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
|
||||
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
|
||||
"usr/local/bin/droiddeck-open-url" to "usr/local/bin/droiddeck-open-url",
|
||||
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
|
||||
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
|
||||
"usr/local/bin/droiddeck-steam-x64" to "usr/local/bin/droiddeck-steam-x64",
|
||||
"usr/local/bin/droiddeck-fex-update" to "usr/local/bin/droiddeck-fex-update",
|
||||
"usr/local/bin/droiddeck-steamrt-shim" to "usr/local/bin/droiddeck-steamrt-shim",
|
||||
"usr/local/bin/droiddeck-x64-arm-proton" to "usr/local/bin/droiddeck-x64-arm-proton",
|
||||
"usr/local/bin/droiddeck-x64-arm-webhelper" to "usr/local/bin/droiddeck-x64-arm-webhelper",
|
||||
@@ -97,6 +99,15 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
|
||||
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
|
||||
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
|
||||
"usr/local/bin/droiddeck-innoextract" to "usr/local/bin/droiddeck-innoextract",
|
||||
"usr/local/lib/droiddeck-inno/innoextract" to "usr/local/lib/droiddeck-inno/innoextract",
|
||||
"usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0",
|
||||
"usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0",
|
||||
"usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0",
|
||||
"usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0",
|
||||
"usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0",
|
||||
"usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract" to "usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract",
|
||||
"usr/local/share/licenses/droiddeck-inno/LICENSE.boost" to "usr/local/share/licenses/droiddeck-inno/LICENSE.boost",
|
||||
"usr/bin/steamos-update" to "usr/bin/steamos-update",
|
||||
"usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch",
|
||||
"usr/bin/steamos-session-select" to "usr/bin/steamos-session-select",
|
||||
@@ -141,6 +152,8 @@ object SessionFiles {
|
||||
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
|
||||
val optional = (arrayOf(
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
// The gamescope pack carries its own WSI layer (patch 0117); it replaces the runtime's stock copy.
|
||||
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
@@ -205,7 +218,11 @@ object SessionFiles {
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||
}
|
||||
if (ProotFastPath.enabled(context)) preload.append(ProotFastPath.LIBRARY + "\n")
|
||||
if (ProotFastPath.enabled(context)) {
|
||||
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
|
||||
preload.append(library + "\n")
|
||||
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
|
||||
}
|
||||
val etc = File(root, "etc").apply { mkdirs() }
|
||||
val staged = File(etc, "ld.so.preload.staged")
|
||||
if (!FileUtils.writeString(staged, preload.toString())
|
||||
|
||||
@@ -12,6 +12,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.core.content.FileProvider
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.util.zip.ZipEntry
|
||||
@@ -49,7 +50,8 @@ object SessionLogShare {
|
||||
val logs = LinuxRuntime.logDir(context)
|
||||
val stores = recent(File(logs, STORES_DIR))
|
||||
val tools = recent(File(logs, SessionPaths.TOOLS_DIR))
|
||||
val total = (files + live + stores + tools).sumOf { it.length() }.coerceAtLeast(1L)
|
||||
val battleNet = battleNetLogs(context)
|
||||
val total = (files + live + stores + tools + battleNet.map { it.second }).sumOf { it.length() }.coerceAtLeast(1L)
|
||||
var done = 0L
|
||||
var shown = -1
|
||||
fun advance(f: File) {
|
||||
@@ -62,6 +64,7 @@ object SessionLogShare {
|
||||
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) }
|
||||
stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) }
|
||||
tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) }
|
||||
battleNet.forEach { (name, f) -> addEntry(z, "$BATTLENET_DIR/$name", f); advance(f) }
|
||||
}
|
||||
return zip
|
||||
}
|
||||
@@ -88,6 +91,27 @@ object SessionLogShare {
|
||||
|
||||
private fun shareDir(context: Context): File = File(context.cacheDir, "share")
|
||||
|
||||
private const val BATTLENET_DIR = "battlenet"
|
||||
|
||||
private fun battleNetLogs(context: Context): List<Pair<String, File>> {
|
||||
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
|
||||
val data = File(drive, "ProgramData/Battle.net")
|
||||
fun logsUnder(dir: File, prefix: String) = dir.listFiles { f -> f.isDirectory && f.name.startsWith(prefix) }.orEmpty().map { File(it, "Logs") }
|
||||
return newest("droiddeck", listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")), 2, setOf("battlenet.log", "spawned.log")) +
|
||||
newest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6) +
|
||||
newest("agent", listOf(File(data, "Agent/Logs")) + logsUnder(File(data, "Agent"), "Agent."), 10, byDir = true) +
|
||||
newest("setup", logsUnder(File(data, "Setup"), ""), 3, byDir = true)
|
||||
}
|
||||
|
||||
private fun newest(folder: String, dirs: List<File>, count: Int, names: Set<String>? = null, byDir: Boolean = false): List<Pair<String, File>> {
|
||||
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
|
||||
return dirs.flatMap { dir ->
|
||||
dir.listFiles { f -> f.isFile && f.name.endsWith(".log") && (names == null || f.name in names) && f.lastModified() >= since && f.length() <= STEAM_LOG_MAX_BYTES }.orEmpty().toList()
|
||||
}.sortedByDescending { it.lastModified() }.take(count).map { f ->
|
||||
(if (byDir) "$folder/${f.parentFile?.parentFile?.name}/${f.name}" else "$folder/${f.name}") to f
|
||||
}
|
||||
}
|
||||
|
||||
private fun recent(dir: File): List<File> {
|
||||
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
|
||||
return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty()
|
||||
|
||||
Loaded 100 of 399 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user