mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
75
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3112402562 | ||
|
|
bc0530463e | ||
|
|
2d07c3df04 | ||
|
|
05a5f745f5 | ||
|
|
1ce0a43db0 | ||
|
|
b5f7ac6700 | ||
|
|
d06caf9838 | ||
|
|
03c8a0e4c2 | ||
|
|
1bd561531a | ||
|
|
64d72913fa | ||
|
|
1b31899896 | ||
|
|
134fa167fe | ||
|
|
da42a5d7a7 | ||
|
|
b6c1d3c09c | ||
|
|
a58b0ac3e0 | ||
|
|
e1700ba982 | ||
|
|
736ac7db74 | ||
|
|
38a84a8e8f | ||
|
|
6e2966be43 | ||
|
|
c2dd90d1b6 | ||
|
|
e637a2e0bd | ||
|
|
679948e792 | ||
|
|
e0fc8362b8 | ||
|
|
9d8ff9615f | ||
|
|
1304809240 | ||
|
|
343a516e1a | ||
|
|
7c08cb58ae | ||
|
|
7e81668de2 | ||
|
|
d231564f8e | ||
|
|
261dee73c4 | ||
|
|
ac8455925e | ||
|
|
270dfbdcc3 | ||
|
|
37e89c5b4d | ||
|
|
e070bd72e0 | ||
|
|
9310d19857 | ||
|
|
4454a6d39a | ||
|
|
453f6f5180 | ||
|
|
6d0484941e | ||
|
|
cf47910881 | ||
|
|
4f0f0cf5b1 | ||
|
|
a78d5cb600 | ||
|
|
206c8a8846 | ||
|
|
bf17ce1151 | ||
|
|
ef38c975b9 | ||
|
|
61953c4f7b | ||
|
|
1f13285ab8 | ||
|
|
1bc23ac169 | ||
|
|
50f50b16e0 | ||
|
|
adc86fc7df | ||
|
|
f3fd3a2307 | ||
|
|
1e877fa602 | ||
|
|
906009a33a | ||
|
|
08559a02f8 | ||
|
|
1d93626453 | ||
|
|
9d0989374b | ||
|
|
3278afaa1a | ||
|
|
bf221ffbbd | ||
|
|
c636eea355 | ||
|
|
ffaa906cd1 | ||
|
|
d61af961c1 | ||
|
|
bc01b77752 | ||
|
|
a1b01a04a8 | ||
|
|
b44235c495 | ||
|
|
b80d5db176 | ||
|
|
d3c0d258b7 | ||
|
|
9dcdbf245a | ||
|
|
369e218afb | ||
|
|
119d24bf6b | ||
|
|
2a905510d5 | ||
|
|
da29919b5a | ||
|
|
05608ac4d4 | ||
|
|
135b84a501 | ||
|
|
e7cbba37d1 | ||
|
|
d9bb5e15b0 | ||
|
|
46cdc32cf1 |
No files matched your search
@@ -57,6 +57,22 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
- name: Version bumps are isolated
|
||||||
|
if: github.event_name == 'pull_request'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
git fetch --no-tags origin main
|
||||||
|
base=$(git merge-base origin/main HEAD)
|
||||||
|
diff=$(git diff -U0 "$base..HEAD" -- app/build.gradle)
|
||||||
|
grep -Eq '^[+-][[:space:]]*version(Code|Name)[[:space:]]' <<<"$diff" || exit 0
|
||||||
|
other_files=$(git diff --name-only "$base..HEAD" | grep -v '^app/build.gradle$' || true)
|
||||||
|
other_gradle=$(grep -E '^[+-]' <<<"$diff" | grep -Ev '^(---|\+\+\+)' | grep -Ev '^[+-][[:space:]]*version(Code|Name)[[:space:]]' || true)
|
||||||
|
if [[ -n "$other_files" || -n "$other_gradle" ]]; then
|
||||||
|
echo "::error::versionCode/versionName changes must be isolated in their own PR"
|
||||||
|
echo "A version PR may only change the versionCode/versionName lines in app/build.gradle." >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Merge onto main, or say what conflicts
|
- name: Merge onto main, or say what conflicts
|
||||||
if: github.event_name == 'pull_request'
|
if: github.event_name == 'pull_request'
|
||||||
run: |
|
run: |
|
||||||
@@ -157,7 +173,7 @@ jobs:
|
|||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: app/src/main/assets/linuxfs
|
path: app/src/main/assets/linuxfs
|
||||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*') }}
|
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**') }}
|
||||||
|
|
||||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||||
if: steps.preloads.outputs.cache-hit != 'true'
|
if: steps.preloads.outputs.cache-hit != 'true'
|
||||||
@@ -179,6 +195,10 @@ jobs:
|
|||||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||||
-o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
-o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
|
aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
|
||||||
|
# Force-SSBS adapter, preloaded into a game's Wine only when the game asks for it.
|
||||||
|
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||||
|
-o "$D/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
|
||||||
|
aarch64-linux-gnu-strip --strip-unneeded "$D/libssbs.so"
|
||||||
mkdir -p "$D/usr/local/bin"
|
mkdir -p "$D/usr/local/bin"
|
||||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
|
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
|
||||||
@@ -190,7 +210,7 @@ jobs:
|
|||||||
done
|
done
|
||||||
if [ -f tools/gamescope/release.env ]; then
|
if [ -f tools/gamescope/release.env ]; then
|
||||||
. tools/gamescope/release.env
|
. tools/gamescope/release.env
|
||||||
gh release download "${GAMESCOPE_TAG}" -R "${GITHUB_REPOSITORY}" -p gamescope.tzst -O gamescope.tzst
|
gh release download "${GAMESCOPE_TAG}" -R "${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}" -p gamescope.tzst -O gamescope.tzst
|
||||||
echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c -
|
echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c -
|
||||||
tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D"
|
tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D"
|
||||||
test -f "$D/usr/local/bin/gamescope"
|
test -f "$D/usr/local/bin/gamescope"
|
||||||
@@ -230,6 +250,26 @@ jobs:
|
|||||||
install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
|
install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
|
||||||
rm -rf mango-pkgs
|
rm -rf mango-pkgs
|
||||||
ls -l "$M"
|
ls -l "$M"
|
||||||
|
# The Windows components installer's tools (tools/msitools/packages.txt).
|
||||||
|
T="$D/usr/local/lib/droiddeck-msitools"
|
||||||
|
mkdir -p "$T" msi-pkgs
|
||||||
|
grep -v '^#' tools/msitools/packages.txt | while read -r sum url; do
|
||||||
|
[ -n "$url" ] || continue
|
||||||
|
curl -fsSL --retry 3 -o msi-pkgs/pkg.tar.xz "$url"
|
||||||
|
echo "$sum msi-pkgs/pkg.tar.xz" | sha256sum -c -
|
||||||
|
tar -xJf msi-pkgs/pkg.tar.xz -C msi-pkgs
|
||||||
|
rm msi-pkgs/pkg.tar.xz
|
||||||
|
done
|
||||||
|
install -m644 msi-pkgs/usr/bin/msiinfo "$T/msiinfo"
|
||||||
|
install -m644 msi-pkgs/usr/bin/cabextract "$T/cabextract"
|
||||||
|
for so in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||||
|
cp -L "msi-pkgs/usr/lib/$so" "$T/$so"
|
||||||
|
done
|
||||||
|
for f in NOTICE GPL-2 GPL-3 LGPL-2.1; do
|
||||||
|
install -Dm644 "tools/msitools/licenses/$f" "$D/usr/local/share/licenses/droiddeck-msitools/$f"
|
||||||
|
done
|
||||||
|
rm -rf msi-pkgs
|
||||||
|
ls -l "$T"
|
||||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$D/usr/local/bin/droiddeck-desktop"
|
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$D/usr/local/bin/droiddeck-desktop"
|
||||||
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$D/usr/local/bin/droiddeck-gpu"
|
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$D/usr/local/bin/droiddeck-gpu"
|
||||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$D/usr/local/bin/droiddeck-desktop-gpu"
|
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$D/usr/local/bin/droiddeck-desktop-gpu"
|
||||||
@@ -291,6 +331,11 @@ jobs:
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
curl -fsSL -o pa.tar.gz https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
|
curl -fsSL -o pa.tar.gz https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
|
||||||
mkdir -p pa13 && tar -xzf pa.tar.gz -C pa13 --strip-components=1 && rm pa.tar.gz
|
mkdir -p pa13 && tar -xzf pa.tar.gz -C pa13 --strip-components=1 && rm pa.tar.gz
|
||||||
|
# DirectAudio - the game driver (one set per Wine audio interface), the Android-side helper and
|
||||||
|
# the Steam client's sinks - comes from a pinned release of The412Banner/directaudio, checksummed,
|
||||||
|
# exactly like gamescope; nothing compiled for audio is kept in this repo.
|
||||||
|
- name: Fetch DirectAudio (tools/directaudio/release.env)
|
||||||
|
run: tools/directaudio/fetch.sh "$PWD" "$PWD/sink-out"
|
||||||
- name: Build the AAudio sink into the audio bundle
|
- name: Build the AAudio sink into the audio bundle
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -300,12 +345,11 @@ jobs:
|
|||||||
tar --use-compress-program=unzstd -xf app/src/main/assets/pulseaudio.tzst -C pa-bundle
|
tar --use-compress-program=unzstd -xf app/src/main/assets/pulseaudio.tzst -C pa-bundle
|
||||||
test ! -f pa-bundle/modules/arm64/module-aaudio-sink.so
|
test ! -f pa-bundle/modules/arm64/module-aaudio-sink.so
|
||||||
install -m755 sink-out/module-aaudio-sink.so pa-bundle/modules/arm64/module-aaudio-sink.so
|
install -m755 sink-out/module-aaudio-sink.so pa-bundle/modules/arm64/module-aaudio-sink.so
|
||||||
install -m755 sink-out/module-directaudio-sink.so pa-bundle/modules/arm64/module-directaudio-sink.so
|
install -m755 sink-out/module-directaudio-native-sink.so pa-bundle/modules/arm64/module-directaudio-native-sink.so
|
||||||
(cd pa-bundle && tar --use-compress-program='zstd -19' -cf ../pulseaudio.tzst .)
|
(cd pa-bundle && tar --use-compress-program='zstd -19' -cf ../pulseaudio.tzst .)
|
||||||
mv pulseaudio.tzst app/src/main/assets/pulseaudio.tzst
|
mv pulseaudio.tzst app/src/main/assets/pulseaudio.tzst
|
||||||
tar --use-compress-program=unzstd -tf app/src/main/assets/pulseaudio.tzst | grep -c '\.so$'
|
tar --use-compress-program=unzstd -tf app/src/main/assets/pulseaudio.tzst | grep -c '\.so$'
|
||||||
rm -rf pa-bundle sink-out
|
rm -rf pa-bundle sink-out
|
||||||
|
|
||||||
- name: Cache proot
|
- name: Cache proot
|
||||||
id: proot
|
id: proot
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
@@ -343,11 +387,23 @@ jobs:
|
|||||||
echo "::error::libfakeinput.so exports the C++ runtime"; exit 1
|
echo "::error::libfakeinput.so exports the C++ runtime"; exit 1
|
||||||
fi
|
fi
|
||||||
SESSION=$(syms "$D/libblsession.so")
|
SESSION=$(syms "$D/libblsession.so")
|
||||||
for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap drmPrimeFDToHandle drmCloseBufferHandle drmIoctl; do
|
for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap drmPrimeFDToHandle drmCloseBufferHandle; do
|
||||||
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
|
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
|
||||||
done
|
done
|
||||||
|
# Zink's GEM_CLOSE is caught at ioctl(); an exported drmIoctl made NMS replay old frames.
|
||||||
|
if grep -qx drmIoctl <<<"$SESSION"; then
|
||||||
|
echo "::error::libblsession.so exports drmIoctl"; exit 1
|
||||||
|
fi
|
||||||
|
SSBS=$(syms "$D/libssbs.so")
|
||||||
|
for sym in sigaction signal bsd_signal sysv_signal; do
|
||||||
|
grep -qx "$sym" <<<"$SSBS" || { echo "::error::libssbs.so does not export $sym"; exit 1; }
|
||||||
|
done
|
||||||
test -f "$D/usr/local/bin/droiddeck-session"
|
test -f "$D/usr/local/bin/droiddeck-session"
|
||||||
test -f "$D/usr/local/bin/droiddeck-proton-extra"
|
test -f "$D/usr/local/bin/droiddeck-proton-extra"
|
||||||
|
test -f "$D/usr/local/bin/droiddeck-msi-install"
|
||||||
|
for f in msiinfo cabextract libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||||
|
test -f "$D/usr/local/lib/droiddeck-msitools/$f" || { echo "::error::droiddeck-msitools/$f missing"; exit 1; }
|
||||||
|
done
|
||||||
|
|
||||||
- name: Cache the CMake build tree
|
- name: Cache the CMake build tree
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
|
|||||||
@@ -13,13 +13,28 @@ permissions:
|
|||||||
contents: read
|
contents: read
|
||||||
pull-requests: read
|
pull-requests: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: pr-release-${{ github.event.pull_request.number }}
|
||||||
|
cancel-in-progress: false
|
||||||
|
queue: max
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
cleanup:
|
cleanup:
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
timeout-minutes: 5
|
timeout-minutes: 5
|
||||||
steps:
|
steps:
|
||||||
|
- name: Check the current PR state
|
||||||
|
id: state
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
state=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .state)
|
||||||
|
echo "closed=$([ "$state" = closed ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||||
# A token of the org's "DroidDeck CI Publisher" app, as build.yml's announce job uses.
|
# A token of the org's "DroidDeck CI Publisher" app, as build.yml's announce job uses.
|
||||||
- uses: actions/create-github-app-token@v2
|
- uses: actions/create-github-app-token@v2
|
||||||
|
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||||
id: ci-token
|
id: ci-token
|
||||||
with:
|
with:
|
||||||
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
|
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
|
||||||
@@ -27,6 +42,7 @@ jobs:
|
|||||||
owner: Droid-Deck
|
owner: Droid-Deck
|
||||||
repositories: DroidDeck-CI
|
repositories: DroidDeck-CI
|
||||||
- name: Delete the test build
|
- name: Delete the test build
|
||||||
|
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
|
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
|
||||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||||
@@ -42,6 +58,19 @@ jobs:
|
|||||||
done
|
done
|
||||||
[ "$found" = 1 ] || echo "No test build for PR #$PR_NUMBER"
|
[ "$found" = 1 ] || echo "No test build for PR #$PR_NUMBER"
|
||||||
|
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||||
|
with:
|
||||||
|
ref: main
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Retire the Discord PR announcement
|
||||||
|
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||||
|
env:
|
||||||
|
WEBHOOK: ${{ secrets.DISCORD_PR_BUILDS_WEBHOOK }}
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||||
|
run: python3 tools/release/pr_discord.py retire
|
||||||
|
|
||||||
catalog:
|
catalog:
|
||||||
needs: cleanup
|
needs: cleanup
|
||||||
if: ${{ always() }}
|
if: ${{ always() }}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ permissions:
|
|||||||
concurrency:
|
concurrency:
|
||||||
group: pr-release-${{ 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 }}
|
group: pr-release-${{ 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 }}
|
||||||
cancel-in-progress: false
|
cancel-in-progress: false
|
||||||
|
queue: max
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
authorize:
|
authorize:
|
||||||
@@ -178,6 +179,10 @@ jobs:
|
|||||||
issues: write
|
issues: write
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
steps:
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: main
|
||||||
|
persist-credentials: false
|
||||||
- uses: actions/download-artifact@v4
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
pattern: droiddeck-pr-signed-*
|
pattern: droiddeck-pr-signed-*
|
||||||
@@ -307,39 +312,27 @@ jobs:
|
|||||||
$NEXT
|
$NEXT
|
||||||
EOF
|
EOF
|
||||||
)
|
)
|
||||||
id=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --paginate \
|
comment=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --paginate --slurp | \
|
||||||
--jq ".[] | select(.body | startswith(\"$mark\")) | .id" | head -1 || true)
|
jq "[.[][] | select(.user.login == \"github-actions[bot]\") | select(.body | startswith(\"$mark\"))] | first // {}")
|
||||||
|
id=$(jq -r '.id // empty' <<<"$comment")
|
||||||
if [ -n "$id" ]; then
|
if [ -n "$id" ]; then
|
||||||
|
state=$(jq -r '.body | split("\n")[] | select(startswith("<!-- droiddeck-discord: ") and endswith(" -->"))' <<<"$comment")
|
||||||
|
if [ -n "$state" ]; then body=$(printf '%s\n%s' "$body" "$state"); fi
|
||||||
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -f body="$body" >/dev/null
|
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -f body="$body" >/dev/null
|
||||||
else
|
else
|
||||||
gh api -X POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" -f body="$body" >/dev/null
|
gh api -X POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" -f body="$body" >/dev/null
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Asked for (the label, a manual run): always announced. Signed on its own after a push:
|
- name: Update the Discord PR announcement
|
||||||
# only a PR's first test build is, and later ones update its release quietly.
|
if: ${{ always() && steps.publish.outcome == 'success' }}
|
||||||
- name: Post to Discord
|
|
||||||
if: ${{ always() && steps.publish.outcome == 'success' && (needs.authorize.outputs.automatic != 'true' || steps.publish.outputs.first == 'true') }}
|
|
||||||
env:
|
env:
|
||||||
WEBHOOK: ${{ secrets.DISCORD_BUILDS_WEBHOOK }}
|
WEBHOOK: ${{ secrets.DISCORD_PR_BUILDS_WEBHOOK }}
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
||||||
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
|
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
|
||||||
RELEASE: ${{ steps.publish.outputs.release }}
|
RELEASE: ${{ steps.publish.outputs.release }}
|
||||||
APK: ${{ steps.publish.outputs.apk }}
|
APK: ${{ steps.publish.outputs.apk }}
|
||||||
run: |
|
run: python3 tools/release/pr_discord.py publish
|
||||||
set -euo pipefail
|
|
||||||
if [ -z "$WEBHOOK" ]; then
|
|
||||||
echo "::notice::No DISCORD_BUILDS_WEBHOOK secret; nothing posted"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
short=${HEAD_SHA:0:7}
|
|
||||||
title=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .title)
|
|
||||||
what="[#$PR_NUMBER]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$PR_NUMBER): $title"
|
|
||||||
get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE")
|
|
||||||
content=$(printf '**New signed PR test build** \`pr-%s\` · \`%s\`\n%s\n_Not merged — for testing._\n%s' "$PR_NUMBER" "$short" "$what" "$get")
|
|
||||||
jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
|
|
||||||
curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
|
|
||||||
echo "Posted: $content"
|
|
||||||
|
|
||||||
catalog:
|
catalog:
|
||||||
needs: publish
|
needs: publish
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ permissions:
|
|||||||
concurrency:
|
concurrency:
|
||||||
group: update-app-catalog
|
group: update-app-catalog
|
||||||
cancel-in-progress: false
|
cancel-in-progress: false
|
||||||
|
queue: max
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
catalog:
|
catalog:
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ app/src/main/assets/linuxfs/
|
|||||||
app/src/main/jniLibs/arm64-v8a/libproot.so
|
app/src/main/jniLibs/arm64-v8a/libproot.so
|
||||||
app/src/main/jniLibs/arm64-v8a/.proot-inputs
|
app/src/main/jniLibs/arm64-v8a/.proot-inputs
|
||||||
app/src/main/jniLibs/arm64-v8a/libproot-loader.so
|
app/src/main/jniLibs/arm64-v8a/libproot-loader.so
|
||||||
|
app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so
|
||||||
app/src/main/assets/droiddeck-esync/
|
app/src/main/assets/droiddeck-esync/
|
||||||
|
|
||||||
# Kotlin compiler session files (build-tool state, never source).
|
# Kotlin compiler session files (build-tool state, never source).
|
||||||
@@ -34,3 +35,4 @@ __pycache__/
|
|||||||
|
|
||||||
# Local signing with the release key (tools/build_local.sh); holds a password.
|
# Local signing with the release key (tools/build_local.sh); holds a password.
|
||||||
.signing.env
|
.signing.env
|
||||||
|
app/src/main/assets/directaudio/
|
||||||
@@ -15,7 +15,7 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big
|
|||||||
|
|
||||||
## Requirements and install
|
## Requirements and install
|
||||||
|
|
||||||
Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; with additional options to install Appimages and set up scripts.
|
Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Adreno 6xx is experimental: DirectX 11 uses DXVK 2 and may run, and DirectX 12 games can still crash. Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; with additional options to install Appimages and set up scripts.
|
||||||
|
|
||||||
Before Steam launches, you must turn off **Restrict child processes** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process.
|
Before Steam launches, you must turn off **Restrict child processes** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process.
|
||||||
|
|
||||||
|
|||||||
+6
-2
@@ -79,8 +79,8 @@ android {
|
|||||||
// file out of its own data directory, and this app's entire job is to exec a rootfs:
|
// file out of its own data directory, and this app's entire job is to exec a rootfs:
|
||||||
// proot, gamescope, the Steam client and everything it launches all live under files/.
|
// proot, gamescope, the Steam client and everything it launches all live under files/.
|
||||||
targetSdkVersion 28
|
targetSdkVersion 28
|
||||||
versionCode 11
|
versionCode 12
|
||||||
versionName "0.3.1"
|
versionName "0.3.2"
|
||||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||||
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
||||||
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
||||||
@@ -165,6 +165,8 @@ android {
|
|||||||
testOptions {
|
testOptions {
|
||||||
// Plain JVM tests: a stray android.util.Log call returns a default instead of throwing.
|
// Plain JVM tests: a stray android.util.Log call returns a default instead of throwing.
|
||||||
unitTests.returnDefaultValues = true
|
unitTests.returnDefaultValues = true
|
||||||
|
// Robolectric tests start activities whose text is now all string resources.
|
||||||
|
unitTests.includeAndroidResources = true
|
||||||
}
|
}
|
||||||
|
|
||||||
compileOptions {
|
compileOptions {
|
||||||
@@ -190,6 +192,8 @@ dependencies {
|
|||||||
// The runtime tarball is a zstd-compressed tar.
|
// The runtime tarball is a zstd-compressed tar.
|
||||||
implementation 'com.github.luben:zstd-jni:1.5.2-3@aar'
|
implementation 'com.github.luben:zstd-jni:1.5.2-3@aar'
|
||||||
implementation 'org.apache.commons:commons-compress:1.27.1'
|
implementation 'org.apache.commons:commons-compress:1.27.1'
|
||||||
|
// Bannerlator's Windows components come as .tar.xz (WinComponents).
|
||||||
|
implementation 'org.tukaani:xz:1.10'
|
||||||
// The UI: every menu, dialog and overlay is Compose. The session's SurfaceView and the
|
// The UI: every menu, dialog and overlay is Compose. The session's SurfaceView and the
|
||||||
// on-screen pad are Views underneath it, which is what they are in every Compose app.
|
// on-screen pad are Views underneath it, which is what they are in every Compose app.
|
||||||
implementation platform('androidx.compose:compose-bom:2024.02.00')
|
implementation platform('androidx.compose:compose-bom:2024.02.00')
|
||||||
|
|||||||
@@ -71,6 +71,10 @@
|
|||||||
<action android:name="android.intent.action.CREATE_SHORTCUT" />
|
<action android:name="android.intent.action.CREATE_SHORTCUT" />
|
||||||
<category android:name="android.intent.category.DEFAULT" />
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.droiddeck.launcher.LAUNCH_GAME" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
<!-- Android owns the Home key. This small translucent Home handler routes the resulting
|
<!-- Android owns the Home key. This small translucent Home handler routes the resulting
|
||||||
|
|||||||
@@ -1,115 +0,0 @@
|
|||||||
# DirectAudio for the Linux Steam client (relay build)
|
|
||||||
|
|
||||||
This is the driver for games that run under **Valve's ARM64 Proton inside a Linux
|
|
||||||
runtime on Android** - Bannerlator's linuxfs session with the native Steam client -
|
|
||||||
where the game process is a glibc process and cannot touch Android's audio
|
|
||||||
libraries itself.
|
|
||||||
|
|
||||||
Two pieces, both required:
|
|
||||||
|
|
||||||
| piece | what it is | where it runs |
|
|
||||||
|---|---|---|
|
|
||||||
| `aarch64-unix/winedirectaudio.so` + the two PE shells | the Wine `mmdevapi` driver, glibc build, **no AAudio inside** | in the game, inside the Linux rootfs |
|
|
||||||
| `directaudio-relay` | a small bionic program that owns the AAudio output and microphone streams | on the Android side, under the app's uid |
|
|
||||||
|
|
||||||
They meet over a unix socket. The driver connects, sends its launch config, and
|
|
||||||
gets back two shared-memory rings: one it fills with mixed game audio, one the
|
|
||||||
helper fills with microphone audio. The helper plays and records; the driver
|
|
||||||
keeps doing everything else it always did.
|
|
||||||
|
|
||||||
## Which Proton
|
|
||||||
|
|
||||||
Built inside `ValveSoftware/wine` at `proton_11.0`. The private `mmdevapi`
|
|
||||||
interface it implements is byte-identical across **Proton 11.0 (ARM64)**,
|
|
||||||
**Proton Experimental (ARM64)** and our own Wine-11 layers (checked 2026-09-19),
|
|
||||||
so this one build serves any of them. A future Proton on a Wine 12 base will
|
|
||||||
need a rebuild - the interface is not versioned, and a mismatch is silence, not
|
|
||||||
an error.
|
|
||||||
|
|
||||||
## Installing the driver next to Proton (not into it)
|
|
||||||
|
|
||||||
Steam verifies and updates its Proton depots, so files added under
|
|
||||||
`steamapps/common/Proton .../files/lib/wine/` will not survive. Put the driver
|
|
||||||
in a directory of its own and point Wine at it:
|
|
||||||
|
|
||||||
```
|
|
||||||
<somewhere>/directaudio/lib/wine/aarch64-unix/winedirectaudio.so
|
|
||||||
<somewhere>/directaudio/lib/wine/aarch64-windows/winedirectaudio.drv
|
|
||||||
<somewhere>/directaudio/lib/wine/i386-windows/winedirectaudio.drv
|
|
||||||
```
|
|
||||||
|
|
||||||
and set, for the game process:
|
|
||||||
|
|
||||||
```
|
|
||||||
WINEDLLPATH=<somewhere>/directaudio/lib/wine
|
|
||||||
```
|
|
||||||
|
|
||||||
Wine searches `WINEDLLPATH` entries with the per-arch subdirectories appended,
|
|
||||||
so both the PE shell and the unixlib are found there. In Bannerlator's runtime
|
|
||||||
the natural place to export it is the `bannerlator-proton` compatibility-tool
|
|
||||||
wrapper, which every Proton launch goes through.
|
|
||||||
|
|
||||||
## Selecting the driver
|
|
||||||
|
|
||||||
`mmdevapi` only tries the drivers named in the registry (or its built-in
|
|
||||||
`pulse,alsa,oss,coreaudio` list, which does not know about this one). Set, in the
|
|
||||||
game's prefix:
|
|
||||||
|
|
||||||
```
|
|
||||||
wine reg add "HKCU\Software\Wine\Drivers" /v Audio /d directaudio /f
|
|
||||||
```
|
|
||||||
|
|
||||||
Under Proton the prefix is `compatdata/<appid>/pfx`; run the command with that
|
|
||||||
prefix as `WINEPREFIX` using Proton's own `bin-arm64/wine`, or write the key from
|
|
||||||
the wrapper before it hands off to Proton.
|
|
||||||
|
|
||||||
## Running the helper
|
|
||||||
|
|
||||||
```
|
|
||||||
directaudio-relay --socket <path> [--log]
|
|
||||||
```
|
|
||||||
|
|
||||||
- Run it **under the app's uid**, the way the app already runs its PulseAudio
|
|
||||||
daemon. Android checks `RECORD_AUDIO` against the calling uid, so a helper
|
|
||||||
started any other way can play but cannot record.
|
|
||||||
- Start it **before** the game: the driver asks "is a helper there?" once, when
|
|
||||||
Wine picks an audio driver, and falls back to unavailable if not.
|
|
||||||
- The socket path must be reachable from inside the Linux rootfs. Bannerlator
|
|
||||||
binds the app's files directory and its runtime directory into the session at
|
|
||||||
their own paths, so any socket under either works unchanged on both sides.
|
|
||||||
- The helper serves any number of game processes; each gets its own streams.
|
|
||||||
It exits on `SIGTERM`; a game exiting tears down that game's streams only.
|
|
||||||
|
|
||||||
## Telling the driver where the helper is
|
|
||||||
|
|
||||||
```
|
|
||||||
BANNER_AUDIO_DIRECT_RELAY=<the same socket path>
|
|
||||||
```
|
|
||||||
|
|
||||||
Unset, the driver looks for `$XDG_RUNTIME_DIR/directaudio-relay`.
|
|
||||||
|
|
||||||
## Everything else is unchanged
|
|
||||||
|
|
||||||
All `BANNER_AUDIO_DIRECT_*` knobs mean what they mean in the in-process build:
|
|
||||||
`_PERF`, `_ADAPTIVE`, `_DECAY`, `_MS`, `_MAXMS`, `_BF`, `_MBF`, `_EXCLUSIVE`,
|
|
||||||
`_WATCHDOG`, `_STALL_MS`, `_DECAY_*`, `_LOG`, `_PERIOD_MS`, `_MINPERIOD_MS`, and
|
|
||||||
the live-config mailbox `_RUNTIME` (the helper watches the file; it must be a
|
|
||||||
path the helper can read on the Android side). **`BANNER_AUDIO_DIRECT_MIC=1`**
|
|
||||||
exposes the capture endpoint exactly as before: the helper opens the input
|
|
||||||
stream (`VOICE_COMMUNICATION` preset) when the game connects and makes it hot on
|
|
||||||
the game's first capture start.
|
|
||||||
|
|
||||||
One thing is different: there is one extra hand-off, the ring. The helper's
|
|
||||||
callback pulls a burst from it, so the driver keeps two bursts queued (about 8 ms
|
|
||||||
on a 192-frame device) on top of the AAudio buffer the presets control, and the
|
|
||||||
helper raises that if a callback ever finds the ring short. `get_latency` reports
|
|
||||||
the sum, so a game that sizes its own buffers from it still sees the truth.
|
|
||||||
|
|
||||||
## Proving it is running
|
|
||||||
|
|
||||||
- Helper side: `logcat -s DA-Relay:I` shows `hello from <exe>`, then `open: buffer
|
|
||||||
... ring target ...`, then `capture open` / `capture start` for the mic.
|
|
||||||
- Game side: the session log carries `DirectAudio: relay: connected - ...`.
|
|
||||||
- The game process's `/proc/<pid>/maps` shows `winedirectaudio.so` and **no**
|
|
||||||
`libaaudio.so` (it is in the helper's maps instead). The AudioFlinger track is
|
|
||||||
owned by the helper's pid.
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,4 +0,0 @@
|
|||||||
directaudio linux-wine11 relay build
|
|
||||||
source 3548a4a730e8d01cb0cb0268d51a2fb8f23dcd33
|
|
||||||
wine ValveSoftware/wine@proton_11.0
|
|
||||||
unixlib.h sha256 fdbed263338d0719c4d12e02b045c23721de33219ec8878e4c2d7ebc9efcbe09
|
|
||||||
@@ -44,6 +44,11 @@ add_subdirectory(waylandcomp)
|
|||||||
add_library(sdnative SHARED sdnative/sdnative.c)
|
add_library(sdnative SHARED sdnative/sdnative.c)
|
||||||
target_link_libraries(sdnative log)
|
target_link_libraries(sdnative log)
|
||||||
|
|
||||||
|
# The device info window's Vulkan section: the phone's own driver, asked once through the system
|
||||||
|
# loader (opened with dlopen, so a phone without Vulkan still loads the app).
|
||||||
|
add_library(deviceinfo SHARED deviceinfo/vkinfo.c)
|
||||||
|
target_link_libraries(deviceinfo dl)
|
||||||
|
|
||||||
# Rebuild Termux terminal-emulator's PTY JNI helper with the app's NDK instead of carrying its
|
# Rebuild Termux terminal-emulator's PTY JNI helper with the app's NDK instead of carrying its
|
||||||
# prebuilt libtermux.so with a redundant libstdc++.so dependency.
|
# prebuilt libtermux.so with a redundant libstdc++.so dependency.
|
||||||
add_library(termux SHARED termux/termux.c)
|
add_library(termux SHARED termux/termux.c)
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
// What the phone's own Vulkan driver says about its GPU, for the app's device info window: one
|
||||||
|
// instance on the system loader, the first physical device's properties, a few limits and the
|
||||||
|
// extensions DXVK and VKD3D-Proton lean on. Returned as "key=value" lines; nothing is kept open.
|
||||||
|
#include <dlfcn.h>
|
||||||
|
#include <jni.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
#define VK_NO_PROTOTYPES
|
||||||
|
#include <vulkan/vulkan.h>
|
||||||
|
|
||||||
|
#define LINE(...) do { if (used < sizeof(out)) used += snprintf(out + used, sizeof(out) - used, __VA_ARGS__); } while (0)
|
||||||
|
|
||||||
|
static const char *const EXTENSIONS[] = {
|
||||||
|
"VK_EXT_robustness2", "VK_EXT_transform_feedback", "VK_EXT_custom_border_color",
|
||||||
|
"VK_KHR_dynamic_rendering", "VK_EXT_extended_dynamic_state3", "VK_EXT_descriptor_indexing",
|
||||||
|
"VK_KHR_timeline_semaphore", "VK_EXT_mesh_shader", "VK_KHR_ray_query",
|
||||||
|
};
|
||||||
|
|
||||||
|
static const char *type_name(VkPhysicalDeviceType type) {
|
||||||
|
switch (type) {
|
||||||
|
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated GPU";
|
||||||
|
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete GPU";
|
||||||
|
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual GPU";
|
||||||
|
case VK_PHYSICAL_DEVICE_TYPE_CPU: return "CPU";
|
||||||
|
default: return "other";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT jstring JNICALL
|
||||||
|
Java_com_droiddeck_launcher_gpu_VulkanInfo_nativeQuery(JNIEnv *env, jclass clazz) {
|
||||||
|
static char out[4096];
|
||||||
|
size_t used = 0;
|
||||||
|
out[0] = 0;
|
||||||
|
void *lib = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
|
||||||
|
if (!lib) { LINE("error=no Vulkan loader\n"); return (*env)->NewStringUTF(env, out); }
|
||||||
|
PFN_vkGetInstanceProcAddr gipa = (PFN_vkGetInstanceProcAddr) dlsym(lib, "vkGetInstanceProcAddr");
|
||||||
|
PFN_vkCreateInstance create = gipa ? (PFN_vkCreateInstance) gipa(NULL, "vkCreateInstance") : NULL;
|
||||||
|
PFN_vkEnumerateInstanceVersion instanceVersion = gipa ? (PFN_vkEnumerateInstanceVersion) gipa(NULL, "vkEnumerateInstanceVersion") : NULL;
|
||||||
|
if (!create) { LINE("error=no vkCreateInstance\n"); dlclose(lib); return (*env)->NewStringUTF(env, out); }
|
||||||
|
uint32_t loader = VK_API_VERSION_1_0;
|
||||||
|
if (instanceVersion) instanceVersion(&loader);
|
||||||
|
LINE("loader=%u.%u.%u\n", VK_API_VERSION_MAJOR(loader), VK_API_VERSION_MINOR(loader), VK_API_VERSION_PATCH(loader));
|
||||||
|
|
||||||
|
VkApplicationInfo app = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "DroidDeck device info",
|
||||||
|
.apiVersion = loader >= VK_API_VERSION_1_1 ? VK_API_VERSION_1_1 : VK_API_VERSION_1_0 };
|
||||||
|
VkInstanceCreateInfo info = { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app };
|
||||||
|
VkInstance instance = VK_NULL_HANDLE;
|
||||||
|
if (create(&info, NULL, &instance) != VK_SUCCESS) { LINE("error=vkCreateInstance failed\n"); dlclose(lib); return (*env)->NewStringUTF(env, out); }
|
||||||
|
|
||||||
|
#define GET(name) PFN_##name name = (PFN_##name) gipa(instance, #name)
|
||||||
|
GET(vkDestroyInstance); GET(vkEnumeratePhysicalDevices); GET(vkGetPhysicalDeviceProperties);
|
||||||
|
GET(vkGetPhysicalDeviceProperties2); GET(vkGetPhysicalDeviceMemoryProperties);
|
||||||
|
GET(vkEnumerateDeviceExtensionProperties); GET(vkGetPhysicalDeviceFeatures);
|
||||||
|
uint32_t count = 1;
|
||||||
|
VkPhysicalDevice device = VK_NULL_HANDLE;
|
||||||
|
VkResult listed = vkEnumeratePhysicalDevices ? vkEnumeratePhysicalDevices(instance, &count, &device) : VK_ERROR_INITIALIZATION_FAILED;
|
||||||
|
if ((listed != VK_SUCCESS && listed != VK_INCOMPLETE) || count == 0 || !device || !vkGetPhysicalDeviceProperties) {
|
||||||
|
LINE("error=no Vulkan device\n");
|
||||||
|
} else {
|
||||||
|
VkPhysicalDeviceProperties p;
|
||||||
|
vkGetPhysicalDeviceProperties(device, &p);
|
||||||
|
LINE("device=%s\n", p.deviceName);
|
||||||
|
LINE("type=%s\n", type_name(p.deviceType));
|
||||||
|
LINE("api=%u.%u.%u\n", VK_API_VERSION_MAJOR(p.apiVersion), VK_API_VERSION_MINOR(p.apiVersion), VK_API_VERSION_PATCH(p.apiVersion));
|
||||||
|
// Qualcomm packs its driver version as 10.10.12 bits, the same layout as VK_MAKE_VERSION.
|
||||||
|
LINE("driver_version=%u.%u.%u\n", p.driverVersion >> 22, (p.driverVersion >> 12) & 0x3ff, p.driverVersion & 0xfff);
|
||||||
|
LINE("vendor_id=0x%04x\ndevice_id=0x%08x\n", p.vendorID, p.deviceID);
|
||||||
|
LINE("max_image_2d=%u\n", p.limits.maxImageDimension2D);
|
||||||
|
|
||||||
|
// Driver name and build string (Vulkan 1.2 or VK_KHR_driver_properties).
|
||||||
|
uint32_t extCount = 0;
|
||||||
|
if (vkEnumerateDeviceExtensionProperties) vkEnumerateDeviceExtensionProperties(device, NULL, &extCount, NULL);
|
||||||
|
static VkExtensionProperties exts[512];
|
||||||
|
if (extCount > 512) extCount = 512;
|
||||||
|
if (extCount && vkEnumerateDeviceExtensionProperties) vkEnumerateDeviceExtensionProperties(device, NULL, &extCount, exts);
|
||||||
|
int driverProps = p.apiVersion >= VK_API_VERSION_1_2;
|
||||||
|
for (uint32_t i = 0; i < extCount; i++)
|
||||||
|
if (!strcmp(exts[i].extensionName, "VK_KHR_driver_properties")) driverProps = 1;
|
||||||
|
if (driverProps && vkGetPhysicalDeviceProperties2) {
|
||||||
|
VkPhysicalDeviceDriverProperties driver = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES };
|
||||||
|
VkPhysicalDeviceProperties2 p2 = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &driver };
|
||||||
|
vkGetPhysicalDeviceProperties2(device, &p2);
|
||||||
|
LINE("driver_name=%s\n", driver.driverName);
|
||||||
|
LINE("driver_info=%s\n", driver.driverInfo);
|
||||||
|
LINE("conformance=%u.%u.%u.%u\n", driver.conformanceVersion.major, driver.conformanceVersion.minor,
|
||||||
|
driver.conformanceVersion.subminor, driver.conformanceVersion.patch);
|
||||||
|
}
|
||||||
|
LINE("extension_count=%u\n", extCount);
|
||||||
|
for (size_t e = 0; e < sizeof(EXTENSIONS) / sizeof(*EXTENSIONS); e++) {
|
||||||
|
int has = 0;
|
||||||
|
for (uint32_t i = 0; i < extCount && !has; i++) has = !strcmp(exts[i].extensionName, EXTENSIONS[e]);
|
||||||
|
LINE("ext.%s=%s\n", EXTENSIONS[e], has ? "yes" : "no");
|
||||||
|
}
|
||||||
|
if (vkGetPhysicalDeviceFeatures) {
|
||||||
|
VkPhysicalDeviceFeatures f;
|
||||||
|
vkGetPhysicalDeviceFeatures(device, &f);
|
||||||
|
LINE("geometry_shader=%s\ntessellation_shader=%s\ntexture_bc=%s\n",
|
||||||
|
f.geometryShader ? "yes" : "no", f.tessellationShader ? "yes" : "no", f.textureCompressionBC ? "yes" : "no");
|
||||||
|
}
|
||||||
|
if (vkGetPhysicalDeviceMemoryProperties) {
|
||||||
|
VkPhysicalDeviceMemoryProperties m;
|
||||||
|
vkGetPhysicalDeviceMemoryProperties(device, &m);
|
||||||
|
VkDeviceSize largest = 0;
|
||||||
|
for (uint32_t i = 0; i < m.memoryHeapCount; i++)
|
||||||
|
if ((m.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) && m.memoryHeaps[i].size > largest) largest = m.memoryHeaps[i].size;
|
||||||
|
LINE("device_heap_mb=%llu\n", (unsigned long long) (largest >> 20));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (vkDestroyInstance) vkDestroyInstance(instance, NULL);
|
||||||
|
dlclose(lib);
|
||||||
|
return (*env)->NewStringUTF(env, out);
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <cerrno>
|
#include <cerrno>
|
||||||
#include <climits>
|
#include <climits>
|
||||||
|
#include <cstddef>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
@@ -1216,6 +1217,7 @@ struct DeckHidraw {
|
|||||||
FakeInputRingHeader *ring = nullptr;
|
FakeInputRingHeader *ring = nullptr;
|
||||||
size_t mapping_size = 0;
|
size_t mapping_size = 0;
|
||||||
uint8_t pending_feature = 0;
|
uint8_t pending_feature = 0;
|
||||||
|
bool touch = false; // Steam's touch controller (below), not the Deck
|
||||||
};
|
};
|
||||||
|
|
||||||
// What the Deck has and an Xbox pad does not, after the ring's events: motion (PadMotion) and the
|
// What the Deck has and an Xbox pad does not, after the ring's events: motion (PadMotion) and the
|
||||||
@@ -1315,13 +1317,15 @@ __attribute__((visibility("hidden"))) static bool is_deck_hidraw_path(const char
|
|||||||
return pathname && fake_deck_enabled() && !strcmp(pathname, DECK_HIDRAW_PATH);
|
return pathname && fake_deck_enabled() && !strcmp(pathname, DECK_HIDRAW_PATH);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The app's own pads are the Deck now; their evdev nodes are withdrawn from everyone.
|
// The app's first pad is the Deck now: its evdev node is withdrawn from everyone. Further players'
|
||||||
|
// pads are left to the client alone, which hands them to games through Steam Input.
|
||||||
__attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const char *pathname) {
|
__attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const char *pathname) {
|
||||||
if (!fake_deck_enabled() || !pathname || strncmp(pathname, "/dev/input/", 11)) return false;
|
if (!fake_deck_enabled() || !pathname || strncmp(pathname, "/dev/input/", 11)) return false;
|
||||||
const char *event = strrchr(pathname, '/') + 1;
|
const char *event = strrchr(pathname, '/') + 1;
|
||||||
if (strncmp(event, "event", 5) && strncmp(event, "js", 2)) return false;
|
if (strncmp(event, "event", 5) && strncmp(event, "js", 2)) return false;
|
||||||
int number = get_event_number(event);
|
int number = get_event_number(event);
|
||||||
return number >= 0 && number < UINPUT_EVENT_BASE;
|
if (number < 0 || number >= UINPUT_EVENT_BASE) return false;
|
||||||
|
return number == 0 || !process_is_steam_client();
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline void put16(uint8_t *at, int value) {
|
static inline void put16(uint8_t *at, int value) {
|
||||||
@@ -1483,6 +1487,321 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) {
|
|||||||
return pair[0];
|
return pair[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ---- Steam's touch controller ----
|
||||||
|
//
|
||||||
|
// docs/development/steam-touch-controller.md. Steam builds its touch controller (Steam Input's
|
||||||
|
// Mobile Touch type, the one Steam Link's on-screen controls are) for any HID device with the ids
|
||||||
|
// 0000:11fb. With FAKE_TOUCHCTL_RING set, the client is offered one as /dev/hidraw17 beside the
|
||||||
|
// Deck, its sysfs written by the app (SteamDeckPad.kt). The app draws the controls; this side only
|
||||||
|
// carries the device's traffic through the file FAKE_TOUCHCTL_RING names, which both map:
|
||||||
|
//
|
||||||
|
// - the app writes the 40-byte input report (under a seqlock), whether the device is plugged in,
|
||||||
|
// and the battery level;
|
||||||
|
// - this side writes what the client tells the device: the app and action set it is on (output
|
||||||
|
// report 4), the action set layers added and removed (5, 6), rumble (1, also passed to the app's
|
||||||
|
// vibration like any pad's) and the setting report (3), and how many readers have it open.
|
||||||
|
//
|
||||||
|
// Plugged in and out by the app (while its controls are up and no physical pad is in use), as
|
||||||
|
// Steam Link withdraws its touch controls: an unplugged device ends its open stream, refuses new
|
||||||
|
// opens, and a udev event (libblsession's stand-in monitor, udevmon.c) tells the client's HID
|
||||||
|
// discovery either way. Only the client is offered it; a game reads Steam Input's virtual pad.
|
||||||
|
static constexpr const char *TOUCH_HIDRAW_PATH = "/dev/hidraw17";
|
||||||
|
static constexpr unsigned int TOUCH_HIDRAW_MINOR = 17;
|
||||||
|
static constexpr int TOUCH_REPORT_BYTES = 40;
|
||||||
|
static constexpr int TOUCH_REPORT_INTERVAL_US = 8000;
|
||||||
|
static constexpr const char *TOUCH_NAME = "Mobile Touch Control";
|
||||||
|
static constexpr const char *TOUCH_SERIAL = "DROIDDECK0001";
|
||||||
|
static constexpr const char *TOUCH_DEVPATH = "/devices/droiddeck/usb2/2-1:1.0/0003:0000:11FB.0002/hidraw/hidraw17";
|
||||||
|
// Generic Desktop / Game Pad: for a vendor id that is not Valve's the client opens only a device
|
||||||
|
// with a gamepad usage. One 40-byte input report, one 64-byte output and one 64-byte feature
|
||||||
|
// report, no report ids. Must match SteamDeckPad.kt.
|
||||||
|
static const uint8_t kTouchReportDescriptor[] = {
|
||||||
|
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01,
|
||||||
|
0x09, 0x02, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x28, 0x81, 0x02,
|
||||||
|
0x09, 0x03, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02,
|
||||||
|
0x09, 0x04, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0};
|
||||||
|
|
||||||
|
// The shared file. Must match SteamTouchDevice.kt.
|
||||||
|
struct TouchRingFile {
|
||||||
|
uint32_t magic; // TCH1
|
||||||
|
uint32_t version;
|
||||||
|
uint64_t report_seq; // odd while the app writes report
|
||||||
|
uint8_t report[TOUCH_REPORT_BYTES];
|
||||||
|
uint32_t plugged;
|
||||||
|
uint32_t battery; // percent
|
||||||
|
// Written here.
|
||||||
|
uint64_t state_seq; // odd while being written
|
||||||
|
uint32_t opened;
|
||||||
|
uint32_t appid;
|
||||||
|
uint32_t action_set;
|
||||||
|
uint32_t layer_count;
|
||||||
|
uint32_t layers[8];
|
||||||
|
uint32_t rumble_seq;
|
||||||
|
uint16_t rumble_low;
|
||||||
|
uint16_t rumble_high;
|
||||||
|
uint32_t rumble_ms;
|
||||||
|
uint32_t setting30;
|
||||||
|
uint32_t action_seq;
|
||||||
|
};
|
||||||
|
static constexpr uint32_t TOUCH_RING_MAGIC = 0x31484354;
|
||||||
|
static constexpr size_t TOUCH_RING_SIZE = 256;
|
||||||
|
static_assert(offsetof(TouchRingFile, report) == 16, "TouchRingFile layout");
|
||||||
|
static_assert(offsetof(TouchRingFile, plugged) == 56, "TouchRingFile layout");
|
||||||
|
static_assert(offsetof(TouchRingFile, state_seq) == 64, "TouchRingFile layout");
|
||||||
|
static_assert(offsetof(TouchRingFile, layers) == 88, "TouchRingFile layout");
|
||||||
|
static_assert(offsetof(TouchRingFile, rumble_seq) == 120, "TouchRingFile layout");
|
||||||
|
static_assert(offsetof(TouchRingFile, action_seq) == 136, "TouchRingFile layout");
|
||||||
|
static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
||||||
|
static TouchRingFile *ring = nullptr;
|
||||||
|
static std::once_flag once;
|
||||||
|
std::call_once(once, [] {
|
||||||
|
const char *path = getenv("FAKE_TOUCHCTL_RING");
|
||||||
|
if (!path || !*path || !fake_deck_enabled()) return;
|
||||||
|
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||||
|
int fd = my_open(path, O_RDWR | O_CLOEXEC);
|
||||||
|
if (fd < 0) {
|
||||||
|
Logger::log("touch: %s not openable (%s)\n", path, strerror(errno));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void *mapping = mmap(nullptr, TOUCH_RING_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||||
|
syscall(SYS_close, fd);
|
||||||
|
if (mapping == MAP_FAILED || static_cast<TouchRingFile *>(mapping)->magic != TOUCH_RING_MAGIC) {
|
||||||
|
Logger::log("touch: %s %s\n", path, mapping == MAP_FAILED ? "could not be mapped" : "has no valid header");
|
||||||
|
if (mapping != MAP_FAILED) munmap(mapping, TOUCH_RING_SIZE);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ring = static_cast<TouchRingFile *>(mapping);
|
||||||
|
});
|
||||||
|
return ring;
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static bool touch_plugged() {
|
||||||
|
TouchRingFile *ring = touch_ring();
|
||||||
|
return ring && __atomic_load_n(&ring->plugged, __ATOMIC_ACQUIRE) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static bool is_touch_hidraw_path(const char *pathname) {
|
||||||
|
return pathname && !strcmp(pathname, TOUCH_HIDRAW_PATH) && process_is_steam_client() && touch_ring();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The state the client gave the device, written under the ring's seqlock.
|
||||||
|
template <typename F>
|
||||||
|
__attribute__((visibility("hidden"))) static void touch_state(F &&write) {
|
||||||
|
TouchRingFile *ring = touch_ring();
|
||||||
|
if (!ring) return;
|
||||||
|
static std::mutex mutex;
|
||||||
|
std::lock_guard<std::mutex> guard(mutex);
|
||||||
|
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
|
||||||
|
write(*ring);
|
||||||
|
__atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL);
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline uint32_t get32(const uint8_t *at) {
|
||||||
|
return static_cast<uint32_t>(at[0]) | static_cast<uint32_t>(at[1]) << 8 | static_cast<uint32_t>(at[2]) << 16 |
|
||||||
|
static_cast<uint32_t>(at[3]) << 24;
|
||||||
|
}
|
||||||
|
|
||||||
|
// An output report from the client (Steam Link's CVirtualController::HandleFeatureReports): the
|
||||||
|
// type, then its fields.
|
||||||
|
__attribute__((visibility("hidden"))) static void touch_output(const uint8_t *data, size_t size) {
|
||||||
|
if (size < 9) return;
|
||||||
|
static std::atomic<unsigned> seen[8];
|
||||||
|
uint8_t type = data[0];
|
||||||
|
unsigned n = type < 8 ? ++seen[type] : 0;
|
||||||
|
if (n && (n & (n - 1)) == 0)
|
||||||
|
Logger::log("touch: output report %u (x%u): app %u, %u\n", type, n, get32(data + 1), get32(data + 5));
|
||||||
|
switch (type) {
|
||||||
|
case 1: { // rumble: low, high, duration
|
||||||
|
uint16_t low = data[1] | data[2] << 8, high = data[3] | data[4] << 8;
|
||||||
|
uint32_t ms = get32(data + 5);
|
||||||
|
touch_state([&](TouchRingFile &r) {
|
||||||
|
r.rumble_low = low;
|
||||||
|
r.rumble_high = high;
|
||||||
|
r.rumble_ms = ms;
|
||||||
|
r.rumble_seq++;
|
||||||
|
});
|
||||||
|
send_vibration(low, high, static_cast<uint16_t>(std::min<uint32_t>(ms, 0xffff)), 0);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 3: // a setting: 0x30 and a value
|
||||||
|
if (data[1] == 0x30) touch_state([&](TouchRingFile &r) { r.setting30 = data[2] | data[3] << 8; });
|
||||||
|
break;
|
||||||
|
case 4: // the app and its action set
|
||||||
|
touch_state([&](TouchRingFile &r) {
|
||||||
|
r.appid = get32(data + 1);
|
||||||
|
r.action_set = get32(data + 5);
|
||||||
|
r.layer_count = 0;
|
||||||
|
r.action_seq++;
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case 5: // a layer added to the app's action set
|
||||||
|
case 6: // and removed
|
||||||
|
touch_state([&](TouchRingFile &r) {
|
||||||
|
uint32_t layer = get32(data + 5);
|
||||||
|
uint32_t count = std::min<uint32_t>(r.layer_count, 8);
|
||||||
|
uint32_t kept = 0;
|
||||||
|
for (uint32_t i = 0; i < count; i++)
|
||||||
|
if (r.layers[i] != layer) r.layers[kept++] = r.layers[i];
|
||||||
|
if (type == 5 && kept < 8) r.layers[kept++] = layer;
|
||||||
|
r.layer_count = kept;
|
||||||
|
r.action_seq++;
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static bool read_touch_report(TouchRingFile *ring, uint8_t *out) {
|
||||||
|
for (int attempt = 0; attempt < 8; attempt++) {
|
||||||
|
uint64_t seq = __atomic_load_n(&ring->report_seq, __ATOMIC_ACQUIRE);
|
||||||
|
if (seq & 1) continue;
|
||||||
|
memcpy(out, ring->report, TOUCH_REPORT_BYTES);
|
||||||
|
__atomic_thread_fence(__ATOMIC_ACQUIRE);
|
||||||
|
if (seq == __atomic_load_n(&ring->report_seq, __ATOMIC_RELAXED)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static void *touch_report_thread(void *arg) {
|
||||||
|
auto *holder = static_cast<std::shared_ptr<DeckHidraw> *>(arg);
|
||||||
|
std::shared_ptr<DeckHidraw> self = *holder;
|
||||||
|
delete holder;
|
||||||
|
TouchRingFile *ring = touch_ring();
|
||||||
|
uint8_t report[TOUCH_REPORT_BYTES] = {};
|
||||||
|
while (touch_plugged()) {
|
||||||
|
read_touch_report(ring, report);
|
||||||
|
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||||
|
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||||
|
break;
|
||||||
|
struct timespec interval = {0, TOUCH_REPORT_INTERVAL_US * 1000L};
|
||||||
|
nanosleep(&interval, nullptr);
|
||||||
|
}
|
||||||
|
// Ending the stream is the unplug: the client's read fails and it lets the controller go.
|
||||||
|
syscall(SYS_close, self->peer);
|
||||||
|
touch_state([](TouchRingFile &r) { if (r.opened) r.opened--; });
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static int open_touch_hidraw(int flags) {
|
||||||
|
if (!touch_plugged()) {
|
||||||
|
errno = ENOENT;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int pair[2];
|
||||||
|
if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, pair) < 0) return -1;
|
||||||
|
int buffer = TOUCH_REPORT_BYTES * 4;
|
||||||
|
setsockopt(pair[1], SOL_SOCKET, SO_SNDBUF, &buffer, sizeof(buffer));
|
||||||
|
if (!(flags & O_CLOEXEC)) fcntl(pair[0], F_SETFD, 0);
|
||||||
|
if (flags & O_NONBLOCK) fcntl(pair[0], F_SETFL, fcntl(pair[0], F_GETFL) | O_NONBLOCK);
|
||||||
|
auto touch = std::make_shared<DeckHidraw>();
|
||||||
|
touch->peer = pair[1];
|
||||||
|
touch->touch = true;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
||||||
|
deck_map()[pair[0]] = touch;
|
||||||
|
}
|
||||||
|
touch_state([](TouchRingFile &r) { r.opened++; });
|
||||||
|
pthread_t thread;
|
||||||
|
auto *arg = new std::shared_ptr<DeckHidraw>(touch);
|
||||||
|
if (pthread_create(&thread, nullptr, touch_report_thread, arg) != 0) {
|
||||||
|
delete arg;
|
||||||
|
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
||||||
|
deck_map().erase(pair[0]);
|
||||||
|
syscall(SYS_close, pair[0]);
|
||||||
|
syscall(SYS_close, pair[1]);
|
||||||
|
touch_state([](TouchRingFile &r) { if (r.opened) r.opened--; });
|
||||||
|
errno = ENOMEM;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
pthread_detach(thread);
|
||||||
|
Logger::log("touch: %s opened as fd %d\n", TOUCH_HIDRAW_PATH, pair[0]);
|
||||||
|
return pair[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
static int copy_ioctl_string(ioctl_request_t op, void *argp, const char *value);
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static int ioctl_touch(DeckHidraw &touch, ioctl_request_t op, void *argp) {
|
||||||
|
if (_IOC_TYPE(op) != 'H') {
|
||||||
|
errno = ENOTTY;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
size_t size = _IOC_SIZE(op);
|
||||||
|
switch (_IOC_NR(op)) {
|
||||||
|
case 0x01: // HIDIOCGRDESCSIZE
|
||||||
|
*static_cast<int *>(argp) = sizeof(kTouchReportDescriptor);
|
||||||
|
return 0;
|
||||||
|
case 0x02: { // HIDIOCGRDESC
|
||||||
|
auto *descriptor = static_cast<uint8_t *>(argp);
|
||||||
|
uint32_t want;
|
||||||
|
memcpy(&want, descriptor, sizeof(want));
|
||||||
|
memcpy(descriptor + 4, kTouchReportDescriptor, std::min<size_t>(want, sizeof(kTouchReportDescriptor)));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
case 0x03: { // HIDIOCGRAWINFO
|
||||||
|
struct {
|
||||||
|
uint32_t bustype;
|
||||||
|
int16_t vendor;
|
||||||
|
int16_t product;
|
||||||
|
} info = {BUS_USB, 0x0000, static_cast<int16_t>(0x11fb)};
|
||||||
|
memcpy(argp, &info, sizeof(info));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
case 0x04: return copy_ioctl_string(op, argp, TOUCH_NAME); // HIDIOCGRAWNAME
|
||||||
|
case 0x05: return copy_ioctl_string(op, argp, "usb-droiddeck-2/input0"); // HIDIOCGRAWPHYS
|
||||||
|
case 0x08: return copy_ioctl_string(op, argp, TOUCH_SERIAL); // HIDIOCGRAWUNIQ
|
||||||
|
case 0x06: // HIDIOCSFEATURE: Steam Link's controller ignores these
|
||||||
|
touch.pending_feature = size > 0 ? static_cast<uint8_t *>(argp)[0] : 0;
|
||||||
|
return static_cast<int>(size);
|
||||||
|
case 0x07: { // HIDIOCGFEATURE: report 2 is the battery
|
||||||
|
auto *buf = static_cast<uint8_t *>(argp);
|
||||||
|
uint8_t id = size ? buf[0] : 0;
|
||||||
|
memset(buf, 0, size);
|
||||||
|
if (size) buf[0] = id;
|
||||||
|
if (size > 2) {
|
||||||
|
TouchRingFile *ring = touch_ring();
|
||||||
|
buf[1] = 2;
|
||||||
|
buf[2] = static_cast<uint8_t>(ring && ring->battery ? std::min<uint32_t>(ring->battery, 100) : 100);
|
||||||
|
}
|
||||||
|
return static_cast<int>(std::min<size_t>(size, 18));
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
errno = EINVAL;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plugging in and out: the app flips `plugged`; this tells the client's HID discovery, which
|
||||||
|
// otherwise never looks again (the sandbox gives it no kernel uevents).
|
||||||
|
__attribute__((visibility("hidden"))) static void touch_uevent(const char *action) {
|
||||||
|
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
|
||||||
|
static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "bl_udevmon_inject"));
|
||||||
|
int sent = inject ? inject(action, TOUCH_DEVPATH, "hidraw", TOUCH_HIDRAW_PATH, DECK_HIDRAW_MAJOR, TOUCH_HIDRAW_MINOR) : -1;
|
||||||
|
Logger::log("touch: %s (udev event to %d monitor%s)\n", action, sent, sent == 1 ? "" : "s");
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((visibility("hidden"))) static void *touch_plug_thread(void *) {
|
||||||
|
bool was = touch_plugged();
|
||||||
|
Logger::log("touch: %s at start\n", was ? "plugged in" : "unplugged");
|
||||||
|
for (;;) {
|
||||||
|
struct timespec interval = {0, 50 * 1000 * 1000};
|
||||||
|
nanosleep(&interval, nullptr);
|
||||||
|
bool now = touch_plugged();
|
||||||
|
if (now == was) continue;
|
||||||
|
was = now;
|
||||||
|
touch_uevent(now ? "add" : "remove");
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((constructor)) static void start_touch_controller() {
|
||||||
|
config();
|
||||||
|
if (!process_is_steam_client() || !touch_ring()) return;
|
||||||
|
pthread_t thread;
|
||||||
|
if (pthread_create(&thread, nullptr, touch_plug_thread, nullptr) == 0) pthread_detach(thread);
|
||||||
|
}
|
||||||
|
|
||||||
// libudev (systemd's sd-device) accepts a device only where its directory is on sysfs, which it
|
// libudev (systemd's sd-device) accepts a device only where its directory is on sysfs, which it
|
||||||
// checks with fstatfs on the directory it resolved. The Deck's sysfs is the app's own files bound
|
// checks with fstatfs on the directory it resolved. The Deck's sysfs is the app's own files bound
|
||||||
// into /sys, so those paths are said to be sysfs; nothing else is touched.
|
// into /sys, so those paths are said to be sysfs; nothing else is touched.
|
||||||
@@ -1823,6 +2142,7 @@ EXPORT int open(const char *pathname, int flags, ...) {
|
|||||||
|
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
||||||
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
||||||
|
if (is_touch_hidraw_path(pathname)) return open_touch_hidraw(flags);
|
||||||
if (is_withdrawn_pad_path(pathname)) {
|
if (is_withdrawn_pad_path(pathname)) {
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
@@ -1897,6 +2217,7 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) {
|
|||||||
|
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
||||||
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
||||||
|
if (is_touch_hidraw_path(pathname)) return open_touch_hidraw(flags);
|
||||||
if (is_withdrawn_pad_path(pathname)) {
|
if (is_withdrawn_pad_path(pathname)) {
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
@@ -1957,6 +2278,12 @@ static int fake_stat_path(const char *pathname, S *statbuf, Real real) {
|
|||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
if (is_touch_hidraw_path(pathname)) {
|
||||||
|
memset(statbuf, 0, sizeof(*statbuf));
|
||||||
|
statbuf->st_mode = S_IFCHR | 0666;
|
||||||
|
statbuf->st_rdev = makedev(DECK_HIDRAW_MAJOR, TOUCH_HIDRAW_MINOR);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
if (is_deck_hidraw_path(pathname)) {
|
if (is_deck_hidraw_path(pathname)) {
|
||||||
memset(statbuf, 0, sizeof(*statbuf));
|
memset(statbuf, 0, sizeof(*statbuf));
|
||||||
statbuf->st_mode = S_IFCHR | 0666;
|
statbuf->st_mode = S_IFCHR | 0666;
|
||||||
@@ -2008,7 +2335,7 @@ static int fake_stat_fd(int fd, S *buf, Real real) {
|
|||||||
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
||||||
if (ret == 0 && deck_map().count(fd)) {
|
if (ret == 0 && deck_map().count(fd)) {
|
||||||
buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFCHR;
|
buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFCHR;
|
||||||
buf->st_rdev = makedev(DECK_HIDRAW_MAJOR, DECK_HIDRAW_MINOR);
|
buf->st_rdev = makedev(DECK_HIDRAW_MAJOR, deck_map()[fd]->touch ? TOUCH_HIDRAW_MINOR : DECK_HIDRAW_MINOR);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
auto controller = controller_map().find(fd);
|
auto controller = controller_map().find(fd);
|
||||||
@@ -2054,6 +2381,7 @@ EXPORT int access(const char *pathname, int mode) {
|
|||||||
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
|
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
||||||
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
|
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
|
||||||
|
if (is_touch_hidraw_path(pathname)) return 0;
|
||||||
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) {
|
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) {
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
@@ -2090,6 +2418,7 @@ EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
|
|||||||
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
|
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
||||||
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
|
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
|
||||||
|
if (is_touch_hidraw_path(pathname)) return 0;
|
||||||
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) {
|
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) {
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
@@ -2211,7 +2540,8 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
|||||||
auto maker = uinput_map().find(fd);
|
auto maker = uinput_map().find(fd);
|
||||||
if (maker != uinput_map().end()) return ioctl_uinput(*maker->second, op, argp);
|
if (maker != uinput_map().end()) return ioctl_uinput(*maker->second, op, argp);
|
||||||
auto deck = deck_map().find(fd);
|
auto deck = deck_map().find(fd);
|
||||||
if (deck != deck_map().end()) return ioctl_deck(*deck->second, op, argp);
|
if (deck != deck_map().end())
|
||||||
|
return deck->second->touch ? ioctl_touch(*deck->second, op, argp) : ioctl_deck(*deck->second, op, argp);
|
||||||
auto controller = controller_map().find(fd);
|
auto controller = controller_map().find(fd);
|
||||||
if (controller == controller_map().end()) {
|
if (controller == controller_map().end()) {
|
||||||
guard.unlock();
|
guard.unlock();
|
||||||
@@ -2537,7 +2867,10 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) {
|
|||||||
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
||||||
auto made = uinput_map().find(fd);
|
auto made = uinput_map().find(fd);
|
||||||
if (made != uinput_map().end()) return write_uinput(*made->second, buf, count);
|
if (made != uinput_map().end()) return write_uinput(*made->second, buf, count);
|
||||||
if (deck_map().count(fd)) return static_cast<ssize_t>(count);
|
if (deck_map().count(fd)) {
|
||||||
|
if (deck_map()[fd]->touch) touch_output(static_cast<const uint8_t *>(buf), count);
|
||||||
|
return static_cast<ssize_t>(count);
|
||||||
|
}
|
||||||
auto controller = controller_map().find(fd);
|
auto controller = controller_map().find(fd);
|
||||||
if (controller != controller_map().end()) {
|
if (controller != controller_map().end()) {
|
||||||
if (fake_fd_is_stale(fd)) {
|
if (fake_fd_is_stale(fd)) {
|
||||||
@@ -2562,7 +2895,11 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
|
|||||||
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
||||||
if (deck_map().count(fd)) {
|
if (deck_map().count(fd)) {
|
||||||
ssize_t total = 0;
|
ssize_t total = 0;
|
||||||
for (int i = 0; i < iovcnt; i++) total += static_cast<ssize_t>(iov[i].iov_len);
|
bool touch = deck_map()[fd]->touch;
|
||||||
|
for (int i = 0; i < iovcnt; i++) {
|
||||||
|
if (touch) touch_output(static_cast<const uint8_t *>(iov[i].iov_base), iov[i].iov_len);
|
||||||
|
total += static_cast<ssize_t>(iov[i].iov_len);
|
||||||
|
}
|
||||||
return total;
|
return total;
|
||||||
}
|
}
|
||||||
auto made = uinput_map().find(fd);
|
auto made = uinput_map().find(fd);
|
||||||
|
|||||||
@@ -11,6 +11,14 @@ import com.droiddeck.launcher.session.GpuClockPin
|
|||||||
* sandboxes are started through (BwrapSpawner).
|
* sandboxes are started through (BwrapSpawner).
|
||||||
*/
|
*/
|
||||||
class App : Application() {
|
class App : Application() {
|
||||||
|
override fun attachBaseContext(base: android.content.Context) =
|
||||||
|
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(base))
|
||||||
|
|
||||||
|
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||||
|
super.onConfigurationChanged(newConfig)
|
||||||
|
com.droiddeck.launcher.core.AppLanguage.systemChanged(newConfig)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
CrashHandler.install(this)
|
CrashHandler.install(this)
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
|||||||
if (compBusy != null) return
|
if (compBusy != null) return
|
||||||
compBusy = label
|
compBusy = label
|
||||||
Thread({
|
Thread({
|
||||||
val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
|
val message = runCatching(work).getOrElse { e -> activity.getString(R.string.main_action_failed, label, e.message ?: e.javaClass.simpleName) }
|
||||||
ui.post {
|
ui.post {
|
||||||
compBusy = null
|
compBusy = null
|
||||||
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
|
||||||
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
|||||||
val cat = runCatching { ComponentsManager.catalog(activity, true) }.getOrNull()
|
val cat = runCatching { ComponentsManager.catalog(activity, true) }.getOrNull()
|
||||||
ui.post {
|
ui.post {
|
||||||
compChecking = false
|
compChecking = false
|
||||||
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(activity, "The Nightlies could not be reached", android.widget.Toast.LENGTH_LONG).show()
|
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(activity, activity.getString(R.string.comp_nightlies_unreachable), android.widget.Toast.LENGTH_LONG).show()
|
||||||
else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
||||||
}
|
}
|
||||||
}, "components-catalog").start()
|
}, "components-catalog").start()
|
||||||
@@ -91,8 +91,8 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
|||||||
Thread({
|
Thread({
|
||||||
val message = runCatching {
|
val message = runCatching {
|
||||||
val pkg = ComponentsManager.download(activity, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } }
|
val pkg = ComponentsManager.download(activity, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } }
|
||||||
"Stored ${pkg.version}"
|
activity.getString(R.string.comp_stored, pkg.version)
|
||||||
}.getOrElse { e -> "Download failed: ${e.message ?: e.javaClass.simpleName}" }
|
}.getOrElse { e -> activity.getString(R.string.comp_download_failed, e.message ?: e.javaClass.simpleName) }
|
||||||
ui.post {
|
ui.post {
|
||||||
compDownloads = compDownloads - item.file
|
compDownloads = compDownloads - item.file
|
||||||
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
|||||||
var deckyChecking by mutableStateOf(false)
|
var deckyChecking by mutableStateOf(false)
|
||||||
var deckyStage by mutableStateOf<String?>(null)
|
var deckyStage by mutableStateOf<String?>(null)
|
||||||
var deckyPercent by mutableIntStateOf(-1)
|
var deckyPercent by mutableIntStateOf(-1)
|
||||||
|
/** True while the stage is the plugin's binary download (DeckyManager.downloadingBinary). */
|
||||||
|
var deckyDownloadingBinary by mutableStateOf(false)
|
||||||
var deckySupervisor by mutableStateOf(false)
|
var deckySupervisor by mutableStateOf(false)
|
||||||
var deckyReleaseRequest = 0
|
var deckyReleaseRequest = 0
|
||||||
|
|
||||||
@@ -41,11 +43,11 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
|||||||
|
|
||||||
fun installDecky(release: DeckyManager.Release) {
|
fun installDecky(release: DeckyManager.Release) {
|
||||||
if (deckyStage != null || SessionState.running) return
|
if (deckyStage != null || SessionState.running) return
|
||||||
deckyStage = "Starting…"; deckyPercent = -1
|
deckyStage = activity.getString(R.string.store_starting); deckyPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
val problem = runCatching {
|
val problem = runCatching {
|
||||||
DeckyManager.install(activity, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
|
DeckyManager.install(activity, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
|
||||||
}.getOrElse { error -> "Decky install failed: ${error.message ?: error.javaClass.simpleName}" }
|
}.getOrElse { error -> activity.getString(R.string.decky_install_failed, error.message ?: error.javaClass.simpleName) }
|
||||||
ui.post {
|
ui.post {
|
||||||
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(activity)
|
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(activity)
|
||||||
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||||
@@ -55,16 +57,17 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
|||||||
|
|
||||||
fun importPluginZip(archive: File) {
|
fun importPluginZip(archive: File) {
|
||||||
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
|
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
|
||||||
deckyStage = "Starting plugin import…"; deckyPercent = -1
|
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
val problem = runCatching {
|
val problem = runCatching {
|
||||||
DeckyManager.installPluginZip(activity, archive) { label, value ->
|
DeckyManager.installPluginZip(activity, archive) { label, value ->
|
||||||
ui.post { deckyStage = label; deckyPercent = value }
|
val binary = DeckyManager.downloadingBinary
|
||||||
|
ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary }
|
||||||
}
|
}
|
||||||
}.getOrElse { error -> "Plugin import failed: ${error.message ?: error.javaClass.simpleName}" }
|
}.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) }
|
||||||
ui.post {
|
ui.post {
|
||||||
deckyStage = null; deckyPercent = -1
|
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
|
||||||
val message = problem ?: "Plugin installed. Restart Steam to load it."
|
val message = problem ?: activity.getString(R.string.decky_plugin_installed)
|
||||||
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
|
||||||
}
|
}
|
||||||
}, "import-decky-plugin").start()
|
}, "import-decky-plugin").start()
|
||||||
|
|||||||
@@ -37,7 +37,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
|
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
|
||||||
var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
||||||
var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
||||||
var releaseStatus by mutableStateOf("Not checked yet - tap refresh to look for new drivers")
|
// Empty until the first refresh: the activity has no context yet while its fields are made.
|
||||||
|
var releaseStatus by mutableStateOf("")
|
||||||
var releaseChecking by mutableStateOf(false)
|
var releaseChecking by mutableStateOf(false)
|
||||||
var canRestoreBundled by mutableStateOf(false)
|
var canRestoreBundled by mutableStateOf(false)
|
||||||
/** Asset name -> download percent, while it downloads. */
|
/** Asset name -> download percent, while it downloads. */
|
||||||
@@ -57,10 +58,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
private var autoCheckedThisProcess = false
|
private var autoCheckedThisProcess = false
|
||||||
|
|
||||||
fun state() = GpuDriversState(
|
fun state() = GpuDriversState(
|
||||||
gpuName = gpu.name, gpuFamily = gpu.family.label, soc = gpu.soc, supportText = gpu.supportText,
|
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity),
|
||||||
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
|
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
|
||||||
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
|
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
|
||||||
autoStatus = autoStatus, releaseStatus = releaseStatus, checking = releaseChecking,
|
autoStatus = autoStatus, releaseStatus = releaseStatus.ifEmpty { activity.getString(R.string.drivers_not_checked) }, checking = releaseChecking,
|
||||||
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
|
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
|
||||||
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
|
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
|
||||||
activeBundle = activeBundle,
|
activeBundle = activeBundle,
|
||||||
@@ -73,10 +74,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
||||||
val bundles = DriverBundle.all(activity)
|
val bundles = DriverBundle.all(activity)
|
||||||
fun bundleRow(id: String, linux: Boolean) = bundles.firstOrNull { (if (linux) it.linuxId else it.androidId) == id }?.let {
|
fun bundleRow(id: String, linux: Boolean) = bundles.firstOrNull { (if (linux) it.linuxId else it.androidId) == id }?.let {
|
||||||
DriverRow(id, it.label, "Android + Linux: sets the ${if (linux) "display" else "runtime"} driver with it", true, DriverRow.BUNDLE)
|
DriverRow(id, it.label, activity.getString(if (linux) R.string.drivers_bundle_sets_display else R.string.drivers_bundle_sets_runtime), true, DriverRow.BUNDLE)
|
||||||
}
|
}
|
||||||
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
|
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
|
||||||
if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
|
if (id.isEmpty()) DriverRow("", activity.getString(R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
|
||||||
else bundleRow(id, linux = true) ?: DriverRow(
|
else bundleRow(id, linux = true) ?: DriverRow(
|
||||||
id, lm.getDriverName(id),
|
id, lm.getDriverName(id),
|
||||||
listOfNotNull(
|
listOfNotNull(
|
||||||
@@ -92,8 +93,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
val auto = td.autoId()
|
val auto = td.autoId()
|
||||||
androidRows = buildList {
|
androidRows = buildList {
|
||||||
add(DriverRow(
|
add(DriverRow(
|
||||||
TurnipDriver.AUTO, "Auto - picked by GPU",
|
TurnipDriver.AUTO, activity.getString(R.string.gpu_auto_by_gpu),
|
||||||
if (auto == "system") "system Vulkan: no bundled build for this GPU" else "${td.displayName(auto)} (bundled)",
|
if (auto == "system") activity.getString(R.string.drivers_system_vulkan) else activity.getString(R.string.drivers_bundled, td.displayName(auto)),
|
||||||
false,
|
false,
|
||||||
))
|
))
|
||||||
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
|
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
|
||||||
@@ -109,7 +110,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
/** One line for the settings row that opens this: "Auto · WinNative · Balanced". */
|
/** One line for the settings row that opens this: "Auto · WinNative · Balanced". */
|
||||||
fun summary(): String {
|
fun summary(): String {
|
||||||
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
|
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
|
||||||
return (if (mode == SessionPrefs.GPU_DRIVERS_AUTO) "Auto" else "Manual") + (active?.let { " · $it" } ?: "")
|
val label = activity.getString(if (mode == SessionPrefs.GPU_DRIVERS_AUTO) R.string.common_auto else R.string.drivers_manual)
|
||||||
|
return active?.let { activity.getString(R.string.drivers_summary, label, it) } ?: label
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The pairs the last check found, with what is installed and in use; this GPU's first. */
|
/** The pairs the last check found, with what is installed and in use; this GPU's first. */
|
||||||
@@ -125,7 +127,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
val mb = p.assets.sumOf { it.size } / 1_048_576.0
|
val mb = p.assets.sumOf { it.size } / 1_048_576.0
|
||||||
PairRow(
|
PairRow(
|
||||||
key = p.key, name = p.name, version = p.version,
|
key = p.key, name = p.name, version = p.version,
|
||||||
detail = if (!p.complete) "Only one half is published right now" else "%.0f MB for both".format(mb),
|
detail = if (!p.complete) activity.getString(R.string.drivers_half_published) else activity.getString(R.string.drivers_pair_size, mb),
|
||||||
recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete,
|
recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete,
|
||||||
installed = displayId != null && linuxId != null,
|
installed = displayId != null && linuxId != null,
|
||||||
active = displayId != null && linuxId != null &&
|
active = displayId != null && linuxId != null &&
|
||||||
@@ -153,11 +155,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
if (!force && autoCheckedThisProcess) return
|
if (!force && autoCheckedThisProcess) return
|
||||||
autoCheckedThisProcess = true
|
autoCheckedThisProcess = true
|
||||||
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
|
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
|
||||||
autoStatus = "No drivers to set: ${gpu.supportText.lowercase()}"
|
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity).lowercase())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
releaseChecking = true
|
releaseChecking = true
|
||||||
autoStatus = "Checking for the latest drivers…"
|
autoStatus = activity.getString(R.string.drivers_checking_latest)
|
||||||
Thread({
|
Thread({
|
||||||
val cached = TurnipReleases.cached(activity)
|
val cached = TurnipReleases.cached(activity)
|
||||||
val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > 24 * 3_600_000L ||
|
val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > 24 * 3_600_000L ||
|
||||||
@@ -172,9 +174,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
val pair = pairs.firstOrNull { it.key == key }
|
val pair = pairs.firstOrNull { it.key == key }
|
||||||
val row = pairRows.firstOrNull { it.key == key }
|
val row = pairRows.firstOrNull { it.key == key }
|
||||||
when {
|
when {
|
||||||
row?.active == true -> autoStatus = "Up to date" + (problem?.let { " (couldn't check: $it)" } ?: "")
|
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
|
||||||
|
?: activity.getString(R.string.upd_current_status)
|
||||||
pair == null || !pair.complete ->
|
pair == null || !pair.complete ->
|
||||||
autoStatus = problem?.let { "Couldn't check: $it" } ?: "The recommended drivers aren't published right now"
|
autoStatus = problem?.let { activity.getString(R.string.upd_couldnt_check, it) } ?: activity.getString(R.string.drivers_recommended_unpublished)
|
||||||
else -> installPair(pair, auto = true)
|
else -> installPair(pair, auto = true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -197,7 +200,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
if (!pair.complete) return
|
if (!pair.complete) return
|
||||||
pairBusy = pair.key
|
pairBusy = pair.key
|
||||||
pairPercent = 0
|
pairPercent = 0
|
||||||
if (auto) autoStatus = "Downloading ${pair.name} ${pair.version}…"
|
if (auto) autoStatus = activity.getString(R.string.drivers_downloading_pair, pair.name, pair.version)
|
||||||
Thread({
|
Thread({
|
||||||
val lm = LinuxVulkanDriverManager(activity)
|
val lm = LinuxVulkanDriverManager(activity)
|
||||||
val td = TurnipDriver(activity)
|
val td = TurnipDriver(activity)
|
||||||
@@ -217,7 +220,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
val displayChanged = SessionPrefs.androidDriver(activity) != displayId
|
val displayChanged = SessionPrefs.androidDriver(activity) != displayId
|
||||||
SessionPrefs.setAndroidDriver(activity, displayId)
|
SessionPrefs.setAndroidDriver(activity, displayId)
|
||||||
SessionPrefs.setLinuxDriver(activity, linuxId)
|
SessionPrefs.setLinuxDriver(activity, linuxId)
|
||||||
val restart = if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
|
val restart = displayChanged && CompositorHost.isStarted
|
||||||
if (auto) {
|
if (auto) {
|
||||||
val previous = SessionPrefs.gpuAutoInstalled(activity)
|
val previous = SessionPrefs.gpuAutoInstalled(activity)
|
||||||
for (id in previous - setOf(displayId, linuxId)) {
|
for (id in previous - setOf(displayId, linuxId)) {
|
||||||
@@ -230,14 +233,18 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
TurnipReleases.forget(activity, id)
|
TurnipReleases.forget(activity, id)
|
||||||
}
|
}
|
||||||
SessionPrefs.setGpuAutoInstalled(activity, setOf(displayId, linuxId))
|
SessionPrefs.setGpuAutoInstalled(activity, setOf(displayId, linuxId))
|
||||||
autoStatus = (if (downloaded) "Updated to" else "Switched to") + " ${pair.name} ${pair.version}.$restart"
|
autoStatus = activity.getString(
|
||||||
|
if (downloaded) { if (restart) R.string.drivers_updated_to_restart else R.string.drivers_updated_to }
|
||||||
|
else { if (restart) R.string.drivers_switched_to_restart else R.string.drivers_switched_to },
|
||||||
|
pair.name, pair.version,
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
android.widget.Toast.makeText(activity, "Using ${pair.name} ${pair.version}.$restart", android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(activity, activity.getString(if (restart) R.string.drivers_using_restart else R.string.drivers_using, pair.name, pair.version), android.widget.Toast.LENGTH_LONG).show()
|
||||||
}
|
}
|
||||||
}.onFailure { e ->
|
}.onFailure { e ->
|
||||||
Log.w(TAG, "driver pair ${pair.key}", e)
|
Log.w(TAG, "driver pair ${pair.key}", e)
|
||||||
val why = if (e is IllegalArgumentException) e.message else "Download failed: ${e.message}"
|
val why = if (e is IllegalArgumentException) e.message else activity.getString(R.string.comp_download_failed, e.message)
|
||||||
if (auto) autoStatus = why ?: "Download failed"
|
if (auto) autoStatus = why ?: activity.getString(R.string.user_apps_download_failed)
|
||||||
else android.widget.Toast.makeText(activity, why, android.widget.Toast.LENGTH_LONG).show()
|
else android.widget.Toast.makeText(activity, why, android.widget.Toast.LENGTH_LONG).show()
|
||||||
}
|
}
|
||||||
refreshDrivers()
|
refreshDrivers()
|
||||||
@@ -298,7 +305,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
try {
|
try {
|
||||||
LinuxVulkanDriverManager(activity).installDriver(uri, name)
|
LinuxVulkanDriverManager(activity).installDriver(uri, name)
|
||||||
} catch (runtime: IllegalArgumentException) {
|
} catch (runtime: IllegalArgumentException) {
|
||||||
throw IllegalArgumentException("Not a driver zip: neither an AdrenoTools driver, a -Linux Turnip nor an Android + Linux bundle")
|
throw IllegalArgumentException(activity.getString(R.string.drivers_not_a_driver))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -307,10 +314,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
e.message
|
e.message
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "driver import", e)
|
Log.w(TAG, "driver import", e)
|
||||||
"Import failed: ${e.message}"
|
activity.getString(R.string.drivers_import_failed, e.message)
|
||||||
}
|
}
|
||||||
ui.post {
|
ui.post {
|
||||||
val done = bundle?.let { useBundle(it) } ?: "Imported ${name ?: "driver"}"
|
val done = bundle?.let { useBundle(it) }
|
||||||
|
?: name?.let { activity.getString(R.string.comp_imported, it) } ?: activity.getString(R.string.drivers_imported_unnamed)
|
||||||
android.widget.Toast.makeText(
|
android.widget.Toast.makeText(
|
||||||
activity, problem ?: done,
|
activity, problem ?: done,
|
||||||
if (problem != null || bundle != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
|
if (problem != null || bundle != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
|
||||||
@@ -340,8 +348,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId
|
val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId
|
||||||
DriverBundle.select(activity, bundle)
|
DriverBundle.select(activity, bundle)
|
||||||
if (mode == SessionPrefs.GPU_DRIVERS_AUTO) setMode(false)
|
if (mode == SessionPrefs.GPU_DRIVERS_AUTO) setMode(false)
|
||||||
return "Using ${bundle.label} as both the runtime and display driver." +
|
return activity.getString(
|
||||||
if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
|
if (displayChanged && CompositorHost.isStarted) R.string.drivers_using_bundle_restart else R.string.drivers_using_bundle,
|
||||||
|
bundle.label,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -354,7 +364,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
if (bundle != null) {
|
if (bundle != null) {
|
||||||
DriverBundle.remove(activity, bundle)
|
DriverBundle.remove(activity, bundle)
|
||||||
TurnipReleases.forget(activity, bundle.id)
|
TurnipReleases.forget(activity, bundle.id)
|
||||||
android.widget.Toast.makeText(activity, "Deleted ${bundle.label} (both drivers)", android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(activity, activity.getString(R.string.drivers_deleted_bundle, bundle.label), android.widget.Toast.LENGTH_SHORT).show()
|
||||||
refreshDrivers()
|
refreshDrivers()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -367,7 +377,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
if (SessionPrefs.androidDriver(activity) == id) SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
|
if (SessionPrefs.androidDriver(activity) == id) SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
|
||||||
}
|
}
|
||||||
TurnipReleases.forget(activity, id)
|
TurnipReleases.forget(activity, id)
|
||||||
android.widget.Toast.makeText(activity, "Deleted ${id}", android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(activity, activity.getString(R.string.drivers_deleted, id), android.widget.Toast.LENGTH_SHORT).show()
|
||||||
refreshDrivers()
|
refreshDrivers()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -378,26 +388,28 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
.filter { it.bundle || it.linux == linux }
|
.filter { it.bundle || it.linux == linux }
|
||||||
.filter { a -> installedIdOf(a) == null }
|
.filter { a -> installedIdOf(a) == null }
|
||||||
.map { a ->
|
.map { a ->
|
||||||
val mb = "%.1f MB".format(a.size / 1_048_576.0)
|
val mb = activity.getString(R.string.common_size_mb, a.size / 1_048_576.0)
|
||||||
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
|
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
|
||||||
}
|
}
|
||||||
linuxDownloads = rows(linux = true)
|
linuxDownloads = rows(linux = true)
|
||||||
androidDownloads = rows(linux = false)
|
androidDownloads = rows(linux = false)
|
||||||
if (!releaseChecking) releaseStatus = when (check) {
|
if (!releaseChecking) releaseStatus = when (check) {
|
||||||
null -> "Not checked yet - tap refresh to look for new drivers"
|
null -> activity.getString(R.string.drivers_not_checked)
|
||||||
else -> "Latest: " + check.latest.joinToString(" · ") { "${it.first} ${it.second}" } +
|
else -> {
|
||||||
(if (check.failed.isEmpty()) "" else " · ${check.failed.joinToString()} unreachable") +
|
val latest = check.latest.joinToString(" · ") { "${it.first} ${it.second}" }
|
||||||
" · checked ${ago(check.checkedAt)}"
|
if (check.failed.isEmpty()) activity.getString(R.string.drivers_release_status, latest, ago(check.checkedAt))
|
||||||
|
else activity.getString(R.string.drivers_release_status_failed, latest, check.failed.joinToString(), ago(check.checkedAt))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun ago(t: Long): String {
|
private fun ago(t: Long): String {
|
||||||
val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0)
|
val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0)
|
||||||
return when {
|
return when {
|
||||||
m < 1 -> "just now"
|
m < 1 -> activity.getString(R.string.upd_just_now)
|
||||||
m < 60 -> "$m min ago"
|
m < 60 -> activity.resources.getQuantityString(R.plurals.drivers_ago_minutes, m.toInt(), m)
|
||||||
m < 48 * 60 -> "${m / 60} h ago"
|
m < 48 * 60 -> activity.resources.getQuantityString(R.plurals.drivers_ago_hours, (m / 60).toInt(), m / 60)
|
||||||
else -> "${m / (24 * 60)} days ago"
|
else -> activity.resources.getQuantityString(R.plurals.drivers_ago_days, (m / (24 * 60)).toInt(), m / (24 * 60))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -405,16 +417,16 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
fun checkLatestTurnip() {
|
fun checkLatestTurnip() {
|
||||||
if (releaseChecking) return
|
if (releaseChecking) return
|
||||||
releaseChecking = true
|
releaseChecking = true
|
||||||
releaseStatus = "Checking Banners-Turnip, WinNative and DroidDeck…"
|
releaseStatus = activity.getString(R.string.drivers_checking_sources)
|
||||||
Thread({
|
Thread({
|
||||||
val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) {
|
val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) {
|
||||||
Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
|
Log.w(TAG, "latest Turnip check", e); e.message ?: activity.getString(R.string.drivers_check_failed)
|
||||||
}
|
}
|
||||||
ui.post {
|
ui.post {
|
||||||
releaseChecking = false
|
releaseChecking = false
|
||||||
refreshReleaseRows()
|
refreshReleaseRows()
|
||||||
refreshPairs()
|
refreshPairs()
|
||||||
if (problem != null) releaseStatus = "Couldn't check: $problem"
|
if (problem != null) releaseStatus = activity.getString(R.string.upd_couldnt_check, problem)
|
||||||
}
|
}
|
||||||
}, "turnip-release-check").start()
|
}, "turnip-release-check").start()
|
||||||
}
|
}
|
||||||
@@ -433,13 +445,16 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
e.message
|
e.message
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "release driver download", e)
|
Log.w(TAG, "release driver download", e)
|
||||||
"Download failed: ${e.message}"
|
activity.getString(R.string.comp_download_failed, e.message)
|
||||||
}
|
}
|
||||||
ui.post {
|
ui.post {
|
||||||
releaseProgress.remove(assetName)
|
releaseProgress.remove(assetName)
|
||||||
val pick = if (asset.bundle) "pick it in either list to set both drivers" else "pick it in the menu"
|
val installed = activity.getString(
|
||||||
|
if (asset.bundle) R.string.drivers_installed_pick_either else R.string.drivers_installed_pick,
|
||||||
|
asset.name.removeSuffix(".zip"),
|
||||||
|
)
|
||||||
android.widget.Toast.makeText(
|
android.widget.Toast.makeText(
|
||||||
activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - $pick",
|
activity, problem ?: installed,
|
||||||
android.widget.Toast.LENGTH_LONG,
|
android.widget.Toast.LENGTH_LONG,
|
||||||
).show()
|
).show()
|
||||||
refreshDrivers()
|
refreshDrivers()
|
||||||
|
|||||||
@@ -7,6 +7,11 @@ import com.droiddeck.launcher.session.SessionService
|
|||||||
|
|
||||||
/** Receives the system Home launch and routes it without consuming KEYCODE_HOME. */
|
/** Receives the system Home launch and routes it without consuming KEYCODE_HOME. */
|
||||||
class HomeActivity : Activity() {
|
class HomeActivity : Activity() {
|
||||||
|
override fun attachBaseContext(newBase: android.content.Context) {
|
||||||
|
super.attachBaseContext(newBase)
|
||||||
|
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
routeHome()
|
routeHome()
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
|||||||
import com.droiddeck.launcher.runtime.DeckyManager
|
import com.droiddeck.launcher.runtime.DeckyManager
|
||||||
import com.droiddeck.launcher.session.SessionService
|
import com.droiddeck.launcher.session.SessionService
|
||||||
import com.droiddeck.launcher.ui.PackageRow
|
import com.droiddeck.launcher.ui.PackageRow
|
||||||
|
import com.droiddeck.launcher.ui.exposeTestTags
|
||||||
import com.droiddeck.launcher.session.OfflineMode
|
import com.droiddeck.launcher.session.OfflineMode
|
||||||
import com.droiddeck.launcher.session.ProtonExtras
|
import com.droiddeck.launcher.session.ProtonExtras
|
||||||
import com.droiddeck.launcher.session.ComponentsManager
|
import com.droiddeck.launcher.session.ComponentsManager
|
||||||
@@ -65,6 +66,9 @@ import com.droiddeck.launcher.ui.FrontEndState
|
|||||||
import com.droiddeck.launcher.ui.FrontEndActions
|
import com.droiddeck.launcher.ui.FrontEndActions
|
||||||
import com.droiddeck.launcher.frontend.CoverArt
|
import com.droiddeck.launcher.frontend.CoverArt
|
||||||
import com.droiddeck.launcher.frontend.Library
|
import com.droiddeck.launcher.frontend.Library
|
||||||
|
import com.droiddeck.launcher.frontend.GameFiles
|
||||||
|
import com.droiddeck.launcher.frontend.GameFileSync
|
||||||
|
import com.droiddeck.launcher.frontend.GameLaunchIntent
|
||||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||||
import com.droiddeck.launcher.ui.RomsDialog
|
import com.droiddeck.launcher.ui.RomsDialog
|
||||||
import com.droiddeck.launcher.files.InAppFilePicker
|
import com.droiddeck.launcher.files.InAppFilePicker
|
||||||
@@ -81,6 +85,11 @@ import com.droiddeck.launcher.input.SecondScreenDisplays
|
|||||||
* the store, downloads, settings - is the client's own job once [SessionActivity] has it on screen.
|
* the store, downloads, settings - is the client's own job once [SessionActivity] has it on screen.
|
||||||
*/
|
*/
|
||||||
class MainActivity : ComponentActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
|
override fun attachBaseContext(newBase: android.content.Context) {
|
||||||
|
super.attachBaseContext(newBase)
|
||||||
|
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||||
|
}
|
||||||
|
|
||||||
private val ui = Handler(Looper.getMainLooper())
|
private val ui = Handler(Looper.getMainLooper())
|
||||||
private val drivers = DriverMenus(this, ui)
|
private val drivers = DriverMenus(this, ui)
|
||||||
private val components = ComponentsMenu(this, ui)
|
private val components = ComponentsMenu(this, ui)
|
||||||
@@ -104,7 +113,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var stage by mutableStateOf("")
|
private var stage by mutableStateOf("")
|
||||||
private var percent by mutableIntStateOf(-1)
|
private var percent by mutableIntStateOf(-1)
|
||||||
private var failed by mutableStateOf(false)
|
private var failed by mutableStateOf(false)
|
||||||
private var frameGenLabel by mutableStateOf("Off")
|
private var frameGenLabel by mutableStateOf("")
|
||||||
private var lossless by mutableStateOf(Lossless.State.NONE)
|
private var lossless by mutableStateOf(Lossless.State.NONE)
|
||||||
private var showRemove by mutableStateOf(false)
|
private var showRemove by mutableStateOf(false)
|
||||||
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
||||||
@@ -151,8 +160,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
||||||
private var showPhantomGate by mutableStateOf(false)
|
private var showPhantomGate by mutableStateOf(false)
|
||||||
private var directAudio by mutableStateOf(false)
|
private var directAudio by mutableStateOf(false)
|
||||||
private var clientDirectAudio by mutableStateOf(false)
|
|
||||||
private var forceFullscreen by mutableStateOf(false)
|
|
||||||
private var stretch16x9 by mutableStateOf(false)
|
private var stretch16x9 by mutableStateOf(false)
|
||||||
private var launcherFullscreen by mutableStateOf(true)
|
private var launcherFullscreen by mutableStateOf(true)
|
||||||
private var animationsEnabled by mutableStateOf(true)
|
private var animationsEnabled by mutableStateOf(true)
|
||||||
@@ -168,6 +175,16 @@ class MainActivity : ComponentActivity() {
|
|||||||
refreshWifiDiscovery()
|
refreshWifiDiscovery()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private val mediaRefresh = Runnable {
|
||||||
|
refresh()
|
||||||
|
refreshAddedGames()
|
||||||
|
}
|
||||||
|
private val mediaReceiver = object : android.content.BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: android.content.Context?, intent: Intent?) {
|
||||||
|
ui.removeCallbacks(mediaRefresh)
|
||||||
|
ui.postDelayed(mediaRefresh, MEDIA_SETTLE_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
private val wifiLocationPermission = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
private val wifiLocationPermission = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||||
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
|
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
|
||||||
refreshWifiDiscovery()
|
refreshWifiDiscovery()
|
||||||
@@ -251,29 +268,32 @@ class MainActivity : ComponentActivity() {
|
|||||||
/** Import a save zip into [game]: pick it in the app's file picker, then back up and unzip off the main thread. */
|
/** Import a save zip into [game]: pick it in the app's file picker, then back up and unzip off the main thread. */
|
||||||
private fun importSaves(name: String, game: () -> GameSaves.Game) {
|
private fun importSaves(name: String, game: () -> GameSaves.Game) {
|
||||||
if (SessionState.running) {
|
if (SessionState.running) {
|
||||||
android.widget.Toast.makeText(this, "Close the Steam session first, so the game can't save over the import", android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, R.string.main_saves_close_session, android.widget.Toast.LENGTH_LONG).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
onSavePicked = { zip ->
|
onSavePicked = { zip ->
|
||||||
saveAction("Importing into $name") {
|
saveAction(getString(R.string.main_saves_importing, name)) {
|
||||||
val (written, backup) = GameSaves.import(game(), zip)
|
val (written, backup) = GameSaves.import(this, game(), zip)
|
||||||
val kind = GameSaves.layoutOf(zip)?.label ?: "zip"
|
val kind = GameSaves.layoutOf(zip)?.label(this) ?: getString(R.string.saves_zip)
|
||||||
"Imported $written files from the $kind into $name" + (backup?.let { ". Old saves backed up to Download/DroidDeck/Saves/backups" } ?: "")
|
resources.getQuantityString(
|
||||||
|
if (backup != null) R.plurals.main_saves_imported_backup else R.plurals.main_saves_imported,
|
||||||
|
written, written, kind, name,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), "Choose a save zip for $name", GameSaves.savesDir().parentFile?.parentFile?.path))
|
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_saves_pick_zip, name), GameSaves.savesDir().parentFile?.parentFile?.path))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Export [game]'s saves in [layout] to a folder picked in the app's file picker. */
|
/** Export [game]'s saves in [layout] to a folder picked in the app's file picker. */
|
||||||
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
|
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
|
||||||
onSavePicked = { dir ->
|
onSavePicked = { dir ->
|
||||||
saveAction("Exporting $name") {
|
saveAction(getString(R.string.main_saves_exporting, name)) {
|
||||||
val (zip, count) = GameSaves.export(game(), layout, dir)
|
val (zip, count) = GameSaves.export(this, game(), layout, dir)
|
||||||
"Exported $count files as a ${layout.label}: ${zip.path.removePrefix("/storage/emulated/0/")}"
|
resources.getQuantityString(R.plurals.main_saves_exported, count, count, layout.label(this), zip.path.removePrefix("/storage/emulated/0/"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
GameSaves.savesDir().mkdirs()
|
GameSaves.savesDir().mkdirs()
|
||||||
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, "Choose where to save $name (${layout.label})", GameSaves.savesDir().path))
|
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_saves_pick_folder, name, layout.label(this)), GameSaves.savesDir().path))
|
||||||
}
|
}
|
||||||
private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
|
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
|
||||||
@@ -308,6 +328,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var settingsMode by mutableStateOf<String?>(null)
|
private var settingsMode by mutableStateOf<String?>(null)
|
||||||
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
|
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
|
||||||
private var fexPreset by mutableStateOf("")
|
private var fexPreset by mutableStateOf("")
|
||||||
|
private var forceSsbs by mutableStateOf(false)
|
||||||
private var steamChannel by mutableStateOf("steamdeck_publicbeta")
|
private var steamChannel by mutableStateOf("steamdeck_publicbeta")
|
||||||
private var runSteamAtStartup by mutableStateOf(false)
|
private var runSteamAtStartup by mutableStateOf(false)
|
||||||
private var theme by mutableStateOf("graphite")
|
private var theme by mutableStateOf("graphite")
|
||||||
@@ -319,12 +340,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var hdrReason by mutableStateOf<String?>(null)
|
private var hdrReason by mutableStateOf<String?>(null)
|
||||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||||
|
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||||
private var backActionsInverted by mutableStateOf(false)
|
private var backActionsInverted by mutableStateOf(false)
|
||||||
private var renderer by mutableStateOf("vulkan")
|
private var renderer by mutableStateOf("vulkan")
|
||||||
private var gameStorage by mutableStateOf("")
|
private var gameStorage by mutableStateOf("")
|
||||||
private var storageDiagnostics by mutableStateOf(false)
|
private var storageDiagnostics by mutableStateOf(false)
|
||||||
private var storageOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
|
private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList())
|
||||||
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
|
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
|
||||||
}
|
}
|
||||||
@@ -333,6 +355,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
|
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
|
||||||
private var runningLabel by mutableStateOf<String?>(null)
|
private var runningLabel by mutableStateOf<String?>(null)
|
||||||
private var logsEnabled by mutableStateOf(true)
|
private var logsEnabled by mutableStateOf(true)
|
||||||
|
private var agentCommands by mutableStateOf(false)
|
||||||
private var showRoms by mutableStateOf(false)
|
private var showRoms by mutableStateOf(false)
|
||||||
private var homeAppSelected by mutableStateOf(false)
|
private var homeAppSelected by mutableStateOf(false)
|
||||||
private var homeScreenEnabled by mutableStateOf(false)
|
private var homeScreenEnabled by mutableStateOf(false)
|
||||||
@@ -355,15 +378,15 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (intent?.component?.className == SessionActivity::class.java.name) {
|
if (intent?.component?.className == SessionActivity::class.java.name) {
|
||||||
when {
|
when {
|
||||||
busy || LinuxRuntimeInstaller.isBusy() -> {
|
busy || LinuxRuntimeInstaller.isBusy() -> {
|
||||||
android.widget.Toast.makeText(this, "Wait for the runtime operation to finish", android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
protons.protonBusyId != null || ProtonExtras.installInProgress -> {
|
protons.protonBusyId != null || ProtonExtras.installInProgress -> {
|
||||||
android.widget.Toast.makeText(this, "Wait for the compatibility tool install to finish", android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.main_wait_proton_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
pkgStage != null -> {
|
pkgStage != null -> {
|
||||||
android.widget.Toast.makeText(this, "Wait for the desktop app install to finish", android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -399,10 +422,15 @@ class MainActivity : ComponentActivity() {
|
|||||||
private fun pickGameExport(game: Library.SteamGame?) {
|
private fun pickGameExport(game: Library.SteamGame?) {
|
||||||
onSavePicked = { folder ->
|
onSavePicked = { folder ->
|
||||||
saveAction(getString(R.string.game_frontend_files)) {
|
saveAction(getString(R.string.game_frontend_files)) {
|
||||||
if (game != null) com.droiddeck.launcher.frontend.GameFiles.export(folder, game)
|
val saved = if (game != null) GameFiles.export(this, folder, game)
|
||||||
else com.droiddeck.launcher.frontend.GameFileSync.enable(this, folder)
|
else {
|
||||||
ui.post { gameSyncFolder = com.droiddeck.launcher.frontend.GameFileSync.folder(this) }
|
GameFileSync.enable(this, folder)
|
||||||
getString(R.string.game_file_exported, folder.path)
|
folder
|
||||||
|
}
|
||||||
|
ui.post {
|
||||||
|
gameSyncFolder = GameFileSync.folder(this)
|
||||||
|
}
|
||||||
|
getString(R.string.game_file_exported, saved.path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.game_file_folder), gameSyncFolder))
|
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.game_file_folder), gameSyncFolder))
|
||||||
@@ -416,10 +444,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
shortcutLibraryScanning = true
|
shortcutLibraryScanning = true
|
||||||
} else shortcutLibraryScanning = false
|
} else shortcutLibraryScanning = false
|
||||||
pendingGameLink = null
|
pendingGameLink = null
|
||||||
if (request.action == Intent.ACTION_VIEW) {
|
if (GameLaunchIntent.accepts(request.action)) {
|
||||||
val copy = Intent(request)
|
val copy = Intent(request)
|
||||||
Thread({
|
Thread({
|
||||||
val id = com.droiddeck.launcher.frontend.GameFiles.readIntent(this, copy)
|
val id = GameLaunchIntent.read(this, copy)
|
||||||
ui.post {
|
ui.post {
|
||||||
if (intent === request && !isDestroyed) {
|
if (intent === request && !isDestroyed) {
|
||||||
pendingGameLink = id
|
pendingGameLink = id
|
||||||
@@ -432,9 +460,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun launchGame(game: Library.SteamGame): Boolean {
|
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
|
||||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||||
android.widget.Toast.makeText(this, "Wait for the install to finish before launching a game", android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if (SessionState.running) {
|
if (SessionState.running) {
|
||||||
@@ -447,10 +475,12 @@ class MainActivity : ComponentActivity() {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
|
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
|
||||||
|
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return startSession(Intent(this, SessionActivity::class.java)
|
return startSession(Intent(this, SessionActivity::class.java)
|
||||||
|
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
|
||||||
.putExtra(SessionService.EXTRA_STEAM_URL,
|
.putExtra(SessionService.EXTRA_STEAM_URL,
|
||||||
com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(game.gameIdString)), steamSession = true)
|
com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(game.gameIdString)), steamSession = true)
|
||||||
}
|
}
|
||||||
@@ -462,10 +492,14 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (game == null) {
|
if (game == null) {
|
||||||
pendingGameLink = null
|
pendingGameLink = null
|
||||||
intent.data = null
|
intent.data = null
|
||||||
|
intent.action = Intent.ACTION_MAIN
|
||||||
|
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
||||||
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
|
||||||
} else if (launchGame(game)) {
|
} else if (launchGame(game, returnHome = true)) {
|
||||||
pendingGameLink = null
|
pendingGameLink = null
|
||||||
intent.data = null
|
intent.data = null
|
||||||
|
intent.action = Intent.ACTION_MAIN
|
||||||
|
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -477,10 +511,11 @@ class MainActivity : ComponentActivity() {
|
|||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
readGameIntent(intent)
|
readGameIntent(intent)
|
||||||
gameSyncFolder = com.droiddeck.launcher.frontend.GameFileSync.folder(this)
|
gameSyncFolder = GameFileSync.folder(this)
|
||||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||||
refreshPhantomStatus()
|
refreshPhantomStatus()
|
||||||
theme = SessionPrefs.theme(this)
|
theme = SessionPrefs.theme(this)
|
||||||
|
frameGenLabel = getString(R.string.frame_gen_off)
|
||||||
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
|
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
|
||||||
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
|
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
|
||||||
steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
|
steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
|
||||||
@@ -492,7 +527,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
updates.start()
|
updates.start()
|
||||||
setContent {
|
setContent {
|
||||||
DroidDeckTheme(theme, appScale = appScale) {
|
DroidDeckTheme(theme, appScale = appScale) {
|
||||||
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
|
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) {
|
||||||
val sm = settingsMode
|
val sm = settingsMode
|
||||||
val page: (@Composable () -> Unit)? = when {
|
val page: (@Composable () -> Unit)? = when {
|
||||||
sm != null -> { { ModeSettingsHost(sm) } }
|
sm != null -> { { ModeSettingsHost(sm) } }
|
||||||
@@ -512,12 +547,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
busy = busy, stage = stage, percent = percent,
|
busy = busy, stage = stage, percent = percent,
|
||||||
desktopInstalled = desktopInstalled,
|
desktopInstalled = desktopInstalled,
|
||||||
offlineAccount = offlineAccount, offline = offline,
|
offlineAccount = offlineAccount, offline = offline,
|
||||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, agentCommands = agentCommands,
|
||||||
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
||||||
frameGen = FrameGen.mode(this),
|
frameGen = FrameGen.mode(this),
|
||||||
lossless = lossless,
|
lossless = lossless,
|
||||||
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
|
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
|
||||||
theme = theme,
|
theme = theme,
|
||||||
|
language = com.droiddeck.launcher.core.AppLanguage.chosen(this),
|
||||||
appScale = appScale,
|
appScale = appScale,
|
||||||
isHomeApp = homeAppSelected,
|
isHomeApp = homeAppSelected,
|
||||||
homeScreenEnabled = homeScreenEnabled,
|
homeScreenEnabled = homeScreenEnabled,
|
||||||
@@ -556,7 +592,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
onSyncGameFiles = { pickGameExport(null) },
|
onSyncGameFiles = { pickGameExport(null) },
|
||||||
onStopGameFileSync = {
|
onStopGameFileSync = {
|
||||||
Thread({
|
Thread({
|
||||||
com.droiddeck.launcher.frontend.GameFileSync.disable(this)
|
GameFileSync.disable(this)
|
||||||
ui.post { gameSyncFolder = null }
|
ui.post { gameSyncFolder = null }
|
||||||
}, "game-file-stop-sync").start()
|
}, "game-file-stop-sync").start()
|
||||||
},
|
},
|
||||||
@@ -623,21 +659,22 @@ class MainActivity : ComponentActivity() {
|
|||||||
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
||||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||||
},
|
},
|
||||||
|
onAgentCommands = {
|
||||||
|
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this))
|
||||||
|
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
||||||
|
},
|
||||||
onShareLogs = {
|
onShareLogs = {
|
||||||
Thread({
|
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
|
||||||
val zip = runCatching { SessionLogShare.zipLatest(this) }.getOrNull()
|
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
|
||||||
ui.post {
|
else startActivity(SessionLogShare.shareIntent(this, zip))
|
||||||
if (zip == null) android.widget.Toast.makeText(this, "No session logs yet: run a session first.", android.widget.Toast.LENGTH_LONG).show()
|
}
|
||||||
else startActivity(SessionLogShare.shareIntent(this, zip))
|
|
||||||
}
|
|
||||||
}, "share-logs").start()
|
|
||||||
},
|
},
|
||||||
onClearLogs = {
|
onClearLogs = {
|
||||||
Thread({
|
Thread({
|
||||||
val cleared = runCatching { SessionArtifacts.clearAll(this) }.getOrDefault(0)
|
val cleared = runCatching { SessionArtifacts.clearAll(this) }.getOrDefault(0)
|
||||||
ui.post {
|
ui.post {
|
||||||
android.widget.Toast.makeText(this,
|
android.widget.Toast.makeText(this,
|
||||||
if (cleared == 0) "No session logs to clear." else "Cleared $cleared session log folder${if (cleared == 1) "" else "s"}.",
|
if (cleared == 0) getString(R.string.main_no_logs_to_clear) else resources.getQuantityString(R.plurals.main_logs_cleared, cleared, cleared),
|
||||||
android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}, "clear-logs").start()
|
}, "clear-logs").start()
|
||||||
@@ -648,6 +685,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
},
|
},
|
||||||
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false },
|
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false },
|
||||||
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
||||||
|
onLanguage = { tag ->
|
||||||
|
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) {
|
||||||
|
com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag)
|
||||||
|
// Redrawn in the new language; Setup's page and tab are saved state.
|
||||||
|
recreate()
|
||||||
|
}
|
||||||
|
},
|
||||||
onAppScale = { percent ->
|
onAppScale = { percent ->
|
||||||
com.droiddeck.launcher.core.AppUiPrefs.setScale(this, percent)
|
com.droiddeck.launcher.core.AppUiPrefs.setScale(this, percent)
|
||||||
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
|
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
|
||||||
@@ -680,7 +724,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
|
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
|
||||||
}
|
}
|
||||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging pairing failed" }
|
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_pair_failed) }
|
||||||
ui.post { complete(error) }
|
ui.post { complete(error) }
|
||||||
}, "wireless-adb-pair").start()
|
}, "wireless-adb-pair").start()
|
||||||
},
|
},
|
||||||
@@ -693,7 +737,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
onWirelessAdbApply = { host, port, enabled, complete ->
|
onWirelessAdbApply = { host, port, enabled, complete ->
|
||||||
Thread({
|
Thread({
|
||||||
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
|
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
|
||||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging command failed" }
|
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_command_failed) }
|
||||||
ui.post {
|
ui.post {
|
||||||
if (error == null) refreshPhantomStatus()
|
if (error == null) refreshPhantomStatus()
|
||||||
complete(error)
|
complete(error)
|
||||||
@@ -703,7 +747,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
onSetPhantomProcessLimit = { enabled, complete ->
|
onSetPhantomProcessLimit = { enabled, complete ->
|
||||||
Thread({
|
Thread({
|
||||||
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
|
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
|
||||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging is unavailable" }
|
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_unavailable) }
|
||||||
ui.post {
|
ui.post {
|
||||||
if (error == null) refreshPhantomStatus()
|
if (error == null) refreshPhantomStatus()
|
||||||
complete(error)
|
complete(error)
|
||||||
@@ -712,9 +756,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
},
|
},
|
||||||
onCopyPhantomCommand = { enabled ->
|
onCopyPhantomCommand = { enabled ->
|
||||||
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
|
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
|
||||||
ClipData.newPlainText("DroidDeck child-process setting", PhantomProcessLimit.adbCommand(enabled)),
|
ClipData.newPlainText(getString(R.string.main_adb_clip_label), PhantomProcessLimit.adbCommand(enabled)),
|
||||||
)
|
)
|
||||||
android.widget.Toast.makeText(this, "ADB command copied", android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
},
|
},
|
||||||
onDismissPhantomGate = { showPhantomGate = false },
|
onDismissPhantomGate = { showPhantomGate = false },
|
||||||
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
|
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
|
||||||
@@ -748,24 +792,24 @@ class MainActivity : ComponentActivity() {
|
|||||||
path = romsDir,
|
path = romsDir,
|
||||||
onChoose = {
|
onChoose = {
|
||||||
showRoms = false
|
showRoms = false
|
||||||
pickRomsDir.launch(InAppFilePicker.buildDirIntent(this, "Choose the ROMs folder", romsDir))
|
pickRomsDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_roms), romsDir))
|
||||||
},
|
},
|
||||||
onClear = { SessionPrefs.setRomsDir(this, ""); romsDir = null; showRoms = false },
|
onClear = { SessionPrefs.setRomsDir(this, ""); romsDir = null; showRoms = false },
|
||||||
onDismiss = { showRoms = false },
|
onDismiss = { showRoms = false },
|
||||||
)
|
)
|
||||||
showNonAdreno?.let { release ->
|
showNonAdreno?.let { release ->
|
||||||
ConfirmDialog(
|
ConfirmDialog(
|
||||||
title = "Not an Adreno GPU",
|
title = androidx.compose.ui.res.stringResource(R.string.main_non_adreno_title),
|
||||||
text = "Turnip supports Adreno GPUs. On ${com.droiddeck.launcher.core.DeviceSupport.gpuName()}, Steam may show a black screen. Download: ${"%.0f".format(release.size / 1e6)} MB.",
|
text = androidx.compose.ui.res.stringResource(R.string.main_non_adreno_text, com.droiddeck.launcher.core.DeviceSupport.gpuName(this@MainActivity), release.size / 1e6),
|
||||||
confirm = "Install anyway",
|
confirm = androidx.compose.ui.res.stringResource(R.string.main_install_anyway),
|
||||||
onConfirm = { showNonAdreno = null; install(release) },
|
onConfirm = { showNonAdreno = null; install(release) },
|
||||||
onDismiss = { showNonAdreno = null },
|
onDismiss = { showNonAdreno = null },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (showRemove) ConfirmDialog(
|
if (showRemove) ConfirmDialog(
|
||||||
title = "Remove Linux runtime",
|
title = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_title),
|
||||||
text = "This deletes the runtime, the Steam client inside it, and every game installed there.",
|
text = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_text),
|
||||||
confirm = "Remove",
|
confirm = androidx.compose.ui.res.stringResource(R.string.store_remove),
|
||||||
onConfirm = { showRemove = false; removeRuntime() },
|
onConfirm = { showRemove = false; removeRuntime() },
|
||||||
onDismiss = { showRemove = false },
|
onDismiss = { showRemove = false },
|
||||||
)
|
)
|
||||||
@@ -875,7 +919,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (!SessionState.running) Thread({
|
if (!SessionState.running) Thread({
|
||||||
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
|
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
|
||||||
if (applied.isNotEmpty()) ui.post {
|
if (applied.isNotEmpty()) ui.post {
|
||||||
android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
|
||||||
}
|
}
|
||||||
ui.post { if (showComponents) components.refreshComponents() }
|
ui.post { if (showComponents) components.refreshComponents() }
|
||||||
}, "components-queue").start()
|
}, "components-queue").start()
|
||||||
@@ -898,6 +942,11 @@ class MainActivity : ComponentActivity() {
|
|||||||
override fun onStart() {
|
override fun onStart() {
|
||||||
super.onStart()
|
super.onStart()
|
||||||
registerReceiver(wifiLocationReceiver, android.content.IntentFilter(android.location.LocationManager.MODE_CHANGED_ACTION))
|
registerReceiver(wifiLocationReceiver, android.content.IntentFilter(android.location.LocationManager.MODE_CHANGED_ACTION))
|
||||||
|
registerReceiver(mediaReceiver, android.content.IntentFilter().apply {
|
||||||
|
for (action in listOf(Intent.ACTION_MEDIA_MOUNTED, Intent.ACTION_MEDIA_UNMOUNTED, Intent.ACTION_MEDIA_REMOVED,
|
||||||
|
Intent.ACTION_MEDIA_EJECT, Intent.ACTION_MEDIA_BAD_REMOVAL)) addAction(action)
|
||||||
|
addDataScheme("file")
|
||||||
|
})
|
||||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||||
refreshSecondScreenDisplays()
|
refreshSecondScreenDisplays()
|
||||||
}
|
}
|
||||||
@@ -909,6 +958,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onStop() {
|
override fun onStop() {
|
||||||
unregisterReceiver(wifiLocationReceiver)
|
unregisterReceiver(wifiLocationReceiver)
|
||||||
|
unregisterReceiver(mediaReceiver)
|
||||||
|
ui.removeCallbacks(mediaRefresh)
|
||||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||||
// The session covers the page by now; coming back finds it as it was.
|
// The session covers the page by now; coming back finds it as it was.
|
||||||
flood = null
|
flood = null
|
||||||
@@ -934,9 +985,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
try {
|
try {
|
||||||
HomeApp.launch(this, app, displayId)
|
HomeApp.launch(this, app, displayId)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
|
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
|
||||||
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
|
val message = when {
|
||||||
android.widget.Toast.makeText(this, "Could not open ${app.label} on $target", android.widget.Toast.LENGTH_SHORT).show()
|
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
|
||||||
|
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
|
||||||
|
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
|
||||||
|
}
|
||||||
|
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -967,7 +1022,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (busy || LinuxRuntimeInstaller.isBusy() || saveBusy != null) return
|
if (busy || LinuxRuntimeInstaller.isBusy() || saveBusy != null) return
|
||||||
saveBusy = label
|
saveBusy = label
|
||||||
Thread({
|
Thread({
|
||||||
val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
|
val message = runCatching(work).getOrElse { e -> getString(R.string.main_action_failed, label, e.message ?: e.javaClass.simpleName) }
|
||||||
ui.post {
|
ui.post {
|
||||||
saveBusy = null
|
saveBusy = null
|
||||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
|
||||||
@@ -1013,10 +1068,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
private fun importComponent(uri: Uri) {
|
private fun importComponent(uri: Uri) {
|
||||||
val name = displayNameOf(uri) ?: "imported.wcp"
|
val name = displayNameOf(uri) ?: "imported.wcp"
|
||||||
components.componentAction("Importing") {
|
components.componentAction(getString(R.string.comp_busy_importing)) {
|
||||||
val tmp = File(cacheDir, "component-import.wcp")
|
val tmp = File(cacheDir, "component-import.wcp")
|
||||||
contentResolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("cannot read the file")
|
contentResolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error(getString(R.string.comp_cannot_read))
|
||||||
try { "Imported ${ComponentsManager.importPackage(this, tmp, name).version}" } finally { tmp.delete() }
|
try { getString(R.string.comp_imported, ComponentsManager.importPackage(this, tmp, name).version) } finally { tmp.delete() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1034,14 +1089,14 @@ class MainActivity : ComponentActivity() {
|
|||||||
requestInitialFocus = focusComponentsContent,
|
requestInitialFocus = focusComponentsContent,
|
||||||
onProton = { components.chooseProton(it) },
|
onProton = { components.chooseProton(it) },
|
||||||
onComp = { components.compComp = it },
|
onComp = { components.compComp = it },
|
||||||
onSwap = { file -> components.compProton?.let { pid -> components.componentAction("Swapping") { ComponentsManager.swap(this, pid, file) } } },
|
onSwap = { file -> components.compProton?.let { pid -> components.componentAction(getString(R.string.comp_busy_swapping)) { ComponentsManager.swap(this, pid, file) } } },
|
||||||
onRestore = { version -> components.compProton?.let { pid -> components.componentAction("Restoring") { ComponentsManager.restore(this, pid, components.compComp, version) } } },
|
onRestore = { version -> components.compProton?.let { pid -> components.componentAction(getString(R.string.comp_busy_restoring)) { ComponentsManager.restore(this, pid, components.compComp, version) } } },
|
||||||
onCancelQueued = { components.compProton?.let { pid -> components.componentAction("Cancelling") { ComponentsManager.cancelQueued(this, pid, components.compComp); "The waiting swap was cancelled." } } },
|
onCancelQueued = { components.compProton?.let { pid -> components.componentAction(getString(R.string.comp_busy_cancelling)) { ComponentsManager.cancelQueued(this, pid, components.compComp); getString(R.string.comp_swap_cancelled) } } },
|
||||||
onDeletePackage = { file -> components.componentAction("Deleting") { ComponentsManager.deletePackage(this, file) } },
|
onDeletePackage = { file -> components.componentAction(getString(R.string.comp_busy_deleting)) { ComponentsManager.deletePackage(this, file) } },
|
||||||
onDeleteOriginal = { version -> components.compProton?.let { pid -> components.componentAction("Deleting") { ComponentsManager.deleteOriginal(this, pid, components.compComp, version) } } },
|
onDeleteOriginal = { version -> components.compProton?.let { pid -> components.componentAction(getString(R.string.comp_busy_deleting)) { ComponentsManager.deleteOriginal(this, pid, components.compComp, version) } } },
|
||||||
onDownload = { components.downloadComponent(it) },
|
onDownload = { components.downloadComponent(it) },
|
||||||
onRefresh = { components.refreshComponentCatalog() },
|
onRefresh = { components.refreshComponentCatalog() },
|
||||||
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) },
|
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) },
|
||||||
onBack = { showComponents = false },
|
onBack = { showComponents = false },
|
||||||
gpu = drivers.state(),
|
gpu = drivers.state(),
|
||||||
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
|
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
|
||||||
@@ -1054,9 +1109,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
|
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
|
||||||
onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) },
|
onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) },
|
||||||
onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) },
|
onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) },
|
||||||
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip or Android + Linux bundle)")) },
|
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.drivers_pick_linux))) },
|
||||||
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip or Android + Linux bundle)")) },
|
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.drivers_pick_android))) },
|
||||||
onImportZip = { pickAnyDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a driver zip or an Android + Linux bundle")) },
|
onImportZip = { pickAnyDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.drivers_pick_any))) },
|
||||||
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
|
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -1092,14 +1147,14 @@ class MainActivity : ComponentActivity() {
|
|||||||
private fun installPackage(id: String) {
|
private fun installPackage(id: String) {
|
||||||
val entry = catalog?.firstOrNull { it.id == id } ?: return
|
val entry = catalog?.firstOrNull { it.id == id } ?: return
|
||||||
if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return
|
if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return
|
||||||
pkgId = id; pkgStage = "Starting…"; pkgPercent = -1
|
pkgId = id; pkgStage = getString(R.string.store_starting); pkgPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
val problem = DesktopCatalog.install(this, entry) { stage, percent ->
|
val problem = DesktopCatalog.install(this, entry) { stage, percent ->
|
||||||
ui.post { pkgStage = stage; pkgPercent = percent }
|
ui.post { pkgStage = stage; pkgPercent = percent }
|
||||||
}
|
}
|
||||||
ui.post {
|
ui.post {
|
||||||
pkgStage = null; pkgId = null
|
pkgStage = null; pkgId = null
|
||||||
if (problem != null) android.widget.Toast.makeText(this, "${entry.name}: $problem", android.widget.Toast.LENGTH_LONG).show()
|
if (problem != null) android.widget.Toast.makeText(this, getString(R.string.main_pkg_problem, entry.name, problem), android.widget.Toast.LENGTH_LONG).show()
|
||||||
refreshPackages()
|
refreshPackages()
|
||||||
refresh()
|
refresh()
|
||||||
}
|
}
|
||||||
@@ -1109,7 +1164,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
private fun removePackage(id: String) {
|
private fun removePackage(id: String) {
|
||||||
val entry = catalog?.firstOrNull { it.id == id } ?: return
|
val entry = catalog?.firstOrNull { it.id == id } ?: return
|
||||||
if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return
|
if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return
|
||||||
pkgId = id; pkgStage = if (entry.kind == "appimage") "Removing ${entry.name}…" else "Forgetting ${entry.name}…"; pkgPercent = -1
|
pkgId = id; pkgStage = getString(if (entry.kind == "appimage") R.string.main_removing_named else R.string.main_forgetting_named, entry.name); pkgPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
DesktopCatalog.remove(this, entry)
|
DesktopCatalog.remove(this, entry)
|
||||||
ui.post {
|
ui.post {
|
||||||
@@ -1131,13 +1186,12 @@ class MainActivity : ComponentActivity() {
|
|||||||
gpuDrivers = drivers.summary(),
|
gpuDrivers = drivers.summary(),
|
||||||
touchMode = touchMode,
|
touchMode = touchMode,
|
||||||
suspendPolicy = suspendPolicy,
|
suspendPolicy = suspendPolicy,
|
||||||
|
steamDownloadsInBackground = steamDownloadsInBackground,
|
||||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
||||||
pipAutoEnter = pipAutoEnter,
|
pipAutoEnter = pipAutoEnter,
|
||||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||||
backActionsInverted = backActionsInverted,
|
backActionsInverted = backActionsInverted,
|
||||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||||
clientDirectAudio = clientDirectAudio,
|
|
||||||
forceFullscreen = if (mode == SessionService.MODE_STEAM) forceFullscreen else null,
|
|
||||||
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
|
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
|
||||||
mic = if (mode == SessionService.MODE_STEAM) mic else null,
|
mic = if (mode == SessionService.MODE_STEAM) mic else null,
|
||||||
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
|
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
|
||||||
@@ -1145,6 +1199,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
storageOptions = storageOptions,
|
storageOptions = storageOptions,
|
||||||
storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics,
|
storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics,
|
||||||
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
||||||
|
forceSsbs = forceSsbs,
|
||||||
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
|
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
|
||||||
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
|
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
|
||||||
steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
|
steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
|
||||||
@@ -1163,6 +1218,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
|
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
|
||||||
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null,
|
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null,
|
||||||
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
|
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
|
||||||
|
deckyDownloadingBinary = decky.deckyDownloadingBinary,
|
||||||
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
|
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
|
||||||
),
|
),
|
||||||
ModeSettingsActions(
|
ModeSettingsActions(
|
||||||
@@ -1189,6 +1245,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
||||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||||
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
||||||
|
onSteamDownloadsInBackground = { enabled ->
|
||||||
|
SessionPrefs.setSteamDownloadsInBackground(this, enabled)
|
||||||
|
steamDownloadsInBackground = enabled
|
||||||
|
},
|
||||||
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
|
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
|
||||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||||
onBackActionsInverted = { inverted ->
|
onBackActionsInverted = { inverted ->
|
||||||
@@ -1196,8 +1256,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
backActionsInverted = inverted
|
backActionsInverted = inverted
|
||||||
},
|
},
|
||||||
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
|
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
|
||||||
onClientDirectAudio = { on -> SessionPrefs.setClientDirectAudio(this, on); clientDirectAudio = on },
|
|
||||||
onForceFullscreen = { on -> SessionPrefs.setForceFullscreen(this, on); forceFullscreen = on },
|
|
||||||
onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on },
|
onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on },
|
||||||
onMic = { on ->
|
onMic = { on ->
|
||||||
SessionPrefs.setMicEnabled(this, on)
|
SessionPrefs.setMicEnabled(this, on)
|
||||||
@@ -1211,13 +1269,14 @@ class MainActivity : ComponentActivity() {
|
|||||||
onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r },
|
onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r },
|
||||||
onGameStorage = { path, label -> setGameStorage(path, label) },
|
onGameStorage = { path, label -> setGameStorage(path, label) },
|
||||||
onPickGameStorageFolder = {
|
onPickGameStorageFolder = {
|
||||||
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, "Choose the game storage folder", gameStorage.ifEmpty { null }))
|
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_game_storage), gameStorage.ifEmpty { null }))
|
||||||
},
|
},
|
||||||
onStorageDiagnostics = { on ->
|
onStorageDiagnostics = { on ->
|
||||||
SessionPrefs.setStorageDiagnosticsEnabled(this, on)
|
SessionPrefs.setStorageDiagnosticsEnabled(this, on)
|
||||||
storageDiagnostics = on
|
storageDiagnostics = on
|
||||||
},
|
},
|
||||||
onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
|
onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
|
||||||
|
onForceSsbs = { on -> SessionPrefs.setForceSsbs(this, on); forceSsbs = on },
|
||||||
onSyncBackend = { id ->
|
onSyncBackend = { id ->
|
||||||
SessionPrefs.setSyncBackend(this, id)
|
SessionPrefs.setSyncBackend(this, id)
|
||||||
fastSync = SessionPrefs.fastSync(this)
|
fastSync = SessionPrefs.fastSync(this)
|
||||||
@@ -1237,13 +1296,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
SessionPrefs.setRunSteamAtStartup(this, on)
|
SessionPrefs.setRunSteamAtStartup(this, on)
|
||||||
runSteamAtStartup = on
|
runSteamAtStartup = on
|
||||||
},
|
},
|
||||||
onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, "Choose a folder of your own games", addedGamesDirs.lastOrNull())) },
|
onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_added_games), addedGamesDirs.lastOrNull())) },
|
||||||
onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() },
|
onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() },
|
||||||
onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() },
|
onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() },
|
||||||
onAddedGameExe = { folder, path -> SessionPrefs.setAddedGameExe(this, folder, path); refreshAddedGames(); refresh() },
|
onAddedGameExe = { folder, path -> SessionPrefs.setAddedGameExe(this, folder, path); refreshAddedGames(); refresh() },
|
||||||
onPickAddedGameExe = { folder ->
|
onPickAddedGameExe = { folder ->
|
||||||
pendingAddedGame = folder
|
pendingAddedGame = folder
|
||||||
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), "Choose the game's .exe", folder))
|
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), getString(R.string.main_pick_game_exe), folder))
|
||||||
},
|
},
|
||||||
onDeckyInstall = { release -> decky.installDecky(release) },
|
onDeckyInstall = { release -> decky.installDecky(release) },
|
||||||
onDeckyCheck = { decky.refreshDecky() },
|
onDeckyCheck = { decky.refreshDecky() },
|
||||||
@@ -1254,7 +1313,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
decky.deckySupervisor = false
|
decky.deckySupervisor = false
|
||||||
},
|
},
|
||||||
onPickDeckyPluginZip = {
|
onPickDeckyPluginZip = {
|
||||||
pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Decky plugin ZIP"))
|
pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip)))
|
||||||
},
|
},
|
||||||
onDismiss = { settingsMode = null },
|
onDismiss = { settingsMode = null },
|
||||||
),
|
),
|
||||||
@@ -1310,7 +1369,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
/** Walks the added-games folders, which can sit on slow shared storage or an SD card. */
|
/** Walks the added-games folders, which can sit on slow shared storage or an SD card. */
|
||||||
private fun scanAddedGames() = com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
|
private fun scanAddedGames() = com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
|
||||||
com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, g.candidates.map { c -> c.path to c.name }.distinctBy { it.first })
|
com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, (g.candidates + g.exe).map { c -> c.path to c.name }.distinctBy { it.first })
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun fetchAddedGameArt() {
|
private fun fetchAddedGameArt() {
|
||||||
@@ -1339,6 +1398,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
showMapping = false
|
showMapping = false
|
||||||
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
||||||
fexPreset = SessionPrefs.fexPreset(this)
|
fexPreset = SessionPrefs.fexPreset(this)
|
||||||
|
forceSsbs = SessionPrefs.forceSsbs(this)
|
||||||
fastSync = SessionPrefs.fastSync(this)
|
fastSync = SessionPrefs.fastSync(this)
|
||||||
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
||||||
syncFallback = SessionPrefs.syncFallback(this)
|
syncFallback = SessionPrefs.syncFallback(this)
|
||||||
@@ -1356,11 +1416,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
|
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
|
||||||
touchMode = SessionPrefs.touchMode(this)
|
touchMode = SessionPrefs.touchMode(this)
|
||||||
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
|
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
|
||||||
|
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||||
oscMode = SessionPrefs.oscMode(this)
|
oscMode = SessionPrefs.oscMode(this)
|
||||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||||
directAudio = SessionPrefs.directAudio(this)
|
directAudio = SessionPrefs.directAudio(this)
|
||||||
clientDirectAudio = SessionPrefs.clientDirectAudio(this)
|
|
||||||
forceFullscreen = SessionPrefs.forceFullscreen(this)
|
|
||||||
stretch16x9 = SessionPrefs.stretch16x9(this)
|
stretch16x9 = SessionPrefs.stretch16x9(this)
|
||||||
mic = SessionPrefs.micEnabled(this)
|
mic = SessionPrefs.micEnabled(this)
|
||||||
refreshWifiDiscovery()
|
refreshWifiDiscovery()
|
||||||
@@ -1373,7 +1432,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
Thread({
|
Thread({
|
||||||
drivers.refreshDrivers()
|
drivers.refreshDrivers()
|
||||||
val games = scanAddedGames()
|
val games = scanAddedGames()
|
||||||
val storage = GameStorage.options(this).map { it.label to it.path }
|
val storage = GameStorage.options(this)
|
||||||
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
|
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
|
||||||
val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this)
|
val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this)
|
||||||
ui.post {
|
ui.post {
|
||||||
@@ -1392,9 +1451,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
/** A second Steam library, proven writable first; "" = internal only. */
|
/** A second Steam library, proven writable first; "" = internal only. */
|
||||||
private fun setGameStorage(path: String, label: String) {
|
private fun setGameStorage(path: String, label: String) {
|
||||||
if (path.isNotEmpty() && path != SessionPrefs.GAME_STORAGE_OFF) {
|
if (path.isNotEmpty() && path != SessionPrefs.GAME_STORAGE_OFF) {
|
||||||
val problem = GameStorage.prepare(path)
|
val problem = GameStorage.prepare(this, path)
|
||||||
if (problem != null) {
|
if (problem != null) {
|
||||||
android.widget.Toast.makeText(this, "Not usable: $problem", android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, getString(R.string.main_storage_not_usable, problem), android.widget.Toast.LENGTH_LONG).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1435,10 +1494,11 @@ class MainActivity : ComponentActivity() {
|
|||||||
frameGenLabel = FrameGen.label(this)
|
frameGenLabel = FrameGen.label(this)
|
||||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||||
|
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
||||||
runningLabel = if (SessionState.running) when (SessionState.mode) {
|
runningLabel = if (SessionState.running) when (SessionState.mode) {
|
||||||
SessionService.MODE_DESKTOP -> "Desktop"
|
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop)
|
||||||
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
|
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
|
||||||
?: SessionState.program?.substringAfterLast('/')?.substringBefore('.') ?: "Program"
|
?: SessionState.program?.substringAfterLast('/')?.substringBefore('.') ?: getString(R.string.main_running_program)
|
||||||
else -> "Steam"
|
else -> "Steam"
|
||||||
} else null
|
} else null
|
||||||
// The libraries, off the main thread: manifests and a folder scan.
|
// The libraries, off the main thread: manifests and a folder scan.
|
||||||
@@ -1505,7 +1565,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
private fun refreshPhantomStatus() {
|
private fun refreshPhantomStatus() {
|
||||||
phantomProcessStatus = PhantomProcessLimit.read(this)
|
phantomProcessStatus = PhantomProcessLimit.read(this)
|
||||||
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||||
"${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.adbCommand()}"
|
getString(
|
||||||
|
R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus),
|
||||||
|
PhantomProcessLimit.instructions(this, phantomProcessStatus), PhantomProcessLimit.adbCommand(),
|
||||||
|
)
|
||||||
} else null
|
} else null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1521,10 +1584,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
if (displayId != null) {
|
if (displayId != null) {
|
||||||
runCatching { startActivity(intent) }
|
runCatching { startActivity(intent) }
|
||||||
android.widget.Toast.makeText(this, "Could not open Settings on the bottom screen; opened it on the main screen.", android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, R.string.main_settings_main_screen, android.widget.Toast.LENGTH_LONG).show()
|
||||||
} else {
|
} else {
|
||||||
startActivity(Intent(android.provider.Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
startActivity(Intent(android.provider.Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
android.widget.Toast.makeText(this, "Open Developer options in Settings", android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, R.string.main_open_dev_options, android.widget.Toast.LENGTH_LONG).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1557,7 +1620,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
|
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
|
||||||
busy = true
|
busy = true
|
||||||
failed = false
|
failed = false
|
||||||
stage = if (LinuxRuntimeInstaller.isRemoving()) "Removing Linux runtime" else "Starting…"
|
stage = getString(if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
|
||||||
percent = -1
|
percent = -1
|
||||||
Thread({
|
Thread({
|
||||||
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
|
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
|
||||||
@@ -1582,6 +1645,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val TAG = "MainActivity"
|
private const val TAG = "MainActivity"
|
||||||
|
private const val MEDIA_SETTLE_MS = 1500L
|
||||||
/** What the picker offers for a driver zip; some file apps label a zip as a plain stream. */
|
/** What the picker offers for a driver zip; some file apps label a zip as a plain stream. */
|
||||||
private val ZIP_EXT = listOf("zip")
|
private val ZIP_EXT = listOf("zip")
|
||||||
private val WCP_EXT = listOf("wcp")
|
private val WCP_EXT = listOf("wcp")
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
|||||||
if (protonBusyId != null || SessionState.running) return
|
if (protonBusyId != null || SessionState.running) return
|
||||||
ProtonExtras.unqueue(activity, tool)
|
ProtonExtras.unqueue(activity, tool)
|
||||||
protonBusyId = id
|
protonBusyId = id
|
||||||
protonStage = "Starting…"
|
protonStage = activity.getString(R.string.store_starting)
|
||||||
protonPercent = -1
|
protonPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
val problem = ProtonExtras.install(activity, tool) { label, value ->
|
val problem = ProtonExtras.install(activity, tool) { label, value ->
|
||||||
@@ -44,7 +44,7 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
|||||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||||
if (protonBusyId != null || SessionState.running) return
|
if (protonBusyId != null || SessionState.running) return
|
||||||
protonBusyId = id
|
protonBusyId = id
|
||||||
protonStage = "Removing ${tool.name}…"
|
protonStage = activity.getString(R.string.main_removing_named, tool.name)
|
||||||
protonPercent = -1
|
protonPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
ProtonExtras.remove(activity, tool)
|
ProtonExtras.remove(activity, tool)
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ import com.droiddeck.launcher.gpu.ScreenEffects
|
|||||||
import com.droiddeck.launcher.gpu.Lossless
|
import com.droiddeck.launcher.gpu.Lossless
|
||||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||||
import com.droiddeck.launcher.input.EvdevKeys
|
import com.droiddeck.launcher.input.EvdevKeys
|
||||||
|
import com.droiddeck.launcher.input.InputSpace
|
||||||
import com.droiddeck.launcher.input.KeyboardHost
|
import com.droiddeck.launcher.input.KeyboardHost
|
||||||
import com.droiddeck.launcher.input.ControllerPrefs
|
import com.droiddeck.launcher.input.ControllerPrefs
|
||||||
import com.droiddeck.launcher.input.SessionClipboard
|
import com.droiddeck.launcher.input.SessionClipboard
|
||||||
@@ -100,6 +101,11 @@ import kotlin.math.abs
|
|||||||
* the HUD line, the loading overlay, the drawer and its dialogs.
|
* the HUD line, the loading overlay, the drawer and its dialogs.
|
||||||
*/
|
*/
|
||||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||||
|
override fun attachBaseContext(newBase: android.content.Context) {
|
||||||
|
super.attachBaseContext(newBase)
|
||||||
|
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||||
|
}
|
||||||
|
|
||||||
private lateinit var pip: com.droiddeck.launcher.session.SessionPipController
|
private lateinit var pip: com.droiddeck.launcher.session.SessionPipController
|
||||||
private var pipUi by mutableStateOf(false)
|
private var pipUi by mutableStateOf(false)
|
||||||
private var pipAutoEnter by mutableStateOf(false)
|
private var pipAutoEnter by mutableStateOf(false)
|
||||||
@@ -139,6 +145,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
if (resumed && !pipUi && SessionState.deckPad) padMotion?.start() else padMotion?.stop()
|
if (resumed && !pipUi && SessionState.deckPad) padMotion?.start() else padMotion?.stop()
|
||||||
}
|
}
|
||||||
private var onScreenControls: OnScreenControls? = null
|
private var onScreenControls: OnScreenControls? = null
|
||||||
|
/** Steam's touch controls (SteamTouchControls), made once the session offers the device. */
|
||||||
|
private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null
|
||||||
|
private var steamTouchAvailable by mutableStateOf(false)
|
||||||
|
private val steamTouchRetry = Runnable { updateOnScreenControls() }
|
||||||
|
/** While Steam's touch controls are up: how the game's touch config says touches outside them
|
||||||
|
* act (Steam Link's input and mouse modes), in place of the drawer's touch mode. */
|
||||||
|
private var steamTouchOptions: com.droiddeck.launcher.input.SteamTouchConfig.Options? = null
|
||||||
|
/** The touch mode touches are routed by: the drawer's, or the game's while Steam's controls are up. */
|
||||||
|
private var routedTouchMode = SessionPrefs.TOUCH_AUTO
|
||||||
private var keyboard: KeyboardHost? = null
|
private var keyboard: KeyboardHost? = null
|
||||||
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
|
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
|
||||||
private val sessionClipboard by lazy {
|
private val sessionClipboard by lazy {
|
||||||
@@ -229,7 +244,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
|
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
|
||||||
private var pcKeyboardOpen by mutableStateOf(false)
|
private var pcKeyboardOpen by mutableStateOf(false)
|
||||||
private var hudOn by mutableStateOf(true)
|
private var hudOn by mutableStateOf(true)
|
||||||
private var fillScreen by mutableStateOf(true)
|
|
||||||
private var upscaler by mutableStateOf(0)
|
private var upscaler by mutableStateOf(0)
|
||||||
private var upscaleSharpness by mutableStateOf(75)
|
private var upscaleSharpness by mutableStateOf(75)
|
||||||
private var effects by mutableStateOf(ScreenEffects.OFF)
|
private var effects by mutableStateOf(ScreenEffects.OFF)
|
||||||
@@ -242,6 +256,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
|
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
|
||||||
private var fexPreset by mutableStateOf("")
|
private var fexPreset by mutableStateOf("")
|
||||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||||
|
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||||
private var onScreenButtonsVisible by mutableStateOf(false)
|
private var onScreenButtonsVisible by mutableStateOf(false)
|
||||||
private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode)
|
private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode)
|
||||||
@@ -289,6 +304,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
override fun onInputDeviceRemoved(deviceId: Int) {
|
override fun onInputDeviceRemoved(deviceId: Int) {
|
||||||
Log.i(TAG, "input device $deviceId disconnected")
|
Log.i(TAG, "input device $deviceId disconnected")
|
||||||
|
padBridge?.onDeviceRemoved(deviceId)
|
||||||
updateOnScreenControls()
|
updateOnScreenControls()
|
||||||
updatePointerCapture()
|
updatePointerCapture()
|
||||||
}
|
}
|
||||||
@@ -301,7 +317,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving()) {
|
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving()) {
|
||||||
runtimeRemovalBlocked = true
|
runtimeRemovalBlocked = true
|
||||||
android.widget.Toast.makeText(this, "Wait for runtime removal to finish", android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.session_wait_removal, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
finish()
|
finish()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -357,6 +373,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
|
|
||||||
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
|
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
|
||||||
padBridge = bridge
|
padBridge = bridge
|
||||||
|
SessionState.padBridge = bridge
|
||||||
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
|
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
|
||||||
@@ -462,6 +479,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
if (hud.text.isNotEmpty()) HudText(hud.text)
|
if (hud.text.isNotEmpty()) HudText(hud.text)
|
||||||
if (loading.visible) LoadingOverlay(
|
if (loading.visible) LoadingOverlay(
|
||||||
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
|
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
|
||||||
|
topic = loading.topic, readable = loading.readable,
|
||||||
title = loadingTitle(), steam = loadingMode() == SessionService.MODE_STEAM,
|
title = loadingTitle(), steam = loadingMode() == SessionService.MODE_STEAM,
|
||||||
// As the drawer's Stop does: the service stops, and a start still installing is cancelled.
|
// As the drawer's Stop does: the service stops, and a start still installing is cancelled.
|
||||||
onCancel = { SessionService.stop(this@SessionActivity); finish() },
|
onCancel = { SessionService.stop(this@SessionActivity); finish() },
|
||||||
@@ -497,23 +515,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
|
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
|
||||||
steam = SessionState.mode == SessionService.MODE_STEAM,
|
steam = SessionState.mode == SessionService.MODE_STEAM,
|
||||||
title = if (SessionState.mode == SessionService.MODE_RUN)
|
title = if (SessionState.mode == SessionService.MODE_RUN)
|
||||||
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "Game" else null,
|
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null,
|
||||||
isHomeApp = isHomeApp,
|
isHomeApp = isHomeApp,
|
||||||
androidApps = androidApps,
|
androidApps = androidApps,
|
||||||
hudOn = hudOn,
|
hudOn = hudOn,
|
||||||
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
|
|
||||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||||
effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias,
|
effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias,
|
||||||
frameGen = frameGen,
|
frameGen = frameGen,
|
||||||
lossless = lossless,
|
lossless = lossless,
|
||||||
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy, touchMode = touchMode,
|
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy,
|
||||||
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
|
steamDownloadsInBackground = steamDownloadsInBackground, touchMode = touchMode,
|
||||||
|
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
|
||||||
fexPreset = fexPreset,
|
fexPreset = fexPreset,
|
||||||
secondScreenMode = secondScreenMode,
|
secondScreenMode = secondScreenMode,
|
||||||
secondScreenDisplays = secondScreenDisplays,
|
secondScreenDisplays = secondScreenDisplays,
|
||||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||||
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
|
|
||||||
onUpscaler = { m ->
|
onUpscaler = { m ->
|
||||||
SessionPrefs.setUpscaler(this@SessionActivity, m); upscaler = m
|
SessionPrefs.setUpscaler(this@SessionActivity, m); upscaler = m
|
||||||
WaylandCompositor.nativeSetUpscaler(m)
|
WaylandCompositor.nativeSetUpscaler(m)
|
||||||
@@ -553,12 +570,27 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||||
backActionsInverted = inverted
|
backActionsInverted = inverted
|
||||||
},
|
},
|
||||||
onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
|
onOsc = { v ->
|
||||||
|
SessionPrefs.setOscMode(this@SessionActivity, v)
|
||||||
|
readPrefs()
|
||||||
|
updateOnScreenControls()
|
||||||
|
if (v == SessionPrefs.OSC_STEAM_TOUCH && com.droiddeck.launcher.input.SteamTouchDevice.current == null)
|
||||||
|
Toast.makeText(this@SessionActivity, R.string.osc_style_next_session, Toast.LENGTH_LONG).show()
|
||||||
|
},
|
||||||
|
onEditSteamTouch = if (steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && onScreenButtonsVisible) ({
|
||||||
|
drawerOpen = false
|
||||||
|
steamTouchControls?.startEditing()
|
||||||
|
}) else null,
|
||||||
onSuspendPolicy = { policy ->
|
onSuspendPolicy = { policy ->
|
||||||
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
|
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
|
||||||
suspendPolicy = policy
|
suspendPolicy = policy
|
||||||
SessionService.suspendPolicyChanged(this@SessionActivity)
|
SessionService.suspendPolicyChanged(this@SessionActivity)
|
||||||
},
|
},
|
||||||
|
onSteamDownloadsInBackground = { enabled ->
|
||||||
|
SessionPrefs.setSteamDownloadsInBackground(this@SessionActivity, enabled)
|
||||||
|
steamDownloadsInBackground = enabled
|
||||||
|
SessionService.suspendPolicyChanged(this@SessionActivity)
|
||||||
|
},
|
||||||
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
||||||
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
||||||
onSecondScreenMode = ::selectSecondScreenMode,
|
onSecondScreenMode = ::selectSecondScreenMode,
|
||||||
@@ -568,9 +600,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
try {
|
try {
|
||||||
HomeApp.launch(this@SessionActivity, app, displayId)
|
HomeApp.launch(this@SessionActivity, app, displayId)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
|
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
|
||||||
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
|
val message = when {
|
||||||
Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show()
|
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
|
||||||
|
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
|
||||||
|
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
|
||||||
|
}
|
||||||
|
Toast.makeText(this@SessionActivity, message, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this@SessionActivity),
|
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this@SessionActivity),
|
||||||
@@ -688,7 +724,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
val snap = runCatching { ComponentsManager.snapshot(this) }.getOrNull()
|
val snap = runCatching { ComponentsManager.snapshot(this) }.getOrNull()
|
||||||
uiHandler.post {
|
uiHandler.post {
|
||||||
drawerComponents = snap
|
drawerComponents = snap
|
||||||
if (applied.isNotEmpty()) android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
|
if (applied.isNotEmpty()) android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
|
||||||
}
|
}
|
||||||
}, "drawer-components").start()
|
}, "drawer-components").start()
|
||||||
}
|
}
|
||||||
@@ -703,10 +739,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
val current = active ?: "orig:$build"
|
val current = active ?: "orig:$build"
|
||||||
if (queued != null && value == current) {
|
if (queued != null && value == current) {
|
||||||
// Picking what is already in place again cancels the swap waiting for the game.
|
// Picking what is already in place again cancels the swap waiting for the game.
|
||||||
ComponentsManager.cancelQueued(this, protonId, comp); "The waiting swap was cancelled."
|
ComponentsManager.cancelQueued(this, protonId, comp); getString(R.string.comp_swap_cancelled)
|
||||||
} else if (value.startsWith("orig:")) ComponentsManager.restore(this, protonId, comp, value.removePrefix("orig:"))
|
} else if (value.startsWith("orig:")) ComponentsManager.restore(this, protonId, comp, value.removePrefix("orig:"))
|
||||||
else ComponentsManager.swap(this, protonId, value)
|
else ComponentsManager.swap(this, protonId, value)
|
||||||
}.getOrElse { e -> "Swap failed: ${e.message ?: e.javaClass.simpleName}" }
|
}.getOrElse { e -> getString(R.string.session_swap_failed, e.message ?: e.javaClass.simpleName) }
|
||||||
uiHandler.post {
|
uiHandler.post {
|
||||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
|
||||||
refreshDrawerComponents()
|
refreshDrawerComponents()
|
||||||
@@ -720,20 +756,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
else intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
else intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||||
|
|
||||||
private fun pausedTitle(): String = when (SessionState.mode) {
|
private fun pausedTitle(): String = when (SessionState.mode) {
|
||||||
SessionService.MODE_DESKTOP -> "The desktop is paused"
|
SessionService.MODE_DESKTOP -> getString(R.string.session_desktop_paused)
|
||||||
SessionService.MODE_RUN -> (com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "The program") + " is paused"
|
SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program)
|
||||||
else -> "Steam is paused"
|
?.let { getString(R.string.session_named_paused, it) } ?: getString(R.string.session_program_paused)
|
||||||
|
else -> getString(R.string.load_steam_paused)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun loadingTitle(): String = when (loadingMode()) {
|
private fun loadingTitle(): String = when (loadingMode()) {
|
||||||
SessionService.MODE_DESKTOP ->
|
SessionService.MODE_DESKTOP ->
|
||||||
if (!SessionState.running && intent.getStringExtra(SessionService.EXTRA_STEAM_UI) != null) "Starting Steam on the desktop"
|
if (!SessionState.running && intent.getStringExtra(SessionService.EXTRA_STEAM_UI) != null) getString(R.string.session_starting_steam_desktop)
|
||||||
else "Starting the desktop"
|
else getString(R.string.session_starting_desktop)
|
||||||
SessionService.MODE_RUN -> {
|
SessionService.MODE_RUN -> {
|
||||||
val program = if (SessionState.running) SessionState.program else intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
val program = if (SessionState.running) SessionState.program else intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||||
"Starting " + (com.droiddeck.launcher.frontend.Library.nameForProgram(program) ?: "the program")
|
com.droiddeck.launcher.frontend.Library.nameForProgram(program)?.let { getString(R.string.session_starting_named, it) }
|
||||||
|
?: getString(R.string.session_starting_program)
|
||||||
}
|
}
|
||||||
else -> "Starting Steam"
|
else -> getString(R.string.load_starting_steam)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun shareCurrentSessionLogs() {
|
private fun shareCurrentSessionLogs() {
|
||||||
@@ -741,31 +779,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
// ended screen's Share logs is for that one.
|
// ended screen's Share logs is for that one.
|
||||||
val folder = SessionPaths.current() ?: SessionPaths.lastEnded()
|
val folder = SessionPaths.current() ?: SessionPaths.lastEnded()
|
||||||
if (folder == null || !folder.isDirectory) {
|
if (folder == null || !folder.isDirectory) {
|
||||||
Toast.makeText(this, "No logs for this session.", Toast.LENGTH_LONG).show()
|
Toast.makeText(this, R.string.session_no_logs, Toast.LENGTH_LONG).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
Thread({
|
SessionLogShare.prepare(this, { folder }) { zip ->
|
||||||
val zip = runCatching { SessionLogShare.zipFolder(this, folder) }
|
if (zip == null) {
|
||||||
.onFailure { Log.w(TAG, "could not package current session logs", it) }
|
Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show()
|
||||||
.getOrNull()
|
} else {
|
||||||
uiHandler.post {
|
runCatching { startActivity(SessionLogShare.shareIntent(this, zip)) }
|
||||||
if (zip == null) {
|
.onFailure {
|
||||||
Toast.makeText(this, "Could not create the session log archive.", Toast.LENGTH_LONG).show()
|
Log.w(TAG, "could not share current session logs", it)
|
||||||
} else {
|
Toast.makeText(this, R.string.session_logs_share_failed, Toast.LENGTH_LONG).show()
|
||||||
runCatching { startActivity(SessionLogShare.shareIntent(this, zip)) }
|
}
|
||||||
.onFailure {
|
|
||||||
Log.w(TAG, "could not share current session logs", it)
|
|
||||||
Toast.makeText(this, "Could not share the session logs.", Toast.LENGTH_LONG).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}, "share-session-logs").start()
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun readPrefs() {
|
private fun readPrefs() {
|
||||||
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
||||||
hudOn = SessionPrefs.hudEnabled(this)
|
hudOn = SessionPrefs.hudEnabled(this)
|
||||||
fillScreen = SessionPrefs.forceFullscreen(this)
|
|
||||||
upscaler = SessionPrefs.upscaler(this)
|
upscaler = SessionPrefs.upscaler(this)
|
||||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||||
effects = SessionPrefs.screenEffects(this)
|
effects = SessionPrefs.screenEffects(this)
|
||||||
@@ -783,9 +815,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
if (nextTouchMode == SessionPrefs.TOUCH_OFF) cursorVisible = false
|
if (nextTouchMode == SessionPrefs.TOUCH_OFF) cursorVisible = false
|
||||||
}
|
}
|
||||||
touchMode = nextTouchMode
|
touchMode = nextTouchMode
|
||||||
|
routedTouchMode = effectiveTouchMode()
|
||||||
frameGen = FrameGen.mode(this)
|
frameGen = FrameGen.mode(this)
|
||||||
fexPreset = SessionPrefs.fexPreset(this)
|
fexPreset = SessionPrefs.fexPreset(this)
|
||||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||||
|
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||||
oscMode = SessionPrefs.oscMode(this)
|
oscMode = SessionPrefs.oscMode(this)
|
||||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||||
}
|
}
|
||||||
@@ -814,8 +848,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
"${SessionState.installing}.installing",
|
"${SessionState.installing}.installing",
|
||||||
mapOf("component" to SessionState.installing),
|
mapOf("component" to SessionState.installing),
|
||||||
)
|
)
|
||||||
loading.step = if (runtime) "downloading the Linux runtime" else if (desktop) "downloading the desktop"
|
val first = if (runtime) RUNTIME_LINES else if (desktop) DESKTOP_LINES else PROTON_LINES
|
||||||
else "downloading Proton Experimental (ARM64)"
|
loading.say(getString(first.downloading), first.topic, readable = true)
|
||||||
loading.percent = -1
|
loading.percent = -1
|
||||||
Thread({
|
Thread({
|
||||||
var failedComponent: String? = null
|
var failedComponent: String? = null
|
||||||
@@ -856,7 +890,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
return@post
|
return@post
|
||||||
}
|
}
|
||||||
loading.percent = -1
|
loading.percent = -1
|
||||||
loading.step = "Starting the session…"
|
loading.say(getString(R.string.session_starting_session), LoadingState.Topic.SESSION, readable = false)
|
||||||
// The surface may have come and gone while the download ran; start on the live one.
|
// The surface may have come and gone while the download ran; start on the live one.
|
||||||
if (surfaceView.holder.surface?.isValid == true) surfaceCreated(surfaceView.holder)
|
if (surfaceView.holder.surface?.isValid == true) surfaceCreated(surfaceView.holder)
|
||||||
}
|
}
|
||||||
@@ -872,14 +906,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}, "session-failure-artifacts").start()
|
}, "session-failure-artifacts").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The loading screen's lines for one package: downloading it (with and without its size), checking it,
|
||||||
|
* unpacking it; the checklist [topic] they belong to, and whether the checking line is shown as it is.
|
||||||
|
*/
|
||||||
|
private class PackageLines(
|
||||||
|
val downloading: Int, val downloadingMb: Int, val checking: Int, val unpacking: Int,
|
||||||
|
val topic: LoadingState.Topic, val checkingReadable: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
/** Reports one package's download on the loading screen: "<what> · 332 of 791 MB", checking, unpacking. */
|
/** Reports one package's download on the loading screen: "<what> · 332 of 791 MB", checking, unpacking. */
|
||||||
private fun progressFor(what: String, mb: Long) = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener { stage, p ->
|
private fun progressFor(what: PackageLines, mb: Long) = object : com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener {
|
||||||
uiHandler.post {
|
override fun onProgress(stage: String, percent: Int) =
|
||||||
loading.percent = p
|
onProgress(com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.Step.OTHER, stage, percent)
|
||||||
loading.step = when {
|
|
||||||
stage.startsWith("Downloading") -> if (p >= 0 && mb > 0) "downloading $what · ${p * mb / 100} of $mb MB" else "downloading $what"
|
override fun onProgress(step: com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.Step, stage: String, percent: Int) {
|
||||||
stage.startsWith("Verifying") -> "checking $what"
|
uiHandler.post {
|
||||||
else -> "unpacking $what"
|
loading.percent = percent
|
||||||
|
when (step) {
|
||||||
|
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.Step.DOWNLOADING -> loading.say(
|
||||||
|
if (percent >= 0 && mb > 0) getString(what.downloadingMb, percent * mb / 100, mb) else getString(what.downloading),
|
||||||
|
what.topic, readable = true,
|
||||||
|
)
|
||||||
|
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.Step.VERIFYING ->
|
||||||
|
loading.say(getString(what.checking), what.topic, what.checkingReadable)
|
||||||
|
else -> loading.say(getString(what.unpacking), what.topic, readable = true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -887,29 +939,29 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
/** Null when the runtime is in, else the loading screen's closing line. */
|
/** Null when the runtime is in, else the loading screen's closing line. */
|
||||||
private fun installRuntime(): String? {
|
private fun installRuntime(): String? {
|
||||||
val release = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.fetchRelease()
|
val release = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.fetchRelease()
|
||||||
?: return "Could not reach the runtime catalog. Check the connection and press Play again."
|
?: return getString(R.string.session_runtime_catalog_unreachable)
|
||||||
val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release,
|
val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release,
|
||||||
progressFor("the Linux runtime", release.size / 1_000_000))
|
progressFor(RUNTIME_LINES, release.size / 1_000_000))
|
||||||
return if (ok) null else "The Linux runtime did not install. Check the runtime in Setup and press Play again."
|
return if (ok) null else getString(R.string.session_runtime_install_failed)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Null when the desktop package is in, else the loading screen's closing line. */
|
/** Null when the desktop package is in, else the loading screen's closing line. */
|
||||||
private fun installDesktop(): String? {
|
private fun installDesktop(): String? {
|
||||||
uiHandler.post { loading.percent = -1; loading.step = "downloading the desktop" }
|
uiHandler.post { loading.percent = -1; loading.say(getString(DESKTOP_LINES.downloading), DESKTOP_LINES.topic, readable = true) }
|
||||||
val entry = com.droiddeck.launcher.runtime.DesktopCatalog.fetch()?.firstOrNull { it.id == "desktop" }
|
val entry = com.droiddeck.launcher.runtime.DesktopCatalog.fetch()?.firstOrNull { it.id == "desktop" }
|
||||||
?: return "Could not reach the desktop catalog. Check the connection and press Desktop again."
|
?: return getString(R.string.session_desktop_catalog_unreachable)
|
||||||
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry,
|
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry,
|
||||||
progressFor("the desktop", entry.size / 1_000_000))
|
progressFor(DESKTOP_LINES, entry.size / 1_000_000))
|
||||||
return problem?.let { "The desktop did not install ($it). Check the connection and press Desktop again." }
|
return problem?.let { getString(R.string.session_desktop_install_failed, it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Null when the ARM64 Proton is in, else why not; the session goes on either way. */
|
/** Null when the ARM64 Proton is in, else why not; the session goes on either way. */
|
||||||
private fun installProton(): String? {
|
private fun installProton(): String? {
|
||||||
uiHandler.post { loading.percent = -1; loading.step = "downloading Proton Experimental (ARM64)" }
|
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
|
||||||
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
||||||
val entry = catalog.fetch(catalog.STEAM_SEED_URL)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
|
val entry = catalog.fetch(catalog.STEAM_SEED_URL)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
|
||||||
?: return "catalog unreachable"
|
?: return "catalog unreachable"
|
||||||
return catalog.install(this, entry, progressFor("Proton Experimental (ARM64)", entry.size / 1_000_000))
|
return catalog.install(this, entry, progressFor(PROTON_LINES, entry.size / 1_000_000))
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||||
@@ -1145,6 +1197,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
// the request landed in this instance's onNewIntent and went with its finish().
|
// the request landed in this instance's onNewIntent and went with its finish().
|
||||||
SessionState.relaunch?.let { next ->
|
SessionState.relaunch?.let { next ->
|
||||||
SessionState.relaunch = null
|
SessionState.relaunch = null
|
||||||
|
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
|
||||||
setIntent(next)
|
setIntent(next)
|
||||||
recreate()
|
recreate()
|
||||||
return@runOnUiThread
|
return@runOnUiThread
|
||||||
@@ -1169,14 +1222,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
// It stays until the user leaves: a failure read against a timer is a failure not read.
|
// It stays until the user leaves: a failure read against a timer is a failure not read.
|
||||||
val what = when (SessionState.mode) {
|
val stopped = when (SessionState.mode) {
|
||||||
SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "The program"
|
SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program)
|
||||||
SessionService.MODE_DESKTOP -> "The desktop"
|
?.let { getString(R.string.session_ended_named, it) } ?: getString(R.string.session_ended_program)
|
||||||
else -> "Steam"
|
SessionService.MODE_DESKTOP -> getString(R.string.session_ended_desktop)
|
||||||
|
else -> getString(R.string.session_ended_named, "Steam")
|
||||||
}
|
}
|
||||||
loading.showEnded(
|
loading.showEnded(
|
||||||
hint?.text ?: "$what stopped unexpectedly. Share the logs with a bug report, or try again.",
|
hint?.text ?: stopped,
|
||||||
"Exit status $status · ${SessionState.logFile?.path ?: "no log"}",
|
getString(R.string.session_ended_detail, status, SessionState.logFile?.path ?: getString(R.string.session_ended_no_log)),
|
||||||
)
|
)
|
||||||
focusEndedScreen()
|
focusEndedScreen()
|
||||||
}
|
}
|
||||||
@@ -1226,8 +1280,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
|
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
|
||||||
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
|
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
|
||||||
} else if (enosys >= 8) {
|
} else if (enosys >= 8) {
|
||||||
EndHint("The log shows $enosys \"Function not implemented\" errors: proot's seccomp acceleration is failing a helper on this device. " +
|
EndHint(resources.getQuantityString(R.plurals.session_hint_enosys, enosys, enosys,
|
||||||
"Try Performance \u2192 \"Run proot without seccomp\" (or \"Skip Steam's xalia helper\") and start again.")
|
getString(R.string.perf_title), getString(R.string.perf_seccomp), getString(R.string.perf_xalia)))
|
||||||
} else null
|
} else null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
@@ -1454,18 +1508,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun movePointer(x: Float, y: Float) {
|
private fun movePointer(x: Float, y: Float) {
|
||||||
val width = surfaceView.width.takeIf { it > 0 } ?: return
|
val rect = drawnRect() ?: return
|
||||||
val height = surfaceView.height.takeIf { it > 0 } ?: return
|
val cx = x.coerceIn(rect.left, rect.right)
|
||||||
val out = SessionState.outputSize
|
val cy = y.coerceIn(rect.top, rect.bottom)
|
||||||
val scale = minOf(width / out.first.toFloat(), height / out.second.toFloat())
|
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
|
||||||
val drawnW = out.first * scale
|
showCursor(cx, cy)
|
||||||
val drawnH = out.second * scale
|
|
||||||
val left = (width - drawnW) / 2f
|
|
||||||
val top = (height - drawnH) / 2f
|
|
||||||
val px = ((x - left) / drawnW * 1920f).toInt().coerceIn(0, 1919)
|
|
||||||
val py = ((y - top) / drawnH * 1080f).toInt().coerceIn(0, 1079)
|
|
||||||
WaylandCompositor.nativeSendPointer(1, px, py)
|
|
||||||
showCursor(x.coerceIn(left, left + drawnW), y.coerceIn(top, top + drawnH))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1612,10 +1659,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
if (width <= 0f || height <= 0f) return
|
if (width <= 0f || height <= 0f) return
|
||||||
val nx = (x / width).coerceIn(0f, 1f)
|
val nx = (x / width).coerceIn(0f, 1f)
|
||||||
val ny = (y / height).coerceIn(0f, 1f)
|
val ny = (y / height).coerceIn(0f, 1f)
|
||||||
WaylandCompositor.nativeSendPointer(1, (nx * 1919f).toInt(), (ny * 1079f).toInt())
|
val rect = drawnRect() ?: return
|
||||||
drawnRect()?.let { rect ->
|
val px = rect.left + nx * rect.width()
|
||||||
showCursor(rect.left + nx * rect.width(), rect.top + ny * rect.height())
|
val py = rect.top + ny * rect.height()
|
||||||
}
|
WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, surfaceView.width), InputSpace.y(py, surfaceView.height))
|
||||||
|
showCursor(px, py)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun closeSecondScreen(reset: Boolean) {
|
private fun closeSecondScreen(reset: Boolean) {
|
||||||
@@ -1627,8 +1675,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The touch mode in force: the game's own while Steam's touch controls are shown. */
|
||||||
|
private fun effectiveTouchMode(): String {
|
||||||
|
val options = steamTouchOptions
|
||||||
|
if (options == null || steamTouchControls?.visibility != View.VISIBLE) return SessionPrefs.touchMode(this)
|
||||||
|
return when {
|
||||||
|
options.inputMode == com.droiddeck.launcher.input.SteamTouchConfig.INPUT_CONTROLLER -> SessionPrefs.TOUCH_OFF
|
||||||
|
options.mouseMode == com.droiddeck.launcher.input.SteamTouchConfig.MOUSE_RELATIVE -> SessionPrefs.TOUCH_PAD
|
||||||
|
else -> SessionPrefs.TOUCH_DIRECT
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applyTouchRouting() {
|
||||||
|
val next = effectiveTouchMode()
|
||||||
|
if (::touchpad.isInitialized) {
|
||||||
|
val speed = steamTouchOptions?.trackpadSensitivity?.takeIf { steamTouchControls?.visibility == View.VISIBLE } ?: 1f
|
||||||
|
touchpad.sensitivity = 1.15f * speed
|
||||||
|
}
|
||||||
|
if (next == routedTouchMode) return
|
||||||
|
if (::touchpad.isInitialized) touchpad.cancel()
|
||||||
|
if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||||
|
if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false
|
||||||
|
routedTouchMode = next
|
||||||
|
}
|
||||||
|
|
||||||
/** Touchpad on the desktop, direct in Steam, unless the drawer says otherwise. */
|
/** Touchpad on the desktop, direct in Steam, unless the drawer says otherwise. */
|
||||||
private fun usingTouchpad(): Boolean = when (SessionPrefs.touchMode(this)) {
|
private fun usingTouchpad(): Boolean = when (routedTouchMode) {
|
||||||
SessionPrefs.TOUCH_PAD -> true
|
SessionPrefs.TOUCH_PAD -> true
|
||||||
SessionPrefs.TOUCH_DIRECT -> false
|
SessionPrefs.TOUCH_DIRECT -> false
|
||||||
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
|
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
|
||||||
@@ -1650,7 +1722,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||||
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event)
|
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event)
|
||||||
// Child views get the event first, so menus, keyboards and the on-screen pad still work.
|
// Child views get the event first, so menus, keyboards and the on-screen pad still work.
|
||||||
if (touchMode == SessionPrefs.TOUCH_OFF) return true
|
if (routedTouchMode == SessionPrefs.TOUCH_OFF) return true
|
||||||
if (usingTouchpad()) {
|
if (usingTouchpad()) {
|
||||||
val rect = drawnRect() ?: return false
|
val rect = drawnRect() ?: return false
|
||||||
if (touchpad.bounds != rect) {
|
if (touchpad.bounds != rect) {
|
||||||
@@ -1662,9 +1734,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
val rect = drawnRect() ?: return false
|
val rect = drawnRect() ?: return false
|
||||||
fun sendTouch(action: Int, index: Int) {
|
fun sendTouch(action: Int, index: Int) {
|
||||||
val x = ((event.getX(index) - rect.left) / rect.width()).coerceIn(0f, 1f)
|
val x = event.getX(index).coerceIn(rect.left, rect.right)
|
||||||
val y = ((event.getY(index) - rect.top) / rect.height()).coerceIn(0f, 1f)
|
val y = event.getY(index).coerceIn(rect.top, rect.bottom)
|
||||||
WaylandCompositor.nativeSendTouch(action, event.getPointerId(index), (x * 1919f).toInt(), (y * 1079f).toInt())
|
WaylandCompositor.nativeSendTouch(action, event.getPointerId(index),
|
||||||
|
InputSpace.x(x, surfaceView.width), InputSpace.y(y, surfaceView.height))
|
||||||
}
|
}
|
||||||
when (event.actionMasked) {
|
when (event.actionMasked) {
|
||||||
// A first finger starts a new gesture, and Android has ended every earlier one: whatever
|
// A first finger starts a new gesture, and Android has ended every earlier one: whatever
|
||||||
@@ -1768,6 +1841,41 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
what, d.name, d.vendorId, d.productId, d.id, d.sources))
|
what, d.name, d.vendorId, d.productId, d.id, d.sources))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Steam's touch controls, once the session has made the device (SessionService). */
|
||||||
|
private fun steamTouch(): com.droiddeck.launcher.input.SteamTouchControls? {
|
||||||
|
val device = com.droiddeck.launcher.input.SteamTouchDevice.current ?: return null
|
||||||
|
steamTouchControls?.let { view ->
|
||||||
|
if (view.device === device) return view
|
||||||
|
// A new session made a new device: the view of the old one goes.
|
||||||
|
view.releaseAll()
|
||||||
|
(view.parent as? android.view.ViewGroup)?.removeView(view)
|
||||||
|
steamTouchControls = null
|
||||||
|
}
|
||||||
|
val root = onScreenControls?.parent as? android.view.ViewGroup ?: return null
|
||||||
|
val view = com.droiddeck.launcher.input.SteamTouchControls(this, device,
|
||||||
|
onMenu = { drawerOpen = true }, onKeyboard = ::togglePcKeyboard)
|
||||||
|
view.visibility = View.GONE
|
||||||
|
view.onOptions = { options ->
|
||||||
|
steamTouchOptions = options
|
||||||
|
applyTouchRouting()
|
||||||
|
}
|
||||||
|
// Paste: the clipboard is shared with the session's X servers; Ctrl+V types it.
|
||||||
|
view.onPaste = {
|
||||||
|
sendGuestKey(29, true); sendGuestKey(47, true) // KEY_LEFTCTRL, KEY_V
|
||||||
|
sendGuestKey(47, false); sendGuestKey(29, false)
|
||||||
|
}
|
||||||
|
// The client reads a controller's config when it connects: after a save, plug the device
|
||||||
|
// out and back in so it takes the new one.
|
||||||
|
view.onSaved = {
|
||||||
|
device.plugged = false
|
||||||
|
uiHandler.postDelayed({ updateOnScreenControls() }, 700)
|
||||||
|
}
|
||||||
|
root.addView(view, root.indexOfChild(onScreenControls) + 1)
|
||||||
|
steamTouchControls = view
|
||||||
|
steamTouchAvailable = true
|
||||||
|
return view
|
||||||
|
}
|
||||||
|
|
||||||
private fun updateOnScreenControls() {
|
private fun updateOnScreenControls() {
|
||||||
val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc")
|
val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc")
|
||||||
.takeIf { it.isFile }
|
.takeIf { it.isFile }
|
||||||
@@ -1778,20 +1886,49 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
onScreenButtonsVisible = false
|
onScreenButtonsVisible = false
|
||||||
controls.releaseAll()
|
controls.releaseAll()
|
||||||
controls.visibility = View.GONE
|
controls.visibility = View.GONE
|
||||||
|
steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE }
|
||||||
|
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM
|
val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM
|
||||||
|
// Steam's touch controller stands in for the app's pad, and is plugged into the client only
|
||||||
|
// while it is shown - as Steam Link withdraws its controls when a physical pad is in use.
|
||||||
|
val wantsSteam = forced == SessionPrefs.OSC_STEAM_TOUCH && SessionState.mode == SessionService.MODE_STEAM
|
||||||
|
val steam = if (wantsSteam) steamTouch() else null
|
||||||
|
// The service makes the device while the session starts, after this activity: the app's
|
||||||
|
// own pad until then, and another look in a moment.
|
||||||
|
if (wantsSteam && steam == null && !isFinishing && !isDestroyed) {
|
||||||
|
uiHandler.removeCallbacks(steamTouchRetry)
|
||||||
|
uiHandler.postDelayed(steamTouchRetry, 1000)
|
||||||
|
}
|
||||||
|
if (steam == null) {
|
||||||
|
steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE }
|
||||||
|
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
|
||||||
|
}
|
||||||
controls.setButtonsOnly(buttonsOnly)
|
controls.setButtonsOnly(buttonsOnly)
|
||||||
val show = when (forced) {
|
val show = when (forced) {
|
||||||
SessionPrefs.OSC_ALWAYS -> true
|
SessionPrefs.OSC_ALWAYS -> true
|
||||||
SessionPrefs.OSC_STEAM_QAM -> true
|
SessionPrefs.OSC_STEAM_QAM -> true
|
||||||
SessionPrefs.OSC_NEVER -> false
|
SessionPrefs.OSC_NEVER -> false
|
||||||
|
// Shown throughout a Steam session: a handheld's built-in pad would keep Auto off for good.
|
||||||
|
// Outside Steam it is Auto.
|
||||||
|
SessionPrefs.OSC_STEAM_TOUCH -> SessionState.mode == SessionService.MODE_STEAM ||
|
||||||
|
(!PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP)
|
||||||
// Auto: the touch pad when there is no controller - except on the desktop, where the
|
// Auto: the touch pad when there is no controller - except on the desktop, where the
|
||||||
// screen is a touchpad for the pointer and a pad over it would be in the way. A game
|
// screen is a touchpad for the pointer and a pad over it would be in the way. A game
|
||||||
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
|
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
|
||||||
else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
|
else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
|
||||||
}
|
}
|
||||||
onScreenButtonsVisible = show
|
onScreenButtonsVisible = show
|
||||||
|
if (steam != null) {
|
||||||
|
if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE }
|
||||||
|
if (!show) steam.releaseAll()
|
||||||
|
steam.visibility = if (show) View.VISIBLE else View.GONE
|
||||||
|
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = show
|
||||||
|
applyTouchRouting()
|
||||||
|
Log.i(TAG, "on-screen controls: Steam's touch controller " + if (show) "shown" else "hidden")
|
||||||
|
return
|
||||||
|
}
|
||||||
if (show == (controls.visibility == View.VISIBLE)) return
|
if (show == (controls.visibility == View.VISIBLE)) return
|
||||||
if (!show) controls.releaseAll()
|
if (!show) controls.releaseAll()
|
||||||
controls.visibility = if (show) View.VISIBLE else View.GONE
|
controls.visibility = if (show) View.VISIBLE else View.GONE
|
||||||
@@ -1906,6 +2043,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
recreate()
|
recreate()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// Home/notification resumes must retain the external frontend's return destination.
|
||||||
|
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
|
||||||
setIntent(intent)
|
setIntent(intent)
|
||||||
if (intent.action == SessionService.ACTION_HOME_GUIDE) {
|
if (intent.action == SessionService.ACTION_HOME_GUIDE) {
|
||||||
handleHomeGuideIntent(intent)
|
handleHomeGuideIntent(intent)
|
||||||
@@ -2008,6 +2147,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
|
uiHandler.removeCallbacks(steamTouchRetry)
|
||||||
if (runtimeRemovalBlocked) { super.onDestroy(); return }
|
if (runtimeRemovalBlocked) { super.onDestroy(); return }
|
||||||
// Deliberately does NOT end the session: this activity can be destroyed while the user is
|
// Deliberately does NOT end the session: this activity can be destroyed while the user is
|
||||||
// in another app, and the whole point of the service is that Steam survives that.
|
// in another app, and the whole point of the service is that Steam survives that.
|
||||||
@@ -2019,6 +2159,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
closeSecondScreen(reset = false)
|
closeSecondScreen(reset = false)
|
||||||
if (::hud.isInitialized) hud.stop()
|
if (::hud.isInitialized) hud.stop()
|
||||||
padBridge?.stop()
|
padBridge?.stop()
|
||||||
|
if (SessionState.padBridge === padBridge) SessionState.padBridge = null
|
||||||
padMotion?.stop()
|
padMotion?.stop()
|
||||||
if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null
|
if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null
|
||||||
if (SessionState.endListener === endListener) SessionState.endListener = null
|
if (SessionState.endListener === endListener) SessionState.endListener = null
|
||||||
@@ -2046,6 +2187,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
* off, it just closes.
|
* off, it just closes.
|
||||||
*/
|
*/
|
||||||
override fun finish() {
|
override fun finish() {
|
||||||
|
if (isFinishing) return
|
||||||
if (!quitFlooded && !closeAtOnce && com.droiddeck.launcher.ui.Motion.scale != 0f &&
|
if (!quitFlooded && !closeAtOnce && com.droiddeck.launcher.ui.Motion.scale != 0f &&
|
||||||
lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) {
|
lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) {
|
||||||
if (!leaving) {
|
if (!leaving) {
|
||||||
@@ -2056,6 +2198,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
super.finish()
|
super.finish()
|
||||||
|
if (!closeAtOnce && intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) {
|
||||||
|
com.droiddeck.launcher.ui.QuitFlood.take()
|
||||||
|
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||||
|
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
|
||||||
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
|
}
|
||||||
if (quitFlooded) overridePendingTransition(0, 0)
|
if (quitFlooded) overridePendingTransition(0, 0)
|
||||||
else overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
|
else overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
|
||||||
}
|
}
|
||||||
@@ -2071,6 +2219,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
const val EXTRA_RETURN_HOME = "returnHome"
|
||||||
/** How long the leaving flood may take before the session closes without it. */
|
/** How long the leaving flood may take before the session closes without it. */
|
||||||
private const val LEAVE_TIMEOUT_MS = 1_500L
|
private const val LEAVE_TIMEOUT_MS = 1_500L
|
||||||
private const val TAG = "SessionActivity"
|
private const val TAG = "SessionActivity"
|
||||||
@@ -2088,5 +2237,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
/** Compositor scale modes (Container.FULLSCREEN_* values): 1 = fit with bars, centred. */
|
/** Compositor scale modes (Container.FULLSCREEN_* values): 1 = fit with bars, centred. */
|
||||||
private const val SCALE_FIT = 1
|
private const val SCALE_FIT = 1
|
||||||
private const val ALIGN_CENTER = 0
|
private const val ALIGN_CENTER = 0
|
||||||
|
private val RUNTIME_LINES = PackageLines(
|
||||||
|
R.string.session_runtime_downloading, R.string.session_runtime_downloading_mb,
|
||||||
|
R.string.session_runtime_checking, R.string.session_runtime_unpacking,
|
||||||
|
LoadingState.Topic.RUNTIME, checkingReadable = true,
|
||||||
|
)
|
||||||
|
private val DESKTOP_LINES = PackageLines(
|
||||||
|
R.string.session_desktop_downloading, R.string.session_desktop_downloading_mb,
|
||||||
|
R.string.session_desktop_checking, R.string.session_desktop_unpacking,
|
||||||
|
LoadingState.Topic.DESKTOP, checkingReadable = false,
|
||||||
|
)
|
||||||
|
private val PROTON_LINES = PackageLines(
|
||||||
|
R.string.session_proton_downloading, R.string.session_proton_downloading_mb,
|
||||||
|
R.string.session_proton_checking, R.string.session_proton_unpacking,
|
||||||
|
LoadingState.Topic.STEAM, checkingReadable = false,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,7 +46,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
onAllowInstalls = {
|
onAllowInstalls = {
|
||||||
askPermission = false
|
askPermission = false
|
||||||
runCatching { activity.startActivity(SelfInstaller.permissionIntent(activity)) }
|
runCatching { activity.startActivity(SelfInstaller.permissionIntent(activity)) }
|
||||||
.onFailure { error = "Couldn't open Android's \"Install unknown apps\" setting"; pending = null }
|
.onFailure { error = activity.getString(R.string.upd_unknown_apps_failed); pending = null }
|
||||||
},
|
},
|
||||||
onDismissPermission = { askPermission = false; pending = null },
|
onDismissPermission = { askPermission = false; pending = null },
|
||||||
)
|
)
|
||||||
@@ -77,7 +77,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
catalog = it
|
catalog = it
|
||||||
follow = AppUpdates.follow(activity, it)
|
follow = AppUpdates.follow(activity, it)
|
||||||
error = null
|
error = null
|
||||||
}.onFailure { if (force) error = "Couldn't check: ${it.message ?: it.javaClass.simpleName}" }
|
}.onFailure { if (force) error = activity.getString(R.string.upd_couldnt_check, it.message ?: it.javaClass.simpleName) }
|
||||||
}
|
}
|
||||||
}, "app-updates").start()
|
}, "app-updates").start()
|
||||||
}
|
}
|
||||||
@@ -90,20 +90,20 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
|
|
||||||
private fun install(r: AppUpdates.Release) {
|
private fun install(r: AppUpdates.Release) {
|
||||||
if (stage != null) return
|
if (stage != null) return
|
||||||
val apk = r.apk ?: run { error = "This build has no download for this copy of DroidDeck"; return }
|
val apk = r.apk ?: run { error = activity.getString(R.string.upd_no_download); return }
|
||||||
AppUpdates.installBlock(r)?.let { error = it; return }
|
AppUpdates.installBlock(r)?.let { error = it.message(activity); return }
|
||||||
if (SessionState.running) { error = "Stop the running session first, then update"; return }
|
if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return }
|
||||||
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
|
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
|
||||||
error = null
|
error = null
|
||||||
stage = "Downloading"
|
stage = activity.getString(R.string.upd_stage_downloading)
|
||||||
percent = 0
|
percent = 0
|
||||||
Thread({
|
Thread({
|
||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
||||||
ui.post { stage = "Installing"; percent = -1 }
|
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
|
||||||
SelfInstaller.install(activity, file)
|
SelfInstaller.install(activity, file)
|
||||||
}
|
}
|
||||||
result.onFailure { e -> ui.post { stage = null; error = e.message ?: "The update failed" } }
|
result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } }
|
||||||
}, "app-update-install").start()
|
}, "app-update-install").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,14 +114,14 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
||||||
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
|
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
|
||||||
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
|
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
|
||||||
if (confirm == null) { stage = null; error = "Android didn't offer to install the update"; return }
|
if (confirm == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
|
||||||
stage = "Waiting for you to confirm"
|
stage = activity.getString(R.string.upd_stage_confirm)
|
||||||
activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
}
|
}
|
||||||
PackageInstaller.STATUS_SUCCESS -> stage = null
|
PackageInstaller.STATUS_SUCCESS -> stage = null
|
||||||
else -> {
|
else -> {
|
||||||
stage = null
|
stage = null
|
||||||
error = SelfInstaller.describeFailure(status, intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE))
|
error = SelfInstaller.describeFailure(activity, status, intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Who may run code through the agent bridge. Reading state, starting and stopping sessions,
|
||||||
|
* launching and quitting games and sending input only need the shell (the provider's DUMP
|
||||||
|
* permission). Running commands in the guest, evaluating JavaScript in the Steam client, session
|
||||||
|
* environment, binary overrides and preference writes reach inside the app's sandbox - the guest
|
||||||
|
* holds the Steam login - which the shell of a stock device otherwise cannot. They require
|
||||||
|
* Setup > Session > Debugging tools to be on, in every build. The bridge itself cannot turn it on.
|
||||||
|
*/
|
||||||
|
object AgentAccess {
|
||||||
|
const val MAX_REQUEST_CHARS = 256 * 1024
|
||||||
|
private const val PREFS = "agent"
|
||||||
|
private const val KEY_COMMANDS = "commands"
|
||||||
|
|
||||||
|
/** The preferences file the bridge must never write: set-pref refuses it. */
|
||||||
|
const val PROTECTED_PREFS = PREFS
|
||||||
|
|
||||||
|
fun commandsAllowed(context: Context): Boolean =
|
||||||
|
prefs(context).getBoolean(KEY_COMMANDS, false)
|
||||||
|
|
||||||
|
/** The Setup toggle's own state. */
|
||||||
|
fun commandsEnabled(context: Context): Boolean = prefs(context).getBoolean(KEY_COMMANDS, false)
|
||||||
|
|
||||||
|
fun setCommandsEnabled(context: Context, enabled: Boolean) {
|
||||||
|
prefs(context).edit().putBoolean(KEY_COMMANDS, enabled).apply()
|
||||||
|
if (!enabled) runCatching { AgentEnv.revoke(context) }
|
||||||
|
.onFailure { android.util.Log.w("AgentAccess", "Could not finish clearing debugging experiments") }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requireCommands(context: Context) {
|
||||||
|
if (!commandsAllowed(context)) throw AgentException(
|
||||||
|
"AGENT_COMMANDS_DISABLED",
|
||||||
|
"Debugging tools are off: turn on Setup > Session > Debugging tools on the device",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requireStart(context: Context, request: org.json.JSONObject) {
|
||||||
|
if (request.optString("mode") == "run") requireCommands(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A refusal with a stable code, answered as {"ok": false, "error": {code, message}}. */
|
||||||
|
class AgentException(val code: String, message: String) : RuntimeException(message)
|
||||||
@@ -10,13 +10,14 @@ import android.net.Uri
|
|||||||
import android.os.Binder
|
import android.os.Binder
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Process
|
import android.os.Process
|
||||||
|
import android.util.Base64
|
||||||
import com.droiddeck.launcher.BuildConfig
|
import com.droiddeck.launcher.BuildConfig
|
||||||
|
import com.droiddeck.launcher.frontend.GameLaunchLink
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||||
import com.droiddeck.launcher.session.SessionArtifacts
|
import com.droiddeck.launcher.session.SessionArtifacts
|
||||||
import com.droiddeck.launcher.session.SessionEvents
|
import com.droiddeck.launcher.session.SessionEvents
|
||||||
import com.droiddeck.launcher.session.SessionPhase
|
import com.droiddeck.launcher.session.SessionPhase
|
||||||
import com.droiddeck.launcher.session.SessionPaths
|
|
||||||
import com.droiddeck.launcher.session.SessionService
|
import com.droiddeck.launcher.session.SessionService
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
@@ -25,7 +26,14 @@ import java.io.File
|
|||||||
import java.util.concurrent.CountDownLatch
|
import java.util.concurrent.CountDownLatch
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
/** A shell-only control surface, installed only by debug builds. */
|
/**
|
||||||
|
* The shell's control surface (docs/agent-control.md), in every build: the provider and its start
|
||||||
|
* Activity need android.permission.DUMP, held by the shell and privileged or explicitly granted callers. Commands that
|
||||||
|
* reach into the app's sandbox are further gated by [AgentAccess].
|
||||||
|
*
|
||||||
|
* A method's request is JSON, base64-encoded in the "request" extra; every answer is JSON in the
|
||||||
|
* "json" key of the returned Bundle, {"ok": true, ...} or {"ok": false, "error": {code, message}}.
|
||||||
|
*/
|
||||||
class AgentBridgeProvider : ContentProvider() {
|
class AgentBridgeProvider : ContentProvider() {
|
||||||
override fun onCreate(): Boolean {
|
override fun onCreate(): Boolean {
|
||||||
val appContext = context?.applicationContext ?: return false
|
val appContext = context?.applicationContext ?: return false
|
||||||
@@ -48,17 +56,53 @@ class AgentBridgeProvider : ContentProvider() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
val response = try {
|
val response = try {
|
||||||
when (method) {
|
val request = decode(extras?.getString(EXTRA_REQUEST))
|
||||||
"state" -> state(context).put("ok", true)
|
// Binder identity is the shell's; everything below acts as the app.
|
||||||
"start" -> error("USE_DROIDDECKCTL", "Start sessions with tools/droiddeckctl so Android launches a visible Activity")
|
val token = Binder.clearCallingIdentity()
|
||||||
"stop" -> stop(context)
|
try {
|
||||||
"resume" -> resume(context)
|
dispatch(context, method, request)
|
||||||
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
|
} finally {
|
||||||
|
Binder.restoreCallingIdentity(token)
|
||||||
}
|
}
|
||||||
|
} catch (e: AgentException) {
|
||||||
|
error(e.code, e.message ?: e.code)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
error("COMMAND_FAILED", e.message ?: e.javaClass.simpleName)
|
error("COMMAND_FAILED", e.message ?: e.javaClass.simpleName)
|
||||||
}
|
}
|
||||||
return Bundle().apply { putString(RESULT_JSON, response.toString()) }
|
val json = response.toString().let {
|
||||||
|
if (it.length <= 384 * 1024) it else error("RESPONSE_TOO_LARGE", "Reduce the command output or select fewer fields").toString()
|
||||||
|
}
|
||||||
|
return Bundle().apply { putString(RESULT_JSON, json) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dispatch(context: Context, method: String, request: JSONObject): JSONObject = when (method) {
|
||||||
|
"state" -> state(context).put("ok", true)
|
||||||
|
"start" -> error("USE_DROIDDECKCTL", "Start sessions with tools/droiddeckctl so Android launches a visible Activity")
|
||||||
|
"stop" -> stop(context)
|
||||||
|
"resume" -> resume(context)
|
||||||
|
"launch" -> launch(context, request)
|
||||||
|
"focus" -> guest(context, JSONObject().put("kind", "focus"), 15_000)
|
||||||
|
"quit" -> guest(context, JSONObject().put("kind", "quit").put("appId", request.opt("appId"))
|
||||||
|
.put("timeout", request.optDouble("timeout", 15.0)), timeoutMs(request, 15.0, 30_000))
|
||||||
|
"input" -> AgentInput.handle(request)
|
||||||
|
"ui" -> AgentUi.handle(request)
|
||||||
|
"guest" -> {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
guest(context, JSONObject(request.toString()).put("kind", "exec"), timeoutMs(request, 30.0, 10_000))
|
||||||
|
}
|
||||||
|
"cdp" -> {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
guest(context, JSONObject(request.toString()).put("kind", "cdp"), timeoutMs(request, 15.0, 5_000))
|
||||||
|
}
|
||||||
|
"env" -> env(context, request)
|
||||||
|
"override" -> {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
AgentEnv.override(context, request.optString("name")).put("ok", true).put("command", "override")
|
||||||
|
}
|
||||||
|
"prefs" -> prefs(context, request)
|
||||||
|
"access" -> JSONObject().put("ok", true).put("commands", AgentAccess.commandsAllowed(context))
|
||||||
|
.put("debugBuild", BuildConfig.DEBUG).put("inbox", AgentEnv.inbox(context).absolutePath)
|
||||||
|
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun state(context: Context): JSONObject {
|
private fun state(context: Context): JSONObject {
|
||||||
@@ -91,13 +135,31 @@ class AgentBridgeProvider : ContentProvider() {
|
|||||||
.put("status", SessionState.failureStatus ?: JSONObject.NULL)
|
.put("status", SessionState.failureStatus ?: JSONObject.NULL)
|
||||||
session.put("failure", failure)
|
session.put("failure", failure)
|
||||||
|
|
||||||
|
// gamescope's focus as last published by the guest agent, without the window lists
|
||||||
|
// (the focus command returns those, fresh).
|
||||||
|
val focus = AgentGuest.focus(context)?.let { snap ->
|
||||||
|
JSONObject()
|
||||||
|
.put("focusedApp", snap.opt("focusedApp") ?: JSONObject.NULL)
|
||||||
|
.put("focusedWindow", snap.opt("focusedWindow") ?: JSONObject.NULL)
|
||||||
|
.put("focusableApps", snap.optJSONArray("focusableApps") ?: JSONArray())
|
||||||
|
.put("baselayerAppIds", snap.optJSONArray("baselayerAppIds") ?: JSONArray())
|
||||||
|
.put("seq", snap.optInt("seq"))
|
||||||
|
.put("t", snap.optLong("t"))
|
||||||
|
}
|
||||||
|
session.put("focus", focus ?: JSONObject.NULL)
|
||||||
|
|
||||||
|
val hello = AgentGuest.hello(context)
|
||||||
return JSONObject()
|
return JSONObject()
|
||||||
.put("schema", 1)
|
.put("schema", SCHEMA)
|
||||||
.put("build", BuildConfig.BUILD_LABEL)
|
.put("build", BuildConfig.BUILD_LABEL)
|
||||||
.put("appVersion", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
.put("appVersion", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
||||||
.put("runtime", JSONObject()
|
.put("runtime", JSONObject()
|
||||||
.put("installed", LinuxRuntime.isInstalled(context))
|
.put("installed", LinuxRuntime.isInstalled(context))
|
||||||
.put("version", runtimeVersion ?: JSONObject.NULL))
|
.put("version", runtimeVersion ?: JSONObject.NULL))
|
||||||
|
.put("agent", JSONObject()
|
||||||
|
.put("guest", hello != null)
|
||||||
|
.put("guestFocus", hello?.optBoolean("focus") ?: false)
|
||||||
|
.put("commands", AgentAccess.commandsAllowed(context)))
|
||||||
.put("session", session)
|
.put("session", session)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,6 +193,67 @@ class AgentBridgeProvider : ContentProvider() {
|
|||||||
return JSONObject().put("ok", true).put("command", "resume")
|
return JSONObject().put("ok", true).put("command", "resume")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun launch(context: Context, request: JSONObject): JSONObject {
|
||||||
|
val appId = request.optString("appId")
|
||||||
|
if (!GameLaunchLink.validId(appId)) throw AgentException("INVALID_APP_ID", "appId must be a decimal Steam app id")
|
||||||
|
if (!SessionState.running || SessionState.mode != SessionService.MODE_STEAM) {
|
||||||
|
throw AgentException("NO_STEAM_SESSION", "Games launch inside a running Steam session")
|
||||||
|
}
|
||||||
|
if (!SessionService.launchGame(context, appId)) throw AgentException("LAUNCH_REJECTED", "The session did not accept the launch")
|
||||||
|
SessionEvents.record("agent.launch_requested", mapOf("appId" to appId))
|
||||||
|
return JSONObject().put("ok", true).put("command", "launch").put("appId", appId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun env(context: Context, request: JSONObject): JSONObject {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
val result = when (val op = request.optString("op", "list")) {
|
||||||
|
"list" -> AgentEnv.list(context)
|
||||||
|
"set" -> {
|
||||||
|
val lines = request.optJSONArray("lines") ?: JSONArray()
|
||||||
|
AgentEnv.set(context, List(lines.length()) { lines.optString(it) }, request.optBoolean("persistent"))
|
||||||
|
}
|
||||||
|
"clear" -> AgentEnv.clear(context, request.optString("scope", "next"))
|
||||||
|
else -> throw AgentException("INVALID_REQUEST", "env op '$op' is not list, set or clear")
|
||||||
|
}
|
||||||
|
return result.put("ok", true).put("command", "env")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun prefs(context: Context, request: JSONObject): JSONObject {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
val file = request.optString("file")
|
||||||
|
val result = when (val op = request.optString("op", "get")) {
|
||||||
|
"get" -> AgentPrefs.get(context, file)
|
||||||
|
"set" -> AgentPrefs.set(context, file, request.optString("key"), request.optString("type", "string"),
|
||||||
|
if (request.isNull("value")) null else request.optString("value"))
|
||||||
|
else -> throw AgentException("INVALID_REQUEST", "prefs op '$op' is not get or set")
|
||||||
|
}
|
||||||
|
return result.put("ok", true).put("command", "prefs")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A guest agent request; its own answer already carries ok or error. */
|
||||||
|
private fun guest(context: Context, request: JSONObject, timeoutMs: Long): JSONObject =
|
||||||
|
AgentGuest.call(context, request, timeoutMs)
|
||||||
|
|
||||||
|
/** The guest's own timeout plus slack for the round trip. */
|
||||||
|
private fun timeoutMs(request: JSONObject, defaultSeconds: Double, slackMs: Long): Long {
|
||||||
|
val seconds = if (request.has("timeout")) request.opt("timeout")?.toString()?.toDoubleOrNull()
|
||||||
|
?: throw AgentException("INVALID_REQUEST", "timeout must be a number") else defaultSeconds
|
||||||
|
if (!seconds.isFinite() || seconds <= 0 || seconds > 600) {
|
||||||
|
throw AgentException("INVALID_REQUEST", "timeout must be a positive number no greater than 600 seconds")
|
||||||
|
}
|
||||||
|
return (seconds * 1000).toLong() + slackMs
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decode(encoded: String?): JSONObject {
|
||||||
|
if (encoded.isNullOrBlank()) return JSONObject()
|
||||||
|
if (encoded.length > AgentAccess.MAX_REQUEST_CHARS) throw AgentException("INVALID_REQUEST", "The encoded request exceeds 256 KiB")
|
||||||
|
return try {
|
||||||
|
JSONObject(String(Base64.decode(encoded, Base64.DEFAULT), Charsets.UTF_8))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
throw AgentException("INVALID_REQUEST", "The request extra is not base64 JSON")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun error(code: String, message: String) = JSONObject()
|
private fun error(code: String, message: String) = JSONObject()
|
||||||
.put("ok", false)
|
.put("ok", false)
|
||||||
.put("error", JSONObject().put("code", code).put("message", message))
|
.put("error", JSONObject().put("code", code).put("message", message))
|
||||||
@@ -143,6 +266,9 @@ class AgentBridgeProvider : ContentProvider() {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val RESULT_JSON = "json"
|
const val RESULT_JSON = "json"
|
||||||
|
const val EXTRA_REQUEST = "request"
|
||||||
|
/** 2 added agent and session.focus; everything in 1 is unchanged. */
|
||||||
|
const val SCHEMA = 2
|
||||||
private val recoveryComplete = CountDownLatch(1)
|
private val recoveryComplete = CountDownLatch(1)
|
||||||
|
|
||||||
fun awaitRecovery() {
|
fun awaitRecovery() {
|
||||||
|
|||||||
@@ -0,0 +1,222 @@
|
|||||||
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.file.Files
|
||||||
|
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
||||||
|
import java.nio.file.StandardOpenOption.READ
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Experiment switches an agent sets without touching Download/droiddeck-env or rebuilding the apk:
|
||||||
|
*
|
||||||
|
* - environment lines (KEY=VALUE) for the session, applied after the user's own droiddeck-env, so
|
||||||
|
* they win. "next" lines are taken by the next session that starts and dropped when it ends;
|
||||||
|
* "persistent" ones stay until cleared.
|
||||||
|
* - binary overrides: a file pushed to the app's external files (agent-inbox/<name>) is installed
|
||||||
|
* as /opt/droiddeck-agent/bin/<name> in the rootfs and put first on the next session's PATH -
|
||||||
|
* a gamescope build under test, say. Removed when that session ends.
|
||||||
|
*
|
||||||
|
* Kept in the app's own files (agent-env.json), never in a place the shell can write.
|
||||||
|
*/
|
||||||
|
object AgentEnv {
|
||||||
|
private const val TAG = "AgentEnv"
|
||||||
|
private const val FILE = "agent-env.json"
|
||||||
|
private const val GUEST_BIN = "/opt/droiddeck-agent/bin"
|
||||||
|
private const val BASE_PATH = "/usr/local/bin:/usr/bin:/bin"
|
||||||
|
private val NAME = Regex("[A-Za-z0-9._-]{1,64}")
|
||||||
|
private val KEY = Regex("[A-Za-z_][A-Za-z0-9_]*")
|
||||||
|
private val lock = Any()
|
||||||
|
|
||||||
|
fun inbox(context: Context): File = File(context.getExternalFilesDir(null), "agent-inbox")
|
||||||
|
|
||||||
|
fun list(context: Context): JSONObject = synchronized(lock) {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
load(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Add [lines] for the next session ([persistent] = every session until cleared). */
|
||||||
|
fun set(context: Context, lines: List<String>, persistent: Boolean): JSONObject = synchronized(lock) {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
if (lines.any { line -> KEY.matchEntire(line.substringBefore('=', "")) == null || !line.contains('=') || line.any { it == '\n' || it == '\r' || it == '\u0000' } }) {
|
||||||
|
throw AgentException("INVALID_ENV", "Environment entries must be single KEY=VALUE lines without NUL bytes")
|
||||||
|
}
|
||||||
|
val state = load(context)
|
||||||
|
val key = if (persistent) "persistent" else "pending"
|
||||||
|
val merged = merge(strings(state.optJSONArray(key)), lines)
|
||||||
|
state.put(key, JSONArray(merged))
|
||||||
|
save(context, state)
|
||||||
|
state
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop lines: [scope] is "next", "persistent" or "all". */
|
||||||
|
fun clear(context: Context, scope: String): JSONObject = synchronized(lock) {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
val state = load(context)
|
||||||
|
when (scope) {
|
||||||
|
"next" -> state.put("pending", JSONArray())
|
||||||
|
"persistent" -> state.put("persistent", JSONArray())
|
||||||
|
"all" -> { state.put("pending", JSONArray()); state.put("persistent", JSONArray()); state.put("pendingOverrides", JSONArray()) }
|
||||||
|
else -> throw AgentException("INVALID_SCOPE", "Scope must be next, persistent or all")
|
||||||
|
}
|
||||||
|
save(context, state)
|
||||||
|
state
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Install agent-inbox/[name] as an override for the next session. */
|
||||||
|
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 '-'")
|
||||||
|
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")
|
||||||
|
val target = File(bin(context), name)
|
||||||
|
target.parentFile?.mkdirs()
|
||||||
|
val staged = File.createTempFile("override-", ".tmp", target.parentFile)
|
||||||
|
try {
|
||||||
|
Files.newInputStream(source.toPath(), READ, NOFOLLOW_LINKS).use { input -> staged.outputStream().use { input.copyTo(it) } }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
staged.delete()
|
||||||
|
throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
|
||||||
|
}
|
||||||
|
if (!staged.setExecutable(true, false) || !staged.renameTo(target)) {
|
||||||
|
staged.delete()
|
||||||
|
throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs")
|
||||||
|
}
|
||||||
|
source.delete()
|
||||||
|
val state = load(context)
|
||||||
|
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
|
||||||
|
save(context, state)
|
||||||
|
state.put("installed", "$GUEST_BIN/$name")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* At session start: the lines this session gets, after the user's droiddeck-env. Pending lines
|
||||||
|
* and overrides become this session's own, to be dropped by [endSession].
|
||||||
|
*/
|
||||||
|
fun beginSession(context: Context): List<String> = synchronized(lock) {
|
||||||
|
if (!AgentAccess.commandsAllowed(context)) {
|
||||||
|
revoke(context)
|
||||||
|
return@synchronized emptyList()
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
// Anything else there was left by a session that never reached endSession (the app died).
|
||||||
|
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)}"
|
||||||
|
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
|
||||||
|
withPath
|
||||||
|
}
|
||||||
|
|
||||||
|
fun revoke(context: Context) = synchronized(lock) {
|
||||||
|
val state = load(context)
|
||||||
|
for (key in listOf("pending", "active", "persistent", "pendingOverrides", "activeOverrides")) state.put(key, JSONArray())
|
||||||
|
save(context, state)
|
||||||
|
bin(context).listFiles()?.forEach { it.delete() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** At session end: this session's lines and override binaries go. */
|
||||||
|
fun endSession(context: Context) = synchronized(lock) {
|
||||||
|
val state = load(context)
|
||||||
|
val overrides = strings(state.optJSONArray("activeOverrides"))
|
||||||
|
val pending = strings(state.optJSONArray("pendingOverrides"))
|
||||||
|
val bin = bin(context)
|
||||||
|
overrides.filter { it !in pending }.forEach { File(bin, it).delete() }
|
||||||
|
state.put("active", JSONArray()).put("activeOverrides", JSONArray())
|
||||||
|
save(context, state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A PATH= line among [lines] (the user's or an agent's) is extended rather than replaced. */
|
||||||
|
private fun pathOf(lines: List<String>) =
|
||||||
|
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: BASE_PATH
|
||||||
|
|
||||||
|
private fun bin(context: Context): File {
|
||||||
|
val root = LinuxRuntime.rootDir(context).canonicalFile.toPath()
|
||||||
|
val directory = root.resolve(GUEST_BIN.removePrefix("/"))
|
||||||
|
var path = directory
|
||||||
|
while (path != root) {
|
||||||
|
if (Files.isSymbolicLink(path)) throw AgentException("OVERRIDE_FAILED", "The override directory must not contain symbolic links")
|
||||||
|
path = path.parent
|
||||||
|
}
|
||||||
|
return directory.toFile()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun merge(existing: List<String>, added: List<String>): List<String> {
|
||||||
|
val keys = added.map { it.substringBefore('=') }.toSet()
|
||||||
|
return existing.filter { it.substringBefore('=') !in keys } + added
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun strings(array: JSONArray?): List<String> =
|
||||||
|
if (array == null) emptyList() else List(array.length()) { array.optString(it) }.filter { it.isNotEmpty() }
|
||||||
|
|
||||||
|
private fun load(context: Context): JSONObject {
|
||||||
|
val file = File(context.filesDir, FILE)
|
||||||
|
val state = try { if (file.isFile) JSONObject(file.readText()) else JSONObject() } catch (e: Exception) { JSONObject() }
|
||||||
|
for (key in listOf("pending", "active", "persistent", "pendingOverrides", "activeOverrides")) {
|
||||||
|
if (!state.has(key)) state.put(key, JSONArray())
|
||||||
|
}
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun save(context: Context, state: JSONObject) {
|
||||||
|
val file = File(context.filesDir, FILE)
|
||||||
|
val staged = File(context.filesDir, "$FILE.tmp")
|
||||||
|
staged.writeText(state.toString())
|
||||||
|
if (!staged.renameTo(file)) {
|
||||||
|
staged.delete()
|
||||||
|
throw AgentException("ENV_WRITE_FAILED", "Could not save the debugging environment")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Typed writes to the app's SharedPreferences, for driving a settings matrix without the UI. */
|
||||||
|
object AgentPrefs {
|
||||||
|
fun set(context: Context, file: String, key: String, type: String, value: String?): JSONObject {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
validateFile(file)
|
||||||
|
if (file == AgentAccess.PROTECTED_PREFS) throw AgentException("PROTECTED_PREFS", "The agent preferences are set on the device only")
|
||||||
|
if (file.isBlank() || key.isBlank()) throw AgentException("INVALID_PREF", "file and key are required")
|
||||||
|
val prefs = context.getSharedPreferences(file, Context.MODE_PRIVATE)
|
||||||
|
val previous = prefs.all[key]
|
||||||
|
val editor = prefs.edit()
|
||||||
|
try {
|
||||||
|
when (type) {
|
||||||
|
"remove" -> editor.remove(key)
|
||||||
|
"bool" -> editor.putBoolean(key, value?.toBooleanStrictOrNull() ?: throw NumberFormatException("not true/false"))
|
||||||
|
"int" -> editor.putInt(key, value!!.toInt())
|
||||||
|
"long" -> editor.putLong(key, value!!.toLong())
|
||||||
|
"float" -> editor.putFloat(key, value!!.toFloat())
|
||||||
|
"string" -> editor.putString(key, value ?: "")
|
||||||
|
else -> throw AgentException("INVALID_PREF", "type must be bool, int, long, float, string or remove")
|
||||||
|
}
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
if (e is AgentException) throw e
|
||||||
|
throw AgentException("INVALID_PREF", "The value is not a $type")
|
||||||
|
}
|
||||||
|
if (!editor.commit()) throw AgentException("PREF_WRITE_FAILED", "Could not write $file/$key")
|
||||||
|
return JSONObject().put("file", file).put("key", key).put("type", type)
|
||||||
|
.put("previous", previous ?: JSONObject.NULL).put("value", prefs.all[key] ?: JSONObject.NULL)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun get(context: Context, file: String): JSONObject {
|
||||||
|
AgentAccess.requireCommands(context)
|
||||||
|
validateFile(file)
|
||||||
|
val all = context.getSharedPreferences(file, Context.MODE_PRIVATE).all
|
||||||
|
return JSONObject().put("file", file).put("values", JSONObject(all.mapValues { it.value ?: JSONObject.NULL }))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun validateFile(file: String) {
|
||||||
|
if (!Regex("[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}").matches(file)) {
|
||||||
|
throw AgentException("INVALID_PREF", "Preference files must be simple names")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.FileObserver
|
||||||
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.session.SessionEvents
|
||||||
|
import com.droiddeck.launcher.session.SessionState
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The app's side of the guest agent (tools/linuxfs/overlay/usr/local/bin/droiddeck-agent): requests
|
||||||
|
* go in as files under the session root's agent directory and answers come back the same way, so
|
||||||
|
* whatever runs does so inside the live session with its own environment.
|
||||||
|
*/
|
||||||
|
object AgentGuest {
|
||||||
|
private const val TAG = "AgentGuest"
|
||||||
|
private const val POLL_MS = 50L
|
||||||
|
private val lock = Any()
|
||||||
|
private var observer: FileObserver? = null
|
||||||
|
private var lastFocusKey: String? = null
|
||||||
|
|
||||||
|
fun dir(context: Context) = File(LinuxRuntime.sessionRoot(context), "agent")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Before each session: nothing of the last one's daemon, answers or focus may be read as
|
||||||
|
* current. Then watch for the new daemon's hello and focus snapshots, which go into the
|
||||||
|
* session's events.jsonl.
|
||||||
|
*/
|
||||||
|
fun reset(context: Context) {
|
||||||
|
synchronized(lock) {
|
||||||
|
observer?.stopWatching()
|
||||||
|
observer = null
|
||||||
|
lastFocusKey = null
|
||||||
|
val dir = dir(context)
|
||||||
|
dir.deleteRecursively()
|
||||||
|
dir.mkdirs()
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
observer = object : FileObserver(dir.path, MOVED_TO or CLOSE_WRITE) {
|
||||||
|
override fun onEvent(event: Int, path: String?) {
|
||||||
|
when (path) {
|
||||||
|
"hello.json" -> readJson(File(dir, path))?.let {
|
||||||
|
SessionEvents.record("agent.ready", mapOf("pid" to it.optInt("pid"), "focus" to it.optBoolean("focus")))
|
||||||
|
}
|
||||||
|
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.also { it.startWatching() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** At the end of a session: no more events for a folder that is being closed. */
|
||||||
|
fun stop() {
|
||||||
|
synchronized(lock) {
|
||||||
|
observer?.stopWatching()
|
||||||
|
observer = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun recordFocus(snapshot: JSONObject) {
|
||||||
|
val fields = linkedMapOf<String, Any?>(
|
||||||
|
"focusedApp" to snapshot.opt("focusedApp"),
|
||||||
|
"focusableApps" to snapshot.optJSONArray("focusableApps")?.toString(),
|
||||||
|
"baselayerAppIds" to snapshot.optJSONArray("baselayerAppIds")?.toString(),
|
||||||
|
)
|
||||||
|
val key = fields.values.joinToString("|")
|
||||||
|
synchronized(lock) {
|
||||||
|
if (key == lastFocusKey) return
|
||||||
|
lastFocusKey = key
|
||||||
|
}
|
||||||
|
SessionEvents.record("focus.changed", fields + ("seq" to snapshot.optInt("seq")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The daemon's hello, when it is running in the current session. */
|
||||||
|
fun hello(context: Context): JSONObject? {
|
||||||
|
if (!SessionState.running) return null
|
||||||
|
val hello = readJson(File(dir(context), "hello.json")) ?: return null
|
||||||
|
val pid = hello.optInt("pid", -1)
|
||||||
|
return hello.takeIf { pid > 1 && File("/proc/$pid").exists() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The newest focus snapshot the daemon published, when a session is running. */
|
||||||
|
fun focus(context: Context): JSONObject? =
|
||||||
|
if (SessionState.running) readJson(File(dir(context), "focus.json")) else null
|
||||||
|
|
||||||
|
/** Send one request and wait for its answer. Throws [AgentException] with a stable code. */
|
||||||
|
fun call(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
|
||||||
|
if (request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context)
|
||||||
|
if (!SessionState.running) throw AgentException("NO_ACTIVE_SESSION", "There is no running session")
|
||||||
|
hello(context) ?: throw AgentException("AGENT_UNAVAILABLE", "The guest agent is not running in this session (yet)")
|
||||||
|
val dir = dir(context)
|
||||||
|
val requests = File(dir, "req").apply { mkdirs() }
|
||||||
|
val answers = File(dir, "resp").apply { mkdirs() }
|
||||||
|
val id = UUID.randomUUID().toString()
|
||||||
|
val staged = File(requests, "$id.json.tmp")
|
||||||
|
val published = File(requests, "$id.json")
|
||||||
|
val answer = File(answers, "$id.json")
|
||||||
|
staged.writeText(request.toString())
|
||||||
|
if (!staged.renameTo(published)) {
|
||||||
|
staged.delete()
|
||||||
|
throw AgentException("AGENT_UNAVAILABLE", "Could not hand the request to the guest agent")
|
||||||
|
}
|
||||||
|
val deadline = System.currentTimeMillis() + timeoutMs
|
||||||
|
while (System.currentTimeMillis() < deadline) {
|
||||||
|
if (answer.isFile) {
|
||||||
|
if (answer.length() > 1024 * 1024) {
|
||||||
|
answer.delete()
|
||||||
|
throw AgentException("RESPONSE_TOO_LARGE", "The guest response exceeds 1 MiB")
|
||||||
|
}
|
||||||
|
val result = readJson(answer)
|
||||||
|
answer.delete()
|
||||||
|
return result ?: throw AgentException("INVALID_AGENT_RESPONSE", "The guest agent's answer was not JSON")
|
||||||
|
}
|
||||||
|
Thread.sleep(POLL_MS)
|
||||||
|
}
|
||||||
|
published.delete()
|
||||||
|
Log.w(TAG, "no answer to ${request.optString("kind")} in ${timeoutMs}ms")
|
||||||
|
throw AgentException("TIMEOUT", "The guest agent did not answer within ${timeoutMs / 1000}s")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readJson(file: File): JSONObject? = try {
|
||||||
|
if (file.isFile && file.length() <= 1024 * 1024) JSONObject(file.readText()) else null
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.input.PadState
|
||||||
|
import com.droiddeck.launcher.session.SessionState
|
||||||
|
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Input into the running session the way a player gives it: keys and touches through the
|
||||||
|
* compositor (what the session screen sends), and the virtual pad through the same PadBridge the
|
||||||
|
* on-screen controls drive, so games that ignore touch still see a controller.
|
||||||
|
*/
|
||||||
|
object AgentInput {
|
||||||
|
/** Out of the way of real fingers, which Android numbers from 0. */
|
||||||
|
private const val TOUCH_ID = 9
|
||||||
|
private const val TOUCH_SCALE_X = 1919f
|
||||||
|
private const val TOUCH_SCALE_Y = 1079f
|
||||||
|
|
||||||
|
fun handle(request: JSONObject): JSONObject {
|
||||||
|
if (!SessionState.running || !SessionState.firstFrameSeen) {
|
||||||
|
throw AgentException("SESSION_NOT_READY", "Input needs a running session that has drawn its first frame")
|
||||||
|
}
|
||||||
|
return when (val type = request.optString("type")) {
|
||||||
|
"key" -> key(request)
|
||||||
|
"text" -> text(request)
|
||||||
|
"tap" -> tap(request)
|
||||||
|
"swipe" -> swipe(request)
|
||||||
|
"pad" -> pad(request)
|
||||||
|
"stick" -> stick(request)
|
||||||
|
"trigger" -> trigger(request)
|
||||||
|
else -> throw AgentException("INVALID_INPUT", "Unknown input type '$type'")
|
||||||
|
}.put("ok", true).put("command", "input").put("type", request.optString("type"))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun key(request: JSONObject): JSONObject {
|
||||||
|
val name = request.optString("key")
|
||||||
|
val code = KEYS[name.uppercase()] ?: name.toIntOrNull()
|
||||||
|
?: throw AgentException("INVALID_INPUT", "Unknown key '$name' (a name such as ENTER or an evdev code)")
|
||||||
|
val modifiers = request.optJSONArray("modifiers")?.let { array ->
|
||||||
|
List(array.length()) { i ->
|
||||||
|
KEYS[array.optString(i).uppercase()] ?: throw AgentException("INVALID_INPUT", "Unknown modifier '${array.optString(i)}'")
|
||||||
|
}
|
||||||
|
}.orEmpty()
|
||||||
|
when (val action = request.optString("action", "tap")) {
|
||||||
|
"down" -> WaylandCompositor.nativeSendKey(code, 1)
|
||||||
|
"up" -> WaylandCompositor.nativeSendKey(code, 0)
|
||||||
|
"tap" -> {
|
||||||
|
modifiers.forEach { WaylandCompositor.nativeSendKey(it, 1) }
|
||||||
|
WaylandCompositor.nativeSendKey(code, 1)
|
||||||
|
hold(request, 40)
|
||||||
|
WaylandCompositor.nativeSendKey(code, 0)
|
||||||
|
modifiers.asReversed().forEach { WaylandCompositor.nativeSendKey(it, 0) }
|
||||||
|
}
|
||||||
|
else -> throw AgentException("INVALID_INPUT", "Key action '$action' is not tap, down or up")
|
||||||
|
}
|
||||||
|
return JSONObject().put("code", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Typed as key presses (US layout), which reaches X programs that have no text-input support. */
|
||||||
|
private fun text(request: JSONObject): JSONObject {
|
||||||
|
val text = request.optString("text")
|
||||||
|
if (request.optBoolean("commit")) {
|
||||||
|
WaylandCompositor.textInputCommit(text)
|
||||||
|
return JSONObject().put("length", text.length).put("via", "text-input")
|
||||||
|
}
|
||||||
|
val missing = text.filter { TYPED[it] == null }
|
||||||
|
if (missing.isNotEmpty()) throw AgentException("INVALID_INPUT", "Cannot type '${missing.toSet().joinToString("")}' as keys; use commit")
|
||||||
|
val delay = request.optLong("delayMs", 15)
|
||||||
|
for (ch in text) {
|
||||||
|
val (code, shift) = TYPED.getValue(ch)
|
||||||
|
if (shift) WaylandCompositor.nativeSendKey(KEYS.getValue("LEFTSHIFT"), 1)
|
||||||
|
WaylandCompositor.nativeSendKey(code, 1)
|
||||||
|
WaylandCompositor.nativeSendKey(code, 0)
|
||||||
|
if (shift) WaylandCompositor.nativeSendKey(KEYS.getValue("LEFTSHIFT"), 0)
|
||||||
|
Thread.sleep(delay)
|
||||||
|
}
|
||||||
|
return JSONObject().put("length", text.length).put("via", "keys")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun tap(request: JSONObject): JSONObject {
|
||||||
|
val (x, y) = point(request, "x", "y")
|
||||||
|
WaylandCompositor.nativeSendTouch(0, TOUCH_ID, x, y)
|
||||||
|
hold(request, 60)
|
||||||
|
WaylandCompositor.nativeSendTouch(2, TOUCH_ID, x, y)
|
||||||
|
return JSONObject().put("touch", org.json.JSONArray().put(x).put(y))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun swipe(request: JSONObject): JSONObject {
|
||||||
|
val (x1, y1) = point(request, "x", "y")
|
||||||
|
val (x2, y2) = point(request, "x2", "y2")
|
||||||
|
val duration = request.optLong("durationMs", 300).coerceIn(16, 10_000)
|
||||||
|
val steps = (duration / 16).toInt().coerceAtLeast(2)
|
||||||
|
WaylandCompositor.nativeSendTouch(0, TOUCH_ID, x1, y1)
|
||||||
|
for (i in 1..steps) {
|
||||||
|
Thread.sleep(duration / steps)
|
||||||
|
WaylandCompositor.nativeSendTouch(1, TOUCH_ID, x1 + (x2 - x1) * i / steps, y1 + (y2 - y1) * i / steps)
|
||||||
|
}
|
||||||
|
WaylandCompositor.nativeSendTouch(2, TOUCH_ID, x2, y2)
|
||||||
|
return JSONObject().put("from", org.json.JSONArray().put(x1).put(y1)).put("to", org.json.JSONArray().put(x2).put(y2))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A point in the compositor's touch space (0..1919 x 0..1079 whatever the session's size), from
|
||||||
|
* the session's output pixels (space "output", the default: what the guest draws at) or 0..1
|
||||||
|
* fractions (space "fraction").
|
||||||
|
*/
|
||||||
|
private fun point(request: JSONObject, xKey: String, yKey: String): Pair<Int, Int> {
|
||||||
|
if (!request.has(xKey) || !request.has(yKey)) throw AgentException("INVALID_INPUT", "$xKey and $yKey are required")
|
||||||
|
val x = request.getDouble(xKey)
|
||||||
|
val y = request.getDouble(yKey)
|
||||||
|
val (fx, fy) = when (val space = request.optString("space", "output")) {
|
||||||
|
"fraction" -> x to y
|
||||||
|
"output" -> {
|
||||||
|
val (w, h) = SessionState.outputSize
|
||||||
|
x / (w - 1).coerceAtLeast(1) to y / (h - 1).coerceAtLeast(1)
|
||||||
|
}
|
||||||
|
else -> throw AgentException("INVALID_INPUT", "space '$space' is not output or fraction")
|
||||||
|
}
|
||||||
|
return (fx.coerceIn(0.0, 1.0) * TOUCH_SCALE_X).toInt() to (fy.coerceIn(0.0, 1.0) * TOUCH_SCALE_Y).toInt()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pad(request: JSONObject): JSONObject {
|
||||||
|
val bridge = SessionState.padBridge ?: throw AgentException("NO_PAD", "The session has no virtual pad")
|
||||||
|
val name = request.optString("button").lowercase()
|
||||||
|
if (name == "qam") {
|
||||||
|
bridge.triggerQam()
|
||||||
|
return JSONObject().put("button", name)
|
||||||
|
}
|
||||||
|
val button = BUTTONS[name]
|
||||||
|
if (button == null && name !in DPAD) throw AgentException("INVALID_INPUT", "Unknown pad button '$name'")
|
||||||
|
val apply = { s: PadState, down: Boolean ->
|
||||||
|
when (name) {
|
||||||
|
"up" -> s.up = down
|
||||||
|
"down" -> s.down = down
|
||||||
|
"left" -> s.left = down
|
||||||
|
"right" -> s.right = down
|
||||||
|
else -> s.press(button!!, down)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
when (val action = request.optString("action", "tap")) {
|
||||||
|
"down" -> bridge.applyTouch { apply(it, true) }
|
||||||
|
"up" -> bridge.applyTouch { apply(it, false) }
|
||||||
|
"tap" -> {
|
||||||
|
bridge.applyTouch { apply(it, true) }
|
||||||
|
hold(request, 120)
|
||||||
|
bridge.applyTouch { apply(it, false) }
|
||||||
|
}
|
||||||
|
else -> throw AgentException("INVALID_INPUT", "Pad action '$action' is not tap, down or up")
|
||||||
|
}
|
||||||
|
return JSONObject().put("button", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stick(request: JSONObject): JSONObject {
|
||||||
|
val bridge = SessionState.padBridge ?: throw AgentException("NO_PAD", "The session has no virtual pad")
|
||||||
|
val right = request.optString("stick", "left") == "right"
|
||||||
|
val x = request.optDouble("x", 0.0).toFloat().coerceIn(-1f, 1f)
|
||||||
|
val y = request.optDouble("y", 0.0).toFloat().coerceIn(-1f, 1f)
|
||||||
|
bridge.applyTouch { if (right) { it.rightX = x; it.rightY = y } else { it.leftX = x; it.leftY = y } }
|
||||||
|
hold(request, 300)
|
||||||
|
bridge.applyTouch { if (right) { it.rightX = 0f; it.rightY = 0f } else { it.leftX = 0f; it.leftY = 0f } }
|
||||||
|
return JSONObject().put("stick", if (right) "right" else "left")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun trigger(request: JSONObject): JSONObject {
|
||||||
|
val bridge = SessionState.padBridge ?: throw AgentException("NO_PAD", "The session has no virtual pad")
|
||||||
|
val right = request.optString("trigger", "right") == "right"
|
||||||
|
val value = request.optDouble("value", 1.0).toFloat().coerceIn(0f, 1f)
|
||||||
|
bridge.applyTouch { if (right) it.rightTrigger = value else it.leftTrigger = value }
|
||||||
|
hold(request, 200)
|
||||||
|
bridge.applyTouch { if (right) it.rightTrigger = 0f else it.leftTrigger = 0f }
|
||||||
|
return JSONObject().put("trigger", if (right) "right" else "left")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hold(request: JSONObject, defaultMs: Long) =
|
||||||
|
Thread.sleep(request.optLong("holdMs", defaultMs).coerceIn(0, 10_000))
|
||||||
|
|
||||||
|
private val DPAD = setOf("up", "down", "left", "right")
|
||||||
|
|
||||||
|
private val BUTTONS = mapOf(
|
||||||
|
"a" to PadState.A, "b" to PadState.B, "x" to PadState.X, "y" to PadState.Y,
|
||||||
|
"lb" to PadState.LB, "rb" to PadState.RB, "select" to PadState.SELECT, "back" to PadState.SELECT,
|
||||||
|
"start" to PadState.START, "menu" to PadState.START, "l3" to PadState.L3, "r3" to PadState.R3,
|
||||||
|
"guide" to PadState.GUIDE, "steam" to PadState.GUIDE,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Linux evdev codes (input-event-codes.h) by name. */
|
||||||
|
private val KEYS: Map<String, Int> = buildMap {
|
||||||
|
"1234567890".forEachIndexed { i, c -> put(c.toString(), 2 + i) }
|
||||||
|
"QWERTYUIOP".forEachIndexed { i, c -> put(c.toString(), 16 + i) }
|
||||||
|
"ASDFGHJKL".forEachIndexed { i, c -> put(c.toString(), 30 + i) }
|
||||||
|
"ZXCVBNM".forEachIndexed { i, c -> put(c.toString(), 44 + i) }
|
||||||
|
(1..10).forEach { put("F$it", 58 + it) }
|
||||||
|
put("F11", 87); put("F12", 88)
|
||||||
|
putAll(mapOf(
|
||||||
|
"ESC" to 1, "MINUS" to 12, "EQUAL" to 13, "BACKSPACE" to 14, "TAB" to 15, "LEFTBRACE" to 26,
|
||||||
|
"RIGHTBRACE" to 27, "ENTER" to 28, "LEFTCTRL" to 29, "SEMICOLON" to 39, "APOSTROPHE" to 40,
|
||||||
|
"GRAVE" to 41, "LEFTSHIFT" to 42, "BACKSLASH" to 43, "COMMA" to 51, "DOT" to 52, "SLASH" to 53,
|
||||||
|
"RIGHTSHIFT" to 54, "LEFTALT" to 56, "SPACE" to 57, "CAPSLOCK" to 58, "RIGHTCTRL" to 97,
|
||||||
|
"RIGHTALT" to 100, "HOME" to 102, "UP" to 103, "PAGEUP" to 104, "LEFT" to 105, "RIGHT" to 106,
|
||||||
|
"END" to 107, "DOWN" to 108, "PAGEDOWN" to 109, "INSERT" to 110, "DELETE" to 111, "LEFTMETA" to 125,
|
||||||
|
"CTRL" to 29, "SHIFT" to 42, "ALT" to 56, "META" to 125, "SUPER" to 125, "RETURN" to 28, "ESCAPE" to 1,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** US-layout characters as (evdev code, shift). */
|
||||||
|
private val TYPED: Map<Char, Pair<Int, Boolean>> = buildMap {
|
||||||
|
for (c in 'a'..'z') put(c, KEYS.getValue(c.uppercase()) to false)
|
||||||
|
for (c in 'A'..'Z') put(c, KEYS.getValue(c.toString()) to true)
|
||||||
|
for (c in '0'..'9') put(c, KEYS.getValue(c.toString()) to false)
|
||||||
|
"!@#$%^&*()".forEachIndexed { i, c -> put(c, KEYS.getValue(((i + 1) % 10).toString()) to true) }
|
||||||
|
putAll(mapOf(
|
||||||
|
' ' to (57 to false), '\n' to (28 to false), '\t' to (15 to false),
|
||||||
|
'-' to (12 to false), '_' to (12 to true), '=' to (13 to false), '+' to (13 to true),
|
||||||
|
'[' to (26 to false), '{' to (26 to true), ']' to (27 to false), '}' to (27 to true),
|
||||||
|
';' to (39 to false), ':' to (39 to true), '\'' to (40 to false), '"' to (40 to true),
|
||||||
|
'`' to (41 to false), '~' to (41 to true), '\\' to (43 to false), '|' to (43 to true),
|
||||||
|
',' to (51 to false), '<' to (51 to true), '.' to (52 to false), '>' to (52 to true),
|
||||||
|
'/' to (53 to false), '?' to (53 to true),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,6 +38,10 @@ class AgentStartActivity : Activity() {
|
|||||||
Log.e(TAG, "missing agent start request")
|
Log.e(TAG, "missing agent start request")
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
if (encoded.length > AgentAccess.MAX_REQUEST_CHARS) {
|
||||||
|
Log.w(TAG, "agent start request is too large")
|
||||||
|
return null
|
||||||
|
}
|
||||||
return try {
|
return try {
|
||||||
JSONObject(String(Base64.decode(encoded, Base64.DEFAULT), Charsets.UTF_8))
|
JSONObject(String(Base64.decode(encoded, Base64.DEFAULT), Charsets.UTF_8))
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -47,6 +51,13 @@ class AgentStartActivity : Activity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun startSession(request: JSONObject) {
|
private fun startSession(request: JSONObject) {
|
||||||
|
try {
|
||||||
|
AgentAccess.requireStart(this, request)
|
||||||
|
} catch (e: AgentException) {
|
||||||
|
Log.w(TAG, e.code)
|
||||||
|
finish()
|
||||||
|
return
|
||||||
|
}
|
||||||
val requestedMode = request.optString("mode")
|
val requestedMode = request.optString("mode")
|
||||||
val sessionMode = when (requestedMode) {
|
val sessionMode = when (requestedMode) {
|
||||||
"steam" -> SessionService.MODE_STEAM
|
"steam" -> SessionService.MODE_STEAM
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.view.inspector.WindowInspector
|
||||||
|
import androidx.compose.ui.platform.ViewRootForTest
|
||||||
|
import androidx.compose.ui.semantics.SemanticsActions
|
||||||
|
import androidx.compose.ui.semantics.SemanticsConfiguration
|
||||||
|
import androidx.compose.ui.semantics.SemanticsNode
|
||||||
|
import androidx.compose.ui.semantics.SemanticsProperties
|
||||||
|
import androidx.compose.ui.semantics.getOrNull
|
||||||
|
import androidx.compose.ui.text.AnnotatedString
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.util.concurrent.CountDownLatch
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.concurrent.atomic.AtomicReference
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The app's own UI as an agent sees it: every Compose node in every window of the process (popups
|
||||||
|
* and menus included), read from Compose's semantics rather than through UI Automator, which on a
|
||||||
|
* dual-screen device dumps whichever window has focus - often not this app's. Nodes carry their
|
||||||
|
* test tag (ui/TestTags.kt), text, content description, role, state and on-screen bounds; click
|
||||||
|
* and set-text act on a node by tag or text, so a test needs no coordinates.
|
||||||
|
*/
|
||||||
|
object AgentUi {
|
||||||
|
private const val TIMEOUT_MS = 5_000L
|
||||||
|
/** Setup's Debugging tools toggle: the bridge never acts on its own gate (AgentAccess). */
|
||||||
|
private const val GATE_TAG = "setting-agent-commands"
|
||||||
|
|
||||||
|
fun handle(request: JSONObject): JSONObject = when (val op = request.optString("op", "dump")) {
|
||||||
|
"dump" -> onMain { dump(request.optBoolean("all")) }
|
||||||
|
"click" -> onMain { act(request) { node -> perform(node, SemanticsActions.OnClick) } }
|
||||||
|
"set-text" -> onMain {
|
||||||
|
val text = request.optString("text")
|
||||||
|
act(request) { node ->
|
||||||
|
node.config.getOrNull(SemanticsActions.SetText)?.action?.invoke(AnnotatedString(text))
|
||||||
|
?: throw AgentException("NOT_EDITABLE", "That node takes no text")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> throw AgentException("INVALID_REQUEST", "ui op '$op' is not dump, click or set-text")
|
||||||
|
}.put("ok", true).put("command", "ui")
|
||||||
|
|
||||||
|
private fun roots(): List<Pair<View, ViewRootForTest>> {
|
||||||
|
if (Build.VERSION.SDK_INT < 29) throw AgentException("UNSUPPORTED", "The UI dump needs Android 10 or later")
|
||||||
|
val found = mutableListOf<Pair<View, ViewRootForTest>>()
|
||||||
|
fun walk(view: View) {
|
||||||
|
if (view is ViewRootForTest) found += view to view
|
||||||
|
if (view is ViewGroup) for (i in 0 until view.childCount) walk(view.getChildAt(i))
|
||||||
|
}
|
||||||
|
WindowInspector.getGlobalWindowViews().filter { it.isAttachedToWindow && it.isShown }.forEach(::walk)
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dump(all: Boolean): JSONObject {
|
||||||
|
val windows = JSONArray()
|
||||||
|
for ((view, root) in roots()) {
|
||||||
|
val nodes = JSONArray()
|
||||||
|
val location = IntArray(2).also { view.getLocationOnScreen(it) }
|
||||||
|
fun visit(node: SemanticsNode) {
|
||||||
|
val json = describe(node, location)
|
||||||
|
if (all || json.has("tag") || json.has("text") || json.has("description") || json.optBoolean("clickable")) nodes.put(json)
|
||||||
|
node.children.forEach(::visit)
|
||||||
|
}
|
||||||
|
visit(root.semanticsOwner.rootSemanticsNode)
|
||||||
|
windows.put(JSONObject()
|
||||||
|
.put("display", view.display?.displayId ?: JSONObject.NULL)
|
||||||
|
.put("window", view.rootView.javaClass.simpleName)
|
||||||
|
.put("nodes", nodes))
|
||||||
|
}
|
||||||
|
return JSONObject().put("windows", windows)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun describe(node: SemanticsNode, origin: IntArray): JSONObject {
|
||||||
|
val config = node.config
|
||||||
|
val json = JSONObject().put("id", node.id)
|
||||||
|
config.getOrNull(SemanticsProperties.TestTag)?.let { json.put("tag", it) }
|
||||||
|
val text = textFields(config)
|
||||||
|
text.keys().forEach { json.put(it, text.get(it)) }
|
||||||
|
config.getOrNull(SemanticsProperties.Role)?.let { json.put("role", it.toString()) }
|
||||||
|
config.getOrNull(SemanticsProperties.ToggleableState)?.let { json.put("toggle", it.name) }
|
||||||
|
config.getOrNull(SemanticsProperties.Selected)?.let { json.put("selected", it) }
|
||||||
|
config.getOrNull(SemanticsProperties.Focused)?.let { json.put("focused", it) }
|
||||||
|
if (config.contains(SemanticsProperties.Disabled)) json.put("disabled", true)
|
||||||
|
if (config.contains(SemanticsActions.OnClick)) json.put("clickable", true)
|
||||||
|
if (config.contains(SemanticsActions.SetText)) json.put("editable", true)
|
||||||
|
val b = node.boundsInWindow
|
||||||
|
json.put("bounds", JSONArray()
|
||||||
|
.put(origin[0] + b.left.toInt()).put(origin[1] + b.top.toInt())
|
||||||
|
.put(origin[0] + b.right.toInt()).put(origin[1] + b.bottom.toInt()))
|
||||||
|
return json
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun textFields(config: SemanticsConfiguration): JSONObject {
|
||||||
|
val password = config.contains(SemanticsProperties.Password)
|
||||||
|
val json = JSONObject()
|
||||||
|
for ((key, value) in listOf(
|
||||||
|
"text" to config.getOrNull(SemanticsProperties.Text)?.joinToString(" ") { it.text },
|
||||||
|
"editableText" to config.getOrNull(SemanticsProperties.EditableText)?.text,
|
||||||
|
"description" to config.getOrNull(SemanticsProperties.ContentDescription)?.joinToString(" "),
|
||||||
|
"state" to config.getOrNull(SemanticsProperties.StateDescription),
|
||||||
|
)) value?.let { json.put(key, if (password) "<redacted>" else it) }
|
||||||
|
return json
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The node a request names by "tag" (exact) or "match" (text or description containing it,
|
||||||
|
* ignoring case); "index" picks among several, in tree order.
|
||||||
|
*/
|
||||||
|
private fun act(request: JSONObject, action: (SemanticsNode) -> Unit): JSONObject {
|
||||||
|
val tag = request.optString("tag").takeIf { it.isNotEmpty() }
|
||||||
|
val text = if (tag == null) request.optString("match").takeIf { it.isNotEmpty() } else null
|
||||||
|
if (tag == null && text == null) throw AgentException("INVALID_REQUEST", "Name the node by tag or match")
|
||||||
|
val matches = mutableListOf<Pair<SemanticsNode, IntArray>>()
|
||||||
|
for ((view, root) in roots()) {
|
||||||
|
val origin = IntArray(2).also { view.getLocationOnScreen(it) }
|
||||||
|
fun visit(node: SemanticsNode) {
|
||||||
|
val config = node.config
|
||||||
|
val hit = if (tag != null) config.getOrNull(SemanticsProperties.TestTag) == tag
|
||||||
|
else (config.getOrNull(SemanticsProperties.Text)?.joinToString(" ") { it.text }
|
||||||
|
?: config.getOrNull(SemanticsProperties.ContentDescription)?.joinToString(" ") ?: "")
|
||||||
|
.contains(text!!, ignoreCase = true)
|
||||||
|
if (hit) matches += node to origin
|
||||||
|
node.children.forEach(::visit)
|
||||||
|
}
|
||||||
|
visit(root.semanticsOwner.rootSemanticsNode)
|
||||||
|
}
|
||||||
|
val index = request.optInt("index", 0)
|
||||||
|
val (node, origin) = matches.getOrNull(index)
|
||||||
|
?: throw AgentException("NO_SUCH_NODE", "No node with ${if (tag != null) "tag '$tag'" else "text '$text'"} (${matches.size} found)")
|
||||||
|
if (generateSequence(node) { it.parent }.any { it.config.getOrNull(SemanticsProperties.TestTag) == GATE_TAG }) {
|
||||||
|
throw AgentException("PROTECTED_CONTROL", "Debugging tools are switched on the device only")
|
||||||
|
}
|
||||||
|
action(node)
|
||||||
|
return JSONObject().put("matches", matches.size).put("node", describe(node, origin))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun perform(node: SemanticsNode, key: androidx.compose.ui.semantics.SemanticsPropertyKey<androidx.compose.ui.semantics.AccessibilityAction<() -> Boolean>>) {
|
||||||
|
val action = node.config.getOrNull(key)?.action ?: throw AgentException("NOT_CLICKABLE", "That node has no click action")
|
||||||
|
action()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T> onMain(block: () -> T): T {
|
||||||
|
if (Looper.myLooper() == Looper.getMainLooper()) return block()
|
||||||
|
val result = AtomicReference<Result<T>>()
|
||||||
|
val done = CountDownLatch(1)
|
||||||
|
Handler(Looper.getMainLooper()).post {
|
||||||
|
result.set(runCatching(block))
|
||||||
|
done.countDown()
|
||||||
|
}
|
||||||
|
if (!done.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) throw AgentException("TIMEOUT", "The UI thread did not answer")
|
||||||
|
return result.get().getOrThrow()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,7 +28,9 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
/** Where the guest reaches the daemon; the session exports PULSE_SERVER=unix:<this>. */
|
/** Where the guest reaches the daemon; the session exports PULSE_SERVER=unix:<this>. */
|
||||||
public static final String SOCKET_NAME = "PS0";
|
public static final String SOCKET_NAME = "PS0";
|
||||||
/** Identifies the bundled pulseaudio.tzst; a change here re-unpacks it over what a device has. */
|
/** Identifies the bundled pulseaudio.tzst; a change here re-unpacks it over what a device has. */
|
||||||
private static final String BUNDLE_STAMP = "2026-09-23-pa13-suspend-r5";
|
private static final String BUNDLE_STAMP = "2026-10-08-pa13-directaudio-native";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private final File workingDir;
|
private final File workingDir;
|
||||||
/** Where the daemon's own output is kept for this session, or null for logcat only. */
|
/** Where the daemon's own output is kept for this session, or null for logcat only. */
|
||||||
@@ -40,8 +42,6 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
* turns that one stream into a source the client can see, named DirectAudioMic.
|
* turns that one stream into a source the client can see, named DirectAudioMic.
|
||||||
*/
|
*/
|
||||||
private final String micFifoPath;
|
private final String micFifoPath;
|
||||||
/** The DirectAudio relay's socket when the client's output should go through it, else null. */
|
|
||||||
private String relaySocketPath;
|
|
||||||
private volatile int pid = -1;
|
private volatile int pid = -1;
|
||||||
|
|
||||||
public PulseAudioComponent(Context context) {
|
public PulseAudioComponent(Context context) {
|
||||||
@@ -54,15 +54,6 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
this.micFifoPath = micFifoPath;
|
this.micFifoPath = micFifoPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Route the daemon's output through the DirectAudio relay at this socket instead of an AAudio
|
|
||||||
* stream of its own. The relay owns the stream outside proot, with its adaptive buffer; the
|
|
||||||
* daemon only fills a shared ring. Set before {@link #start()}; the relay may start later.
|
|
||||||
*/
|
|
||||||
public void setRelaySocket(String path) {
|
|
||||||
this.relaySocketPath = path;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** CRC-32 of the bundled pulseaudio.tzst, or "?" if it cannot be read. About 600 KB; cheap. */
|
/** CRC-32 of the bundled pulseaudio.tzst, or "?" if it cannot be read. About 600 KB; cheap. */
|
||||||
private String bundleChecksum() {
|
private String bundleChecksum() {
|
||||||
java.util.zip.CRC32 crc = new java.util.zip.CRC32();
|
java.util.zip.CRC32 crc = new java.util.zip.CRC32();
|
||||||
@@ -106,6 +97,7 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
String have = FileUtils.readString(stamp);
|
String have = FileUtils.readString(stamp);
|
||||||
String want = BUNDLE_STAMP + "-" + bundleChecksum();
|
String want = BUNDLE_STAMP + "-" + bundleChecksum();
|
||||||
if (!new File(modulesDir, "arm64/module-aaudio-sink.so").isFile()
|
if (!new File(modulesDir, "arm64/module-aaudio-sink.so").isFile()
|
||||||
|
|| !new File(modulesDir, "arm64/module-directaudio-native-sink.so").isFile()
|
||||||
|| !new File(workingDir, "pactl").isFile()
|
|| !new File(workingDir, "pactl").isFile()
|
||||||
|| have == null || !want.equals(have.trim())) {
|
|| have == null || !want.equals(have.trim())) {
|
||||||
Log.i(TAG, "unpacking pulseaudio.tzst (" + want + "; had " + have + ")");
|
Log.i(TAG, "unpacking pulseaudio.tzst (" + want + "; had " + have + ")");
|
||||||
@@ -139,14 +131,15 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
// the sink to 0% and the session plays silence.
|
// the sink to 0% and the session plays silence.
|
||||||
// The sink's name is what the client's Audio settings show as the output device, so it
|
// The sink's name is what the client's Audio settings show as the output device, so it
|
||||||
// says which road the sound takes.
|
// says which road the sound takes.
|
||||||
if (relaySocketPath != null && !relaySocketPath.isEmpty()) {
|
// The client's sound: DirectAudio's own engine, in this process, one step from Android.
|
||||||
config.add("load-module module-directaudio-sink sink_name=DirectAudio socket=\"" + relaySocketPath + "\" performance_mode=1 adaptive=1 volume=1.0");
|
// decay=0: shrinking the device buffer after a quiet spell probes below what works and that
|
||||||
config.add("set-default-sink DirectAudio");
|
// probe is a click; the client plays menus. Between .nofail and .fail a module that cannot
|
||||||
} else {
|
// open its stream does not take the daemon down; ensureClientSink() then loads the plain
|
||||||
// The classic sink: the adaptive AAudio module 0.1.5 shipped, unchanged.
|
// AAudio sink in its place.
|
||||||
config.add("load-module module-aaudio-classic-sink sink_name=AAudioSink performance_mode=1 adaptive=1 volume=1.0");
|
config.add(".nofail");
|
||||||
config.add("set-default-sink AAudioSink");
|
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("set-default-sink DirectAudio");
|
||||||
|
config.add(".fail");
|
||||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||||
// The format is the helper's, fixed at s16le/48000/mono: it resamples when the device
|
// The format is the helper's, fixed at s16le/48000/mono: it resamples when the device
|
||||||
// grants another input rate, so the daemon is never told a rate the bytes are not.
|
// grants another input rate, so the daemon is never told a rate the bytes are not.
|
||||||
@@ -178,6 +171,74 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
Log.i(TAG, line);
|
Log.i(TAG, line);
|
||||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||||
});
|
});
|
||||||
|
Thread guard = new Thread(() -> ensureClientSink(out), "pulse-sink-guard");
|
||||||
|
guard.setDaemon(true);
|
||||||
|
guard.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The fallback: once the daemon answers, if the DirectAudio sink is not
|
||||||
|
* there (the module failed to load or to open its stream), load the plain AAudio sink so the
|
||||||
|
* client is never left without an output. Says so in the audio log either way.
|
||||||
|
*/
|
||||||
|
private void ensureClientSink(java.io.PrintWriter out) {
|
||||||
|
long deadline = System.currentTimeMillis() + 15000L;
|
||||||
|
String sinks = null;
|
||||||
|
while (System.currentTimeMillis() < deadline && pid > 1) {
|
||||||
|
if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
|
||||||
|
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
||||||
|
}
|
||||||
|
String line;
|
||||||
|
if (sinks == null) {
|
||||||
|
line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
|
||||||
|
} 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
|
||||||
|
&& 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";
|
||||||
|
Log.w(TAG, line);
|
||||||
|
}
|
||||||
|
Log.i(TAG, line);
|
||||||
|
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
|
||||||
|
private String pactl(String... args) {
|
||||||
|
File pactl = new File(workingDir, "pactl");
|
||||||
|
if (!pactl.isFile() || pid <= 1) return null;
|
||||||
|
java.lang.Process process = null;
|
||||||
|
try {
|
||||||
|
File modules = new File(workingDir, "modules/arm64");
|
||||||
|
ArrayList<String> cmd = new ArrayList<>();
|
||||||
|
cmd.add(pactl.getAbsolutePath());
|
||||||
|
java.util.Collections.addAll(cmd, args);
|
||||||
|
ProcessBuilder builder = new ProcessBuilder(cmd);
|
||||||
|
builder.directory(workingDir);
|
||||||
|
builder.redirectErrorStream(true);
|
||||||
|
builder.environment().put("LD_LIBRARY_PATH", "/system/lib64:" + modules + ":" + workingDir);
|
||||||
|
builder.environment().put("HOME", workingDir.getAbsolutePath());
|
||||||
|
builder.environment().put("TMPDIR", workingDir.getAbsolutePath());
|
||||||
|
builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath());
|
||||||
|
process = builder.start();
|
||||||
|
String output;
|
||||||
|
try (InputStream in = process.getInputStream()) {
|
||||||
|
output = new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
if (!process.waitFor(5, TimeUnit.SECONDS)) {
|
||||||
|
process.destroyForcibly();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return process.exitValue() == 0 ? output : null;
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
return null;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
if (process != null && process.isAlive()) process.destroyForcibly();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.res.Configuration
|
||||||
|
import android.os.LocaleList
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The language the app shows itself in.
|
||||||
|
*
|
||||||
|
* Nothing chosen (the default) means the system's: Android's own language, or the per-app language
|
||||||
|
* Android 13+ lets a user set for DroidDeck in its settings, exactly as Android resolves it. Picking
|
||||||
|
* one in Setup overrides that until the user picks "System default" again. Each activity and service
|
||||||
|
* applies the choice to its own context ([wrap], [applyTo]), so it works on every Android version
|
||||||
|
* the app runs on rather than only where the platform's per-app language API exists.
|
||||||
|
*
|
||||||
|
* Steam follows the same choice: [SteamLanguage] turns [effective] into the client's language.
|
||||||
|
*/
|
||||||
|
object AppLanguage {
|
||||||
|
/** The stored value meaning "follow the system". */
|
||||||
|
const val SYSTEM = ""
|
||||||
|
|
||||||
|
/** The languages the app ships, as BCP 47 tags, in the order the picker lists them. */
|
||||||
|
val supported: List<String> = listOf("en", "es", "fr", "ru", "ja", "ko", "zh-CN", "zh-TW", "zh-HK")
|
||||||
|
|
||||||
|
private const val PREFS = "language"
|
||||||
|
private const val KEY = "app_language"
|
||||||
|
|
||||||
|
/** The locale Android gave the process before any choice here was applied. */
|
||||||
|
@Volatile private var systemLocale: Locale? = null
|
||||||
|
|
||||||
|
/** The stored choice: one of [supported], or [SYSTEM]. */
|
||||||
|
fun chosen(context: Context): String =
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, SYSTEM)
|
||||||
|
?.takeIf { it in supported } ?: SYSTEM
|
||||||
|
|
||||||
|
fun setChosen(context: Context, tag: String) {
|
||||||
|
val value = if (tag in supported) tag else SYSTEM
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, value).commit()
|
||||||
|
val locale = value.takeIf { it.isNotEmpty() }?.let(Locale::forLanguageTag) ?: system(context)
|
||||||
|
Locale.setDefault(locale)
|
||||||
|
// Code that reads strings through the application context sees the new language too.
|
||||||
|
val app = context.applicationContext
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
app.resources.updateConfiguration(
|
||||||
|
Configuration(app.resources.configuration).apply { setLocales(LocaleList(locale)) },
|
||||||
|
app.resources.displayMetrics,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The locale Android chose for the app, ignoring the choice made here. */
|
||||||
|
fun system(context: Context): Locale =
|
||||||
|
systemLocale ?: context.resources.configuration.locales[0] ?: Locale.getDefault()
|
||||||
|
|
||||||
|
/** The locale the app is shown in: the chosen language, or else the system's. */
|
||||||
|
fun effective(context: Context): Locale =
|
||||||
|
chosen(context).takeIf { it.isNotEmpty() }?.let(Locale::forLanguageTag) ?: system(context)
|
||||||
|
|
||||||
|
/** Remembers the system's locale; call with the untouched base context, before [wrap]. */
|
||||||
|
fun noteSystem(base: Context) {
|
||||||
|
if (systemLocale == null) systemLocale = base.resources.configuration.locales[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [base], showing the chosen language: for an Application's or a Service's attachBaseContext.
|
||||||
|
* Only the locale is overridden, so screen size, density and night mode keep following the
|
||||||
|
* device as they change.
|
||||||
|
*/
|
||||||
|
fun wrap(base: Context): Context {
|
||||||
|
noteSystem(base)
|
||||||
|
val tag = chosen(base).ifEmpty { return base }
|
||||||
|
val locale = Locale.forLanguageTag(tag)
|
||||||
|
Locale.setDefault(locale)
|
||||||
|
return base.createConfigurationContext(override(locale))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies the chosen language to an activity; call from its attachBaseContext, after super.
|
||||||
|
* applyOverrideConfiguration keeps the locale through rotation and window resizes, which an
|
||||||
|
* activity here handles itself rather than being recreated.
|
||||||
|
*/
|
||||||
|
fun applyTo(activity: Activity, base: Context) {
|
||||||
|
noteSystem(base)
|
||||||
|
val tag = chosen(base).ifEmpty { return }
|
||||||
|
val locale = Locale.forLanguageTag(tag)
|
||||||
|
Locale.setDefault(locale)
|
||||||
|
activity.applyOverrideConfiguration(override(locale))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Follows a change of the system's language while the process lives (Application.onConfigurationChanged). */
|
||||||
|
fun systemChanged(config: Configuration) {
|
||||||
|
config.locales[0]?.let { systemLocale = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
// A new Configuration's fontScale is 1, which as an override would undo the user's font size;
|
||||||
|
// 0 leaves it undefined, so only the locale is changed.
|
||||||
|
private fun override(locale: Locale) = Configuration().apply { fontScale = 0f; setLocales(LocaleList(locale)) }
|
||||||
|
|
||||||
|
/** Which of the app's languages [locale] reads as, or null when the app does not ship it. */
|
||||||
|
fun supportedTag(locale: Locale): String? = when (locale.language) {
|
||||||
|
"en", "es", "fr", "ru", "ja", "ko" -> locale.language
|
||||||
|
"zh" -> when {
|
||||||
|
locale.script == "Hans" -> "zh-CN"
|
||||||
|
locale.country == "HK" || locale.country == "MO" -> "zh-HK"
|
||||||
|
locale.script == "Hant" || locale.country == "TW" -> "zh-TW"
|
||||||
|
else -> "zh-CN"
|
||||||
|
}
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [locale]'s language named in itself, without its region unless the app tells them apart. */
|
||||||
|
fun displayName(locale: Locale): String =
|
||||||
|
supportedTag(locale)?.let(::nativeName) ?: locale.getDisplayLanguage(locale).replaceFirstChar { it.titlecase(locale) }
|
||||||
|
|
||||||
|
/** A language's name in that language, for the picker: what a reader of it looks for. */
|
||||||
|
fun nativeName(tag: String): String = when (tag) {
|
||||||
|
"en" -> "English"
|
||||||
|
"es" -> "Español"
|
||||||
|
"fr" -> "Français"
|
||||||
|
"ru" -> "Русский"
|
||||||
|
"ja" -> "日本語"
|
||||||
|
"ko" -> "한국어"
|
||||||
|
"zh-CN" -> "简体中文"
|
||||||
|
"zh-TW" -> "繁體中文(台灣)"
|
||||||
|
"zh-HK" -> "繁體中文(香港)"
|
||||||
|
else -> Locale.forLanguageTag(tag).let { it.getDisplayName(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -109,8 +109,11 @@ object DeviceReport {
|
|||||||
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
|
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
|
||||||
k("Session refresh", String.format(Locale.US, "%.2f Hz", SessionState.refreshHz))
|
k("Session refresh", String.format(Locale.US, "%.2f Hz", SessionState.refreshHz))
|
||||||
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context)
|
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context)
|
||||||
k("Resolution (Steam)", SessionPrefs.resolutionChoice(context, SessionService.MODE_STEAM, panelSize))
|
for ((label, mode) in listOf("Resolution (Steam)" to SessionService.MODE_STEAM, "Resolution (Desktop)" to SessionService.MODE_DESKTOP)) {
|
||||||
k("Resolution (Desktop)", SessionPrefs.resolutionChoice(context, SessionService.MODE_DESKTOP, panelSize))
|
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize)
|
||||||
|
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice)
|
||||||
|
k(label, "$choice (${size.first}x${size.second})")
|
||||||
|
}
|
||||||
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
|
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
|
||||||
|
|
||||||
h("Drivers")
|
h("Drivers")
|
||||||
@@ -163,9 +166,7 @@ object DeviceReport {
|
|||||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||||
k("Stretch games to fill", SessionPrefs.forceFullscreen(context))
|
|
||||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||||
k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic")
|
|
||||||
k("Microphone", SessionPrefs.micEnabled(context))
|
k("Microphone", SessionPrefs.micEnabled(context))
|
||||||
k("On-screen controls", SessionPrefs.oscMode(context))
|
k("On-screen controls", SessionPrefs.oscMode(context))
|
||||||
k("Touch mode", SessionPrefs.touchMode(context))
|
k("Touch mode", SessionPrefs.touchMode(context))
|
||||||
@@ -179,8 +180,14 @@ object DeviceReport {
|
|||||||
h("Android process limits")
|
h("Android process limits")
|
||||||
k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context)))
|
k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context)))
|
||||||
|
|
||||||
h("Device switch files in Download")
|
h("Device switch files")
|
||||||
for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver",
|
SessionService.envSwitchFile(context)?.takeIf { it.isFile }?.let { f ->
|
||||||
|
k("droiddeck-env", FileUtils.readString(f)?.trim()?.replace('\n', ' ')?.ifEmpty { "(present, empty)" } ?: "(present)")
|
||||||
|
}
|
||||||
|
if (File(Environment.getExternalStorageDirectory(), "Download/droiddeck-env").isFile) {
|
||||||
|
k("Download/droiddeck-env", "(ignored - it moved to Android/data/${context.packageName}/files)")
|
||||||
|
}
|
||||||
|
for (name in listOf("droiddeck-tu-debug", "droiddeck-driver",
|
||||||
"droiddeck-osc", "droiddeck-no-pad",
|
"droiddeck-osc", "droiddeck-no-pad",
|
||||||
"droiddeck-no-hud", "droiddeck-wlr-renderer")) {
|
"droiddeck-no-hud", "droiddeck-wlr-renderer")) {
|
||||||
val f = File(Environment.getExternalStorageDirectory(), "Download/$name")
|
val f = File(Environment.getExternalStorageDirectory(), "Download/$name")
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.droiddeck.launcher.core
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -17,8 +19,8 @@ object DeviceSupport {
|
|||||||
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
||||||
|
|
||||||
/** The chip as the device names it, for the card that explains the refusal. */
|
/** The chip as the device names it, for the card that explains the refusal. */
|
||||||
fun gpuName(): String {
|
fun gpuName(context: Context): String {
|
||||||
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
|
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
|
||||||
return soc?.let { "$it (${Build.HARDWARE})" } ?: Build.HARDWARE.ifBlank { "this GPU" }
|
return soc?.let { "$it (${Build.HARDWARE})" } ?: Build.HARDWARE.ifBlank { context.getString(R.string.gpu_this_gpu) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -25,7 +25,7 @@ object GameEnvironment {
|
|||||||
fun validValue(value: String) = '\u0000' !in value && value.length <= 8192
|
fun validValue(value: String) = '\u0000' !in value && value.length <= 8192
|
||||||
fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true)
|
fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true)
|
||||||
|
|
||||||
fun defaults(preset: String): Map<String, String?> = linkedMapOf<String, String?>(
|
fun defaults(preset: String, forceSsbs: Boolean = false): Map<String, String?> = linkedMapOf<String, String?>(
|
||||||
"MESA_SHADER_CACHE_DISABLE" to "false",
|
"MESA_SHADER_CACHE_DISABLE" to "false",
|
||||||
"VKD3D_FEATURE_LEVEL" to "12_2",
|
"VKD3D_FEATURE_LEVEL" to "12_2",
|
||||||
"VKD3D_SHADER_MODEL" to "6_9",
|
"VKD3D_SHADER_MODEL" to "6_9",
|
||||||
@@ -37,8 +37,12 @@ object GameEnvironment {
|
|||||||
"DOTNET_EnableWriteXorExecute" to "0",
|
"DOTNET_EnableWriteXorExecute" to "0",
|
||||||
).apply {
|
).apply {
|
||||||
FexPreset.env(preset).forEach { put(it.substringBefore('='), it.substringAfter('=')) }
|
FexPreset.env(preset).forEach { put(it.substringBefore('='), it.substringAfter('=')) }
|
||||||
|
// Steam settings' Force SSBS: droiddeck-game-env preloads libssbs.so into the game's Wine.
|
||||||
|
if (forceSsbs) put(FORCE_SSBS, "1")
|
||||||
}
|
}
|
||||||
|
|
||||||
fun effective(config: Config, preset: String, scope: String): Map<String, String?> =
|
const val FORCE_SSBS = "DROIDDECK_FORCE_SSBS"
|
||||||
defaults(preset) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
|
||||||
|
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
||||||
|
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
||||||
}
|
}
|
||||||
@@ -40,7 +40,7 @@ object HostProcess {
|
|||||||
if (onLine == null) builder.redirectOutput(File("/dev/null"))
|
if (onLine == null) builder.redirectOutput(File("/dev/null"))
|
||||||
val process = builder.start()
|
val process = builder.start()
|
||||||
val pid = pidOf(process)
|
val pid = pidOf(process)
|
||||||
Log.i(TAG, "started pid $pid: $command")
|
Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)")
|
||||||
if (onLine != null) {
|
if (onLine != null) {
|
||||||
Thread({
|
Thread({
|
||||||
try {
|
try {
|
||||||
@@ -59,7 +59,7 @@ object HostProcess {
|
|||||||
}
|
}
|
||||||
pid
|
pid
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "could not start: $command", e)
|
Log.e(TAG, "could not start: ${argv.first()}", e)
|
||||||
-1
|
-1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,6 +60,15 @@ object LogRedactor {
|
|||||||
private val IPV4 = Regex("(?<![0-9.])(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})(?![0-9.])")
|
private val IPV4 = Regex("(?<![0-9.])(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})(?![0-9.])")
|
||||||
/** An IPv6 literal: "::" somewhere, or all eight groups (a clock's 10:03:05 is neither). */
|
/** An IPv6 literal: "::" somewhere, or all eight groups (a clock's 10:03:05 is neither). */
|
||||||
private val IPV6 = Regex("(?<![0-9A-Za-z:])[0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7}(?:%[A-Za-z0-9_.]+)?(?![0-9A-Za-z:])")
|
private val IPV6 = Regex("(?<![0-9A-Za-z:])[0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7}(?:%[A-Za-z0-9_.]+)?(?![0-9A-Za-z:])")
|
||||||
|
private val MAC = Regex("(?i)(?<![0-9a-z:-])[0-9a-f]{2}([:-])(?:[0-9a-f]{2}\\1){4}[0-9a-f]{2}(?![0-9a-z:-])")
|
||||||
|
private val MAC_FIELD = Regex(
|
||||||
|
"(?i)(\\bmac(?:[_ ]?address)?[\"']?\\s*[:=]\\s*[\"']?)[0-9a-f]{2}([:-])" +
|
||||||
|
"(?:[0-9a-f]{2}\\2){4}[0-9a-f]{2}(?![0-9a-z:-])"
|
||||||
|
)
|
||||||
|
private val DEVICE_IDENTIFIER = Regex(
|
||||||
|
"(?i)(\\b(?:android[_ ]?id|(?:device|controller)[_ ]?serial|serial(?:[_ ]?number)?|build\\.serial)" +
|
||||||
|
"[\"']?\\s*[:=]\\s*)(\"[^\"\\r\\n<>]+\"|'[^'\\r\\n<>]+'|[^\\s\"'<>&;,\\[\\]{}]+)"
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The account a Steam UI login line names ("Login: OnLoginStateChange <account> 2 1 0 0"): a
|
* The account a Steam UI login line names ("Login: OnLoginStateChange <account> 2 1 0 0"): a
|
||||||
@@ -190,6 +199,14 @@ object LogRedactor {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bump whenever a pattern is added or tightened. A session folder records the version it was
|
||||||
|
* scrubbed under (SessionArtifacts.SCRUBBED_TREE_MARKER), and a share copies a file as it is
|
||||||
|
* only when that matches, so a folder scrubbed under older rules is scrubbed again on the way
|
||||||
|
* out.
|
||||||
|
*/
|
||||||
|
const val RULES_VERSION = 2
|
||||||
|
|
||||||
/** [src]'s lines, scrubbed, to [out]. */
|
/** [src]'s lines, scrubbed, to [out]. */
|
||||||
fun scrubTo(src: java.io.File, out: java.io.Writer) {
|
fun scrubTo(src: java.io.File, out: java.io.Writer) {
|
||||||
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
|
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
|
||||||
@@ -200,6 +217,13 @@ object LogRedactor {
|
|||||||
if (line.isEmpty()) return line
|
if (line.isEmpty()) return line
|
||||||
return try {
|
return try {
|
||||||
var out = line
|
var out = line
|
||||||
|
out = MAC_FIELD.replace(out) { "${it.groupValues[1]}<redacted:mac>" }
|
||||||
|
out = MAC.replace(out, "<redacted:mac>")
|
||||||
|
out = DEVICE_IDENTIFIER.replace(out) {
|
||||||
|
val value = it.groupValues[2]
|
||||||
|
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
|
||||||
|
"${it.groupValues[1]}${quote}<redacted:serial>${quote}"
|
||||||
|
}
|
||||||
out = GUID.replace(out, "<redacted:guid>")
|
out = GUID.replace(out, "<redacted:guid>")
|
||||||
out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}<redacted:jwt>" }
|
out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}<redacted:jwt>" }
|
||||||
out = JWT_BASE64.replace(out, "<redacted:jwt>")
|
out = JWT_BASE64.replace(out, "<redacted:jwt>")
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.core
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
|
||||||
/** Android's phantom process monitor can kill the many child processes used by a Steam session. */
|
/** Android's phantom process monitor can kill the many child processes used by a Steam session. */
|
||||||
enum class PhantomProcessStatus {
|
enum class PhantomProcessStatus {
|
||||||
@@ -98,29 +99,30 @@ object PhantomProcessLimit {
|
|||||||
fun blocksSteam(status: PhantomProcessStatus): Boolean =
|
fun blocksSteam(status: PhantomProcessStatus): Boolean =
|
||||||
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
|
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
|
||||||
|
|
||||||
fun title(status: PhantomProcessStatus): String = when (status) {
|
fun title(context: Context, status: PhantomProcessStatus): String = context.getString(when (status) {
|
||||||
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
|
PhantomProcessStatus.ENABLED -> R.string.phantom_title_on
|
||||||
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
|
PhantomProcessStatus.UNSET -> R.string.phantom_title_unset
|
||||||
PhantomProcessStatus.UNREADABLE -> "Child-process limit could not be checked"
|
PhantomProcessStatus.UNREADABLE -> R.string.phantom_title_unreadable
|
||||||
PhantomProcessStatus.DISABLED -> "Child-process limit is off"
|
PhantomProcessStatus.DISABLED -> R.string.phantom_title_off
|
||||||
PhantomProcessStatus.NOT_APPLICABLE -> "Child-process limit not required"
|
PhantomProcessStatus.NOT_APPLICABLE -> R.string.phantom_title_not_required
|
||||||
|
})
|
||||||
|
|
||||||
|
fun instructions(context: Context, status: PhantomProcessStatus): String = when (status) {
|
||||||
|
PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE ->
|
||||||
|
context.getString(R.string.phantom_instructions_fix, fixSentence(context))
|
||||||
|
PhantomProcessStatus.DISABLED -> context.getString(R.string.phantom_instructions_off)
|
||||||
|
PhantomProcessStatus.NOT_APPLICABLE -> context.getString(R.string.phantom_instructions_not_applicable)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun instructions(status: PhantomProcessStatus): String = when (status) {
|
fun gateInstructions(context: Context, status: PhantomProcessStatus): String = when (status) {
|
||||||
PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence() + " If that is not possible, connect this device to a computer with ADB and run the command below. Return here and check again."
|
PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence(context)
|
||||||
PhantomProcessStatus.DISABLED -> "Steam sessions can start."
|
else -> instructions(context, status)
|
||||||
PhantomProcessStatus.NOT_APPLICABLE -> "This Android version does not use this limit."
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun gateInstructions(status: PhantomProcessStatus): String = when (status) {
|
fun fixSentence(context: Context, sdk: Int = Build.VERSION.SDK_INT): String =
|
||||||
PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence()
|
context.getString(if (hasDeveloperToggle(sdk)) R.string.phantom_fix_toggle else R.string.phantom_fix_no_toggle)
|
||||||
else -> instructions(status)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun fixSentence(sdk: Int = Build.VERSION.SDK_INT): String =
|
|
||||||
if (hasDeveloperToggle(sdk)) "Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards."
|
|
||||||
else "This Android version has no switch for it. Use Wireless debugging to change it from this device."
|
|
||||||
|
|
||||||
|
/** English: for the device report. */
|
||||||
fun reportValue(status: PhantomProcessStatus): String = when (status) {
|
fun reportValue(status: PhantomProcessStatus): String = when (status) {
|
||||||
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
|
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
|
||||||
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
|
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.core
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.net.nsd.NsdManager
|
import android.net.nsd.NsdManager
|
||||||
import android.net.nsd.NsdServiceInfo
|
import android.net.nsd.NsdServiceInfo
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.flyfishxu.kadb.Kadb
|
import com.flyfishxu.kadb.Kadb
|
||||||
import com.flyfishxu.kadb.cert.KadbCert
|
import com.flyfishxu.kadb.cert.KadbCert
|
||||||
import java.io.File
|
import java.io.File
|
||||||
@@ -37,21 +38,21 @@ object WirelessAdbFix {
|
|||||||
|
|
||||||
val identity = KadbCert.get(notAfter = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650))
|
val identity = KadbCert.get(notAfter = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650))
|
||||||
KadbCert.set(identity.first, identity.second)
|
KadbCert.set(identity.first, identity.second)
|
||||||
writeAtomically(cert, identity.first)
|
writeAtomically(context, cert, identity.first)
|
||||||
writeAtomically(key, identity.second)
|
writeAtomically(context, key, identity.second)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun writeAtomically(destination: File, contents: ByteArray) {
|
private fun writeAtomically(context: Context, destination: File, contents: ByteArray) {
|
||||||
val temporary = File(destination.parentFile, "${destination.name}.tmp")
|
val temporary = File(destination.parentFile, "${destination.name}.tmp")
|
||||||
temporary.writeBytes(contents)
|
temporary.writeBytes(contents)
|
||||||
check(temporary.renameTo(destination)) { "Could not save Wireless debugging identity" }
|
check(temporary.renameTo(destination)) { context.getString(R.string.adbfix_save_failed) }
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun pair(context: Context, host: String, port: Int, pairingCode: String) {
|
suspend fun pair(context: Context, host: String, port: Int, pairingCode: String) {
|
||||||
loadOrCreateIdentity(context.applicationContext)
|
loadOrCreateIdentity(context.applicationContext)
|
||||||
Kadb.pair(host, port, pairingCode, "DroidDeck")
|
Kadb.pair(host, port, pairingCode, "DroidDeck")
|
||||||
writeAtomically(File(context.noBackupFilesDir, HOST_FILE), host.toByteArray())
|
writeAtomically(context, File(context.noBackupFilesDir, HOST_FILE), host.toByteArray())
|
||||||
writeAtomically(File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
|
writeAtomically(context, File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun savedConnection(context: Context): SavedConnection? {
|
private fun savedConnection(context: Context): SavedConnection? {
|
||||||
@@ -73,6 +74,7 @@ object WirelessAdbFix {
|
|||||||
|
|
||||||
private fun saveConnection(context: Context, host: String, port: Int) {
|
private fun saveConnection(context: Context, host: String, port: Int) {
|
||||||
writeAtomically(
|
writeAtomically(
|
||||||
|
context,
|
||||||
File(context.applicationContext.noBackupFilesDir, CONNECTION_FILE),
|
File(context.applicationContext.noBackupFilesDir, CONNECTION_FILE),
|
||||||
"$host\n$port".toByteArray(),
|
"$host\n$port".toByteArray(),
|
||||||
)
|
)
|
||||||
@@ -171,11 +173,11 @@ object WirelessAdbFix {
|
|||||||
Kadb.create(host, port).use { adb ->
|
Kadb.create(host, port).use { adb ->
|
||||||
PhantomProcessLimit.shellCommands(enabled).forEach { command ->
|
PhantomProcessLimit.shellCommands(enabled).forEach { command ->
|
||||||
val change = adb.shell(command)
|
val change = adb.shell(command)
|
||||||
check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } }
|
check(change.exitCode == 0) { change.allOutput.ifBlank { context.getString(R.string.adbfix_command_failed, change.exitCode) } }
|
||||||
}
|
}
|
||||||
val result = adb.shell(PhantomProcessLimit.verifyCommand())
|
val result = adb.shell(PhantomProcessLimit.verifyCommand())
|
||||||
check(result.exitCode == 0 && PhantomProcessLimit.verified(result.output, enabled)) {
|
check(result.exitCode == 0 && PhantomProcessLimit.verified(result.output, enabled)) {
|
||||||
"Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}"
|
context.getString(R.string.adbfix_not_confirmed, result.allOutput.trim())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (PhantomProcessLimit.usesDeviceConfig()) PhantomProcessLimit.rememberAndroid12(context, !enabled)
|
if (PhantomProcessLimit.usesDeviceConfig()) PhantomProcessLimit.rememberAndroid12(context, !enabled)
|
||||||
@@ -186,7 +188,7 @@ object WirelessAdbFix {
|
|||||||
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
|
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
|
||||||
val appContext = context.applicationContext
|
val appContext = context.applicationContext
|
||||||
val saved = savedConnection(appContext)
|
val saved = savedConnection(appContext)
|
||||||
?: error("No Wireless debugging pairing is saved")
|
?: error(appContext.getString(R.string.adbfix_no_pairing))
|
||||||
val cachedPort = saved.port
|
val cachedPort = saved.port
|
||||||
if (cachedPort != null) {
|
if (cachedPort != null) {
|
||||||
val cachedResult = runCatching {
|
val cachedResult = runCatching {
|
||||||
@@ -201,7 +203,7 @@ object WirelessAdbFix {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||||
?: error("Enter the current Wireless debugging IP address & Port")
|
?: error(appContext.getString(R.string.adbfix_enter_address))
|
||||||
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,9 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
|||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
class WirelessAdbPairingService : Service() {
|
class WirelessAdbPairingService : Service() {
|
||||||
|
override fun attachBaseContext(newBase: android.content.Context) =
|
||||||
|
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(newBase))
|
||||||
|
|
||||||
sealed interface Stage {
|
sealed interface Stage {
|
||||||
data object Idle : Stage
|
data object Idle : Stage
|
||||||
data object Waiting : Stage
|
data object Waiting : Stage
|
||||||
@@ -35,7 +38,7 @@ class WirelessAdbPairingService : Service() {
|
|||||||
private var pairingHost: String? = null
|
private var pairingHost: String? = null
|
||||||
private var pairingPort: Int? = null
|
private var pairingPort: Int? = null
|
||||||
@Volatile private var working = false
|
@Volatile private var working = false
|
||||||
private val timeout = Runnable { finish(Stage.Failed("Timed out waiting for the pairing pop-up. Try again from DroidDeck.")) }
|
private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) }
|
||||||
|
|
||||||
override fun onBind(intent: Intent?): IBinder? = null
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
@@ -75,13 +78,13 @@ class WirelessAdbPairingService : Service() {
|
|||||||
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
|
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
|
||||||
override fun onDiscoveryStopped(serviceType: String) = Unit
|
override fun onDiscoveryStopped(serviceType: String) = Unit
|
||||||
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
|
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
|
||||||
main.post { finish(Stage.Failed("Could not look for the pairing pop-up ($errorCode). Check that Wi-Fi is on.")) }
|
main.post { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed_code, errorCode))) }
|
||||||
}
|
}
|
||||||
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit
|
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit
|
||||||
}
|
}
|
||||||
runCatching { manager.discoverServices("$PAIRING_TYPE.", NsdManager.PROTOCOL_DNS_SD, listener) }
|
runCatching { manager.discoverServices("$PAIRING_TYPE.", NsdManager.PROTOCOL_DNS_SD, listener) }
|
||||||
.onSuccess { nsd = manager; discovery = listener }
|
.onSuccess { nsd = manager; discovery = listener }
|
||||||
.onFailure { finish(Stage.Failed("Could not look for the pairing pop-up: ${it.localizedMessage}")) }
|
.onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun resolveListener() = object : NsdManager.ResolveListener {
|
private fun resolveListener() = object : NsdManager.ResolveListener {
|
||||||
@@ -107,34 +110,34 @@ class WirelessAdbPairingService : Service() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (code.length != 6) {
|
if (code.length != 6) {
|
||||||
show(Stage.CodeNeeded("Enter all 6 digits of the code"))
|
show(Stage.CodeNeeded(getString(R.string.adbpair_six_digits)))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
working = true
|
working = true
|
||||||
show(Stage.Working("Pairing…"))
|
show(Stage.Working(getString(R.string.adbpair_pairing)))
|
||||||
Thread({
|
Thread({
|
||||||
val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
|
val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
|
||||||
if (paired.isFailure) {
|
if (paired.isFailure) {
|
||||||
main.post {
|
main.post {
|
||||||
working = false
|
working = false
|
||||||
pairingPort = null
|
pairingPort = null
|
||||||
show(Stage.CodeNeeded("That code didn't work. Open the pairing pop-up again and enter its new code."))
|
show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected)))
|
||||||
}
|
}
|
||||||
return@Thread
|
return@Thread
|
||||||
}
|
}
|
||||||
main.post {
|
main.post {
|
||||||
stopDiscovery()
|
stopDiscovery()
|
||||||
show(Stage.Working("Paired. Connecting…"))
|
show(Stage.Working(getString(R.string.adbpair_connecting)))
|
||||||
}
|
}
|
||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
val connectPort = WirelessAdbFix.localConnectPort(this)
|
val connectPort = WirelessAdbFix.localConnectPort(this)
|
||||||
?: error("Paired, but the Wireless debugging port was not found. Keep Wireless debugging on and try again.")
|
?: error(getString(R.string.adbpair_port_not_found))
|
||||||
main.post { show(Stage.Working("Applying the setting…")) }
|
main.post { show(Stage.Working(getString(R.string.adbpair_applying))) }
|
||||||
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
|
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
|
||||||
}
|
}
|
||||||
main.post {
|
main.post {
|
||||||
working = false
|
working = false
|
||||||
finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: "Wireless debugging command failed") } ?: Stage.Done)
|
finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_command_failed)) } ?: Stage.Done)
|
||||||
}
|
}
|
||||||
}, "wireless-adb-pairing").start()
|
}, "wireless-adb-pairing").start()
|
||||||
}
|
}
|
||||||
@@ -174,9 +177,9 @@ class WirelessAdbPairingService : Service() {
|
|||||||
|
|
||||||
private fun notification(stage: Stage): Notification {
|
private fun notification(stage: Stage): Notification {
|
||||||
val manager = getSystemService(NotificationManager::class.java)
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Wireless debugging setup",
|
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.adbpair_channel_name),
|
||||||
NotificationManager.IMPORTANCE_HIGH).apply {
|
NotificationManager.IMPORTANCE_HIGH).apply {
|
||||||
description = "Asks for the Wireless debugging pairing code while Settings is open"
|
description = getString(R.string.adbpair_channel_description)
|
||||||
setShowBadge(false)
|
setShowBadge(false)
|
||||||
setSound(null, null)
|
setSound(null, null)
|
||||||
enableVibration(false)
|
enableVibration(false)
|
||||||
@@ -193,41 +196,40 @@ class WirelessAdbPairingService : Service() {
|
|||||||
.setCategory(Notification.CATEGORY_STATUS)
|
.setCategory(Notification.CATEGORY_STATUS)
|
||||||
when (stage) {
|
when (stage) {
|
||||||
Stage.Waiting, Stage.Idle -> builder
|
Stage.Waiting, Stage.Idle -> builder
|
||||||
.setContentTitle("Pair Wireless debugging")
|
.setContentTitle(getString(R.string.adbpair_title_pair))
|
||||||
.setContentText("Turn on Wireless debugging, then tap “Pair device with pairing code”.")
|
.setContentText(getString(R.string.adbpair_waiting_text))
|
||||||
.setStyle(Notification.BigTextStyle().bigText(
|
.setStyle(Notification.BigTextStyle().bigText(getString(R.string.adbpair_waiting_long)))
|
||||||
"Turn on Wireless debugging, then tap “Pair device with pairing code”. Stay in Settings: the code goes in this notification."))
|
|
||||||
.setOngoing(true)
|
.setOngoing(true)
|
||||||
.setOnlyAlertOnce(true)
|
.setOnlyAlertOnce(true)
|
||||||
.addAction(Notification.Action.Builder(null, "Cancel", cancel).build())
|
.addAction(Notification.Action.Builder(null, getString(R.string.common_cancel), cancel).build())
|
||||||
is Stage.CodeNeeded -> {
|
is Stage.CodeNeeded -> {
|
||||||
val reply = PendingIntent.getService(this, 2,
|
val reply = PendingIntent.getService(this, 2,
|
||||||
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CODE),
|
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CODE),
|
||||||
if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||||
else PendingIntent.FLAG_UPDATE_CURRENT)
|
else PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
val input = RemoteInput.Builder(KEY_CODE).setLabel("6-digit pairing code").build()
|
val input = RemoteInput.Builder(KEY_CODE).setLabel(getString(R.string.adbpair_code_label)).build()
|
||||||
val text = stage.error ?: "Tap Enter code and type the 6 digits shown in Settings."
|
val text = stage.error ?: getString(R.string.adbpair_code_hint)
|
||||||
builder
|
builder
|
||||||
.setContentTitle(if (stage.error == null) "Enter the Wi-Fi pairing code" else "Try the code again")
|
.setContentTitle(getString(if (stage.error == null) R.string.adbpair_title_code else R.string.adbpair_title_retry))
|
||||||
.setContentText(text)
|
.setContentText(text)
|
||||||
.setStyle(Notification.BigTextStyle().bigText(text))
|
.setStyle(Notification.BigTextStyle().bigText(text))
|
||||||
.setOngoing(true)
|
.setOngoing(true)
|
||||||
.addAction(Notification.Action.Builder(null, "Enter code", reply).addRemoteInput(input).build())
|
.addAction(Notification.Action.Builder(null, getString(R.string.adbpair_enter_code), reply).addRemoteInput(input).build())
|
||||||
.addAction(Notification.Action.Builder(null, "Cancel", cancel).build())
|
.addAction(Notification.Action.Builder(null, getString(R.string.common_cancel), cancel).build())
|
||||||
}
|
}
|
||||||
is Stage.Working -> builder
|
is Stage.Working -> builder
|
||||||
.setContentTitle("Setting up Steam")
|
.setContentTitle(getString(R.string.adbpair_title_working))
|
||||||
.setContentText(stage.step)
|
.setContentText(stage.step)
|
||||||
.setProgress(0, 0, true)
|
.setProgress(0, 0, true)
|
||||||
.setOngoing(true)
|
.setOngoing(true)
|
||||||
.setOnlyAlertOnce(true)
|
.setOnlyAlertOnce(true)
|
||||||
Stage.Done -> builder
|
Stage.Done -> builder
|
||||||
.setContentTitle("Steam is ready")
|
.setContentTitle(getString(R.string.adbpair_title_done))
|
||||||
.setContentText("Tap to go back to DroidDeck. You can turn Wireless debugging off now.")
|
.setContentText(getString(R.string.adbpair_done_text))
|
||||||
.setStyle(Notification.BigTextStyle().bigText("Tap to go back to DroidDeck. You can turn Wireless debugging off now."))
|
.setStyle(Notification.BigTextStyle().bigText(getString(R.string.adbpair_done_text)))
|
||||||
.setAutoCancel(true)
|
.setAutoCancel(true)
|
||||||
is Stage.Failed -> builder
|
is Stage.Failed -> builder
|
||||||
.setContentTitle("Wireless debugging setup stopped")
|
.setContentTitle(getString(R.string.adbpair_title_failed))
|
||||||
.setContentText(stage.error)
|
.setContentText(stage.error)
|
||||||
.setStyle(Notification.BigTextStyle().bigText(stage.error))
|
.setStyle(Notification.BigTextStyle().bigText(stage.error))
|
||||||
.setAutoCancel(true)
|
.setAutoCancel(true)
|
||||||
|
|||||||
@@ -56,6 +56,8 @@ data class RailItem(
|
|||||||
val selected: Boolean,
|
val selected: Boolean,
|
||||||
/** >0 shows a small accent count badge on the item's icon (expanded and collapsed). */
|
/** >0 shows a small accent count badge on the item's icon (expanded and collapsed). */
|
||||||
val badge: Int = 0,
|
val badge: Int = 0,
|
||||||
|
/** The under-icon label when the rail is collapsed, for names too long to fit; null derives one. */
|
||||||
|
val shortLabel: String? = null,
|
||||||
// onClick stays LAST so existing call sites can pass it as a trailing lambda; badge is an
|
// onClick stays LAST so existing call sites can pass it as a trailing lambda; badge is an
|
||||||
// optional named param before it (default 0).
|
// optional named param before it (default 0).
|
||||||
val onClick: () -> Unit,
|
val onClick: () -> Unit,
|
||||||
@@ -73,7 +75,6 @@ private fun collapsedLabel(label: String): String {
|
|||||||
when (label) {
|
when (label) {
|
||||||
"ENVIROMENT" -> return "ENVIRON" // the app's existing (mis)spelling, kept uppercase
|
"ENVIROMENT" -> return "ENVIRON" // the app's existing (mis)spelling, kept uppercase
|
||||||
"WIN COMPONENTS" -> return "WIN COMP"
|
"WIN COMPONENTS" -> return "WIN COMP"
|
||||||
"Downloads" -> return "Downlds"
|
|
||||||
}
|
}
|
||||||
if (label.contains(' ')) return label // multi-word → wraps to 2 lines
|
if (label.contains(' ')) return label // multi-word → wraps to 2 lines
|
||||||
return if (label.length > 9) label.take(8) + "…" else label
|
return if (label.length > 9) label.take(8) + "…" else label
|
||||||
@@ -317,7 +318,7 @@ fun CollapsibleRail(
|
|||||||
RailItemIcon(item, iconTint)
|
RailItemIcon(item, iconTint)
|
||||||
Spacer(Modifier.height(2.dp))
|
Spacer(Modifier.height(2.dp))
|
||||||
Text(
|
Text(
|
||||||
collapsedLabel(item.label),
|
item.shortLabel ?: collapsedLabel(item.label),
|
||||||
color = labelColor,
|
color = labelColor,
|
||||||
fontSize = 7.5.sp,
|
fontSize = 7.5.sp,
|
||||||
lineHeight = 8.5.sp,
|
lineHeight = 8.5.sp,
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ import java.io.File
|
|||||||
|
|
||||||
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
|
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
|
||||||
class FileManagerActivity : ComponentActivity() {
|
class FileManagerActivity : ComponentActivity() {
|
||||||
|
override fun attachBaseContext(newBase: android.content.Context) {
|
||||||
|
super.attachBaseContext(newBase)
|
||||||
|
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import androidx.compose.foundation.lazy.grid.items
|
|||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Add
|
import androidx.compose.material.icons.filled.Add
|
||||||
|
import androidx.compose.material.icons.filled.ArrowUpward
|
||||||
import androidx.compose.material.icons.filled.Checklist
|
import androidx.compose.material.icons.filled.Checklist
|
||||||
import androidx.compose.material.icons.filled.Delete
|
import androidx.compose.material.icons.filled.Delete
|
||||||
import androidx.compose.material.icons.filled.FileCopy
|
import androidx.compose.material.icons.filled.FileCopy
|
||||||
@@ -61,6 +62,7 @@ import androidx.compose.ui.layout.ContentScale
|
|||||||
import androidx.compose.ui.graphics.vector.rememberVectorPainter
|
import androidx.compose.ui.graphics.vector.rememberVectorPainter
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
import coil.compose.AsyncImage
|
import coil.compose.AsyncImage
|
||||||
import androidx.compose.ui.text.font.FontFamily
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
@@ -107,7 +109,7 @@ private fun FileContextMenuItems(
|
|||||||
) {
|
) {
|
||||||
val isDir = file.isDirectory
|
val isDir = file.isDirectory
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text("Select") },
|
text = { Text(stringResource(R.string.fm_select)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onSelect() },
|
onClick = { onDismissMenu(); onSelect() },
|
||||||
)
|
)
|
||||||
@@ -115,7 +117,7 @@ private fun FileContextMenuItems(
|
|||||||
// Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config
|
// Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config
|
||||||
// files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu.
|
// files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu.
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text("Properties") },
|
text = { Text(stringResource(R.string.fm_properties)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onProperties() },
|
onClick = { onDismissMenu(); onProperties() },
|
||||||
)
|
)
|
||||||
@@ -123,7 +125,7 @@ private fun FileContextMenuItems(
|
|||||||
// Favorites are directories - only folders get the pin toggle.
|
// Favorites are directories - only folders get the pin toggle.
|
||||||
if (isDir) {
|
if (isDir) {
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(if (isFavorite) "Remove from Favorites" else "Add to Favorites") },
|
text = { Text(if (isFavorite) stringResource(R.string.fm_favorite_remove) else stringResource(R.string.fm_favorite_add)) },
|
||||||
leadingIcon = {
|
leadingIcon = {
|
||||||
Icon(
|
Icon(
|
||||||
if (isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder,
|
if (isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder,
|
||||||
@@ -136,25 +138,25 @@ private fun FileContextMenuItems(
|
|||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
}
|
}
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text("Rename") },
|
text = { Text(stringResource(R.string.fm_rename)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onRename() },
|
onClick = { onDismissMenu(); onRename() },
|
||||||
)
|
)
|
||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text("Copy") },
|
text = { Text(stringResource(R.string.fm_copy)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onCopy() },
|
onClick = { onDismissMenu(); onCopy() },
|
||||||
)
|
)
|
||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text("Cut") },
|
text = { Text(stringResource(R.string.fm_cut)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onCut() },
|
onClick = { onDismissMenu(); onCut() },
|
||||||
)
|
)
|
||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text("Delete") },
|
text = { Text(stringResource(R.string.common_delete)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onDelete() },
|
onClick = { onDismissMenu(); onDelete() },
|
||||||
)
|
)
|
||||||
@@ -184,6 +186,7 @@ internal fun FileItemRow(
|
|||||||
onProperties: () -> Unit = {},
|
onProperties: () -> Unit = {},
|
||||||
) {
|
) {
|
||||||
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
||||||
|
val context = LocalContext.current
|
||||||
val isDir = file.isDirectory
|
val isDir = file.isDirectory
|
||||||
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
|
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
|
||||||
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
|
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
|
||||||
@@ -276,7 +279,7 @@ internal fun FileItemRow(
|
|||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = buildString {
|
text = buildString {
|
||||||
if (!isDir) append(FileOps.formatBytes(file.length())).append(" \u2022 ")
|
if (!isDir) append(FileOps.formatBytes(context, file.length())).append(" \u2022 ")
|
||||||
append(dateFormat.format(Date(file.lastModified())))
|
append(dateFormat.format(Date(file.lastModified())))
|
||||||
},
|
},
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
@@ -285,7 +288,7 @@ internal fun FileItemRow(
|
|||||||
}
|
}
|
||||||
if (showActions) Box {
|
if (showActions) Box {
|
||||||
IconButton(onClick = onMenu) {
|
IconButton(onClick = onMenu) {
|
||||||
Icon(Icons.Filled.MoreVert, "Actions", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
Icon(Icons.Filled.MoreVert, stringResource(R.string.fm_actions), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
||||||
}
|
}
|
||||||
DropdownMenu(
|
DropdownMenu(
|
||||||
expanded = menuExpanded,
|
expanded = menuExpanded,
|
||||||
@@ -310,6 +313,47 @@ internal fun FileItemRow(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The ".." row at the top of a folder: one level up, styled like a folder row so it reads as part
|
||||||
|
// of the list and takes controller focus the same way.
|
||||||
|
@Composable
|
||||||
|
internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||||
|
.clickable(onClick = onTap),
|
||||||
|
shape = RoundedCornerShape(10.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||||
|
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Filled.ArrowUpward,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = "..",
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.fm_up_one_level),
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Dedicated Favorites list that replaces the file list while the star toggle is on.
|
// Dedicated Favorites list that replaces the file list while the star toggle is on.
|
||||||
// Reads the store keyed on [favTick] so it recomposes after any pin/unpin.
|
// Reads the store keyed on [favTick] so it recomposes after any pin/unpin.
|
||||||
@Composable
|
@Composable
|
||||||
@@ -338,7 +382,7 @@ internal fun FavoritesList(
|
|||||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = "Favorites",
|
text = stringResource(R.string.fm_favorites),
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
fontSize = 15.sp,
|
fontSize = 15.sp,
|
||||||
fontWeight = FontWeight.SemiBold,
|
fontWeight = FontWeight.SemiBold,
|
||||||
@@ -351,7 +395,7 @@ internal fun FavoritesList(
|
|||||||
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||||
Spacer(Modifier.width(6.dp))
|
Spacer(Modifier.width(6.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "Pin current folder",
|
text = stringResource(R.string.fm_pin_current),
|
||||||
color = MaterialTheme.colorScheme.primary,
|
color = MaterialTheme.colorScheme.primary,
|
||||||
fontSize = 13.sp,
|
fontSize = 13.sp,
|
||||||
)
|
)
|
||||||
@@ -366,7 +410,7 @@ internal fun FavoritesList(
|
|||||||
contentAlignment = Alignment.Center,
|
contentAlignment = Alignment.Center,
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = "No favorites yet - pin a folder with its ⋮ menu to jump back here fast.",
|
text = stringResource(R.string.fm_no_favorites),
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
fontSize = 13.sp,
|
fontSize = 13.sp,
|
||||||
modifier = Modifier.padding(horizontal = 32.dp),
|
modifier = Modifier.padding(horizontal = 32.dp),
|
||||||
@@ -431,7 +475,7 @@ private fun FavoriteCard(
|
|||||||
// Origin line: coloured drive badge + source description.
|
// Origin line: coloured drive badge + source description.
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
Text(
|
Text(
|
||||||
text = loc.driveLabel,
|
text = stringResource(loc.driveLabel),
|
||||||
color = badgeFg,
|
color = badgeFg,
|
||||||
fontSize = 11.sp,
|
fontSize = 11.sp,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
@@ -443,9 +487,9 @@ private fun FavoriteCard(
|
|||||||
Spacer(Modifier.width(6.dp))
|
Spacer(Modifier.width(6.dp))
|
||||||
Text(
|
Text(
|
||||||
text = when (loc.storage) {
|
text = when (loc.storage) {
|
||||||
FavStorage.INTERNAL -> "Internal storage"
|
FavStorage.INTERNAL -> stringResource(R.string.games_internal)
|
||||||
FavStorage.SD -> "SD card"
|
FavStorage.SD -> stringResource(R.string.fm_drive_sd)
|
||||||
FavStorage.OTHER -> "Storage"
|
FavStorage.OTHER -> stringResource(R.string.fm_drive_storage)
|
||||||
},
|
},
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
fontSize = 12.sp,
|
fontSize = 12.sp,
|
||||||
@@ -464,7 +508,7 @@ private fun FavoriteCard(
|
|||||||
IconButton(onClick = onUnpin) {
|
IconButton(onClick = onUnpin) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Filled.Star,
|
Icons.Filled.Star,
|
||||||
contentDescription = "Remove from favorites",
|
contentDescription = stringResource(R.string.fm_unpin_favorite),
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
modifier = Modifier.size(22.dp),
|
modifier = Modifier.size(22.dp),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import androidx.compose.material.icons.filled.Image
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
// The File Manager's non-UI helpers: sorting, paths, conflict choices and favourite locations.
|
// The File Manager's non-UI helpers: sorting, paths, conflict choices and favourite locations.
|
||||||
@@ -77,7 +79,7 @@ enum class FavStorage { INTERNAL, SD, OTHER }
|
|||||||
|
|
||||||
data class FavLocation(
|
data class FavLocation(
|
||||||
val storage: FavStorage,
|
val storage: FavStorage,
|
||||||
val driveLabel: String, // "Internal", "SD card", or "Storage"
|
@StringRes val driveLabel: Int, // Internal, SD card, or Storage
|
||||||
val displayPath: String // the unix absolute path
|
val displayPath: String // the unix absolute path
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -87,15 +89,20 @@ fun describeLocation(file: File): FavLocation {
|
|||||||
|
|
||||||
val internal = "/storage/emulated/0"
|
val internal = "/storage/emulated/0"
|
||||||
if (abs == internal || abs.startsWith("$internal/")) {
|
if (abs == internal || abs.startsWith("$internal/")) {
|
||||||
return FavLocation(FavStorage.INTERNAL, "Internal", abs)
|
return FavLocation(FavStorage.INTERNAL, R.string.fm_drive_internal, abs)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (abs.startsWith("/storage/")) {
|
if (abs.startsWith("/storage/")) {
|
||||||
val name = abs.removePrefix("/storage/").substringBefore('/')
|
val name = abs.removePrefix("/storage/").substringBefore('/')
|
||||||
if (name.isNotEmpty() && name != "emulated" && name != "self") {
|
if (name.isNotEmpty() && name != "emulated" && name != "self") {
|
||||||
return FavLocation(FavStorage.SD, "SD card", abs)
|
return FavLocation(FavStorage.SD, R.string.fm_drive_sd, abs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return FavLocation(FavStorage.OTHER, "Storage", abs)
|
// The Linux system's root (the app's files/linuxfs, the sessions' /) and anything under it.
|
||||||
|
if (Regex("/files/linuxfs(/|$)").containsMatchIn(abs)) {
|
||||||
|
return FavLocation(FavStorage.OTHER, R.string.fm_drive_linux, abs)
|
||||||
|
}
|
||||||
|
|
||||||
|
return FavLocation(FavStorage.OTHER, R.string.fm_drive_storage, abs)
|
||||||
}
|
}
|
||||||
@@ -22,6 +22,7 @@ import androidx.compose.foundation.layout.width
|
|||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.lazy.grid.GridCells
|
import androidx.compose.foundation.lazy.grid.GridCells
|
||||||
|
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||||
import androidx.compose.foundation.lazy.grid.items
|
import androidx.compose.foundation.lazy.grid.items
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
@@ -41,6 +42,7 @@ import androidx.compose.material.icons.filled.ViewList
|
|||||||
import androidx.compose.material.icons.filled.StarBorder
|
import androidx.compose.material.icons.filled.StarBorder
|
||||||
import androidx.compose.material.icons.filled.Storage
|
import androidx.compose.material.icons.filled.Storage
|
||||||
import androidx.compose.material.icons.filled.Smartphone
|
import androidx.compose.material.icons.filled.Smartphone
|
||||||
|
import androidx.compose.material.icons.filled.Terminal
|
||||||
import androidx.compose.material.icons.filled.Download
|
import androidx.compose.material.icons.filled.Download
|
||||||
import androidx.compose.material.icons.filled.Description
|
import androidx.compose.material.icons.filled.Description
|
||||||
import androidx.compose.material.icons.filled.Image
|
import androidx.compose.material.icons.filled.Image
|
||||||
@@ -76,6 +78,9 @@ import androidx.compose.ui.draw.clip
|
|||||||
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
||||||
import androidx.compose.ui.platform.LocalConfiguration
|
import androidx.compose.ui.platform.LocalConfiguration
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.pluralStringResource
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||||
import androidx.lifecycle.Lifecycle
|
import androidx.lifecycle.Lifecycle
|
||||||
import androidx.lifecycle.LifecycleEventObserver
|
import androidx.lifecycle.LifecycleEventObserver
|
||||||
@@ -140,7 +145,14 @@ fun FileManagerScreen(
|
|||||||
val name = abs.removePrefix("/storage/").substringBefore('/')
|
val name = abs.removePrefix("/storage/").substringBefore('/')
|
||||||
if (name.isNotEmpty() && name != "emulated" && name != "self") File("/storage/$name") else rootDir
|
if (name.isNotEmpty() && name != "emulated" && name != "self") File("/storage/$name") else rootDir
|
||||||
}
|
}
|
||||||
else -> rootDir
|
// A game's own folder or Proton prefix lives in the app's private storage, which has no
|
||||||
|
// volume above it: floor at the app's files dir so up/back still reach the library roots.
|
||||||
|
else -> {
|
||||||
|
val appFiles = runCatching { context.filesDir.canonicalPath }.getOrNull()
|
||||||
|
generateSequence(rootDir) { it.parentFile }
|
||||||
|
.firstOrNull { appFiles != null && runCatching { it.canonicalPath }.getOrNull() == appFiles }
|
||||||
|
?: rootDir
|
||||||
|
}
|
||||||
}
|
}
|
||||||
mutableStateOf(vol)
|
mutableStateOf(vol)
|
||||||
}
|
}
|
||||||
@@ -229,7 +241,9 @@ fun FileManagerScreen(
|
|||||||
loadDirectory(dir)
|
loadDirectory(dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(Unit) { openDrive(rootDir) }
|
// Open the start dir without openDrive(): that pins the floor to the start dir itself, which
|
||||||
|
// greyed out up/back whenever the manager was opened at a game's folder.
|
||||||
|
LaunchedEffect(Unit) { loadDirectory(rootDir) }
|
||||||
|
|
||||||
// System/gesture Back: while the Favorites view is open it closes that first; otherwise
|
// System/gesture Back: while the Favorites view is open it closes that first; otherwise
|
||||||
// it goes up one directory. Only at the current drive's root with Favorites closed is it
|
// it goes up one directory. Only at the current drive's root with Favorites closed is it
|
||||||
@@ -243,6 +257,14 @@ fun FileManagerScreen(
|
|||||||
if (parent != null && parent.exists()) loadDirectory(parent)
|
if (parent != null && parent.exists()) loadDirectory(parent)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// One level up, never above the current drive's root: shared by the toolbar arrow and the
|
||||||
|
// ".." row at the top of the list.
|
||||||
|
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
||||||
|
fun goUp() {
|
||||||
|
val parent = currentDir.parentFile
|
||||||
|
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
|
||||||
|
}
|
||||||
|
|
||||||
// Resolve a non-colliding destination in [dir] for [name] (foo.txt -> "foo (1).txt").
|
// Resolve a non-colliding destination in [dir] for [name] (foo.txt -> "foo (1).txt").
|
||||||
fun uniqueDestination(dir: File, name: String): File {
|
fun uniqueDestination(dir: File, name: String): File {
|
||||||
var candidate = File(dir, name)
|
var candidate = File(dir, name)
|
||||||
@@ -261,11 +283,11 @@ fun FileManagerScreen(
|
|||||||
fun performDelete(file: File) {
|
fun performDelete(file: File) {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
operationLabel = "Deleting..."
|
operationLabel = context.getString(R.string.fm_op_deleting)
|
||||||
val ok = withContext(Dispatchers.IO) { FileOps.delete(file) }
|
val ok = withContext(Dispatchers.IO) { FileOps.delete(file) }
|
||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
if (!ok) Toast.makeText(context, "Delete failed", Toast.LENGTH_SHORT).show()
|
if (!ok) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,7 +310,7 @@ fun FileManagerScreen(
|
|||||||
operationJob = scope.launch {
|
operationJob = scope.launch {
|
||||||
operationProgress = 0f
|
operationProgress = 0f
|
||||||
operationDeterminate = true
|
operationDeterminate = true
|
||||||
operationLabel = if (cut) "Moving..." else "Copying..."
|
operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying)
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
|
|
||||||
var applyToAll: ConflictChoice? = null
|
var applyToAll: ConflictChoice? = null
|
||||||
@@ -324,10 +346,10 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Progress is per item; with a batch the label carries the overall position.
|
// Progress is per item; with a batch the label carries the overall position.
|
||||||
operationLabel = buildString {
|
operationLabel = if (sources.size > 1) {
|
||||||
append(if (cut) "Moving" else "Copying")
|
context.getString(if (cut) R.string.fm_op_moving_batch else R.string.fm_op_copying_batch, done + 1, sources.size, src.name)
|
||||||
if (sources.size > 1) append(" ${done + 1}/${sources.size}")
|
} else {
|
||||||
append(" - ").append(src.name)
|
context.getString(if (cut) R.string.fm_op_moving_item else R.string.fm_op_copying_item, src.name)
|
||||||
}
|
}
|
||||||
var lastPct = -1
|
var lastPct = -1
|
||||||
val onProgress = FileOps.ProgressCallback { copied, total ->
|
val onProgress = FileOps.ProgressCallback { copied, total ->
|
||||||
@@ -355,9 +377,9 @@ fun FileManagerScreen(
|
|||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
|
|
||||||
val message = when {
|
val message = when {
|
||||||
failed > 0 -> "$done done, $failed failed"
|
failed > 0 -> context.getString(R.string.fm_paste_failed, done, failed)
|
||||||
skipped > 0 -> "$done done, $skipped skipped"
|
skipped > 0 -> context.getString(R.string.fm_paste_skipped, done, skipped)
|
||||||
sources.size > 1 -> "$done items ${if (cut) "moved" else "copied"}"
|
sources.size > 1 -> context.resources.getQuantityString(if (cut) R.plurals.fm_paste_moved else R.plurals.fm_paste_copied, done, done)
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
if (message != null) Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
if (message != null) Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
||||||
@@ -367,32 +389,32 @@ fun FileManagerScreen(
|
|||||||
fun performRename(file: File, newName: String) {
|
fun performRename(file: File, newName: String) {
|
||||||
val target = File(file.parentFile, newName)
|
val target = File(file.parentFile, newName)
|
||||||
if (target.exists()) {
|
if (target.exists()) {
|
||||||
Toast.makeText(context, "\"$newName\" already exists", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_already_exists, newName), Toast.LENGTH_SHORT).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
scope.launch {
|
scope.launch {
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
operationLabel = "Renaming..."
|
operationLabel = context.getString(R.string.fm_op_renaming)
|
||||||
val ok = withContext(Dispatchers.IO) { file.renameTo(target) }
|
val ok = withContext(Dispatchers.IO) { file.renameTo(target) }
|
||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
if (!ok) Toast.makeText(context, "Rename failed", Toast.LENGTH_SHORT).show()
|
if (!ok) Toast.makeText(context, R.string.fm_rename_failed, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun createFolder(parent: File, name: String) {
|
fun createFolder(parent: File, name: String) {
|
||||||
val target = File(parent, name)
|
val target = File(parent, name)
|
||||||
if (target.exists()) {
|
if (target.exists()) {
|
||||||
Toast.makeText(context, "\"$name\" already exists", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
scope.launch {
|
scope.launch {
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
operationLabel = "Creating folder..."
|
operationLabel = context.getString(R.string.fm_op_creating_folder)
|
||||||
val ok = withContext(Dispatchers.IO) { target.mkdirs() }
|
val ok = withContext(Dispatchers.IO) { target.mkdirs() }
|
||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
if (!ok) Toast.makeText(context, "Could not create folder", Toast.LENGTH_SHORT).show()
|
if (!ok) Toast.makeText(context, R.string.fm_create_folder_failed, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,6 +431,9 @@ fun FileManagerScreen(
|
|||||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||||
}
|
}
|
||||||
val drives = remember(storageTick) { StorageRoots.list(context) }
|
val drives = remember(storageTick) { StorageRoots.list(context) }
|
||||||
|
val linuxRoot = remember(storageTick) {
|
||||||
|
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
|
||||||
|
}
|
||||||
|
|
||||||
// ── Dialogs ──
|
// ── Dialogs ──
|
||||||
|
|
||||||
@@ -416,12 +441,12 @@ fun FileManagerScreen(
|
|||||||
var folderName by remember { mutableStateOf("") }
|
var folderName by remember { mutableStateOf("") }
|
||||||
OutlinedAlertDialog(
|
OutlinedAlertDialog(
|
||||||
onDismissRequest = { showNewFolderDialog = false },
|
onDismissRequest = { showNewFolderDialog = false },
|
||||||
title = { Text("New Folder") },
|
title = { Text(stringResource(R.string.fm_new_folder)) },
|
||||||
text = {
|
text = {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = folderName,
|
value = folderName,
|
||||||
onValueChange = { folderName = it },
|
onValueChange = { folderName = it },
|
||||||
label = { Text("Folder name") },
|
label = { Text(stringResource(R.string.fm_folder_name)) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -429,9 +454,9 @@ fun FileManagerScreen(
|
|||||||
TextButton(onClick = {
|
TextButton(onClick = {
|
||||||
showNewFolderDialog = false
|
showNewFolderDialog = false
|
||||||
if (folderName.isNotBlank()) createFolder(currentDir, folderName)
|
if (folderName.isNotBlank()) createFolder(currentDir, folderName)
|
||||||
}) { Text("Create") }
|
}) { Text(stringResource(R.string.fm_create)) }
|
||||||
},
|
},
|
||||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text("Cancel") } },
|
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -439,12 +464,12 @@ fun FileManagerScreen(
|
|||||||
var newName by remember(renameTarget) { mutableStateOf(renameTarget?.name ?: "") }
|
var newName by remember(renameTarget) { mutableStateOf(renameTarget?.name ?: "") }
|
||||||
OutlinedAlertDialog(
|
OutlinedAlertDialog(
|
||||||
onDismissRequest = { renameTarget = null },
|
onDismissRequest = { renameTarget = null },
|
||||||
title = { Text("Rename") },
|
title = { Text(stringResource(R.string.fm_rename)) },
|
||||||
text = {
|
text = {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = newName,
|
value = newName,
|
||||||
onValueChange = { newName = it },
|
onValueChange = { newName = it },
|
||||||
label = { Text("New name") },
|
label = { Text(stringResource(R.string.fm_new_name)) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -453,9 +478,9 @@ fun FileManagerScreen(
|
|||||||
val file = renameTarget
|
val file = renameTarget
|
||||||
renameTarget = null
|
renameTarget = null
|
||||||
if (file != null && newName.isNotBlank()) performRename(file, newName)
|
if (file != null && newName.isNotBlank()) performRename(file, newName)
|
||||||
}) { Text("Rename") }
|
}) { Text(stringResource(R.string.fm_rename)) }
|
||||||
},
|
},
|
||||||
dismissButton = { TextButton(onClick = { renameTarget = null }) { Text("Cancel") } },
|
dismissButton = { TextButton(onClick = { renameTarget = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -473,15 +498,15 @@ fun FileManagerScreen(
|
|||||||
val file = selectedEntry ?: return
|
val file = selectedEntry ?: return
|
||||||
OutlinedAlertDialog(
|
OutlinedAlertDialog(
|
||||||
onDismissRequest = { selectedEntry = null },
|
onDismissRequest = { selectedEntry = null },
|
||||||
title = { Text("Delete?") },
|
title = { Text(stringResource(R.string.fm_delete_title)) },
|
||||||
text = { Text("Delete \"${file.name}\" permanently?") },
|
text = { Text(stringResource(R.string.fm_delete_text, file.name)) },
|
||||||
confirmButton = {
|
confirmButton = {
|
||||||
TextButton(onClick = {
|
TextButton(onClick = {
|
||||||
selectedEntry = null
|
selectedEntry = null
|
||||||
performDelete(file)
|
performDelete(file)
|
||||||
}) { Text("Delete") }
|
}) { Text(stringResource(R.string.common_delete)) }
|
||||||
},
|
},
|
||||||
dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text("Cancel") } },
|
dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -489,10 +514,10 @@ fun FileManagerScreen(
|
|||||||
val victims = pendingBulkDelete
|
val victims = pendingBulkDelete
|
||||||
OutlinedAlertDialog(
|
OutlinedAlertDialog(
|
||||||
onDismissRequest = { pendingBulkDelete = emptyList() },
|
onDismissRequest = { pendingBulkDelete = emptyList() },
|
||||||
title = { Text("Delete ${victims.size} item${if (victims.size == 1) "" else "s"}?") },
|
title = { Text(pluralStringResource(R.plurals.fm_delete_items_title, victims.size, victims.size)) },
|
||||||
text = {
|
text = {
|
||||||
Column {
|
Column {
|
||||||
Text("This can't be undone.")
|
Text(stringResource(R.string.fm_cannot_undo))
|
||||||
Spacer(Modifier.height(6.dp))
|
Spacer(Modifier.height(6.dp))
|
||||||
// Name a few so an accidental Select-All is obvious before it's too late.
|
// Name a few so an accidental Select-All is obvious before it's too late.
|
||||||
victims.take(5).forEach {
|
victims.take(5).forEach {
|
||||||
@@ -500,7 +525,7 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
if (victims.size > 5) {
|
if (victims.size > 5) {
|
||||||
Text(
|
Text(
|
||||||
"…and ${victims.size - 5} more",
|
pluralStringResource(R.plurals.fm_and_more, victims.size - 5, victims.size - 5),
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
fontSize = 12.sp,
|
fontSize = 12.sp,
|
||||||
)
|
)
|
||||||
@@ -516,19 +541,19 @@ fun FileManagerScreen(
|
|||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
var failed = 0
|
var failed = 0
|
||||||
victims.forEachIndexed { i, f ->
|
victims.forEachIndexed { i, f ->
|
||||||
operationLabel = "Deleting ${i + 1}/${victims.size} - ${f.name}"
|
operationLabel = context.getString(R.string.fm_op_deleting_batch, i + 1, victims.size, f.name)
|
||||||
if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++
|
if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++
|
||||||
}
|
}
|
||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
operationJob = null
|
operationJob = null
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
if (failed > 0) {
|
if (failed > 0) {
|
||||||
Toast.makeText(context, "$failed couldn't be deleted", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}) { Text("Delete", color = MaterialTheme.colorScheme.error) }
|
}) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||||
},
|
},
|
||||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text("Cancel") } },
|
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text(stringResource(R.string.common_cancel)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -537,12 +562,12 @@ fun FileManagerScreen(
|
|||||||
val isDir = conflict.isDirectory
|
val isDir = conflict.isDirectory
|
||||||
OutlinedAlertDialog(
|
OutlinedAlertDialog(
|
||||||
onDismissRequest = { pendingConflict = null },
|
onDismissRequest = { pendingConflict = null },
|
||||||
title = { Text("\"${conflict.name}\" already exists") },
|
title = { Text(stringResource(R.string.fm_already_exists, conflict.name)) },
|
||||||
text = {
|
text = {
|
||||||
Column {
|
Column {
|
||||||
Text(
|
Text(
|
||||||
if (isDir) "Merge adds and replaces files inside the existing folder."
|
if (isDir) stringResource(R.string.fm_conflict_merge_hint)
|
||||||
else "Overwrite replaces the existing file.",
|
else stringResource(R.string.fm_conflict_overwrite_hint),
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
fontSize = 12.sp,
|
fontSize = 12.sp,
|
||||||
)
|
)
|
||||||
@@ -553,15 +578,15 @@ fun FileManagerScreen(
|
|||||||
checked = conflictApplyToAll,
|
checked = conflictApplyToAll,
|
||||||
onCheckedChange = { conflictApplyToAll = it },
|
onCheckedChange = { conflictApplyToAll = it },
|
||||||
)
|
)
|
||||||
Text("Apply to all conflicts", fontSize = 12.sp)
|
Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(4.dp))
|
||||||
listOf(
|
listOf(
|
||||||
(if (isDir) ConflictChoice.MERGE else ConflictChoice.OVERWRITE) to
|
(if (isDir) ConflictChoice.MERGE else ConflictChoice.OVERWRITE) to
|
||||||
(if (isDir) "Merge" else "Overwrite"),
|
(if (isDir) stringResource(R.string.fm_conflict_merge) else stringResource(R.string.fm_conflict_overwrite)),
|
||||||
ConflictChoice.KEEP_BOTH to "Keep both",
|
ConflictChoice.KEEP_BOTH to stringResource(R.string.fm_conflict_keep_both),
|
||||||
ConflictChoice.SKIP to "Skip",
|
ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip),
|
||||||
).forEach { (choice, label) ->
|
).forEach { (choice, label) ->
|
||||||
TextButton(
|
TextButton(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
@@ -573,7 +598,7 @@ fun FileManagerScreen(
|
|||||||
confirmButton = {},
|
confirmButton = {},
|
||||||
dismissButton = {
|
dismissButton = {
|
||||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) {
|
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) {
|
||||||
Text("Cancel")
|
Text(stringResource(R.string.common_cancel))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -603,7 +628,7 @@ fun FileManagerScreen(
|
|||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
|
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Text("Select this folder")
|
Text(stringResource(R.string.fm_select_this_folder))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// ── Path bar ──
|
// ── Path bar ──
|
||||||
@@ -614,15 +639,11 @@ fun FileManagerScreen(
|
|||||||
.background(MaterialTheme.colorScheme.surfaceContainer)
|
.background(MaterialTheme.colorScheme.surfaceContainer)
|
||||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||||
) {
|
) {
|
||||||
IconButton(onClick = {
|
IconButton(onClick = { goUp() }, enabled = canGoUp) {
|
||||||
val parent = currentDir.parentFile
|
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
|
||||||
// Don't climb above the current drive's root.
|
|
||||||
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
|
|
||||||
}, enabled = currentDir != currentRoot) {
|
|
||||||
Icon(Icons.Filled.ArrowBack, "Back", tint = MaterialTheme.colorScheme.primary)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val currentDriveLabel = describeLocation(currentDir).driveLabel
|
val currentDriveLabel = stringResource(describeLocation(currentDir).driveLabel)
|
||||||
// Dim the drive chip while the Favorites list is open (it's not the active context).
|
// Dim the drive chip while the Favorites list is open (it's not the active context).
|
||||||
val driveChipAlpha = if (showFavorites) 0.45f else 1f
|
val driveChipAlpha = if (showFavorites) 0.45f else 1f
|
||||||
Box {
|
Box {
|
||||||
@@ -666,13 +687,23 @@ fun FileManagerScreen(
|
|||||||
} else {
|
} else {
|
||||||
Toast.makeText(
|
Toast.makeText(
|
||||||
context,
|
context,
|
||||||
"${drive.label} is mounted but not readable right now",
|
context.getString(R.string.fm_drive_not_readable, drive.label),
|
||||||
Toast.LENGTH_SHORT,
|
Toast.LENGTH_SHORT,
|
||||||
).show()
|
).show()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
linuxRoot?.let { root ->
|
||||||
|
MenuItemDivider()
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(stringResource(R.string.fm_drive_linux)) },
|
||||||
|
leadingIcon = {
|
||||||
|
Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||||
|
},
|
||||||
|
onClick = { showDriveMenu = false; openDrive(root) },
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -680,7 +711,7 @@ fun FileManagerScreen(
|
|||||||
|
|
||||||
if (showFavorites) {
|
if (showFavorites) {
|
||||||
Text(
|
Text(
|
||||||
text = "Favorites",
|
text = stringResource(R.string.fm_favorites),
|
||||||
color = MaterialTheme.colorScheme.primary,
|
color = MaterialTheme.colorScheme.primary,
|
||||||
fontSize = 13.sp,
|
fontSize = 13.sp,
|
||||||
fontWeight = FontWeight.SemiBold,
|
fontWeight = FontWeight.SemiBold,
|
||||||
@@ -718,7 +749,7 @@ fun FileManagerScreen(
|
|||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||||
Spacer(Modifier.width(5.dp))
|
Spacer(Modifier.width(5.dp))
|
||||||
Text("New Folder", color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp)
|
Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
IconButton(onClick = {
|
IconButton(onClick = {
|
||||||
@@ -727,19 +758,19 @@ fun FileManagerScreen(
|
|||||||
}) {
|
}) {
|
||||||
Icon(
|
Icon(
|
||||||
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
||||||
if (gridView) "List view" else "Grid view",
|
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
|
||||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) {
|
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) {
|
||||||
Icon(Icons.Filled.Search, "Search", tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
Box {
|
Box {
|
||||||
IconButton(onClick = { showSortMenu = true }) {
|
IconButton(onClick = { showSortMenu = true }) {
|
||||||
Icon(Icons.Filled.Sort, "Sort", tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
|
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
|
||||||
listOf("name" to "Name", "date" to "Date modified", "size" to "Size")
|
listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size))
|
||||||
.forEach { (key, label) ->
|
.forEach { (key, label) ->
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = {
|
text = {
|
||||||
@@ -758,7 +789,7 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(if (compactRows) "Comfortable rows" else "Compact rows") },
|
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) },
|
||||||
onClick = {
|
onClick = {
|
||||||
compactRows = !compactRows
|
compactRows = !compactRows
|
||||||
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
|
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
|
||||||
@@ -766,7 +797,7 @@ fun FileManagerScreen(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(if (showHidden) "Hide hidden files" else "Show hidden files") },
|
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
|
||||||
onClick = {
|
onClick = {
|
||||||
showHidden = !showHidden
|
showHidden = !showHidden
|
||||||
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
|
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
|
||||||
@@ -781,9 +812,9 @@ fun FileManagerScreen(
|
|||||||
// Star toggle: open/close the dedicated Favorites list.
|
// Star toggle: open/close the dedicated Favorites list.
|
||||||
IconButton(onClick = { showFavorites = !showFavorites }) {
|
IconButton(onClick = { showFavorites = !showFavorites }) {
|
||||||
if (showFavorites) {
|
if (showFavorites) {
|
||||||
Icon(Icons.Filled.Star, "Hide favorites", tint = MaterialTheme.colorScheme.primary)
|
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
|
||||||
} else {
|
} else {
|
||||||
Icon(Icons.Filled.StarBorder, "Show favorites", tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -794,7 +825,7 @@ fun FileManagerScreen(
|
|||||||
value = searchQuery,
|
value = searchQuery,
|
||||||
onValueChange = { searchQuery = it },
|
onValueChange = { searchQuery = it },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
placeholder = { Text("Filter this folder", fontSize = 13.sp) },
|
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),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -821,7 +852,7 @@ fun FileManagerScreen(
|
|||||||
)
|
)
|
||||||
if (freeSpace > 0) {
|
if (freeSpace > 0) {
|
||||||
Text(
|
Text(
|
||||||
"${FileOps.formatBytes(freeSpace)} free",
|
stringResource(R.string.fm_free_space, FileOps.formatBytes(context, freeSpace)),
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
fontSize = 12.sp,
|
fontSize = 12.sp,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
@@ -842,7 +873,7 @@ fun FileManagerScreen(
|
|||||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
"${selectedPaths.size} selected",
|
stringResource(R.string.fm_selected_count, selectedPaths.size),
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
fontSize = 13.sp,
|
fontSize = 13.sp,
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
@@ -855,7 +886,7 @@ fun FileManagerScreen(
|
|||||||
else entries.map { it.absolutePath }.toSet()
|
else entries.map { it.absolutePath }.toSet()
|
||||||
},
|
},
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
) { Text(if (selectedPaths.size == entries.size) "None" else "All", fontSize = 12.sp) }
|
) { Text(if (selectedPaths.size == entries.size) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) }
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
enabled = selectedPaths.isNotEmpty(),
|
enabled = selectedPaths.isNotEmpty(),
|
||||||
@@ -866,7 +897,7 @@ fun FileManagerScreen(
|
|||||||
selectedPaths = emptySet()
|
selectedPaths = emptySet()
|
||||||
},
|
},
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
) { Text("Copy", fontSize = 12.sp) }
|
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) }
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
enabled = selectedPaths.isNotEmpty(),
|
enabled = selectedPaths.isNotEmpty(),
|
||||||
@@ -877,19 +908,19 @@ fun FileManagerScreen(
|
|||||||
selectedPaths = emptySet()
|
selectedPaths = emptySet()
|
||||||
},
|
},
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
) { Text("Cut", fontSize = 12.sp) }
|
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) }
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
enabled = selectedPaths.isNotEmpty(),
|
enabled = selectedPaths.isNotEmpty(),
|
||||||
onClick = { pendingBulkDelete = entries.filter { it.absolutePath in selectedPaths } },
|
onClick = { pendingBulkDelete = entries.filter { it.absolutePath in selectedPaths } },
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
|
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
|
||||||
) { Text("Delete", color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
|
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onClick = { selectionMode = false; selectedPaths = emptySet() },
|
onClick = { selectionMode = false; selectedPaths = emptySet() },
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
) { Text("Done", fontSize = 12.sp) }
|
) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -903,16 +934,16 @@ fun FileManagerScreen(
|
|||||||
.clickable { performPaste() }
|
.clickable { performPaste() }
|
||||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.ContentPaste, "Paste", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
Icon(Icons.Filled.ContentPaste, stringResource(R.string.fm_paste), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
val what = if (clipboardFiles.size == 1) clipboardFiles.first().name
|
val what = if (clipboardFiles.size == 1) clipboardFiles.first().name
|
||||||
else "${clipboardFiles.size} items"
|
else pluralStringResource(R.plurals.fm_items, clipboardFiles.size, clipboardFiles.size)
|
||||||
Text(
|
Text(
|
||||||
"Paste $what${if (isCutOperation) " (move)" else ""} here",
|
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),
|
color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) {
|
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) {
|
||||||
Text("Cancel", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
|
Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -944,7 +975,7 @@ fun FileManagerScreen(
|
|||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
operationDeterminate = false
|
operationDeterminate = false
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
}) { Text("Cancel", fontSize = 12.sp) }
|
}) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(4.dp))
|
||||||
@@ -970,38 +1001,40 @@ fun FileManagerScreen(
|
|||||||
// shown in pick mode (the themed picker keeps its slim layout). Built each recompose (cheap)
|
// shown in pick mode (the themed picker keeps its slim layout). Built each recompose (cheap)
|
||||||
// so it tracks the current drive/favourites without stale click lambdas.
|
// so it tracks the current drive/favourites without stale click lambdas.
|
||||||
val fmRailState = rememberRailState("filemanager")
|
val fmRailState = rememberRailState("filemanager")
|
||||||
fun locItem(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, dir: File) =
|
fun locItem(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, dir: File, shortLabel: String? = null) =
|
||||||
RailItem(label, icon, !showFavorites && currentRoot.absolutePath == dir.absolutePath) {
|
RailItem(label, icon, !showFavorites && currentRoot.absolutePath == dir.absolutePath, shortLabel = shortLabel) {
|
||||||
showFavorites = false; openDrive(dir)
|
showFavorites = false; openDrive(dir)
|
||||||
}
|
}
|
||||||
val storageItems = buildList {
|
val storageItems = buildList {
|
||||||
add(locItem("Internal", Icons.Filled.Smartphone, File("/storage/emulated/0")))
|
add(locItem(stringResource(R.string.fm_drive_internal), Icons.Filled.Smartphone, File("/storage/emulated/0")))
|
||||||
drives.filter { it.removable }.forEach { d ->
|
drives.filter { it.removable }.forEach { d ->
|
||||||
add(RailItem(d.label, Icons.Filled.SdStorage, !showFavorites && currentRoot.absolutePath == d.dir.absolutePath) {
|
add(RailItem(d.label, Icons.Filled.SdStorage, !showFavorites && currentRoot.absolutePath == d.dir.absolutePath) {
|
||||||
showFavorites = false; if (d.readable) openDrive(d.dir)
|
showFavorites = false; if (d.readable) openDrive(d.dir)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
// The Linux system the sessions run in: its own / (the desktop's root), once installed.
|
||||||
|
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
|
||||||
}
|
}
|
||||||
val quickItems = buildList {
|
val quickItems = buildList {
|
||||||
File("/storage/emulated/0/Download").takeIf { it.isDirectory }?.let { add(locItem("Downloads", Icons.Filled.Download, it)) }
|
File("/storage/emulated/0/Download").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_downloads), Icons.Filled.Download, it, stringResource(R.string.fm_rail_downloads_short))) }
|
||||||
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
|
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
|
||||||
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
|
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
|
||||||
?.let { add(locItem("ROMs", Icons.Filled.SportsEsports, it)) }
|
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) }
|
||||||
File("/storage/emulated/0/Download/DroidDeck").takeIf { it.isDirectory }?.let { add(locItem("Session logs", Icons.Filled.Description, it)) }
|
File("/storage/emulated/0/Download/DroidDeck").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
|
||||||
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem("Pictures", Icons.Filled.Image, it)) }
|
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) }
|
||||||
}
|
}
|
||||||
val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } }
|
val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } }
|
||||||
.map { d -> RailItem(d.name, Icons.Filled.Star, false) { showFavorites = false; openDrive(d) } }
|
.map { d -> RailItem(d.name, Icons.Filled.Star, false) { showFavorites = false; openDrive(d) } }
|
||||||
val locationSections = buildList {
|
val locationSections = buildList {
|
||||||
add(RailSection("STORAGE", storageItems))
|
add(RailSection(stringResource(R.string.fm_rail_storage), storageItems))
|
||||||
if (quickItems.isNotEmpty()) add(RailSection("QUICK", quickItems))
|
if (quickItems.isNotEmpty()) add(RailSection(stringResource(R.string.fm_rail_quick), quickItems))
|
||||||
if (favItems.isNotEmpty()) add(RailSection("FAVORITES", favItems))
|
if (favItems.isNotEmpty()) add(RailSection(stringResource(R.string.fm_rail_favorites), favItems))
|
||||||
}
|
}
|
||||||
|
|
||||||
Row(modifier = Modifier.weight(1f).fillMaxWidth()) {
|
Row(modifier = Modifier.weight(1f).fillMaxWidth()) {
|
||||||
// The slim picker keeps its layout: no rail.
|
// The slim picker keeps its layout: no rail.
|
||||||
if (!pickMode) {
|
if (!pickMode) {
|
||||||
CollapsibleRail(state = fmRailState, title = "Files", sections = locationSections, outlinedItems = true)
|
CollapsibleRail(state = fmRailState, title = stringResource(R.string.fm_rail_title), sections = locationSections, outlinedItems = true)
|
||||||
}
|
}
|
||||||
Box(modifier = Modifier.weight(1f).fillMaxSize()) {
|
Box(modifier = Modifier.weight(1f).fillMaxSize()) {
|
||||||
// ── Favorites list OR file list ──
|
// ── Favorites list OR file list ──
|
||||||
@@ -1012,7 +1045,7 @@ fun FileManagerScreen(
|
|||||||
onPinCurrent = {
|
onPinCurrent = {
|
||||||
FavoritesStore.add(context, currentDir.absolutePath)
|
FavoritesStore.add(context, currentDir.absolutePath)
|
||||||
favTick++
|
favTick++
|
||||||
Toast.makeText(context, "Added \"${currentDir.name}\" to Favorites", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_favorite_added, currentDir.name), Toast.LENGTH_SHORT).show()
|
||||||
},
|
},
|
||||||
onJump = { dir ->
|
onJump = { dir ->
|
||||||
showFavorites = false
|
showFavorites = false
|
||||||
@@ -1021,7 +1054,7 @@ fun FileManagerScreen(
|
|||||||
onUnpin = { dir ->
|
onUnpin = { dir ->
|
||||||
FavoritesStore.remove(context, dir.absolutePath)
|
FavoritesStore.remove(context, dir.absolutePath)
|
||||||
favTick++
|
favTick++
|
||||||
Toast.makeText(context, "Removed \"${dir.name}\" from Favorites", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_favorite_removed, dir.name), Toast.LENGTH_SHORT).show()
|
||||||
},
|
},
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
)
|
)
|
||||||
@@ -1041,6 +1074,9 @@ fun FileManagerScreen(
|
|||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
contentPadding = PaddingValues(8.dp),
|
contentPadding = PaddingValues(8.dp),
|
||||||
) {
|
) {
|
||||||
|
if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) {
|
||||||
|
ParentFolderRow(compact = compactRows, onTap = { goUp() })
|
||||||
|
}
|
||||||
items(shownEntries, key = { it.absolutePath }) { file ->
|
items(shownEntries, key = { it.absolutePath }) { file ->
|
||||||
val isFav = remember(file.absolutePath, favTick) {
|
val isFav = remember(file.absolutePath, favTick) {
|
||||||
FavoritesStore.isFavorite(context, file.absolutePath)
|
FavoritesStore.isFavorite(context, file.absolutePath)
|
||||||
@@ -1095,8 +1131,8 @@ fun FileManagerScreen(
|
|||||||
showMenuFor = null
|
showMenuFor = null
|
||||||
Toast.makeText(
|
Toast.makeText(
|
||||||
context,
|
context,
|
||||||
if (nowFav) "Added \"${file.name}\" to Favorites"
|
if (nowFav) context.getString(R.string.fm_favorite_added, file.name)
|
||||||
else "Removed \"${file.name}\" from Favorites",
|
else context.getString(R.string.fm_favorite_removed, file.name),
|
||||||
Toast.LENGTH_SHORT,
|
Toast.LENGTH_SHORT,
|
||||||
).show()
|
).show()
|
||||||
},
|
},
|
||||||
@@ -1106,13 +1142,16 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
} else
|
} else
|
||||||
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
|
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
|
||||||
|
if (canGoUp) item(key = "..") {
|
||||||
|
ParentFolderRow(compact = compactRows, onTap = { goUp() })
|
||||||
|
}
|
||||||
if (entries.isEmpty()) {
|
if (entries.isEmpty()) {
|
||||||
item {
|
item {
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier.fillParentMaxSize(),
|
modifier = Modifier.fillParentMaxSize(),
|
||||||
contentAlignment = Alignment.Center,
|
contentAlignment = Alignment.Center,
|
||||||
) {
|
) {
|
||||||
Text("Empty directory", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
Text(stringResource(R.string.fm_empty_directory), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -1173,8 +1212,8 @@ fun FileManagerScreen(
|
|||||||
showMenuFor = null
|
showMenuFor = null
|
||||||
Toast.makeText(
|
Toast.makeText(
|
||||||
context,
|
context,
|
||||||
if (nowFav) "Added \"${file.name}\" to Favorites"
|
if (nowFav) context.getString(R.string.fm_favorite_added, file.name)
|
||||||
else "Removed \"${file.name}\" from Favorites",
|
else context.getString(R.string.fm_favorite_removed, file.name),
|
||||||
Toast.LENGTH_SHORT,
|
Toast.LENGTH_SHORT,
|
||||||
).show()
|
).show()
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.droiddeck.launcher.files
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileInputStream
|
import java.io.FileInputStream
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
@@ -19,9 +21,9 @@ object FileOps {
|
|||||||
/** Byte-accurate copy progress (copied/total bytes), reported as the copy proceeds. */
|
/** Byte-accurate copy progress (copied/total bytes), reported as the copy proceeds. */
|
||||||
fun interface ProgressCallback { fun onProgress(copiedBytes: Long, totalBytes: Long) }
|
fun interface ProgressCallback { fun onProgress(copiedBytes: Long, totalBytes: Long) }
|
||||||
|
|
||||||
fun formatBytes(bytes: Long): String {
|
fun formatBytes(context: Context, bytes: Long): String {
|
||||||
if (bytes <= 0) return "0 bytes"
|
if (bytes <= 0) return context.getString(R.string.fm_size_zero)
|
||||||
val units = arrayOf("bytes", "KB", "MB", "GB", "TB")
|
val units = arrayOf(context.getString(R.string.fm_unit_bytes), "KB", "MB", "GB", "TB")
|
||||||
val group = (Math.log10(bytes.toDouble()) / Math.log10(1024.0)).toInt().coerceIn(0, units.lastIndex)
|
val group = (Math.log10(bytes.toDouble()) / Math.log10(1024.0)).toInt().coerceIn(0, units.lastIndex)
|
||||||
return String.format(Locale.ENGLISH, "%.2f", bytes / Math.pow(1024.0, group.toDouble())) + " " + units[group]
|
return String.format(Locale.ENGLISH, "%.2f", bytes / Math.pow(1024.0, group.toDouble())) + " " + units[group]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.systemBarsPadding
|
|||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
@@ -26,6 +27,11 @@ import java.io.File
|
|||||||
* - [EXTRA_PICKER_TITLE] the header
|
* - [EXTRA_PICKER_TITLE] the header
|
||||||
*/
|
*/
|
||||||
class FilePickerActivity : ComponentActivity() {
|
class FilePickerActivity : ComponentActivity() {
|
||||||
|
override fun attachBaseContext(newBase: android.content.Context) {
|
||||||
|
super.attachBaseContext(newBase)
|
||||||
|
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
@@ -50,7 +56,7 @@ class FilePickerActivity : ComponentActivity() {
|
|||||||
pickDirMode = pickDir,
|
pickDirMode = pickDir,
|
||||||
pickExtensions = extensions,
|
pickExtensions = extensions,
|
||||||
initialDir = initialDir,
|
initialDir = initialDir,
|
||||||
pickerTitle = title ?: if (pickDir) "Choose a folder" else "Choose a file",
|
pickerTitle = title ?: getString(if (pickDir) R.string.fm_choose_folder else R.string.fm_choose_file),
|
||||||
onPick = { file ->
|
onPick = { file ->
|
||||||
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
|
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
|
||||||
finish()
|
finish()
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import androidx.compose.runtime.setValue
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
@@ -66,7 +68,7 @@ internal fun FilePropertiesDialog(
|
|||||||
|
|
||||||
OutlinedAlertDialog(
|
OutlinedAlertDialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
title = { Text("Properties") },
|
title = { Text(stringResource(R.string.fm_properties)) },
|
||||||
text = {
|
text = {
|
||||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||||
// ── Basic info ──
|
// ── Basic info ──
|
||||||
@@ -79,14 +81,14 @@ internal fun FilePropertiesDialog(
|
|||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(6.dp))
|
Spacer(Modifier.height(6.dp))
|
||||||
PropertyLine("Location", file.parent ?: "-")
|
PropertyLine(stringResource(R.string.fm_prop_location), file.parent ?: "-")
|
||||||
PropertyLine(
|
PropertyLine(
|
||||||
"Type",
|
stringResource(R.string.fm_prop_type),
|
||||||
if (file.isDirectory) "Folder"
|
if (file.isDirectory) stringResource(R.string.fm_type_folder)
|
||||||
else file.extension.uppercase().let { if (it.isBlank()) "File" else "$it file" },
|
else file.extension.uppercase().let { if (it.isBlank()) stringResource(R.string.fm_type_file) else stringResource(R.string.fm_type_ext_file, it) },
|
||||||
)
|
)
|
||||||
if (!file.isDirectory) PropertyLine("Size", FileOps.formatBytes(file.length()))
|
if (!file.isDirectory) PropertyLine(stringResource(R.string.fm_prop_size), FileOps.formatBytes(context, file.length()))
|
||||||
PropertyLine("Modified", dateFormat.format(Date(file.lastModified())))
|
PropertyLine(stringResource(R.string.fm_prop_modified), dateFormat.format(Date(file.lastModified())))
|
||||||
|
|
||||||
Spacer(Modifier.height(10.dp))
|
Spacer(Modifier.height(10.dp))
|
||||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
||||||
@@ -95,8 +97,8 @@ internal fun FilePropertiesDialog(
|
|||||||
val state = attrs
|
val state = attrs
|
||||||
// ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY).
|
// ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY).
|
||||||
AttributeToggleRow(
|
AttributeToggleRow(
|
||||||
label = "Read-only",
|
label = stringResource(R.string.fm_read_only),
|
||||||
description = "Stops games (and Wine) from overwriting or deleting this file.",
|
description = stringResource(R.string.fm_read_only_hint),
|
||||||
checked = state?.readOnly == true,
|
checked = state?.readOnly == true,
|
||||||
enabled = state != null && !busy,
|
enabled = state != null && !busy,
|
||||||
onToggle = { want ->
|
onToggle = { want ->
|
||||||
@@ -108,7 +110,7 @@ internal fun FilePropertiesDialog(
|
|||||||
attrs = attrs?.copy(readOnly = want)
|
attrs = attrs?.copy(readOnly = want)
|
||||||
onChanged()
|
onChanged()
|
||||||
} else {
|
} else {
|
||||||
Toast.makeText(context, "Couldn't change Read-only", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, R.string.fm_read_only_failed, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -117,10 +119,10 @@ internal fun FilePropertiesDialog(
|
|||||||
// ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr.
|
// ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr.
|
||||||
val hiddenSupported = state?.hiddenSupported == true
|
val hiddenSupported = state?.hiddenSupported == true
|
||||||
AttributeToggleRow(
|
AttributeToggleRow(
|
||||||
label = "Hidden",
|
label = stringResource(R.string.fm_hidden),
|
||||||
description = if (state != null && !hiddenSupported)
|
description = if (state != null && !hiddenSupported)
|
||||||
"This storage can't store the hidden flag."
|
stringResource(R.string.fm_hidden_unsupported)
|
||||||
else "Marks the file hidden in Windows (Wine's hidden attribute).",
|
else stringResource(R.string.fm_hidden_hint),
|
||||||
checked = state?.hidden == true,
|
checked = state?.hidden == true,
|
||||||
enabled = state != null && hiddenSupported && !busy,
|
enabled = state != null && hiddenSupported && !busy,
|
||||||
onToggle = { want ->
|
onToggle = { want ->
|
||||||
@@ -134,14 +136,14 @@ internal fun FilePropertiesDialog(
|
|||||||
} else {
|
} else {
|
||||||
// The write failed after all - disable the toggle rather than lie.
|
// The write failed after all - disable the toggle rather than lie.
|
||||||
attrs = attrs?.copy(hiddenSupported = false)
|
attrs = attrs?.copy(hiddenSupported = false)
|
||||||
Toast.makeText(context, "Couldn't change Hidden on this storage", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, R.string.fm_hidden_failed, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
confirmButton = { TextButton(onClick = onDismiss) { Text("Done") } },
|
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.fm_done)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import android.os.Build
|
|||||||
import android.os.Environment
|
import android.os.Environment
|
||||||
import android.os.storage.StorageManager
|
import android.os.storage.StorageManager
|
||||||
import android.os.storage.StorageVolume
|
import android.os.storage.StorageVolume
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -63,7 +64,7 @@ object StorageRoots {
|
|||||||
|
|
||||||
// Internal storage is never removable and never absent; seed it first so it heads the menu.
|
// Internal storage is never removable and never absent; seed it first so it heads the menu.
|
||||||
volumeOf(PRIMARY_KEY).apply {
|
volumeOf(PRIMARY_KEY).apply {
|
||||||
label = "Internal"
|
label = context.getString(R.string.fm_drive_internal)
|
||||||
removable = false
|
removable = false
|
||||||
candidates += File(INTERNAL_PATH)
|
candidates += File(INTERNAL_PATH)
|
||||||
}
|
}
|
||||||
@@ -109,13 +110,13 @@ object StorageRoots {
|
|||||||
entry.seeds += dir
|
entry.seeds += dir
|
||||||
}
|
}
|
||||||
|
|
||||||
val roots = volumes.values.map { it.toRoot() }
|
val roots = volumes.values.map { it.toRoot(context) }
|
||||||
val internal = roots.filter { !it.removable }
|
val internal = roots.filter { !it.removable }
|
||||||
val removable = roots.filter { it.removable }.sortedBy { it.label }
|
val removable = roots.filter { it.removable }.sortedBy { it.label }
|
||||||
return disambiguate(internal + removable)
|
return disambiguate(internal + removable)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun Volume.toRoot(): StorageRoot {
|
private fun Volume.toRoot(context: Context): StorageRoot {
|
||||||
// Prefer a path we can actually list; a readable child beats an unreadable root.
|
// Prefer a path we can actually list; a readable child beats an unreadable root.
|
||||||
val dir = candidates.firstOrNull(::canBrowse)
|
val dir = candidates.firstOrNull(::canBrowse)
|
||||||
?: candidates.firstNotNullOfOrNull { root -> seeds.firstNotNullOfOrNull { deepestReadable(root, it) } }
|
?: candidates.firstNotNullOfOrNull { root -> seeds.firstNotNullOfOrNull { deepestReadable(root, it) } }
|
||||||
@@ -125,14 +126,14 @@ object StorageRoots {
|
|||||||
?: File("/storage/$key")
|
?: File("/storage/$key")
|
||||||
|
|
||||||
return StorageRoot(
|
return StorageRoot(
|
||||||
label = label ?: defaultLabel(),
|
label = label ?: defaultLabel(context),
|
||||||
dir = dir,
|
dir = dir,
|
||||||
removable = removable,
|
removable = removable,
|
||||||
readable = canBrowse(dir),
|
readable = canBrowse(dir),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun Volume.defaultLabel(): String = if (removable) "SD card" else key
|
private fun Volume.defaultLabel(context: Context): String = if (removable) context.getString(R.string.fm_drive_sd) else key
|
||||||
|
|
||||||
/** Appends the volume id to any label used by more than one volume, so entries stay tellable apart. */
|
/** Appends the volume id to any label used by more than one volume, so entries stay tellable apart. */
|
||||||
private fun disambiguate(roots: List<StorageRoot>): List<StorageRoot> {
|
private fun disambiguate(roots: List<StorageRoot>): List<StorageRoot> {
|
||||||
@@ -183,12 +184,12 @@ object StorageRoots {
|
|||||||
* name like "android", which tells the user nothing about which card they are looking at.
|
* name like "android", which tells the user nothing about which card they are looking at.
|
||||||
*/
|
*/
|
||||||
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
|
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
|
||||||
if (volume.isPrimary) return "Internal"
|
if (volume.isPrimary) return context.getString(R.string.fm_drive_internal)
|
||||||
if (volume.isRemovable) return "SD card"
|
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
|
||||||
val description = volume.getDescription(context)?.trim()
|
val description = volume.getDescription(context)?.trim()
|
||||||
return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
||||||
?: uuid
|
?: uuid
|
||||||
?: "Storage"
|
?: context.getString(R.string.fm_drive_storage)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
|
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ object AddedGames {
|
|||||||
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
|
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
|
||||||
val steamInstalls = steamInstallDirs(dir)
|
val steamInstalls = steamInstallDirs(dir)
|
||||||
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) {
|
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) {
|
||||||
if (folder.name.lowercase() in steamInstalls) continue
|
if (folder.name.lowercase() in steamInstalls || folder.name.equals("steamapps", ignoreCase = true)) continue
|
||||||
scanGame(context, folder, out)
|
scanGame(context, folder, out)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -126,32 +126,59 @@ object AddedGames {
|
|||||||
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
|
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
|
||||||
run {
|
run {
|
||||||
val candidates = candidates(folder)
|
val candidates = candidates(folder)
|
||||||
val chosen = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
val picked = SessionPrefs.addedGameExe(context, folder.path)
|
||||||
val exe = chosen ?: candidates.firstOrNull() ?: return
|
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||||
val guestExe = guestPath(context, exe)
|
val found = chosen ?: candidates.firstOrNull() ?: return
|
||||||
if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return }
|
val foundGuest = guestPath(context, found)
|
||||||
val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return
|
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${found.path}"); return }
|
||||||
val name = folder.name
|
val name = folder.name
|
||||||
// Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put.
|
// Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put.
|
||||||
val crc = CRC32().apply { update(("\"${guestExe.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value
|
val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value
|
||||||
val appId = crc or 0x80000000L
|
val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L)
|
||||||
val steamRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
val config = accountConfig(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"))
|
||||||
val steamId = steamRoute(steamRoot, appId)
|
val record = config?.let { shortcutRecord(it, appId) }
|
||||||
|
val rev = record?.optInt("rev", 0) ?: 0
|
||||||
|
val adopted = guestPath(context, folder)
|
||||||
|
?.let { steamTarget(folder, it, record, foundGuest, SessionPrefs.addedGameExeSeen(context, folder.path)) }
|
||||||
|
?.takeIf { SessionPrefs.adoptAddedGameExe(context, folder.path, picked, it.path, rev) }
|
||||||
|
val exe = adopted ?: found
|
||||||
|
val guestExe = if (adopted != null) guestPath(context, adopted) ?: return else foundGuest
|
||||||
|
val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return
|
||||||
|
val steamId = config?.let { steamRoute(it, appId) }
|
||||||
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
|
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
|
||||||
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId))
|
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun steamRoute(root: File, appId: Long): Int? = runCatching {
|
private fun accountConfig(root: File): File? {
|
||||||
val users = File(root, "config/loginusers.vdf").readText()
|
val users = runCatching { File(root, "config/loginusers.vdf").readText() }.getOrDefault("")
|
||||||
val blocks = Regex(""""(\d{5,})"\s*\{([^}]*)\}""")
|
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users)
|
||||||
val recent = blocks.findAll(users).firstOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
|
.lastOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
|
||||||
?: return@runCatching null
|
val account = recent?.groupValues?.get(1)?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
|
||||||
val account = recent.groupValues[1].toLong() - 76561197960265728L
|
?: File(root, "userdata").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) && it != "0" }?.singleOrNull()
|
||||||
JSONObject(File(root, "userdata/$account/config/.droiddeck-routes.json").readText())
|
return account?.let { File(root, "userdata/$it/config") }
|
||||||
.optInt(appId.toString()).takeIf { it > 0 }
|
}
|
||||||
|
|
||||||
|
private fun steamRoute(config: File, appId: Long): Int? = runCatching {
|
||||||
|
JSONObject(File(config, ".droiddeck-routes.json").readText()).optInt(appId.toString()).takeIf { it > 0 }
|
||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
|
|
||||||
|
private fun shortcutRecord(config: File, appId: Long): JSONObject? = runCatching {
|
||||||
|
JSONObject(File(config, ".droiddeck-shortcuts.json").readText()).optJSONObject("games")?.optJSONObject(appId.toString())
|
||||||
|
}.getOrNull()
|
||||||
|
|
||||||
|
internal fun steamTarget(folder: File, folderGuest: String, record: JSONObject?, guestExe: String, seen: Int): File? {
|
||||||
|
if (record == null || record.optInt("rev", 0) == seen) return null
|
||||||
|
val asked = unquote(record.optJSONObject("app")?.optString("Exe"))
|
||||||
|
val steam = unquote(record.optJSONObject("steam")?.optString("Exe"))
|
||||||
|
if (asked != guestExe || steam.isEmpty() || steam == asked || !steam.startsWith("$folderGuest/")) return null
|
||||||
|
val file = File(folder, steam.removePrefix("$folderGuest/"))
|
||||||
|
val inside = runCatching { file.canonicalPath.startsWith(folder.canonicalPath + File.separator) }.getOrDefault(false)
|
||||||
|
return file.takeIf { inside && it.isFile }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
|
||||||
|
|
||||||
/** The list the session hands the runtime's shortcuts writer; one file per session start. */
|
/** The list the session hands the runtime's shortcuts writer; one file per session start. */
|
||||||
fun writeListing(context: Context, games: List<Game>): File {
|
fun writeListing(context: Context, games: List<Game>): File {
|
||||||
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
||||||
@@ -161,6 +188,7 @@ object AddedGames {
|
|||||||
json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe))
|
json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe))
|
||||||
.append(",\"folder\":").append(quote(guestPath(context, g.folder) ?: g.guestDir))
|
.append(",\"folder\":").append(quote(guestPath(context, g.folder) ?: g.guestDir))
|
||||||
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
|
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
|
||||||
|
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
|
||||||
// The art, as the session sees it: the app's cache is bound at its own path, a file in
|
// The art, as the session sees it: the app's cache is bound at its own path, a file in
|
||||||
// the game's folder at the folder's guest path.
|
// the game's folder at the folder's guest path.
|
||||||
val art = AddedGameArt.resolve(context, g)
|
val art = AddedGameArt.resolve(context, g)
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Best-effort detection of the Windows redistributables a game bundles, by scanning its install
|
||||||
|
* folder for the redist installers Steam/Epic/GOG ship (`_CommonRedist/`, `_Redist/`,
|
||||||
|
* `Redistributables/`, loose `vcredist_x64.exe`, …) and mapping them to entries in our component
|
||||||
|
* catalog (WinComponents, Bannerlator's components.json `name` keys). The result drives the
|
||||||
|
* Recommended part of a game's Windows components; the user still switches each one on.
|
||||||
|
* Bannerlator's detector, unchanged but for this note and its package.
|
||||||
|
*
|
||||||
|
* Wine-aware: keeps the redists that actually matter under Wine/DXVK (VC++ runtimes, .NET, PhysX,
|
||||||
|
* OpenAL, XACT, XNA, GFWL) and SKIPS the ones DXVK/VKD3D already provide (DX12 Agility SDK) or that
|
||||||
|
* aren't our components (anti-cheat, Rockstar/Social-Club/launcher setups). Never throws; returns an
|
||||||
|
* empty list on anything unexpected. Pure filesystem — no network, no Android deps (unit-testable).
|
||||||
|
*/
|
||||||
|
object DependencyDetector {
|
||||||
|
|
||||||
|
/** How a recommendation was found — drives the UI's "recommended vs optional" split. */
|
||||||
|
enum class Kind {
|
||||||
|
/** The game bundles the redist installer (in _CommonRedist etc.) — meant to be installed. */
|
||||||
|
BUNDLED,
|
||||||
|
/** A runtime DLL the game ships loose — usually already works from the game folder; install
|
||||||
|
* only if the game misbehaves. */
|
||||||
|
SHIPPED,
|
||||||
|
/** Steam installs it with the game from Steamworks Shared ([SteamRedists]). */
|
||||||
|
STEAM,
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A recommended component: the catalog [componentName] to install, a display [label], the on-disk
|
||||||
|
* redist that triggered it ([reason]), and [kind] (bundled installer vs shipped DLL). */
|
||||||
|
data class Recommendation(val componentName: String, val label: String, val reason: String, val kind: Kind = Kind.BUNDLED)
|
||||||
|
|
||||||
|
private const val MAX_DEPTH = 5
|
||||||
|
private const val MAX_ENTRIES = 8000 // cost guard against giant game trees
|
||||||
|
|
||||||
|
/** A loose VC++ installer with no year in its path — resolved to "latest" only if no specific
|
||||||
|
* vcredistYYYY was found anywhere (else it's just a duplicate of the versioned one). */
|
||||||
|
private const val VCREDIST_LOOSE = "__vcredist_loose"
|
||||||
|
|
||||||
|
/** Directory names that are redist containers worth descending into. */
|
||||||
|
private val REDIST_DIR_RE = Regex(
|
||||||
|
"""(?i)^(_?commonredist|_?redist(ributables)?|__?installer|vcredist|vc_redist|directx|direct_x|physx|openal|dotnet(fx)?|\.net|xna|xact|redist|support)$"""
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Skip whole subtrees that are never our components. */
|
||||||
|
private val SKIP_DIR_RE = Regex("""(?i)^(d3d12.*|.*agility.*|dxvk|vkd3d|battleye|easyanticheat|eac|anticheat)$""")
|
||||||
|
|
||||||
|
private val YEAR_TO_VCREDIST = mapOf(
|
||||||
|
"2005" to "vcredist2005", "2008" to "vcredist2008", "2010" to "vcredist2010",
|
||||||
|
"2012" to "vcredist2012", "2013" to "vcredist2013", "2015" to "vcredist2015",
|
||||||
|
"2017" to "vcredist2015", "2019" to "vcredist2019", "2022" to "vcredist2022",
|
||||||
|
)
|
||||||
|
|
||||||
|
private val LABELS = mapOf(
|
||||||
|
"vcredist2005" to "Visual C++ 2005", "vcredist2008" to "Visual C++ 2008",
|
||||||
|
"vcredist2010" to "Visual C++ 2010", "vcredist2012" to "Visual C++ 2012",
|
||||||
|
"vcredist2013" to "Visual C++ 2013", "vcredist2015" to "Visual C++ 2015-2017",
|
||||||
|
"vcredist2019" to "Visual C++ 2019", "vcredist2022" to "Visual C++ 2015-2022",
|
||||||
|
"physx" to "NVIDIA PhysX", "oalinst" to "OpenAL", "xact" to "DirectX XACT audio",
|
||||||
|
"xact_x64" to "DirectX XACT audio (x64)", "xna40" to "XNA Framework 4.0",
|
||||||
|
"xna31" to "XNA Framework 3.1", "d3dx9" to "DirectX 9 (d3dx9)", "d3dx11" to "DirectX 11 (d3dx11)",
|
||||||
|
"XLiveRedist" to "Games for Windows Live", "dotnet40" to ".NET Framework 4.0",
|
||||||
|
"dotnet45" to ".NET Framework 4.5", "dotnet452" to ".NET Framework 4.5.2",
|
||||||
|
"dotnet46" to ".NET Framework 4.6", "dotnet472" to ".NET Framework 4.7.2",
|
||||||
|
"dotnet48" to ".NET Framework 4.8", "dotnet35" to ".NET Framework 3.5",
|
||||||
|
"dotnetcoredesktop6" to ".NET Desktop 6", "dotnetcoredesktop7" to ".NET Desktop 7",
|
||||||
|
"dotnetcoredesktop8" to ".NET Desktop 8",
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Preferred install order (runtimes others may depend on first). */
|
||||||
|
private val INSTALL_ORDER = listOf(
|
||||||
|
"vcredist2005", "vcredist2008", "vcredist2010", "vcredist2012", "vcredist2013",
|
||||||
|
"vcredist2015", "vcredist2019", "vcredist2022",
|
||||||
|
"dotnet35", "dotnet40", "dotnet45", "dotnet452", "dotnet46", "dotnet472", "dotnet48",
|
||||||
|
"dotnetcoredesktop6", "dotnetcoredesktop7", "dotnetcoredesktop8",
|
||||||
|
"d3dx9", "d3dx11", "xact", "xact_x64", "xna31", "xna40", "physx", "oalinst", "XLiveRedist",
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detect from the .exe the user picked, resolving the game root first: walk up from the exe's
|
||||||
|
* folder (bounded) to the nearest ancestor that holds a redist container (`_CommonRedist`, …) at
|
||||||
|
* its top level, and scan from there — so a nested exe (`…/Game/bin/x.exe`) still finds a root-level
|
||||||
|
* `_CommonRedist`, without over-reaching into a shared `steamapps/common` (which has no redist
|
||||||
|
* container of its own). Falls back to scanning the exe's own folder.
|
||||||
|
*/
|
||||||
|
fun detectForExe(exeFile: File): List<Recommendation> {
|
||||||
|
val start = exeFile.absoluteFile.parentFile ?: return emptyList()
|
||||||
|
var d: File? = start
|
||||||
|
var depth = 0
|
||||||
|
while (d != null && depth < 4) {
|
||||||
|
val hasRedistContainer = try {
|
||||||
|
d.listFiles()?.any { it.isDirectory && REDIST_DIR_RE.matches(it.name.lowercase(Locale.US)) } == true
|
||||||
|
} catch (_: Throwable) { false }
|
||||||
|
if (hasRedistContainer) return detect(d)
|
||||||
|
d = d.parentFile
|
||||||
|
depth++
|
||||||
|
}
|
||||||
|
return detect(start)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scan [gameDir] and return the recommended components, de-duplicated (first reason wins), in a
|
||||||
|
* stable install-friendly order. Empty when nothing is detected or [gameDir] isn't a directory.
|
||||||
|
*/
|
||||||
|
fun detect(gameDir: File): List<Recommendation> {
|
||||||
|
if (!gameDir.isDirectory) return emptyList()
|
||||||
|
val hits = LinkedHashMap<String, Recommendation>() // componentName -> first recommendation
|
||||||
|
var visited = 0
|
||||||
|
|
||||||
|
fun consider(f: File, isDir: Boolean, insideRedist: Boolean) {
|
||||||
|
val name = f.name.lowercase(Locale.US)
|
||||||
|
val path = f.path.replace('\\', '/').lowercase(Locale.US)
|
||||||
|
// Bundled = in a redist container or an installer (exe/msi/cab); shipped = a loose runtime DLL.
|
||||||
|
val kind = if (insideRedist || isDir || name.endsWith(".exe") || name.endsWith(".msi") || name.endsWith(".cab"))
|
||||||
|
Kind.BUNDLED else Kind.SHIPPED
|
||||||
|
for (comp in classify(path, name, isDir)) {
|
||||||
|
val existing = hits[comp]
|
||||||
|
if (existing == null) {
|
||||||
|
hits[comp] = Recommendation(comp, LABELS[comp] ?: comp, relativeReason(gameDir, f), kind)
|
||||||
|
} else if (existing.kind == Kind.SHIPPED && kind == Kind.BUNDLED) {
|
||||||
|
hits[comp] = existing.copy(kind = Kind.BUNDLED) // a bundled installer outranks a shipped DLL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun walk(dir: File, depth: Int, insideRedist: Boolean) {
|
||||||
|
if (depth > MAX_DEPTH || visited > MAX_ENTRIES) return
|
||||||
|
val entries = dir.listFiles() ?: return
|
||||||
|
for (f in entries) {
|
||||||
|
if (visited++ > MAX_ENTRIES) return
|
||||||
|
val lower = f.name.lowercase(Locale.US)
|
||||||
|
if (f.isDirectory) {
|
||||||
|
if (SKIP_DIR_RE.matches(lower)) continue
|
||||||
|
val isRedistDir = insideRedist || REDIST_DIR_RE.matches(lower)
|
||||||
|
if (isRedistDir) consider(f, isDir = true, insideRedist = true)
|
||||||
|
// Aggressive coverage: descend redist containers fully, and otherwise sweep the game
|
||||||
|
// tree a few levels deep so runtime libraries the game ships (in bin/, etc.) are seen.
|
||||||
|
if (isRedistDir || depth < 3) walk(f, depth + 1, isRedistDir)
|
||||||
|
} else {
|
||||||
|
// Classify installers + runtime libraries (.dll/.exe/.msi) anywhere in the scanned
|
||||||
|
// tree; other files are ignored. Recommendations are advisory, so cast a wide net.
|
||||||
|
val ext = lower.substringAfterLast('.', "")
|
||||||
|
if (insideRedist || ext == "dll" || ext == "exe" || ext == "msi") consider(f, isDir = false, insideRedist = insideRedist)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return try {
|
||||||
|
walk(gameDir, 0, false)
|
||||||
|
resolveLooseVcredist(hits)
|
||||||
|
hits.values.sortedBy { INSTALL_ORDER.indexOf(it.componentName).let { i -> if (i < 0) 999 else i } }
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A loose VC++ installer resolves to the latest 14.x only if no specific vcredistYYYY was found. */
|
||||||
|
private fun resolveLooseVcredist(hits: LinkedHashMap<String, Recommendation>) {
|
||||||
|
val loose = hits.remove(VCREDIST_LOOSE) ?: return
|
||||||
|
val hasSpecific = hits.keys.any { it in YEAR_TO_VCREDIST.values }
|
||||||
|
if (!hasSpecific) hits["vcredist2022"] = loose.copy(componentName = "vcredist2022", label = LABELS["vcredist2022"]!!)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun relativeReason(gameDir: File, f: File): String {
|
||||||
|
val g = gameDir.path.replace('\\', '/')
|
||||||
|
val p = f.path.replace('\\', '/')
|
||||||
|
return if (p.startsWith("$g/")) p.substring(g.length + 1) else f.name
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map a redist file/dir (its full lowercased [path], leaf [name], and whether it [isDir]) to
|
||||||
|
* catalog component name(s). Empty for things we deliberately skip.
|
||||||
|
*/
|
||||||
|
private fun classify(path: String, name: String, isDir: Boolean): List<String> {
|
||||||
|
// Hard skips first — DX12 is provided by DXVK/VKD3D; these aren't our components.
|
||||||
|
if (path.contains("d3d12") || path.contains("agility") ||
|
||||||
|
path.contains("battleye") || path.contains("anticheat") || path.contains("easyanticheat") ||
|
||||||
|
name.contains("socialclub") || name.contains("social-club") ||
|
||||||
|
name.contains("rockstar") || name == "setup.exe"
|
||||||
|
) return emptyList()
|
||||||
|
|
||||||
|
// Visual C++ runtimes — most important. Year comes from the path context.
|
||||||
|
if (path.contains("vcredist") || path.contains("vc_redist") || name.startsWith("vcredist") || name.startsWith("vc_redist")) {
|
||||||
|
val year = YEAR_TO_VCREDIST.keys.firstOrNull { path.contains(it) }
|
||||||
|
return when {
|
||||||
|
year != null -> listOf(YEAR_TO_VCREDIST.getValue(year))
|
||||||
|
isDir -> emptyList() // bare "vcredist" container — wait for the year subfolder / installer
|
||||||
|
else -> listOf(VCREDIST_LOOSE) // loose installer, no year → resolved post-walk
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// VC++ runtime DLL the game ships (msvcp140.dll → 2015-2022, msvcp120.dll → 2013, …).
|
||||||
|
VCRUNTIME_DLL.entries.firstOrNull { name.startsWith(it.key) }?.let { return listOf(it.value) }
|
||||||
|
if (path.contains("openal") || name.startsWith("oalinst") || name == "openal32.dll" || name == "wrap_oal.dll") return listOf("oalinst")
|
||||||
|
if (path.contains("physx") || name.startsWith("physx")) return listOf("physx")
|
||||||
|
if (path.contains("xact") || name.startsWith("xactengine") || name.startsWith("x3daudio")) return listOf("xact", "xact_x64")
|
||||||
|
// Games for Windows Live — the redist folder, OR a GFWL library the game ships (xlive.dll,
|
||||||
|
// Codemasters' dbxLive32/64, gfwl*): GFWL titles need XLiveRedist to run even when they don't
|
||||||
|
// bundle the redist itself.
|
||||||
|
if (path.contains("xliveredist") || name.contains("xlive") || name.startsWith("gfwl") || name.startsWith("dbxlive")) {
|
||||||
|
return listOf("XLiveRedist")
|
||||||
|
}
|
||||||
|
if (path.contains("xna")) return listOf(if (path.contains("3.1") || path.contains("3_1") || path.contains("v31")) "xna31" else "xna40")
|
||||||
|
// .NET — Framework and Core/Desktop runtimes.
|
||||||
|
if (path.contains("dotnet") || path.contains(".net") || name.startsWith("ndp") || name.startsWith("dotnetfx") || name.contains("windowsdesktop-runtime")) {
|
||||||
|
val comp = dotnetComponent("$path $name")
|
||||||
|
return when {
|
||||||
|
comp != null -> listOf(comp)
|
||||||
|
isDir -> emptyList() // bare ".NET" container — wait for the versioned installer
|
||||||
|
else -> listOf("dotnet48") // unlabeled .NET Framework installer file → sensible default
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// DirectX 11 helper DLLs the game ships (d3dx11_43.dll).
|
||||||
|
if (D3DX11_RE.matches(name)) return listOf("d3dx11")
|
||||||
|
// DirectX 9 helper DLLs / d3dcompiler / June-2010 DX redist (DXVK provides core d3d9 but NOT
|
||||||
|
// these helper DLLs).
|
||||||
|
if (name.startsWith("dxsetup") || name.startsWith("dxwebsetup") ||
|
||||||
|
D3DX9_RE.matches(name) || D3DCOMPILER_RE.matches(name) ||
|
||||||
|
(path.contains("directx") && name.endsWith(".exe"))
|
||||||
|
) return listOf("d3dx9")
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runtime DLL prefix → the VC++ redistributable that provides it (checked with startsWith). */
|
||||||
|
private val VCRUNTIME_DLL = linkedMapOf(
|
||||||
|
"vcruntime140" to "vcredist2022", "msvcp140" to "vcredist2022", "msvcr140" to "vcredist2022", "concrt140" to "vcredist2022",
|
||||||
|
"msvcp120" to "vcredist2013", "msvcr120" to "vcredist2013",
|
||||||
|
"msvcp110" to "vcredist2012", "msvcr110" to "vcredist2012",
|
||||||
|
"msvcp100" to "vcredist2010", "msvcr100" to "vcredist2010",
|
||||||
|
"msvcp90" to "vcredist2008", "msvcr90" to "vcredist2008",
|
||||||
|
"msvcp80" to "vcredist2005", "msvcr80" to "vcredist2005",
|
||||||
|
)
|
||||||
|
private val D3DX9_RE = Regex("""d3dx9_\d+\.dll""")
|
||||||
|
private val D3DX11_RE = Regex("""d3dx11_\d+\.dll""")
|
||||||
|
private val D3DCOMPILER_RE = Regex("""d3dcompiler_\d+\.dll""")
|
||||||
|
|
||||||
|
/** Resolve a .NET component from installer/path text, or null when no version is discernible. */
|
||||||
|
private fun dotnetComponent(s: String): String? = when {
|
||||||
|
s.contains("desktop-runtime-8") || Regex("""\b8\.\d""").containsMatchIn(s) -> "dotnetcoredesktop8"
|
||||||
|
s.contains("desktop-runtime-7") || Regex("""\b7\.\d""").containsMatchIn(s) -> "dotnetcoredesktop7"
|
||||||
|
s.contains("desktop-runtime-6") || Regex("""\b6\.\d""").containsMatchIn(s) -> "dotnetcoredesktop6"
|
||||||
|
s.contains("ndp48") || s.contains("fx48") || s.contains("4.8") -> "dotnet48"
|
||||||
|
s.contains("ndp472") || s.contains("4.7.2") -> "dotnet472"
|
||||||
|
s.contains("ndp46") || s.contains("4.6") -> "dotnet46"
|
||||||
|
s.contains("ndp452") || s.contains("4.5.2") -> "dotnet452"
|
||||||
|
s.contains("dotnetfx45") || s.contains("ndp45") || s.contains("4.5") -> "dotnet45"
|
||||||
|
s.contains("dotnetfx40") || s.contains("ndp40") || s.contains("4.0") -> "dotnet40"
|
||||||
|
s.contains("dotnetfx35") || s.contains("3.5") -> "dotnet35"
|
||||||
|
else -> null // no version signal (e.g. a bare "DotNet" container dir)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.frontend
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.droiddeck.launcher.session.GameStorage
|
import com.droiddeck.launcher.session.GameStorage
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
@@ -37,18 +38,18 @@ object GameFileSync {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized private fun sync(context: Context, folder: File) {
|
@Synchronized private fun sync(context: Context, folder: File) {
|
||||||
check(LinuxRuntime.isInstalled(context)) { "Install the runtime first" }
|
check(LinuxRuntime.isInstalled(context)) { context.getString(R.string.game_sync_err_runtime) }
|
||||||
// A disconnected library must not be interpreted as a mass uninstall.
|
// A disconnected library must not be interpreted as a mass uninstall.
|
||||||
check(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps").isDirectory) { "Steam library is unavailable" }
|
check(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps").isDirectory) { context.getString(R.string.game_sync_err_steam_library) }
|
||||||
val storage = GameStorage.effective(context)
|
val storage = GameStorage.effective(context)
|
||||||
val storageSetting = SessionPrefs.gameStorage(context)
|
val storageSetting = SessionPrefs.gameStorage(context)
|
||||||
val previousStorage = prefs(context).getString("storagePath", null)
|
val previousStorage = prefs(context).getString("storagePath", null)
|
||||||
if (storageSetting.isEmpty() && prefs(context).getString("storageSetting", null) == storageSetting && previousStorage != null) {
|
if (storageSetting.isEmpty() && prefs(context).getString("storageSetting", null) == storageSetting && previousStorage != null) {
|
||||||
check(File(previousStorage).isDirectory) { "Previous SD library is unavailable" }
|
check(File(previousStorage).isDirectory) { context.getString(R.string.game_sync_err_previous_sd) }
|
||||||
}
|
}
|
||||||
storage?.let { check(File(it.path).listFiles() != null) { "Game storage is unavailable" } }
|
storage?.let { check(File(it.path).listFiles() != null) { context.getString(R.string.game_sync_err_game_storage) } }
|
||||||
SessionPrefs.addedGamesDirs(context).forEach { check(File(it).listFiles() != null) { "Added games folder is unavailable" } }
|
SessionPrefs.addedGamesDirs(context).forEach { check(File(it).listFiles() != null) { context.getString(R.string.game_sync_err_added_games) } }
|
||||||
GameFiles.sync(folder, Library.launchableGames(context, strictRead = true))
|
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true))
|
||||||
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
|
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.frontend
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.util.AtomicFile
|
import android.util.AtomicFile
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import androidx.core.util.readText
|
import androidx.core.util.readText
|
||||||
import androidx.core.util.writeBytes
|
import androidx.core.util.writeBytes
|
||||||
import androidx.core.util.writeText
|
import androidx.core.util.writeText
|
||||||
@@ -12,7 +13,7 @@ import java.io.InputStream
|
|||||||
|
|
||||||
/** Small, portable launch files for frontends that scan ROM folders. No guest paths or commands. */
|
/** Small, portable launch files for frontends that scan ROM folders. No guest paths or commands. */
|
||||||
object GameFiles {
|
object GameFiles {
|
||||||
const val EXTENSION = "droiddeck"
|
const val EXTENSION = "steam"
|
||||||
private const val MAX_BYTES = 128
|
private const val MAX_BYTES = 128
|
||||||
private const val INVENTORY = ".droiddeck-sync.json"
|
private const val INVENTORY = ".droiddeck-sync.json"
|
||||||
private const val FORMAT = "droiddeck-game-files-v1"
|
private const val FORMAT = "droiddeck-game-files-v1"
|
||||||
@@ -46,83 +47,115 @@ object GameFiles {
|
|||||||
}
|
}
|
||||||
if (count > MAX_BYTES) return null
|
if (count > MAX_BYTES) return null
|
||||||
val text = String(bytes, 0, count, Charsets.UTF_8).trim()
|
val text = String(bytes, 0, count, Charsets.UTF_8).trim()
|
||||||
return GameLaunchLink.parse(text) ?: text.takeIf(GameLaunchLink::validId)
|
return text.takeIf(GameLaunchLink::validId)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun filename(game: Library.SteamGame): String {
|
fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String {
|
||||||
val sanitized = game.name.replace(Regex("[\\p{Cntrl}\\\\/:*?\"<>|]"), "_")
|
val sanitized = game.name.replace(Regex("[\\p{Cntrl}\\\\/:*?\"<>|]"), "_")
|
||||||
.trim().trim('.').ifBlank { "Game" }
|
.trim().trim('.').ifBlank { "Game" }
|
||||||
val points = sanitized.codePoints().limit(40).toArray()
|
val points = sanitized.codePoints().limit(40).toArray()
|
||||||
val title = String(points, 0, points.size)
|
val title = String(points, 0, points.size)
|
||||||
return "$title (${game.gameIdString}).$EXTENSION"
|
val suffix = if (disambiguate) " (${game.gameIdString})" else ""
|
||||||
|
return "$title$suffix.$EXTENSION"
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun contents(id: String) = GameLaunchLink.uri(id) + "\n"
|
private fun contents(id: String): String {
|
||||||
|
require(GameLaunchLink.validId(id))
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
@Synchronized fun export(folder: File, game: Library.SteamGame): File {
|
@Synchronized fun export(context: Context, folder: File, game: Library.SteamGame): File =
|
||||||
require(folder.isDirectory) { "Folder is unavailable" }
|
exportNamed(context, folder, game, filename(game))
|
||||||
val target = child(folder, filename(game))
|
|
||||||
|
private fun exportNamed(context: Context, folder: File, game: Library.SteamGame, name: String): File {
|
||||||
|
require(folder.isDirectory) { context.getString(R.string.gfiles_folder_unavailable) }
|
||||||
val text = contents(game.gameIdString)
|
val text = contents(game.gameIdString)
|
||||||
require(!target.exists() || matches(target, text)) { "A different file already uses ${target.name}" }
|
val target = exportTarget(context, folder, game, name)
|
||||||
|
require(!target.exists() || matches(target, text)) { context.getString(R.string.gfiles_name_taken, target.name) }
|
||||||
if (!target.exists()) write(target, text)
|
if (!target.exists()) write(target, text)
|
||||||
exportArt(folder, game)
|
exportArt(context, folder, game)
|
||||||
return target
|
return target
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun exportTarget(context: Context, folder: File, game: Library.SteamGame, name: String): File {
|
||||||
|
val target = child(context, folder, name)
|
||||||
|
return if (target.exists() && !matches(target, contents(game.gameIdString))) {
|
||||||
|
child(context, folder, filename(game, disambiguate = true))
|
||||||
|
} else target
|
||||||
|
}
|
||||||
|
|
||||||
/** Cocoon matches icons in its data folder's images directory. Never replace custom art. */
|
/** Cocoon matches icons in its data folder's images directory. Never replace custom art. */
|
||||||
private fun exportArt(folder: File, game: Library.SteamGame) {
|
private fun exportArt(context: Context, folder: File, game: Library.SteamGame) {
|
||||||
val art = listOfNotNull(game.icon, game.art).firstOrNull {
|
val art = listOfNotNull(game.icon, game.art).firstOrNull {
|
||||||
it.isFile && it.extension.lowercase() in listOf("jpg", "jpeg", "png", "webp")
|
it.isFile && it.extension.lowercase() in listOf("jpg", "jpeg", "png", "webp")
|
||||||
} ?: return
|
} ?: return
|
||||||
val title = filename(game).substringBeforeLast(" (${game.gameIdString})")
|
val title = filename(game).substringBeforeLast(".")
|
||||||
.replace(Regex("\\[[^]]*]|\\([^)]*\\)"), "")
|
.replace(Regex("\\[[^]]*]|\\([^)]*\\)"), "")
|
||||||
.replace(Regex("[^a-zA-Z0-9\\s]"), "").trim()
|
.replace(Regex("[^a-zA-Z0-9\\s]"), "").trim()
|
||||||
.replace(Regex("\\s+"), "-").lowercase(java.util.Locale.ROOT).take(50).trimEnd('-')
|
.replace(Regex("\\s+"), "-").lowercase(java.util.Locale.ROOT).take(50).trimEnd('-')
|
||||||
if (title.isEmpty()) return
|
if (title.isEmpty()) return
|
||||||
val images = child(folder, "images")
|
val images = child(context, folder, "images")
|
||||||
check(images.isDirectory || images.mkdir()) { "Artwork folder is unavailable" }
|
check(images.isDirectory || images.mkdir()) { context.getString(R.string.gfiles_art_unavailable) }
|
||||||
val target = child(images, "$title-icon.${art.extension.lowercase()}")
|
val target = child(context, images, "$title-icon.${art.extension.lowercase()}")
|
||||||
if (!target.exists()) AtomicFile(target).writeBytes(art.readBytes())
|
if (!target.exists()) AtomicFile(target).writeBytes(art.readBytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Only remove files in our inventory whose content is still exactly what we wrote. */
|
/** Only remove files in our inventory whose content is still exactly what we wrote. */
|
||||||
@Synchronized fun sync(folder: File, games: List<Library.SteamGame>) {
|
@Synchronized fun sync(context: Context, folder: File, games: List<Library.SteamGame>) {
|
||||||
require(folder.isDirectory) { "Folder is unavailable" }
|
require(folder.isDirectory) { context.getString(R.string.gfiles_folder_unavailable) }
|
||||||
val inventory = child(folder, INVENTORY)
|
val inventory = child(context, folder, INVENTORY)
|
||||||
val previous = if (inventory.exists()) {
|
val previous = if (inventory.exists()) {
|
||||||
val record = JSONObject(AtomicFile(inventory).readText())
|
val record = JSONObject(AtomicFile(inventory).readText())
|
||||||
require(record.optString("format") == FORMAT) { "Folder has an unrelated sync inventory" }
|
require(record.optString("format") == FORMAT) { context.getString(R.string.gfiles_unrelated_inventory) }
|
||||||
record.getJSONObject("games")
|
record.getJSONObject("games")
|
||||||
} else JSONObject()
|
} else JSONObject()
|
||||||
val next = JSONObject()
|
val next = JSONObject()
|
||||||
val exports = games.distinctBy { it.gameId }.map { game ->
|
val unique = games.distinctBy { it.gameId }
|
||||||
val target = child(folder, filename(game))
|
val names = unique.groupingBy { filename(it).lowercase(java.util.Locale.ROOT) }.eachCount()
|
||||||
|
val exports = unique.map { game ->
|
||||||
|
val name = filename(game, disambiguate = names.getValue(filename(game).lowercase(java.util.Locale.ROOT)) > 1)
|
||||||
|
val preferred = child(context, folder, name)
|
||||||
|
val target = if (inventoryOwns(context, folder, previous, preferred, game.gameIdString)) preferred
|
||||||
|
else exportTarget(context, folder, game, name)
|
||||||
|
val text = contents(game.gameIdString)
|
||||||
|
val existed = target.exists()
|
||||||
// Keep an edited export without letting it block the rest of the library sync.
|
// Keep an edited export without letting it block the rest of the library sync.
|
||||||
val file = if (previous.optString(target.name) == game.gameIdString && target.exists() &&
|
val owned = inventoryOwns(context, folder, previous, target, game.gameIdString)
|
||||||
!matches(target, contents(game.gameIdString))) target else export(folder, game)
|
val file = if (owned && target.exists() &&
|
||||||
next.put(file.name, game.gameIdString)
|
!matches(target, text)) target else exportNamed(context, folder, game, target.name)
|
||||||
|
if (!existed || owned) next.put(file.name, game.gameIdString)
|
||||||
file
|
file
|
||||||
}
|
}
|
||||||
// Write new exports before pruning; a failed write must not remove old launch files.
|
// Write new exports before pruning; a failed write must not remove old launch files.
|
||||||
for (name in previous.keys()) {
|
for (name in previous.keys()) {
|
||||||
val id = previous.getString(name)
|
val id = previous.getString(name)
|
||||||
if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) {
|
if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) {
|
||||||
val file = child(folder, name)
|
val file = child(context, folder, name)
|
||||||
if (matches(file, contents(id))) {
|
if (matches(file, contents(id))) {
|
||||||
// Android shared storage is often case insensitive. A case-only rename may
|
// Android shared storage is often case insensitive. A case-only rename may
|
||||||
// still resolve to the live export, which must not be pruned as an old file.
|
// still resolve to the live export, which must not be pruned as an old file.
|
||||||
val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) }
|
val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) }
|
||||||
if (!retained) check(file.delete()) { "Could not remove $name" }
|
if (!retained) check(file.delete()) { context.getString(R.string.gfiles_remove_failed, name) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString())
|
if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString())
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun child(folder: File, name: String): File {
|
private fun inventoryOwns(context: Context, folder: File, record: JSONObject, file: File, id: String): Boolean {
|
||||||
|
if (record.optString(file.name) == id) return true
|
||||||
|
if (!file.exists()) return false
|
||||||
|
return record.keys().asSequence().any { name ->
|
||||||
|
record.optString(name) == id && child(context, folder, name).let { old ->
|
||||||
|
old.exists() && java.nio.file.Files.isSameFile(old.toPath(), file.toPath())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun child(context: Context, folder: File, name: String): File {
|
||||||
require(name.isNotEmpty() && '/' !in name && '\\' !in name && name != "." && name != "..")
|
require(name.isNotEmpty() && '/' !in name && '\\' !in name && name != "." && name != "..")
|
||||||
val file = File(folder, name)
|
val file = File(folder, name)
|
||||||
require(file.canonicalFile.parentFile == folder.canonicalFile) { "File leaves the export folder" }
|
require(file.canonicalFile.parentFile == folder.canonicalFile) { context.getString(R.string.gfiles_outside_folder) }
|
||||||
return file
|
return file
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
|
||||||
|
object GameLaunchIntent {
|
||||||
|
const val ACTION = "com.droiddeck.launcher.LAUNCH_GAME"
|
||||||
|
const val EXTRA_APP_ID = "app_id"
|
||||||
|
const val EXTRA_GAME_SOURCE = "game_source"
|
||||||
|
private const val GAMENATIVE_ACTION = "app.gamenative.LAUNCH_GAME"
|
||||||
|
|
||||||
|
fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION
|
||||||
|
|
||||||
|
fun read(context: Context, intent: Intent): String? = when (intent.action) {
|
||||||
|
Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent)
|
||||||
|
ACTION, GAMENATIVE_ACTION -> readId(intent)
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
internal fun readId(intent: Intent): String? = runCatching {
|
||||||
|
if (intent.action != ACTION && intent.action != GAMENATIVE_ACTION) return null
|
||||||
|
val source = intent.extras?.get(EXTRA_GAME_SOURCE)
|
||||||
|
if (source != null && (source !is String || !source.equals("STEAM", ignoreCase = true))) return null
|
||||||
|
val id = when (val value = intent.extras?.get(EXTRA_APP_ID)) {
|
||||||
|
is Int -> value.takeIf { it > 0 }?.toString()
|
||||||
|
is String -> value.takeIf(GameLaunchLink::validId)
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
id
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
@@ -33,6 +33,8 @@ object Library {
|
|||||||
|
|
||||||
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
||||||
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
|
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
|
||||||
|
/** The shown name of [system] when it is words rather than a platform name, else 0. */
|
||||||
|
val systemRes: Int get() = if (id == "retroarch") R.string.content_system_many else 0
|
||||||
/** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */
|
/** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */
|
||||||
val iconRes: Int get() = when (id) {
|
val iconRes: Int get() = when (id) {
|
||||||
"rpcs3" -> R.drawable.emu_rpcs3; "armsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin
|
"rpcs3" -> R.drawable.emu_rpcs3; "armsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin
|
||||||
@@ -84,17 +86,20 @@ object Library {
|
|||||||
return listOfNotNull(
|
return listOfNotNull(
|
||||||
root to "internal",
|
root to "internal",
|
||||||
GameStorage.effective(context)?.let { File(it.path) to it.label },
|
GameStorage.effective(context)?.let { File(it.path) to it.label },
|
||||||
)
|
) + GameStorage.gamesFolderLibraries(context).map { it.host to it.label }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
|
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
|
||||||
fun protonPrefix(context: Context, appId: Long, preferredLibrary: File? = null): File? {
|
fun protonPrefix(
|
||||||
|
context: Context, appId: Long, preferredLibrary: File? = null,
|
||||||
|
libraries: List<File> = steamLibraries(context).map { it.first },
|
||||||
|
): File? {
|
||||||
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
|
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
|
||||||
val secondary = GameStorage.effective(context)?.let { File(it.path) }
|
val secondary = libraries.drop(1).mapNotNull { runCatching { it.canonicalPath }.getOrNull() }.toSet()
|
||||||
fun prefixRoot(root: File): File = if (secondary != null && root.canonicalPath == secondary.canonicalPath)
|
fun prefixRoot(root: File): File = if (runCatching { root.canonicalPath }.getOrNull() in secondary)
|
||||||
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
|
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
|
||||||
else root
|
else root
|
||||||
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first }).map(::prefixRoot)
|
val roots = (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
|
||||||
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
|
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
|
||||||
return roots.asSequence()
|
return roots.asSequence()
|
||||||
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
|
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
|
||||||
@@ -105,11 +110,12 @@ object Library {
|
|||||||
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||||
val cache = File(root, "appcache/librarycache")
|
val cache = File(root, "appcache/librarycache")
|
||||||
val libraries = steamLibraries(context)
|
val libraries = steamLibraries(context)
|
||||||
|
val roots = libraries.map { it.first }
|
||||||
val out = LinkedHashMap<Int, SteamGame>()
|
val out = LinkedHashMap<Int, SteamGame>()
|
||||||
for ((library, label) in libraries) {
|
for ((library, label) in libraries) {
|
||||||
val steamapps = File(library, "steamapps")
|
val steamapps = File(library, "steamapps")
|
||||||
val manifests = steamapps.listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }
|
val manifests = steamapps.listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }
|
||||||
if (strictRead && steamapps.isDirectory) check(manifests != null) { "Steam manifests are unavailable" }
|
if (strictRead && steamapps.isDirectory) check(manifests != null) { context.getString(R.string.game_sync_err_manifests) }
|
||||||
manifests?.sortedBy { it.name }?.forEach { manifest ->
|
manifests?.sortedBy { it.name }?.forEach { manifest ->
|
||||||
val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach
|
val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach
|
||||||
if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach
|
if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach
|
||||||
@@ -130,7 +136,7 @@ object Library {
|
|||||||
out[appId] = SteamGame(
|
out[appId] = SteamGame(
|
||||||
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
|
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
|
||||||
gameFiles = gameFiles,
|
gameFiles = gameFiles,
|
||||||
protonPrefix = protonPrefix(context, appId.toLong(), library),
|
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
|
||||||
icon = steamCacheImage(cache, appId, listOf("icon.jpg", "icon.png"))
|
icon = steamCacheImage(cache, appId, listOf("icon.jpg", "icon.png"))
|
||||||
?: File(cache, appId.toString()).listFiles()?.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) },
|
?: File(cache, appId.toString()).listFiles()?.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) },
|
||||||
)
|
)
|
||||||
@@ -140,16 +146,19 @@ object Library {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The same installed-game inventory used for links, shortcuts and file exports. */
|
/** The same installed-game inventory used for links, shortcuts and file exports. */
|
||||||
fun launchableGames(context: Context, strictRead: Boolean = false): List<SteamGame> = (steamGames(context, strictRead) + AddedGames.scan(context).map { g ->
|
fun launchableGames(context: Context, strictRead: Boolean = false): List<SteamGame> {
|
||||||
AddedGameArt.resolve(context, g).let { art ->
|
val roots = steamLibraries(context).map { it.first }
|
||||||
SteamGame(
|
return (steamGames(context, strictRead) + AddedGames.scan(context).map { g ->
|
||||||
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
|
AddedGameArt.resolve(context, g).let { art ->
|
||||||
hero = art.hero ?: art.header, gameFiles = g.folder,
|
SteamGame(
|
||||||
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId),
|
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
|
||||||
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
|
hero = art.hero ?: art.header, gameFiles = g.folder,
|
||||||
)
|
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
|
||||||
}
|
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
|
||||||
}).distinctBy { it.gameId }
|
)
|
||||||
|
}
|
||||||
|
}).distinctBy { it.gameId }
|
||||||
|
}
|
||||||
|
|
||||||
/** Steam stores current library art inside hash-named folders under the app's cache dir. */
|
/** Steam stores current library art inside hash-named folders under the app's cache dir. */
|
||||||
private fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? {
|
private fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? {
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which catalog components a game's prefix already has from elsewhere - a real installer, the game,
|
||||||
|
* the user - so the list can say so instead of recommending them again. Bannerlator's detector,
|
||||||
|
* on DroidDeck's compatdata/<id>: only markers absent from a fresh Proton prefix count (OpenAL32,
|
||||||
|
* Mono, PhysX, Games for Windows Live); msvcp140, d3dx9 and the like ship with Proton and cannot
|
||||||
|
* tell. Files DroidDeck put there itself (droiddeck-wincomponents' state) are not counted.
|
||||||
|
* Pure filesystem reads; never throws.
|
||||||
|
*/
|
||||||
|
object PrefixInstalledDetector {
|
||||||
|
private const val STATE = ".droiddeck-wincomponents.json"
|
||||||
|
|
||||||
|
/** Detector names (oalinst, mono, physx, XLiveRedist) present in [compat]/pfx. */
|
||||||
|
fun detect(compat: File?): Set<String> = try {
|
||||||
|
val pfx = compat?.let { File(it, "pfx") }
|
||||||
|
if (pfx == null || !pfx.isDirectory) emptySet() else {
|
||||||
|
val ours = ours(compat)
|
||||||
|
val out = HashSet<String>()
|
||||||
|
val openal = listOf("system32", "syswow64").map { "drive_c/windows/$it/openal32.dll" }
|
||||||
|
if (openal.any { it !in ours && fileIgnoringCase(pfx, it) }) out += "oalinst"
|
||||||
|
if (File(pfx, "drive_c/windows/mono").isDirectory) out += "mono"
|
||||||
|
if (hasPhysX(pfx)) out += "physx"
|
||||||
|
if (registryContains(pfx, "Games for Windows")) out += "XLiveRedist"
|
||||||
|
out
|
||||||
|
}
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
emptySet()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ours(compat: File): Set<String> = try {
|
||||||
|
val files = JSONObject(File(compat, STATE).readText()).optJSONObject("files")
|
||||||
|
files?.keys()?.asSequence()?.map { it.lowercase() }?.toSet().orEmpty()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
emptySet()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Windows names ignore case; the prefix's folder may spell them either way. */
|
||||||
|
private fun fileIgnoringCase(pfx: File, rel: String): Boolean {
|
||||||
|
val target = File(pfx, rel)
|
||||||
|
return target.parentFile?.listFiles()?.any { it.isFile && it.name.equals(target.name, ignoreCase = true) } == true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasPhysX(pfx: File): Boolean {
|
||||||
|
for (pf in arrayOf("drive_c/Program Files", "drive_c/Program Files (x86)")) {
|
||||||
|
val base = File(pfx, pf)
|
||||||
|
if (File(base, "NVIDIA Corporation/PhysX").isDirectory) return true
|
||||||
|
if (base.listFiles()?.any { it.isDirectory && it.name.contains("PhysX", ignoreCase = true) } == true) return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun registryContains(pfx: File, needle: String): Boolean =
|
||||||
|
arrayOf("system.reg", "user.reg").any { name ->
|
||||||
|
val f = File(pfx, name)
|
||||||
|
try {
|
||||||
|
f.isFile && f.length() < 32L * 1024 * 1024 &&
|
||||||
|
f.bufferedReader().use { r -> r.lineSequence().any { it.contains(needle, ignoreCase = true) } }
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.droiddeck.launcher.frontend
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What Steam itself installs alongside a game: the Steamworks Shared redistributables (app 228980)
|
||||||
|
* listed under "SharedDepots" in the game's appmanifest. Those live in Steamworks Shared rather than
|
||||||
|
* the game's folder, so the folder scan ([DependencyDetector]) cannot see them; this reads Steam's
|
||||||
|
* list instead. Depots are matched to Bannerlator's catalog names; unknown ones are left out.
|
||||||
|
*/
|
||||||
|
object SteamRedists {
|
||||||
|
/** Steamworks Shared depot -> (catalog component, what Steam calls it). 2015-2019 runtimes are one family. */
|
||||||
|
val DEPOTS = linkedMapOf(
|
||||||
|
"228981" to ("vcredist2005_dll" to "VC++ 2005"),
|
||||||
|
"228982" to ("vcredist2008_dll" to "VC++ 2008"),
|
||||||
|
"228983" to ("vcredist2010_dll" to "VC++ 2010"),
|
||||||
|
"228984" to ("vcredist2012_dll" to "VC++ 2012"),
|
||||||
|
"228985" to ("vcredist2013_dll" to "VC++ 2013"),
|
||||||
|
"228986" to ("vcredist2015_dll" to "VC++ 2015"),
|
||||||
|
"228987" to ("vcredist2019_dll" to "VC++ 2017"),
|
||||||
|
"228988" to ("vcredist2019_dll" to "VC++ 2019"),
|
||||||
|
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
|
||||||
|
"228990" to ("d3dx9" to "DirectX (June 2010)"),
|
||||||
|
)
|
||||||
|
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
||||||
|
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
||||||
|
|
||||||
|
/** The game's appmanifest beside its install folder (steamapps/common/<dir> -> steamapps/). */
|
||||||
|
fun manifest(gameDir: File?, appId: Int): File? {
|
||||||
|
val steamapps = gameDir?.parentFile?.parentFile ?: return null
|
||||||
|
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun detect(gameDir: File?, appId: Int): List<DependencyDetector.Recommendation> {
|
||||||
|
val text = try {
|
||||||
|
manifest(gameDir, appId)?.takeIf { it.length() < 1L shl 20 }?.readText() ?: return emptyList()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
|
val block = BLOCK.find(text)?.groupValues?.get(1) ?: return emptyList()
|
||||||
|
return ENTRY.findAll(block).mapNotNull { DEPOTS[it.groupValues[1]] }
|
||||||
|
.distinctBy { it.first }
|
||||||
|
.map { (component, label) -> DependencyDetector.Recommendation(component, label, label, DependencyDetector.Kind.STEAM) }
|
||||||
|
.toList()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package com.droiddeck.launcher.gpu
|
||||||
|
|
||||||
|
import android.app.ActivityManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.os.Build
|
||||||
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
import java.io.File
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything the device info window shows about the phone's chip: SoC, GPU, CPU, memory, system,
|
||||||
|
* the phone's own Vulkan driver and the drivers DroidDeck uses. Reads files and asks Vulkan once
|
||||||
|
* ([VulkanInfo]), so [collect] belongs off the main thread. Values the phone does not give are
|
||||||
|
* left out rather than guessed.
|
||||||
|
*/
|
||||||
|
object DeviceInfo {
|
||||||
|
class Section(val title: String, val rows: List<Pair<String, String>>)
|
||||||
|
|
||||||
|
fun collect(context: Context): List<Section> {
|
||||||
|
val vk = VulkanInfo.query()
|
||||||
|
// After Vulkan has been asked, detection can use its name too.
|
||||||
|
val gpu = GpuInfo.detect()
|
||||||
|
return listOf(
|
||||||
|
chip(), gpu(gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||||
|
).filter { it.rows.isNotEmpty() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The whole window as plain text, for a bug report. */
|
||||||
|
fun text(sections: List<Section>): String = buildString {
|
||||||
|
append("DroidDeck device info\n")
|
||||||
|
for (s in sections) {
|
||||||
|
append('\n').append(s.title).append('\n')
|
||||||
|
for ((k, v) in s.rows) append(" ").append(k).append(": ").append(v).append('\n')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun MutableList<Pair<String, String>>.add(key: String, value: String?) {
|
||||||
|
if (!value.isNullOrBlank() && value != Build.UNKNOWN) add(key to value.trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun read(path: String): String? = FileUtils.readString(File(path))?.trim()?.ifEmpty { null }
|
||||||
|
|
||||||
|
private fun prop(name: String): String = GpuInfo.systemProperty(name)
|
||||||
|
|
||||||
|
private fun chip() = Section("Chip (SoC)", buildList<Pair<String, String>> {
|
||||||
|
val model = SocNames.model()
|
||||||
|
val platform = prop("ro.board.platform")
|
||||||
|
add("Name", SocNames.name(model, platform))
|
||||||
|
add("Model", model)
|
||||||
|
if (Build.VERSION.SDK_INT >= 31) add("Maker", Build.SOC_MANUFACTURER)
|
||||||
|
add("Platform", platform)
|
||||||
|
add("Hardware", Build.HARDWARE)
|
||||||
|
add("Board", Build.BOARD)
|
||||||
|
val id = read("/sys/devices/soc0/soc_id")
|
||||||
|
val machine = read("/sys/devices/soc0/machine")
|
||||||
|
add("SoC id", listOfNotNull(id, machine).joinToString(" · "))
|
||||||
|
add("Family", read("/sys/devices/soc0/family"))
|
||||||
|
})
|
||||||
|
|
||||||
|
private fun gpu(gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
|
||||||
|
add("GPU", gpu.name)
|
||||||
|
add("Family", gpu.family.label)
|
||||||
|
add("Model found from", when (gpu.modelSource) {
|
||||||
|
"kernel" -> "the kernel's GPU name"
|
||||||
|
"vulkan" -> "the Vulkan driver (the kernel's name has no model)"
|
||||||
|
"platform" -> "the platform (the kernel's name has no model)"
|
||||||
|
else -> "unknown"
|
||||||
|
})
|
||||||
|
add("Kernel name", gpu.kgslName)
|
||||||
|
val kgsl = "/sys/class/kgsl/kgsl-3d0"
|
||||||
|
add("Clock range", gpuRange())
|
||||||
|
add("Load", read("$kgsl/gpu_busy_percentage")?.let { if (it.endsWith("%")) it else "$it %" })
|
||||||
|
add("Temperature", read("$kgsl/temp")?.toLongOrNull()?.let { if (it > 1000) "${it / 1000} °C" else "$it °C" })
|
||||||
|
add("Support", gpu.supportText)
|
||||||
|
})
|
||||||
|
|
||||||
|
private fun cpu() = Section("CPU", buildList<Pair<String, String>> {
|
||||||
|
add("Cores", Runtime.getRuntime().availableProcessors().toString())
|
||||||
|
// Each cpufreq policy is one cluster: the cores it covers and their speed range.
|
||||||
|
val policies = File("/sys/devices/system/cpu/cpufreq").listFiles { f -> f.name.matches(Regex("policy\\d+")) }
|
||||||
|
?.sortedBy { it.name.removePrefix("policy").toInt() }.orEmpty()
|
||||||
|
for (p in policies) {
|
||||||
|
val cpus = (read("${p.path}/related_cpus") ?: read("${p.path}/affected_cpus"))?.split(Regex("\\s+"))?.filter { it.isNotEmpty() }.orEmpty()
|
||||||
|
val min = read("${p.path}/cpuinfo_min_freq")?.toLongOrNull()
|
||||||
|
val max = read("${p.path}/cpuinfo_max_freq")?.toLongOrNull() ?: continue
|
||||||
|
val cores = if (cpus.size > 1) "cores ${cpus.first()}-${cpus.last()}" else "core ${cpus.firstOrNull() ?: p.name.removePrefix("policy")}"
|
||||||
|
add("Cluster ${p.name.removePrefix("policy")}", "${cpus.size.coerceAtLeast(1)} × $cores · " +
|
||||||
|
(if (min != null) ghz(min) + "–" else "") + ghz(max))
|
||||||
|
}
|
||||||
|
add("ABI", Build.SUPPORTED_ABIS.joinToString(", "))
|
||||||
|
})
|
||||||
|
|
||||||
|
private fun ghz(khz: Long) = String.format(Locale.US, "%.2f GHz", khz / 1e6)
|
||||||
|
|
||||||
|
/** The GPU's slowest and fastest step: KGSL's list, else a devfreq GPU node (Mali and others). */
|
||||||
|
private fun gpuRange(): String? {
|
||||||
|
fun mhz(hz: Long) = "${hz / 1_000_000} MHz"
|
||||||
|
val kgsl = read("/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies")
|
||||||
|
?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
|
||||||
|
if (kgsl.isNotEmpty()) return "${mhz(kgsl.min())}–${mhz(kgsl.max())} (${kgsl.size} steps)"
|
||||||
|
read("/sys/class/kgsl/kgsl-3d0/max_gpuclk")?.toLongOrNull()?.let { return "up to ${mhz(it)}" }
|
||||||
|
val node = File("/sys/class/devfreq").listFiles()?.firstOrNull { f ->
|
||||||
|
val n = f.name.lowercase()
|
||||||
|
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
|
||||||
|
} ?: return null
|
||||||
|
val steps = read("${node.path}/available_frequencies")?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
|
||||||
|
if (steps.isNotEmpty()) return "${mhz(steps.min())}–${mhz(steps.max())} (${steps.size} steps)"
|
||||||
|
val min = read("${node.path}/min_freq")?.toLongOrNull()
|
||||||
|
val max = read("${node.path}/max_freq")?.toLongOrNull() ?: return null
|
||||||
|
return (if (min != null) "${mhz(min)}–" else "up to ") + mhz(max)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun memory(context: Context) = Section("Memory", buildList<Pair<String, String>> {
|
||||||
|
val am = context.getSystemService(ActivityManager::class.java) ?: return@buildList
|
||||||
|
val mi = ActivityManager.MemoryInfo().also(am::getMemoryInfo)
|
||||||
|
add("Total", FileUtils.sizeToString(mi.totalMem))
|
||||||
|
add("Available now", FileUtils.sizeToString(mi.availMem))
|
||||||
|
})
|
||||||
|
|
||||||
|
private fun system() = Section("System", buildList<Pair<String, String>> {
|
||||||
|
add("Device", "${Build.MANUFACTURER} ${Build.MODEL}")
|
||||||
|
add("Android", "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
|
||||||
|
add("Security patch", Build.VERSION.SECURITY_PATCH)
|
||||||
|
add("Kernel", System.getProperty("os.version"))
|
||||||
|
add("Build", Build.DISPLAY)
|
||||||
|
})
|
||||||
|
|
||||||
|
private fun vulkan(context: Context, vk: Map<String, String>) = Section("Vulkan (the phone's own driver)", buildList<Pair<String, String>> {
|
||||||
|
vk["error"]?.let { add("Error", it) }
|
||||||
|
add("Device", vk["device"])
|
||||||
|
add("Type", vk["type"])
|
||||||
|
add("API version", vk["api"])
|
||||||
|
add("Loader version", vk["loader"])
|
||||||
|
add("Driver", listOfNotNull(vk["driver_name"], vk["driver_version"]).joinToString(" "))
|
||||||
|
// Qualcomm's build string starts with its own label ("Driver Build: 43c70540de, ...").
|
||||||
|
add("Driver build", vk["driver_info"]?.replace(Regex("(?i)^driver build:\\s*"), ""))
|
||||||
|
add("Conformance", vk["conformance"])
|
||||||
|
add("Vendor / device id", listOfNotNull(vk["vendor_id"], vk["device_id"]).joinToString(" / "))
|
||||||
|
add("Max texture size", vk["max_image_2d"])
|
||||||
|
add("GPU memory heap", vk["device_heap_mb"]?.let { "$it MB" })
|
||||||
|
add("Extensions", vk["extension_count"])
|
||||||
|
val features = listOf("geometry_shader" to "Geometry shaders", "tessellation_shader" to "Tessellation", "texture_bc" to "BC textures")
|
||||||
|
for ((key, label) in features) add(label, vk[key])
|
||||||
|
for ((key, value) in vk) if (key.startsWith("ext.")) add(key.removePrefix("ext."), value)
|
||||||
|
// What Android certifies the phone for.
|
||||||
|
val pm = context.packageManager
|
||||||
|
val hw = pm.systemAvailableFeatures.associate { it.name to it.version }
|
||||||
|
hw[PackageManager.FEATURE_VULKAN_HARDWARE_VERSION]?.let {
|
||||||
|
add("Android-certified version", "${it shr 22}.${(it shr 12) and 0x3ff}.${it and 0xfff}")
|
||||||
|
}
|
||||||
|
hw[PackageManager.FEATURE_VULKAN_HARDWARE_LEVEL]?.let { add("Android hardware level", it.toString()) }
|
||||||
|
})
|
||||||
|
|
||||||
|
private fun drivers(context: Context, gpu: GpuInfo) = Section("Drivers DroidDeck uses", buildList<Pair<String, String>> {
|
||||||
|
add("Driver mode", SessionPrefs.gpuDriverMode(context))
|
||||||
|
val turnip = TurnipDriver(context)
|
||||||
|
val choice = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
|
||||||
|
add("Display driver", "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
|
||||||
|
val linux = LinuxVulkanDriverManager(context)
|
||||||
|
val id = SessionPrefs.linuxDriver(context)
|
||||||
|
add("Game driver", if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
|
||||||
|
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.gpu
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
@@ -84,7 +85,7 @@ object DriverBundle {
|
|||||||
unzip(context, uri, work)
|
unzip(context, uri, work)
|
||||||
val manifest = File(work, MANIFEST).takeIf { it.isFile }
|
val manifest = File(work, MANIFEST).takeIf { it.isFile }
|
||||||
?.let { runCatching { parseManifest(JSONObject(FileUtils.readString(it))) }.getOrNull() }
|
?.let { runCatching { parseManifest(JSONObject(FileUtils.readString(it))) }.getOrNull() }
|
||||||
?: throw IllegalArgumentException("Not a driver bundle: no manifest.json naming an android and a linux driver")
|
?: throw IllegalArgumentException(context.getString(R.string.bundle_no_manifest))
|
||||||
val androidDir = File(work, manifest.androidPath)
|
val androidDir = File(work, manifest.androidPath)
|
||||||
val linuxDir = File(work, manifest.linuxPath)
|
val linuxDir = File(work, manifest.linuxPath)
|
||||||
|
|
||||||
@@ -135,7 +136,7 @@ object DriverBundle {
|
|||||||
for (entry in generateSequence { zip.nextEntry }) {
|
for (entry in generateSequence { zip.nextEntry }) {
|
||||||
if (entry.isDirectory) continue
|
if (entry.isDirectory) continue
|
||||||
val out = File(root, entry.name).canonicalFile
|
val out = File(root, entry.name).canonicalFile
|
||||||
if (!out.path.startsWith(root.path + File.separator)) throw IllegalArgumentException("Not a driver bundle: ${entry.name} points outside it")
|
if (!out.path.startsWith(root.path + File.separator)) throw IllegalArgumentException(context.getString(R.string.bundle_entry_outside, entry.name))
|
||||||
out.parentFile?.mkdirs()
|
out.parentFile?.mkdirs()
|
||||||
out.outputStream().use { sink ->
|
out.outputStream().use { sink ->
|
||||||
val buf = ByteArray(1 shl 16)
|
val buf = ByteArray(1 shl 16)
|
||||||
@@ -143,7 +144,7 @@ object DriverBundle {
|
|||||||
val r = zip.read(buf)
|
val r = zip.read(buf)
|
||||||
if (r <= 0) break
|
if (r <= 0) break
|
||||||
total += r
|
total += r
|
||||||
if (total > MAX_BYTES) throw IllegalArgumentException("Not a driver bundle: it unpacks to more than ${MAX_BYTES shr 20} MB")
|
if (total > MAX_BYTES) throw IllegalArgumentException(context.getString(R.string.bundle_too_large, MAX_BYTES shr 20))
|
||||||
sink.write(buf, 0, r)
|
sink.write(buf, 0, r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
package com.droiddeck.launcher.gpu
|
package com.droiddeck.launcher.gpu
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What GPU this is, in the terms the driver lists are sorted by. KGSL names the model
|
* What GPU this is, in the terms the driver lists are sorted by. KGSL names the model
|
||||||
* ("Adreno740v2", "Adreno825"); the family decides which Turnip builds run on it at all, and the
|
* ("Adreno740v2", "Adreno825"); the family decides which Turnip builds run on it at all, and the
|
||||||
* support level is what the app has actually been tested on (Adreno 725 and up) - an Adreno 610
|
* support level is what the app has actually been tested on (Adreno 650, 725 and newer) - an
|
||||||
* may start, but it is not "supported" just because it is a Qualcomm chip.
|
* Adreno 610 may start, but it is not "supported" just because it is a Qualcomm chip.
|
||||||
*/
|
*/
|
||||||
data class GpuInfo(
|
data class GpuInfo(
|
||||||
/** "Adreno 740", or the vendor's own name when this is not an Adreno. */
|
/** "Adreno 740", or the vendor's own name when this is not an Adreno. */
|
||||||
@@ -16,10 +18,14 @@ data class GpuInfo(
|
|||||||
/** The three-digit Adreno model (740, 825), or 0 when KGSL does not say. */
|
/** The three-digit Adreno model (740, 825), or 0 when KGSL does not say. */
|
||||||
val model: Int,
|
val model: Int,
|
||||||
val family: Family,
|
val family: Family,
|
||||||
/** The SoC as the device reports it ("SM8550", "QCS8550"), or "" when it does not. */
|
/** The SoC as a person would say it ("Snapdragon 8 Gen 2 (QCS8550)"), or "" when the phone does not say. */
|
||||||
val soc: String,
|
val soc: String,
|
||||||
/** Samsung's One UI on an 8 Gen 2: its Turnip needs the OneUI build, or frames tear and flicker. */
|
/** Samsung's One UI on an 8 Gen 2: its Turnip needs the OneUI build, or frames tear and flicker. */
|
||||||
val oneUi8Gen2: Boolean,
|
val oneUi8Gen2: Boolean,
|
||||||
|
/** KGSL's own name for the GPU, as the kernel spells it ("Adreno740v2", "Adreno33v2"). */
|
||||||
|
val kgslName: String = "",
|
||||||
|
/** Where [model] came from: "kernel", "vulkan" or "platform", "" when unknown. */
|
||||||
|
val modelSource: String = "",
|
||||||
) {
|
) {
|
||||||
enum class Family(val label: String) {
|
enum class Family(val label: String) {
|
||||||
A8XX("Adreno 8xx"),
|
A8XX("Adreno 8xx"),
|
||||||
@@ -29,7 +35,10 @@ data class GpuInfo(
|
|||||||
A6XX("Adreno 6xx"),
|
A6XX("Adreno 6xx"),
|
||||||
/** An Adreno whose model KGSL does not give: treated as the newest family it could be. */
|
/** An Adreno whose model KGSL does not give: treated as the newest family it could be. */
|
||||||
ADRENO_UNKNOWN("Adreno"),
|
ADRENO_UNKNOWN("Adreno"),
|
||||||
NOT_ADRENO("Not an Adreno GPU"),
|
NOT_ADRENO("Not an Adreno GPU");
|
||||||
|
|
||||||
|
/** [label] in the app's language: the Adreno families are names, the rest is words. */
|
||||||
|
fun label(context: Context): String = if (this == NOT_ADRENO) context.getString(R.string.gpuinfo_not_adreno) else label
|
||||||
}
|
}
|
||||||
|
|
||||||
enum class Support { TESTED, UNTESTED, UNSUPPORTED }
|
enum class Support { TESTED, UNTESTED, UNSUPPORTED }
|
||||||
@@ -37,36 +46,82 @@ data class GpuInfo(
|
|||||||
val support: Support
|
val support: Support
|
||||||
get() = when {
|
get() = when {
|
||||||
family == Family.NOT_ADRENO -> Support.UNSUPPORTED
|
family == Family.NOT_ADRENO -> Support.UNSUPPORTED
|
||||||
|
family == Family.A6XX && model == 650 -> Support.TESTED
|
||||||
family == Family.A8XX -> Support.TESTED
|
family == Family.A8XX -> Support.TESTED
|
||||||
family == Family.A7XX && model >= 725 -> Support.TESTED
|
family == Family.A7XX && model >= 725 -> Support.TESTED
|
||||||
else -> Support.UNTESTED
|
else -> Support.UNTESTED
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One line for the device card and the system check. */
|
/** One line for the device card and the system check, in English for the device report. */
|
||||||
val supportText: String
|
val supportText: String
|
||||||
get() = when (support) {
|
get() = when (support) {
|
||||||
Support.TESTED -> "Supported"
|
Support.TESTED -> "Supported"
|
||||||
Support.UNTESTED -> if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
|
Support.UNTESTED -> if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
|
||||||
else "Below tested hardware (Adreno 725 and newer): it may not run"
|
else "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
|
||||||
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
|
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** [supportText] in the app's language. */
|
||||||
|
fun supportText(context: Context): String = context.getString(when (support) {
|
||||||
|
Support.TESTED -> R.string.gpuinfo_supported
|
||||||
|
Support.UNTESTED -> if (family == Family.A7XX_LOW) R.string.gpuinfo_experimental else R.string.gpuinfo_below_tested
|
||||||
|
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
|
||||||
|
})
|
||||||
|
|
||||||
|
/** [name] for the screen: the stand-in for a GPU the device does not name is in the app's language. */
|
||||||
|
fun displayName(context: Context): String = if (name == UNNAMED) context.getString(R.string.gpu_this_gpu) else name
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
/** [name] when the device names no GPU; English, as the device report shows it. */
|
||||||
|
private const val UNNAMED = "this GPU"
|
||||||
|
|
||||||
fun detect(): GpuInfo {
|
fun detect(): GpuInfo {
|
||||||
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
||||||
val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid")
|
val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid")
|
||||||
.firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) }
|
.firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) }
|
||||||
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN }.orEmpty() else ""
|
// Where vendors put the chip's model, named when it is known: "Snapdragon 8 Gen 2 (QCS8550)".
|
||||||
val model = raw?.let { Regex("""(\d{3})""").find(it)?.groupValues?.get(1)?.toIntOrNull() } ?: 0
|
val soc = if (adreno) SocNames.label() else ""
|
||||||
|
val fromKernel = raw?.let { threeDigits(it) } ?: 0
|
||||||
|
// Some kernels name the GPU without its model (AYANEO's Pocket FIT: "Adreno33v2"). The
|
||||||
|
// Vulkan driver's own name, when this process has asked it, then the platform's code
|
||||||
|
// name stand in - the GPU is the same on every phone of a platform.
|
||||||
|
val fromVulkan = if (fromKernel > 0 || !adreno) 0 else VulkanInfo.cachedOrNull()?.get("device")?.let { threeDigits(it) } ?: 0
|
||||||
|
val fromPlatform = if (fromKernel > 0 || fromVulkan > 0 || !adreno) 0 else platformModel()
|
||||||
|
val model = maxOf(fromKernel, fromVulkan, fromPlatform)
|
||||||
|
val source = when {
|
||||||
|
fromKernel > 0 -> "kernel"
|
||||||
|
fromVulkan > 0 -> "vulkan"
|
||||||
|
fromPlatform > 0 -> "platform"
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
val family = familyOf(adreno, model)
|
val family = familyOf(adreno, model)
|
||||||
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
||||||
return GpuInfo(
|
return GpuInfo(
|
||||||
name = if (!adreno) Build.HARDWARE.ifBlank { "this GPU" } else if (model > 0) "Adreno $model" else "Adreno",
|
name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno",
|
||||||
model = model, family = family, soc = soc,
|
model = model, family = family, soc = soc,
|
||||||
oneUi8Gen2 = samsung && model == 740,
|
oneUi8Gen2 = samsung && model == 740,
|
||||||
|
kgslName = raw.orEmpty(), modelSource = source,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun threeDigits(text: String): Int = Regex("""(\d{3})""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||||
|
|
||||||
|
/** Qualcomm platform code names whose GPU is known for certain. */
|
||||||
|
private val PLATFORMS = mapOf(
|
||||||
|
"msmnile" to 640, "kona" to 650, "lahaina" to 660, "taro" to 730, "cape" to 730,
|
||||||
|
"kalama" to 740, "pineapple" to 750, "sun" to 830,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal fun platformModel(platform: String = systemProperty("ro.board.platform")): Int =
|
||||||
|
PLATFORMS[platform.lowercase()] ?: PLATFORMS[systemProperty("ro.vendor.qti.soc_name").lowercase()] ?: 0
|
||||||
|
|
||||||
|
/** android.os.SystemProperties.get, which apps may read but not call directly. */
|
||||||
|
fun systemProperty(name: String): String = try {
|
||||||
|
Class.forName("android.os.SystemProperties").getMethod("get", String::class.java).invoke(null, name) as? String ?: ""
|
||||||
|
} catch (_: Exception) {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
|
||||||
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
|
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
|
||||||
!adreno -> Family.NOT_ADRENO
|
!adreno -> Family.NOT_ADRENO
|
||||||
model == 0 -> Family.ADRENO_UNKNOWN
|
model == 0 -> Family.ADRENO_UNKNOWN
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import android.content.Context;
|
|||||||
import android.net.Uri;
|
import android.net.Uri;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.R;
|
||||||
import com.droiddeck.launcher.core.FileUtils;
|
import com.droiddeck.launcher.core.FileUtils;
|
||||||
|
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
@@ -181,20 +182,17 @@ public class LinuxVulkanDriverManager {
|
|||||||
String adopt(File tmpDir, String soName, JSONObject zipMeta, String displayName) throws IOException {
|
String adopt(File tmpDir, String soName, JSONObject zipMeta, String displayName) throws IOException {
|
||||||
try {
|
try {
|
||||||
if (soName == null) {
|
if (soName == null) {
|
||||||
throw new IllegalArgumentException("No libvulkan_freedreno*.so in this zip. An Android "
|
throw new IllegalArgumentException(context.getString(R.string.lvd_no_library));
|
||||||
+ "(AdrenoTools) or -Wayland Turnip zip is not a Linux runtime driver.");
|
|
||||||
}
|
}
|
||||||
File so = new File(tmpDir, LIB_NAME);
|
File so = new File(tmpDir, LIB_NAME);
|
||||||
if (!isAarch64Elf(so)) {
|
if (!isAarch64Elf(so)) {
|
||||||
throw new IllegalArgumentException(soName + " is not a 64-bit AArch64 ELF shared library.");
|
throw new IllegalArgumentException(context.getString(R.string.lvd_not_aarch64, soName));
|
||||||
}
|
}
|
||||||
// The one check that actually separates this from the bionic builds. Both sonames
|
// The one check that actually separates this from the bionic builds. Both sonames
|
||||||
// are in the driver's .dynstr, so a byte scan is enough and needs no ELF parsing:
|
// are in the driver's .dynstr, so a byte scan is enough and needs no ELF parsing:
|
||||||
// glibc's is versioned ("libc.so.6"), bionic's is not ("libc.so").
|
// glibc's is versioned ("libc.so.6"), bionic's is not ("libc.so").
|
||||||
if (!containsAscii(so, "libc.so.6")) {
|
if (!containsAscii(so, "libc.so.6")) {
|
||||||
throw new IllegalArgumentException(soName + " is not a glibc driver - it links Android's libc. "
|
throw new IllegalArgumentException(context.getString(R.string.lvd_not_glibc, soName));
|
||||||
+ "The Linux runtime needs a \"-Linux\" zip; a plain or \"-Wayland\" Turnip cannot be "
|
|
||||||
+ "loaded by the Steam client at all.");
|
|
||||||
}
|
}
|
||||||
String kind = zipMeta != null ? zipMeta.optString("kind", "") : "";
|
String kind = zipMeta != null ? zipMeta.optString("kind", "") : "";
|
||||||
if (!kind.isEmpty() && !"linux-vulkan-icd".equals(kind)) {
|
if (!kind.isEmpty() && !"linux-vulkan-icd".equals(kind)) {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package com.droiddeck.launcher.gpu
|
package com.droiddeck.launcher.gpu
|
||||||
|
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
@@ -82,11 +84,15 @@ data class ScreenEffects(
|
|||||||
* SessionPrefs.upscalerChoices mode the Look switches to.
|
* SessionPrefs.upscalerChoices mode the Look switches to.
|
||||||
*/
|
*/
|
||||||
data class Look(
|
data class Look(
|
||||||
|
/** The Look's id: what the row picks by and the compositor logs. */
|
||||||
val name: String,
|
val name: String,
|
||||||
val effects: ScreenEffects,
|
val effects: ScreenEffects,
|
||||||
val scalingMode: Int? = null,
|
val scalingMode: Int? = null,
|
||||||
/** One line under the row while this Look is picked. */
|
/** One line under the row while this Look is picked. */
|
||||||
val desc: String,
|
val desc: String,
|
||||||
|
/** [name] and [desc] in the app's language, for the menu. */
|
||||||
|
@StringRes val label: Int,
|
||||||
|
@StringRes val descRes: Int,
|
||||||
)
|
)
|
||||||
|
|
||||||
object ScreenEffectLooks {
|
object ScreenEffectLooks {
|
||||||
@@ -96,29 +102,29 @@ object ScreenEffectLooks {
|
|||||||
|
|
||||||
/** Index 0 is the neutral state a fresh session matches, so the row always names something. */
|
/** Index 0 is the neutral state a fresh session matches, so the row always names something. */
|
||||||
val LOOKS: List<Look> = listOf(
|
val LOOKS: List<Look> = listOf(
|
||||||
Look("Off", ScreenEffects.OFF, desc = "Nothing applied."),
|
Look("Off", ScreenEffects.OFF, desc = "Nothing applied.", label = R.string.frame_gen_off, descRes = R.string.look_off_desc),
|
||||||
Look("Game Clarity", ScreenEffects(brightness = 2, contrast = 12, saturation = 108, cas = true, casLevel = 55),
|
Look("Game Clarity", ScreenEffects(brightness = 2, contrast = 12, saturation = 108, cas = true, casLevel = 55),
|
||||||
desc = "Sharpening with a touch of contrast - the everyday one."),
|
desc = "Sharpening with a touch of contrast - the everyday one.", label = R.string.look_game_clarity, descRes = R.string.look_game_clarity_desc),
|
||||||
Look("Vivid", ScreenEffects(brightness = 3, contrast = 10, gamma = 0.98f, saturation = 145, cas = true, casLevel = 30, deband = true),
|
Look("Vivid", ScreenEffects(brightness = 3, contrast = 10, gamma = 0.98f, saturation = 145, cas = true, casLevel = 30, deband = true),
|
||||||
desc = "Colour pushed hard. Deband on so skies don't stripe."),
|
desc = "Colour pushed hard. Deband on so skies don't stripe.", label = R.string.look_vivid, descRes = R.string.look_vivid_desc),
|
||||||
Look("Cinematic", ScreenEffects(brightness = -4, contrast = 22, gamma = 1.10f, saturation = 88, cas = true, casLevel = 20, fxaa = true, deband = true),
|
Look("Cinematic", ScreenEffects(brightness = -4, contrast = 22, gamma = 1.10f, saturation = 88, cas = true, casLevel = 20, fxaa = true, deband = true),
|
||||||
desc = "Deeper contrast, cooler colour, edges smoothed."),
|
desc = "Deeper contrast, cooler colour, edges smoothed.", label = R.string.look_cinematic, descRes = R.string.look_cinematic_desc),
|
||||||
Look("Competitive", ScreenEffects(brightness = 16, contrast = 18, gamma = 0.92f, saturation = 82, cas = true, casLevel = 75),
|
Look("Competitive", ScreenEffects(brightness = 16, contrast = 18, gamma = 0.92f, saturation = 82, cas = true, casLevel = 75),
|
||||||
desc = "Shadows lifted and heavy sharpening - spot people first."),
|
desc = "Shadows lifted and heavy sharpening - spot people first.", label = R.string.look_competitive, descRes = R.string.look_competitive_desc),
|
||||||
Look("Adaptive Sharpen", ScreenEffects(cas = true, casLevel = 85),
|
Look("Adaptive Sharpen", ScreenEffects(cas = true, casLevel = 85),
|
||||||
desc = "Sharpening only, colour untouched."),
|
desc = "Sharpening only, colour untouched.", label = R.string.look_adaptive_sharpen, descRes = R.string.look_adaptive_sharpen_desc),
|
||||||
Look("Filmic", ScreenEffects(brightness = -2, contrast = 16, gamma = 1.14f, saturation = 92, cas = true, casLevel = 15, fxaa = true, deband = true),
|
Look("Filmic", ScreenEffects(brightness = -2, contrast = 16, gamma = 1.14f, saturation = 92, cas = true, casLevel = 15, fxaa = true, deband = true),
|
||||||
desc = "Film-like curve, slightly muted."),
|
desc = "Film-like curve, slightly muted.", label = R.string.look_filmic, descRes = R.string.look_filmic_desc),
|
||||||
Look("Arcade", ScreenEffects(brightness = 6, contrast = 20, gamma = 0.95f, saturation = 170, cas = true, casLevel = 45, deband = true),
|
Look("Arcade", ScreenEffects(brightness = 6, contrast = 20, gamma = 0.95f, saturation = 170, cas = true, casLevel = 45, deband = true),
|
||||||
desc = "Loud and punchy."),
|
desc = "Loud and punchy.", label = R.string.look_arcade, descRes = R.string.look_arcade_desc),
|
||||||
Look("Retro CRT", ScreenEffects(brightness = 6, contrast = 14, gamma = 1.05f, saturation = 115, crt = true, ntsc = true),
|
Look("Retro CRT", ScreenEffects(brightness = 6, contrast = 14, gamma = 1.05f, saturation = 115, crt = true, ntsc = true),
|
||||||
desc = "The CRT tube and analogue signal passes together."),
|
desc = "The CRT tube and analogue signal passes together.", label = R.string.look_retro_crt, descRes = R.string.look_retro_crt_desc),
|
||||||
Look("Upscale Sharp", ScreenEffects(contrast = 6, saturation = 104, cas = true, casLevel = 70), scalingMode = SCALING_FSR,
|
Look("Upscale Sharp", ScreenEffects(contrast = 6, saturation = 104, cas = true, casLevel = 70), scalingMode = SCALING_FSR,
|
||||||
desc = "For running below panel resolution."),
|
desc = "For running below panel resolution.", label = R.string.look_upscale_sharp, descRes = R.string.look_upscale_sharp_desc),
|
||||||
Look("Pixel Clean", ScreenEffects(contrast = 8, deband = true), scalingMode = SCALING_NEAREST,
|
Look("Pixel Clean", ScreenEffects(contrast = 8, deband = true), scalingMode = SCALING_NEAREST,
|
||||||
desc = "Crisp pixels for 2D and old titles."),
|
desc = "Crisp pixels for 2D and old titles.", label = R.string.look_pixel_clean, descRes = R.string.look_pixel_clean_desc),
|
||||||
Look("Anime Edge", ScreenEffects(brightness = 2, contrast = 10, saturation = 125, cas = true, casLevel = 50, toon = true, deband = true),
|
Look("Anime Edge", ScreenEffects(brightness = 2, contrast = 10, saturation = 125, cas = true, casLevel = 50, toon = true, deband = true),
|
||||||
desc = "Toon outlines plus sharpening."),
|
desc = "Toon outlines plus sharpening.", label = R.string.look_anime_edge, descRes = R.string.look_anime_edge_desc),
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.droiddeck.launcher.gpu
|
||||||
|
|
||||||
|
import android.os.Build
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which chip this is, as a person would say it. Handhelds often leave Android's SoC model blank
|
||||||
|
* (the AYANEO Pocket FIT does), so the model is looked for where vendors put it, the same order
|
||||||
|
* ClusterTune uses; then it is named from a table of models we are sure of, or from the platform
|
||||||
|
* code name as a family ("Snapdragon 8 Gen 3 family") when the model itself is a vendor variant.
|
||||||
|
*/
|
||||||
|
object SocNames {
|
||||||
|
/** Model codes whose product name is certain. */
|
||||||
|
private val MODELS = mapOf(
|
||||||
|
"SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870",
|
||||||
|
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
|
||||||
|
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
|
||||||
|
"SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5",
|
||||||
|
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
||||||
|
"SM6375" to "Snapdragon 695",
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Platform code names: every chip of one platform shares its CPU and GPU design. */
|
||||||
|
private val PLATFORMS = mapOf(
|
||||||
|
"msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888",
|
||||||
|
"taro" to "Snapdragon 8 Gen 1", "cape" to "Snapdragon 8+ Gen 1", "kalama" to "Snapdragon 8 Gen 2",
|
||||||
|
"pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite",
|
||||||
|
)
|
||||||
|
|
||||||
|
/** The chip's model code ("QCS8550", "SG8350P"), or "" when the phone does not say. */
|
||||||
|
fun model(prop: (String) -> String = GpuInfo::systemProperty): String {
|
||||||
|
val sdk = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it != Build.UNKNOWN }.orEmpty() else ""
|
||||||
|
return listOf(prop("ro.soc.model"), prop("ro.vendor.qti.soc_model"), sdk, prop("ro.fota.platform"))
|
||||||
|
.map { it.trim() }
|
||||||
|
// ro.fota.platform is often a branch name ("MSM_13.0"), not a chip.
|
||||||
|
.firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Snapdragon 8 Gen 2", "Snapdragon 8 Gen 3 family", or null when neither the model nor the platform is known. */
|
||||||
|
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
|
||||||
|
MODELS[model.uppercase()] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
||||||
|
|
||||||
|
/** For the GPU card: "Snapdragon 8 Gen 2 (QCS8550)", the bare model, or "". */
|
||||||
|
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
|
||||||
|
val name = name(model, platform)
|
||||||
|
return when {
|
||||||
|
name != null && model.isNotEmpty() -> "$name ($model)"
|
||||||
|
name != null -> name
|
||||||
|
else -> model
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import android.net.Uri;
|
|||||||
import android.os.Environment;
|
import android.os.Environment;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.R;
|
||||||
import com.droiddeck.launcher.core.FileUtils;
|
import com.droiddeck.launcher.core.FileUtils;
|
||||||
import com.droiddeck.launcher.core.TarZst;
|
import com.droiddeck.launcher.core.TarZst;
|
||||||
import com.droiddeck.launcher.session.SessionPrefs;
|
import com.droiddeck.launcher.session.SessionPrefs;
|
||||||
@@ -218,7 +219,7 @@ public final class TurnipDriver {
|
|||||||
*/
|
*/
|
||||||
String adopt(File tmpDir, String displayName) throws IOException {
|
String adopt(File tmpDir, String displayName) throws IOException {
|
||||||
String rejected = rejectionReason(tmpDir);
|
String rejected = rejectionReason(tmpDir);
|
||||||
if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected);
|
if (rejected != null) throw new IllegalArgumentException(context.getString(R.string.turnip_not_adrenotools, rejected));
|
||||||
|
|
||||||
JSONObject meta = readMetaFile(new File(tmpDir, "meta.json"));
|
JSONObject meta = readMetaFile(new File(tmpDir, "meta.json"));
|
||||||
String name = meta != null ? meta.optString("name", "") : "";
|
String name = meta != null ? meta.optString("name", "") : "";
|
||||||
@@ -245,31 +246,31 @@ public final class TurnipDriver {
|
|||||||
* Why a just-extracted zip is not something adrenotools can be pointed at, or null when it is.
|
* Why a just-extracted zip is not something adrenotools can be pointed at, or null when it is.
|
||||||
* The kinds refused by name are the other driver lists' zips, which carry a meta.json too.
|
* The kinds refused by name are the other driver lists' zips, which carry a meta.json too.
|
||||||
*/
|
*/
|
||||||
private static String rejectionReason(File dir) {
|
private String rejectionReason(File dir) {
|
||||||
File metaFile = new File(dir, "meta.json");
|
File metaFile = new File(dir, "meta.json");
|
||||||
if (!metaFile.isFile()) return "no meta.json";
|
if (!metaFile.isFile()) return context.getString(R.string.turnip_reject_no_meta);
|
||||||
String libraryName, kind;
|
String libraryName, kind;
|
||||||
try {
|
try {
|
||||||
JSONObject meta = new JSONObject(FileUtils.readString(metaFile));
|
JSONObject meta = new JSONObject(FileUtils.readString(metaFile));
|
||||||
libraryName = meta.optString("libraryName", "");
|
libraryName = meta.optString("libraryName", "");
|
||||||
kind = meta.optString("kind", "");
|
kind = meta.optString("kind", "");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return "meta.json is unreadable (" + e.getMessage() + ")";
|
return context.getString(R.string.turnip_reject_meta_unreadable, e.getMessage());
|
||||||
}
|
}
|
||||||
if ("linux-vulkan-icd".equals(kind))
|
if ("linux-vulkan-icd".equals(kind))
|
||||||
return "this is a Linux runtime driver (import it under \"Linux runtime driver\")";
|
return context.getString(R.string.turnip_reject_linux_driver);
|
||||||
if ("wayland-game-driver".equals(kind))
|
if ("wayland-game-driver".equals(kind))
|
||||||
return "this is a Wayland game driver, which this app has no use for";
|
return context.getString(R.string.turnip_reject_wayland);
|
||||||
if (libraryName.isEmpty())
|
if (libraryName.isEmpty())
|
||||||
return "meta.json names no libraryName, so nothing could be handed to AdrenoTools";
|
return context.getString(R.string.turnip_reject_no_library_name);
|
||||||
File library = new File(dir, libraryName);
|
File library = new File(dir, libraryName);
|
||||||
if (!library.isFile())
|
if (!library.isFile())
|
||||||
return "meta.json names " + libraryName + ", which is not in the zip";
|
return context.getString(R.string.turnip_reject_library_missing, libraryName);
|
||||||
if (!LinuxVulkanDriverManager.isAarch64Elf(library))
|
if (!LinuxVulkanDriverManager.isAarch64Elf(library))
|
||||||
return libraryName + " is not a 64-bit AArch64 ELF shared library";
|
return context.getString(R.string.turnip_reject_not_aarch64, libraryName);
|
||||||
// A glibc build that happens to carry a libraryName would load nothing in this process.
|
// A glibc build that happens to carry a libraryName would load nothing in this process.
|
||||||
if (LinuxVulkanDriverManager.containsAscii(library, "libc.so.6"))
|
if (LinuxVulkanDriverManager.containsAscii(library, "libc.so.6"))
|
||||||
return libraryName + " links glibc - a \"-Linux\" Turnip, which belongs under \"Linux runtime driver\"";
|
return context.getString(R.string.turnip_reject_glibc, libraryName);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.droiddeck.launcher.gpu
|
package com.droiddeck.launcher.gpu
|
||||||
|
|
||||||
import com.droiddeck.launcher.core.Hashes
|
import com.droiddeck.launcher.core.Hashes
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
@@ -95,7 +96,7 @@ object TurnipReleases {
|
|||||||
var lastError: Exception? = null
|
var lastError: Exception? = null
|
||||||
for (src in SOURCES) {
|
for (src in SOURCES) {
|
||||||
try {
|
try {
|
||||||
val releases = JSONArray(get("https://api.github.com/repos/${src.repo}/releases?per_page=15"))
|
val releases = JSONArray(get(context, "https://api.github.com/repos/${src.repo}/releases?per_page=15"))
|
||||||
val seen = HashSet<String>()
|
val seen = HashSet<String>()
|
||||||
var newest: String? = null
|
var newest: String? = null
|
||||||
for (i in 0 until releases.length()) {
|
for (i in 0 until releases.length()) {
|
||||||
@@ -135,7 +136,7 @@ object TurnipReleases {
|
|||||||
return parse(stored)
|
return parse(stored)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun get(url: String): String {
|
private fun get(context: Context, url: String): String {
|
||||||
val c = URL(url).openConnection() as HttpURLConnection
|
val c = URL(url).openConnection() as HttpURLConnection
|
||||||
c.connectTimeout = 15_000
|
c.connectTimeout = 15_000
|
||||||
c.readTimeout = 20_000
|
c.readTimeout = 20_000
|
||||||
@@ -143,8 +144,8 @@ object TurnipReleases {
|
|||||||
c.setRequestProperty("User-Agent", "DroidDeck-app")
|
c.setRequestProperty("User-Agent", "DroidDeck-app")
|
||||||
try {
|
try {
|
||||||
val code = c.responseCode
|
val code = c.responseCode
|
||||||
if (code == 403 || code == 429) throw IOException("GitHub's rate limit was hit - try again later")
|
if (code == 403 || code == 429) throw IOException(context.getString(R.string.turnip_rate_limited))
|
||||||
if (code != 200) throw IOException("GitHub answered HTTP $code")
|
if (code != 200) throw IOException(context.getString(R.string.turnip_github_http, code))
|
||||||
return c.inputStream.bufferedReader().use { it.readText() }
|
return c.inputStream.bufferedReader().use { it.readText() }
|
||||||
} finally {
|
} finally {
|
||||||
c.disconnect()
|
c.disconnect()
|
||||||
@@ -194,7 +195,7 @@ object TurnipReleases {
|
|||||||
|
|
||||||
/** Download an asset into the cache; the caller imports it and deletes the file. */
|
/** Download an asset into the cache; the caller imports it and deletes the file. */
|
||||||
fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File {
|
fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File {
|
||||||
if (asset.sha256.isEmpty()) throw IOException("This driver list predates checksums - refresh it and try again")
|
if (asset.sha256.isEmpty()) throw IOException(context.getString(R.string.turnip_list_predates_checksums))
|
||||||
val target = File(context.cacheDir, asset.name)
|
val target = File(context.cacheDir, asset.name)
|
||||||
val c = URL(asset.url).openConnection() as HttpURLConnection
|
val c = URL(asset.url).openConnection() as HttpURLConnection
|
||||||
c.connectTimeout = 15_000
|
c.connectTimeout = 15_000
|
||||||
@@ -202,7 +203,7 @@ object TurnipReleases {
|
|||||||
c.setRequestProperty("User-Agent", "DroidDeck-app")
|
c.setRequestProperty("User-Agent", "DroidDeck-app")
|
||||||
c.instanceFollowRedirects = true
|
c.instanceFollowRedirects = true
|
||||||
try {
|
try {
|
||||||
if (c.responseCode != 200) throw IOException("download answered HTTP ${c.responseCode}")
|
if (c.responseCode != 200) throw IOException(context.getString(R.string.turnip_download_http, c.responseCode))
|
||||||
val total = c.contentLengthLong.takeIf { it > 0 } ?: asset.size
|
val total = c.contentLengthLong.takeIf { it > 0 } ?: asset.size
|
||||||
c.inputStream.use { input ->
|
c.inputStream.use { input ->
|
||||||
FileOutputStream(target).use { out ->
|
FileOutputStream(target).use { out ->
|
||||||
@@ -220,7 +221,7 @@ object TurnipReleases {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!asset.sha256.equals(Hashes.sha256(target), ignoreCase = true)) {
|
if (!asset.sha256.equals(Hashes.sha256(target), ignoreCase = true)) {
|
||||||
throw IOException("Checksum mismatch - the download was discarded")
|
throw IOException(context.getString(R.string.turnip_checksum_mismatch))
|
||||||
}
|
}
|
||||||
return target
|
return target
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.droiddeck.launcher.gpu
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The phone's own Vulkan driver, as it describes itself (native/deviceinfo): device name, API and
|
||||||
|
* driver versions, a few limits and the extensions DXVK/VKD3D lean on. Asked once per process and
|
||||||
|
* kept; the first [query] creates a Vulkan instance, so it belongs off the main thread.
|
||||||
|
*/
|
||||||
|
object VulkanInfo {
|
||||||
|
@Volatile private var cached: Map<String, String>? = null
|
||||||
|
|
||||||
|
@JvmStatic private external fun nativeQuery(): String
|
||||||
|
|
||||||
|
/** Blocking on first use. Empty-ish map with an "error" key when Vulkan cannot be asked. */
|
||||||
|
@Synchronized
|
||||||
|
fun query(): Map<String, String> {
|
||||||
|
cached?.let { return it }
|
||||||
|
val text = try {
|
||||||
|
System.loadLibrary("deviceinfo")
|
||||||
|
nativeQuery()
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
Log.w("VulkanInfo", "query failed", t)
|
||||||
|
"error=" + (t.message ?: t.javaClass.simpleName)
|
||||||
|
}
|
||||||
|
val map = text.lineSequence().mapNotNull { line ->
|
||||||
|
val eq = line.indexOf('=')
|
||||||
|
if (eq <= 0) null else line.substring(0, eq) to line.substring(eq + 1)
|
||||||
|
}.toMap(LinkedHashMap())
|
||||||
|
cached = map
|
||||||
|
return map
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What [query] found, if it has run in this process; never blocks. */
|
||||||
|
fun cachedOrNull(): Map<String, String>? = cached
|
||||||
|
}
|
||||||
@@ -24,11 +24,18 @@ import androidx.compose.ui.text.font.FontWeight
|
|||||||
import androidx.compose.ui.platform.ComposeView
|
import androidx.compose.ui.platform.ComposeView
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||||
import com.droiddeck.launcher.ui.onSignal
|
import com.droiddeck.launcher.ui.onSignal
|
||||||
import com.droiddeck.launcher.ui.LocalPalette
|
import com.droiddeck.launcher.ui.LocalPalette
|
||||||
|
|
||||||
class ControllerEditorActivity : ComponentActivity() {
|
class ControllerEditorActivity : ComponentActivity() {
|
||||||
|
override fun attachBaseContext(newBase: android.content.Context) {
|
||||||
|
super.attachBaseContext(newBase)
|
||||||
|
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||||
|
}
|
||||||
|
|
||||||
private lateinit var controls: OnScreenControls
|
private lateinit var controls: OnScreenControls
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
@@ -48,10 +55,10 @@ class ControllerEditorActivity : ComponentActivity() {
|
|||||||
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.9f), RoundedCornerShape(50))
|
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.9f), RoundedCornerShape(50))
|
||||||
.padding(start = 14.dp, end = 5.dp, top = 5.dp, bottom = 5.dp),
|
.padding(start = 14.dp, end = 5.dp, top = 5.dp, bottom = 5.dp),
|
||||||
) {
|
) {
|
||||||
Text("Drag to move", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(end = 4.dp))
|
Text(stringResource(R.string.ctrl_editor_drag), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(end = 4.dp))
|
||||||
EditorButton("Reset", false) { controls.resetLayout() }
|
EditorButton(stringResource(R.string.ctrl_reset), false) { controls.resetLayout() }
|
||||||
EditorButton("Cancel", false) { finish() }
|
EditorButton(stringResource(R.string.common_cancel), false) { finish() }
|
||||||
EditorButton("Save", true) {
|
EditorButton(stringResource(R.string.ctrl_editor_save), true) {
|
||||||
controls.saveLayout()
|
controls.saveLayout()
|
||||||
finish()
|
finish()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,21 @@
|
|||||||
package com.droiddeck.launcher.input
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
|
||||||
object ControllerPrefs {
|
object ControllerPrefs {
|
||||||
const val STEAM_BLUE = 0xFF1A9FFF.toInt()
|
const val STEAM_BLUE = 0xFF1A9FFF.toInt()
|
||||||
const val OFF = "off"
|
const val OFF = "off"
|
||||||
|
|
||||||
val tints = listOf(
|
val tints = listOf(
|
||||||
STEAM_BLUE to "Steam blue",
|
STEAM_BLUE to R.string.ctrl_tint_steam_blue,
|
||||||
0xFF66C0F4.toInt() to "Sky",
|
0xFF66C0F4.toInt() to R.string.ctrl_tint_sky,
|
||||||
0xFFE8EEF4.toInt() to "White",
|
0xFFE8EEF4.toInt() to R.string.ctrl_tint_white,
|
||||||
0xFFC77DFF.toInt() to "Violet",
|
0xFFC77DFF.toInt() to R.string.ctrl_tint_violet,
|
||||||
0xFF3DDC84.toInt() to "Green",
|
0xFF3DDC84.toInt() to R.string.ctrl_tint_green,
|
||||||
0xFFFFA726.toInt() to "Amber",
|
0xFFFFA726.toInt() to R.string.ctrl_tint_amber,
|
||||||
0xFFFF5252.toInt() to "Red",
|
0xFFFF5252.toInt() to R.string.ctrl_tint_red,
|
||||||
0xFFFF6FB5.toInt() to "Pink",
|
0xFFFF6FB5.toInt() to R.string.ctrl_tint_pink,
|
||||||
)
|
)
|
||||||
|
|
||||||
val opacities = listOf(40, 60, 80, 100)
|
val opacities = listOf(40, 60, 80, 100)
|
||||||
@@ -22,17 +23,17 @@ object ControllerPrefs {
|
|||||||
val sizes = listOf(80, 90, 100, 110, 125)
|
val sizes = listOf(80, 90, 100, 110, 125)
|
||||||
|
|
||||||
val mappable = listOf(
|
val mappable = listOf(
|
||||||
"a" to "A button", "b" to "B button", "x" to "X button", "y" to "Y button",
|
"a" to R.string.ctrl_button_a, "b" to R.string.ctrl_button_b, "x" to R.string.ctrl_button_x, "y" to R.string.ctrl_button_y,
|
||||||
"lb" to "Left bumper", "rb" to "Right bumper", "lt" to "Left trigger", "rt" to "Right trigger",
|
"lb" to R.string.ctrl_button_lb, "rb" to R.string.ctrl_button_rb, "lt" to R.string.ctrl_button_lt, "rt" to R.string.ctrl_button_rt,
|
||||||
"select" to "View button", "start" to "Menu button",
|
"select" to R.string.ctrl_button_view, "start" to R.string.ctrl_button_menu,
|
||||||
)
|
)
|
||||||
|
|
||||||
val targets = listOf(
|
val targets = listOf(
|
||||||
"a" to "A", "b" to "B", "x" to "X", "y" to "Y",
|
"a" to R.string.ctrl_target_a, "b" to R.string.ctrl_target_b, "x" to R.string.ctrl_target_x, "y" to R.string.ctrl_target_y,
|
||||||
"lb" to "LB", "rb" to "RB", "lt" to "LT", "rt" to "RT",
|
"lb" to R.string.ctrl_target_lb, "rb" to R.string.ctrl_target_rb, "lt" to R.string.ctrl_target_lt, "rt" to R.string.ctrl_target_rt,
|
||||||
"l3" to "L3", "r3" to "R3", "select" to "View", "start" to "Menu", "guide" to "Steam",
|
"l3" to R.string.ctrl_target_l3, "r3" to R.string.ctrl_target_r3, "select" to R.string.ctrl_target_view, "start" to R.string.ctrl_target_menu, "guide" to R.string.ctrl_target_steam,
|
||||||
"up" to "D-pad up", "down" to "D-pad down", "left" to "D-pad left", "right" to "D-pad right",
|
"up" to R.string.ctrl_target_up, "down" to R.string.ctrl_target_down, "left" to R.string.ctrl_target_left, "right" to R.string.ctrl_target_right,
|
||||||
OFF to "Hidden",
|
OFF to R.string.ctrl_target_hidden,
|
||||||
)
|
)
|
||||||
|
|
||||||
class Settings(
|
class Settings(
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
object InputSpace {
|
||||||
|
const val WIDTH = 1920
|
||||||
|
const val HEIGHT = 1080
|
||||||
|
|
||||||
|
fun x(position: Float, viewWidth: Int): Int = scale(position, viewWidth, WIDTH)
|
||||||
|
|
||||||
|
fun y(position: Float, viewHeight: Int): Int = scale(position, viewHeight, HEIGHT)
|
||||||
|
|
||||||
|
private fun scale(position: Float, extent: Int, size: Int): Int =
|
||||||
|
if (extent <= 0) 0 else (position / extent * size).toInt().coerceIn(0, size - 1)
|
||||||
|
}
|
||||||
@@ -10,6 +10,8 @@ import android.view.MotionEvent;
|
|||||||
import com.droiddeck.launcher.session.SessionState;
|
import com.droiddeck.launcher.session.SessionState;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.concurrent.atomic.AtomicIntegerArray;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A physical controller, republished as a synthetic evdev device the Steam client can see.
|
* A physical controller, republished as a synthetic evdev device the Steam client can see.
|
||||||
@@ -25,11 +27,14 @@ import java.io.File;
|
|||||||
* to the client instead ({@link com.droiddeck.launcher.session.SteamDeckPad}), which has a Quick
|
* to the client instead ({@link com.droiddeck.launcher.session.SteamDeckPad}), which has a Quick
|
||||||
* Access button of its own; an Xbox pad has none, so there the client's menu is reached with the
|
* Access button of its own; an Xbox pad has none, so there the client's menu is reached with the
|
||||||
* Guide-then-A chord the client itself answers.
|
* Guide-then-A chord the client itself answers.
|
||||||
|
*
|
||||||
|
* <p>Each further controller is another player: slots 1 to 3, an Xbox 360 pad each, which in a
|
||||||
|
* Steam session only the client reads (libfakeinput) and hands games through Steam Input.
|
||||||
*/
|
*/
|
||||||
public final class PadBridge {
|
public final class PadBridge {
|
||||||
private static final String TAG = "PadBridge";
|
private static final String TAG = "PadBridge";
|
||||||
/** Slot 0 is the one the session exports; extra slots would each show as another pad. */
|
/** Player slots: the session prepares a ring for each (SessionService). */
|
||||||
private static final int SLOT = 0;
|
public static final int SLOTS = 4;
|
||||||
private static final float DEAD_ZONE = 0.12f;
|
private static final float DEAD_ZONE = 0.12f;
|
||||||
// The client takes A as part of the chord only once it has had Guide held for a while, and a
|
// The client takes A as part of the chord only once it has had Guide held for a while, and a
|
||||||
// client starved of CPU needs longer. Too short, and it acts on A as well, selecting whatever it
|
// client starved of CPU needs longer. Too short, and it acts on A as well, selecting whatever it
|
||||||
@@ -50,8 +55,13 @@ public final class PadBridge {
|
|||||||
chordHandler = new Handler(thread.getLooper());
|
chordHandler = new Handler(thread.getLooper());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private final File fakeInputDir;
|
||||||
private final FakeInputWriter writer;
|
private final FakeInputWriter writer;
|
||||||
private final PadState state = new PadState();
|
private final PadState state = new PadState();
|
||||||
|
/** The input device id holding each slot, or {@link #NO_CONTROLLER}. */
|
||||||
|
private final int[] owners = new int[SLOTS];
|
||||||
|
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
|
||||||
|
private final PadState[] playerStates = new PadState[SLOTS];
|
||||||
private final PadState effectiveState = new PadState();
|
private final PadState effectiveState = new PadState();
|
||||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||||
private boolean open;
|
private boolean open;
|
||||||
@@ -79,29 +89,50 @@ public final class PadBridge {
|
|||||||
/** No physical controller is driving the pad: nothing yet, or the on-screen controls were last. */
|
/** No physical controller is driving the pad: nothing yet, or the on-screen controls were last. */
|
||||||
public static final int NO_CONTROLLER = -1;
|
public static final int NO_CONTROLLER = -1;
|
||||||
/**
|
/**
|
||||||
* The Android input device id of the physical controller that last drove the pad, or
|
* The Android input device id of the physical controller that last drove any slot, or
|
||||||
* {@link #NO_CONTROLLER}. Every pad feeds the one exported slot, so this is how a game's rumble
|
* {@link #NO_CONTROLLER}: where rumble goes when it names no slot of ours (RumbleComponent).
|
||||||
* on that slot finds the motors in the player's hands (RumbleComponent).
|
|
||||||
*/
|
*/
|
||||||
private static volatile int activeControllerId = NO_CONTROLLER;
|
private static volatile int activeControllerId = NO_CONTROLLER;
|
||||||
|
/** Per slot, the controller its rumble belongs to; slot 0's is none while the on-screen controls lead. */
|
||||||
|
private static final AtomicIntegerArray slotControllers = new AtomicIntegerArray(SLOTS);
|
||||||
|
static {
|
||||||
|
for (int slot = 0; slot < SLOTS; slot++) slotControllers.set(slot, NO_CONTROLLER);
|
||||||
|
}
|
||||||
|
|
||||||
public static int activeControllerId() { return activeControllerId; }
|
public static int activeControllerId() { return activeControllerId; }
|
||||||
|
|
||||||
|
/** The controller playing in this ring slot, or the last one used for any other slot. */
|
||||||
|
public static int controllerForSlot(int slot) {
|
||||||
|
return slot >= 0 && slot < SLOTS ? slotControllers.get(slot) : activeControllerId;
|
||||||
|
}
|
||||||
|
|
||||||
public PadBridge(File fakeInputDir) {
|
public PadBridge(File fakeInputDir) {
|
||||||
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
|
this.fakeInputDir = fakeInputDir;
|
||||||
|
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), 0);
|
||||||
|
Arrays.fill(owners, NO_CONTROLLER);
|
||||||
|
for (int slot = 1; slot < SLOTS; slot++) playerStates[slot] = new PadState();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Opens the ring; safe to call more than once. */
|
/** Opens the ring; safe to call more than once. */
|
||||||
public synchronized boolean start() {
|
public synchronized boolean start() {
|
||||||
if (!open) {
|
if (!open) {
|
||||||
open = writer.open();
|
open = writer.open();
|
||||||
Log.i(TAG, "ring slot " + SLOT + (open ? " open" : " NOT open"));
|
Log.i(TAG, "ring slot 0" + (open ? " open" : " NOT open"));
|
||||||
}
|
}
|
||||||
return open;
|
return open;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void stop() {
|
public synchronized void stop() {
|
||||||
activeControllerId = NO_CONTROLLER;
|
activeControllerId = NO_CONTROLLER;
|
||||||
|
for (int slot = 0; slot < SLOTS; slot++) {
|
||||||
|
owners[slot] = NO_CONTROLLER;
|
||||||
|
slotControllers.set(slot, NO_CONTROLLER);
|
||||||
|
if (playerWriters[slot] != null) {
|
||||||
|
playerWriters[slot].destroy();
|
||||||
|
playerWriters[slot] = null;
|
||||||
|
}
|
||||||
|
if (playerStates[slot] != null) playerStates[slot].clear();
|
||||||
|
}
|
||||||
systemGuidePressed = false;
|
systemGuidePressed = false;
|
||||||
systemQamPressed = false;
|
systemQamPressed = false;
|
||||||
qamChordActive = false;
|
qamChordActive = false;
|
||||||
@@ -155,38 +186,40 @@ public final class PadBridge {
|
|||||||
|
|
||||||
/** @return true when the event was a pad button and has been consumed. */
|
/** @return true when the event was a pad button and has been consumed. */
|
||||||
public synchronized boolean onKeyEvent(KeyEvent event) {
|
public synchronized boolean onKeyEvent(KeyEvent event) {
|
||||||
if (!isFromController(event.getDevice())) return false;
|
if (!isFromController(event.getDevice()) || !isPadKey(event.getKeyCode())) return false;
|
||||||
noteDevice(event.getDevice());
|
int slot = slotFor(event.getDevice());
|
||||||
|
PadState pad = stateFor(slot);
|
||||||
|
noteDevice(event.getDevice(), slot);
|
||||||
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
|
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
|
||||||
switch (event.getKeyCode()) {
|
switch (event.getKeyCode()) {
|
||||||
case KeyEvent.KEYCODE_BUTTON_A: state.press(0, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_A: pad.press(0, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_B: state.press(1, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_B: pad.press(1, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_X: state.press(2, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_X: pad.press(2, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_Y: state.press(3, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_Y: pad.press(3, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_L1: state.press(4, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_L1: pad.press(4, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_R1: state.press(5, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_R1: pad.press(5, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_SELECT:
|
case KeyEvent.KEYCODE_BUTTON_SELECT:
|
||||||
case KeyEvent.KEYCODE_BACK: state.press(6, pressed); break;
|
case KeyEvent.KEYCODE_BACK: pad.press(6, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_START:
|
case KeyEvent.KEYCODE_BUTTON_START:
|
||||||
case KeyEvent.KEYCODE_MENU: state.press(7, pressed); break;
|
case KeyEvent.KEYCODE_MENU: pad.press(7, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_THUMBL: state.press(8, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_THUMBR: state.press(9, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.press(9, pressed); break;
|
||||||
// The client's own in-game menu is opened by this one; the interposer publishes it as
|
// The client's own in-game menu is opened by this one; the interposer publishes it as
|
||||||
// BTN_MODE, which SDL reports as the "guide" button.
|
// BTN_MODE, which SDL reports as the "guide" button.
|
||||||
case KeyEvent.KEYCODE_BUTTON_MODE:
|
case KeyEvent.KEYCODE_BUTTON_MODE:
|
||||||
case KeyEvent.KEYCODE_HOME: state.press(PadState.GUIDE, pressed); break;
|
case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_L2: state.leftTrigger = pressed ? 1f : 0f; break;
|
case KeyEvent.KEYCODE_BUTTON_L2: pad.leftTrigger = pressed ? 1f : 0f; break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_R2: state.rightTrigger = pressed ? 1f : 0f; break;
|
case KeyEvent.KEYCODE_BUTTON_R2: pad.rightTrigger = pressed ? 1f : 0f; break;
|
||||||
case KeyEvent.KEYCODE_DPAD_UP: state.up = pressed; break;
|
case KeyEvent.KEYCODE_DPAD_UP: pad.up = pressed; break;
|
||||||
case KeyEvent.KEYCODE_DPAD_RIGHT: state.right = pressed; break;
|
case KeyEvent.KEYCODE_DPAD_RIGHT: pad.right = pressed; break;
|
||||||
case KeyEvent.KEYCODE_DPAD_DOWN: state.down = pressed; break;
|
case KeyEvent.KEYCODE_DPAD_DOWN: pad.down = pressed; break;
|
||||||
case KeyEvent.KEYCODE_DPAD_LEFT: state.left = pressed; break;
|
case KeyEvent.KEYCODE_DPAD_LEFT: pad.left = pressed; break;
|
||||||
default: return false;
|
default: return false;
|
||||||
}
|
}
|
||||||
if (pressed) notePlayerInput();
|
if (pressed) notePlayerInput();
|
||||||
statButtons++;
|
statButtons++;
|
||||||
scheduleStats();
|
scheduleStats();
|
||||||
publish();
|
publish(slot);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,33 +227,35 @@ public final class PadBridge {
|
|||||||
public synchronized boolean onMotionEvent(MotionEvent event) {
|
public synchronized boolean onMotionEvent(MotionEvent event) {
|
||||||
if (!isFromController(event.getDevice())) return false;
|
if (!isFromController(event.getDevice())) return false;
|
||||||
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
|
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
|
||||||
noteDevice(event.getDevice());
|
int slot = slotFor(event.getDevice());
|
||||||
|
PadState pad = stateFor(slot);
|
||||||
|
noteDevice(event.getDevice(), slot);
|
||||||
statAxes++;
|
statAxes++;
|
||||||
scheduleStats();
|
scheduleStats();
|
||||||
state.leftX = axis(event, MotionEvent.AXIS_X);
|
pad.leftX = axis(event, MotionEvent.AXIS_X);
|
||||||
// Android's Y axis grows downwards and evdev's ABS_Y does too, so no flip here: what the
|
// Android's Y axis grows downwards and evdev's ABS_Y does too, so no flip here: what the
|
||||||
// pad reports as "down" is what the client is told.
|
// pad reports as "down" is what the client is told.
|
||||||
state.leftY = axis(event, MotionEvent.AXIS_Y);
|
pad.leftY = axis(event, MotionEvent.AXIS_Y);
|
||||||
state.rightX = axis(event, MotionEvent.AXIS_Z);
|
pad.rightX = axis(event, MotionEvent.AXIS_Z);
|
||||||
state.rightY = axis(event, MotionEvent.AXIS_RZ);
|
pad.rightY = axis(event, MotionEvent.AXIS_RZ);
|
||||||
float lt = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
|
float lt = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
|
||||||
float rt = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
|
float rt = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
|
||||||
// Some pads only report the triggers on BRAKE/GAS.
|
// Some pads only report the triggers on BRAKE/GAS.
|
||||||
if (lt == 0f) lt = event.getAxisValue(MotionEvent.AXIS_BRAKE);
|
if (lt == 0f) lt = event.getAxisValue(MotionEvent.AXIS_BRAKE);
|
||||||
if (rt == 0f) rt = event.getAxisValue(MotionEvent.AXIS_GAS);
|
if (rt == 0f) rt = event.getAxisValue(MotionEvent.AXIS_GAS);
|
||||||
state.leftTrigger = lt;
|
pad.leftTrigger = lt;
|
||||||
state.rightTrigger = rt;
|
pad.rightTrigger = rt;
|
||||||
float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
|
float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
|
||||||
float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
|
float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
|
||||||
state.up = hatY < -0.5f;
|
pad.up = hatY < -0.5f;
|
||||||
state.right = hatX > 0.5f;
|
pad.right = hatX > 0.5f;
|
||||||
state.down = hatY > 0.5f;
|
pad.down = hatY > 0.5f;
|
||||||
state.left = hatX < -0.5f;
|
pad.left = hatX < -0.5f;
|
||||||
if (Math.max(Math.max(Math.abs(state.leftX), Math.abs(state.leftY)), Math.max(Math.abs(state.rightX), Math.abs(state.rightY))) > 0.5f
|
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 || state.up || state.right || state.down || state.left) {
|
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
|
||||||
notePlayerInput();
|
notePlayerInput();
|
||||||
}
|
}
|
||||||
publish();
|
publish(slot);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,6 +266,7 @@ public final class PadBridge {
|
|||||||
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
|
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
|
||||||
mutation.accept(state);
|
mutation.accept(state);
|
||||||
activeControllerId = NO_CONTROLLER;
|
activeControllerId = NO_CONTROLLER;
|
||||||
|
slotControllers.set(0, NO_CONTROLLER);
|
||||||
notePlayerInput();
|
notePlayerInput();
|
||||||
statOnScreen++;
|
statOnScreen++;
|
||||||
scheduleStats();
|
scheduleStats();
|
||||||
@@ -255,6 +291,18 @@ public final class PadBridge {
|
|||||||
public synchronized void releaseAll() {
|
public synchronized void releaseAll() {
|
||||||
state.clear();
|
state.clear();
|
||||||
publish();
|
publish();
|
||||||
|
for (int slot = 1; slot < SLOTS; slot++) {
|
||||||
|
if (playerWriters[slot] == null) continue;
|
||||||
|
playerStates[slot].clear();
|
||||||
|
publish(slot);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A controller went away: its player's buttons are let go, and a further player's pad is unplugged. */
|
||||||
|
public synchronized void onDeviceRemoved(int deviceId) {
|
||||||
|
for (int slot = 0; slot < SLOTS; slot++) {
|
||||||
|
if (owners[slot] == deviceId) free(slot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Opens the client's Quick Access menu: a tap of the Deck's button, or the Guide-then-A chord. */
|
/** Opens the client's Quick Access menu: a tap of the Deck's button, or the Guide-then-A chord. */
|
||||||
@@ -310,16 +358,71 @@ public final class PadBridge {
|
|||||||
publish();
|
publish();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static boolean isPadKey(int keyCode) {
|
||||||
|
switch (keyCode) {
|
||||||
|
case KeyEvent.KEYCODE_BACK:
|
||||||
|
case KeyEvent.KEYCODE_MENU:
|
||||||
|
case KeyEvent.KEYCODE_HOME:
|
||||||
|
case KeyEvent.KEYCODE_DPAD_UP:
|
||||||
|
case KeyEvent.KEYCODE_DPAD_RIGHT:
|
||||||
|
case KeyEvent.KEYCODE_DPAD_DOWN:
|
||||||
|
case KeyEvent.KEYCODE_DPAD_LEFT:
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return KeyEvent.isGamepadButton(keyCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The slot this controller plays in: the one it has, else the first free one, else player 1's. */
|
||||||
|
private int slotFor(InputDevice device) {
|
||||||
|
int id = device.getId();
|
||||||
|
if (owners[0] == id) return 0;
|
||||||
|
for (int slot = 1; slot < SLOTS; slot++) {
|
||||||
|
if (owners[slot] == id) return slot;
|
||||||
|
}
|
||||||
|
for (int slot = 0; slot < SLOTS; slot++) {
|
||||||
|
if (owners[slot] != NO_CONTROLLER && InputDevice.getDevice(owners[slot]) == null) free(slot);
|
||||||
|
}
|
||||||
|
for (int slot = 0; slot < SLOTS; slot++) {
|
||||||
|
if (owners[slot] != NO_CONTROLLER) continue;
|
||||||
|
owners[slot] = id;
|
||||||
|
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") is player " + (slot + 1));
|
||||||
|
return slot;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private PadState stateFor(int slot) {
|
||||||
|
return slot == 0 ? state : playerStates[slot];
|
||||||
|
}
|
||||||
|
|
||||||
|
private void free(int slot) {
|
||||||
|
Log.i(TAG, "player " + (slot + 1) + " (id " + owners[slot] + ") left");
|
||||||
|
owners[slot] = NO_CONTROLLER;
|
||||||
|
slotControllers.set(slot, NO_CONTROLLER);
|
||||||
|
if (slot == 0) {
|
||||||
|
state.clear();
|
||||||
|
publish();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
playerStates[slot].clear();
|
||||||
|
if (playerWriters[slot] != null) {
|
||||||
|
playerWriters[slot].destroy();
|
||||||
|
playerWriters[slot] = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Per event, so the common case - the same pad as last time - is a single compare. */
|
/** Per event, so the common case - the same pad as last time - is a single compare. */
|
||||||
private void noteDevice(InputDevice device) {
|
private void noteDevice(InputDevice device, int slot) {
|
||||||
activeControllerId = device.getId();
|
activeControllerId = device.getId();
|
||||||
|
slotControllers.set(slot, device.getId());
|
||||||
if (device.getId() == lastDeviceId) return;
|
if (device.getId() == lastDeviceId) return;
|
||||||
lastDeviceId = device.getId();
|
lastDeviceId = device.getId();
|
||||||
statDevice = device.getName();
|
statDevice = device.getName();
|
||||||
if (seenDevices.add(device.getId())) {
|
if (seenDevices.add(device.getId())) {
|
||||||
Log.i(TAG, String.format(java.util.Locale.ROOT, "first input from \"%s\" (%04x:%04x, id %d, sources 0x%x); ring %s, deck pad %b",
|
Log.i(TAG, String.format(java.util.Locale.ROOT, "first input from \"%s\" (%04x:%04x, id %d, sources 0x%x); slot %d, ring %s, deck pad %b",
|
||||||
device.getName(), device.getVendorId(), device.getProductId(), device.getId(), device.getSources(),
|
device.getName(), device.getVendorId(), device.getProductId(), device.getId(), device.getSources(),
|
||||||
open ? "open" : "not open yet", SessionState.getDeckPad()));
|
slot, open ? "open" : "not open yet", SessionState.getDeckPad()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -339,6 +442,23 @@ public final class PadBridge {
|
|||||||
statButtons = statAxes = statOnScreen = statDropped = 0;
|
statButtons = statAxes = statOnScreen = statDropped = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void publish(int slot) {
|
||||||
|
if (slot == 0) {
|
||||||
|
publish();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
FakeInputWriter player = playerWriters[slot];
|
||||||
|
if (player == null) {
|
||||||
|
player = new FakeInputWriter(fakeInputDir.getAbsolutePath(), slot);
|
||||||
|
if (!player.open()) {
|
||||||
|
statDropped++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
playerWriters[slot] = player;
|
||||||
|
}
|
||||||
|
player.writePad(playerStates[slot]);
|
||||||
|
}
|
||||||
|
|
||||||
private void publish() {
|
private void publish() {
|
||||||
if (!open && !start()) {
|
if (!open && !start()) {
|
||||||
statDropped++;
|
statDropped++;
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
|
|||||||
Handler(worker.looper).post {
|
Handler(worker.looper).post {
|
||||||
gyro.fill(0)
|
gyro.fill(0)
|
||||||
FakeInputWriter.writeMotion(SLOT, accel, gyro)
|
FakeInputWriter.writeMotion(SLOT, accel, gyro)
|
||||||
|
SteamTouchDevice.current?.setMotion(accel, gyro)
|
||||||
}
|
}
|
||||||
worker.quitSafely()
|
worker.quitSafely()
|
||||||
}
|
}
|
||||||
@@ -85,6 +86,7 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
|
|||||||
target[1] = counts(-z * scale)
|
target[1] = counts(-z * scale)
|
||||||
target[2] = counts(y * scale)
|
target[2] = counts(y * scale)
|
||||||
FakeInputWriter.writeMotion(SLOT, accel, gyro)
|
FakeInputWriter.writeMotion(SLOT, accel, gyro)
|
||||||
|
SteamTouchDevice.current?.setMotion(accel, gyro)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
|
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
|
||||||
|
|||||||
@@ -2,14 +2,16 @@ package com.droiddeck.launcher.input
|
|||||||
|
|
||||||
import android.hardware.display.DisplayManager
|
import android.hardware.display.DisplayManager
|
||||||
import android.view.Display
|
import android.view.Display
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
|
||||||
/** The control surface shown on a secondary Android display during a Linux session. */
|
/** The control surface shown on a secondary Android display during a Linux session. */
|
||||||
enum class SecondScreenMode(val id: String, val label: String) {
|
enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
|
||||||
NONE("none", "None"),
|
NONE("none", R.string.second_mode_none),
|
||||||
KEYBOARD_TRACKPAD("keyboard-trackpad", "Keyboard + trackpad"),
|
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
|
||||||
TERMINAL("terminal", "Terminal"),
|
TERMINAL("terminal", R.string.second_mode_terminal),
|
||||||
/** The Steam Deck controller's back grips and trackpads; offered while the pad is one. */
|
/** The Steam Deck controller's back grips and trackpads; offered while the pad is one. */
|
||||||
DECK_CONTROLS("deck-controls", "Deck grips + trackpads"),
|
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
|
||||||
}
|
}
|
||||||
|
|
||||||
data class SecondScreenDisplay(val id: Int, val label: String)
|
data class SecondScreenDisplay(val id: Int, val label: String)
|
||||||
|
|||||||
@@ -0,0 +1,285 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.util.LruCache
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What each touch control is bound to, and the icon it shows - Steam's, as its configurator keeps
|
||||||
|
* them.
|
||||||
|
*
|
||||||
|
* A Steam Input binding is one string: `<action>, <label>, <icon>, <#foreground #background>`, e.g.
|
||||||
|
* `xinput_button A, Jump, ghost_045_move_0400.png, #232323 #E4E4E4`. The icon is a file name looked
|
||||||
|
* up as Steam does (steamui.so): the game's own `TouchMenuIcons` folder, then the binding icon
|
||||||
|
* library `tenfoot/resource/images/library/controller/binding_icons`. Steam draws it filled with
|
||||||
|
* the foreground colour through its own alpha (mask-image) on a button of the background colour.
|
||||||
|
* Steam Link is sent these per control by the client it streams from; here they are read from the
|
||||||
|
* game's touch config, and editing one writes the binding string back, as the configurator does.
|
||||||
|
*/
|
||||||
|
object SteamTouchBindings {
|
||||||
|
|
||||||
|
/** Steam's binding icon colours (the configurator's palette, steamui sp.js), and its defaults. */
|
||||||
|
val PALETTE = listOf(
|
||||||
|
"#FFFFFF", "#E4E4E4", "#AAAAAA", "#787878", "#434343", "#222222", "#0000AD", "#0045AD", "#0074AD",
|
||||||
|
"#00ADAD", "#33AD69", "#00AD3D", "#00AD00", "#48B119", "#74AD00", "#96AD00", "#ADA200", "#AD5D00",
|
||||||
|
"#AD3A00", "#AD0000", "#AD0051", "#AD007F", "#AD00AD", "#6800AD", "#4800AD",
|
||||||
|
)
|
||||||
|
const val DEFAULT_FOREGROUND = "#232323"
|
||||||
|
const val DEFAULT_BACKGROUND = "#E4E4E4"
|
||||||
|
|
||||||
|
/** A parsed binding string. Empty strings for absent fields. */
|
||||||
|
data class Binding(val action: String, val label: String, val icon: String, val foreground: String, val background: String) {
|
||||||
|
fun compose(): String =
|
||||||
|
if (icon.isEmpty() && foreground.isEmpty() && background.isEmpty()) "$action, $label, "
|
||||||
|
else "$action, $label, $icon, ${listOf(foreground, background).filter { it.isNotEmpty() }.joinToString(" ")}"
|
||||||
|
|
||||||
|
val hasIcon get() = icon.isNotEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parse(binding: String): Binding {
|
||||||
|
val parts = binding.split(',').map { it.trim() }
|
||||||
|
val colors = parts.getOrNull(3).orEmpty().split(' ').filter { it.startsWith("#") }
|
||||||
|
return Binding(parts.getOrNull(0).orEmpty(), parts.getOrNull(1).orEmpty(), parts.getOrNull(2).orEmpty(),
|
||||||
|
colors.getOrNull(0).orEmpty(), colors.getOrNull(1).orEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a control's binding lives: its input in the group the preset puts on its source. */
|
||||||
|
data class Ref(val groupId: String, val input: String)
|
||||||
|
|
||||||
|
/** The source and input names a control reads (D-pad: its four directions). */
|
||||||
|
private fun inputsOf(type: Int): List<Pair<String, String>> = when (type) {
|
||||||
|
SteamTouchConfig.A -> listOf("button_diamond" to "button_a")
|
||||||
|
SteamTouchConfig.B -> listOf("button_diamond" to "button_b")
|
||||||
|
SteamTouchConfig.X -> listOf("button_diamond" to "button_x")
|
||||||
|
SteamTouchConfig.Y -> listOf("button_diamond" to "button_y")
|
||||||
|
SteamTouchConfig.SELECT -> listOf("switch" to "button_menu")
|
||||||
|
SteamTouchConfig.START -> listOf("switch" to "button_escape")
|
||||||
|
SteamTouchConfig.BUMPER_LEFT -> listOf("switch" to "left_bumper")
|
||||||
|
SteamTouchConfig.BUMPER_RIGHT -> listOf("switch" to "right_bumper")
|
||||||
|
SteamTouchConfig.TRIGGER_LEFT -> listOf("left_trigger" to "click")
|
||||||
|
SteamTouchConfig.TRIGGER_RIGHT -> listOf("right_trigger" to "click")
|
||||||
|
SteamTouchConfig.JOYSTICK_LEFT_BUTTON -> listOf("joystick" to "click")
|
||||||
|
SteamTouchConfig.JOYSTICK_RIGHT_BUTTON -> listOf("right_joystick" to "click")
|
||||||
|
SteamTouchConfig.MACRO_1_FINGER -> listOf("switch" to "button_macro_1finger")
|
||||||
|
SteamTouchConfig.MACRO_2_FINGER -> listOf("switch" to "button_macro_2finger")
|
||||||
|
SteamTouchConfig.DPAD -> DPAD_INPUTS.map { "dpad" to it }
|
||||||
|
in SteamTouchConfig.MACRO_0..SteamTouchConfig.MACRO_0 + 7 -> listOf("switch" to "button_macro${type - SteamTouchConfig.MACRO_0}")
|
||||||
|
else -> emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** D-pad directions, in the order [refsFor] returns them: up, down, left, right. */
|
||||||
|
val DPAD_INPUTS = listOf("dpad_north", "dpad_south", "dpad_west", "dpad_east")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where control [type]'s bindings are for preset [preset] (the action set less one) and its
|
||||||
|
* active [layers]: a layer's group wins over the base's for the same source.
|
||||||
|
*/
|
||||||
|
fun refsFor(mappings: KeyValues.Node, type: Int, preset: Int, layers: List<Int> = emptyList()): List<Ref?> {
|
||||||
|
val presets = mappings.children("preset").associateBy { it.string("id")?.toIntOrNull() ?: -1 }
|
||||||
|
val stack = layers.reversed().mapNotNull { presets[it - 1] } + listOfNotNull(presets[preset] ?: presets.values.firstOrNull())
|
||||||
|
return inputsOf(type).map { (source, input) ->
|
||||||
|
stack.firstNotNullOfOrNull { p -> groupFor(p, source)?.let { Ref(it, input) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun groupFor(preset: KeyValues.Node, source: String): String? =
|
||||||
|
preset.child("group_source_bindings")?.entries?.firstOrNull { (_, v) ->
|
||||||
|
val parts = (v as? String)?.split(' ') ?: return@firstOrNull false
|
||||||
|
parts.getOrNull(0) == source && parts.getOrNull(1) == "active" && !parts.contains("modeshift")
|
||||||
|
}?.first
|
||||||
|
|
||||||
|
/** The binding at [ref]: its first activator's first binding (Full_Press when there is one). */
|
||||||
|
fun bindingAt(mappings: KeyValues.Node, ref: Ref): Binding? {
|
||||||
|
val group = mappings.children("group").firstOrNull { it.string("id") == ref.groupId } ?: return null
|
||||||
|
val activators = group.child("inputs")?.child(ref.input)?.child("activators") ?: return null
|
||||||
|
val activator = activators.child("Full_Press") ?: activators.entries.firstNotNullOfOrNull { it.second as? KeyValues.Node }
|
||||||
|
return activator?.child("bindings")?.string("binding")?.let(::parse)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A short glyph for a binding with no icon or label: what it presses. */
|
||||||
|
fun glyph(binding: Binding?): String? {
|
||||||
|
val words = binding?.action?.split(' ') ?: return null
|
||||||
|
val arg = words.getOrNull(1)?.uppercase() ?: return null
|
||||||
|
return when (words[0]) {
|
||||||
|
"xinput_button" -> XINPUT_GLYPHS[arg] ?: arg
|
||||||
|
"key_press" -> KEY_GLYPHS[arg] ?: arg.take(4)
|
||||||
|
"mouse_button" -> when (arg) { "LEFT" -> "LMB"; "RIGHT" -> "RMB"; "MIDDLE" -> "MMB"; else -> "M" + arg.take(2) }
|
||||||
|
"mouse_wheel" -> if (arg.contains("UP")) "▲" else "▼"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val XINPUT_GLYPHS = mapOf(
|
||||||
|
"SHOULDER_LEFT" to "LB", "SHOULDER_RIGHT" to "RB", "TRIGGER_LEFT" to "LT", "TRIGGER_RIGHT" to "RT",
|
||||||
|
"JOYSTICK_LEFT" to "L3", "JOYSTICK_RIGHT" to "R3", "START" to "☰", "SELECT" to "⧉", "BACK" to "⧉",
|
||||||
|
"DPAD_UP" to "▲", "DPAD_DOWN" to "▼", "DPAD_LEFT" to "◀", "DPAD_RIGHT" to "▶",
|
||||||
|
)
|
||||||
|
private val KEY_GLYPHS = mapOf(
|
||||||
|
"RETURN" to "⏎", "SPACE" to "␣", "ESCAPE" to "Esc", "TAB" to "Tab", "BACKSPACE" to "⌫",
|
||||||
|
"LEFT_SHIFT" to "⇧", "RIGHT_SHIFT" to "⇧", "LEFT_CONTROL" to "Ctrl", "RIGHT_CONTROL" to "Ctrl",
|
||||||
|
"LEFT_ALT" to "Alt", "RIGHT_ALT" to "Alt", "UP_ARROW" to "↑", "DOWN_ARROW" to "↓",
|
||||||
|
"LEFT_ARROW" to "←", "RIGHT_ARROW" to "→",
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---- Writing a binding back ----
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rewrites every binding of [ref]'s input in config [text] (VDF) with [change], keeping the rest
|
||||||
|
* of the file byte for byte. Returns the new text, or null when the input is not there.
|
||||||
|
*/
|
||||||
|
fun rewrite(text: String, ref: Ref, change: (Binding) -> Binding): String? {
|
||||||
|
val tokens = Vdf.tokens(text)
|
||||||
|
val group = Vdf.blocks(tokens, 0, tokens.size, "group").firstOrNull { (s, e) ->
|
||||||
|
Vdf.value(tokens, s, e, "id") == ref.groupId
|
||||||
|
} ?: return null
|
||||||
|
val inputs = Vdf.blocks(tokens, group.first, group.second, "inputs").firstOrNull() ?: return null
|
||||||
|
val input = Vdf.blocks(tokens, inputs.first, inputs.second, ref.input).firstOrNull() ?: return null
|
||||||
|
val targets = (input.first until input.second).filter { i ->
|
||||||
|
tokens[i].text.equals("binding", true) && tokens[i].quoted && i + 1 < input.second && tokens[i + 1].quoted
|
||||||
|
}.map { tokens[it + 1] }
|
||||||
|
if (targets.isEmpty()) return null
|
||||||
|
val out = StringBuilder(text)
|
||||||
|
for (t in targets.sortedByDescending { it.start }) out.replace(t.start, t.end, change(parse(t.text)).compose())
|
||||||
|
return out.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A VDF tokenizer that keeps where each token sits, for edits that leave the rest untouched. */
|
||||||
|
private object Vdf {
|
||||||
|
class Token(val text: String, val quoted: Boolean, val start: Int, val end: Int)
|
||||||
|
|
||||||
|
fun tokens(text: String): List<Token> {
|
||||||
|
val out = mutableListOf<Token>()
|
||||||
|
var i = 0
|
||||||
|
while (i < text.length) {
|
||||||
|
val c = text[i]
|
||||||
|
when {
|
||||||
|
c.isWhitespace() -> i++
|
||||||
|
c == '/' && i + 1 < text.length && text[i + 1] == '/' -> while (i < text.length && text[i] != '\n') i++
|
||||||
|
c == '{' || c == '}' -> { out += Token(c.toString(), false, i, i + 1); i++ }
|
||||||
|
c == '"' -> {
|
||||||
|
val start = i + 1
|
||||||
|
i++
|
||||||
|
while (i < text.length && text[i] != '"') { if (text[i] == '\\') i++; i++ }
|
||||||
|
out += Token(text.substring(start, minOf(i, text.length)), true, start, minOf(i, text.length))
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
val start = i
|
||||||
|
while (i < text.length && !text[i].isWhitespace() && text[i] != '{' && text[i] != '}' && text[i] != '"') i++
|
||||||
|
out += Token(text.substring(start, i), false, start, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The bodies (token index ranges inside the braces) of direct children named [key] of the
|
||||||
|
* block spanning [from, to). */
|
||||||
|
fun blocks(tokens: List<Token>, from: Int, to: Int, key: String): List<Pair<Int, Int>> {
|
||||||
|
val found = mutableListOf<Pair<Int, Int>>()
|
||||||
|
var i = from
|
||||||
|
var depth = 0
|
||||||
|
while (i < to) {
|
||||||
|
val t = tokens[i]
|
||||||
|
if (t.text == "{" && !t.quoted) depth++
|
||||||
|
else if (t.text == "}" && !t.quoted) depth--
|
||||||
|
else if (depth == 0 && t.quoted && t.text.equals(key, true) && i + 1 < to && tokens[i + 1].text == "{" && !tokens[i + 1].quoted) {
|
||||||
|
val open = i + 1
|
||||||
|
var d = 0
|
||||||
|
var j = open
|
||||||
|
while (j < to) {
|
||||||
|
if (tokens[j].text == "{" && !tokens[j].quoted) d++
|
||||||
|
if (tokens[j].text == "}" && !tokens[j].quoted) { d--; if (d == 0) break }
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
found += (open + 1) to j
|
||||||
|
i = j + 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
// The whole file is one top-level block ("controller_mappings"): look inside it too.
|
||||||
|
if (found.isEmpty() && from == 0) {
|
||||||
|
val top = tokens.indexOfFirst { it.text == "{" && !it.quoted }
|
||||||
|
if (top > 0) {
|
||||||
|
var d = 0
|
||||||
|
var j = top
|
||||||
|
while (j < to) {
|
||||||
|
if (tokens[j].text == "{" && !tokens[j].quoted) d++
|
||||||
|
if (tokens[j].text == "}" && !tokens[j].quoted) { d--; if (d == 0) break }
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
return blocks(tokens, top + 1, j, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A direct key-value of the block spanning [from, to). */
|
||||||
|
fun value(tokens: List<Token>, from: Int, to: Int, key: String): String? {
|
||||||
|
var depth = 0
|
||||||
|
var i = from
|
||||||
|
while (i < to) {
|
||||||
|
val t = tokens[i]
|
||||||
|
if (t.text == "{" && !t.quoted) depth++
|
||||||
|
else if (t.text == "}" && !t.quoted) depth--
|
||||||
|
else if (depth == 0 && t.quoted && t.text.equals(key, true) && i + 1 < to && tokens[i + 1].quoted) return tokens[i + 1].text
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Icons ----
|
||||||
|
|
||||||
|
private val cache = object : LruCache<String, Bitmap>(24 * 1024 * 1024) {
|
||||||
|
override fun sizeOf(key: String, value: Bitmap) = value.byteCount
|
||||||
|
}
|
||||||
|
private val missing = HashSet<String>()
|
||||||
|
|
||||||
|
fun libraryDir(context: Context) = File(SteamTouchConfig.steamRoot(context), "tenfoot/resource/images/library/controller/binding_icons")
|
||||||
|
|
||||||
|
/** The game's own icons folder (`TouchMenuIcons` in its install directory), when it has one. */
|
||||||
|
fun gameIconsDir(context: Context, appId: Int): File? = try {
|
||||||
|
val manifest = File(SteamTouchConfig.steamRoot(context), "steamapps/appmanifest_$appId.acf")
|
||||||
|
val installDir = KeyValues.parse(manifest.readText()).let { it.child("AppState") ?: it }.string("installdir")
|
||||||
|
installDir?.let { File(SteamTouchConfig.steamRoot(context), "steamapps/common/$it/TouchMenuIcons") }?.takeIf { it.isDirectory }
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun iconFile(context: Context, appId: Int, name: String): File? {
|
||||||
|
if (name.isEmpty() || name.contains('/')) return null
|
||||||
|
gameIconsDir(context, appId)?.let { File(it, name) }?.takeIf { it.isFile }?.let { return it }
|
||||||
|
File(libraryDir(context), name).takeIf { it.isFile }?.let { return it }
|
||||||
|
return File(SteamTouchConfig.steamRoot(context), "steamui/images/controller/$name").takeIf { it.isFile }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An icon, decoded at about [size] px. Blocking (reads a file); cached. */
|
||||||
|
fun icon(context: Context, appId: Int, name: String, size: Int = 128): Bitmap? {
|
||||||
|
val key = "$appId/$name/$size"
|
||||||
|
cache.get(key)?.let { return it }
|
||||||
|
if (key in missing) return null
|
||||||
|
val file = iconFile(context, appId, name)
|
||||||
|
val bitmap = file?.let {
|
||||||
|
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||||
|
BitmapFactory.decodeFile(it.path, bounds)
|
||||||
|
var sample = 1
|
||||||
|
while (bounds.outWidth / (sample * 2) >= size) sample *= 2
|
||||||
|
BitmapFactory.decodeFile(it.path, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||||
|
}
|
||||||
|
if (bitmap == null) missing += key else cache.put(key, bitmap)
|
||||||
|
return bitmap
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cachedIcon(appId: Int, name: String, size: Int = 128): Bitmap? = cache.get("$appId/$name/$size")
|
||||||
|
|
||||||
|
/** Icon names for the picker: the game's own first, then Steam's library by category. */
|
||||||
|
fun iconNames(context: Context, appId: Int): List<String> {
|
||||||
|
val own = gameIconsDir(context, appId)?.list()?.filter { it.endsWith(".png", true) }?.sorted().orEmpty()
|
||||||
|
val library = libraryDir(context).list()?.filter { it.endsWith(".png", true) && it != "special_blank.png" }?.sorted().orEmpty()
|
||||||
|
return own + library.filter { it !in own }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,654 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.io.RandomAccessFile
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Steam's touch configs, read and written where Steam keeps them.
|
||||||
|
*
|
||||||
|
* A touch config is a Steam Input config (`controller_mobile_touch`) like any other - bindings per
|
||||||
|
* action set, synced to the account, shared as community configs - with one extra key,
|
||||||
|
* `touch_layout`: where each on-screen control sits, per action set, as a hex-encoded
|
||||||
|
* `CVirtualControllerLayouts` protobuf (steammessages_virtualcontroller.proto). Steam Link is
|
||||||
|
* handed both by the client it streams from; here the client tells the device only the app and
|
||||||
|
* action set it is on (SteamTouchDevice), so the config is found on disk: the file the client's
|
||||||
|
* console log says it loaded for the touch controller, else the app's entry in
|
||||||
|
* `configset_controller_mobile_touch.vdf`. With no layout in it, controls go where Steam Link puts
|
||||||
|
* them by default. Saving a layout writes `touch_layout` into the app's autosave config, as the
|
||||||
|
* client does when Steam Link saves one; Steam Cloud picks that file up like any autosave.
|
||||||
|
* (docs/development/steam-touch-controller.md.)
|
||||||
|
*/
|
||||||
|
object SteamTouchConfig {
|
||||||
|
private const val TAG = "SteamTouch"
|
||||||
|
|
||||||
|
// EControllerElementType.
|
||||||
|
const val THUMB = 0
|
||||||
|
const val STEAM = 1
|
||||||
|
const val JOYSTICK_LEFT = 2
|
||||||
|
const val JOYSTICK_LEFT_BUTTON = 3
|
||||||
|
const val JOYSTICK_RIGHT = 4
|
||||||
|
const val JOYSTICK_RIGHT_BUTTON = 5
|
||||||
|
const val DPAD = 6
|
||||||
|
const val A = 7
|
||||||
|
const val B = 8
|
||||||
|
const val X = 9
|
||||||
|
const val Y = 10
|
||||||
|
const val SELECT = 11
|
||||||
|
const val START = 12
|
||||||
|
const val TRIGGER_LEFT = 13
|
||||||
|
const val TRIGGER_RIGHT = 14
|
||||||
|
const val BUMPER_LEFT = 15
|
||||||
|
const val BUMPER_RIGHT = 16
|
||||||
|
const val MACRO_0 = 17 // 17..24 = macros 0-7
|
||||||
|
const val TRACKPAD_CENTER = 25
|
||||||
|
const val TRACKPAD_LEFT = 26
|
||||||
|
const val TRACKPAD_RIGHT = 27
|
||||||
|
const val KEYBOARD = 28
|
||||||
|
const val MACRO_1_FINGER = 30
|
||||||
|
const val MACRO_2_FINGER = 31
|
||||||
|
const val MAGNIFYING_GLASS = 29
|
||||||
|
const val PASTE = 34
|
||||||
|
|
||||||
|
/** Controls a layout may place though no binding asks for them (Steam Link's tray). */
|
||||||
|
val OPTIONAL = setOf(PASTE)
|
||||||
|
|
||||||
|
/** A control's place: centre as a fraction of the screen, and its scale. */
|
||||||
|
data class Element(val type: Int, val visible: Boolean, val x: Float, val y: Float, val xScale: Float = 1f, val yScale: Float = 1f)
|
||||||
|
|
||||||
|
data class Layout(val actionSet: Int, val elements: List<Element>, val color: FloatArray?, val version: Int?)
|
||||||
|
|
||||||
|
/** A decoded `touch_layout`; [rest] is every other top-level field, written back untouched. */
|
||||||
|
class Layouts(val layouts: List<Layout>, val rest: ByteArray) {
|
||||||
|
fun forActionSet(id: Int): Layout? = layouts.firstOrNull { it.actionSet == id }
|
||||||
|
|
||||||
|
/** The per-game options Steam Link keeps beside the layouts (CVirtualControllerLayouts
|
||||||
|
* fields 2-4): input mode, mouse mode, trackpad sensitivity. */
|
||||||
|
val options: Options get() = Options.decode(rest)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** EInputMode: 1 mouse, 2 controller, 3 both. EMouseMode: 2 absolute cursor (direct touch),
|
||||||
|
* 3 touch, 4 relative (trackpad); 0 = not set. */
|
||||||
|
data class Options(val inputMode: Int = INPUT_CONTROLLER, val mouseMode: Int = 0, val trackpadSensitivity: Float = 1f) {
|
||||||
|
/** [rest] with these options in place of its own fields 2-4, the rest kept as it was. */
|
||||||
|
fun encodeInto(rest: ByteArray): ByteArray {
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
val p = Proto(rest)
|
||||||
|
while (p.more()) {
|
||||||
|
val start = p.pos
|
||||||
|
val (field, wire) = p.key()
|
||||||
|
p.skip(wire)
|
||||||
|
if (field !in 2..4) out.write(rest, start, p.pos - start)
|
||||||
|
}
|
||||||
|
tag(out, 2, 0); varint(out, inputMode.toLong())
|
||||||
|
if (mouseMode != 0) { tag(out, 3, 0); varint(out, mouseMode.toLong()) }
|
||||||
|
tag(out, 4, 5); fixed(out, trackpadSensitivity)
|
||||||
|
return out.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun decode(rest: ByteArray): Options {
|
||||||
|
var input = INPUT_CONTROLLER
|
||||||
|
var mouse = 0
|
||||||
|
var sensitivity = 1f
|
||||||
|
val p = Proto(rest)
|
||||||
|
while (p.more()) {
|
||||||
|
val (field, wire) = p.key()
|
||||||
|
when {
|
||||||
|
field == 2 && wire == 0 -> input = p.varint().toInt()
|
||||||
|
field == 3 && wire == 0 -> mouse = p.varint().toInt()
|
||||||
|
field == 4 && wire == 5 -> sensitivity = p.float()
|
||||||
|
else -> p.skip(wire)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Options(input, mouse, sensitivity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const val INPUT_MOUSE = 1
|
||||||
|
const val INPUT_CONTROLLER = 2
|
||||||
|
const val INPUT_BOTH = 3
|
||||||
|
const val MOUSE_ABSOLUTE = 2
|
||||||
|
const val MOUSE_TOUCH = 3
|
||||||
|
const val MOUSE_RELATIVE = 4
|
||||||
|
|
||||||
|
/** The config's action sets in preset order: id as the device is told (preset id + 1) and title. */
|
||||||
|
fun actionSets(config: Config): List<Pair<Int, String>> {
|
||||||
|
val mappings = config.mappings ?: return listOf(1 to "Default")
|
||||||
|
val titles = mappings.child("actions")?.entries?.mapNotNull { (key, v) ->
|
||||||
|
(v as? KeyValues.Node)?.let { key to (it.string("title") ?: key) }
|
||||||
|
}?.toMap().orEmpty()
|
||||||
|
val sets = mappings.children("preset").mapNotNull { preset ->
|
||||||
|
val id = preset.string("id")?.toIntOrNull() ?: return@mapNotNull null
|
||||||
|
val name = preset.string("name") ?: ""
|
||||||
|
(id + 1) to (titles[name]?.takeUnless { it.startsWith("#") } ?: name.ifEmpty { "Set ${id + 1}" })
|
||||||
|
}.sortedBy { it.first }
|
||||||
|
return sets.ifEmpty { listOf(1 to "Default") }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A config as the overlay needs it. */
|
||||||
|
class Config(
|
||||||
|
val file: File?,
|
||||||
|
val text: String?,
|
||||||
|
val layouts: Layouts?,
|
||||||
|
/** Bound controls per preset (action set id - 1). */
|
||||||
|
val available: Map<Int, Set<Int>>,
|
||||||
|
/** The parsed config, for its bindings (SteamTouchBindings). */
|
||||||
|
val mappings: KeyValues.Node? = null,
|
||||||
|
) {
|
||||||
|
/** The config's own title, as Steam Link's tray shows it ("Default", "Gamepad"…). */
|
||||||
|
val title: String? get() = mappings?.string("title")?.let { t ->
|
||||||
|
if (t.startsWith("#")) mappings.child("localization")?.child("english")?.string("title") ?: "Default" else t
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The controls to show for [actionSet] (as the device is told it) and [layers]. */
|
||||||
|
fun availableFor(actionSet: Int, layers: List<Int>): Set<Int> {
|
||||||
|
val base = available[presetOf(actionSet)] ?: available.values.firstOrNull() ?: DEFAULT_SET
|
||||||
|
return layers.fold(base) { set, layer -> set + (available[presetOf(layer)] ?: emptySet()) } + ALWAYS
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Big Picture's own config uses Steam's basic UI bindings: the default set. */
|
||||||
|
private val DEFAULT_SET = setOf(DPAD, A, B, X, Y, SELECT, START)
|
||||||
|
private val ALWAYS = setOf(STEAM, THUMB, KEYBOARD)
|
||||||
|
|
||||||
|
/** The layout entry for the action set the device was told about (the client counts from 1,
|
||||||
|
* 0 for an app with none). */
|
||||||
|
fun layoutIdOf(actionSet: Int) = if (actionSet <= 0) 1 else actionSet
|
||||||
|
private fun presetOf(actionSet: Int) = layoutIdOf(actionSet) - 1
|
||||||
|
|
||||||
|
// ---- Where Steam keeps them ----
|
||||||
|
|
||||||
|
/** A game's name from its app manifest, when it is installed. */
|
||||||
|
fun gameName(context: Context, appId: Int): String? = try {
|
||||||
|
val kv = KeyValues.parse(File(steamRoot(context), "steamapps/appmanifest_$appId.acf").readText())
|
||||||
|
(kv.child("AppState") ?: kv).string("name")
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun steamRoot(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||||
|
|
||||||
|
fun configDir(context: Context): File? {
|
||||||
|
val base = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
|
||||||
|
val account = accountId(context)
|
||||||
|
if (account != null) File(base, "$account/config").takeIf { it.isDirectory }?.let { return it }
|
||||||
|
return base.listFiles()?.filter { it.name.all(Char::isDigit) && File(it, "config").isDirectory }
|
||||||
|
?.maxByOrNull { it.lastModified() }?.let { File(it, "config") }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The signed-in account (loginusers.vdf's MostRecent) as a 32-bit account id. */
|
||||||
|
private fun accountId(context: Context): Long? = try {
|
||||||
|
val users = KeyValues.parse(File(steamRoot(context), "config/loginusers.vdf").readText())
|
||||||
|
val node = users.child("users")
|
||||||
|
val entries = node?.entries?.mapNotNull { (k, v) -> (v as? KeyValues.Node)?.let { k to it } }.orEmpty()
|
||||||
|
val chosen = entries.firstOrNull { it.second.string("MostRecent") == "1" } ?: entries.firstOrNull()
|
||||||
|
chosen?.first?.toLongOrNull()?.minus(76561197960265728L)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The config the client has for app [appId] on the touch controller. Blocking: reads files. */
|
||||||
|
fun load(context: Context, appId: Int): Config {
|
||||||
|
val dir = configDir(context)
|
||||||
|
// The app's own saved config is what the client loads when there is one (its configset
|
||||||
|
// entry); otherwise what it logged loading - a template, an official or a workshop config.
|
||||||
|
val file = dir?.let { autosaveConfig(it, appId) }
|
||||||
|
?: loggedConfig(context, appId)?.takeIf { isTouchConfig(it) }
|
||||||
|
?: dir?.let { configsetConfig(context, it, appId) }
|
||||||
|
if (file == null) {
|
||||||
|
Log.i(TAG, "steam touch: app $appId has no touch config on disk; default layout")
|
||||||
|
return Config(null, null, null, emptyMap())
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
val text = file.readText()
|
||||||
|
val kv = KeyValues.parse(text.removePrefix(""))
|
||||||
|
val mappings = kv.child("controller_mappings") ?: kv
|
||||||
|
val layouts = mappings.string("touch_layout")?.let { hex -> decodeLayouts(hexToBytes(hex)) }
|
||||||
|
Log.i(TAG, "steam touch: app $appId uses ${file.path} (${layouts?.layouts?.size ?: 0} layouts)")
|
||||||
|
Config(file, text, layouts, availability(mappings), mappings)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "steam touch: ${file.path} unreadable: $e")
|
||||||
|
Config(file, null, null, emptyMap())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isTouchConfig(file: File) = file.isFile &&
|
||||||
|
file.bufferedReader().use { r -> generateSequence { r.readLine() }.take(40).any { it.contains("controller_mobile_touch") } }
|
||||||
|
|
||||||
|
/** From the client's console log: the last config it loaded for [appId] on the touch controller
|
||||||
|
* (`Loaded Config for ... App ID <n>, Controller <i>: <path>`, where controller i reported
|
||||||
|
* type 43). Guest paths come back as the app's own. */
|
||||||
|
private fun loggedConfig(context: Context, appId: Int): File? = try {
|
||||||
|
val log = File(steamRoot(context), "logs/console_log.txt")
|
||||||
|
val tail = RandomAccessFile(log, "r").use { raf ->
|
||||||
|
val start = maxOf(0L, raf.length() - 2_000_000L)
|
||||||
|
raf.seek(start)
|
||||||
|
val bytes = ByteArray((raf.length() - start).toInt())
|
||||||
|
raf.readFully(bytes)
|
||||||
|
String(bytes)
|
||||||
|
}
|
||||||
|
val touchIndex = Regex("""!! Controller (\d+) attributes:\s*\n\s*Type: 43""").findAll(tail).lastOrNull()?.groupValues?.get(1)
|
||||||
|
if (touchIndex == null) null else {
|
||||||
|
val loaded = Regex("""Loaded Config for [^\n]*? Path for App ID $appId, Controller $touchIndex: ([^\n]+)""")
|
||||||
|
.findAll(tail).lastOrNull()?.groupValues?.get(1)?.trim()
|
||||||
|
loaded?.let { guestPath -> File(LinuxRuntime.rootDir(context), guestPath.trimStart('/').replace("//", "/")) }
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun autosaveConfig(dir: File, appId: Int): File? = try {
|
||||||
|
val set = KeyValues.parse(File(dir, CONFIGSET).readText()).child("controller_config")?.child(appId.toString())
|
||||||
|
if (set?.string("autosave") == "1") File(dir, "$appId/controller_mobile_touch.vdf").takeIf { it.isFile } else null
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's entry in configset_controller_mobile_touch.vdf. */
|
||||||
|
private fun configsetConfig(context: Context, dir: File, appId: Int): File? = try {
|
||||||
|
val set = KeyValues.parse(File(dir, CONFIGSET).readText()).child("controller_config")?.child(appId.toString())
|
||||||
|
when {
|
||||||
|
set == null -> null
|
||||||
|
set.string("autosave") == "1" -> File(dir, "$appId/controller_mobile_touch.vdf")
|
||||||
|
set.string("template") != null -> File(steamRoot(context), "controller_base/templates/" + set.string("template"))
|
||||||
|
else -> null
|
||||||
|
}?.takeIf { it.isFile }
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val CONFIGSET = "configset_controller_mobile_touch.vdf"
|
||||||
|
|
||||||
|
// ---- What a config binds ----
|
||||||
|
|
||||||
|
/** Per preset, the controls its active sources bind - what Steam Link shows (UpdateElementAvailability). */
|
||||||
|
private fun availability(mappings: KeyValues.Node): Map<Int, Set<Int>> {
|
||||||
|
val groups = mappings.children("group").associateBy({ it.string("id") ?: "" }) { group ->
|
||||||
|
group.child("inputs")?.entries?.filter { (_, v) -> (v as? KeyValues.Node)?.let(::hasBinding) == true }
|
||||||
|
?.map { it.first }?.toSet().orEmpty()
|
||||||
|
}
|
||||||
|
return mappings.children("preset").associate { preset ->
|
||||||
|
val id = preset.string("id")?.toIntOrNull() ?: 0
|
||||||
|
val set = mutableSetOf<Int>()
|
||||||
|
preset.child("group_source_bindings")?.entries?.forEach { (groupId, value) ->
|
||||||
|
val parts = (value as? String)?.split(' ') ?: return@forEach
|
||||||
|
if (parts.getOrNull(1) != "active" || parts.contains("modeshift")) return@forEach
|
||||||
|
val bound = groups[groupId].orEmpty()
|
||||||
|
when (parts[0]) {
|
||||||
|
"button_diamond" -> mapOf("button_a" to A, "button_b" to B, "button_x" to X, "button_y" to Y)
|
||||||
|
.forEach { (input, element) -> if (input in bound) set += element }
|
||||||
|
"dpad" -> set += DPAD
|
||||||
|
"joystick" -> { set += JOYSTICK_LEFT; if ("click" in bound) set += JOYSTICK_LEFT_BUTTON }
|
||||||
|
"right_joystick" -> { set += JOYSTICK_RIGHT; if ("click" in bound) set += JOYSTICK_RIGHT_BUTTON }
|
||||||
|
"left_trigger" -> set += TRIGGER_LEFT
|
||||||
|
"right_trigger" -> set += TRIGGER_RIGHT
|
||||||
|
"left_trackpad" -> set += TRACKPAD_LEFT
|
||||||
|
"right_trackpad" -> set += TRACKPAD_RIGHT
|
||||||
|
"center_trackpad" -> set += TRACKPAD_CENTER
|
||||||
|
"switch" -> bound.forEach { input ->
|
||||||
|
when (input) {
|
||||||
|
"button_escape" -> set += START
|
||||||
|
"button_menu" -> set += SELECT
|
||||||
|
"left_bumper" -> set += BUMPER_LEFT
|
||||||
|
"right_bumper" -> set += BUMPER_RIGHT
|
||||||
|
"button_macro_1finger" -> set += MACRO_1_FINGER
|
||||||
|
"button_macro_2finger" -> set += MACRO_2_FINGER
|
||||||
|
else -> Regex("button_macro(\\d)").matchEntire(input)?.let { set += MACRO_0 + it.groupValues[1].toInt() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
id to set.toSet()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasBinding(input: KeyValues.Node): Boolean =
|
||||||
|
input.child("activators")?.entries?.any { (_, activator) ->
|
||||||
|
(activator as? KeyValues.Node)?.child("bindings")?.entries?.any { (k, v) -> k == "binding" && (v as? String)?.isNotBlank() == true } == true
|
||||||
|
} == true
|
||||||
|
|
||||||
|
// ---- Steam Link's defaults ----
|
||||||
|
|
||||||
|
/** Where Steam Link puts a control with no layout (CVirtualController::BInitializeDefaultElement,
|
||||||
|
* on a 1280x720 screen), and the same scheme for the controls its table leaves out, made room
|
||||||
|
* for when a config binds sticks. */
|
||||||
|
fun defaultElement(type: Int, available: Set<Int>): Element? {
|
||||||
|
val leftStick = JOYSTICK_LEFT in available
|
||||||
|
val rightStick = JOYSTICK_RIGHT in available
|
||||||
|
val faceY = if (rightStick) -0.30f else 0f
|
||||||
|
val p: Pair<Float, Float> = when (type) {
|
||||||
|
THUMB -> 75f / 1280 to 75f / 720
|
||||||
|
STEAM -> 636f / 1280 to 75f / 720
|
||||||
|
SELECT -> 516f / 1280 to 75f / 720
|
||||||
|
START -> 756f / 1280 to 75f / 720
|
||||||
|
KEYBOARD -> 1205f / 1280 to 75f / 720
|
||||||
|
PASTE -> 1115f / 1280 to 75f / 720
|
||||||
|
DPAD -> if (leftStick) 0.147f to 0.47f else 200f / 1280 to 525f / 720
|
||||||
|
A -> 1083f / 1280 to 607f / 720 + faceY
|
||||||
|
B -> 1163f / 1280 to 527f / 720 + faceY
|
||||||
|
X -> 1003f / 1280 to 527f / 720 + faceY
|
||||||
|
Y -> 1083f / 1280 to 447f / 720 + faceY
|
||||||
|
JOYSTICK_LEFT -> 0.137f to 0.76f
|
||||||
|
JOYSTICK_RIGHT -> 0.85f to 0.76f
|
||||||
|
JOYSTICK_LEFT_BUTTON -> 0.29f to 0.88f
|
||||||
|
JOYSTICK_RIGHT_BUTTON -> 0.71f to 0.88f
|
||||||
|
BUMPER_LEFT -> 0.06f to 0.205f
|
||||||
|
TRIGGER_LEFT -> 0.16f to 0.205f
|
||||||
|
BUMPER_RIGHT -> 0.94f to 0.205f
|
||||||
|
TRIGGER_RIGHT -> 0.84f to 0.205f
|
||||||
|
TRACKPAD_LEFT -> 0.3f to 0.55f
|
||||||
|
TRACKPAD_CENTER -> 0.5f to 0.55f
|
||||||
|
TRACKPAD_RIGHT -> 0.7f to 0.55f
|
||||||
|
MACRO_1_FINGER -> 0.42f to 0.92f
|
||||||
|
MACRO_2_FINGER -> 0.58f to 0.92f
|
||||||
|
in MACRO_0..MACRO_0 + 7 -> (0.3f + 0.057f * (type - MACRO_0)) to 0.22f
|
||||||
|
else -> return null
|
||||||
|
}
|
||||||
|
return Element(type, true, p.first, p.second)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The controls to draw: the layout's own where it has one, Steam Link's defaults otherwise,
|
||||||
|
* only those the config binds. */
|
||||||
|
fun elementsFor(config: Config, actionSet: Int, layers: List<Int>): List<Element> {
|
||||||
|
val available = config.availableFor(actionSet, layers)
|
||||||
|
val layout = config.layouts?.forActionSet(layoutIdOf(actionSet))
|
||||||
|
val placed = layout?.elements?.associateBy { it.type }.orEmpty()
|
||||||
|
val optional = OPTIONAL.filter { placed[it]?.visible == true && it !in available }
|
||||||
|
return (available + optional).mapNotNull { type ->
|
||||||
|
val own = placed[type]
|
||||||
|
when {
|
||||||
|
own != null && !own.visible -> null
|
||||||
|
own != null -> own
|
||||||
|
else -> defaultElement(type, available)
|
||||||
|
}
|
||||||
|
}.sortedBy { it.type }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun layoutColor(config: Config, actionSet: Int): FloatArray? = config.layouts?.forActionSet(layoutIdOf(actionSet))?.color
|
||||||
|
|
||||||
|
// ---- Saving ----
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves [elements] as the layout of [actionSet] in app [appId]'s touch config: into the app's
|
||||||
|
* autosave config (`<appid>/controller_mobile_touch.vdf`, made from the config in use when the
|
||||||
|
* app has none) and selected for the app in the configset, as the client saves a layout Steam
|
||||||
|
* Link sends it. Returns the file written, or null.
|
||||||
|
*/
|
||||||
|
fun saveLayout(
|
||||||
|
context: Context,
|
||||||
|
appId: Int,
|
||||||
|
config: Config,
|
||||||
|
actionSet: Int,
|
||||||
|
elements: List<Element>,
|
||||||
|
color: FloatArray? = null,
|
||||||
|
bindings: Map<SteamTouchBindings.Ref, (SteamTouchBindings.Binding) -> SteamTouchBindings.Binding> = emptyMap(),
|
||||||
|
): File? = saveLayouts(context, appId, config, mapOf(layoutIdOf(actionSet) to elements), color?.let { c -> setOf(layoutIdOf(actionSet)).associateWith { c } } ?: emptyMap(), bindings)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves the layouts of several action sets (by layout id) at once, with their colours, any
|
||||||
|
* binding edits and the per-game [options], into the game's autosave touch config.
|
||||||
|
*/
|
||||||
|
fun saveLayouts(
|
||||||
|
context: Context,
|
||||||
|
appId: Int,
|
||||||
|
config: Config,
|
||||||
|
sets: Map<Int, List<Element>>,
|
||||||
|
colors: Map<Int, FloatArray> = emptyMap(),
|
||||||
|
bindings: Map<SteamTouchBindings.Ref, (SteamTouchBindings.Binding) -> SteamTouchBindings.Binding> = emptyMap(),
|
||||||
|
options: Options? = null,
|
||||||
|
): File? {
|
||||||
|
val dir = configDir(context) ?: return null
|
||||||
|
// Icons, labels and colours live in the binding strings (SteamTouchBindings), as the
|
||||||
|
// configurator writes them.
|
||||||
|
val source = bindings.entries.fold(config.text ?: return null) { text, (ref, change) ->
|
||||||
|
SteamTouchBindings.rewrite(text, ref, change) ?: text
|
||||||
|
}
|
||||||
|
val target = File(dir, "$appId/controller_mobile_touch.vdf")
|
||||||
|
val old = config.layouts
|
||||||
|
val keep = old?.layouts?.filter { it.actionSet !in sets.keys }.orEmpty()
|
||||||
|
val written = sets.map { (id, elements) ->
|
||||||
|
Layout(id, elements, colors[id] ?: old?.forActionSet(id)?.color ?: floatArrayOf(1f, 1f, 1f, 0.4f), old?.forActionSet(id)?.version)
|
||||||
|
}
|
||||||
|
val rest = old?.rest ?: byteArrayOf(0x10, 0x02) // input_mode = controller
|
||||||
|
val layouts = Layouts((keep + written).sortedBy { it.actionSet }, options?.encodeInto(rest) ?: rest)
|
||||||
|
val hex = bytesToHex(encodeLayouts(layouts))
|
||||||
|
val line = "\t\"touch_layout\"\t\t\"$hex\""
|
||||||
|
val existing = Regex("""\n\s*"touch_layout"\s+"[0-9a-fA-F]*"""")
|
||||||
|
val text = if (existing.containsMatchIn(source)) source.replace(existing, "\n$line")
|
||||||
|
else source.replaceFirst(Regex("""("controller_type"\s+"controller_mobile_touch"[^\n]*)"""), "$1\n$line")
|
||||||
|
if (!text.contains("touch_layout")) return null
|
||||||
|
target.parentFile?.mkdirs()
|
||||||
|
val tmp = File(target.path + ".tmp")
|
||||||
|
tmp.writeText(text)
|
||||||
|
if (!tmp.renameTo(target)) return null
|
||||||
|
selectAutosave(dir, appId)
|
||||||
|
Log.i(TAG, "steam touch: saved layouts ${sets.keys} for app $appId to ${target.path}")
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Points the app's configset entry at its autosave config. */
|
||||||
|
private fun selectAutosave(dir: File, appId: Int) {
|
||||||
|
val file = File(dir, CONFIGSET)
|
||||||
|
val text = if (file.isFile) file.readText() else "\"controller_config\"\n{\n}\n"
|
||||||
|
val entry = "\t\"$appId\"\n\t{\n\t\t\"autosave\"\t\t\"1\"\n\t}"
|
||||||
|
val block = Regex("""\n\s*"$appId"\s*\{[^}]*\}""")
|
||||||
|
val next = if (block.containsMatchIn(text)) text.replace(block, "\n$entry")
|
||||||
|
else text.substring(0, text.lastIndexOf('}')).trimEnd() + "\n$entry\n}\n"
|
||||||
|
File(file.path + ".tmp").apply { writeText(next) }.renameTo(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- touch_layout: CVirtualControllerLayouts ----
|
||||||
|
|
||||||
|
fun decodeLayouts(bytes: ByteArray): Layouts {
|
||||||
|
val layouts = mutableListOf<Layout>()
|
||||||
|
val rest = ByteArrayOutputStream()
|
||||||
|
val p = Proto(bytes)
|
||||||
|
while (p.more()) {
|
||||||
|
val start = p.pos
|
||||||
|
val (field, wire) = p.key()
|
||||||
|
if (field == 1 && wire == 2) layouts += decodeLayout(p.bytes())
|
||||||
|
else { p.skip(wire); rest.write(bytes, start, p.pos - start) }
|
||||||
|
}
|
||||||
|
return Layouts(layouts, rest.toByteArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeLayout(bytes: ByteArray): Layout {
|
||||||
|
var actionSet = 0
|
||||||
|
var version: Int? = null
|
||||||
|
var color: FloatArray? = null
|
||||||
|
val elements = mutableListOf<Element>()
|
||||||
|
val p = Proto(bytes)
|
||||||
|
while (p.more()) {
|
||||||
|
val (field, wire) = p.key()
|
||||||
|
when {
|
||||||
|
field == 1 && wire == 0 -> version = p.varint().toInt()
|
||||||
|
field == 2 && wire == 0 -> actionSet = p.varint().toInt()
|
||||||
|
field == 4 && wire == 2 -> elements += decodeElement(p.bytes())
|
||||||
|
field == 5 && wire == 2 -> color = decodeColor(p.bytes())
|
||||||
|
else -> p.skip(wire)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Layout(actionSet, elements, color, version)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeElement(bytes: ByteArray): Element {
|
||||||
|
var type = -1
|
||||||
|
var visible = false
|
||||||
|
var x = 0f
|
||||||
|
var y = 0f
|
||||||
|
var sx = 1f
|
||||||
|
var sy = 1f
|
||||||
|
val p = Proto(bytes)
|
||||||
|
while (p.more()) {
|
||||||
|
val (field, wire) = p.key()
|
||||||
|
when {
|
||||||
|
field == 1 && wire == 0 -> type = p.varint().toInt()
|
||||||
|
field == 2 && wire == 0 -> visible = p.varint() != 0L
|
||||||
|
field == 3 && wire == 5 -> x = p.float()
|
||||||
|
field == 4 && wire == 5 -> y = p.float()
|
||||||
|
field == 5 && wire == 5 -> sx = p.float()
|
||||||
|
field == 6 && wire == 5 -> sy = p.float()
|
||||||
|
else -> p.skip(wire)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Element(type, visible, x, y, sx, sy)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeColor(bytes: ByteArray): FloatArray {
|
||||||
|
val c = floatArrayOf(1f, 1f, 1f, 1f)
|
||||||
|
val p = Proto(bytes)
|
||||||
|
while (p.more()) {
|
||||||
|
val (field, wire) = p.key()
|
||||||
|
if (field in 1..4 && wire == 5) c[field - 1] = p.float() else p.skip(wire)
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
fun encodeLayouts(layouts: Layouts): ByteArray {
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
layouts.layouts.forEach { layout ->
|
||||||
|
val l = ByteArrayOutputStream()
|
||||||
|
layout.version?.let { tag(l, 1, 0); varint(l, it.toLong()) }
|
||||||
|
tag(l, 2, 0); varint(l, layout.actionSet.toLong())
|
||||||
|
layout.elements.forEach { e ->
|
||||||
|
val m = ByteArrayOutputStream()
|
||||||
|
tag(m, 1, 0); varint(m, e.type.toLong())
|
||||||
|
tag(m, 2, 0); varint(m, if (e.visible) 1 else 0)
|
||||||
|
tag(m, 3, 5); fixed(m, e.x)
|
||||||
|
tag(m, 4, 5); fixed(m, e.y)
|
||||||
|
tag(m, 5, 5); fixed(m, e.xScale)
|
||||||
|
tag(m, 6, 5); fixed(m, e.yScale)
|
||||||
|
tag(l, 4, 2); bytes(l, m.toByteArray())
|
||||||
|
}
|
||||||
|
layout.color?.let { c ->
|
||||||
|
val m = ByteArrayOutputStream()
|
||||||
|
for (i in 0 until 4) { tag(m, i + 1, 5); fixed(m, c[i]) }
|
||||||
|
tag(l, 5, 2); bytes(l, m.toByteArray())
|
||||||
|
}
|
||||||
|
tag(out, 1, 2); bytes(out, l.toByteArray())
|
||||||
|
}
|
||||||
|
out.write(layouts.rest)
|
||||||
|
return out.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun tag(out: ByteArrayOutputStream, field: Int, wire: Int) = varint(out, (field shl 3 or wire).toLong())
|
||||||
|
private fun varint(out: ByteArrayOutputStream, value: Long) {
|
||||||
|
var v = value
|
||||||
|
while (true) {
|
||||||
|
if (v and 0x7fL.inv() == 0L) { out.write(v.toInt()); return }
|
||||||
|
out.write((v and 0x7f or 0x80).toInt())
|
||||||
|
v = v ushr 7
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun fixed(out: ByteArrayOutputStream, f: Float) {
|
||||||
|
val bits = java.lang.Float.floatToIntBits(f)
|
||||||
|
for (i in 0 until 4) out.write(bits ushr (8 * i) and 0xff)
|
||||||
|
}
|
||||||
|
private fun bytes(out: ByteArrayOutputStream, b: ByteArray) { varint(out, b.size.toLong()); out.write(b) }
|
||||||
|
|
||||||
|
private class Proto(val data: ByteArray) {
|
||||||
|
var pos = 0
|
||||||
|
fun varint(): Long {
|
||||||
|
var shift = 0
|
||||||
|
var result = 0L
|
||||||
|
while (pos < data.size) {
|
||||||
|
val b = data[pos++].toInt() and 0xff
|
||||||
|
result = result or ((b and 0x7f).toLong() shl shift)
|
||||||
|
if (b and 0x80 == 0) break
|
||||||
|
shift += 7
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
fun float(): Float {
|
||||||
|
var bits = 0
|
||||||
|
for (i in 0 until 4) bits = bits or ((data[pos + i].toInt() and 0xff) shl (8 * i))
|
||||||
|
pos += 4
|
||||||
|
return java.lang.Float.intBitsToFloat(bits)
|
||||||
|
}
|
||||||
|
fun bytes(): ByteArray {
|
||||||
|
val n = varint().toInt()
|
||||||
|
return data.copyOfRange(pos, pos + n).also { pos += n }
|
||||||
|
}
|
||||||
|
fun skip(wire: Int) {
|
||||||
|
when (wire) {
|
||||||
|
0 -> varint()
|
||||||
|
1 -> pos += 8
|
||||||
|
2 -> pos += varint().toInt()
|
||||||
|
5 -> pos += 4
|
||||||
|
else -> pos = data.size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun more() = pos < data.size
|
||||||
|
fun key(): Pair<Int, Int> = varint().toInt().let { (it ushr 3) to (it and 7) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hexToBytes(hex: String) = ByteArray(hex.length / 2) { hex.substring(2 * it, 2 * it + 2).toInt(16).toByte() }
|
||||||
|
fun bytesToHex(b: ByteArray) = b.joinToString("") { "%02x".format(it.toInt() and 0xff) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Valve's KeyValues text format, as far as controller configs use it. */
|
||||||
|
class KeyValues private constructor() {
|
||||||
|
class Node(val entries: MutableList<Pair<String, Any>> = mutableListOf()) {
|
||||||
|
fun child(key: String): Node? = entries.firstOrNull { it.first.equals(key, true) && it.second is Node }?.second as Node?
|
||||||
|
fun children(key: String): List<Node> = entries.filter { it.first.equals(key, true) && it.second is Node }.map { it.second as Node }
|
||||||
|
fun string(key: String): String? = entries.firstOrNull { it.first.equals(key, true) && it.second is String }?.second as String?
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun parse(text: String): Node {
|
||||||
|
val tokens = tokenize(text)
|
||||||
|
var i = 0
|
||||||
|
fun node(): Node {
|
||||||
|
val n = Node()
|
||||||
|
while (i < tokens.size) {
|
||||||
|
val t = tokens[i++]
|
||||||
|
if (t == "}" ) return n
|
||||||
|
if (t == "{") continue
|
||||||
|
if (i >= tokens.size) break
|
||||||
|
val next = tokens[i]
|
||||||
|
if (next == "{") { i++; n.entries += t to node() } else { i++; n.entries += t to next }
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
return node()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun tokenize(text: String): List<String> {
|
||||||
|
val out = mutableListOf<String>()
|
||||||
|
var i = 0
|
||||||
|
while (i < text.length) {
|
||||||
|
val c = text[i]
|
||||||
|
when {
|
||||||
|
c.isWhitespace() -> i++
|
||||||
|
c == '/' && i + 1 < text.length && text[i + 1] == '/' -> while (i < text.length && text[i] != '\n') i++
|
||||||
|
c == '{' || c == '}' -> { out += c.toString(); i++ }
|
||||||
|
c == '"' -> {
|
||||||
|
val sb = StringBuilder()
|
||||||
|
i++
|
||||||
|
while (i < text.length && text[i] != '"') {
|
||||||
|
if (text[i] == '\\' && i + 1 < text.length) {
|
||||||
|
i++
|
||||||
|
sb.append(when (text[i]) { 'n' -> '\n'; 't' -> '\t'; else -> text[i] })
|
||||||
|
} else sb.append(text[i])
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
out += sb.toString()
|
||||||
|
}
|
||||||
|
c == '[' -> { while (i < text.length && text[i] != ']') i++; i++ }
|
||||||
|
else -> {
|
||||||
|
val start = i
|
||||||
|
while (i < text.length && !text[i].isWhitespace() && text[i] != '{' && text[i] != '}' && text[i] != '"') i++
|
||||||
|
out += text.substring(start, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,171 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import java.io.File
|
||||||
|
import java.io.RandomAccessFile
|
||||||
|
import java.nio.ByteOrder
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.nio.channels.FileChannel
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Steam's touch controller, as the app's side of it.
|
||||||
|
*
|
||||||
|
* libfakeinput offers the Steam client a HID device with the ids of Steam Link's touch controls
|
||||||
|
* (0000:11fb), and the client builds its own touch controller for it: Steam Input's Mobile Touch
|
||||||
|
* type, with the game's touch config, action sets, community configs and cloud sync all Steam's
|
||||||
|
* (docs/development/steam-touch-controller.md). This class is the file the two share
|
||||||
|
* (fakeinput_steam.cpp: TouchRingFile): the app writes the device's 40-byte input report and
|
||||||
|
* whether it is plugged in; libfakeinput writes back what the client told the device - the app and
|
||||||
|
* action set it is on, its layers, rumble.
|
||||||
|
*/
|
||||||
|
class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
|
||||||
|
|
||||||
|
/** What the client last told the device. */
|
||||||
|
data class State(
|
||||||
|
val opened: Int,
|
||||||
|
val appId: Int,
|
||||||
|
val actionSet: Int,
|
||||||
|
val layers: List<Int>,
|
||||||
|
val actionSeq: Int,
|
||||||
|
)
|
||||||
|
|
||||||
|
// The input report (Steam Link's CVirtualController, docs/development/steam-touch-controller.md):
|
||||||
|
// bytes 0-7 buttons, 8-15 sticks, 16-27 trackpads, 28-33 accelerometer, 34-39 gyro.
|
||||||
|
private val report = ByteArray(REPORT_BYTES)
|
||||||
|
private var reportSeq = 0L
|
||||||
|
|
||||||
|
/** The controls part of the report: button bits, sticks (LX, LY, RX, RY, already in the report's
|
||||||
|
* units) and trackpads (centre, left, right: x, y each). */
|
||||||
|
@Synchronized
|
||||||
|
fun setControls(buttons: Long, sticks: ShortArray, pads: ShortArray) {
|
||||||
|
val next = report.copyOf()
|
||||||
|
for (i in 0 until 8) next[i] = (buttons ushr (8 * i)).toByte()
|
||||||
|
for (i in 0 until 4) putShort(next, 8 + 2 * i, sticks[i])
|
||||||
|
for (i in 0 until 6) putShort(next, 16 + 2 * i, pads[i])
|
||||||
|
publish(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Motion in the Deck's axes and units (PadMotion), which the touch report shares. */
|
||||||
|
@Synchronized
|
||||||
|
fun setMotion(accel: ShortArray, gyro: ShortArray) {
|
||||||
|
// Sent only while the client asks for it (setting report 0x30, which Steam Link reads as
|
||||||
|
// "gyro on") and the player has not turned motion off - as Steam Link does.
|
||||||
|
if (!plugged || !gyroRequested || !motionEnabled) return
|
||||||
|
val next = report.copyOf()
|
||||||
|
for (i in 0 until 3) {
|
||||||
|
// Accelerometer: the Deck's 1 g = 16384 is the touch report's ±2 g = ±32767 already.
|
||||||
|
putShort(next, 28 + 2 * i, accel[i])
|
||||||
|
// Gyro: the Deck's 2000 °/s = 32768; the touch report's full scale is 1000 °/s
|
||||||
|
// (Steam Link: rad/s × 180/π / 1000 × 32767).
|
||||||
|
putShort(next, 34 + 2 * i, (gyro[i] * 2).coerceIn(-32767, 32767).toShort())
|
||||||
|
}
|
||||||
|
publish(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the client has asked the device for motion (setting report 0x30 non-zero). */
|
||||||
|
val gyroRequested get() = buffer.getInt(OFF_SETTING30) != 0
|
||||||
|
|
||||||
|
/** The player's motion switch (Steam Link's gyroscope option). */
|
||||||
|
@Volatile var motionEnabled = true
|
||||||
|
set(value) {
|
||||||
|
field = value
|
||||||
|
if (!value) synchronized(this) {
|
||||||
|
val next = report.copyOf()
|
||||||
|
for (i in 28 until 40) next[i] = 0
|
||||||
|
publish(next)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun putShort(into: ByteArray, at: Int, value: Short) {
|
||||||
|
into[at] = value.toInt().toByte()
|
||||||
|
into[at + 1] = (value.toInt() shr 8).toByte()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes the report under the seqlock libfakeinput reads it with. */
|
||||||
|
private fun publish(next: ByteArray) {
|
||||||
|
if (next.contentEquals(report)) return
|
||||||
|
next.copyInto(report)
|
||||||
|
buffer.putLong(OFF_REPORT_SEQ, ++reportSeq)
|
||||||
|
for (i in 0 until REPORT_BYTES) buffer.put(OFF_REPORT + i, report[i])
|
||||||
|
buffer.putLong(OFF_REPORT_SEQ, ++reportSeq)
|
||||||
|
}
|
||||||
|
|
||||||
|
var plugged: Boolean
|
||||||
|
get() = buffer.getInt(OFF_PLUGGED) != 0
|
||||||
|
set(value) {
|
||||||
|
if (value == plugged) return
|
||||||
|
if (!value) synchronized(this) { publish(ByteArray(REPORT_BYTES)) }
|
||||||
|
buffer.putInt(OFF_PLUGGED, if (value) 1 else 0)
|
||||||
|
Log.i(TAG, "steam touch: " + if (value) "plugged in" else "unplugged")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setBattery(percent: Int) = buffer.putInt(OFF_BATTERY, percent.coerceIn(0, 100))
|
||||||
|
|
||||||
|
fun state(): State {
|
||||||
|
repeat(8) {
|
||||||
|
val seq = buffer.getLong(OFF_STATE_SEQ)
|
||||||
|
if (seq and 1L != 0L) return@repeat
|
||||||
|
val count = buffer.getInt(OFF_LAYER_COUNT).coerceIn(0, 8)
|
||||||
|
val read = State(
|
||||||
|
opened = buffer.getInt(OFF_OPENED),
|
||||||
|
appId = buffer.getInt(OFF_APPID),
|
||||||
|
actionSet = buffer.getInt(OFF_ACTION_SET),
|
||||||
|
layers = (0 until count).map { buffer.getInt(OFF_LAYERS + 4 * it) },
|
||||||
|
actionSeq = buffer.getInt(OFF_ACTION_SEQ),
|
||||||
|
)
|
||||||
|
if (seq == buffer.getLong(OFF_STATE_SEQ)) return read
|
||||||
|
}
|
||||||
|
return State(0, 0, 0, emptyList(), -1)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "SteamTouch"
|
||||||
|
const val REPORT_BYTES = 40
|
||||||
|
private const val SIZE = 256
|
||||||
|
private const val MAGIC = 0x31484354 // TCH1
|
||||||
|
private const val OFF_REPORT_SEQ = 8
|
||||||
|
private const val OFF_REPORT = 16
|
||||||
|
private const val OFF_PLUGGED = 56
|
||||||
|
private const val OFF_BATTERY = 60
|
||||||
|
private const val OFF_STATE_SEQ = 64
|
||||||
|
private const val OFF_OPENED = 72
|
||||||
|
private const val OFF_APPID = 76
|
||||||
|
private const val OFF_ACTION_SET = 80
|
||||||
|
private const val OFF_LAYER_COUNT = 84
|
||||||
|
private const val OFF_LAYERS = 88
|
||||||
|
private const val OFF_SETTING30 = 132
|
||||||
|
private const val OFF_ACTION_SEQ = 136
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var current: SteamTouchDevice? = null
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** The shared file in the session's pad directory, made fresh each session. */
|
||||||
|
fun ringFile(fakeInputDir: File) = File(fakeInputDir, "touchctl")
|
||||||
|
|
||||||
|
/** Creates the file for a new session (unplugged) and maps it. */
|
||||||
|
fun prepare(fakeInputDir: File): File? = try {
|
||||||
|
val file = ringFile(fakeInputDir)
|
||||||
|
file.delete()
|
||||||
|
RandomAccessFile(file, "rw").use { raf ->
|
||||||
|
raf.setLength(SIZE.toLong())
|
||||||
|
val map = raf.channel.map(FileChannel.MapMode.READ_WRITE, 0, SIZE.toLong()).order(ByteOrder.LITTLE_ENDIAN)
|
||||||
|
map.putInt(4, 1)
|
||||||
|
map.putInt(0, MAGIC)
|
||||||
|
current = SteamTouchDevice(map)
|
||||||
|
}
|
||||||
|
file.setReadable(true, false)
|
||||||
|
file.setWritable(true, false)
|
||||||
|
file
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "steam touch: no shared file: $e")
|
||||||
|
current = null
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun release() {
|
||||||
|
current?.plugged = false
|
||||||
|
current = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.graphics.PorterDuff
|
||||||
|
import android.graphics.PorterDuffColorFilter
|
||||||
|
import android.graphics.drawable.GradientDrawable
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.text.InputType
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.BaseAdapter
|
||||||
|
import android.widget.EditText
|
||||||
|
import android.widget.GridView
|
||||||
|
import android.widget.HorizontalScrollView
|
||||||
|
import android.widget.ImageView
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.TextView
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Picks a touch control's icon, label and colours the way Steam's configurator does: an icon from
|
||||||
|
* the game's own `TouchMenuIcons` and Steam's binding icon library, a foreground and a background
|
||||||
|
* from Steam's palette. [onPicked] gets the binding with the new fields (the action untouched).
|
||||||
|
*/
|
||||||
|
class SteamTouchIconPicker(
|
||||||
|
private val context: Context,
|
||||||
|
private val host: ViewGroup,
|
||||||
|
private val appId: Int,
|
||||||
|
private val title: String,
|
||||||
|
private val current: SteamTouchBindings.Binding,
|
||||||
|
private val onPicked: (SteamTouchBindings.Binding) -> Unit,
|
||||||
|
) {
|
||||||
|
private val main = Handler(Looper.getMainLooper())
|
||||||
|
private val loader = Executors.newFixedThreadPool(2)
|
||||||
|
private var icon = current.icon
|
||||||
|
private var foreground = current.foreground.ifEmpty { SteamTouchBindings.DEFAULT_FOREGROUND }
|
||||||
|
private var background = current.background.ifEmpty { SteamTouchBindings.DEFAULT_BACKGROUND }
|
||||||
|
private val density = context.resources.displayMetrics.density
|
||||||
|
|
||||||
|
private fun dp(v: Int) = (v * density).toInt()
|
||||||
|
|
||||||
|
fun show() {
|
||||||
|
// Side by side, for a landscape screen: what is picked on the left, the icons on the right.
|
||||||
|
val root = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; setPadding(dp(16), dp(8), dp(16), 0) }
|
||||||
|
val left = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
|
||||||
|
val label = EditText(context).apply {
|
||||||
|
hint = "Label (optional)"
|
||||||
|
setText(current.label)
|
||||||
|
inputType = InputType.TYPE_CLASS_TEXT
|
||||||
|
setSingleLine()
|
||||||
|
}
|
||||||
|
left.addView(label)
|
||||||
|
val preview = ImageView(context)
|
||||||
|
val names = SteamTouchBindings.iconNames(context, appId)
|
||||||
|
val grid = GridView(context).apply {
|
||||||
|
numColumns = GridView.AUTO_FIT
|
||||||
|
columnWidth = dp(56)
|
||||||
|
stretchMode = GridView.STRETCH_COLUMN_WIDTH
|
||||||
|
verticalSpacing = dp(6)
|
||||||
|
horizontalSpacing = dp(6)
|
||||||
|
}
|
||||||
|
val adapter = IconAdapter(names)
|
||||||
|
grid.adapter = adapter
|
||||||
|
grid.setOnItemClickListener { _, _, position, _ ->
|
||||||
|
icon = names[position]
|
||||||
|
adapter.notifyDataSetChanged()
|
||||||
|
updatePreview(preview)
|
||||||
|
}
|
||||||
|
left.addView(LinearLayout(context).apply {
|
||||||
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
|
setPadding(0, dp(8), 0, 0)
|
||||||
|
addView(preview, LinearLayout.LayoutParams(dp(56), dp(56)))
|
||||||
|
addView(TextView(context).apply {
|
||||||
|
text = if (names.isEmpty()) "Steam's icons were not found" else "${names.size} icons from Steam"
|
||||||
|
setPadding(dp(12), 0, 0, 0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
left.addView(paletteRow("Icon colour", { foreground }) { foreground = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||||
|
left.addView(paletteRow("Button colour", { background }) { background = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||||
|
root.addView(left, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
|
||||||
|
root.addView(grid, LinearLayout.LayoutParams(0, dp(250), 1.2f).apply { marginStart = dp(16) })
|
||||||
|
updatePreview(preview)
|
||||||
|
showPanel(host, title, root, listOf(
|
||||||
|
"No icon" to {
|
||||||
|
onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = "", foreground = "", background = ""))
|
||||||
|
},
|
||||||
|
"Cancel" to {},
|
||||||
|
"Use" to {
|
||||||
|
onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = icon,
|
||||||
|
foreground = if (icon.isEmpty()) "" else foreground, background = if (icon.isEmpty()) "" else background))
|
||||||
|
},
|
||||||
|
)) { loader.shutdown() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun paletteRow(name: String, value: () -> String, onPick: (String) -> Unit): View {
|
||||||
|
val row = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }
|
||||||
|
val swatches = mutableListOf<View>()
|
||||||
|
fun refresh() = swatches.forEachIndexed { i, v ->
|
||||||
|
(v.background as GradientDrawable).setStroke(dp(if (SteamTouchBindings.PALETTE[i].equals(value(), true)) 3 else 1),
|
||||||
|
if (SteamTouchBindings.PALETTE[i].equals(value(), true)) Color.rgb(102, 192, 244) else Color.GRAY)
|
||||||
|
}
|
||||||
|
SteamTouchBindings.PALETTE.forEach { hex ->
|
||||||
|
val swatch = View(context).apply {
|
||||||
|
background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(Color.parseColor(hex)) }
|
||||||
|
setOnClickListener { onPick(hex); refresh() }
|
||||||
|
}
|
||||||
|
swatches += swatch
|
||||||
|
row.addView(swatch, LinearLayout.LayoutParams(dp(30), dp(30)).apply { marginEnd = dp(6) })
|
||||||
|
}
|
||||||
|
refresh()
|
||||||
|
return LinearLayout(context).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
setPadding(0, dp(8), 0, 0)
|
||||||
|
addView(TextView(context).apply { text = name })
|
||||||
|
addView(HorizontalScrollView(context).apply { addView(row) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updatePreview(view: ImageView) {
|
||||||
|
if (icon.isEmpty()) { view.setImageDrawable(null); view.background = null; return }
|
||||||
|
loader.execute {
|
||||||
|
val bitmap = SteamTouchBindings.icon(context, appId, icon, 128)?.let { render(it, dp(56)) }
|
||||||
|
main.post { view.setImageBitmap(bitmap) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The icon as Steam draws it: on a disc of the background colour, filled with the foreground
|
||||||
|
* through its own alpha. */
|
||||||
|
private fun render(icon: Bitmap, size: Int): Bitmap {
|
||||||
|
val out = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
|
||||||
|
val canvas = Canvas(out)
|
||||||
|
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||||
|
paint.color = Color.parseColor(background)
|
||||||
|
canvas.drawCircle(size / 2f, size / 2f, size / 2f, paint)
|
||||||
|
drawSteamIcon(canvas, icon, android.graphics.RectF(size * 0.18f, size * 0.18f, size * 0.82f, size * 0.82f), Color.parseColor(foreground), paint)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private inner class IconAdapter(val names: List<String>) : BaseAdapter() {
|
||||||
|
private val loading = HashSet<String>()
|
||||||
|
private var refreshQueued = false
|
||||||
|
|
||||||
|
/** Loads an icon in the background; the grid redraws from the cache once some have come in. */
|
||||||
|
private fun load(name: String) {
|
||||||
|
if (!loading.add(name)) return
|
||||||
|
loader.execute {
|
||||||
|
SteamTouchBindings.icon(context, appId, name, 96)
|
||||||
|
main.post {
|
||||||
|
loading.remove(name)
|
||||||
|
if (refreshQueued) return@post
|
||||||
|
refreshQueued = true
|
||||||
|
main.postDelayed({ refreshQueued = false; notifyDataSetChanged() }, 120)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getCount() = names.size
|
||||||
|
override fun getItem(position: Int) = names[position]
|
||||||
|
override fun getItemId(position: Int) = position.toLong()
|
||||||
|
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
|
||||||
|
val view = (convertView as? ImageView) ?: ImageView(context).apply {
|
||||||
|
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(56))
|
||||||
|
setPadding(dp(8), dp(8), dp(8), dp(8))
|
||||||
|
}
|
||||||
|
val name = names[position]
|
||||||
|
view.tag = name
|
||||||
|
view.background = GradientDrawable().apply {
|
||||||
|
cornerRadius = dp(8).toFloat()
|
||||||
|
setColor(Color.parseColor(background))
|
||||||
|
if (name == icon) setStroke(dp(3), Color.rgb(102, 192, 244))
|
||||||
|
}
|
||||||
|
view.colorFilter = null
|
||||||
|
val cached = SteamTouchBindings.cachedIcon(appId, name, 96)
|
||||||
|
if (cached != null) {
|
||||||
|
val t = tinted(name, cached)
|
||||||
|
if ((view.drawable as? android.graphics.drawable.BitmapDrawable)?.bitmap !== t) view.setImageBitmap(t)
|
||||||
|
} else {
|
||||||
|
view.setImageDrawable(null)
|
||||||
|
load(name)
|
||||||
|
}
|
||||||
|
return view
|
||||||
|
}
|
||||||
|
|
||||||
|
// One thumbnail per icon and colour, reused when the grid rebinds.
|
||||||
|
private val thumbs = android.util.LruCache<String, Bitmap>(64)
|
||||||
|
|
||||||
|
private fun tinted(name: String, icon: Bitmap): Bitmap {
|
||||||
|
val key = "$name|$foreground"
|
||||||
|
thumbs.get(key)?.let { return it }
|
||||||
|
val out = Bitmap.createBitmap(icon.width, icon.height, Bitmap.Config.ARGB_8888)
|
||||||
|
drawSteamIcon(Canvas(out), icon, android.graphics.RectF(0f, 0f, icon.width.toFloat(), icon.height.toFloat()),
|
||||||
|
Color.parseColor(foreground), Paint(Paint.FILTER_BITMAP_FLAG))
|
||||||
|
thumbs.put(key, out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/**
|
||||||
|
* A panel over the session, in the session's own window: a dialog's window of its own left
|
||||||
|
* new bitmaps and layers undrawn in the session window afterwards on the Thor.
|
||||||
|
*/
|
||||||
|
fun showPanel(host: ViewGroup, title: String, content: View, buttons: List<Pair<String, () -> Unit>>, onClose: () -> Unit = {}): () -> Unit {
|
||||||
|
val context = host.context
|
||||||
|
val density = context.resources.displayMetrics.density
|
||||||
|
fun dp(v: Int) = (v * density).toInt()
|
||||||
|
val scrim = android.widget.FrameLayout(context).apply {
|
||||||
|
setBackgroundColor(Color.argb(140, 0, 0, 0))
|
||||||
|
isClickable = true
|
||||||
|
isFocusable = true
|
||||||
|
}
|
||||||
|
// DroidDeck's panel: dark surface, rounded, a hairline border.
|
||||||
|
val card = LinearLayout(context).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
background = GradientDrawable().apply {
|
||||||
|
cornerRadius = dp(18).toFloat(); setColor(Color.rgb(18, 20, 23)); setStroke(dp(1), Color.rgb(38, 42, 49))
|
||||||
|
}
|
||||||
|
setPadding(dp(12), dp(14), dp(12), dp(10))
|
||||||
|
isClickable = true
|
||||||
|
}
|
||||||
|
card.addView(TextView(context).apply {
|
||||||
|
text = title
|
||||||
|
textSize = 15f
|
||||||
|
setTypeface(android.graphics.Typeface.DEFAULT_BOLD)
|
||||||
|
gravity = Gravity.CENTER
|
||||||
|
setTextColor(Color.WHITE)
|
||||||
|
setPadding(dp(16), 0, dp(16), dp(4))
|
||||||
|
})
|
||||||
|
card.addView(content)
|
||||||
|
val row = LinearLayout(context).apply { gravity = Gravity.CENTER; setPadding(dp(8), dp(10), dp(8), 0) }
|
||||||
|
fun close() {
|
||||||
|
(scrim.parent as? ViewGroup)?.removeView(scrim)
|
||||||
|
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager
|
||||||
|
imm.hideSoftInputFromWindow(host.windowToken, 0)
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
buttons.forEachIndexed { i, (name, action) ->
|
||||||
|
row.addView(TextView(context).apply {
|
||||||
|
text = name
|
||||||
|
gravity = Gravity.CENTER
|
||||||
|
textSize = 14f
|
||||||
|
setTextColor(Color.WHITE)
|
||||||
|
val primary = i == buttons.size - 1
|
||||||
|
setTextColor(if (primary) Color.rgb(3, 17, 31) else Color.rgb(242, 244, 247))
|
||||||
|
background = GradientDrawable().apply {
|
||||||
|
cornerRadius = dp(12).toFloat()
|
||||||
|
if (primary) setColor(Color.rgb(26, 159, 255)) else { setColor(Color.rgb(26, 29, 34)); setStroke(dp(1), Color.rgb(52, 58, 67)) }
|
||||||
|
}
|
||||||
|
setPadding(dp(20), dp(10), dp(20), dp(10))
|
||||||
|
setOnClickListener { close(); action() }
|
||||||
|
}, LinearLayout.LayoutParams(0, dp(44), 1f).apply { marginStart = dp(6); marginEnd = dp(6) })
|
||||||
|
}
|
||||||
|
card.addView(row)
|
||||||
|
val width = minOf(dp(640), (context.resources.displayMetrics.widthPixels * 0.9f).toInt())
|
||||||
|
scrim.addView(card, android.widget.FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER))
|
||||||
|
scrim.setOnClickListener { close() }
|
||||||
|
host.addView(scrim, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
|
||||||
|
return { if (scrim.parent != null) close() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Steam's binding icon look (steamui: the icon multiplied with its foreground colour,
|
||||||
|
* background-blend-mode: multiply, keeping the icon's own alpha). */
|
||||||
|
fun drawSteamIcon(canvas: Canvas, icon: Bitmap, into: android.graphics.RectF, foreground: Int, paint: Paint) {
|
||||||
|
val tint = Paint(paint).apply { colorFilter = PorterDuffColorFilter(foreground, PorterDuff.Mode.MULTIPLY) }
|
||||||
|
canvas.drawBitmap(icon, null, into, tint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import android.graphics.BitmapFactory
|
|||||||
import android.os.StatFs
|
import android.os.StatFs
|
||||||
import android.system.Os
|
import android.system.Os
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.RandomAccessFile
|
import java.io.RandomAccessFile
|
||||||
@@ -27,6 +29,11 @@ object AppImageManager {
|
|||||||
val guestDir: String get() = "$GUEST_DIR/$id"
|
val guestDir: String get() = "$GUEST_DIR/$id"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Why a file cannot be imported: [text] with its [args]. */
|
||||||
|
internal class Problem(@StringRes val text: Int, vararg val args: Any) {
|
||||||
|
fun describe(context: Context): String = context.getString(text, *args)
|
||||||
|
}
|
||||||
|
|
||||||
private fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_DIR.substring(1))
|
private fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_DIR.substring(1))
|
||||||
|
|
||||||
fun list(context: Context): List<Item> =
|
fun list(context: Context): List<Item> =
|
||||||
@@ -44,22 +51,22 @@ object AppImageManager {
|
|||||||
* What is wrong with [file] as an AppImage for this device, or null when it can be imported.
|
* What is wrong with [file] as an AppImage for this device, or null when it can be imported.
|
||||||
* An AppImage is an ELF program (its runtime) with "AI" and the format version at byte 8.
|
* An AppImage is an ELF program (its runtime) with "AI" and the format version at byte 8.
|
||||||
*/
|
*/
|
||||||
internal fun problem(file: File): String? {
|
internal fun problem(file: File): Problem? {
|
||||||
if (!file.isFile) return "The file is gone"
|
if (!file.isFile) return Problem(R.string.user_apps_file_gone)
|
||||||
val head = ByteArray(20)
|
val head = ByteArray(20)
|
||||||
try {
|
try {
|
||||||
RandomAccessFile(file, "r").use { if (it.read(head) < head.size) return "The file is too small to be an AppImage" }
|
RandomAccessFile(file, "r").use { if (it.read(head) < head.size) return Problem(R.string.appimg_too_small) }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
return "The file cannot be read: ${e.message}"
|
return Problem(R.string.appimg_unreadable, e.message.toString())
|
||||||
}
|
}
|
||||||
if (head[0] != 0x7f.toByte() || head[1] != 'E'.code.toByte() || head[2] != 'L'.code.toByte() || head[3] != 'F'.code.toByte()) {
|
if (head[0] != 0x7f.toByte() || head[1] != 'E'.code.toByte() || head[2] != 'L'.code.toByte() || head[3] != 'F'.code.toByte()) {
|
||||||
return "This is not an AppImage (it is not a Linux program)"
|
return Problem(R.string.appimg_not_linux)
|
||||||
}
|
}
|
||||||
val machine = (head[18].toInt() and 0xff) or ((head[19].toInt() and 0xff) shl 8)
|
val machine = (head[18].toInt() and 0xff) or ((head[19].toInt() and 0xff) shl 8)
|
||||||
return when {
|
return when {
|
||||||
machine != LinuxFex.ELF_AARCH64 && !LinuxFex.isX86(machine) -> "This AppImage is built for neither ARM64 (aarch64) nor x86 PCs"
|
machine != LinuxFex.ELF_AARCH64 && !LinuxFex.isX86(machine) -> Problem(R.string.appimg_wrong_arch)
|
||||||
head[8] != 'A'.code.toByte() || head[9] != 'I'.code.toByte() -> "This is a Linux program but not an AppImage"
|
head[8] != 'A'.code.toByte() || head[9] != 'I'.code.toByte() -> Problem(R.string.appimg_not_appimage)
|
||||||
head[10].toInt() != 2 -> "Only type 2 AppImages can be imported (this one is type ${head[10].toInt()})"
|
head[10].toInt() != 2 -> Problem(R.string.appimg_wrong_type, head[10].toInt())
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -83,12 +90,12 @@ object AppImageManager {
|
|||||||
fun import(
|
fun import(
|
||||||
context: Context, file: File, name: String?, icon: File?, meta: Map<String, String> = emptyMap(), onProgress: (String) -> Unit,
|
context: Context, file: File, name: String?, icon: File?, meta: Map<String, String> = emptyMap(), onProgress: (String) -> Unit,
|
||||||
): String? {
|
): String? {
|
||||||
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
|
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||||
problem(file)?.let { return it }
|
problem(file)?.let { return it.describe(context) }
|
||||||
val base = root(context).apply { mkdirs() }
|
val base = root(context).apply { mkdirs() }
|
||||||
// Room for the image while it is extracted, and the extracted tree (about the same again).
|
// Room for the image while it is extracted, and the extracted tree (about the same again).
|
||||||
if (StatFs(base.path).availableBytes < file.length() * 3) {
|
if (StatFs(base.path).availableBytes < file.length() * 3) {
|
||||||
return "Not enough free space: importing needs about ${FileUtils.sizeToString(file.length() * 3)}"
|
return context.getString(R.string.appimg_no_space_import, FileUtils.sizeToString(file.length() * 3))
|
||||||
}
|
}
|
||||||
val dir = File(base, idFor(name ?: file.name, base.list()?.toSet() ?: emptySet()))
|
val dir = File(base, idFor(name ?: file.name, base.list()?.toSet() ?: emptySet()))
|
||||||
try {
|
try {
|
||||||
@@ -103,17 +110,17 @@ object AppImageManager {
|
|||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "import ${file.name}", e)
|
Log.e(TAG, "import ${file.name}", e)
|
||||||
FileUtils.delete(dir)
|
FileUtils.delete(dir)
|
||||||
return e.message ?: "Import failed"
|
return e.message ?: context.getString(R.string.appimg_import_failed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Swaps the program of imported [id] for [file], keeping its name and icon; the old one stays if this fails. */
|
/** Swaps the program of imported [id] for [file], keeping its name and icon; the old one stays if this fails. */
|
||||||
fun replace(context: Context, id: String, file: File, meta: Map<String, String>, onProgress: (String) -> Unit): String? {
|
fun replace(context: Context, id: String, file: File, meta: Map<String, String>, onProgress: (String) -> Unit): String? {
|
||||||
problem(file)?.let { return it }
|
problem(file)?.let { return it.describe(context) }
|
||||||
val dir = dir(context, id)
|
val dir = dir(context, id)
|
||||||
if (!File(dir, "app").isDirectory) return "That AppImage is gone"
|
if (!File(dir, "app").isDirectory) return context.getString(R.string.appimg_gone)
|
||||||
if (StatFs(dir.path).availableBytes < file.length() * 3) {
|
if (StatFs(dir.path).availableBytes < file.length() * 3) {
|
||||||
return "Not enough free space: updating needs about ${FileUtils.sizeToString(file.length() * 3)}"
|
return context.getString(R.string.appimg_no_space_update, FileUtils.sizeToString(file.length() * 3))
|
||||||
}
|
}
|
||||||
return try {
|
return try {
|
||||||
extract(context, dir, file, onProgress) ?: run {
|
extract(context, dir, file, onProgress) ?: run {
|
||||||
@@ -123,7 +130,7 @@ object AppImageManager {
|
|||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "replace $id", e)
|
Log.e(TAG, "replace $id", e)
|
||||||
e.message ?: "Update failed"
|
e.message ?: context.getString(R.string.appimg_update_failed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,10 +142,10 @@ object AppImageManager {
|
|||||||
dir.mkdirs()
|
dir.mkdirs()
|
||||||
// Copied in, not run where it lies: shared storage is mounted noexec, and proot's loader
|
// Copied in, not run where it lies: shared storage is mounted noexec, and proot's loader
|
||||||
// maps a program executable.
|
// maps a program executable.
|
||||||
onProgress("Copying ${file.name}")
|
onProgress(context.getString(R.string.user_apps_copying, file.name))
|
||||||
file.inputStream().use { input -> image.outputStream().use { FileUtils.copy(input, it) } }
|
file.inputStream().use { input -> image.outputStream().use { FileUtils.copy(input, it) } }
|
||||||
image.setExecutable(true, false)
|
image.setExecutable(true, false)
|
||||||
onProgress("Extracting ${file.name}")
|
onProgress(context.getString(R.string.appimg_extracting, file.name))
|
||||||
val unpack = if (LinuxFex.isX86(LinuxFex.elfMachine(image))) "${LinuxFex.TOOL} extract ./image.AppImage"
|
val unpack = if (LinuxFex.isX86(LinuxFex.elfMachine(image))) "${LinuxFex.TOOL} extract ./image.AppImage"
|
||||||
else "./image.AppImage --appimage-extract || { rm -rf squashfs-root AppDir; ${LinuxFex.TOOL} extract ./image.AppImage; }"
|
else "./image.AppImage --appimage-extract || { rm -rf squashfs-root AppDir; ${LinuxFex.TOOL} extract ./image.AppImage; }"
|
||||||
val out = StringBuilder()
|
val out = StringBuilder()
|
||||||
@@ -152,7 +159,8 @@ object AppImageManager {
|
|||||||
), logName = "appimage-import", linkDir = links) { line -> if (out.length < 2000) out.appendLine(line) }
|
), logName = "appimage-import", linkDir = links) { line -> if (out.length < 2000) out.appendLine(line) }
|
||||||
if (status != 0 || !File(dir, "app").isDirectory) {
|
if (status != 0 || !File(dir, "app").isDirectory) {
|
||||||
listOf("squashfs-root", "AppDir").forEach { FileUtils.delete(File(dir, it)) }
|
listOf("squashfs-root", "AppDir").forEach { FileUtils.delete(File(dir, it)) }
|
||||||
return "The AppImage could not be extracted" + (out.lines().lastOrNull { it.isNotBlank() }?.let { ": $it" } ?: "")
|
return out.lines().lastOrNull { it.isNotBlank() }?.let { context.getString(R.string.appimg_extract_failed_detail, it) }
|
||||||
|
?: context.getString(R.string.appimg_extract_failed)
|
||||||
}
|
}
|
||||||
copyLinkedFiles(File(dir, "app"), links)
|
copyLinkedFiles(File(dir, "app"), links)
|
||||||
return null
|
return null
|
||||||
|
|||||||
@@ -300,7 +300,10 @@ object BwrapSpawner {
|
|||||||
// session has Xwayland) it stays on X11, which works. GTK and Qt go by their own settings.
|
// session has Xwayland) it stays on X11, which works. GTK and Qt go by their own settings.
|
||||||
if (env.containsKey("DISPLAY")) env["XDG_SESSION_TYPE"] = "x11"
|
if (env.containsKey("DISPLAY")) env["XDG_SESSION_TYPE"] = "x11"
|
||||||
for (name in listOf("MOZ_DISABLE_CONTENT_SANDBOX", "MOZ_DISABLE_GMP_SANDBOX", "MOZ_DISABLE_RDD_SANDBOX",
|
for (name in listOf("MOZ_DISABLE_CONTENT_SANDBOX", "MOZ_DISABLE_GMP_SANDBOX", "MOZ_DISABLE_RDD_SANDBOX",
|
||||||
"MOZ_DISABLE_SOCKET_PROCESS_SANDBOX", "MOZ_DISABLE_UTILITY_SANDBOX")) {
|
"MOZ_DISABLE_SOCKET_PROCESS_SANDBOX", "MOZ_DISABLE_UTILITY_SANDBOX",
|
||||||
|
// Android 16 refuses the size seal Firefox puts on a tab's shared
|
||||||
|
// memory, and the tab then dies on every page (droiddeck-desktop).
|
||||||
|
"MOZ_SHM_NO_SEALS")) {
|
||||||
env.putIfAbsent(name, "1")
|
env.putIfAbsent(name, "1")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.runtime
|
|||||||
import com.droiddeck.launcher.core.Hashes
|
import com.droiddeck.launcher.core.Hashes
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.core.Downloader
|
import com.droiddeck.launcher.core.Downloader
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import com.droiddeck.launcher.core.ArchivePaths
|
import com.droiddeck.launcher.core.ArchivePaths
|
||||||
@@ -24,13 +25,17 @@ object DeckyManager {
|
|||||||
private const val VERSION = "root/homebrew/services/.droiddeck-decky-version"
|
private const val VERSION = "root/homebrew/services/.droiddeck-decky-version"
|
||||||
private const val CEF_REMOTE_DEBUG_MARKER = "root/.local/share/Steam/.cef-enable-remote-debugging"
|
private const val CEF_REMOTE_DEBUG_MARKER = "root/.local/share/Steam/.cef-enable-remote-debugging"
|
||||||
|
|
||||||
|
/** True while a plugin's remote binary downloads: what the UI branches on, not the stage's words. */
|
||||||
|
@Volatile var downloadingBinary = false
|
||||||
|
private set
|
||||||
|
|
||||||
data class Release(val tag: String, val prerelease: Boolean, val asset: String, val url: String, val digest: String?, val shaUrl: String?, val size: Long, val machine: Int)
|
data class Release(val tag: String, val prerelease: Boolean, val asset: String, val url: String, val digest: String?, val shaUrl: String?, val size: Long, val machine: Int)
|
||||||
data class ReleaseChannels(val stable: List<Release>, val prerelease: List<Release>)
|
data class ReleaseChannels(val stable: List<Release>, val prerelease: List<Release>)
|
||||||
|
|
||||||
fun installed(context: Context): String? {
|
fun installed(context: Context): String? {
|
||||||
val loader = loader(context)
|
val loader = loader(context)
|
||||||
if (!loader.isFile || !loader.canExecute()) return null
|
if (!loader.isFile || !loader.canExecute()) return null
|
||||||
return File(LinuxRuntime.rootDir(context), VERSION).takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: "Installed"
|
return File(LinuxRuntime.rootDir(context), VERSION).takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: context.getString(R.string.setup_installed)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun loader(context: Context) = File(LinuxRuntime.rootDir(context), PATH)
|
fun loader(context: Context) = File(LinuxRuntime.rootDir(context), PATH)
|
||||||
@@ -102,39 +107,40 @@ object DeckyManager {
|
|||||||
|
|
||||||
/** Downloads to a sibling temp file and atomically renames only after size, digest and ELF checks. */
|
/** Downloads to a sibling temp file and atomically renames only after size, digest and ELF checks. */
|
||||||
fun install(context: Context, release: Release, progress: (String, Int) -> Unit): String? {
|
fun install(context: Context, release: Release, progress: (String, Int) -> Unit): String? {
|
||||||
if (SessionState.running) return "Stop the active session before installing Decky Loader"
|
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_loader)
|
||||||
val target = loader(context)
|
val target = loader(context)
|
||||||
target.parentFile?.mkdirs()
|
target.parentFile?.mkdirs()
|
||||||
val temp = File(target.parentFile, "PluginLoader.download")
|
val temp = File(target.parentFile, "PluginLoader.download")
|
||||||
val ok = Downloader.downloadFile(release.url, temp, false) { f -> progress("Downloading ${release.tag}", if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }
|
val downloading = context.getString(R.string.user_apps_downloading, release.tag)
|
||||||
if (!ok) { temp.delete(); return "Decky Loader download failed" }
|
val ok = Downloader.downloadFile(release.url, temp, false) { f -> progress(downloading, if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }
|
||||||
if (temp.length() != release.size) { temp.delete(); return "Decky Loader size did not match the release metadata" }
|
if (!ok) { temp.delete(); return context.getString(R.string.deckymgr_download_failed) }
|
||||||
|
if (temp.length() != release.size) { temp.delete(); return context.getString(R.string.deckymgr_size_mismatch) }
|
||||||
val expected = release.digest?.substringAfter(':') ?: release.shaUrl?.let { checksumUrl ->
|
val expected = release.digest?.substringAfter(':') ?: release.shaUrl?.let { checksumUrl ->
|
||||||
val checksumBody = Downloader.downloadString(checksumUrl) ?: run { temp.delete(); return "Could not download the release checksum" }
|
val checksumBody = Downloader.downloadString(checksumUrl) ?: run { temp.delete(); return context.getString(R.string.deckymgr_checksum_download_failed) }
|
||||||
Regex("(?i)\\b[0-9a-f]{64}\\b").find(checksumBody)?.value
|
Regex("(?i)\\b[0-9a-f]{64}\\b").find(checksumBody)?.value
|
||||||
} ?: run { temp.delete(); return "Release checksum is missing" }
|
} ?: run { temp.delete(); return context.getString(R.string.deckymgr_checksum_missing) }
|
||||||
if (!expected.matches(Regex("(?i)[0-9a-f]{64}"))) { temp.delete(); return "Release checksum is invalid" }
|
if (!expected.matches(Regex("(?i)[0-9a-f]{64}"))) { temp.delete(); return context.getString(R.string.deckymgr_checksum_invalid) }
|
||||||
if (!expected.equals(Hashes.sha256(temp), true)) { temp.delete(); return "Decky Loader checksum mismatch" }
|
if (!expected.equals(Hashes.sha256(temp), true)) { temp.delete(); return context.getString(R.string.deckymgr_checksum_mismatch) }
|
||||||
if (!validElf(temp, release.machine)) { temp.delete(); return "Release asset is not a compatible 64-bit Linux executable" }
|
if (!validElf(temp, release.machine)) { temp.delete(); return context.getString(R.string.deckymgr_not_elf) }
|
||||||
if (SessionState.running) { temp.delete(); return "A session started during the download; stop it before installing Decky Loader" }
|
if (SessionState.running) { temp.delete(); return context.getString(R.string.deckymgr_session_started_loader) }
|
||||||
if (!temp.setExecutable(true, false)) { temp.delete(); return "Could not mark PluginLoader executable" }
|
if (!temp.setExecutable(true, false)) { temp.delete(); return context.getString(R.string.deckymgr_loader_not_executable) }
|
||||||
// Decky needs Steam's local CEF debugger only when its session supervisor is enabled.
|
// Decky needs Steam's local CEF debugger only when its session supervisor is enabled.
|
||||||
val cefMarker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER)
|
val cefMarker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER)
|
||||||
val cefReady = !supervisorEnabled(context) || cefMarker.isFile || runCatching {
|
val cefReady = !supervisorEnabled(context) || cefMarker.isFile || runCatching {
|
||||||
cefMarker.parentFile?.mkdirs()
|
cefMarker.parentFile?.mkdirs()
|
||||||
cefMarker.createNewFile() || cefMarker.isFile
|
cefMarker.createNewFile() || cefMarker.isFile
|
||||||
}.getOrDefault(false)
|
}.getOrDefault(false)
|
||||||
if (!cefReady) { temp.delete(); return "Could not enable Steam CEF remote debugging" }
|
if (!cefReady) { temp.delete(); return context.getString(R.string.deckymgr_cef_failed) }
|
||||||
val staged = File(target.parentFile, "PluginLoader.new")
|
val staged = File(target.parentFile, "PluginLoader.new")
|
||||||
staged.delete()
|
staged.delete()
|
||||||
if (!temp.renameTo(staged)) { temp.delete(); return "Could not stage PluginLoader" }
|
if (!temp.renameTo(staged)) { temp.delete(); return context.getString(R.string.deckymgr_stage_failed) }
|
||||||
val old = File(target.parentFile, "PluginLoader.old")
|
val old = File(target.parentFile, "PluginLoader.old")
|
||||||
old.delete()
|
old.delete()
|
||||||
if (target.exists() && !target.renameTo(old)) { staged.delete(); return "Could not preserve the existing PluginLoader" }
|
if (target.exists() && !target.renameTo(old)) { staged.delete(); return context.getString(R.string.deckymgr_loader_preserve_failed) }
|
||||||
if (!staged.renameTo(target)) {
|
if (!staged.renameTo(target)) {
|
||||||
if (old.exists()) old.renameTo(target)
|
if (old.exists()) old.renameTo(target)
|
||||||
staged.delete()
|
staged.delete()
|
||||||
return "Could not activate the new PluginLoader"
|
return context.getString(R.string.deckymgr_loader_activate_failed)
|
||||||
}
|
}
|
||||||
old.delete()
|
old.delete()
|
||||||
File(target.parentFile, ".droiddeck-decky-version").writeText(release.tag + "\n")
|
File(target.parentFile, ".droiddeck-decky-version").writeText(release.tag + "\n")
|
||||||
@@ -145,43 +151,44 @@ object DeckyManager {
|
|||||||
|
|
||||||
/** Imports a Decky distribution ZIP into homebrew/plugins for the next Steam session. */
|
/** Imports a Decky distribution ZIP into homebrew/plugins for the next Steam session. */
|
||||||
fun installPluginZip(context: Context, archive: File, progress: (String, Int) -> Unit): String? {
|
fun installPluginZip(context: Context, archive: File, progress: (String, Int) -> Unit): String? {
|
||||||
if (SessionState.running) return "Stop the active session before installing a plugin"
|
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin)
|
||||||
if (installed(context) == null) return "Install Decky Loader before importing a plugin"
|
if (installed(context) == null) return context.getString(R.string.deckymgr_loader_required)
|
||||||
if (!archive.isFile || !archive.canRead()) return "Could not read the selected ZIP file"
|
if (!archive.isFile || !archive.canRead()) return context.getString(R.string.deckymgr_zip_unreadable)
|
||||||
|
|
||||||
val plugins = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins")
|
val plugins = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins")
|
||||||
if (!plugins.exists() && !plugins.mkdirs()) return "Could not create the Decky plugins directory"
|
if (!plugins.exists() && !plugins.mkdirs()) return context.getString(R.string.deckymgr_plugins_dir_failed)
|
||||||
val staging = File(plugins, ".droiddeck-import-${UUID.randomUUID()}")
|
val staging = File(plugins, ".droiddeck-import-${UUID.randomUUID()}")
|
||||||
val backupSuffix = ".droiddeck-backup-${UUID.randomUUID()}"
|
val backupSuffix = ".droiddeck-backup-${UUID.randomUUID()}"
|
||||||
try {
|
try {
|
||||||
staging.mkdirs()
|
staging.mkdirs()
|
||||||
progress("Extracting plugin ZIP", -1)
|
progress(context.getString(R.string.deckymgr_extracting_zip), -1)
|
||||||
extractPluginZip(archive, staging)
|
extractPluginZip(context, archive, staging)
|
||||||
val roots = staging.listFiles()?.filter { it.isDirectory } ?: emptyList()
|
val roots = staging.listFiles()?.filter { it.isDirectory } ?: emptyList()
|
||||||
if (roots.size != 1 || staging.listFiles()?.size != 1) return "Plugin ZIP must contain one top-level plugin folder"
|
if (roots.size != 1 || staging.listFiles()?.size != 1) return context.getString(R.string.deckymgr_zip_one_folder)
|
||||||
val plugin = roots.single()
|
val plugin = roots.single()
|
||||||
if (!File(plugin, "plugin.json").isFile || !File(plugin, "package.json").isFile || !File(plugin, "dist/index.js").isFile) {
|
if (!File(plugin, "plugin.json").isFile || !File(plugin, "package.json").isFile || !File(plugin, "dist/index.js").isFile) {
|
||||||
return "Plugin ZIP is missing plugin.json, package.json, or dist/index.js"
|
return context.getString(R.string.deckymgr_zip_missing_files)
|
||||||
}
|
}
|
||||||
val name = JSONObject(File(plugin, "plugin.json").readText()).getString("name")
|
val name = JSONObject(File(plugin, "plugin.json").readText()).getString("name")
|
||||||
require(name.isNotBlank()) { "Plugin name is missing" }
|
require(name.isNotBlank()) { context.getString(R.string.deckymgr_plugin_name_missing) }
|
||||||
val metadata = JSONObject(File(plugin, "package.json").readText())
|
val metadata = JSONObject(File(plugin, "package.json").readText())
|
||||||
downloadRemoteBinaries(metadata, plugin, progress)
|
downloadRemoteBinaries(context, metadata, plugin, progress)
|
||||||
if (SessionState.running) return "A session started during installation; stop it before installing a plugin"
|
if (SessionState.running) return context.getString(R.string.deckymgr_session_started_plugin)
|
||||||
|
|
||||||
DeckyPluginInstall.activate(plugin, plugins, name,
|
DeckyPluginInstall.activate(plugin, plugins, name,
|
||||||
File(plugins.parentFile, "settings/loader.json"), backupSuffix)
|
File(plugins.parentFile, "settings/loader.json"), backupSuffix)
|
||||||
progress("Plugin installed · restart Steam to load it", 100)
|
progress(context.getString(R.string.deckymgr_plugin_installed), 100)
|
||||||
return null
|
return null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "plugin ZIP import", e)
|
Log.w(TAG, "plugin ZIP import", e)
|
||||||
return e.message?.takeIf { it.isNotBlank() } ?: "Plugin ZIP installation failed"
|
if (e is DeckyPluginInstall.Failure) return context.getString(e.text)
|
||||||
|
return e.message?.takeIf { it.isNotBlank() } ?: context.getString(R.string.deckymgr_plugin_install_failed)
|
||||||
} finally {
|
} finally {
|
||||||
staging.deleteRecursively()
|
staging.deleteRecursively()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun extractPluginZip(archive: File, destination: File) {
|
private fun extractPluginZip(context: Context, archive: File, destination: File) {
|
||||||
var totalBytes = 0L
|
var totalBytes = 0L
|
||||||
var entries = 0
|
var entries = 0
|
||||||
val seen = HashSet<String>()
|
val seen = HashSet<String>()
|
||||||
@@ -189,30 +196,30 @@ object DeckyManager {
|
|||||||
while (true) {
|
while (true) {
|
||||||
val entry = zip.nextEntry ?: break
|
val entry = zip.nextEntry ?: break
|
||||||
entries++
|
entries++
|
||||||
require(entries <= 10_000) { "Plugin ZIP contains too many entries" }
|
require(entries <= 10_000) { context.getString(R.string.deckymgr_zip_too_many) }
|
||||||
val relative = entry.name.replace('\\', '/')
|
val relative = entry.name.replace('\\', '/')
|
||||||
require(relative.isNotBlank() && !relative.startsWith('/')) { "Plugin ZIP contains an invalid path" }
|
require(relative.isNotBlank() && !relative.startsWith('/')) { context.getString(R.string.deckymgr_zip_invalid_path) }
|
||||||
require(seen.add(relative)) { "Plugin ZIP contains duplicate paths" }
|
require(seen.add(relative)) { context.getString(R.string.deckymgr_zip_duplicate_paths) }
|
||||||
val output = ArchivePaths.inside(destination, relative)
|
val output = ArchivePaths.inside(destination, relative)
|
||||||
?: throw IllegalArgumentException("Plugin ZIP contains an unsafe path")
|
?: throw IllegalArgumentException(context.getString(R.string.deckymgr_zip_unsafe_path))
|
||||||
if (entry.isDirectory) {
|
if (entry.isDirectory) {
|
||||||
require(output.mkdirs() || output.isDirectory) { "Could not create plugin folder" }
|
require(output.mkdirs() || output.isDirectory) { context.getString(R.string.deckymgr_folder_failed) }
|
||||||
} else {
|
} else {
|
||||||
require(output.parentFile?.let { it.mkdirs() || it.isDirectory } == true) { "Could not create plugin folder" }
|
require(output.parentFile?.let { it.mkdirs() || it.isDirectory } == true) { context.getString(R.string.deckymgr_folder_failed) }
|
||||||
FileOutputStream(output).use { out ->
|
FileOutputStream(output).use { out ->
|
||||||
val buffer = ByteArray(64 * 1024)
|
val buffer = ByteArray(64 * 1024)
|
||||||
while (true) {
|
while (true) {
|
||||||
val read = zip.read(buffer)
|
val read = zip.read(buffer)
|
||||||
if (read < 0) break
|
if (read < 0) break
|
||||||
totalBytes += read
|
totalBytes += read
|
||||||
require(totalBytes <= MAX_PLUGIN_ZIP_BYTES) { "Plugin ZIP expands beyond the 1 GiB limit" }
|
require(totalBytes <= MAX_PLUGIN_ZIP_BYTES) { context.getString(R.string.deckymgr_zip_too_large) }
|
||||||
out.write(buffer, 0, read)
|
out.write(buffer, 0, read)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Decky distributions place plugin executables under bin/. Java's ZIP reader
|
// Decky distributions place plugin executables under bin/. Java's ZIP reader
|
||||||
// does not expose Unix mode bits, so restore execution on those payload files.
|
// does not expose Unix mode bits, so restore execution on those payload files.
|
||||||
if (relative.split('/').dropLast(1).any { it == "bin" } && !output.setExecutable(true, false)) {
|
if (relative.split('/').dropLast(1).any { it == "bin" } && !output.setExecutable(true, false)) {
|
||||||
throw IllegalStateException("Could not mark bundled plugin binary executable")
|
throw IllegalStateException(context.getString(R.string.deckymgr_bundled_not_executable))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
zip.closeEntry()
|
zip.closeEntry()
|
||||||
@@ -220,42 +227,49 @@ object DeckyManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun downloadRemoteBinaries(metadata: JSONObject, plugin: File, progress: (String, Int) -> Unit) {
|
private fun downloadRemoteBinaries(context: Context, metadata: JSONObject, plugin: File, progress: (String, Int) -> Unit) {
|
||||||
val binaries = metadata.optJSONArray("remote_binary") ?: return
|
val binaries = metadata.optJSONArray("remote_binary") ?: return
|
||||||
val bin = File(plugin, "bin")
|
val bin = File(plugin, "bin")
|
||||||
for (i in 0 until binaries.length()) {
|
for (i in 0 until binaries.length()) {
|
||||||
val binary = binaries.optJSONObject(i) ?: throw IllegalArgumentException("Invalid remote_binary entry")
|
val binary = binaries.optJSONObject(i) ?: throw IllegalArgumentException(context.getString(R.string.deckymgr_remote_entry_invalid))
|
||||||
val name = binary.optString("name")
|
val name = binary.optString("name")
|
||||||
val url = binary.optString("url")
|
val url = binary.optString("url")
|
||||||
val hash = binary.optString("sha256hash")
|
val hash = binary.optString("sha256hash")
|
||||||
require(name.isNotBlank() && name != "." && name != ".." && !name.contains('/') && !name.contains('\\')) { "Invalid remote binary name" }
|
require(name.isNotBlank() && name != "." && name != ".." && !name.contains('/') && !name.contains('\\')) { context.getString(R.string.deckymgr_remote_name_invalid) }
|
||||||
require(url.startsWith("https://")) { "Remote binary URL must use HTTPS" }
|
require(url.startsWith("https://")) { context.getString(R.string.deckymgr_remote_url_https) }
|
||||||
require(hash.matches(Regex("(?i)[0-9a-f]{64}"))) { "Remote binary $name has an invalid SHA-256 hash" }
|
require(hash.matches(Regex("(?i)[0-9a-f]{64}"))) { context.getString(R.string.deckymgr_remote_hash_invalid, name) }
|
||||||
require(bin.mkdirs() || bin.isDirectory) { "Could not create plugin bin directory" }
|
require(bin.mkdirs() || bin.isDirectory) { context.getString(R.string.deckymgr_bin_dir_failed) }
|
||||||
val temp = File(bin, ".$name.download")
|
val temp = File(bin, ".$name.download")
|
||||||
progress("Downloading plugin binary · $name", -1)
|
val downloading = context.getString(R.string.deckymgr_downloading_binary, name)
|
||||||
if (!Downloader.downloadFile(url, temp, false) { fraction ->
|
downloadingBinary = true
|
||||||
progress("Downloading plugin binary · $name", if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100))
|
progress(downloading, -1)
|
||||||
}) {
|
val downloaded = try {
|
||||||
|
Downloader.downloadFile(url, temp, false) { fraction ->
|
||||||
|
progress(downloading, if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100))
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
downloadingBinary = false
|
||||||
|
}
|
||||||
|
if (!downloaded) {
|
||||||
temp.delete()
|
temp.delete()
|
||||||
throw IllegalStateException("Could not download plugin binary $name")
|
throw IllegalStateException(context.getString(R.string.deckymgr_binary_download_failed, name))
|
||||||
}
|
}
|
||||||
if (!hash.equals(Hashes.sha256(temp), ignoreCase = true)) {
|
if (!hash.equals(Hashes.sha256(temp), ignoreCase = true)) {
|
||||||
temp.delete()
|
temp.delete()
|
||||||
throw IllegalStateException("Plugin binary checksum mismatch · $name")
|
throw IllegalStateException(context.getString(R.string.deckymgr_binary_checksum_mismatch, name))
|
||||||
}
|
}
|
||||||
if (!temp.setExecutable(true, false)) {
|
if (!temp.setExecutable(true, false)) {
|
||||||
temp.delete()
|
temp.delete()
|
||||||
throw IllegalStateException("Could not mark plugin binary executable · $name")
|
throw IllegalStateException(context.getString(R.string.deckymgr_binary_not_executable, name))
|
||||||
}
|
}
|
||||||
val target = File(bin, name)
|
val target = File(bin, name)
|
||||||
if (target.exists() && !target.delete()) {
|
if (target.exists() && !target.delete()) {
|
||||||
temp.delete()
|
temp.delete()
|
||||||
throw IllegalStateException("Could not replace plugin binary · $name")
|
throw IllegalStateException(context.getString(R.string.deckymgr_binary_replace_failed, name))
|
||||||
}
|
}
|
||||||
if (!temp.renameTo(target)) {
|
if (!temp.renameTo(target)) {
|
||||||
temp.delete()
|
temp.delete()
|
||||||
throw IllegalStateException("Could not install plugin binary · $name")
|
throw IllegalStateException(context.getString(R.string.deckymgr_binary_install_failed, name))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
package com.droiddeck.launcher.runtime
|
package com.droiddeck.launcher.runtime
|
||||||
|
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
|
||||||
/** Offline equivalent of Decky's identity-based replacement and loader settings update. */
|
/** Offline equivalent of Decky's identity-based replacement and loader settings update. */
|
||||||
internal object DeckyPluginInstall {
|
internal object DeckyPluginInstall {
|
||||||
|
/** A failure the user is told about: [text] is its string resource. */
|
||||||
|
class Failure(@StringRes val text: Int) : IllegalStateException()
|
||||||
|
|
||||||
fun activate(staged: File, plugins: File, name: String, settingsFile: File, backupSuffix: String) {
|
fun activate(staged: File, plugins: File, name: String, settingsFile: File, backupSuffix: String) {
|
||||||
val settings = if (settingsFile.exists()) JSONObject(settingsFile.readText()) else JSONObject()
|
val settings = if (settingsFile.exists()) JSONObject(settingsFile.readText()) else JSONObject()
|
||||||
val existing = plugins.listFiles().orEmpty().filter { folder ->
|
val existing = plugins.listFiles().orEmpty().filter { folder ->
|
||||||
@@ -14,7 +19,7 @@ internal object DeckyPluginInstall {
|
|||||||
}.getOrDefault(false)
|
}.getOrDefault(false)
|
||||||
}
|
}
|
||||||
val target = File(plugins, staged.name)
|
val target = File(plugins, staged.name)
|
||||||
require(!target.exists() || target in existing) { "Plugin folder belongs to another plugin" }
|
if (target.exists() && target !in existing) throw Failure(R.string.deckymgr_folder_taken)
|
||||||
val order = settings.optJSONArray("pluginOrder") ?: JSONArray(plugins.listFiles().orEmpty()
|
val order = settings.optJSONArray("pluginOrder") ?: JSONArray(plugins.listFiles().orEmpty()
|
||||||
.filter { it.isDirectory && !it.name.startsWith(".droiddeck-") }
|
.filter { it.isDirectory && !it.name.startsWith(".droiddeck-") }
|
||||||
.mapNotNull { runCatching { JSONObject(File(it, "plugin.json").readText()).getString("name") }.getOrNull() }
|
.mapNotNull { runCatching { JSONObject(File(it, "plugin.json").readText()).getString("name") }.getOrNull() }
|
||||||
@@ -34,15 +39,15 @@ internal object DeckyPluginInstall {
|
|||||||
pending.writeText(settings.toString(4))
|
pending.writeText(settings.toString(4))
|
||||||
for (old in existing) {
|
for (old in existing) {
|
||||||
val backup = File(plugins, ".droiddeck-backup-${old.name}$backupSuffix")
|
val backup = File(plugins, ".droiddeck-backup-${old.name}$backupSuffix")
|
||||||
check(old.renameTo(backup)) { "Could not preserve the existing plugin" }
|
if (!old.renameTo(backup)) throw Failure(R.string.deckymgr_preserve_failed)
|
||||||
backups.add(old to backup)
|
backups.add(old to backup)
|
||||||
}
|
}
|
||||||
check(staged.renameTo(target)) { "Could not activate the imported plugin" }
|
if (!staged.renameTo(target)) throw Failure(R.string.deckymgr_activate_failed)
|
||||||
activated = true
|
activated = true
|
||||||
check(pending.renameTo(settingsFile)) { "Could not update Decky plugin settings" }
|
if (!pending.renameTo(settingsFile)) throw Failure(R.string.deckymgr_settings_failed)
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
if (activated) target.deleteRecursively()
|
if (activated) target.deleteRecursively()
|
||||||
for ((old, backup) in backups.asReversed()) check(backup.renameTo(old)) { "Could not restore the existing plugin" }
|
for ((old, backup) in backups.asReversed()) if (!backup.renameTo(old)) throw Failure(R.string.deckymgr_restore_failed)
|
||||||
throw error
|
throw error
|
||||||
} finally {
|
} finally {
|
||||||
pending.delete()
|
pending.delete()
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.runtime
|
|||||||
import com.droiddeck.launcher.core.Hashes
|
import com.droiddeck.launcher.core.Hashes
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.core.Downloader
|
import com.droiddeck.launcher.core.Downloader
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
@@ -81,20 +82,21 @@ object DesktopCatalog {
|
|||||||
/** Downloads, verifies and installs one package. Returns null on success, else a message. */
|
/** Downloads, verifies and installs one package. Returns null on success, else a message. */
|
||||||
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||||
val root = LinuxRuntime.rootDir(context)
|
val root = LinuxRuntime.rootDir(context)
|
||||||
if (!root.isDirectory) return "The Linux runtime is not installed"
|
if (!root.isDirectory) return context.getString(R.string.deskpkg_runtime_missing)
|
||||||
// Every catalog row carries a sha256; one without is refused rather than trusted.
|
// Every catalog row carries a sha256; one without is refused rather than trusted.
|
||||||
if (entry.sha256.isEmpty()) return "The catalog has no checksum for ${entry.name}"
|
if (entry.sha256.isEmpty()) return context.getString(R.string.deskpkg_no_checksum, entry.name)
|
||||||
val download = File(context.cacheDir, "pkg-${entry.id}.download")
|
val download = File(context.cacheDir, "pkg-${entry.id}.download")
|
||||||
try {
|
try {
|
||||||
listener?.onProgress("Downloading ${entry.name}", 0)
|
val downloading = context.getString(R.string.user_apps_downloading, entry.name)
|
||||||
|
listener?.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, 0)
|
||||||
val ok = Downloader.downloadFile(entry.url, download, true) { f ->
|
val ok = Downloader.downloadFile(entry.url, download, true) { f ->
|
||||||
listener?.onProgress("Downloading ${entry.name}", if (f < 0) -1 else Math.round(f * 100f))
|
listener?.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, if (f < 0) -1 else Math.round(f * 100f))
|
||||||
}
|
}
|
||||||
if (!ok) return "Download failed"
|
if (!ok) return context.getString(R.string.user_apps_download_failed)
|
||||||
listener?.onProgress("Verifying", -1)
|
listener?.onProgress(LinuxRuntimeInstaller.Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1)
|
||||||
val actual = Hashes.sha256(download)
|
val actual = Hashes.sha256(download)
|
||||||
if (!entry.sha256.equals(actual, ignoreCase = true)) return "Checksum mismatch - nothing was changed"
|
if (!entry.sha256.equals(actual, ignoreCase = true)) return context.getString(R.string.deskpkg_checksum_mismatch)
|
||||||
listener?.onProgress("Installing ${entry.name}", -1)
|
listener?.onProgress(context.getString(R.string.deskpkg_installing, entry.name), -1)
|
||||||
when (entry.kind) {
|
when (entry.kind) {
|
||||||
"appimage" -> {
|
"appimage" -> {
|
||||||
val dir = File(root, "opt/appimages").apply { mkdirs() }
|
val dir = File(root, "opt/appimages").apply { mkdirs() }
|
||||||
@@ -102,20 +104,20 @@ object DesktopCatalog {
|
|||||||
// Some projects zip the AppImage (melonDS); the one file inside is what we want.
|
// Some projects zip the AppImage (melonDS); the one file inside is what we want.
|
||||||
val placed = if (entry.url.endsWith(".zip", ignoreCase = true)) unzipAppImage(download, target)
|
val placed = if (entry.url.endsWith(".zip", ignoreCase = true)) unzipAppImage(download, target)
|
||||||
else download.renameTo(target)
|
else download.renameTo(target)
|
||||||
if (!placed) return "Could not place the AppImage"
|
if (!placed) return context.getString(R.string.deskpkg_place_failed)
|
||||||
target.setExecutable(true, false)
|
target.setExecutable(true, false)
|
||||||
FileUtils.writeString(File(root, "usr/share/applications/droiddeck-${entry.id}.desktop"),
|
FileUtils.writeString(File(root, "usr/share/applications/droiddeck-${entry.id}.desktop"),
|
||||||
"[Desktop Entry]\nType=Application\nName=${entry.name}\n" +
|
"[Desktop Entry]\nType=Application\nName=${entry.name}\n" +
|
||||||
"Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/${entry.id}.AppImage\n" +
|
"Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/${entry.id}.AppImage\n" +
|
||||||
"Icon=${entry.icon}\nTerminal=false\nCategories=${entry.category};\n")
|
"Icon=${entry.icon}\nTerminal=false\nCategories=${entry.category};\n")
|
||||||
}
|
}
|
||||||
else -> if (!LinuxRuntimeInstaller.extract(download, root, listener)) return "Extraction failed"
|
else -> if (!LinuxRuntimeInstaller.extract(context, download, root, listener)) return context.getString(R.string.deskpkg_extract_failed)
|
||||||
}
|
}
|
||||||
FileUtils.writeString(marker(context, entry.id), entry.version)
|
FileUtils.writeString(marker(context, entry.id), entry.version)
|
||||||
return null
|
return null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "install ${entry.id}", e)
|
Log.e(TAG, "install ${entry.id}", e)
|
||||||
return e.message ?: "Install failed"
|
return e.message ?: context.getString(R.string.deskpkg_install_failed)
|
||||||
} finally {
|
} finally {
|
||||||
download.delete()
|
download.delete()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.runtime
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
@@ -92,9 +93,10 @@ object FlatpakManager {
|
|||||||
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
|
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
|
||||||
}
|
}
|
||||||
|
|
||||||
private inline fun <T> exclusive(what: String, block: () -> T): T? {
|
/** [block]'s result, or [ifBusy]'s while another operation has the installation. */
|
||||||
|
private inline fun <T> exclusive(what: String, ifBusy: () -> T, block: () -> T): T {
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
if (busy != null) return null
|
if (busy != null) return ifBusy()
|
||||||
busy = what
|
busy = what
|
||||||
}
|
}
|
||||||
try { return block() } finally { busy = null }
|
try { return block() } finally { busy = null }
|
||||||
@@ -102,8 +104,8 @@ object FlatpakManager {
|
|||||||
|
|
||||||
/** Puts Flatpak into the runtime and adds Flathub. Null on success, else what went wrong. */
|
/** Puts Flatpak into the runtime and adds Flathub. Null on success, else what went wrong. */
|
||||||
fun setup(context: Context, onProgress: (String, Int) -> Unit): String? {
|
fun setup(context: Context, onProgress: (String, Int) -> Unit): String? {
|
||||||
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
|
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||||
return exclusive("setup") {
|
return exclusive("setup", { context.getString(R.string.flatpakmgr_busy) }) {
|
||||||
var failure: String? = null
|
var failure: String? = null
|
||||||
val status = runGuest(context, listOf("/bin/bash", SETUP), fakeRoot = true) { line ->
|
val status = runGuest(context, listOf("/bin/bash", SETUP), fakeRoot = true) { line ->
|
||||||
Log.i(TAG, "setup: $line")
|
Log.i(TAG, "setup: $line")
|
||||||
@@ -114,63 +116,76 @@ object FlatpakManager {
|
|||||||
}
|
}
|
||||||
when {
|
when {
|
||||||
failure != null -> failure
|
failure != null -> failure
|
||||||
status != 0 -> "Flatpak setup failed (exit $status)"
|
status != 0 -> context.getString(R.string.flatpakmgr_setup_failed, status)
|
||||||
!ready(context) -> "Flatpak setup did not finish"
|
!ready(context) -> context.getString(R.string.flatpakmgr_setup_unfinished)
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
} ?: "Another store task is running"
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One store operation - install, uninstall or update - with its progress as a stage line and
|
* One store operation - install, uninstall or update - with its progress as a stage line and
|
||||||
* an overall percentage across the steps Flatpak plans (a runtime, its extensions, the app).
|
* an overall percentage across the steps Flatpak plans (a runtime, its extensions, the app).
|
||||||
*/
|
*/
|
||||||
private fun transaction(context: Context, verb: String, id: String?, onProgress: (String, Int) -> Unit): String? {
|
private fun transaction(
|
||||||
if (!ready(context)) return "Set up Flatpak first"
|
context: Context, verb: String, id: String?, onProgress: (String, Int) -> Unit, onDone: (JSONObject) -> Unit = {},
|
||||||
return exclusive("$verb:${id ?: "all"}") {
|
): String? {
|
||||||
|
if (!ready(context)) return context.getString(R.string.flatpakmgr_not_ready)
|
||||||
|
return exclusive("$verb:${id ?: "all"}", { context.getString(R.string.flatpakmgr_busy) }) {
|
||||||
var error: String? = null
|
var error: String? = null
|
||||||
// Progress lines carry no ref; they belong to the step the last "op" line started.
|
// Progress lines carry no ref; they belong to the step the last "op" line started.
|
||||||
var step = "Starting"
|
var step = context.getString(R.string.flatpakmgr_starting)
|
||||||
val argv = listOfNotNull("/usr/bin/python3", HELPER, verb, id)
|
val argv = listOfNotNull("/usr/bin/python3", HELPER, verb, id)
|
||||||
val status = runGuest(context, argv, fakeRoot = false) { line ->
|
val status = runGuest(context, argv, fakeRoot = false) { line ->
|
||||||
val o = runCatching { JSONObject(line) }.getOrNull()
|
val o = runCatching { JSONObject(line) }.getOrNull()
|
||||||
if (o == null) { Log.i(TAG, "$verb: $line"); return@runGuest }
|
if (o == null) { Log.i(TAG, "$verb: $line"); return@runGuest }
|
||||||
when (o.optString("e")) {
|
when (o.optString("e")) {
|
||||||
"op" -> { step = stage(o); onProgress(step, overall(o, 0)) }
|
"op" -> { step = stage(context, o); onProgress(step, overall(o, 0)) }
|
||||||
"progress" -> onProgress(step, overall(o, o.optInt("percent")))
|
"progress" -> onProgress(step, overall(o, o.optInt("percent")))
|
||||||
"error" -> { error = o.optString("message"); Log.w(TAG, "$verb $id: $error") }
|
"error" -> { error = o.optString("message"); Log.w(TAG, "$verb $id: $error") }
|
||||||
"warning" -> Log.w(TAG, "$verb $id: ${o.optString("message")}")
|
"warning" -> Log.w(TAG, "$verb $id: ${o.optString("message")}")
|
||||||
|
"done" -> onDone(o)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
error ?: if (status != 0) "Flatpak exited with status $status" else null
|
error ?: if (status != 0) context.getString(R.string.flatpakmgr_exit_status, status) else null
|
||||||
} ?: "Another store task is running"
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun stage(o: JSONObject): String {
|
private fun stage(context: Context, o: JSONObject): String {
|
||||||
val ref = o.optString("ref")
|
val ref = o.optString("ref")
|
||||||
val name = refLabel(ref)
|
if (ref.isEmpty()) return o.optString("status").ifEmpty { context.getString(R.string.setup_check_busy) }
|
||||||
val step = if (o.optInt("n") > 1) " (${o.optInt("i")}/${o.optInt("n")})" else ""
|
val name = refLabel(ref) { id, args -> context.getString(id, *args) }
|
||||||
return when (o.optString("kind")) {
|
val n = o.optInt("n")
|
||||||
"uninstall" -> "Removing $name$step"
|
val kind = o.optString("kind")
|
||||||
"update" -> "Updating $name$step"
|
return if (n > 1) context.getString(when (kind) {
|
||||||
else -> "Installing $name$step"
|
"uninstall" -> R.string.flatpakmgr_removing_step
|
||||||
}.let { if (ref.isEmpty()) o.optString("status").ifEmpty { "Working" } else it }
|
"update" -> R.string.flatpakmgr_updating_step
|
||||||
|
else -> R.string.flatpakmgr_installing_step
|
||||||
|
}, name, o.optInt("i"), n)
|
||||||
|
else context.getString(when (kind) {
|
||||||
|
"uninstall" -> R.string.flatpakmgr_removing
|
||||||
|
"update" -> R.string.flatpakmgr_updating
|
||||||
|
else -> R.string.flatpakmgr_installing
|
||||||
|
}, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A ref in words: "app/org.supertuxproject.SuperTux/aarch64/stable" is "SuperTux". */
|
/**
|
||||||
internal fun refLabel(ref: String): String {
|
* A ref in words: "app/org.supertuxproject.SuperTux/aarch64/stable" is "SuperTux". [text]
|
||||||
|
* resolves a string resource with its arguments.
|
||||||
|
*/
|
||||||
|
internal fun refLabel(ref: String, text: (Int, Array<out Any>) -> String): String {
|
||||||
val parts = ref.split('/')
|
val parts = ref.split('/')
|
||||||
val id = parts.getOrNull(1) ?: return ref
|
val id = parts.getOrNull(1) ?: return ref
|
||||||
if (parts.firstOrNull() == "app") return id.substringAfterLast('.')
|
if (parts.firstOrNull() == "app") return id.substringAfterLast('.')
|
||||||
val branch = parts.getOrNull(3)?.let { " $it" } ?: ""
|
val branch = parts.getOrNull(3)
|
||||||
return when {
|
return when {
|
||||||
id.endsWith(".Locale") -> "translations"
|
id.endsWith(".Locale") -> text(R.string.flatpakmgr_ref_translations, emptyArray())
|
||||||
".GL." in id || ".GL32." in id -> "graphics drivers"
|
".GL." in id || ".GL32." in id -> text(R.string.flatpakmgr_ref_graphics_drivers, emptyArray())
|
||||||
"codecs" in id.lowercase() || id.endsWith(".ffmpeg-full") -> "media codecs"
|
"codecs" in id.lowercase() || id.endsWith(".ffmpeg-full") -> text(R.string.flatpakmgr_ref_media_codecs, emptyArray())
|
||||||
id.endsWith(".Platform") -> when (val vendor = id.removeSuffix(".Platform").substringAfterLast('.')) {
|
id.endsWith(".Platform") -> when (val vendor = id.removeSuffix(".Platform").substringAfterLast('.')) {
|
||||||
"gnome", "kde" -> vendor.uppercase()
|
"gnome", "kde" -> vendor.uppercase()
|
||||||
else -> vendor.replaceFirstChar { it.uppercase() }
|
else -> vendor.replaceFirstChar { it.uppercase() }
|
||||||
} + " runtime$branch"
|
}.let { if (branch != null) text(R.string.flatpakmgr_ref_runtime_branch, arrayOf(it, branch)) else text(R.string.flatpakmgr_ref_runtime, arrayOf(it)) }
|
||||||
else -> id.substringAfterLast('.')
|
else -> id.substringAfterLast('.')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -184,13 +199,20 @@ object FlatpakManager {
|
|||||||
|
|
||||||
fun install(context: Context, id: String, onProgress: (String, Int) -> Unit) = transaction(context, "install", id, onProgress)
|
fun install(context: Context, id: String, onProgress: (String, Int) -> Unit) = transaction(context, "install", id, onProgress)
|
||||||
fun uninstall(context: Context, id: String, onProgress: (String, Int) -> Unit) = transaction(context, "uninstall", id, onProgress)
|
fun uninstall(context: Context, id: String, onProgress: (String, Int) -> Unit) = transaction(context, "uninstall", id, onProgress)
|
||||||
|
|
||||||
|
/** Installs the .flatpak bundle at [guestPath], its runtimes from Flathub: the app's ID, and what went wrong if anything. */
|
||||||
|
fun installBundle(context: Context, guestPath: String, onProgress: (String, Int) -> Unit): Pair<String?, String?> {
|
||||||
|
var id: String? = null
|
||||||
|
val problem = transaction(context, "install-bundle", guestPath, onProgress) { id = it.optString("id").ifEmpty { null } }
|
||||||
|
return id to problem
|
||||||
|
}
|
||||||
fun update(context: Context, id: String?, onProgress: (String, Int) -> Unit) = transaction(context, "update", id, onProgress)
|
fun update(context: Context, id: String?, onProgress: (String, Int) -> Unit) = transaction(context, "update", id, onProgress)
|
||||||
|
|
||||||
/** Installed apps with an update on Flathub, or null when that could not be checked. */
|
/** Installed apps with an update on Flathub, or null when that could not be checked. */
|
||||||
fun updates(context: Context): Set<String>? {
|
fun updates(context: Context): Set<String>? {
|
||||||
if (!ready(context)) return emptySet()
|
if (!ready(context)) return emptySet()
|
||||||
var apps: Set<String>? = null
|
var apps: Set<String>? = null
|
||||||
exclusive("updates") {
|
exclusive("updates", {}) {
|
||||||
runGuest(context, listOf("/usr/bin/python3", HELPER, "updates"), fakeRoot = false) { line ->
|
runGuest(context, listOf("/usr/bin/python3", HELPER, "updates"), fakeRoot = false) { line ->
|
||||||
val o = runCatching { JSONObject(line) }.getOrNull() ?: return@runGuest
|
val o = runCatching { JSONObject(line) }.getOrNull() ?: return@runGuest
|
||||||
if (o.optString("e") == "updates") {
|
if (o.optString("e") == "updates") {
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ public final class LinuxRuntime {
|
|||||||
* session ended at once. A long host path behind it is proot's to shorten.
|
* session ended at once. A long host path behind it is proot's to shorten.
|
||||||
*/
|
*/
|
||||||
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
|
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
|
||||||
|
private static final String SYSTEM_FONTS = "/system/fonts";
|
||||||
|
private static final String GUEST_SYSTEM_FONTS = "/usr/local/share/fonts/android";
|
||||||
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
|
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
|
||||||
public static final String DEBUG_LOG_DIR = "DroidDeck";
|
public static final String DEBUG_LOG_DIR = "DroidDeck";
|
||||||
|
|
||||||
@@ -207,6 +209,7 @@ public final class LinuxRuntime {
|
|||||||
File shm = new File(context.getCacheDir(), "shm");
|
File shm = new File(context.getCacheDir(), "shm");
|
||||||
shm.mkdirs();
|
shm.mkdirs();
|
||||||
bind(cmd, shm.getPath() + ":/dev/shm");
|
bind(cmd, shm.getPath() + ":/dev/shm");
|
||||||
|
bindSystemFonts(cmd, root);
|
||||||
|
|
||||||
// Android denies apps these; glibc, Steam and libcap read them at startup.
|
// Android denies apps these; glibc, Steam and libcap read them at startup.
|
||||||
File fakeProc = new File(root, "etc/droiddeck/proc");
|
File fakeProc = new File(root, "etc/droiddeck/proc");
|
||||||
@@ -465,6 +468,15 @@ public final class LinuxRuntime {
|
|||||||
return byType;
|
return byType;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void bindSystemFonts(List<String> cmd, File root) {
|
||||||
|
File fonts = new File(SYSTEM_FONTS);
|
||||||
|
File target = new File(root, GUEST_SYSTEM_FONTS.substring(1));
|
||||||
|
if (!fonts.isDirectory() || !fonts.canRead() || !new File(root, "usr/local").isDirectory()) return;
|
||||||
|
if (target.isDirectory() || target.mkdirs()) {
|
||||||
|
bind(cmd, SYSTEM_FONTS + ":" + GUEST_SYSTEM_FONTS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static void bind(List<String> cmd, String spec) {
|
private static void bind(List<String> cmd, String spec) {
|
||||||
cmd.add("-b");
|
cmd.add("-b");
|
||||||
cmd.add(spec);
|
cmd.add(spec);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import android.content.Context;
|
|||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.R;
|
||||||
import com.droiddeck.launcher.core.ArchivePaths;
|
import com.droiddeck.launcher.core.ArchivePaths;
|
||||||
import com.droiddeck.launcher.core.Downloader;
|
import com.droiddeck.launcher.core.Downloader;
|
||||||
import com.droiddeck.launcher.core.Hashes;
|
import com.droiddeck.launcher.core.Hashes;
|
||||||
@@ -44,9 +45,17 @@ public final class LinuxRuntimeInstaller {
|
|||||||
|
|
||||||
private static final String VERSION_FILE = ".version";
|
private static final String VERSION_FILE = ".version";
|
||||||
|
|
||||||
|
/** What a stage is doing, for code that branches on it rather than on its (translated) words. */
|
||||||
|
public enum Step { DOWNLOADING, VERIFYING, OTHER }
|
||||||
|
|
||||||
public interface ProgressListener {
|
public interface ProgressListener {
|
||||||
/** {@code percent} is -1 while the size is unknown. */
|
/** {@code percent} is -1 while the size is unknown. */
|
||||||
void onProgress(String stage, int percent);
|
void onProgress(String stage, int percent);
|
||||||
|
|
||||||
|
/** The same with its {@link Step}; a listener that branches on the step overrides this one. */
|
||||||
|
default void onProgress(Step step, String stage, int percent) {
|
||||||
|
onProgress(stage, percent);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final class Release {
|
public static final class Release {
|
||||||
@@ -71,11 +80,12 @@ public final class LinuxRuntimeInstaller {
|
|||||||
private static final class Job {
|
private static final class Job {
|
||||||
final CopyOnWriteArrayList<ProgressListener> listeners = new CopyOnWriteArrayList<>();
|
final CopyOnWriteArrayList<ProgressListener> listeners = new CopyOnWriteArrayList<>();
|
||||||
final CountDownLatch done = new CountDownLatch(1);
|
final CountDownLatch done = new CountDownLatch(1);
|
||||||
volatile String stage = "Starting\u2026";
|
volatile String stage;
|
||||||
|
volatile Step step = Step.OTHER;
|
||||||
volatile int percent = -1;
|
volatile int percent = -1;
|
||||||
volatile boolean ok;
|
volatile boolean ok;
|
||||||
final boolean removal;
|
final boolean removal;
|
||||||
Job(boolean removal) { this.removal = removal; }
|
Job(boolean removal, String stage) { this.removal = removal; this.stage = stage; }
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final Object JOB_LOCK = new Object();
|
private static final Object JOB_LOCK = new Object();
|
||||||
@@ -131,16 +141,23 @@ public final class LinuxRuntimeInstaller {
|
|||||||
synchronized (JOB_LOCK) {
|
synchronized (JOB_LOCK) {
|
||||||
if (running != null && running.removal) return false;
|
if (running != null && running.removal) return false;
|
||||||
owner = running == null;
|
owner = running == null;
|
||||||
if (owner) { running = new Job(false); removalError = null; }
|
if (owner) { running = new Job(false, context.getString(R.string.user_apps_starting)); removalError = null; }
|
||||||
job = running;
|
job = running;
|
||||||
if (listener != null) job.listeners.add(listener);
|
if (listener != null) job.listeners.add(listener);
|
||||||
}
|
}
|
||||||
if (!owner) return join(job, listener);
|
if (!owner) return join(job, listener);
|
||||||
try {
|
try {
|
||||||
job.ok = installOnce(context.getApplicationContext(), release, (stage, percent) -> {
|
job.ok = installOnce(context.getApplicationContext(), release, new ProgressListener() {
|
||||||
job.stage = stage;
|
@Override public void onProgress(String stage, int percent) {
|
||||||
job.percent = percent;
|
onProgress(Step.OTHER, stage, percent);
|
||||||
for (ProgressListener l : job.listeners) l.onProgress(stage, percent);
|
}
|
||||||
|
|
||||||
|
@Override public void onProgress(Step step, String stage, int percent) {
|
||||||
|
job.step = step;
|
||||||
|
job.stage = stage;
|
||||||
|
job.percent = percent;
|
||||||
|
for (ProgressListener l : job.listeners) l.onProgress(step, stage, percent);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
return job.ok;
|
return job.ok;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -192,7 +209,7 @@ public final class LinuxRuntimeInstaller {
|
|||||||
|
|
||||||
private static boolean join(Job job, ProgressListener listener) {
|
private static boolean join(Job job, ProgressListener listener) {
|
||||||
try {
|
try {
|
||||||
if (listener != null) listener.onProgress(job.stage, job.percent);
|
if (listener != null) listener.onProgress(job.step, job.stage, job.percent);
|
||||||
job.done.await();
|
job.done.await();
|
||||||
return job.ok;
|
return job.ok;
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
@@ -209,13 +226,15 @@ public final class LinuxRuntimeInstaller {
|
|||||||
// A failed/interrupted explicit removal must finish before a fresh installation.
|
// A failed/interrupted explicit removal must finish before a fresh installation.
|
||||||
// Its quarantined home is not user data to carry into an update.
|
// Its quarantined home is not user data to carry into an update.
|
||||||
File pendingRemoval = removalDirectory(LinuxRuntime.rootDir(context));
|
File pendingRemoval = removalDirectory(LinuxRuntime.rootDir(context));
|
||||||
if (pendingRemoval.exists() && listener != null) listener.onProgress("Removing runtime leftovers", -1);
|
if (pendingRemoval.exists() && listener != null) listener.onProgress(context.getString(R.string.rtinst_removing_leftovers), -1);
|
||||||
RuntimeFileTree.delete(pendingRemoval, null);
|
if (!discard(pendingRemoval, null)) throw new IOException("Cannot clear the previous runtime: " + pendingRemoval);
|
||||||
if (listener != null) listener.onProgress("Downloading", 0);
|
emptyTrash(LinuxRuntime.rootDir(context).getParentFile());
|
||||||
|
String downloading = context.getString(R.string.rtinst_downloading);
|
||||||
|
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
|
||||||
// Downloader reports a 0..1 fraction, or -1 while the total size is unknown.
|
// Downloader reports a 0..1 fraction, or -1 while the total size is unknown.
|
||||||
boolean ok = Downloader.downloadFile(release.url, archive, true, (fraction) -> {
|
boolean ok = Downloader.downloadFile(release.url, archive, true, (fraction) -> {
|
||||||
if (listener != null) {
|
if (listener != null) {
|
||||||
listener.onProgress("Downloading",
|
listener.onProgress(Step.DOWNLOADING, downloading,
|
||||||
fraction < 0 ? -1 : Math.round(fraction * 100f));
|
fraction < 0 ? -1 : Math.round(fraction * 100f));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -224,7 +243,7 @@ public final class LinuxRuntimeInstaller {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (listener != null) listener.onProgress("Verifying", -1);
|
if (listener != null) listener.onProgress(Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1);
|
||||||
String actual = Hashes.sha256(archive);
|
String actual = Hashes.sha256(archive);
|
||||||
if (!release.sha256.equalsIgnoreCase(actual)) {
|
if (!release.sha256.equalsIgnoreCase(actual)) {
|
||||||
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
|
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
|
||||||
@@ -237,16 +256,18 @@ public final class LinuxRuntimeInstaller {
|
|||||||
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
|
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
|
||||||
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
|
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
|
||||||
recoverInterruptedSwap(root, staging, old);
|
recoverInterruptedSwap(root, staging, old);
|
||||||
RuntimeFileTree.delete(staging, null);
|
if (!discard(staging, null) || !staging.mkdirs()) return false;
|
||||||
if (!staging.mkdirs()) return false;
|
if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1);
|
||||||
if (listener != null) listener.onProgress("Extracting", -1);
|
if (!extract(context, archive, staging, listener)) {
|
||||||
if (!extract(archive, staging, listener)) {
|
|
||||||
RuntimeFileTree.delete(staging, null);
|
RuntimeFileTree.delete(staging, null);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
|
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
|
||||||
|
|
||||||
RuntimeFileTree.delete(old, null);
|
if (!discard(old, null)) {
|
||||||
|
discard(staging, null);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if (root.isDirectory() && !root.renameTo(old)) {
|
if (root.isDirectory() && !root.renameTo(old)) {
|
||||||
RuntimeFileTree.delete(staging, null);
|
RuntimeFileTree.delete(staging, null);
|
||||||
return false;
|
return false;
|
||||||
@@ -274,7 +295,7 @@ public final class LinuxRuntimeInstaller {
|
|||||||
if (old.isDirectory()) old.renameTo(root);
|
if (old.isDirectory()) old.renameTo(root);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
RuntimeFileTree.delete(old, null);
|
discard(old, null);
|
||||||
return LinuxRuntime.isInstalled(context);
|
return LinuxRuntime.isInstalled(context);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Log.e(TAG, "install", e);
|
Log.e(TAG, "install", e);
|
||||||
@@ -297,6 +318,35 @@ public final class LinuxRuntimeInstaller {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Where entries the app cannot unlink are set aside, out of the way of the runtime's names. */
|
||||||
|
static final String TRASH = ".runtime-trash";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets {@code tree} out from under its name. What can be deleted is; if something inside
|
||||||
|
* cannot be (a file made by root or {@code su} carries another SELinux category, and the app
|
||||||
|
* may not unlink it), the remainder is moved aside into {@link #TRASH} instead of blocking
|
||||||
|
* every later install and removal on it. False only when even that move is refused.
|
||||||
|
*/
|
||||||
|
static boolean discard(File tree, java.util.function.LongConsumer progress) {
|
||||||
|
if (RuntimeFileTree.deleteWhatCan(tree, progress)) return true;
|
||||||
|
File trash = new File(tree.getParentFile(), TRASH);
|
||||||
|
trash.mkdirs();
|
||||||
|
File aside = new File(trash, tree.getName() + "-" + System.currentTimeMillis());
|
||||||
|
if (tree.renameTo(aside)) {
|
||||||
|
Log.w(TAG, "could not delete all of " + tree + "; set the rest aside in " + aside);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
Log.w(TAG, "could not delete or set aside " + tree);
|
||||||
|
return !tree.exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Another try at what {@link #discard} set aside. Whatever still cannot go stays there. */
|
||||||
|
static void emptyTrash(File parent) {
|
||||||
|
File trash = new File(parent, TRASH);
|
||||||
|
if (trash.exists() && !RuntimeFileTree.deleteWhatCan(trash, null))
|
||||||
|
Log.i(TAG, "some runtime leftovers still cannot be deleted: " + trash);
|
||||||
|
}
|
||||||
|
|
||||||
private static boolean isEmptyDir(File dir) {
|
private static boolean isEmptyDir(File dir) {
|
||||||
String[] names = dir.list();
|
String[] names = dir.list();
|
||||||
return dir.isDirectory() && names != null && names.length == 0;
|
return dir.isDirectory() && names != null && names.length == 0;
|
||||||
@@ -307,30 +357,35 @@ public final class LinuxRuntimeInstaller {
|
|||||||
if (com.droiddeck.launcher.session.SessionState.INSTANCE.getRunning()) return null;
|
if (com.droiddeck.launcher.session.SessionState.INSTANCE.getRunning()) return null;
|
||||||
com.droiddeck.launcher.session.SessionPhase phase = com.droiddeck.launcher.session.SessionState.INSTANCE.getPhase();
|
com.droiddeck.launcher.session.SessionPhase phase = com.droiddeck.launcher.session.SessionState.INSTANCE.getPhase();
|
||||||
if (phase != com.droiddeck.launcher.session.SessionPhase.IDLE && phase != com.droiddeck.launcher.session.SessionPhase.FAILED) return null;
|
if (phase != com.droiddeck.launcher.session.SessionPhase.IDLE && phase != com.droiddeck.launcher.session.SessionPhase.FAILED) return null;
|
||||||
return beginUninstall(LinuxRuntime.rootDir(context));
|
return beginUninstall(context.getApplicationContext(), LinuxRuntime.rootDir(context));
|
||||||
}
|
}
|
||||||
|
|
||||||
static Removal beginUninstall(File root) {
|
/** {@code app} words the progress; unit tests pass null and get none. */
|
||||||
|
static Removal beginUninstall(Context app, File root) {
|
||||||
synchronized (JOB_LOCK) {
|
synchronized (JOB_LOCK) {
|
||||||
if (running != null) return null;
|
if (running != null) return null;
|
||||||
removalError = null;
|
removalError = null;
|
||||||
running = new Job(true);
|
running = new Job(true, text(app, R.string.rtinst_removing));
|
||||||
running.stage = "Removing Linux runtime";
|
return new Removal(app, root, running);
|
||||||
return new Removal(root, running);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String text(Context app, int id) {
|
||||||
|
return app == null ? "" : app.getString(id);
|
||||||
|
}
|
||||||
|
|
||||||
public static final class Removal {
|
public static final class Removal {
|
||||||
|
private final Context app;
|
||||||
private final File root;
|
private final File root;
|
||||||
private final Job job;
|
private final Job job;
|
||||||
private final java.util.concurrent.atomic.AtomicBoolean started = new java.util.concurrent.atomic.AtomicBoolean();
|
private final java.util.concurrent.atomic.AtomicBoolean started = new java.util.concurrent.atomic.AtomicBoolean();
|
||||||
private Removal(File root, Job job) { this.root = root; this.job = job; }
|
private Removal(Context app, File root, Job job) { this.app = app; this.root = root; this.job = job; }
|
||||||
|
|
||||||
public boolean run(ProgressListener listener) {
|
public boolean run(ProgressListener listener) {
|
||||||
if (!started.compareAndSet(false, true)) return join(job, listener);
|
if (!started.compareAndSet(false, true)) return join(job, listener);
|
||||||
if (listener != null) job.listeners.add(listener);
|
if (listener != null) job.listeners.add(listener);
|
||||||
try {
|
try {
|
||||||
report("Removing Linux runtime", -1);
|
report(text(app, R.string.rtinst_removing), -1);
|
||||||
final long[] removed = {0};
|
final long[] removed = {0};
|
||||||
final long[] lastShown = {0};
|
final long[] lastShown = {0};
|
||||||
java.util.function.LongConsumer progress = ignored -> {
|
java.util.function.LongConsumer progress = ignored -> {
|
||||||
@@ -338,27 +393,34 @@ public final class LinuxRuntimeInstaller {
|
|||||||
long now = System.nanoTime();
|
long now = System.nanoTime();
|
||||||
if (removed[0] == 1 || now - lastShown[0] >= 200_000_000L) {
|
if (removed[0] == 1 || now - lastShown[0] >= 200_000_000L) {
|
||||||
lastShown[0] = now;
|
lastShown[0] = now;
|
||||||
report("Removing Linux runtime · " + removed[0] + " entries", -1);
|
report(app == null ? "" : app.getResources().getQuantityString(
|
||||||
|
R.plurals.rtinst_removing_entries, (int) Math.min(removed[0], Integer.MAX_VALUE), removed[0]), -1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
File pending = removalDirectory(root);
|
File pending = removalDirectory(root);
|
||||||
// Invalidate the installation before traversing it. A process killed halfway
|
// Invalidate the installation before traversing it. A process killed halfway
|
||||||
// through leaves a named removal to resume, never a launchable partial runtime.
|
// through leaves a named removal to resume, never a launchable partial runtime.
|
||||||
if (root.exists()) {
|
if (root.exists()) {
|
||||||
RuntimeFileTree.delete(pending, progress);
|
if (!discard(pending, progress) || !root.renameTo(pending))
|
||||||
if (!root.renameTo(pending)) throw new IOException("Cannot prepare the runtime for removal");
|
throw new IOException("Cannot prepare the runtime for removal");
|
||||||
} else if (!pending.isDirectory() && !pending.mkdirs()) {
|
} else if (!pending.isDirectory() && !pending.mkdirs()) {
|
||||||
throw new IOException("Cannot prepare the runtime for removal");
|
throw new IOException("Cannot prepare the runtime for removal");
|
||||||
}
|
}
|
||||||
// Keep the quarantine until all leftovers are gone, so a failure stays retryable.
|
// Keep the quarantine until all leftovers are gone, so a failure stays retryable.
|
||||||
RuntimeFileTree.delete(new File(root.getParentFile(), root.getName() + ".new"), progress);
|
// An entry the app may not delete is set aside rather than failing the removal:
|
||||||
RuntimeFileTree.delete(new File(root.getParentFile(), root.getName() + ".old"), progress);
|
// a quarantine that can never clear would block reinstalling for good.
|
||||||
RuntimeFileTree.delete(pending, progress);
|
for (File leftover : new File[]{
|
||||||
|
new File(root.getParentFile(), root.getName() + ".new"),
|
||||||
|
new File(root.getParentFile(), root.getName() + ".old"),
|
||||||
|
pending}) {
|
||||||
|
if (!discard(leftover, progress)) throw new IOException("Cannot remove " + leftover);
|
||||||
|
}
|
||||||
|
emptyTrash(root.getParentFile());
|
||||||
job.ok = true;
|
job.ok = true;
|
||||||
report("Linux runtime removed", 100);
|
report(text(app, R.string.rtinst_removed), 100);
|
||||||
return true;
|
return true;
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
removalError = "Could not finish removing the Linux runtime. Retry removal in Setup.";
|
removalError = text(app, R.string.rtinst_removal_failed);
|
||||||
Log.w(TAG, "runtime removal incomplete", e);
|
Log.w(TAG, "runtime removal incomplete", e);
|
||||||
report(removalError, -1);
|
report(removalError, -1);
|
||||||
return false;
|
return false;
|
||||||
@@ -380,8 +442,9 @@ public final class LinuxRuntimeInstaller {
|
|||||||
* empty file instead of its link target is a rootfs that boots to nothing. Symlinks, hard
|
* empty file instead of its link target is a rootfs that boots to nothing. Symlinks, hard
|
||||||
* links and the executable bit are all carried over here.
|
* links and the executable bit are all carried over here.
|
||||||
*/
|
*/
|
||||||
public static boolean extract(File archive, File destination, ProgressListener listener) {
|
public static boolean extract(Context context, File archive, File destination, ProgressListener listener) {
|
||||||
long entries = 0;
|
long entries = 0;
|
||||||
|
String extracting = context.getString(R.string.rtinst_extracting);
|
||||||
try (InputStream in = new ZstdCompressorInputStream(
|
try (InputStream in = new ZstdCompressorInputStream(
|
||||||
new BufferedInputStream(new FileInputStream(archive), 1 << 16));
|
new BufferedInputStream(new FileInputStream(archive), 1 << 16));
|
||||||
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
||||||
@@ -432,7 +495,7 @@ public final class LinuxRuntimeInstaller {
|
|||||||
continue; // device nodes and fifos: the runtime binds the real ones
|
continue; // device nodes and fifos: the runtime binds the real ones
|
||||||
}
|
}
|
||||||
if (++entries % 2000 == 0 && listener != null) {
|
if (++entries % 2000 == 0 && listener != null) {
|
||||||
listener.onProgress("Extracting", -1);
|
listener.onProgress(extracting, -1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -21,13 +21,22 @@ import java.security.MessageDigest
|
|||||||
*/
|
*/
|
||||||
object ProotFastPath {
|
object ProotFastPath {
|
||||||
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
|
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
|
||||||
|
/** MAX_BINDS in fastpath.c: past it the library turns itself off, so the session keeps it off. */
|
||||||
|
const val MAX_BINDS = 256
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Only the app's own proot (libproot.so, built with patches/0014) lets the trampoline through.
|
||||||
|
* The runtime's fallback copy (LinuxRuntime.prootBinary) is Termux's, which traps those calls
|
||||||
|
* too and translates their host paths a second time: every lookup then fails inside the
|
||||||
|
* process and goes to proot anyway, paying for both.
|
||||||
|
*/
|
||||||
fun enabled(context: Context): Boolean =
|
fun enabled(context: Context): Boolean =
|
||||||
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context)
|
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context) &&
|
||||||
|
LinuxRuntime.prootBinary(context).parent == context.applicationInfo.nativeLibraryDir
|
||||||
|
|
||||||
/** The key for this rootfs and these binds, or null when the library cannot be told them. */
|
/** The key for this rootfs and these binds, or null when the library cannot be told them. */
|
||||||
fun key(root: File, binds: List<String>): String? {
|
fun key(root: File, binds: List<String>): String? {
|
||||||
if (binds.any { it.contains('|') } || root.path.contains('|')) return null
|
if (binds.size > MAX_BINDS || binds.any { it.contains('|') } || root.path.contains('|')) return null
|
||||||
val digest = MessageDigest.getInstance("SHA-256")
|
val digest = MessageDigest.getInstance("SHA-256")
|
||||||
.digest((root.path + "\n" + binds.joinToString("\n")).toByteArray())
|
.digest((root.path + "\n" + binds.joinToString("\n")).toByteArray())
|
||||||
return digest.take(12).joinToString("") { "%02x".format(it) }
|
return digest.take(12).joinToString("") { "%02x".format(it) }
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.runtime;
|
|||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.nio.file.AccessDeniedException;
|
||||||
import java.nio.file.DirectoryStream;
|
import java.nio.file.DirectoryStream;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.LinkOption;
|
import java.nio.file.LinkOption;
|
||||||
@@ -9,11 +10,15 @@ import java.nio.file.NoSuchFileException;
|
|||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.attribute.BasicFileAttributes;
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
import java.util.function.LongConsumer;
|
import java.util.function.LongConsumer;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
/** Checked removal of an app-owned runtime tree, including read-only directories. */
|
/** Checked removal of an app-owned runtime tree, including read-only directories. */
|
||||||
final class RuntimeFileTree {
|
final class RuntimeFileTree {
|
||||||
private RuntimeFileTree() {}
|
private RuntimeFileTree() {}
|
||||||
|
|
||||||
|
/** Unit tests stand in for an entry the app cannot unlink (a file another SELinux user made). */
|
||||||
|
static volatile Predicate<Path> refuseForTest;
|
||||||
|
|
||||||
static void delete(File root, LongConsumer progress) throws IOException {
|
static void delete(File root, LongConsumer progress) throws IOException {
|
||||||
delete(root.toPath(), progress, new long[]{0});
|
delete(root.toPath(), progress, new long[]{0});
|
||||||
}
|
}
|
||||||
@@ -30,10 +35,48 @@ final class RuntimeFileTree {
|
|||||||
for (Path child : children) delete(child, progress, removed);
|
for (Path child : children) delete(child, progress, removed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Files.delete(path);
|
unlink(path);
|
||||||
if (progress != null) progress.accept(++removed[0]);
|
if (progress != null) progress.accept(++removed[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes what it can of {@code root} and carries on past entries it cannot, rather than
|
||||||
|
* stopping at the first. Returns true when nothing is left.
|
||||||
|
*/
|
||||||
|
static boolean deleteWhatCan(File root, LongConsumer progress) {
|
||||||
|
return deleteWhatCan(root.toPath(), progress, new long[]{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean deleteWhatCan(Path path, LongConsumer progress, long[] removed) {
|
||||||
|
BasicFileAttributes attrs;
|
||||||
|
try { attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); }
|
||||||
|
catch (NoSuchFileException e) { return true; }
|
||||||
|
catch (IOException e) { return false; }
|
||||||
|
boolean emptied = true;
|
||||||
|
if (attrs.isDirectory()) {
|
||||||
|
try {
|
||||||
|
makeWritable(path.toFile());
|
||||||
|
try (DirectoryStream<Path> children = Files.newDirectoryStream(path)) {
|
||||||
|
for (Path child : children) emptied &= deleteWhatCan(child, progress, removed);
|
||||||
|
}
|
||||||
|
} catch (IOException | RuntimeException e) {
|
||||||
|
emptied = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!emptied) return false;
|
||||||
|
try { unlink(path); }
|
||||||
|
catch (NoSuchFileException e) { return true; }
|
||||||
|
catch (IOException e) { return false; }
|
||||||
|
if (progress != null) progress.accept(++removed[0]);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void unlink(Path path) throws IOException {
|
||||||
|
Predicate<Path> refuse = refuseForTest;
|
||||||
|
if (refuse != null && refuse.test(path)) throw new AccessDeniedException(path.toString());
|
||||||
|
Files.delete(path);
|
||||||
|
}
|
||||||
|
|
||||||
private static void makeWritable(File dir) throws IOException {
|
private static void makeWritable(File dir) throws IOException {
|
||||||
if (!dir.setReadable(true, true) || !dir.setWritable(true, true) || !dir.setExecutable(true, true))
|
if (!dir.setReadable(true, true) || !dir.setWritable(true, true) || !dir.setExecutable(true, true))
|
||||||
throw new IOException("Cannot make directory removable: " + dir);
|
throw new IOException("Cannot make directory removable: " + dir);
|
||||||
|
|||||||
@@ -22,12 +22,15 @@ import com.droiddeck.launcher.R
|
|||||||
* two gets there first.
|
* two gets there first.
|
||||||
*/
|
*/
|
||||||
class RuntimeInstallService : Service() {
|
class RuntimeInstallService : Service() {
|
||||||
|
override fun attachBaseContext(newBase: android.content.Context) =
|
||||||
|
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(newBase))
|
||||||
|
|
||||||
override fun onBind(intent: Intent?): IBinder? = null
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
val removal = intent?.action == ACTION_REMOVE
|
val removal = intent?.action == ACTION_REMOVE
|
||||||
val release = intent?.let(::releaseFrom)
|
val release = intent?.let(::releaseFrom)
|
||||||
startForeground(NOTIFICATION_ID, notification(if (removal) "Removing Linux runtime" else "Starting…", -1))
|
startForeground(NOTIFICATION_ID, notification(getString(if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
|
||||||
if (release == null && !removal) {
|
if (release == null && !removal) {
|
||||||
stopSelf(startId)
|
stopSelf(startId)
|
||||||
return START_NOT_STICKY
|
return START_NOT_STICKY
|
||||||
@@ -53,9 +56,9 @@ class RuntimeInstallService : Service() {
|
|||||||
|
|
||||||
private fun notification(stage: String, percent: Int): Notification {
|
private fun notification(stage: String, percent: Int): Notification {
|
||||||
val manager = getSystemService(NotificationManager::class.java)
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Linux runtime",
|
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime),
|
||||||
NotificationManager.IMPORTANCE_LOW).apply {
|
NotificationManager.IMPORTANCE_LOW).apply {
|
||||||
description = "Shows while the Linux runtime is installed or removed"
|
description = getString(R.string.rtinst_channel_description)
|
||||||
setShowBadge(false)
|
setShowBadge(false)
|
||||||
setSound(null, null)
|
setSound(null, null)
|
||||||
enableVibration(false)
|
enableVibration(false)
|
||||||
@@ -65,7 +68,7 @@ class RuntimeInstallService : Service() {
|
|||||||
PendingIntent.FLAG_IMMUTABLE)
|
PendingIntent.FLAG_IMMUTABLE)
|
||||||
return Notification.Builder(this, CHANNEL_ID)
|
return Notification.Builder(this, CHANNEL_ID)
|
||||||
.setSmallIcon(R.drawable.ic_stat_session)
|
.setSmallIcon(R.drawable.ic_stat_session)
|
||||||
.setContentTitle(if (LinuxRuntimeInstaller.isRemoving()) "Removing the Linux runtime" else "Installing the Linux runtime")
|
.setContentTitle(getString(if (LinuxRuntimeInstaller.isRemoving()) R.string.rtinst_title_removing else R.string.rtinst_title_installing))
|
||||||
.setContentText(stage)
|
.setContentText(stage)
|
||||||
.setProgress(100, percent.coerceIn(0, 100), percent < 0)
|
.setProgress(100, percent.coerceIn(0, 100), percent < 0)
|
||||||
.setContentIntent(open)
|
.setContentIntent(open)
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ object UserApps {
|
|||||||
class AppImage(val file: File) : Source()
|
class AppImage(val file: File) : Source()
|
||||||
class GitHub(val repo: String) : Source()
|
class GitHub(val repo: String) : Source()
|
||||||
class Flatpak(val id: String) : Source()
|
class Flatpak(val id: String) : Source()
|
||||||
|
class FlatpakBundle(val file: File) : Source()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** [icon]: a picked file's path or a suggested icon's URL. */
|
/** [icon]: a picked file's path or a suggested icon's URL. */
|
||||||
@@ -124,6 +125,7 @@ object UserApps {
|
|||||||
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon) { onProgress(it, -1) }
|
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon) { onProgress(it, -1) }
|
||||||
is Source.GitHub -> addFromGitHub(context, s.repo, name, icon, onProgress)
|
is Source.GitHub -> addFromGitHub(context, s.repo, name, icon, onProgress)
|
||||||
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
|
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
|
||||||
|
is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -422,9 +424,36 @@ object UserApps {
|
|||||||
private fun addFlatpak(context: Context, id: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
private fun addFlatpak(context: Context, id: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
||||||
if (!FlatpakManager.ready(context)) FlatpakManager.setup(context, onProgress)?.let { return it }
|
if (!FlatpakManager.ready(context)) FlatpakManager.setup(context, onProgress)?.let { return it }
|
||||||
FlatpakManager.install(context, id, onProgress)?.let { return it }
|
FlatpakManager.install(context, id, onProgress)?.let { return it }
|
||||||
val custom = overrides(context, id)
|
customiseFlatpak(context, id, name, icon)
|
||||||
if (name != null) FileUtils.writeString(File(custom.apply { mkdirs() }, "name"), name)
|
|
||||||
if (icon != null && !saveIcon(icon, File(custom, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun addFlatpakBundle(context: Context, file: File, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
||||||
|
if (!file.isFile) return context.getString(R.string.user_apps_file_gone)
|
||||||
|
if (!FlatpakManager.ready(context)) FlatpakManager.setup(context, onProgress)?.let { return it }
|
||||||
|
// Shared storage is bound into the runtime at its own path; a file anywhere else is copied in.
|
||||||
|
val shared = Environment.getExternalStorageDirectory().canonicalPath
|
||||||
|
val copy = File(LinuxRuntime.rootDir(context), "tmp/droiddeck-bundle.flatpak").takeIf { !file.canonicalPath.startsWith("$shared/") }
|
||||||
|
try {
|
||||||
|
if (copy != null) {
|
||||||
|
onProgress(context.getString(R.string.user_apps_copying, file.name), -1)
|
||||||
|
file.copyTo(copy.apply { parentFile?.mkdirs() }, overwrite = true)
|
||||||
|
}
|
||||||
|
val (id, problem) = FlatpakManager.installBundle(context, copy?.let { "/tmp/${it.name}" } ?: file.canonicalPath, onProgress)
|
||||||
|
problem?.let { return it }
|
||||||
|
if (id != null) customiseFlatpak(context, id, name, icon)
|
||||||
|
return null
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "bundle ${file.path}", e)
|
||||||
|
return e.message ?: context.getString(R.string.user_apps_failed)
|
||||||
|
} finally {
|
||||||
|
copy?.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun customiseFlatpak(context: Context, id: String, name: String?, icon: File?) {
|
||||||
|
val custom = overrides(context, id)
|
||||||
|
if (name != null) FileUtils.writeString(File(custom.apply { mkdirs() }, "name"), name)
|
||||||
|
if (icon != null && !saveIcon(icon, File(custom.apply { mkdirs() }, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
package com.droiddeck.launcher.session
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
import com.droiddeck.launcher.core.Hashes
|
import com.droiddeck.launcher.core.Hashes
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.core.Downloader
|
import com.droiddeck.launcher.core.Downloader
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
|
import com.droiddeck.launcher.gpu.GpuInfo
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.github.luben.zstd.ZstdInputStream
|
import com.github.luben.zstd.ZstdInputStream
|
||||||
import com.github.luben.zstd.ZstdOutputStream
|
import com.github.luben.zstd.ZstdOutputStream
|
||||||
@@ -247,12 +249,13 @@ object ComponentsManager {
|
|||||||
Regex("\\(([^)]+)\\)").find(text)?.groupValues?.get(1) ?: text.split(Regex("\\s+")).last()
|
Regex("\\(([^)]+)\\)").find(text)?.groupValues?.get(1) ?: text.split(Regex("\\s+")).last()
|
||||||
}.getOrDefault("")
|
}.getOrDefault("")
|
||||||
|
|
||||||
private fun fexVersion(dir: File): String {
|
/** The FEX build's version name; [unnamed] when its DLL carries none, "" when there is no FEX. */
|
||||||
|
private fun fexVersion(dir: File, unnamed: String = "FEX (build without a version name)"): String {
|
||||||
val dll = File(dir, FEX_FILES[0])
|
val dll = File(dir, FEX_FILES[0])
|
||||||
if (!dll.isFile) return ""
|
if (!dll.isFile) return ""
|
||||||
val text = runCatching { String(dll.readBytes(), Charsets.ISO_8859_1) }.getOrDefault("")
|
val text = runCatching { String(dll.readBytes(), Charsets.ISO_8859_1) }.getOrDefault("")
|
||||||
return Regex("FEX-\\d{4}(?:\\.\\d+)?(?:-\\d+-g[0-9a-f]{6,})?").findAll(text).map { it.value }.maxByOrNull { it.length }
|
return Regex("FEX-\\d{4}(?:\\.\\d+)?(?:-\\d+-g[0-9a-f]{6,})?").findAll(text).map { it.value }.maxByOrNull { it.length }
|
||||||
?: "FEX (build without a version name)"
|
?: unnamed
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun compFiles(dir: File, comp: String): List<String> {
|
private fun compFiles(dir: File, comp: String): List<String> {
|
||||||
@@ -273,23 +276,24 @@ object ComponentsManager {
|
|||||||
private inline fun <T> readWcp(f: File, block: (TarArchiveInputStream) -> T): T =
|
private inline fun <T> readWcp(f: File, block: (TarArchiveInputStream) -> T): T =
|
||||||
TarArchiveInputStream(ZstdInputStream(BufferedInputStream(FileInputStream(f), 1 shl 16))).use(block)
|
TarArchiveInputStream(ZstdInputStream(BufferedInputStream(FileInputStream(f), 1 shl 16))).use(block)
|
||||||
|
|
||||||
private fun readProfile(f: File): JSONObject = readWcp(f) { tar ->
|
private fun readProfile(context: Context, f: File): JSONObject = readWcp(f) { tar ->
|
||||||
while (true) {
|
while (true) {
|
||||||
val e = tar.nextTarEntry ?: break
|
val e = tar.nextTarEntry ?: break
|
||||||
if (!e.isDirectory && normalize(e.name) == "profile.json") return@readWcp JSONObject(tar.readBytes().decodeToString())
|
if (!e.isDirectory && normalize(e.name) == "profile.json") return@readWcp JSONObject(tar.readBytes().decodeToString())
|
||||||
}
|
}
|
||||||
throw IllegalArgumentException("no profile.json in ${f.name}")
|
throw IllegalArgumentException(context.getString(R.string.cmgr_no_profile, f.name))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun packageInfo(f: File): Package {
|
private fun packageInfo(context: Context, f: File): Package {
|
||||||
val prof = readProfile(f)
|
val prof = readProfile(context, f)
|
||||||
val comp = TYPES[prof.optString("type")] ?: throw IllegalArgumentException("${f.name} is not a Linux component package (type ${prof.optString("type")})")
|
val comp = TYPES[prof.optString("type")]
|
||||||
|
?: throw IllegalArgumentException(context.getString(R.string.cmgr_not_component_package, f.name, prof.optString("type")))
|
||||||
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
|
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
|
||||||
}
|
}
|
||||||
|
|
||||||
fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
|
fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
|
||||||
?.filter { it.isFile && it.name.endsWith(".wcp") }?.sortedBy { it.name }
|
?.filter { it.isFile && it.name.endsWith(".wcp") }?.sortedBy { it.name }
|
||||||
?.mapNotNull { f -> runCatching { packageInfo(f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
|
?.mapNotNull { f -> runCatching { packageInfo(context, f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
|
||||||
?: emptyList()
|
?: emptyList()
|
||||||
|
|
||||||
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
|
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
|
||||||
@@ -362,7 +366,7 @@ object ComponentsManager {
|
|||||||
return versions.flatMap { v ->
|
return versions.flatMap { v ->
|
||||||
COMPONENTS.mapNotNull { comp ->
|
COMPONENTS.mapNotNull { comp ->
|
||||||
val f = File(v, "$comp.wcp")
|
val f = File(v, "$comp.wcp")
|
||||||
if (!f.isFile) null else Original(comp, v.name, runCatching { readProfile(f).optString("description") }.getOrDefault(""), f.length())
|
if (!f.isFile) null else Original(comp, v.name, runCatching { readProfile(context, f).optString("description") }.getOrDefault(""), f.length())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -414,24 +418,24 @@ object ComponentsManager {
|
|||||||
val syncPacks = EsyncPacks.status(root(context))
|
val syncPacks = EsyncPacks.status(root(context))
|
||||||
val views = protons(context).map { p ->
|
val views = protons(context).map { p ->
|
||||||
val comps = COMPONENTS.associateWith { comp ->
|
val comps = COMPONENTS.associateWith { comp ->
|
||||||
val detected = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
|
val detected = if (comp == "fex") fexVersion(p.dir, context.getString(R.string.cmgr_fex_unnamed)) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
|
||||||
val detail = if (comp == "fex") (if (File(p.dir, FEX_FILES[2]).isFile) "with Linux helpers" else "DLLs only") else ""
|
val detail = if (comp == "fex") context.getString(if (File(p.dir, FEX_FILES[2]).isFile) R.string.cmgr_fex_linux_helpers else R.string.cmgr_fex_dlls_only) else ""
|
||||||
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
|
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
|
||||||
val inUseLabel = when {
|
val inUseLabel = when {
|
||||||
active == null -> "Original"
|
active == null -> context.getString(R.string.comp_tag_original)
|
||||||
active.optString("protonVersion") != p.version -> "Original (Proton updated since the last swap)"
|
active.optString("protonVersion") != p.version -> context.getString(R.string.cmgr_original_proton_updated)
|
||||||
else -> {
|
else -> {
|
||||||
val want = active.optJSONObject("files") ?: JSONObject()
|
val want = active.optJSONObject("files") ?: JSONObject()
|
||||||
val fp = fingerprint(p.dir, comp)
|
val fp = fingerprint(p.dir, comp)
|
||||||
if (want.keys().asSequence().all { fp[it] == want.optString(it) }) active.optString("label", active.optString("file"))
|
if (want.keys().asSequence().all { fp[it] == want.optString(it) }) originalLabel(context, active) ?: active.optString("label", active.optString("file"))
|
||||||
else "Changed outside Components"
|
else context.getString(R.string.cmgr_changed_outside)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
|
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
|
||||||
Component(
|
Component(
|
||||||
detected.ifEmpty { "not present" }, detail, inUseLabel,
|
detected.ifEmpty { context.getString(R.string.cmgr_not_present) }, detail, inUseLabel,
|
||||||
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
|
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
|
||||||
q?.optString("label"),
|
q?.let { originalLabel(context, it) ?: it.optString("label") },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
ProtonView(p, comps, originals(context, p.id), gameRunning(context, p), reapplied[p.dir.name] ?: 0, syncPacks.tool(p.guestPath))
|
ProtonView(p, comps, originals(context, p.id), gameRunning(context, p), reapplied[p.dir.name] ?: 0, syncPacks.tool(p.guestPath))
|
||||||
@@ -439,6 +443,16 @@ object ComponentsManager {
|
|||||||
Snapshot(views, packages(context))
|
Snapshot(views, packages(context))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The label of a chosen or queued original, in the app's language: the stored "label" was written
|
||||||
|
* in English when it was chosen. Null for a package, whose label is its version.
|
||||||
|
*/
|
||||||
|
private fun originalLabel(context: Context, entry: JSONObject): String? = when {
|
||||||
|
entry.optString("kind") == "original" -> context.getString(R.string.cmgr_original_version, entry.optString("protonVersion"))
|
||||||
|
entry.optString("file").startsWith("original ") -> context.getString(R.string.cmgr_original_from, entry.optString("file").removePrefix("original "))
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ launch-time enforcement
|
// ------------------------------------------------------------------ launch-time enforcement
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -507,17 +521,17 @@ object ComponentsManager {
|
|||||||
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
|
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
|
||||||
val p = proton(context, protonId)
|
val p = proton(context, protonId)
|
||||||
val wcp = File(packagesDir(context), safeName(file))
|
val wcp = File(packagesDir(context), safeName(file))
|
||||||
val info = packageInfo(wcp)
|
val info = packageInfo(context, wcp)
|
||||||
val state = loadState(context)
|
val state = loadState(context)
|
||||||
if (inUse(context, p)) {
|
if (inUse(context, p)) {
|
||||||
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
|
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
|
||||||
saveState(context, state)
|
saveState(context, state)
|
||||||
return "${LABEL[info.comp]} ${info.version} goes into ${p.name} when the game running on it closes."
|
return context.getString(R.string.cmgr_swap_queued, LABEL[info.comp], info.version, p.name)
|
||||||
}
|
}
|
||||||
applyPackage(context, p, info, wcp, state)
|
applyPackage(context, p, info, wcp, state)
|
||||||
state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
|
state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
|
||||||
saveState(context, state)
|
saveState(context, state)
|
||||||
"${LABEL[info.comp]} ${info.version} is now in ${p.name}. It applies the next time a game starts."
|
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
|
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
|
||||||
@@ -533,17 +547,17 @@ object ComponentsManager {
|
|||||||
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
|
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
|
||||||
val p = proton(context, protonId)
|
val p = proton(context, protonId)
|
||||||
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
|
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
|
||||||
check(wcp.isFile) { "That original bundle is not stored" }
|
check(wcp.isFile) { context.getString(R.string.cmgr_original_missing) }
|
||||||
val state = loadState(context)
|
val state = loadState(context)
|
||||||
if (inUse(context, p)) {
|
if (inUse(context, p)) {
|
||||||
state.sub("queued").sub(p.id).put(comp, JSONObject().put("kind", "original").put("protonVersion", protonVersion).put("label", "Original $protonVersion"))
|
state.sub("queued").sub(p.id).put(comp, JSONObject().put("kind", "original").put("protonVersion", protonVersion).put("label", "Original $protonVersion"))
|
||||||
saveState(context, state)
|
saveState(context, state)
|
||||||
return "${LABEL[comp]} of ${p.name} goes back to its original when the game running on it closes."
|
return context.getString(R.string.cmgr_restore_queued, LABEL[comp], p.name)
|
||||||
}
|
}
|
||||||
applyOriginal(context, p, comp, protonVersion, wcp, state)
|
applyOriginal(context, p, comp, protonVersion, wcp, state)
|
||||||
state.sub("queued").optJSONObject(p.id)?.remove(comp)
|
state.sub("queued").optJSONObject(p.id)?.remove(comp)
|
||||||
saveState(context, state)
|
saveState(context, state)
|
||||||
"${LABEL[comp]} of ${p.name} restored from its $protonVersion original."
|
context.getString(R.string.cmgr_restore_done, LABEL[comp], p.name, protonVersion)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun applyOriginal(context: Context, p: Proton, comp: String, protonVersion: String, wcp: File, state: JSONObject) {
|
private fun applyOriginal(context: Context, p: Proton, comp: String, protonVersion: String, wcp: File, state: JSONObject) {
|
||||||
@@ -575,7 +589,7 @@ object ComponentsManager {
|
|||||||
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
|
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
|
||||||
} else {
|
} else {
|
||||||
val wcp = File(packagesDir(context), q.optString("file"))
|
val wcp = File(packagesDir(context), q.optString("file"))
|
||||||
applyPackage(context, p, packageInfo(wcp), wcp, state)
|
applyPackage(context, p, packageInfo(context, wcp), wcp, state)
|
||||||
}
|
}
|
||||||
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
|
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
|
||||||
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
|
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
|
||||||
@@ -599,27 +613,27 @@ object ComponentsManager {
|
|||||||
val active = state.sub("active")
|
val active = state.sub("active")
|
||||||
for (pid in active.keys()) {
|
for (pid in active.keys()) {
|
||||||
val comps = active.optJSONObject(pid) ?: continue
|
val comps = active.optJSONObject(pid) ?: continue
|
||||||
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { "$name is in use in $pid. Swap that Proton to something else first." }
|
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
|
||||||
}
|
}
|
||||||
val f = File(packagesDir(context), name)
|
val f = File(packagesDir(context), name)
|
||||||
check(f.isFile) { "$name is not stored" }
|
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
|
||||||
f.delete()
|
f.delete()
|
||||||
"Deleted $name."
|
context.getString(R.string.cmgr_deleted, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun deleteOriginal(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
|
fun deleteOriginal(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
|
||||||
val p = proton(context, protonId)
|
val p = proton(context, protonId)
|
||||||
check(safeName(p.version) != protonVersion) { "The installed build's original is kept: it is the way back." }
|
check(safeName(p.version) != protonVersion) { context.getString(R.string.cmgr_original_kept) }
|
||||||
val f = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
|
val f = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
|
||||||
check(f.isFile) { "Not stored" }
|
check(f.isFile) { context.getString(R.string.cmgr_not_stored) }
|
||||||
f.delete()
|
f.delete()
|
||||||
f.parentFile?.takeIf { it.listFiles().isNullOrEmpty() }?.delete()
|
f.parentFile?.takeIf { it.listFiles().isNullOrEmpty() }?.delete()
|
||||||
"Deleted the $protonVersion original of ${LABEL[comp]}."
|
context.getString(R.string.cmgr_deleted_original, protonVersion, LABEL[comp])
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Imports a -linux .wcp from anywhere the app can read (the file picker hands over a copy). */
|
/** Imports a -linux .wcp from anywhere the app can read (the file picker hands over a copy). */
|
||||||
fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) {
|
fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) {
|
||||||
val info = packageInfo(source)
|
val info = packageInfo(context, source)
|
||||||
val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" })
|
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)
|
source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest)
|
||||||
info.copy(file = dest.name)
|
info.copy(file = dest.name)
|
||||||
@@ -660,16 +674,117 @@ object ComponentsManager {
|
|||||||
return Catalog(items, o.optLong("fetchedAt"))
|
return Catalog(items, o.optLong("fetchedAt"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A package Proton does not ship, required on the GPUs listed here. An empty [models] set
|
||||||
|
* means every model in [families]. A row the user already chose in Components is left alone;
|
||||||
|
* a Steam update that puts the Proton's own files back is replaced on the next session.
|
||||||
|
*/
|
||||||
|
internal data class ForcedPackage(
|
||||||
|
val families: Set<GpuInfo.Family>,
|
||||||
|
val comp: String,
|
||||||
|
val file: String,
|
||||||
|
val release: String,
|
||||||
|
val models: Set<Int> = emptySet(),
|
||||||
|
) {
|
||||||
|
fun matches(gpu: GpuInfo) = gpu.family in families && (models.isEmpty() || gpu.model in models)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal val FORCED_PACKAGES = listOf(
|
||||||
|
// DXVK 3 refuses to start unless the device exposes storageBuffer8BitAccess. Turnip on
|
||||||
|
// Adreno 6xx does not. 2.7.1 is the last DXVK 2 package on the Dxvk-Linux tag.
|
||||||
|
ForcedPackage(setOf(GpuInfo.Family.A6XX), "dxvk", "dxvk-2.7.1-linux.wcp", "Dxvk-Linux"),
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when this Proton should receive the forced package. No active swap means the Proton's
|
||||||
|
* own copy. A record for a different Proton build means a Steam update put that copy back,
|
||||||
|
* whichever package was recorded. A record for this build is a Components choice and stays.
|
||||||
|
*/
|
||||||
|
internal fun forcedPackageWanted(activeFile: String?, protonVersionMatches: Boolean): Boolean =
|
||||||
|
activeFile.isNullOrEmpty() || !protonVersionMatches
|
||||||
|
|
||||||
|
/** The catalog row for this file and release, or null. */
|
||||||
|
internal fun catalogMatch(items: List<CatalogItem>, file: String, release: String): CatalogItem? =
|
||||||
|
items.firstOrNull { it.file == file && it.release == release }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Install every [FORCED_PACKAGES] row this GPU matches into each Proton that
|
||||||
|
* [forcedPackageWanted] selects. Returns a line for the log, or null when this GPU or these
|
||||||
|
* Protons need nothing. A failed fetch throws and the session logs it without stopping.
|
||||||
|
*/
|
||||||
|
fun ensureForcedPackages(context: Context): String? = ensureForcedPackages(
|
||||||
|
context, GpuInfo.detect(),
|
||||||
|
{ file, release -> catalogItem(context, file, release) },
|
||||||
|
{ download(context, it) {} },
|
||||||
|
{ id, file -> swap(context, id, file) },
|
||||||
|
)
|
||||||
|
|
||||||
|
internal fun ensureForcedPackages(
|
||||||
|
context: Context,
|
||||||
|
gpu: GpuInfo,
|
||||||
|
lookup: (file: String, release: String) -> CatalogItem?,
|
||||||
|
fetch: (CatalogItem) -> Unit,
|
||||||
|
apply: (protonId: String, file: String) -> String,
|
||||||
|
): String? {
|
||||||
|
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }
|
||||||
|
if (rules.isEmpty()) return null
|
||||||
|
val installed = protons(context)
|
||||||
|
val lines = mutableListOf<String>()
|
||||||
|
for (rule in rules) {
|
||||||
|
val state = loadState(context)
|
||||||
|
val targets = installed.filter { p ->
|
||||||
|
val active = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject(rule.comp)
|
||||||
|
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version)
|
||||||
|
}
|
||||||
|
if (targets.isEmpty()) continue
|
||||||
|
val missing = missingPackage(context, rule, lookup, fetch)
|
||||||
|
if (missing != null) {
|
||||||
|
lines.add(missing)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
lines.add(targets.joinToString("; ") { apply(it.id, rule.file) })
|
||||||
|
}
|
||||||
|
return lines.joinToString("; ").ifEmpty { null }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Null when [rule]'s package is stored and readable. Otherwise the log line, after a fetch. */
|
||||||
|
private fun missingPackage(
|
||||||
|
context: Context,
|
||||||
|
rule: ForcedPackage,
|
||||||
|
lookup: (file: String, release: String) -> CatalogItem?,
|
||||||
|
fetch: (CatalogItem) -> Unit,
|
||||||
|
): String? {
|
||||||
|
val wcp = File(packagesDir(context), safeName(rule.file))
|
||||||
|
if (wcp.isFile && runCatching { packageInfo(context, wcp) }.isSuccess) return null
|
||||||
|
wcp.delete()
|
||||||
|
val item = lookup(rule.file, rule.release)
|
||||||
|
?: return "${rule.file} is not in the Nightlies listing; ${LABEL.getValue(rule.comp)} stays on the Proton's copy"
|
||||||
|
fetch(item)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The cached Nightlies row for this file, fetching the listing when the cache does not have it. */
|
||||||
|
internal fun catalogItem(context: Context, file: String, release: String): CatalogItem? =
|
||||||
|
resolveCatalogItem(file, release, { catalog(context, false).items }, { catalog(context, true).items })
|
||||||
|
|
||||||
|
/** [cached] when it has the row, otherwise [refresh]. [refresh] is not called on a hit. */
|
||||||
|
internal fun resolveCatalogItem(
|
||||||
|
file: String,
|
||||||
|
release: String,
|
||||||
|
cached: () -> List<CatalogItem>,
|
||||||
|
refresh: () -> List<CatalogItem>,
|
||||||
|
): CatalogItem? = catalogMatch(cached(), file, release) ?: catalogMatch(refresh(), file, release)
|
||||||
|
|
||||||
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
|
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
|
||||||
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
|
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
|
||||||
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { "Downloads come only from the Nightlies releases" }
|
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { context.getString(R.string.cmgr_nightlies_only) }
|
||||||
require(Hashes.isGithubSha256(item.digest)) { "This package list predates checksums - refresh it and try again" }
|
require(Hashes.isGithubSha256(item.digest)) { context.getString(R.string.cmgr_list_predates_checksums) }
|
||||||
val dest = File(packagesDir(context), safeName(item.file))
|
val dest = File(packagesDir(context), safeName(item.file))
|
||||||
val part = File(dest.parentFile, dest.name + ".part")
|
val part = File(dest.parentFile, dest.name + ".part")
|
||||||
part.delete()
|
part.delete()
|
||||||
check(Downloader.downloadFile(item.url, part, false) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { "Download failed" }
|
check(Downloader.downloadFile(item.url, part, false) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { context.getString(R.string.user_apps_download_failed) }
|
||||||
if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error("Checksum mismatch") }
|
if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error(context.getString(R.string.cmgr_checksum_mismatch)) }
|
||||||
val info = runCatching { packageInfo(part) }.getOrElse { part.delete(); throw it }
|
val info = runCatching { packageInfo(context, part) }.getOrElse { part.delete(); throw it }
|
||||||
synchronized(lock) { part.renameTo(dest) }
|
synchronized(lock) { part.renameTo(dest) }
|
||||||
return info.copy(file = dest.name)
|
return info.copy(file = dest.name)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,7 +49,6 @@ object EsyncPacks {
|
|||||||
private const val TOOLS = "tools.tsv"
|
private const val TOOLS = "tools.tsv"
|
||||||
private const val FLOOR = "floor"
|
private const val FLOOR = "floor"
|
||||||
private const val PACK_FAILURES = "packFailures"
|
private const val PACK_FAILURES = "packFailures"
|
||||||
private const val PROGRESS_LABEL = "Fetching droiddeck-esync pack"
|
|
||||||
private const val INDEX_LIMIT = 4L shl 20
|
private const val INDEX_LIMIT = 4L shl 20
|
||||||
private const val SIG_LIMIT = 4096L
|
private const val SIG_LIMIT = 4096L
|
||||||
private const val ASSET_LIMIT = 256L shl 20
|
private const val ASSET_LIMIT = 256L shl 20
|
||||||
@@ -618,14 +617,15 @@ object EsyncPacks {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
onProgress?.invoke(PROGRESS_LABEL, -1)
|
val label = context.getString(com.droiddeck.launcher.R.string.esync_fetching)
|
||||||
|
onProgress?.invoke(label, -1)
|
||||||
var reported = -1
|
var reported = -1
|
||||||
val fetched = FileOutputStream(part).use { output ->
|
val fetched = FileOutputStream(part).use { output ->
|
||||||
fetch(entry.asset.url, entry.asset.size, output) { done ->
|
fetch(entry.asset.url, entry.asset.size, output) { done ->
|
||||||
val percent = (done * 100 / entry.asset.size).toInt().coerceIn(0, 100)
|
val percent = (done * 100 / entry.asset.size).toInt().coerceIn(0, 100)
|
||||||
if (percent != reported) {
|
if (percent != reported) {
|
||||||
reported = percent
|
reported = percent
|
||||||
onProgress?.invoke(PROGRESS_LABEL, percent)
|
onProgress?.invoke(label, percent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ object GameEnvironmentStore {
|
|||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
||||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context)) + config.shared)
|
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||||
val json = encode(resolved)
|
val json = encode(resolved)
|
||||||
// The Display page's texture filtering, as DXVK options the launcher appends to
|
// The Display page's texture filtering, as DXVK options the launcher appends to
|
||||||
// DXVK_CONFIG after the profiles - a user's own DXVK_CONFIG entry keeps its options.
|
// DXVK_CONFIG after the profiles - a user's own DXVK_CONFIG entry keeps its options.
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.droiddeck.launcher.session
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
import android.os.Environment
|
import android.os.Environment
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.frontend.Library
|
import com.droiddeck.launcher.frontend.Library
|
||||||
import java.io.BufferedInputStream
|
import java.io.BufferedInputStream
|
||||||
import java.io.BufferedOutputStream
|
import java.io.BufferedOutputStream
|
||||||
@@ -25,9 +27,12 @@ import java.util.zip.ZipOutputStream
|
|||||||
* Ported from Bannerlator's GameSaveBackup and SaveLocator.
|
* Ported from Bannerlator's GameSaveBackup and SaveLocator.
|
||||||
*/
|
*/
|
||||||
object GameSaves {
|
object GameSaves {
|
||||||
enum class Layout(val label: String, val rootPrefix: String, val user: String) {
|
enum class Layout(val app: String, val rootPrefix: String, val user: String) {
|
||||||
GAMEHUB("GameHub zip", "/drive_c/", "steamuser"),
|
GAMEHUB("GameHub", "/drive_c/", "steamuser"),
|
||||||
WINLATOR("Winlator zip", "drive_c/", "xuser"),
|
WINLATOR("Winlator", "drive_c/", "xuser");
|
||||||
|
|
||||||
|
/** "GameHub zip", in the app's language. */
|
||||||
|
fun label(context: Context): String = context.getString(R.string.saves_layout_zip, app)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A game, its prefix, and the save folders found in it. */
|
/** A game, its prefix, and the save folders found in it. */
|
||||||
@@ -127,12 +132,12 @@ object GameSaves {
|
|||||||
* Zips the game's saves into [dir] as "<Game>_<date>.zip" in [layout]. The found save folders when
|
* Zips the game's saves into [dir] as "<Game>_<date>.zip" in [layout]. The found save folders when
|
||||||
* there are any, else the whole steamuser profile minus Temp and crash dumps. Returns the zip.
|
* there are any, else the whole steamuser profile minus Temp and crash dumps. Returns the zip.
|
||||||
*/
|
*/
|
||||||
fun export(game: Game, layout: Layout, dir: File): Pair<File, Int> {
|
fun export(context: Context, game: Game, layout: Layout, dir: File): Pair<File, Int> {
|
||||||
val prefix = game.prefix ?: error("${game.game.name} has not been launched yet")
|
val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name))
|
||||||
dir.mkdirs()
|
dir.mkdirs()
|
||||||
val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip")
|
val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip")
|
||||||
val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out)
|
val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out)
|
||||||
if (count == 0) { out.delete(); error("No save files found for ${game.game.name}") }
|
if (count == 0) { out.delete(); error(context.getString(R.string.saves_none_found, game.game.name)) }
|
||||||
return out to count
|
return out to count
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,11 +167,11 @@ object GameSaves {
|
|||||||
* profile holds now into Download/DroidDeck/Saves/backups. Entries outside drive_c, launcher
|
* profile holds now into Download/DroidDeck/Saves/backups. Entries outside drive_c, launcher
|
||||||
* shortcuts and anything escaping drive_c are skipped. Returns (files written, backup or null).
|
* shortcuts and anything escaping drive_c are skipped. Returns (files written, backup or null).
|
||||||
*/
|
*/
|
||||||
fun import(game: Game, zip: File): Pair<Int, File?> {
|
fun import(context: Context, game: Game, zip: File): Pair<Int, File?> {
|
||||||
val prefix = game.prefix ?: error("${game.game.name} has not been launched yet")
|
val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name))
|
||||||
val driveC = File(prefix, "drive_c")
|
val driveC = File(prefix, "drive_c")
|
||||||
if (!driveC.isDirectory) error("${game.game.name} has not been launched yet")
|
if (!driveC.isDirectory) error(context.getString(R.string.saves_not_launched, game.game.name))
|
||||||
if (!looksLikeSaveZip(zip)) error("${zip.name} has no drive_c folder, so it isn't a GameHub or Winlator save zip")
|
if (!looksLikeSaveZip(zip)) error(context.getString(R.string.saves_not_save_zip, zip.name))
|
||||||
|
|
||||||
backupsDir().mkdirs()
|
backupsDir().mkdirs()
|
||||||
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip")
|
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip")
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import android.content.Context
|
|||||||
import android.os.Environment
|
import android.os.Environment
|
||||||
import android.os.StatFs
|
import android.os.StatFs
|
||||||
import android.os.storage.StorageManager
|
import android.os.storage.StorageManager
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
|
import com.droiddeck.launcher.frontend.AddedGames
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -17,7 +19,8 @@ import java.io.File
|
|||||||
* slowly (intro movies, big asset loads); internal stays the default and the dialog says so.
|
* slowly (intro movies, big asset loads); internal stays the default and the dialog says so.
|
||||||
*/
|
*/
|
||||||
object GameStorage {
|
object GameStorage {
|
||||||
class Option(val label: String, val path: String)
|
/** A library root: [label] as the menu lists it (a volume with its free space), [name] alone. */
|
||||||
|
class Option(val label: String, val path: String, val name: String = label)
|
||||||
|
|
||||||
/** Every removable volume, as its app folder, with the free space it has. */
|
/** Every removable volume, as its app folder, with the free space it has. */
|
||||||
fun options(context: Context): List<Option> {
|
fun options(context: Context): List<Option> {
|
||||||
@@ -26,8 +29,8 @@ object GameStorage {
|
|||||||
val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false }
|
val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false }
|
||||||
if (!removable) return@mapNotNull null
|
if (!removable) return@mapNotNull null
|
||||||
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
|
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
|
||||||
val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: "SD card"
|
val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: context.getString(R.string.gstore_sd_card)
|
||||||
Option("$name · ${free(dir)} free", File(dir, "steam").absolutePath)
|
Option(context.getString(R.string.gstore_volume_free, name, free(dir)), File(dir, "steam").absolutePath, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,15 +44,15 @@ object GameStorage {
|
|||||||
* Makes [path] a library root the session can bind - the folder and its steamapps/ - and proves
|
* Makes [path] a library root the session can bind - the folder and its steamapps/ - and proves
|
||||||
* it writable. Returns why it cannot be used, or null when it can.
|
* it writable. Returns why it cannot be used, or null when it can.
|
||||||
*/
|
*/
|
||||||
fun prepare(path: String): String? {
|
fun prepare(context: Context, path: String): String? {
|
||||||
val root = File(path)
|
val root = File(path)
|
||||||
val steamapps = File(root, "steamapps")
|
val steamapps = File(root, "steamapps")
|
||||||
if (!steamapps.isDirectory && !steamapps.mkdirs()) return "cannot create folders in $path"
|
if (!steamapps.isDirectory && !steamapps.mkdirs()) return context.getString(R.string.gstore_cannot_create, path)
|
||||||
val probe = File(steamapps, ".writable")
|
val probe = File(steamapps, ".writable")
|
||||||
return try {
|
return try {
|
||||||
if (!probe.createNewFile() && !probe.isFile) "cannot write in $path" else { probe.delete(); null }
|
if (!probe.createNewFile() && !probe.isFile) context.getString(R.string.gstore_cannot_write, path) else { probe.delete(); null }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
"cannot write in $path (${e.message})"
|
context.getString(R.string.gstore_cannot_write_detail, path, e.message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,13 +61,32 @@ object GameStorage {
|
|||||||
val pref = SessionPrefs.gameStorage(context)
|
val pref = SessionPrefs.gameStorage(context)
|
||||||
return when {
|
return when {
|
||||||
pref == SessionPrefs.GAME_STORAGE_OFF -> null
|
pref == SessionPrefs.GAME_STORAGE_OFF -> null
|
||||||
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.label.substringBefore(" ·"), it.path) }
|
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) }
|
||||||
else -> Option(SessionPrefs.gameStorageLabel(context), pref)
|
else -> Option(SessionPrefs.gameStorageLabel(context), pref)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class Library(val host: File, val guest: String, val label: String)
|
||||||
|
|
||||||
|
fun gamesFolderLibraries(context: Context): List<Library> {
|
||||||
|
if (SessionPrefs.gameStorage(context).isNotEmpty()) return emptyList()
|
||||||
|
val card = effective(context)?.let { canonical(File(it.path)) }
|
||||||
|
val sm = context.getSystemService(StorageManager::class.java)
|
||||||
|
return AddedGames.roots(context).mapNotNull { root ->
|
||||||
|
val host = canonical(root.host)
|
||||||
|
if ('"' in root.guest || '\\' in root.guest || !root.host.isDirectory || !root.host.canWrite()) return@mapNotNull null
|
||||||
|
if (card != null && (host == card || host.startsWith("$card/") || card.startsWith("$host/"))) return@mapNotNull null
|
||||||
|
val volume = try { sm?.getStorageVolume(root.host)?.getDescription(context) } catch (e: Exception) { null }
|
||||||
|
val name = root.host.name.ifEmpty { context.getString(R.string.gstore_folder) }
|
||||||
|
val label = if (volume.isNullOrBlank()) name else context.getString(R.string.gstore_folder_on_volume, name, volume)
|
||||||
|
Library(root.host, root.guest, label.replace('"', ' ').replace('\\', ' '))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
|
||||||
|
|
||||||
/** The label the client shows for a chosen folder: its last name, or the volume's. */
|
/** The label the client shows for a chosen folder: its last name, or the volume's. */
|
||||||
fun labelFor(context: Context, path: String): String =
|
fun labelFor(context: Context, path: String): String =
|
||||||
options(context).firstOrNull { it.path == path }?.label?.substringBefore(" ·")
|
options(context).firstOrNull { it.path == path }?.name
|
||||||
?: File(path).name.ifEmpty { "Folder" }
|
?: File(path).name.ifEmpty { context.getString(R.string.gstore_folder) }
|
||||||
}
|
}
|
||||||
@@ -17,9 +17,16 @@ import java.nio.charset.StandardCharsets
|
|||||||
* progress, and lifting that out is the difference between "starting the Steam client" for three
|
* progress, and lifting that out is the difference between "starting the Steam client" for three
|
||||||
* minutes and a percentage that moves.
|
* minutes and a percentage that moves.
|
||||||
*/
|
*/
|
||||||
class LoadingState(context: Context, steam: Boolean = true) {
|
class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||||
var visible by mutableStateOf(true)
|
var visible by mutableStateOf(true)
|
||||||
var step by mutableStateOf("Starting the session…")
|
var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting))
|
||||||
|
private set
|
||||||
|
/** What [step] is about, so the screen picks its checklist stage without reading the (translated) words. */
|
||||||
|
var topic by mutableStateOf(Topic.SESSION)
|
||||||
|
private set
|
||||||
|
/** [step] is a download or install line worth showing as it is, not one of the script's own notes. */
|
||||||
|
var readable by mutableStateOf(false)
|
||||||
|
private set
|
||||||
var percent by mutableIntStateOf(-1)
|
var percent by mutableIntStateOf(-1)
|
||||||
var elapsed by mutableStateOf("")
|
var elapsed by mutableStateOf("")
|
||||||
var hint by mutableStateOf("")
|
var hint by mutableStateOf("")
|
||||||
@@ -31,15 +38,23 @@ class LoadingState(context: Context, steam: Boolean = true) {
|
|||||||
private val hints = context.resources.getStringArray(
|
private val hints = context.resources.getStringArray(
|
||||||
if (steam) com.droiddeck.launcher.R.array.loading_hints else com.droiddeck.launcher.R.array.loading_hints_desktop,
|
if (steam) com.droiddeck.launcher.R.array.loading_hints else com.droiddeck.launcher.R.array.loading_hints_desktop,
|
||||||
)
|
)
|
||||||
|
private val res = context.resources
|
||||||
private val startedAt = SystemClock.elapsedRealtime()
|
private val startedAt = SystemClock.elapsedRealtime()
|
||||||
|
|
||||||
/** Once a second: the clock and the hint. */
|
/** Once a second: the clock and the hint. */
|
||||||
fun tick() {
|
fun tick() {
|
||||||
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
|
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
|
||||||
elapsed = String.format(java.util.Locale.US, "%d:%02d elapsed · still working", seconds / 60, seconds % 60)
|
elapsed = res.getString(com.droiddeck.launcher.R.string.loadstate_elapsed, seconds / 60, seconds % 60)
|
||||||
hint = hints[((seconds / 8) % hints.size).toInt()]
|
hint = hints[((seconds / 8) % hints.size).toInt()]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A line the app itself writes (an install's progress, the session starting). */
|
||||||
|
fun say(line: String, topic: Topic, readable: Boolean) {
|
||||||
|
step = line
|
||||||
|
this.topic = topic
|
||||||
|
this.readable = readable
|
||||||
|
}
|
||||||
|
|
||||||
fun showEnded(message: String, detail: String? = null) {
|
fun showEnded(message: String, detail: String? = null) {
|
||||||
visible = true
|
visible = true
|
||||||
ended = true
|
ended = true
|
||||||
@@ -50,12 +65,16 @@ class LoadingState(context: Context, steam: Boolean = true) {
|
|||||||
/** Re-reads the end of the log and updates the line and the bar. */
|
/** Re-reads the end of the log and updates the line and the bar. */
|
||||||
fun update(context: Context, log: File?) {
|
fun update(context: Context, log: File?) {
|
||||||
val state = read(context, log) ?: return
|
val state = read(context, log) ?: return
|
||||||
step = state.first
|
step = state.line
|
||||||
percent = state.second
|
topic = state.topic
|
||||||
|
readable = state.readable
|
||||||
|
percent = state.percent
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private class Line(val line: String, val percent: Int, val topic: Topic, val readable: Boolean)
|
||||||
|
|
||||||
/** Only the tail is read: the client alone writes megabytes an hour. */
|
/** Only the tail is read: the client alone writes megabytes an hour. */
|
||||||
private fun read(context: Context, log: File?): Pair<String, Int>? {
|
private fun read(context: Context, log: File?): Line? {
|
||||||
if (log == null || !log.isFile) return null
|
if (log == null || !log.isFile) return null
|
||||||
val text = try {
|
val text = try {
|
||||||
RandomAccessFile(log, "r").use { file ->
|
RandomAccessFile(log, "r").use { file ->
|
||||||
@@ -100,16 +119,45 @@ class LoadingState(context: Context, steam: Boolean = true) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return when {
|
return when {
|
||||||
downloadAt > stepAt && downloadPercent >= 0 ->
|
downloadAt > stepAt && downloadPercent >= 0 -> Line(
|
||||||
Pair("Downloading the Steam client update · $downloadPercent%", downloadPercent)
|
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent,
|
||||||
clientDownloadAt == stepAt && clientDownload != null ->
|
Topic.STEAM, readable = true,
|
||||||
Pair("Downloading the Steam client · $clientDownload", clientPercent)
|
)
|
||||||
stepText != null -> Pair(stepText, -1)
|
clientDownloadAt == stepAt && clientDownload != null -> Line(
|
||||||
|
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent,
|
||||||
|
Topic.STEAM, readable = true,
|
||||||
|
)
|
||||||
|
stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText))
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The checklist stages a loading line can move the screen to. */
|
||||||
|
enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER }
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
/**
|
||||||
|
* A session script "== STEP" line's topic in a Steam ([steam]) or desktop session; those
|
||||||
|
* lines are English whatever the app's language.
|
||||||
|
*/
|
||||||
|
internal fun topicOf(scriptStep: String, steam: Boolean): Topic {
|
||||||
|
val t = scriptStep.lowercase()
|
||||||
|
return when {
|
||||||
|
"linux runtime" in t -> Topic.RUNTIME
|
||||||
|
"starting the session" in t -> Topic.SESSION
|
||||||
|
!steam && "desktop" in t -> Topic.DESKTOP
|
||||||
|
steam && "starting the steam client" in t -> Topic.STEAM_STARTING
|
||||||
|
steam && ("steam" in t || "client" in t || "proton" in t || "library" in t || "compatibility" in t) -> Topic.STEAM
|
||||||
|
else -> Topic.OTHER
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The script's install lines are worth reading as they are; its other notes are not. */
|
||||||
|
internal fun readableScriptStep(scriptStep: String): Boolean {
|
||||||
|
val t = scriptStep.lowercase()
|
||||||
|
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
|
||||||
|
}
|
||||||
|
|
||||||
private const val TAIL_BYTES = 48L * 1024
|
private const val TAIL_BYTES = 48L * 1024
|
||||||
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
|
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
|
||||||
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
|
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ object OfflineMode {
|
|||||||
|
|
||||||
private fun loginUsers(root: File) = File(root, "root/.local/share/Steam/config/loginusers.vdf")
|
private fun loginUsers(root: File) = File(root, "root/.local/share/Steam/config/loginusers.vdf")
|
||||||
|
|
||||||
/** Whether the client has an account it could sign in as offline. */
|
/** The account the client could sign in as offline: its name, "" when it recorded none, null when there is none. */
|
||||||
fun account(context: Context): String? {
|
fun account(context: Context): String? {
|
||||||
val file = loginUsers(LinuxRuntime.rootDir(context))
|
val file = loginUsers(LinuxRuntime.rootDir(context))
|
||||||
val text = try {
|
val text = try {
|
||||||
@@ -39,7 +39,7 @@ object OfflineMode {
|
|||||||
Log.w(TAG, "could not read loginusers.vdf", e); return null
|
Log.w(TAG, "could not read loginusers.vdf", e); return null
|
||||||
}
|
}
|
||||||
if (!REMEMBER.containsMatchIn(text)) return null
|
if (!REMEMBER.containsMatchIn(text)) return null
|
||||||
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() } ?: "signed in"
|
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
|
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.droiddeck.launcher.session
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
import com.droiddeck.launcher.core.Hashes
|
import com.droiddeck.launcher.core.Hashes
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.StatFs
|
import android.os.StatFs
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
@@ -59,70 +60,72 @@ object ProtonExtras {
|
|||||||
/** Downloads, verifies and registers the latest build without waiting for another session. */
|
/** Downloads, verifies and registers the latest build without waiting for another session. */
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||||
if (installInProgress) return "A compatibility tool install is already running"
|
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||||
installInProgress = true
|
installInProgress = true
|
||||||
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||||
if (SessionState.running) return "Stop the active session before installing compatibility tools"
|
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||||
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
|
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||||
|
|
||||||
val asset = findLatestAsset(tool) ?: return "Could not find an ARM64 release for ${tool.name}"
|
val asset = findLatestAsset(tool) ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||||
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
||||||
return "At least 4 GB free plus the download size is required to install ${tool.name}"
|
return context.getString(R.string.pextra_no_space, tool.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
onProgress("Downloading ${tool.name} ${asset.tag}", 0)
|
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
||||||
|
onProgress(downloading, 0)
|
||||||
var downloaded = false
|
var downloaded = false
|
||||||
for (attempt in 0 until 5) {
|
for (attempt in 0 until 5) {
|
||||||
downloaded = Downloader.downloadFile(asset.url, archive, true) { fraction ->
|
downloaded = Downloader.downloadFile(asset.url, archive, true) { fraction ->
|
||||||
onProgress("Downloading ${tool.name} ${asset.tag}", if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
||||||
}
|
}
|
||||||
if (downloaded) break
|
if (downloaded) break
|
||||||
if (attempt < 4) {
|
if (attempt < 4) {
|
||||||
onProgress("Retrying download · attempt ${attempt + 2} of 5", -1)
|
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1)
|
||||||
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
||||||
Thread.currentThread().interrupt()
|
Thread.currentThread().interrupt()
|
||||||
return "Download interrupted"
|
return context.getString(R.string.pextra_interrupted)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!downloaded) return "Download failed; the partial file is kept so a retry can resume"
|
if (!downloaded) return context.getString(R.string.pextra_download_failed)
|
||||||
if (asset.size > 0 && archive.length() != asset.size) {
|
if (asset.size > 0 && archive.length() != asset.size) {
|
||||||
if (archive.length() > asset.size) {
|
if (archive.length() > asset.size) {
|
||||||
archive.delete()
|
archive.delete()
|
||||||
return "Download exceeded the release size and was deleted"
|
return context.getString(R.string.pextra_too_big)
|
||||||
}
|
}
|
||||||
return "Download was incomplete; the partial file is kept for a resumable retry"
|
return context.getString(R.string.pextra_incomplete)
|
||||||
}
|
}
|
||||||
|
|
||||||
// One checksum has to be found and has to match: GitHub's sha256 digest, else the
|
// One checksum has to be found and has to match: GitHub's sha256 digest, else the
|
||||||
// release's own sha512 file. A download neither vouches for is not installed.
|
// release's own sha512 file. A download neither vouches for is not installed.
|
||||||
onProgress("Verifying download", -1)
|
onProgress(context.getString(R.string.pextra_verifying), -1)
|
||||||
val verified = when {
|
val verified = when {
|
||||||
asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true)
|
asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true)
|
||||||
asset.sha512 != null -> {
|
asset.sha512 != null -> {
|
||||||
val expected = Downloader.downloadString(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
|
val expected = Downloader.downloadString(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
|
||||||
?: return "Could not read the release checksum; try again"
|
?: return context.getString(R.string.pextra_checksum_unreadable)
|
||||||
expected.equals(Hashes.sha512(archive), ignoreCase = true)
|
expected.equals(Hashes.sha512(archive), ignoreCase = true)
|
||||||
}
|
}
|
||||||
else -> {
|
else -> {
|
||||||
archive.delete()
|
archive.delete()
|
||||||
return "${tool.name} ${asset.tag} publishes no checksum; nothing was installed"
|
return context.getString(R.string.pextra_no_checksum, tool.name, asset.tag)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!verified) {
|
if (!verified) {
|
||||||
archive.delete()
|
archive.delete()
|
||||||
return "Checksum mismatch; the download was deleted"
|
return context.getString(R.string.pextra_checksum_mismatch)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (SessionState.running) return "A session started during the download; stop it before installing compatibility tools"
|
if (SessionState.running) return context.getString(R.string.pextra_session_started)
|
||||||
onProgress("Installing ${tool.name}", -1)
|
val installing = context.getString(R.string.pextra_installing, tool.name)
|
||||||
|
onProgress(installing, -1)
|
||||||
return try {
|
return try {
|
||||||
val root = LinuxRuntime.rootDir(context)
|
val root = LinuxRuntime.rootDir(context)
|
||||||
LinuxRuntime.writeAccounts(context)
|
LinuxRuntime.writeAccounts(context)
|
||||||
@@ -146,17 +149,17 @@ object ProtonExtras {
|
|||||||
lines.forEach { line ->
|
lines.forEach { line ->
|
||||||
Log.i(TAG, line)
|
Log.i(TAG, line)
|
||||||
if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) {
|
if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) {
|
||||||
onProgress("Installing ${tool.name}", -1)
|
onProgress(installing, -1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val status = child.waitFor()
|
val status = child.waitFor()
|
||||||
if (status != 0) "${tool.name} installation failed (exit $status)"
|
if (status != 0) context.getString(R.string.pextra_install_failed, tool.name, status)
|
||||||
else {
|
else {
|
||||||
archive.delete()
|
archive.delete()
|
||||||
unqueue(context, tool)
|
unqueue(context, tool)
|
||||||
if (EsyncPacks.enabled(context)) {
|
if (EsyncPacks.enabled(context)) {
|
||||||
onProgress("Fetching droiddeck-esync pack", -1)
|
onProgress(context.getString(R.string.esync_fetching), -1)
|
||||||
try {
|
try {
|
||||||
EsyncPacks.fetchWanted(context, root, onProgress)
|
EsyncPacks.fetchWanted(context, root, onProgress)
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
@@ -167,7 +170,7 @@ object ProtonExtras {
|
|||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "install ${tool.id}", e)
|
Log.e(TAG, "install ${tool.id}", e)
|
||||||
e.message ?: "Could not install ${tool.name}"
|
e.message ?: context.getString(R.string.pextra_could_not_install, tool.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,19 +22,19 @@ import kotlin.math.max
|
|||||||
* When a game plays a force-feedback effect on the fake pad (or Steam Input sends the Deck's
|
* When a game plays a force-feedback effect on the fake pad (or Steam Input sends the Deck's
|
||||||
* rumble report), the fake evdev layer inside the guest connects to the abstract socket [NAME]
|
* rumble report), the fake evdev layer inside the guest connects to the abstract socket [NAME]
|
||||||
* and sends one packet: strong, weak, duration in ms and the pad slot, four little-endian 16-bit
|
* and sends one packet: strong, weak, duration in ms and the pad slot, four little-endian 16-bit
|
||||||
* values. This listens for those and plays the effect on the physical controller that last drove
|
* values. This listens for those and plays the effect on the physical controller playing in that
|
||||||
* the pad (PadBridge.activeControllerId) when Android exposes its motors - strong and weak
|
* slot (PadBridge.controllerForSlot) when Android exposes its motors - strong and weak separately
|
||||||
* separately where it has two - and otherwise on the device's own vibrator, with the stronger
|
* where it has two - and otherwise on the device's own vibrator, with the stronger motor's
|
||||||
* motor's strength: the on-screen pad, or a controller without rumble. Best effort both ways: a
|
* strength: the on-screen pad, or a controller without rumble. Best effort both ways: a missing
|
||||||
* missing listener costs the guest nothing, and a bad packet is dropped.
|
* listener costs the guest nothing, and a bad packet is dropped.
|
||||||
*/
|
*/
|
||||||
class RumbleComponent : SessionPart() {
|
class RumbleComponent : SessionPart() {
|
||||||
@Volatile private var server: LocalServerSocket? = null
|
@Volatile private var server: LocalServerSocket? = null
|
||||||
private var phone: Motors? = null
|
private var phone: Motors? = null
|
||||||
/** Where the last effect went, so the next one (or a stop) can end it there. */
|
/** Per slot, where its last effect went, so the next one (or a stop) can end it there. */
|
||||||
private var playing: Motors? = null
|
private val playing = HashMap<Int, Motors>()
|
||||||
private var controllerId = PadBridge.NO_CONTROLLER
|
/** Each controller's motors, looked up once; null when it has none. */
|
||||||
private var controller: Motors? = null
|
private val controllers = HashMap<Int, Motors?>()
|
||||||
private var preferences: SharedPreferences? = null
|
private var preferences: SharedPreferences? = null
|
||||||
private var enabled = false
|
private var enabled = false
|
||||||
private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||||
@@ -46,7 +46,7 @@ class RumbleComponent : SessionPart() {
|
|||||||
|
|
||||||
@Synchronized private fun refreshEnabled() {
|
@Synchronized private fun refreshEnabled() {
|
||||||
enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true
|
enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true
|
||||||
if (!enabled) { playing?.cancel(); playing = null }
|
if (!enabled) cancelAll()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun start() {
|
override fun start() {
|
||||||
@@ -64,7 +64,7 @@ class RumbleComponent : SessionPart() {
|
|||||||
try {
|
try {
|
||||||
val bytes = ByteArray(8)
|
val bytes = ByteArray(8)
|
||||||
DataInputStream(client.inputStream).readFully(bytes)
|
DataInputStream(client.inputStream).readFully(bytes)
|
||||||
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4))
|
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6))
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
// A partial packet or a closed peer: nothing to play.
|
// A partial packet or a closed peer: nothing to play.
|
||||||
} finally {
|
} finally {
|
||||||
@@ -79,11 +79,9 @@ class RumbleComponent : SessionPart() {
|
|||||||
preferences?.unregisterOnSharedPreferenceChangeListener(preferenceListener)
|
preferences?.unregisterOnSharedPreferenceChangeListener(preferenceListener)
|
||||||
preferences = null
|
preferences = null
|
||||||
enabled = false
|
enabled = false
|
||||||
playing?.cancel()
|
cancelAll()
|
||||||
playing = null
|
|
||||||
phone = null
|
phone = null
|
||||||
controller = null
|
controllers.clear()
|
||||||
controllerId = PadBridge.NO_CONTROLLER
|
|
||||||
val s = server
|
val s = server
|
||||||
server = null
|
server = null
|
||||||
try { s?.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ }
|
try { s?.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ }
|
||||||
@@ -91,13 +89,14 @@ 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)
|
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) {
|
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
|
||||||
if (!enabled) return
|
if (!enabled) return
|
||||||
val target = target()
|
val target = target(slot)
|
||||||
if (target !== playing) {
|
val previous = playing[slot]
|
||||||
playing?.cancel()
|
if (target !== previous) {
|
||||||
playing = target
|
previous?.cancel()
|
||||||
target?.let { Log.i(TAG, "rumble: playing on ${it.name}") }
|
if (target == null) playing.remove(slot) else playing[slot] = target
|
||||||
|
target?.let { Log.i(TAG, "rumble: slot $slot playing on ${it.name}") }
|
||||||
}
|
}
|
||||||
if (target == null) return
|
if (target == null) return
|
||||||
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); return }
|
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); return }
|
||||||
@@ -108,14 +107,17 @@ class RumbleComponent : SessionPart() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The active controller's motors when it has any, else the phone's. */
|
/** The motors of the controller playing in this slot when it has any, else the phone's. */
|
||||||
private fun target(): Motors? {
|
private fun target(slot: Int): Motors? {
|
||||||
val id = PadBridge.activeControllerId()
|
val id = PadBridge.controllerForSlot(slot)
|
||||||
if (id != controllerId) {
|
if (id == PadBridge.NO_CONTROLLER) return phone
|
||||||
controllerId = id
|
if (!controllers.containsKey(id)) controllers[id] = try { controllerMotors(id) } catch (e: Exception) { null }
|
||||||
controller = if (id == PadBridge.NO_CONTROLLER) null else try { controllerMotors(id) } catch (e: Exception) { null }
|
return controllers[id] ?: phone
|
||||||
}
|
}
|
||||||
return controller ?: phone
|
|
||||||
|
private fun cancelAll() {
|
||||||
|
playing.values.toSet().forEach { it.cancel() }
|
||||||
|
playing.clear()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One place an effect can play. Strengths are the evdev 0..65535 magnitudes. */
|
/** One place an effect can play. Strengths are the evdev 0..65535 magnitudes. */
|
||||||
|
|||||||
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user