mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
195
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7b36f5a4f | ||
|
|
ffb2a3d6e6 | ||
|
|
aff81a13e3 | ||
|
|
570d40f825 | ||
|
|
3dbcefc14c | ||
|
|
9cbad0b1ac | ||
|
|
f524ffc3d6 | ||
|
|
1fe92c978a | ||
|
|
1f016211f2 | ||
|
|
49c5ff188b | ||
|
|
46f99b9e08 | ||
|
|
dcb1a3001b | ||
|
|
dbfcd764f3 | ||
|
|
96e4bd4eab | ||
|
|
d788afc126 | ||
|
|
50a7b1b9f5 | ||
|
|
79027970e1 | ||
|
|
6e9853add5 | ||
|
|
07f2dc8e8f | ||
|
|
0f924aebb0 | ||
|
|
8ec499ae3f | ||
|
|
53c1933ac8 | ||
|
|
4df3f775e1 | ||
|
|
6b570c573b | ||
|
|
d164749a7f | ||
|
|
50c5fd79f7 | ||
|
|
c6169cba80 | ||
|
|
017c1c6b31 | ||
|
|
a8df9a7ae1 | ||
|
|
d38fd373f0 | ||
|
|
a6fe10d8ff | ||
|
|
953549704a | ||
|
|
19d8819137 | ||
|
|
1b80b506cb | ||
|
|
4b289a4802 | ||
|
|
09288e9a1e | ||
|
|
238ef76c5c | ||
|
|
906e66e3cf | ||
|
|
c0d14f9632 | ||
|
|
70bda85dd5 | ||
|
|
9e6f81540f | ||
|
|
3e1fc3e60e | ||
|
|
826853fff5 | ||
|
|
9be131cf6d | ||
|
|
5ed97915c7 | ||
|
|
d8654ae1be | ||
|
|
8f4744398d | ||
|
|
8f4cefd3bd | ||
|
|
01dc415f10 | ||
|
|
af1fe6c61c | ||
|
|
7bf75af8a1 | ||
|
|
c08952dff9 | ||
|
|
58430cd393 | ||
|
|
46d42f9ca9 | ||
|
|
43ff1db06b | ||
|
|
f934feb457 | ||
|
|
79d41b29ad | ||
|
|
bb6523cd9c | ||
|
|
925e9743a8 | ||
|
|
049c4be6e5 | ||
|
|
e36cf24ba9 | ||
|
|
1772291da7 | ||
|
|
3c4ac03656 | ||
|
|
7248d01b1b | ||
|
|
f1f98c3bab | ||
|
|
4405e2a389 | ||
|
|
67b82ad9b4 | ||
|
|
33bdc75a99 | ||
|
|
a573f8b14f | ||
|
|
7630173b24 | ||
|
|
7d942367fd | ||
|
|
da0a01a25b | ||
|
|
9a7cb70969 | ||
|
|
7c8f5c2707 | ||
|
|
14b130500f | ||
|
|
afe81ea69f | ||
|
|
5ca0575e67 | ||
|
|
9e405ec92c | ||
|
|
8f0e124b5d | ||
|
|
31c475d5e1 | ||
|
|
46206b3e16 | ||
|
|
4399db4716 | ||
|
|
ee6cf20ae4 | ||
|
|
2a51b044c5 | ||
|
|
ab023667a0 | ||
|
|
0a27c8bb98 | ||
|
|
bcd4e0d99f | ||
|
|
86ea861818 | ||
|
|
76e0460064 | ||
|
|
64647e0d99 | ||
|
|
8bb1895702 | ||
|
|
ae47876386 | ||
|
|
6e252ea3ad | ||
|
|
1f82db66ac | ||
|
|
fbeefc9c9a | ||
|
|
2e3b69e9ff | ||
|
|
9db80cebd9 | ||
|
|
f920aad104 | ||
|
|
e709e1c454 | ||
|
|
5f8655b13e | ||
|
|
c298da6f60 | ||
|
|
caf16c8aa5 | ||
|
|
c1dd542f97 | ||
|
|
cf44aaed14 | ||
|
|
39debda0b0 | ||
|
|
46ec222fa5 | ||
|
|
e2d87c5083 | ||
|
|
1534cf1c93 | ||
|
|
627344ea30 | ||
|
|
7905e2f8ba | ||
|
|
f6c6e73a6b | ||
|
|
309893b722 | ||
|
|
9b800ceb5e | ||
|
|
a03ec8eb57 | ||
|
|
e349d2544e | ||
|
|
5f2699e56b | ||
|
|
cd87718ac2 | ||
|
|
f9304f41c7 | ||
|
|
95aab3703f | ||
|
|
fcaaf4dde0 | ||
|
|
d967dd03a3 | ||
|
|
366afa6b73 | ||
|
|
5cb8e7fdf3 | ||
|
|
8ee80aa20f | ||
|
|
78f942313d | ||
|
|
8576652fb6 | ||
|
|
f539660650 | ||
|
|
ba3f840b8d | ||
|
|
ec31c9e2b6 | ||
|
|
59e98afae7 | ||
|
|
15b1e196af | ||
|
|
b0a8c0898e | ||
|
|
e3b1b60914 | ||
|
|
86ad1544a6 | ||
|
|
db80e7592a | ||
|
|
6ecc5a22d3 | ||
|
|
963af6df8e | ||
|
|
f683e97172 | ||
|
|
5df25c77ca | ||
|
|
3502b43cea | ||
|
|
4b8c3b158d | ||
|
|
2151db3883 | ||
|
|
823f70320f | ||
|
|
bf7f7ecda7 | ||
|
|
3b8b14b06c | ||
|
|
a305a91c66 | ||
|
|
3e558ab33e | ||
|
|
d5b9cf5b41 | ||
|
|
2478c44948 | ||
|
|
6400a9ef09 | ||
|
|
c78adda7ca | ||
|
|
43b17483fb | ||
|
|
84c877813f | ||
|
|
f43cc43d05 | ||
|
|
101139ec99 | ||
|
|
527cb85867 | ||
|
|
6ef8e2274e | ||
|
|
00525cde15 | ||
|
|
210c127446 | ||
|
|
234e40157e | ||
|
|
c3809c0a75 | ||
|
|
71b7b6efad | ||
|
|
a0e7c1715a | ||
|
|
2c2d55058e | ||
|
|
7f61e514e6 | ||
|
|
b891019b87 | ||
|
|
1a29c65d4f | ||
|
|
ff5e4c7ac7 | ||
|
|
2d38f11b36 | ||
|
|
fd2e1652ad | ||
|
|
c6b6e7362e | ||
|
|
cb7edbefd2 | ||
|
|
a9b5994a91 | ||
|
|
42f25c2a6c | ||
|
|
501debc7f6 | ||
|
|
1f70d43fe2 | ||
|
|
a8d03d687f | ||
|
|
9cfab884d5 | ||
|
|
aefa5a3c0d | ||
|
|
6de3c59d7c | ||
|
|
bc11653c15 | ||
|
|
d6496b2f96 | ||
|
|
3577073ab9 | ||
|
|
a2587f4f20 | ||
|
|
b2687701c1 | ||
|
|
378175c6ac | ||
|
|
183cbd9351 | ||
|
|
6af598b25e | ||
|
|
86226910c3 | ||
|
|
0399c3e510 | ||
|
|
088c8ff1cf | ||
|
|
31dd8f9987 | ||
|
|
567181d05f | ||
|
|
a9054aac3f | ||
|
|
50dace9958 |
No files matched your search
@@ -6,3 +6,4 @@ KeegantheVeganat0r
|
|||||||
kingokksa
|
kingokksa
|
||||||
ovurrsl
|
ovurrsl
|
||||||
KeegantheVeganat0r
|
KeegantheVeganat0r
|
||||||
|
EnzoDLofi
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
name: Build bionic runtime pack and DroidDeck-Bionic tool
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- 'tools/bionic-runtime/**'
|
||||||
|
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
|
||||||
|
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
|
||||||
|
- 'app/src/main/cpp/fakeinput_steam.cpp'
|
||||||
|
- 'tools/gpuload/**'
|
||||||
|
- '.github/workflows/build-bionic-runtime.yml'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 45
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Host tools
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
sudo apt-get update -qq
|
||||||
|
sudo apt-get install -y -qq --no-install-recommends libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev \
|
||||||
|
libxcb1-dev libxcb-composite0-dev libglm-dev zstd
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||||
|
export BUILD_NUMBER=${{ github.run_number }}
|
||||||
|
tools/bionic-runtime/build.sh "$RUNNER_TEMP/bionic-runtime" "$PWD/out"
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: droiddeck-bionic-runtime-${{ github.sha }}
|
||||||
|
path: out/*
|
||||||
@@ -29,11 +29,14 @@ jobs:
|
|||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Build in Arch Linux ARM
|
- name: Build in Arch Linux ARM
|
||||||
env:
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }}
|
FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }}
|
||||||
FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }}
|
FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
docker run --rm -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
|
FEX_VERSION=$(gh api repos/FEX-Emu/FEX/releases/latest --jq .tag_name)
|
||||||
|
echo "Building $FEX_VERSION, FEX's latest release"
|
||||||
|
docker run --rm -e FEX_VERSION="$FEX_VERSION" -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
|
||||||
sudo chown -R "$(id -u):$(id -g)" .
|
sudo chown -R "$(id -u):$(id -g)" .
|
||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -164,6 +164,9 @@ jobs:
|
|||||||
!/docs/releases/media/
|
!/docs/releases/media/
|
||||||
sparse-checkout-cone-mode: false
|
sparse-checkout-cone-mode: false
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
- name: Clear scratch earlier runs left behind
|
||||||
|
if: runner.environment == 'self-hosted'
|
||||||
|
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
|
||||||
- name: Merge the pinned APK base
|
- name: Merge the pinned APK base
|
||||||
if: github.event_name == 'pull_request'
|
if: github.event_name == 'pull_request'
|
||||||
env:
|
env:
|
||||||
@@ -367,6 +370,10 @@ jobs:
|
|||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
submodules: recursive
|
submodules: recursive
|
||||||
|
|
||||||
|
- name: Clear scratch earlier runs left behind
|
||||||
|
if: runner.environment == 'self-hosted'
|
||||||
|
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
|
||||||
|
|
||||||
- name: Check human authorship
|
- name: Check human authorship
|
||||||
env:
|
env:
|
||||||
EVENT_NAME: ${{ github.event_name }}
|
EVENT_NAME: ${{ github.event_name }}
|
||||||
@@ -565,23 +572,65 @@ jobs:
|
|||||||
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
||||||
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
|
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
|
||||||
|
|
||||||
|
# A hosted runner needs over 20 minutes per launcher; rebuild only when its sources change, and save each
|
||||||
|
# build as soon as it finishes so a later timeout cannot discard it.
|
||||||
|
- name: Restore the Ubisoft launcher build
|
||||||
|
id: ubisoft-cache
|
||||||
|
uses: actions/cache/restore@v4
|
||||||
|
with:
|
||||||
|
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
|
||||||
|
key: ubisoft-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/ubisoft-launcher/src/**', 'tools/ubisoft-launcher/Cargo.toml', 'tools/ubisoft-launcher/Cargo.lock', 'tools/ubisoft-launcher/build.sh', 'tools/ubisoft-launcher/build.rs', 'tools/ubisoft-launcher/.cargo/**') }}
|
||||||
- name: Ubisoft launcher service (x86_64-pc-windows-gnu)
|
- name: Ubisoft launcher service (x86_64-pc-windows-gnu)
|
||||||
|
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||||
bash tools/ubisoft-launcher/build.sh
|
bash tools/ubisoft-launcher/build.sh
|
||||||
|
- name: Save the Ubisoft launcher build
|
||||||
|
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
|
||||||
|
uses: actions/cache/save@v4
|
||||||
|
with:
|
||||||
|
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
|
||||||
|
key: ${{ steps.ubisoft-cache.outputs.cache-primary-key }}
|
||||||
|
|
||||||
|
- name: Restore the Rockstar launcher build
|
||||||
|
id: rockstar-cache
|
||||||
|
uses: actions/cache/restore@v4
|
||||||
|
with:
|
||||||
|
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
|
||||||
|
key: rockstar-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/rockstar-launcher/src/**', 'tools/rockstar-launcher/Cargo.toml', 'tools/rockstar-launcher/Cargo.lock', 'tools/rockstar-launcher/build.sh', 'tools/rockstar-launcher/build.rs', 'tools/rockstar-launcher/.cargo/**') }}
|
||||||
- name: Rockstar launcher service (32-bit and 64-bit)
|
- name: Rockstar launcher service (32-bit and 64-bit)
|
||||||
|
if: steps.rockstar-cache.outputs.cache-hit != 'true'
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; }
|
command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; }
|
||||||
|
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||||
bash tools/rockstar-launcher/build.sh
|
bash tools/rockstar-launcher/build.sh
|
||||||
|
- name: Save the Rockstar launcher build
|
||||||
|
if: steps.rockstar-cache.outputs.cache-hit != 'true'
|
||||||
|
uses: actions/cache/save@v4
|
||||||
|
with:
|
||||||
|
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
|
||||||
|
key: ${{ steps.rockstar-cache.outputs.cache-primary-key }}
|
||||||
|
|
||||||
|
- name: Restore the Epic launcher build
|
||||||
|
id: epic-cache
|
||||||
|
uses: actions/cache/restore@v4
|
||||||
|
with:
|
||||||
|
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
|
||||||
|
key: epic-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/epic-launcher/src/**', 'tools/epic-launcher/Cargo.toml', 'tools/epic-launcher/Cargo.lock', 'tools/epic-launcher/build.sh', 'tools/epic-launcher/build.rs', 'tools/epic-launcher/.cargo/**') }}
|
||||||
- name: Epic Games Launcher parent stand-in (x86_64-pc-windows-gnu)
|
- name: Epic Games Launcher parent stand-in (x86_64-pc-windows-gnu)
|
||||||
|
if: steps.epic-cache.outputs.cache-hit != 'true'
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||||
bash tools/epic-launcher/build.sh
|
bash tools/epic-launcher/build.sh
|
||||||
|
- name: Save the Epic launcher build
|
||||||
|
if: steps.epic-cache.outputs.cache-hit != 'true'
|
||||||
|
uses: actions/cache/save@v4
|
||||||
|
with:
|
||||||
|
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
|
||||||
|
key: ${{ steps.epic-cache.outputs.cache-primary-key }}
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
@@ -685,6 +734,37 @@ jobs:
|
|||||||
if-no-files-found: ignore
|
if-no-files-found: ignore
|
||||||
overwrite: true
|
overwrite: true
|
||||||
|
|
||||||
|
- name: Resolve the Robolectric version
|
||||||
|
id: robolectric
|
||||||
|
run: |
|
||||||
|
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
|
||||||
|
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
|
||||||
|
# The cache path sits beside the workspace because runner homes are at different depths from it, and
|
||||||
|
# actions/cache stores paths relative to the workspace. Runners that keep their own ~/.m2 skip the cache.
|
||||||
|
- name: Place Robolectric's Android jars beside the workspace
|
||||||
|
id: robolectric-jars
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
jars="$GITHUB_WORKSPACE/../robolectric-jars"
|
||||||
|
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
|
||||||
|
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
|
||||||
|
echo "cache=false" >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
mkdir -p "$jars" "$(dirname "$m2")"
|
||||||
|
ln -sfn "$(cd "$jars" && pwd)" "$m2"
|
||||||
|
echo "cache=true" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
- name: Restore Robolectric's Android jars
|
||||||
|
id: robolectric-cache
|
||||||
|
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||||
|
uses: actions/cache/restore@v4
|
||||||
|
with:
|
||||||
|
path: ../robolectric-jars
|
||||||
|
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||||
|
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
|
||||||
|
- name: Count the restored Robolectric jars
|
||||||
|
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||||
|
run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV"
|
||||||
- name: Unit tests
|
- name: Unit tests
|
||||||
id: unit-tests
|
id: unit-tests
|
||||||
env:
|
env:
|
||||||
@@ -695,6 +775,34 @@ jobs:
|
|||||||
mkdir -p app/build
|
mkdir -p app/build
|
||||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
|
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
|
||||||
|
|
||||||
|
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
|
||||||
|
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
|
||||||
|
- name: Save Robolectric's Android jars
|
||||||
|
id: robolectric-jars-final
|
||||||
|
if: always() && steps.robolectric-jars.outputs.cache == 'true'
|
||||||
|
run: |
|
||||||
|
python3 - <<'PY'
|
||||||
|
import glob, os, zipfile
|
||||||
|
root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars')
|
||||||
|
for f in glob.glob(os.path.join(root, '**', '*'), recursive=True):
|
||||||
|
if not os.path.isfile(f):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None
|
||||||
|
except Exception:
|
||||||
|
ok = False
|
||||||
|
if not ok:
|
||||||
|
os.remove(f)
|
||||||
|
PY
|
||||||
|
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
|
||||||
|
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
|
||||||
|
- name: Store Robolectric's Android jars
|
||||||
|
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
|
||||||
|
uses: actions/cache/save@v4
|
||||||
|
with:
|
||||||
|
path: ../robolectric-jars
|
||||||
|
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||||
|
|
||||||
- name: Upload unit test diagnostics
|
- name: Upload unit test diagnostics
|
||||||
id: unit-test-diagnostics
|
id: unit-test-diagnostics
|
||||||
if: always() && steps.unit-tests.outcome != 'skipped'
|
if: always() && steps.unit-tests.outcome != 'skipped'
|
||||||
|
|||||||
@@ -2,7 +2,42 @@
|
|||||||
|
|
||||||
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
|
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
|
||||||
|
|
||||||
# Working on the device
|
# Building and testing
|
||||||
|
|
||||||
|
- For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step.
|
||||||
|
- `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`.
|
||||||
|
- Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout.
|
||||||
|
- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally.
|
||||||
|
- Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '<class>'` and `python3 -m unittest discover -s tools/tests -p 'test_<area>*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI.
|
||||||
|
- For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape.
|
||||||
|
- After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`.
|
||||||
|
- Compile errors in code you didn't touch, after switching branches, are usually stale incremental state. Rebuild once before you change anything.
|
||||||
|
|
||||||
|
# Worktrees and shared machines
|
||||||
|
|
||||||
|
- After `git worktree add`, run `git submodule update --init --recursive`. Without it, `buildVkBridgeServer` fails on missing `external/MaliBridge`. Do not commit the `tools/syncthing/syncthing-android` pointer the build dirties.
|
||||||
|
- Other agents may be building on the same machine. Never run `./gradlew --stop` or kill Gradle/Kotlin daemons you did not start. If you need isolation, use `GRADLE_USER_HOME=<own dir> GRADLE_RO_DEP_CACHE=$HOME/.gradle/caches`.
|
||||||
|
|
||||||
|
# Driving the app and device
|
||||||
|
|
||||||
|
- Do it yourself with `tools/droiddeckctl` (see `docs/agent-control.md`) instead of asking the user: `cdp eval` for Steam's UI (`SteamClient.Apps.TerminateApp('<appid>', false)` quits a game, including on a Remote Play host), `input`, `quit`, `displays`, `screenshot --display <id>`.
|
||||||
|
- A stream has started only when the session state reads `Streaming`. `SteamClient.Apps.StreamGame` alone can leave Steam on its menu, so open the game page and press Stream.
|
||||||
|
- Test controller navigation with `tools/droiddeckctl input gamepad ...`, a real uinput pad. `adb shell input keyevent DPAD_*` does not arrive as a joystick event and hides d-pad/stick bugs.
|
||||||
|
- A release-signed build installs over a release-signed install with `adb install -r`. Don't back up, uninstall or clear data to update. Scope `pm` and permission resets to `com.droiddeck.launcher`, never the whole device.
|
||||||
|
|
||||||
|
# CI
|
||||||
|
|
||||||
|
- Before pushing a PR, run `tools/pre_pr.sh`. It checks authorship and the merge onto `main`, then, when app sources change, compiles and runs lint as CI does. It picks tests by name: `<File>*Test` for changed Kotlin files, and `tools/tests` modules that mention a changed path. Add any other tests that cover your change, and leave the full suites to CI.
|
||||||
|
- CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge.
|
||||||
|
- Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors.
|
||||||
|
- Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them.
|
||||||
|
- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs/<job-id>/logs`, or `gh run download <run> -n unit-test-results`. Don't call a failure a runner problem until you have read it.
|
||||||
|
- Only these are known flakes worth a `gh run rerun <run> --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real.
|
||||||
|
- A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`.
|
||||||
|
|
||||||
|
# Agents running on the device (DroidDeck's in-app agent)
|
||||||
|
|
||||||
|
These apply only where `dd-lab-build` exists. Agents on a dev host use `tools/quick_deploy.sh` instead.
|
||||||
|
|
||||||
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
|
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
|
||||||
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
|
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
|
||||||
|
|||||||
@@ -7,10 +7,10 @@
|
|||||||
|
|
||||||
DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linux desktop, integration with GOG, Epic Games, Xbox, and other storefronts, Steam VR, and more!
|
DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linux desktop, integration with GOG, Epic Games, Xbox, and other storefronts, Steam VR, and more!
|
||||||
|
|
||||||
<p align="center"><b>100% open source. No ads. No telemetry. No proprietary components. No source withheld.</b></p>
|
<p align="center"><b>100% open source. No ads. No Subscriptions. No telemetry. No proprietary components. No source withheld.</b></p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.1%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.1"></a>
|
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.11%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.11"></a>
|
||||||
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
|
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
|
|||||||
<a href="https://trendshift.io/repositories/267852"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"></a>
|
<a href="https://trendshift.io/repositories/267852"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center"><img src="docs/media/steam-to-desktop.gif" width="100%" alt="On a Retroid Pocket Duo: Play Steam from the DroidDeck launcher, open Pac-Man in Steam Big Picture and play it, exit the game, then Switch to Desktop from the Power menu"></p>
|
<p align="center"><a href="https://www.youtube.com/watch?v=ruaTSm_7a2c"><img src="docs/media/droiddeck-showcase.gif" width="60%" alt="A table of handhelds and phones all running DroidDeck, one waking to the Steam menu, the AYN Thor's bottom screen used as a touchpad, and scrolling around Steam on a phone before swiping to the home screen. Footage from Cyber Dopamine's video, linked."></a></p>
|
||||||
|
|
||||||
> The official website is [droid-deck.dev](https://droid-deck.dev). Only download DroidDeck from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
|
> The official website is [droid-deck.dev](https://droid-deck.dev). Only download DroidDeck from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
|
|||||||
|
|
||||||
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
|
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
|
||||||
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
|
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
|
||||||
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk), install the Linux runtime, press **Play** and sign in to Steam.
|
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk), install the Linux runtime, press **Play** and sign in to Steam.
|
||||||
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
|
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
|
||||||
|
|
||||||
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
|
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
|
||||||
@@ -57,9 +57,6 @@ The APK lands in `app/build/outputs/apk/release/`. Install it with `tools/deploy
|
|||||||
|
|
||||||
On Windows, see `tools/run_windows.ps1` and `tools/prepare_windows_runtime.py`.
|
On Windows, see `tools/run_windows.ps1` and `tools/prepare_windows_runtime.py`.
|
||||||
|
|
||||||
## Limits
|
|
||||||
|
|
||||||
Compatibility and performance vary by device. Desktop compositing is software rendered, and Firefox sandboxing is reduced under proot.
|
|
||||||
|
|
||||||
## Credits and licence
|
## Credits and licence
|
||||||
|
|
||||||
@@ -70,8 +67,10 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
|||||||
|
|
||||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source.
|
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
||||||
|
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
|
||||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||||
|
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
|
||||||
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
||||||
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
||||||
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
|
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
|
||||||
@@ -91,7 +90,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
|||||||
<details>
|
<details>
|
||||||
<summary><b>Stores</b></summary>
|
<summary><b>Stores</b></summary>
|
||||||
|
|
||||||
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send.
|
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send. Deleted GOG cloud saves are recognised by the empty-gzip deletion hash gogdl and Lutris skip.
|
||||||
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
|
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
|
||||||
- The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268).
|
- The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268).
|
||||||
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
|
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
|
||||||
@@ -99,7 +98,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
|||||||
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
|
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
|
||||||
- The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code.
|
- The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code.
|
||||||
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
|
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
|
||||||
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
|
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. Installed addons show their `.toc` version and `X-WoWI-ID`, and are checked against that list for updates, as [WowUp](https://github.com/WowUp/WowUp) does. The Addons tab installs the official [CurseForge](https://www.curseforge.com/download/app) Linux app from CurseForge's own update feed (downloaded at install time and checked against its SHA-512, not included), which keeps its own sign-in.
|
||||||
- The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
|
- The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
|
||||||
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
|
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
|
||||||
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
|
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
|
||||||
|
|||||||
+10
-8
@@ -125,14 +125,15 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
|
|||||||
android {
|
android {
|
||||||
namespace 'com.droiddeck.launcher'
|
namespace 'com.droiddeck.launcher'
|
||||||
compileSdk 34
|
compileSdk 34
|
||||||
ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
|
ndkVersion project.findProperty('ndkVersion') ?: providers.fileContents(rootProject.layout.projectDirectory.file('tools/ci/toolchains.env'))
|
||||||
|
.asText.get().readLines().find { it.startsWith('CI_ANDROID_NDK_VERSION=') }.split('=', 2)[1].trim()
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId "com.droiddeck.launcher"
|
applicationId "com.droiddeck.launcher"
|
||||||
minSdkVersion 26
|
minSdkVersion 26
|
||||||
targetSdkVersion 34
|
targetSdkVersion 34
|
||||||
versionCode 19
|
versionCode 20
|
||||||
versionName "0.7.1"
|
versionName "0.7.11"
|
||||||
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}"
|
||||||
@@ -232,6 +233,9 @@ android {
|
|||||||
}
|
}
|
||||||
maxHeapSize = '2g'
|
maxHeapSize = '2g'
|
||||||
maxParallelForks = 2
|
maxParallelForks = 2
|
||||||
|
def jvmTemp = new File(temporaryDir, 'jvm')
|
||||||
|
systemProperty 'java.io.tmpdir', jvmTemp.absolutePath
|
||||||
|
doFirst { jvmTemp.mkdirs() }
|
||||||
def logTarget = providers.systemProperty('robolectric.logging').orNull
|
def logTarget = providers.systemProperty('robolectric.logging').orNull
|
||||||
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
|
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
|
||||||
}
|
}
|
||||||
@@ -261,11 +265,9 @@ if (vitureSdkDir) {
|
|||||||
tasks.named('preBuild').configure { dependsOn(stageVitureNotices) }
|
tasks.named('preBuild').configure { dependsOn(stageVitureNotices) }
|
||||||
}
|
}
|
||||||
|
|
||||||
def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
|
def stageSessionScripts = tasks.register('stageSessionScripts', Exec) {
|
||||||
from(rootProject.file('tools/linuxfs/overlay')) {
|
workingDir rootProject.projectDir
|
||||||
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
|
commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage'
|
||||||
}
|
|
||||||
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
|
|
||||||
}
|
}
|
||||||
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
|
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Li
|
|||||||
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
|
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
|
||||||
|
|
||||||
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
|
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
|
||||||
|
@DroidDeckPreviews @Composable private fun SteamEmptyPreview() = Launcher("steam", games = emptyList())
|
||||||
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
|
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
|
||||||
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
|
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
|
||||||
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
|
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ internal val sampleActions: FrontEndActions = FrontEndActions(
|
|||||||
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
|
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
|
||||||
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
|
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
|
||||||
onFiles = {}, onLogs = {}, onOffline = {},
|
onFiles = {}, onLogs = {}, onOffline = {},
|
||||||
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> },
|
onSetPhantomProcessLimit = { _, _ -> },
|
||||||
)
|
)
|
||||||
|
|
||||||
/** The in-game menu's actions with settled sample values; its switches do nothing. */
|
/** The in-game menu's actions with settled sample values; its switches do nothing. */
|
||||||
|
|||||||
@@ -232,6 +232,7 @@
|
|||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:screenOrientation="user"
|
android:screenOrientation="user"
|
||||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||||
|
android:windowSoftInputMode="adjustResize"
|
||||||
android:theme="@style/AppTheme" />
|
android:theme="@style/AppTheme" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
#define SYS_munmap 215
|
#define SYS_munmap 215
|
||||||
#define SYS_mmap 222
|
#define SYS_mmap 222
|
||||||
#define SYS_mprotect 226
|
#define SYS_mprotect 226
|
||||||
|
#define SYS_getpid 172
|
||||||
|
|
||||||
#define AT_FDCWD_ (-100)
|
#define AT_FDCWD_ (-100)
|
||||||
#define O_RDONLY_ 0
|
#define O_RDONLY_ 0
|
||||||
@@ -52,6 +53,21 @@ static size_t slen(const char *s) {
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static int seq(const char *a, const char *b) {
|
||||||
|
while (*a && *a == *b) a++, b++;
|
||||||
|
return *a == *b;
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char *env_get(char **envp, const char *name) {
|
||||||
|
size_t n = slen(name);
|
||||||
|
for (; *envp; envp++) {
|
||||||
|
size_t i = 0;
|
||||||
|
while (i < n && (*envp)[i] == name[i]) i++;
|
||||||
|
if (i == n && (*envp)[n] == '=') return *envp + n + 1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); }
|
static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); }
|
||||||
|
|
||||||
static void out_num(long v) {
|
static void out_num(long v) {
|
||||||
@@ -112,19 +128,43 @@ static int prot_of(uint32_t flags) {
|
|||||||
|
|
||||||
static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); }
|
static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); }
|
||||||
|
|
||||||
static void load(const char *path, struct image *im, uintptr_t page) {
|
static void read_interp(int fd, const Elf64_Phdr *ph, int phnum, char *interp, size_t size, const char *path) {
|
||||||
|
interp[0] = 0;
|
||||||
|
for (int i = 0; i < phnum; i++) {
|
||||||
|
if (ph[i].p_type != PT_INTERP) continue;
|
||||||
|
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= size) die("bad PT_INTERP", path, 0);
|
||||||
|
if (xpread(fd, interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
|
||||||
|
die("truncated PT_INTERP", path, 0);
|
||||||
|
interp[ph[i].p_filesz] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int read_headers(const char *path, Elf64_Ehdr *eh, Elf64_Phdr *ph) {
|
||||||
int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0);
|
int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0);
|
||||||
if (fd < 0) die("cannot open", path, fd);
|
if (fd < 0) die("cannot open", path, fd);
|
||||||
Elf64_Ehdr eh;
|
if (xpread(fd, eh, sizeof(*eh), 0) != (long)sizeof(*eh)) die("not an ELF file", path, 0);
|
||||||
if (xpread(fd, &eh, sizeof(eh), 0) != (long)sizeof(eh)) die("not an ELF file", path, 0);
|
if (eh->e_ident[EI_MAG0] != ELFMAG0 || eh->e_ident[EI_MAG1] != ELFMAG1 || eh->e_ident[EI_MAG2] != ELFMAG2 ||
|
||||||
if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || eh.e_ident[EI_MAG2] != ELFMAG2 ||
|
eh->e_ident[EI_MAG3] != ELFMAG3 || eh->e_ident[EI_CLASS] != ELFCLASS64 || eh->e_machine != EM_AARCH64 ||
|
||||||
eh.e_ident[EI_MAG3] != ELFMAG3 || eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_AARCH64 ||
|
(eh->e_type != ET_EXEC && eh->e_type != ET_DYN) || eh->e_phentsize != sizeof(Elf64_Phdr) ||
|
||||||
(eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || eh.e_phentsize != sizeof(Elf64_Phdr) ||
|
eh->e_phnum == 0 || eh->e_phnum > MAX_PHDRS)
|
||||||
eh.e_phnum == 0 || eh.e_phnum > MAX_PHDRS)
|
|
||||||
die("not a 64-bit ARM ELF program", path, 0);
|
die("not a 64-bit ARM ELF program", path, 0);
|
||||||
|
long size = (long)eh->e_phnum * (long)sizeof(Elf64_Phdr);
|
||||||
|
if (xpread(fd, ph, (size_t)size, (long)eh->e_phoff) != size) die("truncated program headers", path, 0);
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void interp_of(const char *path, char *interp, size_t size) {
|
||||||
|
Elf64_Ehdr eh;
|
||||||
Elf64_Phdr ph[MAX_PHDRS];
|
Elf64_Phdr ph[MAX_PHDRS];
|
||||||
long size = (long)eh.e_phnum * (long)sizeof(Elf64_Phdr);
|
int fd = read_headers(path, &eh, ph);
|
||||||
if (xpread(fd, ph, (size_t)size, (long)eh.e_phoff) != size) die("truncated program headers", path, 0);
|
read_interp(fd, ph, eh.e_phnum, interp, size, path);
|
||||||
|
sys6(SYS_close, fd, 0, 0, 0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void load(const char *path, struct image *im, uintptr_t page) {
|
||||||
|
Elf64_Ehdr eh;
|
||||||
|
Elf64_Phdr ph[MAX_PHDRS];
|
||||||
|
int fd = read_headers(path, &eh, ph);
|
||||||
|
|
||||||
uintptr_t lo = UINTPTR_MAX, hi = 0;
|
uintptr_t lo = UINTPTR_MAX, hi = 0;
|
||||||
for (int i = 0; i < eh.e_phnum; i++) {
|
for (int i = 0; i < eh.e_phnum; i++) {
|
||||||
@@ -173,16 +213,9 @@ static void load(const char *path, struct image *im, uintptr_t page) {
|
|||||||
im->phnum = eh.e_phnum;
|
im->phnum = eh.e_phnum;
|
||||||
im->phent = eh.e_phentsize;
|
im->phent = eh.e_phentsize;
|
||||||
im->phdr = 0;
|
im->phdr = 0;
|
||||||
im->interp[0] = 0;
|
read_interp(fd, ph, eh.e_phnum, im->interp, sizeof(im->interp), path);
|
||||||
for (int i = 0; i < eh.e_phnum; i++) {
|
for (int i = 0; i < eh.e_phnum; i++)
|
||||||
if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr;
|
if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr;
|
||||||
if (ph[i].p_type == PT_INTERP) {
|
|
||||||
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= sizeof(im->interp)) die("bad PT_INTERP", path, 0);
|
|
||||||
if (xpread(fd, im->interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
|
|
||||||
die("truncated PT_INTERP", path, 0);
|
|
||||||
im->interp[ph[i].p_filesz] = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!im->phdr) {
|
if (!im->phdr) {
|
||||||
for (int i = 0; i < eh.e_phnum; i++) {
|
for (int i = 0; i < eh.e_phnum; i++) {
|
||||||
Elf64_Phdr *p = &ph[i];
|
Elf64_Phdr *p = &ph[i];
|
||||||
@@ -202,6 +235,36 @@ static unsigned long auxv_get(const uintptr_t *auxv, unsigned long type, unsigne
|
|||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static int is_self_exe(const char *execfn) {
|
||||||
|
if (!execfn) return 0;
|
||||||
|
if (seq(execfn, "/proc/self/exe") || seq(execfn, "/proc/thread-self/exe")) return 1;
|
||||||
|
const char *p = "/proc/";
|
||||||
|
while (*p && *p == *execfn) p++, execfn++;
|
||||||
|
if (*p) return 0;
|
||||||
|
char num[24];
|
||||||
|
int i = (int)sizeof(num) - 1;
|
||||||
|
num[i] = 0;
|
||||||
|
unsigned long pid = (unsigned long)sys6(SYS_getpid, 0, 0, 0, 0, 0, 0);
|
||||||
|
do {
|
||||||
|
num[--i] = (char)('0' + pid % 10);
|
||||||
|
pid /= 10;
|
||||||
|
} while (pid && i > 0);
|
||||||
|
const char *d = num + i;
|
||||||
|
while (*d && *d == *execfn) d++, execfn++;
|
||||||
|
return !*d && seq(execfn, "/exe");
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) {
|
||||||
|
const char *root = env_get(envp, "DDNATV_ROOT");
|
||||||
|
if (!root || interp[0] != '/') return interp;
|
||||||
|
size_t a = slen(root), b = slen(interp);
|
||||||
|
if (a + b + 1 > size) return interp;
|
||||||
|
for (size_t i = 0; i < a; i++) buf[i] = root[i];
|
||||||
|
for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i];
|
||||||
|
if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp;
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
__attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
|
__attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
|
||||||
long argc = (long)sp[0];
|
long argc = (long)sp[0];
|
||||||
char **argv = (char **)(sp + 1);
|
char **argv = (char **)(sp + 1);
|
||||||
@@ -211,25 +274,66 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
|
|||||||
uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1);
|
uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1);
|
||||||
long naux = 0;
|
long naux = 0;
|
||||||
while (auxv[naux * 2] != AT_NULL) naux++;
|
while (auxv[naux * 2] != AT_NULL) naux++;
|
||||||
if (argc < 3) die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
|
int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0));
|
||||||
|
const char *path;
|
||||||
|
char **args = argv + 2;
|
||||||
|
long nargs = argc - 2;
|
||||||
|
char interp_buf[4096];
|
||||||
|
char hook_buf[4096];
|
||||||
|
if (reexec) {
|
||||||
|
path = env_get(envp, "DDNATV_REAL_EXE");
|
||||||
|
if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0);
|
||||||
|
args = argv;
|
||||||
|
nargs = argc;
|
||||||
|
const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH");
|
||||||
|
char prog_interp[256];
|
||||||
|
interp_of(path, prog_interp, sizeof(prog_interp));
|
||||||
|
if (prog_interp[0] && lib_path && lib_path[0]) {
|
||||||
|
const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf));
|
||||||
|
const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
|
||||||
|
if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
|
||||||
|
long n = argc > 1 ? argc - 1 : 0;
|
||||||
|
char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *));
|
||||||
|
long k = 0;
|
||||||
|
v[k++] = (char *)ld_so;
|
||||||
|
if (hook == (const char *)hook_buf) {
|
||||||
|
v[k++] = (char *)"--preload";
|
||||||
|
v[k++] = (char *)hook;
|
||||||
|
}
|
||||||
|
v[k++] = (char *)"--library-path";
|
||||||
|
v[k++] = (char *)lib_path;
|
||||||
|
v[k++] = (char *)"--argv0";
|
||||||
|
v[k++] = argc > 0 ? argv[0] : (char *)path;
|
||||||
|
v[k++] = (char *)path;
|
||||||
|
for (long i = 0; i < n; i++) v[k++] = argv[1 + i];
|
||||||
|
v[k] = 0;
|
||||||
|
args = v;
|
||||||
|
nargs = k;
|
||||||
|
path = ld_so;
|
||||||
|
}
|
||||||
|
} else if (argc < 3) {
|
||||||
|
die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
|
||||||
|
} else {
|
||||||
|
path = argv[1];
|
||||||
|
}
|
||||||
|
|
||||||
uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096);
|
uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096);
|
||||||
const char *path = argv[1];
|
|
||||||
struct image prog, interp;
|
struct image prog, interp;
|
||||||
load(path, &prog, page);
|
load(path, &prog, page);
|
||||||
int has_interp = prog.interp[0] != 0;
|
int has_interp = prog.interp[0] != 0;
|
||||||
if (has_interp) load(prog.interp, &interp, page);
|
if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page);
|
||||||
|
|
||||||
// The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one.
|
// The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one.
|
||||||
// The strings stay where the kernel put them.
|
// The strings stay where the kernel put them.
|
||||||
static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN};
|
static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN};
|
||||||
long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0]));
|
long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0]));
|
||||||
long new_argc = argc - 2;
|
long new_argc = nargs;
|
||||||
long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2;
|
long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2;
|
||||||
uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
|
uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp;
|
||||||
|
uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
|
||||||
uintptr_t *w = nsp;
|
uintptr_t *w = nsp;
|
||||||
*w++ = (uintptr_t)new_argc;
|
*w++ = (uintptr_t)new_argc;
|
||||||
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2];
|
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i];
|
||||||
*w++ = 0;
|
*w++ = 0;
|
||||||
for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i];
|
for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i];
|
||||||
*w++ = 0;
|
*w++ = 0;
|
||||||
|
|||||||
@@ -58,6 +58,59 @@
|
|||||||
|
|
||||||
#define EXPORT extern "C" __attribute__((visibility("default")))
|
#define EXPORT extern "C" __attribute__((visibility("default")))
|
||||||
|
|
||||||
|
struct SymbolSlot {
|
||||||
|
std::atomic<void *> fn{nullptr};
|
||||||
|
std::atomic<bool> resolved{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Fn> static Fn resolved_symbol(SymbolSlot &slot, void *handle, const char *name) {
|
||||||
|
if (!slot.resolved.load(std::memory_order_acquire)) {
|
||||||
|
slot.fn.store(dlsym(handle, name), std::memory_order_relaxed);
|
||||||
|
slot.resolved.store(true, std::memory_order_release);
|
||||||
|
}
|
||||||
|
return reinterpret_cast<Fn>(slot.fn.load(std::memory_order_relaxed));
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class Next : size_t {
|
||||||
|
open,
|
||||||
|
openat,
|
||||||
|
close,
|
||||||
|
write,
|
||||||
|
ioctl,
|
||||||
|
poll,
|
||||||
|
ppoll,
|
||||||
|
select,
|
||||||
|
stat,
|
||||||
|
stat64,
|
||||||
|
fstat,
|
||||||
|
fstat64,
|
||||||
|
xstat,
|
||||||
|
xstat64,
|
||||||
|
fxstat,
|
||||||
|
fxstat64,
|
||||||
|
statx,
|
||||||
|
statfs,
|
||||||
|
fstatfs,
|
||||||
|
access,
|
||||||
|
faccessat,
|
||||||
|
opendir,
|
||||||
|
scandir,
|
||||||
|
inotify_add_watch,
|
||||||
|
count
|
||||||
|
};
|
||||||
|
|
||||||
|
static const char *const next_names[] = {"open", "openat", "close", "write", "ioctl", "poll", "ppoll", "select", "stat", "stat64", "fstat", "fstat64", "__xstat", "__xstat64", "__fxstat", "__fxstat64", "statx", "statfs", "fstatfs", "access", "faccessat", "opendir", "scandir", "inotify_add_watch"};
|
||||||
|
static_assert(sizeof(next_names) / sizeof(next_names[0]) == static_cast<size_t>(Next::count), "next_names");
|
||||||
|
static SymbolSlot next_slots[static_cast<size_t>(Next::count)];
|
||||||
|
|
||||||
|
template <typename Fn> static Fn next_symbol(Next which) {
|
||||||
|
return resolved_symbol<Fn>(next_slots[static_cast<size_t>(which)], RTLD_NEXT, next_names[static_cast<size_t>(which)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void resolve_next_symbols() {
|
||||||
|
for (size_t i = 0; i < static_cast<size_t>(Next::count); i++) next_symbol<void *>(static_cast<Next>(i));
|
||||||
|
}
|
||||||
|
|
||||||
#ifdef __GLIBC__
|
#ifdef __GLIBC__
|
||||||
typedef unsigned long ioctl_request_t;
|
typedef unsigned long ioctl_request_t;
|
||||||
#else
|
#else
|
||||||
@@ -205,6 +258,11 @@ static void controller_fork_prepare();
|
|||||||
static void controller_fork_parent();
|
static void controller_fork_parent();
|
||||||
static void controller_fork_child();
|
static void controller_fork_child();
|
||||||
|
|
||||||
|
// bionic: libc's own start-up calls hooked functions (access) before environ is set. Settings read
|
||||||
|
// then would be empty and cached for good, so until environ exists hooks see defaults, uncached.
|
||||||
|
extern "C" char **environ;
|
||||||
|
static bool env_ready() { return environ != nullptr; }
|
||||||
|
|
||||||
struct FakeConfig {
|
struct FakeConfig {
|
||||||
const char *hook_dir;
|
const char *hook_dir;
|
||||||
const char *udev_data_dir;
|
const char *udev_data_dir;
|
||||||
@@ -218,6 +276,10 @@ struct FakeConfig {
|
|||||||
// would throw a recursive-init error there, so the fields are filled without allocating, and a
|
// would throw a recursive-init error there, so the fields are filled without allocating, and a
|
||||||
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
|
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
|
||||||
static FakeConfig &config() {
|
static FakeConfig &config() {
|
||||||
|
if (!env_ready()) {
|
||||||
|
static FakeConfig early = {"/data/data/com.termux/files/home/fake-input", nullptr, false, false, false};
|
||||||
|
return early;
|
||||||
|
}
|
||||||
static FakeConfig cfg;
|
static FakeConfig cfg;
|
||||||
static std::atomic<int> state{0};
|
static std::atomic<int> state{0};
|
||||||
static __thread bool initializing __attribute__((tls_model("initial-exec")));
|
static __thread bool initializing __attribute__((tls_model("initial-exec")));
|
||||||
@@ -433,6 +495,7 @@ void log(const char *message, ...) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((constructor)) static void library_init() {
|
__attribute__((constructor)) static void library_init() {
|
||||||
|
resolve_next_symbols();
|
||||||
config();
|
config();
|
||||||
controller_mutex();
|
controller_mutex();
|
||||||
controller_map();
|
controller_map();
|
||||||
@@ -587,7 +650,7 @@ get_fake_input_rdev(const char *event) {
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static void load_ring_paths() {
|
__attribute__((visibility("hidden"))) static void load_ring_paths() {
|
||||||
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
||||||
if (ring_paths_loaded)
|
if (ring_paths_loaded || !env_ready())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
|
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
|
||||||
@@ -724,7 +787,7 @@ open_fake_input_ring(const char *event, int flags) {
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
|
|
||||||
int fd = my_open(ring_path.c_str(), O_RDWR | (flags & (O_NONBLOCK | O_CLOEXEC)));
|
int fd = my_open(ring_path.c_str(), O_RDWR | (flags & (O_NONBLOCK | O_CLOEXEC)));
|
||||||
if (fd < 0)
|
if (fd < 0)
|
||||||
@@ -807,12 +870,25 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
|
|||||||
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
|
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
|
||||||
static int known;
|
static int known;
|
||||||
if (known == 0) {
|
if (known == 0) {
|
||||||
|
if (!env_ready()) return false;
|
||||||
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
|
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
|
||||||
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
|
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
|
||||||
}
|
}
|
||||||
return known == 1;
|
return known == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The bionic Proton layer's winebus has no udev bus, and its SDL bus skips 28de:11ff (Proton reads Steam's virtual
|
||||||
|
// pad through udev/evdev), so with FAKE_EVDEV_STEAM_PAD_AS_X360=1 other processes see that pad as a plain Xbox 360 pad.
|
||||||
|
__attribute__((visibility("hidden"))) static bool steam_pad_as_x360() {
|
||||||
|
static int known;
|
||||||
|
if (known == 0) {
|
||||||
|
if (!env_ready()) return false;
|
||||||
|
const char *v = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
|
||||||
|
known = v && atoi(v) && !is_steam_client() ? 1 : -1;
|
||||||
|
}
|
||||||
|
return known == 1;
|
||||||
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static bool
|
__attribute__((visibility("hidden"))) static bool
|
||||||
presents_xbox_triggers(const FakeController &fake) {
|
presents_xbox_triggers(const FakeController &fake) {
|
||||||
return fake.uinput || !is_steam_client();
|
return fake.uinput || !is_steam_client();
|
||||||
@@ -978,7 +1054,7 @@ __attribute__((visibility("hidden"))) static void unpublish_uinput(UinputWriter
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out) {
|
__attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out) {
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
for (int node = UINPUT_EVENT_BASE; node < UINPUT_EVENT_LIMIT; node++) {
|
for (int node = UINPUT_EVENT_BASE; node < UINPUT_EVENT_LIMIT; node++) {
|
||||||
std::string path = uinput_ring_path(node);
|
std::string path = uinput_ring_path(node);
|
||||||
int fd = my_open(path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
|
int fd = my_open(path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
|
||||||
@@ -1005,7 +1081,7 @@ __attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out)
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w) {
|
__attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w) {
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
int fd = -1;
|
int fd = -1;
|
||||||
int node = claim_uinput_node(&fd);
|
int node = claim_uinput_node(&fd);
|
||||||
if (node < 0) return -1;
|
if (node < 0) return -1;
|
||||||
@@ -1391,6 +1467,7 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
|
|||||||
|
|
||||||
static bool fake_deck_enabled() {
|
static bool fake_deck_enabled() {
|
||||||
static int enabled = -1;
|
static int enabled = -1;
|
||||||
|
if (enabled < 0 && !env_ready()) return false;
|
||||||
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
|
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
|
||||||
return enabled == 1;
|
return enabled == 1;
|
||||||
}
|
}
|
||||||
@@ -1398,6 +1475,7 @@ static bool fake_deck_enabled() {
|
|||||||
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
|
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
|
||||||
static int type = -1;
|
static int type = -1;
|
||||||
if (type < 0) {
|
if (type < 0) {
|
||||||
|
if (!env_ready()) return PAD_TYPE_DECK;
|
||||||
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
|
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
|
||||||
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
|
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
|
||||||
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
|
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
|
||||||
@@ -1416,7 +1494,7 @@ __attribute__((visibility("hidden"))) static const uint8_t *ring_blocks() {
|
|||||||
std::lock_guard<std::mutex> guard(lock);
|
std::lock_guard<std::mutex> guard(lock);
|
||||||
if ((mapped = block.load(std::memory_order_acquire))) return mapped;
|
if ((mapped = block.load(std::memory_order_acquire))) return mapped;
|
||||||
tries.fetch_add(1, std::memory_order_relaxed);
|
tries.fetch_add(1, std::memory_order_relaxed);
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
std::string path = get_ring_path_for_slot(0);
|
std::string path = get_ring_path_for_slot(0);
|
||||||
int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||||
if (fd < 0) return nullptr;
|
if (fd < 0) return nullptr;
|
||||||
@@ -1470,6 +1548,7 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
|
|||||||
|
|
||||||
static bool fake_triton_enabled() {
|
static bool fake_triton_enabled() {
|
||||||
static int enabled = -1;
|
static int enabled = -1;
|
||||||
|
if (enabled < 0 && !env_ready()) return false;
|
||||||
if (enabled < 0)
|
if (enabled < 0)
|
||||||
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
|
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
|
||||||
return enabled == 1;
|
return enabled == 1;
|
||||||
@@ -1768,7 +1847,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
|
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
|
||||||
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
|
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
if (!process_reads_pads()) {
|
if (!process_reads_pads()) {
|
||||||
Logger::log("deck: %s refused: not the Steam client\n", path);
|
Logger::log("deck: %s refused: not the Steam client\n", path);
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
@@ -1977,7 +2056,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
|
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
if (!process_reads_pads()) {
|
if (!process_reads_pads()) {
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
@@ -2091,11 +2170,12 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
||||||
static TouchRingFile *ring = nullptr;
|
static TouchRingFile *ring = nullptr;
|
||||||
|
if (!env_ready()) return nullptr;
|
||||||
static std::once_flag once;
|
static std::once_flag once;
|
||||||
std::call_once(once, [] {
|
std::call_once(once, [] {
|
||||||
const char *path = getenv("FAKE_TOUCHCTL_RING");
|
const char *path = getenv("FAKE_TOUCHCTL_RING");
|
||||||
if (!path || !*path || !fake_deck_enabled()) return;
|
if (!path || !*path || !fake_deck_enabled()) return;
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
int fd = my_open(path, O_RDWR | O_CLOEXEC);
|
int fd = my_open(path, O_RDWR | O_CLOEXEC);
|
||||||
if (fd < 0) {
|
if (fd < 0) {
|
||||||
Logger::log("touch: %s not openable (%s)\n", path, strerror(errno));
|
Logger::log("touch: %s not openable (%s)\n", path, strerror(errno));
|
||||||
@@ -2312,7 +2392,8 @@ __attribute__((visibility("hidden"))) static int inject_uevent(const char *actio
|
|||||||
const char *subsystem, const char *devname,
|
const char *subsystem, const char *devname,
|
||||||
unsigned major, unsigned minor) {
|
unsigned major, unsigned minor) {
|
||||||
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
|
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
|
||||||
static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "dd_udevmon_inject"));
|
static SymbolSlot inject_slot;
|
||||||
|
const auto inject = resolved_symbol<inject_fn>(inject_slot, RTLD_DEFAULT, "dd_udevmon_inject");
|
||||||
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
|
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2434,6 +2515,7 @@ __attribute__((constructor)) static void start_touch_controller() {
|
|||||||
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
|
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
|
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
|
||||||
|
if (!env_ready()) return nullptr;
|
||||||
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
|
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
|
||||||
return dir && *dir ? dir : nullptr;
|
return dir && *dir ? dir : nullptr;
|
||||||
}
|
}
|
||||||
@@ -2469,7 +2551,7 @@ __attribute__((visibility("hidden"))) static void note_deck_sysfs(const char *ho
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int fstatfs(int fd, struct statfs *buf) {
|
EXPORT int fstatfs(int fd, struct statfs *buf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, struct statfs *)>(dlsym(RTLD_NEXT, "fstatfs"));
|
const auto real = next_symbol<int (*)(int, struct statfs *)>(Next::fstatfs);
|
||||||
int result = real(fd, buf);
|
int result = real(fd, buf);
|
||||||
if (fake_deck_enabled() && is_deck_sysfs_fd(fd)) {
|
if (fake_deck_enabled() && is_deck_sysfs_fd(fd)) {
|
||||||
note_deck_sysfs("fstatfs", result);
|
note_deck_sysfs("fstatfs", result);
|
||||||
@@ -2479,7 +2561,7 @@ EXPORT int fstatfs(int fd, struct statfs *buf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int statfs(const char *path, struct statfs *buf) {
|
EXPORT int statfs(const char *path, struct statfs *buf) {
|
||||||
static auto real = reinterpret_cast<int (*)(const char *, struct statfs *)>(dlsym(RTLD_NEXT, "statfs"));
|
const auto real = next_symbol<int (*)(const char *, struct statfs *)>(Next::statfs);
|
||||||
int result = real(path, buf);
|
int result = real(path, buf);
|
||||||
if (fake_deck_enabled() && is_deck_sysfs_path(path)) {
|
if (fake_deck_enabled() && is_deck_sysfs_path(path)) {
|
||||||
note_deck_sysfs(path, result);
|
note_deck_sysfs(path, result);
|
||||||
@@ -2528,7 +2610,7 @@ __attribute__((visibility("hidden"))) static int deck_imu_mode_change(const uint
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHidraw &deck, int mode) {
|
__attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHidraw &deck, int mode) {
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return;
|
if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return;
|
||||||
std::string path = get_ring_path_for_slot(0);
|
std::string path = get_ring_path_for_slot(0);
|
||||||
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
|
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
|
||||||
@@ -3037,7 +3119,7 @@ static int real_fstat(int fd, struct stat *buf);
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
__attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
||||||
int dirfd, const char *path, int flags, struct statx *buf) {
|
int dirfd, const char *path, int flags, struct statx *buf) {
|
||||||
static auto real_openat = reinterpret_cast<decltype(&::openat)>(dlsym(RTLD_NEXT, "openat"));
|
const auto real_openat = next_symbol<decltype(&::openat)>(Next::openat);
|
||||||
int target;
|
int target;
|
||||||
if (!path || !*path) {
|
if (!path || !*path) {
|
||||||
if (!(flags & AT_EMPTY_PATH)) return false;
|
if (!(flags & AT_EMPTY_PATH)) return false;
|
||||||
@@ -3075,7 +3157,7 @@ __attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *buf) {
|
EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *buf) {
|
||||||
static auto real = reinterpret_cast<decltype(&::statx)>(dlsym(RTLD_NEXT, "statx"));
|
const auto real = next_symbol<decltype(&::statx)>(Next::statx);
|
||||||
int result = real(dirfd, path, flags, mask, buf);
|
int result = real(dirfd, path, flags, mask, buf);
|
||||||
int saved_errno = errno;
|
int saved_errno = errno;
|
||||||
constexpr unsigned unique_mount_id = 0x4000;
|
constexpr unsigned unique_mount_id = 0x4000;
|
||||||
@@ -3096,7 +3178,7 @@ EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct s
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
EXPORT DIR *opendir(const char *name) {
|
EXPORT DIR *opendir(const char *name) {
|
||||||
static auto real = reinterpret_cast<DIR *(*)(const char *)>(dlsym(RTLD_NEXT, "opendir"));
|
const auto real = next_symbol<DIR *(*)(const char *)>(Next::opendir);
|
||||||
DIR *dir = real(name);
|
DIR *dir = real(name);
|
||||||
if (!dir) {
|
if (!dir) {
|
||||||
note_sys_failure(AT_FDCWD, name);
|
note_sys_failure(AT_FDCWD, name);
|
||||||
@@ -3126,7 +3208,7 @@ EXPORT int open(const char *pathname, int flags, ...) {
|
|||||||
|
|
||||||
va_end(va);
|
va_end(va);
|
||||||
|
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
|
|
||||||
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);
|
||||||
@@ -3204,7 +3286,7 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) {
|
|||||||
|
|
||||||
va_end(va);
|
va_end(va);
|
||||||
|
|
||||||
static auto my_openat = reinterpret_cast<int (*)(int, const char *, int, ...)>(dlsym(RTLD_NEXT, "openat"));
|
const auto my_openat = next_symbol<int (*)(int, const char *, int, ...)>(Next::openat);
|
||||||
|
|
||||||
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);
|
||||||
@@ -3363,10 +3445,10 @@ static int fake_stat_fd(int fd, S *buf, Real real) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static int real_stat(const char *pathname, struct stat *statbuf) {
|
static int real_stat(const char *pathname, struct stat *statbuf) {
|
||||||
static auto fn = reinterpret_cast<int (*)(const char *, struct stat *)>(dlsym(RTLD_NEXT, "stat"));
|
const auto fn = next_symbol<int (*)(const char *, struct stat *)>(Next::stat);
|
||||||
if (fn) return fn(pathname, statbuf);
|
if (fn) return fn(pathname, statbuf);
|
||||||
#ifdef _STAT_VER
|
#ifdef _STAT_VER
|
||||||
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
|
const auto xfn = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
|
||||||
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
||||||
#endif
|
#endif
|
||||||
errno = ENOSYS;
|
errno = ENOSYS;
|
||||||
@@ -3374,10 +3456,10 @@ static int real_stat(const char *pathname, struct stat *statbuf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static int real_fstat(int fd, struct stat *buf) {
|
static int real_fstat(int fd, struct stat *buf) {
|
||||||
static auto fn = reinterpret_cast<int (*)(int, struct stat *)>(dlsym(RTLD_NEXT, "fstat"));
|
const auto fn = next_symbol<int (*)(int, struct stat *)>(Next::fstat);
|
||||||
if (fn) return fn(fd, buf);
|
if (fn) return fn(fd, buf);
|
||||||
#ifdef _STAT_VER
|
#ifdef _STAT_VER
|
||||||
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
|
const auto xfn = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
|
||||||
if (xfn) return xfn(_STAT_VER, fd, buf);
|
if (xfn) return xfn(_STAT_VER, fd, buf);
|
||||||
#endif
|
#endif
|
||||||
errno = ENOSYS;
|
errno = ENOSYS;
|
||||||
@@ -3393,7 +3475,7 @@ EXPORT int fstat(int fd, struct stat *buf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int access(const char *pathname, int mode) {
|
EXPORT int access(const char *pathname, int mode) {
|
||||||
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
|
const auto my_access = next_symbol<decltype(&::access)>(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_reads_pads()) return 0;
|
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||||
@@ -3434,7 +3516,7 @@ EXPORT int access(const char *pathname, int mode) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
|
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
|
||||||
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
|
const auto my_faccessat = next_symbol<decltype(&::faccessat)>(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_reads_pads()) return 0;
|
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||||
@@ -3478,7 +3560,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
|
|||||||
int (*filter)(const struct dirent *),
|
int (*filter)(const struct dirent *),
|
||||||
int (*compar)(const struct dirent **,
|
int (*compar)(const struct dirent **,
|
||||||
const struct dirent **)) {
|
const struct dirent **)) {
|
||||||
static auto my_scandir = reinterpret_cast<decltype(&::scandir)>(dlsym(RTLD_NEXT, "scandir"));
|
const auto my_scandir = next_symbol<decltype(&::scandir)>(Next::scandir);
|
||||||
|
|
||||||
if (dirp) {
|
if (dirp) {
|
||||||
if (!strcmp(dirp, "/dev/input")) {
|
if (!strcmp(dirp, "/dev/input")) {
|
||||||
@@ -3492,7 +3574,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
|
EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
|
||||||
static auto my_inotify_add_watch = reinterpret_cast<decltype(&::inotify_add_watch)>(dlsym(RTLD_NEXT, "inotify_add_watch"));
|
const auto my_inotify_add_watch = next_symbol<decltype(&::inotify_add_watch)>(Next::inotify_add_watch);
|
||||||
|
|
||||||
char *fake_path = nullptr;
|
char *fake_path = nullptr;
|
||||||
if (pathname) {
|
if (pathname) {
|
||||||
@@ -3631,7 +3713,7 @@ static bool wait_snapshot(std::shared_ptr<FakeController> fake,
|
|||||||
|
|
||||||
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
|
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
|
||||||
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
|
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
|
||||||
static const auto next = reinterpret_cast<ioctl_fn>(dlsym(RTLD_NEXT, "ioctl"));
|
const auto next = next_symbol<ioctl_fn>(Next::ioctl);
|
||||||
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
|
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3689,6 +3771,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
|||||||
id.bustype = 0x03;
|
id.bustype = 0x03;
|
||||||
if (made) {
|
if (made) {
|
||||||
id = made->id;
|
id = made->id;
|
||||||
|
if (steam_pad_as_x360() && id.vendor == STEAM_VIRTUAL_VENDOR_ID && id.product == STEAM_VIRTUAL_PRODUCT_ID) {
|
||||||
|
id.vendor = X360_VENDOR_ID;
|
||||||
|
id.product = X360_PRODUCT_ID;
|
||||||
|
}
|
||||||
} else if (presents_steam_virtual()) {
|
} else if (presents_steam_virtual()) {
|
||||||
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
|
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
|
||||||
id.product = STEAM_VIRTUAL_PRODUCT_ID;
|
id.product = STEAM_VIRTUAL_PRODUCT_ID;
|
||||||
@@ -3866,7 +3952,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int close(int fd) {
|
EXPORT int close(int fd) {
|
||||||
static auto my_close = reinterpret_cast<decltype(&::close)>(dlsym(RTLD_NEXT, "close"));
|
const auto my_close = next_symbol<decltype(&::close)>(Next::close);
|
||||||
|
|
||||||
if (!watched(fd)) return my_close(fd);
|
if (!watched(fd)) return my_close(fd);
|
||||||
close_uinput(fd);
|
close_uinput(fd);
|
||||||
@@ -4054,7 +4140,7 @@ EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT ssize_t write(int fd, const void *buf, size_t count) {
|
EXPORT ssize_t write(int fd, const void *buf, size_t count) {
|
||||||
static auto my_write = reinterpret_cast<decltype(&::write)>(dlsym(RTLD_NEXT, "write"));
|
const auto my_write = next_symbol<decltype(&::write)>(Next::write);
|
||||||
|
|
||||||
if (!watched(fd)) return my_write(fd, buf, count);
|
if (!watched(fd)) return my_write(fd, buf, count);
|
||||||
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
||||||
@@ -4129,8 +4215,8 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
|
|||||||
|
|
||||||
static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
|
static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
|
||||||
const sigset_t *sigmask) {
|
const sigset_t *sigmask) {
|
||||||
static auto my_poll = reinterpret_cast<decltype(&::poll)>(dlsym(RTLD_NEXT, "poll"));
|
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
|
||||||
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
|
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||||
|
|
||||||
nfds_t first = 0;
|
nfds_t first = 0;
|
||||||
while (first < nfds && !watched(fds[first].fd)) first++;
|
while (first < nfds && !watched(fds[first].fd)) first++;
|
||||||
@@ -4234,7 +4320,7 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
|
|||||||
|
|
||||||
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
||||||
const struct timespec *timeout, const sigset_t *sigmask) {
|
const struct timespec *timeout, const sigset_t *sigmask) {
|
||||||
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
|
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||||
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
||||||
errno = EINVAL;
|
errno = EINVAL;
|
||||||
return -1;
|
return -1;
|
||||||
@@ -4261,7 +4347,7 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
|||||||
|
|
||||||
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
||||||
fd_set *exceptfds, struct timeval *timeout) {
|
fd_set *exceptfds, struct timeval *timeout) {
|
||||||
static auto my_select = reinterpret_cast<decltype(&::select)>(dlsym(RTLD_NEXT, "select"));
|
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
|
||||||
|
|
||||||
fd_set original_readfds;
|
fd_set original_readfds;
|
||||||
fd_set original_writefds;
|
fd_set original_writefds;
|
||||||
@@ -4423,10 +4509,10 @@ EXPORT int openat64(int dirfd, const char *pathname, int flags, ...) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
||||||
static auto fn = reinterpret_cast<int (*)(const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "stat64"));
|
const auto fn = next_symbol<int (*)(const char *, struct stat64 *)>(Next::stat64);
|
||||||
if (fn) return fn(pathname, statbuf);
|
if (fn) return fn(pathname, statbuf);
|
||||||
#ifdef _STAT_VER
|
#ifdef _STAT_VER
|
||||||
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
|
const auto xfn = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
|
||||||
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
||||||
#endif
|
#endif
|
||||||
errno = ENOSYS;
|
errno = ENOSYS;
|
||||||
@@ -4434,10 +4520,10 @@ static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static int real_fstat64(int fd, struct stat64 *buf) {
|
static int real_fstat64(int fd, struct stat64 *buf) {
|
||||||
static auto fn = reinterpret_cast<int (*)(int, struct stat64 *)>(dlsym(RTLD_NEXT, "fstat64"));
|
const auto fn = next_symbol<int (*)(int, struct stat64 *)>(Next::fstat64);
|
||||||
if (fn) return fn(fd, buf);
|
if (fn) return fn(fd, buf);
|
||||||
#ifdef _STAT_VER
|
#ifdef _STAT_VER
|
||||||
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
|
const auto xfn = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
|
||||||
if (xfn) return xfn(_STAT_VER, fd, buf);
|
if (xfn) return xfn(_STAT_VER, fd, buf);
|
||||||
#endif
|
#endif
|
||||||
errno = ENOSYS;
|
errno = ENOSYS;
|
||||||
@@ -4453,27 +4539,27 @@ EXPORT int fstat64(int fd, struct stat64 *buf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int __xstat(int version, const char *pathname, struct stat *statbuf) {
|
EXPORT int __xstat(int version, const char *pathname, struct stat *statbuf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
|
const auto real = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
|
||||||
if (!real) return stat(pathname, statbuf);
|
if (!real) return stat(pathname, statbuf);
|
||||||
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat *buf) { return real(version, path, buf); });
|
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat *buf) { return real(version, path, buf); });
|
||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int __xstat64(int version, const char *pathname, struct stat64 *statbuf) {
|
EXPORT int __xstat64(int version, const char *pathname, struct stat64 *statbuf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
|
const auto real = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
|
||||||
if (!real) return stat64(pathname, statbuf);
|
if (!real) return stat64(pathname, statbuf);
|
||||||
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat64 *buf) { return real(version, path, buf); });
|
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat64 *buf) { return real(version, path, buf); });
|
||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int __fxstat(int version, int fd, struct stat *buf) {
|
EXPORT int __fxstat(int version, int fd, struct stat *buf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
|
const auto real = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
|
||||||
if (!real) return fstat(fd, buf);
|
if (!real) return fstat(fd, buf);
|
||||||
return fake_stat_fd(fd, buf, [version](int f, struct stat *b) { return real(version, f, b); });
|
return fake_stat_fd(fd, buf, [version, real](int f, struct stat *b) { return real(version, f, b); });
|
||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) {
|
EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
|
const auto real = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
|
||||||
if (!real) return fstat64(fd, buf);
|
if (!real) return fstat64(fd, buf);
|
||||||
return fake_stat_fd(fd, buf, [version](int f, struct stat64 *b) { return real(version, f, b); });
|
return fake_stat_fd(fd, buf, [version, real](int f, struct stat64 *b) { return real(version, f, b); });
|
||||||
}
|
}
|
||||||
|
|
||||||
#if defined(__x86_64__) || defined(__i386__)
|
#if defined(__x86_64__) || defined(__i386__)
|
||||||
@@ -4487,18 +4573,37 @@ static const char *const interposed_names[] = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
static dlsym_fn next_dlsym() {
|
static dlsym_fn next_dlsym() {
|
||||||
static const dlsym_fn fn = [] {
|
static std::atomic<dlsym_fn> fn{nullptr};
|
||||||
|
static std::atomic<bool> resolved{false};
|
||||||
|
if (!resolved.load(std::memory_order_acquire)) {
|
||||||
#ifdef __x86_64__
|
#ifdef __x86_64__
|
||||||
const char *base = "GLIBC_2.2.5";
|
const char *base = "GLIBC_2.2.5";
|
||||||
#else
|
#else
|
||||||
const char *base = "GLIBC_2.0";
|
const char *base = "GLIBC_2.0";
|
||||||
#endif
|
#endif
|
||||||
|
dlsym_fn found{};
|
||||||
for (const char *version : {base, "GLIBC_2.34"}) {
|
for (const char *version : {base, "GLIBC_2.34"}) {
|
||||||
if (auto found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version))) return found;
|
if ((found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version)))) break;
|
||||||
}
|
}
|
||||||
return dlsym_fn{};
|
fn.store(found, std::memory_order_relaxed);
|
||||||
}();
|
resolved.store(true, std::memory_order_release);
|
||||||
return fn;
|
}
|
||||||
|
return fn.load(std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void *libc_handle() {
|
||||||
|
static std::atomic<void *> handle{nullptr};
|
||||||
|
static std::atomic<bool> resolved{false};
|
||||||
|
if (!resolved.load(std::memory_order_acquire)) {
|
||||||
|
handle.store(dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD), std::memory_order_relaxed);
|
||||||
|
resolved.store(true, std::memory_order_release);
|
||||||
|
}
|
||||||
|
return handle.load(std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((constructor)) static void resolve_dlsym_targets() {
|
||||||
|
next_dlsym();
|
||||||
|
libc_handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); }
|
static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); }
|
||||||
@@ -4516,8 +4621,7 @@ extern "C" __attribute__((visibility("hidden"), used)) void *fakeinput_dlsym_tar
|
|||||||
dlsym_fn next = next_dlsym();
|
dlsym_fn next = next_dlsym();
|
||||||
if (!next) return reinterpret_cast<void *>(missing_dlsym);
|
if (!next) return reinterpret_cast<void *>(missing_dlsym);
|
||||||
if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || name == nullptr) return reinterpret_cast<void *>(next);
|
if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || name == nullptr) return reinterpret_cast<void *>(next);
|
||||||
static void *const libc = dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD);
|
if (handle != libc_handle() || !interposed(name)) return reinterpret_cast<void *>(next);
|
||||||
if (handle != libc || !interposed(name)) return reinterpret_cast<void *>(next);
|
|
||||||
return reinterpret_cast<void *>(global_dlsym);
|
return reinterpret_cast<void *>(global_dlsym);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -620,7 +620,8 @@ static void cursor_publish_shown(void) {
|
|||||||
|
|
||||||
static void cursor_publish_hidden(void) {
|
static void cursor_publish_hidden(void) {
|
||||||
pthread_mutex_lock(&g_cursor_lock);
|
pthread_mutex_lock(&g_cursor_lock);
|
||||||
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
|
// A client that hides the cursor before ever showing one (gamescope drawing its own) must still be reported.
|
||||||
|
if (!g_cursor_hidden || g_cursor_serial == 0) { g_cursor_hidden = 1; g_cursor_serial++; }
|
||||||
pthread_mutex_unlock(&g_cursor_lock);
|
pthread_mutex_unlock(&g_cursor_lock);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -737,6 +738,11 @@ static void describe(const struct surface *s, char *out, size_t size) {
|
|||||||
else snprintf(out, size, "window %#x (%s)", w->hwnd, prog);
|
else snprintf(out, size, "window %#x (%s)", w->hwnd, prog);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static int is_steam_client_surface(const struct surface *s) {
|
||||||
|
const char *name = client_name(wl_resource_get_client(s->resource));
|
||||||
|
return strcmp(name, "steam") == 0 || strstr(name, "steamwebhelper") != NULL;
|
||||||
|
}
|
||||||
|
|
||||||
static struct surface *toplevel_by_hwnd(uint32_t hwnd) {
|
static struct surface *toplevel_by_hwnd(uint32_t hwnd) {
|
||||||
struct surface *s;
|
struct surface *s;
|
||||||
wl_list_for_each(s, &g_toplevels, toplevel_link)
|
wl_list_for_each(s, &g_toplevels, toplevel_link)
|
||||||
@@ -894,6 +900,7 @@ int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
|
|||||||
static uint64_t g_game_frames;
|
static uint64_t g_game_frames;
|
||||||
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
|
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
|
||||||
extern void droiddeck_on_game_frame(void);
|
extern void droiddeck_on_game_frame(void);
|
||||||
|
extern void droiddeck_on_compositor_frame(void);
|
||||||
extern void droiddeck_on_content_rate(int fps);
|
extern void droiddeck_on_content_rate(int fps);
|
||||||
static int64_t g_cadence_ns;
|
static int64_t g_cadence_ns;
|
||||||
static int64_t g_cadence_frames;
|
static int64_t g_cadence_frames;
|
||||||
@@ -949,9 +956,10 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
|||||||
g_hud_shm = s;
|
g_hud_shm = s;
|
||||||
g_hud_shm_ns = now;
|
g_hud_shm_ns = now;
|
||||||
g_hud_new = 1;
|
g_hud_new = 1;
|
||||||
droiddeck_on_game_frame();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (s == g_hud_shm && (!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL))
|
||||||
|
droiddeck_on_compositor_frame();
|
||||||
}
|
}
|
||||||
|
|
||||||
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
|
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
|
||||||
@@ -1025,7 +1033,8 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
|||||||
droiddeck_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)",
|
droiddeck_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)",
|
||||||
name, b->width, b->height, (unsigned long long)b->modifier);
|
name, b->width, b->height, (unsigned long long)b->modifier);
|
||||||
}
|
}
|
||||||
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
if (s != g_hud_surface && !is_steam_client_surface(s) &&
|
||||||
|
(b->img || ahb_swapchain_has_ahb(b)) &&
|
||||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) ||
|
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) ||
|
||||||
(announced_now && !below_surface(g_hud_surface, s) &&
|
(announced_now && !below_surface(g_hud_surface, s) &&
|
||||||
(int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
(int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||||
@@ -1050,9 +1059,12 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
|||||||
: "the compositor's driver could NOT import it (nothing can show it)");
|
: "the compositor's driver could NOT import it (nothing can show it)");
|
||||||
s->hdr_fmt_logged = b->format;
|
s->hdr_fmt_logged = b->format;
|
||||||
}
|
}
|
||||||
if (s == g_hud_surface) {
|
if (s == g_hud_surface && !is_steam_client_surface(s)) {
|
||||||
g_hud_alive_ns = now_ns();
|
g_hud_alive_ns = now_ns();
|
||||||
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; note_game_frame_gap(); droiddeck_on_game_frame(); }
|
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; note_game_frame_gap(); droiddeck_on_game_frame(); }
|
||||||
|
} else if (is_steam_client_surface(s) && !repeat &&
|
||||||
|
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL)) {
|
||||||
|
droiddeck_on_compositor_frame();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -163,6 +163,7 @@ struct layer {
|
|||||||
ARect geo_src, geo_dst;
|
ARect geo_src, geo_dst;
|
||||||
int geo_valid;
|
int geo_valid;
|
||||||
int alloc_tier;
|
int alloc_tier;
|
||||||
|
unsigned import_failed_fmts;
|
||||||
uint64_t pool_modifier;
|
uint64_t pool_modifier;
|
||||||
int first_logged;
|
int first_logged;
|
||||||
int64_t drop_logged_ns;
|
int64_t drop_logged_ns;
|
||||||
@@ -487,7 +488,8 @@ static const char *tier_name(int tier) {
|
|||||||
|
|
||||||
static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) {
|
static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) {
|
||||||
g_alloc_failed = 0;
|
g_alloc_failed = 0;
|
||||||
while (l->alloc_tier <= TIER_LINEAR) {
|
const unsigned fmt_bit = fmt == AHB_RGB10A2 ? 2u : 1u;
|
||||||
|
while (l->alloc_tier <= TIER_LINEAR && !(l->import_failed_fmts & fmt_bit)) {
|
||||||
const int tier = l->alloc_tier;
|
const int tier = l->alloc_tier;
|
||||||
AHardwareBuffer_Desc d = {
|
AHardwareBuffer_Desc d = {
|
||||||
.width = (uint32_t)w, .height = (uint32_t)h, .layers = 1,
|
.width = (uint32_t)w, .height = (uint32_t)h, .layers = 1,
|
||||||
@@ -518,6 +520,10 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
|
|||||||
img = vkp_image_import_dmabuf(nh->data[0], fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888, mod, w, h,
|
img = vkp_image_import_dmabuf(nh->data[0], fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888, mod, w, h,
|
||||||
got.stride * 4, 0, 1);
|
got.stride * 4, 0, 1);
|
||||||
path = "dma-buf (QTI handle)";
|
path = "dma-buf (QTI handle)";
|
||||||
|
if (!img && mod == MOD_LINEAR && vkp_can_import_ahb()) {
|
||||||
|
img = vkp_image_import_ahb(ahb, info, sizeof(info));
|
||||||
|
if (img) { mod = SC_MOD_GRALLOC; path = "AHardwareBuffer"; }
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
if (tier == TIER_UBWC) {
|
if (tier == TIER_UBWC) {
|
||||||
char hd[256];
|
char hd[256];
|
||||||
@@ -556,6 +562,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
|
|||||||
nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd);
|
nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd);
|
||||||
AHardwareBuffer_release(ahb);
|
AHardwareBuffer_release(ahb);
|
||||||
if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; }
|
if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; }
|
||||||
|
l->import_failed_fmts |= fmt_bit;
|
||||||
g_alloc_failed = 1;
|
g_alloc_failed = 1;
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
@@ -941,7 +948,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
|
|||||||
|
|
||||||
int wait_fd;
|
int wait_fd;
|
||||||
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
|
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
|
||||||
if (idx < 0) { log_drop(l); return 0; }
|
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
|
||||||
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
|
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
|
||||||
if (present_slot(l, idx, r, color, 0) != 0) return -1;
|
if (present_slot(l, idx, r, color, 0) != 0) return -1;
|
||||||
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8);
|
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8);
|
||||||
@@ -1150,7 +1157,7 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl
|
|||||||
if (sw <= 0 || sh <= 0) return -1;
|
if (sw <= 0 || sh <= 0) return -1;
|
||||||
int wait_fd;
|
int wait_fd;
|
||||||
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
|
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
|
||||||
if (idx < 0) { log_drop(l); return 0; }
|
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
|
||||||
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
|
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
|
||||||
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
|
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
|
||||||
if (!l->first_logged) {
|
if (!l->first_logged) {
|
||||||
|
|||||||
@@ -24,6 +24,12 @@ static inline uint32_t vkp_linear_dmabuf_texel_bytes(VkFormat fmt) {
|
|||||||
return fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? 8u : 4u;
|
return fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? 8u : 4u;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static inline int vkp_padded_linear_target_needs_layout(int drm_modifiers, uint64_t modifier, VkFormat fmt,
|
||||||
|
int w, uint32_t stride, uint32_t offset) {
|
||||||
|
return !drm_modifiers && modifier == 0 &&
|
||||||
|
(offset != 0 || (uint64_t)stride != (uint64_t)w * vkp_linear_dmabuf_texel_bytes(fmt));
|
||||||
|
}
|
||||||
|
|
||||||
static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, uint32_t stride, uint32_t offset,
|
static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, uint32_t stride, uint32_t offset,
|
||||||
VkBufferImageCopy *copy) {
|
VkBufferImageCopy *copy) {
|
||||||
const uint32_t texel = vkp_linear_dmabuf_texel_bytes(fmt);
|
const uint32_t texel = vkp_linear_dmabuf_texel_bytes(fmt);
|
||||||
@@ -39,11 +45,11 @@ static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, ui
|
|||||||
}
|
}
|
||||||
|
|
||||||
static inline VkBufferMemoryBarrier vkp_linear_dmabuf_ownership(VkBuffer buffer, uint32_t queue_family,
|
static inline VkBufferMemoryBarrier vkp_linear_dmabuf_ownership(VkBuffer buffer, uint32_t queue_family,
|
||||||
int acquire) {
|
VkAccessFlags access, int acquire) {
|
||||||
return (VkBufferMemoryBarrier){
|
return (VkBufferMemoryBarrier){
|
||||||
.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
|
.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
|
||||||
.srcAccessMask = acquire ? 0 : VK_ACCESS_TRANSFER_READ_BIT,
|
.srcAccessMask = acquire ? 0 : access,
|
||||||
.dstAccessMask = acquire ? VK_ACCESS_TRANSFER_READ_BIT : 0,
|
.dstAccessMask = acquire ? access : 0,
|
||||||
.srcQueueFamilyIndex = acquire ? VK_QUEUE_FAMILY_FOREIGN_EXT : queue_family,
|
.srcQueueFamilyIndex = acquire ? VK_QUEUE_FAMILY_FOREIGN_EXT : queue_family,
|
||||||
.dstQueueFamilyIndex = acquire ? queue_family : VK_QUEUE_FAMILY_FOREIGN_EXT,
|
.dstQueueFamilyIndex = acquire ? queue_family : VK_QUEUE_FAMILY_FOREIGN_EXT,
|
||||||
.buffer = buffer,
|
.buffer = buffer,
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
|
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
|
||||||
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
|
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
|
||||||
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \
|
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \
|
||||||
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
|
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) X(CmdCopyImageToBuffer) \
|
||||||
X(CreateBuffer) X(DestroyBuffer) X(GetBufferMemoryRequirements) X(BindBufferMemory) \
|
X(CreateBuffer) X(DestroyBuffer) X(GetBufferMemoryRequirements) X(BindBufferMemory) \
|
||||||
X(CmdCopyBufferToImage) \
|
X(CmdCopyBufferToImage) \
|
||||||
\
|
\
|
||||||
|
|||||||
@@ -1123,7 +1123,7 @@ static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_
|
|||||||
static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img) {
|
static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img) {
|
||||||
if (!img || !img->linear_buf) return;
|
if (!img || !img->linear_buf) return;
|
||||||
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||||
VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, 1);
|
VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 1);
|
||||||
VkImageMemoryBarrier write = {
|
VkImageMemoryBarrier write = {
|
||||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||||
@@ -1132,7 +1132,7 @@ static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img
|
|||||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
|
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
|
||||||
0, NULL, 1, &acquire, 1, &write);
|
0, NULL, 1, &acquire, 1, &write);
|
||||||
g_vk.CmdCopyBufferToImage(cmd, img->linear_buf, img->image, VK_IMAGE_LAYOUT_GENERAL, 1, &img->linear_copy);
|
g_vk.CmdCopyBufferToImage(cmd, img->linear_buf, img->image, VK_IMAGE_LAYOUT_GENERAL, 1, &img->linear_copy);
|
||||||
VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, 0);
|
VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 0);
|
||||||
VkImageMemoryBarrier read = {
|
VkImageMemoryBarrier read = {
|
||||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||||
@@ -1259,7 +1259,8 @@ static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferIma
|
|||||||
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
|
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
|
||||||
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
|
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
|
||||||
VkBufferCreateInfo bci = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = &ext, .size = size,
|
VkBufferCreateInfo bci = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = &ext, .size = size,
|
||||||
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE};
|
.usage = img->blit_dst ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
|
||||||
|
.sharingMode = VK_SHARING_MODE_EXCLUSIVE};
|
||||||
VkResult r = g_vk.CreateBuffer(g_dev, &bci, NULL, &img->linear_buf);
|
VkResult r = g_vk.CreateBuffer(g_dev, &bci, NULL, &img->linear_buf);
|
||||||
if (r != VK_SUCCESS) goto fail;
|
if (r != VK_SUCCESS) goto fail;
|
||||||
uint32_t allowed = 0xffffffff;
|
uint32_t allowed = 0xffffffff;
|
||||||
@@ -1312,8 +1313,8 @@ static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferIma
|
|||||||
img->in_general = 1;
|
img->in_general = 1;
|
||||||
return 0;
|
return 0;
|
||||||
fail:
|
fail:
|
||||||
LOGE("dmabuf: reading the linear %dx%d buffer at its row pitch failed (%s); importing it as an image",
|
LOGE("dmabuf: %s the linear %dx%d buffer at its row pitch failed (%s)",
|
||||||
img->w, img->h, vk_result_name(r));
|
img->blit_dst ? "writing" : "reading", img->w, img->h, vk_result_name(r));
|
||||||
if (dupfd >= 0) close(dupfd);
|
if (dupfd >= 0) close(dupfd);
|
||||||
destroy_image_objects(img);
|
destroy_image_objects(img);
|
||||||
return -1;
|
return -1;
|
||||||
@@ -1324,15 +1325,20 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
|||||||
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
|
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
|
||||||
if (dev_init() != 0) return NULL;
|
if (dev_init() != 0) return NULL;
|
||||||
|
|
||||||
|
const VkFormat format = drm_to_vk(drm_format);
|
||||||
|
const int padded_target = as_blit_dst &&
|
||||||
|
vkp_padded_linear_target_needs_layout(g_drm_modifiers, modifier, format, w, stride, offset);
|
||||||
|
if (padded_target && !g_vk.CmdCopyImageToBuffer) return NULL;
|
||||||
|
|
||||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||||
if (!img) return NULL;
|
if (!img) return NULL;
|
||||||
img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0;
|
img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0;
|
||||||
img->fmt = drm_to_vk(drm_format);
|
img->fmt = format;
|
||||||
const int through_buffer = vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst);
|
const int through_buffer = padded_target || vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst);
|
||||||
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
|
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
|
||||||
const int modifier_sampled = !as_blit_dst && g_drm_modifiers && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
|
const int modifier_sampled = !as_blit_dst && g_drm_modifiers && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
|
||||||
modifier_importable(img->fmt, modifier, sampled_usage);
|
modifier_importable(img->fmt, modifier, sampled_usage);
|
||||||
img->sampled = through_buffer ? optimal_sampled(img->fmt) : modifier_sampled;
|
img->sampled = !as_blit_dst && (through_buffer ? optimal_sampled(img->fmt) : modifier_sampled);
|
||||||
/* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
|
/* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
|
||||||
* or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
|
* or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
|
||||||
{
|
{
|
||||||
@@ -1358,7 +1364,12 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
|||||||
if (through_buffer) {
|
if (through_buffer) {
|
||||||
VkBufferImageCopy linear_copy;
|
VkBufferImageCopy linear_copy;
|
||||||
const VkDeviceSize linear_size = vkp_linear_dmabuf_copy(img->fmt, w, h, stride, offset, &linear_copy);
|
const VkDeviceSize linear_size = vkp_linear_dmabuf_copy(img->fmt, w, h, stride, offset, &linear_copy);
|
||||||
if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) return img;
|
if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) {
|
||||||
|
if (padded_target) droiddeck_log("gpu", "linear layer target %dx%d writes at pitch %u via DMA-BUF",
|
||||||
|
w, h, stride);
|
||||||
|
return img;
|
||||||
|
}
|
||||||
|
if (padded_target) { free(img); return NULL; }
|
||||||
img->sampled = modifier_sampled;
|
img->sampled = modifier_sampled;
|
||||||
}
|
}
|
||||||
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
|
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
|
||||||
@@ -1483,7 +1494,7 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int vkp_can_import_ahb(void) {
|
int vkp_can_import_ahb(void) {
|
||||||
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && g_ahb_import &&
|
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && !g_library_name && g_ahb_import &&
|
||||||
g_vk.GetAndroidHardwareBufferPropertiesANDROID;
|
g_vk.GetAndroidHardwareBufferPropertiesANDROID;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2522,6 +2533,48 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_layout, struct vkp_image *dst,
|
||||||
|
const VkImageBlit *blit, VkFilter filter) {
|
||||||
|
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||||
|
const VkImageMemoryBarrier acquire = {
|
||||||
|
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||||
|
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||||
|
.srcQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : VK_QUEUE_FAMILY_FOREIGN_EXT,
|
||||||
|
.dstQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : g_qfam,
|
||||||
|
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
|
||||||
|
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||||
|
0, 0, NULL, 0, NULL, 1, &acquire);
|
||||||
|
g_vk.CmdBlitImage(cmd, src, src_layout, dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
|
||||||
|
if (dst->staged) {
|
||||||
|
const VkImageMemoryBarrier read = {
|
||||||
|
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||||
|
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||||
|
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||||
|
.image = dst->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
|
||||||
|
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
|
||||||
|
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||||
|
0, 0, NULL, 0, NULL, 1, &read);
|
||||||
|
const VkBufferMemoryBarrier write = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 1);
|
||||||
|
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||||
|
0, 0, NULL, 1, &write, 0, NULL);
|
||||||
|
VkBufferImageCopy copy = dst->linear_copy;
|
||||||
|
copy.imageExtent.width = (uint32_t)blit->dstOffsets[1].x;
|
||||||
|
copy.imageExtent.height = (uint32_t)blit->dstOffsets[1].y;
|
||||||
|
g_vk.CmdCopyImageToBuffer(cmd, dst->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->linear_buf, 1, ©);
|
||||||
|
const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 0);
|
||||||
|
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
|
||||||
|
0, 0, NULL, 1, &release, 0, NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const VkImageMemoryBarrier release = {
|
||||||
|
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||||
|
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
|
||||||
|
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
|
||||||
|
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
|
||||||
|
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
|
||||||
|
0, 0, NULL, 0, NULL, 1, &release);
|
||||||
|
}
|
||||||
|
|
||||||
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||||
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
|
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
|
||||||
if (wait_fd >= 0) close(wait_fd);
|
if (wait_fd >= 0) close(wait_fd);
|
||||||
@@ -2540,41 +2593,28 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
|||||||
struct vkp_external_client_barrier_pair src_pair;
|
struct vkp_external_client_barrier_pair src_pair;
|
||||||
const int src_external = vkp_external_client_barrier_pair(
|
const int src_external = vkp_external_client_barrier_pair(
|
||||||
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
|
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
|
||||||
VkImageMemoryBarrier acq[2] = {
|
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
|
||||||
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
|
|
||||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||||
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
|
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
|
||||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
|
||||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
|
||||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
|
|
||||||
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
|
|
||||||
if (!src_external) {
|
if (!src_external) {
|
||||||
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
|
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
|
||||||
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
|
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
|
||||||
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
|
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
|
||||||
src->in_general = 1;
|
src->in_general = 1;
|
||||||
}
|
}
|
||||||
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
|
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
|
||||||
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 2, acq);
|
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
|
||||||
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
|
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
|
||||||
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||||
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
|
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
|
||||||
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||||
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
|
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
|
||||||
g_vk.CmdBlitImage(g_cmd, src->image,
|
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||||
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
dst, &blit, VK_FILTER_NEAREST);
|
||||||
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
|
|
||||||
release_external_client_image(g_cmd, src);
|
release_external_client_image(g_cmd, src);
|
||||||
VkImageMemoryBarrier rel = {
|
|
||||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
|
||||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
|
|
||||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
|
|
||||||
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
|
|
||||||
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
|
|
||||||
0, 0, NULL, 0, NULL, 1, &rel);
|
|
||||||
g_vk.EndCommandBuffer(g_cmd);
|
g_vk.EndCommandBuffer(g_cmd);
|
||||||
|
|
||||||
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||||||
@@ -2890,31 +2930,14 @@ static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp
|
|||||||
}
|
}
|
||||||
const int gpu_wait = take_wait_fd(wait_fd);
|
const int gpu_wait = take_wait_fd(wait_fd);
|
||||||
if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; }
|
if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; }
|
||||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
|
||||||
|
|
||||||
for (int i = 0; i < n; i++) {
|
for (int i = 0; i < n; i++) {
|
||||||
struct vkp_image *dst = dsts[i];
|
struct vkp_image *dst = dsts[i];
|
||||||
VkImageMemoryBarrier acq = {
|
|
||||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
|
||||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
|
|
||||||
.dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range,
|
|
||||||
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
|
|
||||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
|
||||||
0, 0, NULL, 0, NULL, 1, &acq);
|
|
||||||
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||||
.srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}},
|
.srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}},
|
||||||
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||||
.dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}};
|
.dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}};
|
||||||
g_vk.CmdBlitImage(cmd, srcs[i], src_layout, dst->image,
|
blit_to_layer(cmd, srcs[i], src_layout, dst, &blit,
|
||||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
|
(g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
|
||||||
(g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
|
|
||||||
VkImageMemoryBarrier rel = {
|
|
||||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
|
||||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
|
|
||||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
|
|
||||||
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
|
|
||||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
|
|
||||||
0, 0, NULL, 0, NULL, 1, &rel);
|
|
||||||
}
|
}
|
||||||
g_vk.EndCommandBuffer(cmd);
|
g_vk.EndCommandBuffer(cmd);
|
||||||
|
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ static jclass g_compositor_cls;
|
|||||||
static jmethodID g_on_first_frame;
|
static jmethodID g_on_first_frame;
|
||||||
static jmethodID g_on_game_surface;
|
static jmethodID g_on_game_surface;
|
||||||
static jmethodID g_on_game_frame;
|
static jmethodID g_on_game_frame;
|
||||||
|
static jmethodID g_on_compositor_frame;
|
||||||
static jmethodID g_on_game_program;
|
static jmethodID g_on_game_program;
|
||||||
static jmethodID g_on_pointer_lock;
|
static jmethodID g_on_pointer_lock;
|
||||||
static jmethodID g_on_clipboard;
|
static jmethodID g_on_clipboard;
|
||||||
@@ -84,6 +85,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
|
|||||||
g_on_game_surface = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameSurface",
|
g_on_game_surface = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameSurface",
|
||||||
"(Ljava/lang/String;Ljava/lang/String;)V");
|
"(Ljava/lang/String;Ljava/lang/String;)V");
|
||||||
g_on_game_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameFrame", "()V");
|
g_on_game_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameFrame", "()V");
|
||||||
|
g_on_compositor_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onCompositorFrame", "()V");
|
||||||
g_on_game_program = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameProgram",
|
g_on_game_program = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameProgram",
|
||||||
"(ILjava/lang/String;)V");
|
"(ILjava/lang/String;)V");
|
||||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; }
|
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; }
|
||||||
@@ -154,6 +156,13 @@ void droiddeck_on_game_frame(void) {
|
|||||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void droiddeck_on_compositor_frame(void) {
|
||||||
|
JNIEnv *env;
|
||||||
|
if (!g_compositor_cls || !g_on_compositor_frame || !(env = thread_env())) return;
|
||||||
|
(*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_compositor_frame);
|
||||||
|
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||||
|
}
|
||||||
|
|
||||||
void droiddeck_on_refresh_target(int refresh, int frame_rate) {
|
void droiddeck_on_refresh_target(int refresh, int frame_rate) {
|
||||||
JNIEnv *env;
|
JNIEnv *env;
|
||||||
if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return;
|
if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return;
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class App : Application() {
|
|||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
com.droiddeck.launcher.runtime.NativeGuest.init(this)
|
com.droiddeck.launcher.runtime.NativeGuest.init(this)
|
||||||
|
com.droiddeck.launcher.session.Onboarding.attach(this)
|
||||||
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
|
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
|
||||||
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
||||||
com.droiddeck.launcher.ui.BuildWatermark.install(this)
|
com.droiddeck.launcher.ui.BuildWatermark.install(this)
|
||||||
@@ -46,6 +47,7 @@ class App : Application() {
|
|||||||
com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this)
|
com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this)
|
||||||
com.droiddeck.launcher.agent.AgentHost.refresh(this)
|
com.droiddeck.launcher.agent.AgentHost.refresh(this)
|
||||||
com.droiddeck.launcher.ui.NavTabs.load(this)
|
com.droiddeck.launcher.ui.NavTabs.load(this)
|
||||||
|
com.droiddeck.launcher.ui.DrawerPages.load(this)
|
||||||
com.droiddeck.launcher.ui.DeveloperTools.load(this)
|
com.droiddeck.launcher.ui.DeveloperTools.load(this)
|
||||||
com.droiddeck.launcher.ui.AgentPet.install(this)
|
com.droiddeck.launcher.ui.AgentPet.install(this)
|
||||||
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
|
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
|
||||||
@@ -53,7 +55,7 @@ class App : Application() {
|
|||||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.entries.map { it.id })
|
com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.tabbed.map { it.id })
|
||||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||||
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
|
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
|
||||||
com.droiddeck.launcher.core.DownloadSource.init(this)
|
com.droiddeck.launcher.core.DownloadSource.init(this)
|
||||||
@@ -78,6 +80,7 @@ class App : Application() {
|
|||||||
com.droiddeck.launcher.stores.ea.EaBackend.app = this
|
com.droiddeck.launcher.stores.ea.EaBackend.app = this
|
||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
|
||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend)
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend)
|
||||||
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.steam.SteamBackend)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun prefetchAddonPacks() {
|
private fun prefetchAddonPacks() {
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
|||||||
checkAgain = null
|
checkAgain = null
|
||||||
checkComponentUpdates(again)
|
checkComponentUpdates(again)
|
||||||
}
|
}
|
||||||
if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
|
if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; "))
|
||||||
refreshComponents()
|
refreshComponents()
|
||||||
}
|
}
|
||||||
}, "component-updates").start()
|
}, "component-updates").start()
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import androidx.compose.runtime.mutableIntStateOf
|
|||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import com.droiddeck.launcher.runtime.DeckyManager
|
import com.droiddeck.launcher.runtime.DeckyManager
|
||||||
|
import com.droiddeck.launcher.runtime.DeckyStore
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
@@ -21,6 +22,59 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
|||||||
var deckySupervisor by mutableStateOf(false)
|
var deckySupervisor by mutableStateOf(false)
|
||||||
var deckyPendingZip by mutableStateOf<File?>(null)
|
var deckyPendingZip by mutableStateOf<File?>(null)
|
||||||
var deckyReleaseRequest = 0
|
var deckyReleaseRequest = 0
|
||||||
|
var deckyPlugins by mutableStateOf<List<DeckyStore.Installed>>(emptyList())
|
||||||
|
var deckyStore by mutableStateOf<List<DeckyStore.Plugin>?>(null)
|
||||||
|
var deckyStoreFailed by mutableStateOf(false)
|
||||||
|
private var storeRequest = 0
|
||||||
|
|
||||||
|
fun refreshPlugins() {
|
||||||
|
Thread({
|
||||||
|
val found = DeckyStore.installed(activity)
|
||||||
|
ui.post { deckyPlugins = found }
|
||||||
|
}, "decky-plugins").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun refreshStore() {
|
||||||
|
val request = ++storeRequest
|
||||||
|
deckyStore = null; deckyStoreFailed = false
|
||||||
|
Thread({
|
||||||
|
val listing = DeckyStore.fetch()
|
||||||
|
ui.post {
|
||||||
|
if (request != storeRequest) return@post
|
||||||
|
deckyStore = listing.orEmpty(); deckyStoreFailed = listing == null
|
||||||
|
}
|
||||||
|
}, "decky-store").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun installStorePlugin(plugin: DeckyStore.Plugin) {
|
||||||
|
val version = plugin.latest ?: return
|
||||||
|
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
|
||||||
|
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1
|
||||||
|
Thread({
|
||||||
|
val problem = runCatching {
|
||||||
|
DeckyStore.install(activity, plugin, version) { label, value ->
|
||||||
|
val binary = DeckyManager.downloadingBinary
|
||||||
|
ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary }
|
||||||
|
}
|
||||||
|
}.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) }
|
||||||
|
ui.post {
|
||||||
|
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
|
||||||
|
android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.decky_plugin_installed), android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
refreshPlugins()
|
||||||
|
}
|
||||||
|
}, "install-decky-store").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removePlugin(plugin: DeckyStore.Installed) {
|
||||||
|
if (deckyStage != null || SessionState.running) return
|
||||||
|
Thread({
|
||||||
|
val problem = DeckyStore.remove(activity, plugin)
|
||||||
|
ui.post {
|
||||||
|
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
refreshPlugins()
|
||||||
|
}
|
||||||
|
}, "remove-decky-plugin").start()
|
||||||
|
}
|
||||||
|
|
||||||
fun refreshDecky() {
|
fun refreshDecky() {
|
||||||
val request = ++deckyReleaseRequest
|
val request = ++deckyReleaseRequest
|
||||||
@@ -90,6 +144,7 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
|||||||
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
|
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
|
||||||
val message = problem ?: activity.getString(R.string.decky_plugin_installed)
|
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()
|
||||||
|
refreshPlugins()
|
||||||
}
|
}
|
||||||
}, "import-decky-plugin").start()
|
}, "import-decky-plugin").start()
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -118,12 +118,18 @@ object HomeWidgets {
|
|||||||
if (live.size != parsed.size) save(context)
|
if (live.size != parsed.size) save(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val listeners: MutableSet<Any> = java.util.Collections.newSetFromMap(java.util.IdentityHashMap())
|
||||||
|
|
||||||
fun startListening(context: Context) {
|
fun startListening(context: Context) {
|
||||||
|
listeners.add(context)
|
||||||
load(context)
|
load(context)
|
||||||
runCatching { host(context).startListening() }
|
runCatching { host(context).startListening() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A restarted launcher starts before the old one stops; the host keeps listening until the last owner stops.
|
||||||
fun stopListening(context: Context) {
|
fun stopListening(context: Context) {
|
||||||
|
listeners.remove(context)
|
||||||
|
if (listeners.isNotEmpty()) return
|
||||||
runCatching { host(context).stopListening() }
|
runCatching { host(context).stopListening() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.SystemClock
|
||||||
|
|
||||||
|
/**
|
||||||
|
* State a restarting launcher passes to its replacement inside this process. Intent extras are not used
|
||||||
|
* because FrontEndActivity is exported and any app could fill them.
|
||||||
|
*/
|
||||||
|
internal object LauncherHandoff {
|
||||||
|
private const val LIFETIME_MS = 10_000L
|
||||||
|
private var state: Bundle? = null
|
||||||
|
private var at = 0L
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun put(carried: Bundle) {
|
||||||
|
state = carried
|
||||||
|
at = SystemClock.elapsedRealtime()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun take(): Bundle? {
|
||||||
|
val carried = state
|
||||||
|
state = null
|
||||||
|
return carried?.takeIf { SystemClock.elapsedRealtime() - at <= LIFETIME_MS }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -93,6 +93,14 @@ class PairingGuideActivity : ComponentActivity() {
|
|||||||
launchPending = true
|
launchPending = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
val stage = WirelessAdbPairingService.stage.value
|
||||||
|
if (isFinishing && (stage is WirelessAdbPairingService.Stage.Waiting || stage is WirelessAdbPairingService.Stage.CodeNeeded)) {
|
||||||
|
WirelessAdbPairingService.cancel(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
if (!launchPending) return
|
if (!launchPending) return
|
||||||
|
|||||||
@@ -8,7 +8,9 @@ import androidx.compose.runtime.mutableIntStateOf
|
|||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import com.droiddeck.launcher.session.ExperimentalProtons
|
import com.droiddeck.launcher.session.ExperimentalProtons
|
||||||
|
import com.droiddeck.launcher.session.Onboarding
|
||||||
import com.droiddeck.launcher.session.ProtonExtras
|
import com.droiddeck.launcher.session.ProtonExtras
|
||||||
|
import com.droiddeck.launcher.session.SteamClientPrefetch
|
||||||
import com.droiddeck.launcher.ui.ProtonRow
|
import com.droiddeck.launcher.ui.ProtonRow
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import com.droiddeck.launcher.session.SessionPhase
|
import com.droiddeck.launcher.session.SessionPhase
|
||||||
@@ -47,7 +49,7 @@ internal class ProtonMenu(
|
|||||||
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
|
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
|
||||||
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
|
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
|
||||||
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
||||||
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
|
{ tool, progress -> ProtonExtras.install(activity, tool, onProgress = progress) }
|
||||||
|
|
||||||
fun installProton(id: String, automatic: Boolean = false) {
|
fun installProton(id: String, automatic: Boolean = false) {
|
||||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||||
@@ -60,10 +62,15 @@ internal class ProtonMenu(
|
|||||||
Thread({
|
Thread({
|
||||||
val problem = runCatching {
|
val problem = runCatching {
|
||||||
installer(tool) { label, value ->
|
installer(tool) { label, value ->
|
||||||
|
if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value)
|
||||||
ui.post { protonStage = label; protonPercent = value }
|
ui.post { protonStage = label; protonPercent = value }
|
||||||
}
|
}
|
||||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||||
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
||||||
|
if (tool.id == ProtonExtras.OWN) {
|
||||||
|
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
|
||||||
|
Onboarding.recheck(activity)
|
||||||
|
}
|
||||||
ui.post {
|
ui.post {
|
||||||
protonProblem = problem
|
protonProblem = problem
|
||||||
protonBusyId = null
|
protonBusyId = null
|
||||||
@@ -149,7 +156,7 @@ internal class ProtonMenu(
|
|||||||
|
|
||||||
fun refreshProtons() {
|
fun refreshProtons() {
|
||||||
refreshExperimental()
|
refreshExperimental()
|
||||||
protonRows = ProtonExtras.tools.map {
|
protonRows = ProtonExtras.offered(activity).map {
|
||||||
val all = ProtonExtras.installedAll(activity, it)
|
val all = ProtonExtras.installedAll(activity, it)
|
||||||
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
||||||
}
|
}
|
||||||
@@ -170,16 +177,46 @@ internal class ProtonMenu(
|
|||||||
Operation.checking.set(false)
|
Operation.checking.set(false)
|
||||||
}
|
}
|
||||||
ensureAutoUpdates()
|
ensureAutoUpdates()
|
||||||
|
ensureSteamClient()
|
||||||
}
|
}
|
||||||
if (!published) Operation.checking.set(false)
|
if (!published) Operation.checking.set(false)
|
||||||
}, "proton-updates").start()
|
}, "proton-updates").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */
|
||||||
|
fun prefetchOwn() {
|
||||||
|
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||||
|
if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() ||
|
||||||
|
ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return
|
||||||
|
Thread({
|
||||||
|
val problem = runCatching {
|
||||||
|
ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) }
|
||||||
|
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||||
|
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
|
||||||
|
Onboarding.recheck(activity)
|
||||||
|
ui.post { ensureAutoUpdates() }
|
||||||
|
}, "proton-prefetch").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */
|
||||||
|
fun ensureSteamClient() {
|
||||||
|
if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||||
|
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) ||
|
||||||
|
!AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return
|
||||||
|
SteamClientPrefetch.start(
|
||||||
|
activity,
|
||||||
|
{ mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) },
|
||||||
|
activity.getString(R.string.onboarding_steam_failed),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
|
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
|
||||||
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
|
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
|
||||||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
|
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
|
||||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
|
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return
|
||||||
|
val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty()
|
||||||
|
if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return
|
||||||
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
||||||
protonBusyId = ProtonExtras.OWN
|
protonBusyId = ProtonExtras.OWN
|
||||||
protonProblem = null
|
protonProblem = null
|
||||||
|
|||||||
@@ -154,6 +154,8 @@ import com.droiddeck.launcher.session.ComponentsManager
|
|||||||
import com.droiddeck.launcher.session.LatestRequestCoordinator
|
import com.droiddeck.launcher.session.LatestRequestCoordinator
|
||||||
import com.droiddeck.launcher.ui.SessionDrawerPage
|
import com.droiddeck.launcher.ui.SessionDrawerPage
|
||||||
import com.droiddeck.launcher.ui.sessionDrawerPages
|
import com.droiddeck.launcher.ui.sessionDrawerPages
|
||||||
|
import com.droiddeck.launcher.ui.strip
|
||||||
|
import com.droiddeck.launcher.ui.tabFor
|
||||||
import com.droiddeck.launcher.ui.step
|
import com.droiddeck.launcher.ui.step
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
|
|
||||||
@@ -244,9 +246,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
override fun key(code: Int, down: Boolean) { heldKeys.set(4, code, down) }
|
override fun key(code: Int, down: Boolean) { heldKeys.set(4, code, down) }
|
||||||
override fun button(code: Int, down: Boolean) { heldButtons.set(4, code, down) }
|
override fun button(code: Int, down: Boolean) { heldButtons.set(4, code, down) }
|
||||||
override fun pointer(dx: Float, dy: Float) {
|
override fun pointer(dx: Float, dy: Float) {
|
||||||
if (Looper.myLooper() == Looper.getMainLooper()) moveInputPointer(dx, dy)
|
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||||
else uiHandler.post {
|
if (!menuOwnsController) moveInputPointer(dx, dy)
|
||||||
if (resumed && !SessionState.suspended && !pipUi && !drawerOpen && !inputSettingsOpen)
|
} else uiHandler.post {
|
||||||
|
if (resumed && !SessionState.suspended && !pipUi && !menuOwnsController && !inputSettingsOpen)
|
||||||
moveInputPointer(dx, dy)
|
moveInputPointer(dx, dy)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -545,6 +548,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
drawerOpenState = value
|
drawerOpenState = value
|
||||||
if (!value && drawerDocked) closeDockedMenu()
|
if (!value && drawerDocked) closeDockedMenu()
|
||||||
}
|
}
|
||||||
|
private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController)
|
||||||
|
private val dockedTouchOnly: Boolean get() = drawerOpen && drawerDocked && !dockedMenuController
|
||||||
|
private val menuOwnsController: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuOwnsController(drawerOpen, drawerDocked, dockedMenuController)
|
||||||
private var quitFrom by mutableStateOf<androidx.compose.ui.geometry.Rect?>(null)
|
private var quitFrom by mutableStateOf<androidx.compose.ui.geometry.Rect?>(null)
|
||||||
private var quitFlooded = false
|
private var quitFlooded = false
|
||||||
private var leaving by mutableStateOf(false)
|
private var leaving by mutableStateOf(false)
|
||||||
@@ -588,6 +594,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
|
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
|
||||||
private var drawerControllerActive by mutableStateOf(false)
|
private var drawerControllerActive by mutableStateOf(false)
|
||||||
private var backHold by mutableStateOf(true)
|
private var backHold by mutableStateOf(true)
|
||||||
|
private var dockedMenuController by mutableStateOf(false)
|
||||||
|
private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
||||||
|
private var dualScreenSessionMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
|
||||||
private var backActionsInverted by mutableStateOf(false)
|
private var backActionsInverted by mutableStateOf(false)
|
||||||
private var backDoubleTapMs by mutableStateOf(500)
|
private var backDoubleTapMs by mutableStateOf(500)
|
||||||
private var lowLatency by mutableStateOf(true)
|
private var lowLatency by mutableStateOf(true)
|
||||||
@@ -833,15 +842,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
finish()
|
finish()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(intent)) {
|
||||||
|
runtimeRemovalBlocked = true
|
||||||
|
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
finish()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (savedInstanceState == null && !SessionState.running && !com.droiddeck.launcher.stores.steam.SteamStore.downloading()) {
|
||||||
|
// The Steam client signs in itself; the store's own sign-in must not overlap it.
|
||||||
|
Thread({ com.droiddeck.launcher.stores.steam.SteamEngine.forget() }, "steam-store-signout").start()
|
||||||
|
}
|
||||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||||
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||||
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
|
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
|
||||||
SessionState.secondScreenAutoOpened = false
|
SessionState.secondScreenAutoOpened = false
|
||||||
|
SessionState.bottomMenu = false
|
||||||
SessionState.secondScreenProvisional = false
|
SessionState.secondScreenProvisional = false
|
||||||
SessionState.secondScreenAutomatic = false
|
SessionState.secondScreenAutomatic = false
|
||||||
SessionState.gameOnBottom = false
|
SessionState.gameOnBottom = SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED
|
||||||
gameOnBottom = false
|
gameOnBottom = SessionState.gameOnBottom
|
||||||
}
|
}
|
||||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||||
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||||
@@ -865,9 +885,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
cornerTap = SessionPrefs.drawerCornerTap(this)
|
cornerTap = SessionPrefs.drawerCornerTap(this)
|
||||||
applyOutputPacing()
|
applyOutputPacing()
|
||||||
if (!SessionState.running) {
|
if (!SessionState.running) {
|
||||||
SessionState.followScreen = followChoice()
|
SessionState.followScales = SessionPrefs.followScales(this, displayMode(),
|
||||||
SessionState.followScale = followScale()
|
com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
||||||
}
|
}
|
||||||
|
applyFollowChoice()
|
||||||
applyFollowOrientation(resources.configuration)
|
applyFollowOrientation(resources.configuration)
|
||||||
goFullscreen()
|
goFullscreen()
|
||||||
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
|
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
|
||||||
@@ -926,11 +947,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
|
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
|
||||||
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
|
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
|
||||||
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
|
|
||||||
!SessionPrefs.bluetoothAsked(this)) {
|
|
||||||
SessionPrefs.setBluetoothAsked(this)
|
|
||||||
requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH)
|
|
||||||
}
|
|
||||||
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
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
|
||||||
@@ -1109,6 +1125,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
when {
|
when {
|
||||||
::loading.isInitialized && loading.ended -> finish()
|
::loading.isInitialized && loading.ended -> finish()
|
||||||
inputSettingsOpen -> inputSettingsOpen = false
|
inputSettingsOpen -> inputSettingsOpen = false
|
||||||
|
dockedTouchOnly -> routeBackAction()
|
||||||
drawerOpen -> drawerOpen = false
|
drawerOpen -> drawerOpen = false
|
||||||
achievementsOpen -> closeAchievements()
|
achievementsOpen -> closeAchievements()
|
||||||
pcKeyboardOpen -> pcKeyboardOpen = false
|
pcKeyboardOpen -> pcKeyboardOpen = false
|
||||||
@@ -1137,6 +1154,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
val uiPointer = appUiOwnsPointer()
|
val uiPointer = appUiOwnsPointer()
|
||||||
|
val cursorHidden = cursorHiddenByUi()
|
||||||
androidx.compose.runtime.SideEffect {
|
androidx.compose.runtime.SideEffect {
|
||||||
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
|
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
|
||||||
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
|
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
|
||||||
@@ -1187,7 +1205,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
|
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
|
||||||
CursorOverlay({ cursorPos }, cursorVisible && (!uiPointer || onlyPcKeyboardOpen()) && !bottomOutputActive,
|
CursorOverlay({ cursorPos }, cursorVisible && (!cursorHidden || onlyPcKeyboardOpen()) && !bottomOutputActive,
|
||||||
resources.displayMetrics.density,
|
resources.displayMetrics.density,
|
||||||
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
||||||
if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity)
|
if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity)
|
||||||
@@ -1304,9 +1322,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
|
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
|
LaunchedEffect(drawerOpen, menuOwnsController, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
|
||||||
updateOnScreenControls()
|
updateOnScreenControls()
|
||||||
padBridge?.setInputEnabled(resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
|
padBridge?.setInputEnabled(resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
|
||||||
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended) {
|
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended) {
|
||||||
backQamInput.cancel()
|
backQamInput.cancel()
|
||||||
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
|
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
|
||||||
@@ -1358,13 +1376,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
onDismiss = { gestureSettingsOpen = false },
|
onDismiss = { gestureSettingsOpen = false },
|
||||||
onSaved = { gestureSettingsOpen = false; refreshGestureConfig() },
|
onSaved = { gestureSettingsOpen = false; refreshGestureConfig() },
|
||||||
)
|
)
|
||||||
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
|
androidx.compose.runtime.LaunchedEffect(drawerOpen, menuOwnsController) {
|
||||||
if (drawerOpen) {
|
if (drawerOpen) {
|
||||||
syncLossless()
|
syncLossless()
|
||||||
releasePads()
|
if (menuOwnsController) {
|
||||||
androidx.compose.runtime.withFrameNanos { }
|
releasePads()
|
||||||
val requested = focusDrawer()
|
androidx.compose.runtime.withFrameNanos { }
|
||||||
Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked")
|
val requested = focusDrawer()
|
||||||
|
Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked")
|
||||||
|
} else {
|
||||||
|
releaseDrawerDirection()
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
releaseDrawerDirection()
|
releaseDrawerDirection()
|
||||||
}
|
}
|
||||||
@@ -1423,7 +1445,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
if (!SessionState.manualPause && !SessionState.suspended) pauseAnimated = false
|
if (!SessionState.manualPause && !SessionState.suspended) pauseAnimated = false
|
||||||
}
|
}
|
||||||
SessionPausedOverlay(
|
SessionPausedOverlay(
|
||||||
suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed || SessionState.manualPause),
|
suspended = (SessionState.suspended || SessionState.manualPause) && (!autoResume || SessionState.resumeFailed || SessionState.manualPause),
|
||||||
engaged = SessionState.resumeRequested || SessionState.resuming,
|
engaged = SessionState.resumeRequested || SessionState.resuming,
|
||||||
failures = SessionState.resumeFailures,
|
failures = SessionState.resumeFailures,
|
||||||
frame = pausedFrame,
|
frame = pausedFrame,
|
||||||
@@ -1522,6 +1544,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
fexPreset = fexPreset,
|
fexPreset = fexPreset,
|
||||||
secondScreenMode = secondScreenMode,
|
secondScreenMode = secondScreenMode,
|
||||||
secondScreenNone = !bottomOutputActive && !dockDrawer(),
|
secondScreenNone = !bottomOutputActive && !dockDrawer(),
|
||||||
|
dualScreenMode = dualScreenSessionMode,
|
||||||
|
onDualScreenMode = ::chooseDualScreenSessionMode,
|
||||||
gameOnBottom = bottomOutputActive,
|
gameOnBottom = bottomOutputActive,
|
||||||
gameSwapAvailable = bottomSwapAvailable,
|
gameSwapAvailable = bottomSwapAvailable,
|
||||||
gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay)
|
gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay)
|
||||||
@@ -1532,6 +1556,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
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() },
|
||||||
|
onHudOnlyDuringGame = { on ->
|
||||||
|
SessionPrefs.setHudOnlyDuringGame(this@SessionActivity, on)
|
||||||
|
hud.refresh()
|
||||||
|
},
|
||||||
onGpuClockPin = { on ->
|
onGpuClockPin = { on ->
|
||||||
SessionPrefs.setGpuClockPin(this@SessionActivity, on)
|
SessionPrefs.setGpuClockPin(this@SessionActivity, on)
|
||||||
gpuClockPin = on
|
gpuClockPin = on
|
||||||
@@ -1752,6 +1780,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id))
|
com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id))
|
||||||
padType = id
|
padType = id
|
||||||
onScreenControls?.reload()
|
onScreenControls?.reload()
|
||||||
|
applyUnfoldedControls()
|
||||||
|
unfoldedPanel?.reload()
|
||||||
bottomInputControls?.reload()
|
bottomInputControls?.reload()
|
||||||
},
|
},
|
||||||
backHold = backHold,
|
backHold = backHold,
|
||||||
@@ -1759,6 +1789,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
SessionPrefs.setBackHold(this@SessionActivity, on)
|
SessionPrefs.setBackHold(this@SessionActivity, on)
|
||||||
backHold = on
|
backHold = on
|
||||||
},
|
},
|
||||||
|
dockedMenuController = dockedMenuController,
|
||||||
|
onDockedMenuController = { on ->
|
||||||
|
SessionPrefs.setDockedMenuController(this@SessionActivity, on)
|
||||||
|
dockedMenuController = on
|
||||||
|
if (!on && drawerDocked) drawerControllerActive = false
|
||||||
|
},
|
||||||
backActionsInverted = backActionsInverted,
|
backActionsInverted = backActionsInverted,
|
||||||
backDoubleTapMs = backDoubleTapMs,
|
backDoubleTapMs = backDoubleTapMs,
|
||||||
onBackDoubleTapMs = { ms ->
|
onBackDoubleTapMs = { ms ->
|
||||||
@@ -1827,6 +1863,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
setRelativeMouse(mode)
|
setRelativeMouse(mode)
|
||||||
},
|
},
|
||||||
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
||||||
|
onSelectMenuMode = ::pickMenuMode,
|
||||||
onSecondScreenMode = { mode ->
|
onSecondScreenMode = { mode ->
|
||||||
if (docked) drawerOpen = false
|
if (docked) drawerOpen = false
|
||||||
pickSecondScreenMode(mode)
|
pickSecondScreenMode(mode)
|
||||||
@@ -1850,6 +1887,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
pipAutoEnter = pipAutoEnter,
|
pipAutoEnter = pipAutoEnter,
|
||||||
onPip = { pip.enter() },
|
onPip = { pip.enter() },
|
||||||
onPause = ::pauseNow,
|
onPause = ::pauseNow,
|
||||||
|
paused = SessionState.suspended || SessionState.manualPause,
|
||||||
|
onResume = { SessionService.resume(this@SessionActivity) },
|
||||||
|
orientation = sessionOrientation,
|
||||||
|
onOrientation = { value ->
|
||||||
|
SessionPrefs.setOrientation(this@SessionActivity, value)
|
||||||
|
sessionOrientation = value
|
||||||
|
applyFollowOrientation(resources.configuration)
|
||||||
|
},
|
||||||
onPipAutoEnter = { on ->
|
onPipAutoEnter = { on ->
|
||||||
SessionPrefs.setPipAutoEnter(this@SessionActivity, on)
|
SessionPrefs.setPipAutoEnter(this@SessionActivity, on)
|
||||||
pipAutoEnter = on
|
pipAutoEnter = on
|
||||||
@@ -1947,7 +1992,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun sendSteamGuide() {
|
private fun sendSteamGuide() {
|
||||||
drawerOpen = false
|
if (!dockedTouchOnly) drawerOpen = false
|
||||||
padBridge?.triggerSteamMenu()
|
padBridge?.triggerSteamMenu()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1994,7 +2039,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun triggerSteamQam() {
|
private fun triggerSteamQam() {
|
||||||
drawerOpen = false
|
if (!dockedTouchOnly) drawerOpen = false
|
||||||
padBridge?.triggerQam()
|
padBridge?.triggerQam()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2083,7 +2128,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private fun performBackAction(double: Boolean) {
|
private fun performBackAction(double: Boolean) {
|
||||||
val isSteam = SessionState.mode == SessionService.MODE_STEAM
|
val isSteam = SessionState.mode == SessionService.MODE_STEAM
|
||||||
val opensQam = isSteam && (double xor backActionsInverted)
|
val opensQam = isSteam && (double xor backActionsInverted)
|
||||||
if (opensQam) triggerSteamQam() else drawerOpen = !drawerOpen
|
if (opensQam) triggerSteamQam() else if (!dockedTouchOnly) drawerOpen = !drawerOpen
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleHomeGuideIntent(incoming: Intent?) {
|
private fun handleHomeGuideIntent(incoming: Intent?) {
|
||||||
@@ -2627,6 +2672,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
oscRearButtons = SessionPrefs.oscRearButtons(this)
|
oscRearButtons = SessionPrefs.oscRearButtons(this)
|
||||||
oscTrackpads = SessionPrefs.oscTrackpads(this)
|
oscTrackpads = SessionPrefs.oscTrackpads(this)
|
||||||
backHold = SessionPrefs.backHold(this)
|
backHold = SessionPrefs.backHold(this)
|
||||||
|
dockedMenuController = SessionPrefs.dockedMenuController(this)
|
||||||
|
sessionOrientation = SessionPrefs.orientation(this)
|
||||||
|
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
|
||||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||||
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
|
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
|
||||||
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
|
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
|
||||||
@@ -2796,6 +2844,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
|
|
||||||
private fun installProton(): String? {
|
private fun installProton(): String? {
|
||||||
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
|
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
|
||||||
|
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(this)) return installOwnProton()
|
||||||
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
||||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||||
SessionState.installCancellation = cancellation
|
SessionState.installCancellation = cancellation
|
||||||
@@ -2808,6 +2857,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun installOwnProton(): String? {
|
||||||
|
val extras = com.droiddeck.launcher.session.ProtonExtras
|
||||||
|
while ((extras.prefetching || extras.installInProgress) && !SessionState.stopRequested) {
|
||||||
|
try { Thread.sleep(250) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return "interrupted" }
|
||||||
|
}
|
||||||
|
if (SessionState.stopRequested) return "cancelled"
|
||||||
|
if (!com.droiddeck.launcher.runtime.DesktopCatalog.ownProtonMissing(this)) return null
|
||||||
|
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||||
|
SessionState.installCancellation = cancellation
|
||||||
|
return try {
|
||||||
|
extras.install(this, extras.tools.first { it.id == extras.OWN }, cancellation) { label, percent ->
|
||||||
|
uiHandler.post { loading.percent = percent; loading.say(label, PROTON_LINES.topic, readable = true) }
|
||||||
|
}.also { if (it == null) com.droiddeck.launcher.session.Onboarding.recheck(this) }
|
||||||
|
} finally {
|
||||||
|
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||||
if (holder !== outputHolder()) return
|
if (holder !== outputHolder()) return
|
||||||
if (installingRuntime || SessionState.stopRequested || ended) return
|
if (installingRuntime || SessionState.stopRequested || ended) return
|
||||||
@@ -2956,16 +3023,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
WaylandCompositor.nativeResizeOutput(size.first, size.second)
|
WaylandCompositor.nativeResizeOutput(size.first, size.second)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun followScale(): Float {
|
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
|
||||||
val mode = displayMode()
|
|
||||||
val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
|
||||||
return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun followChoice(): Boolean {
|
private fun applyFollowChoice() {
|
||||||
val mode = displayMode()
|
val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first }
|
||||||
return com.droiddeck.launcher.session.SessionDisplay.isFollow(
|
SessionState.followScreen = scale != null
|
||||||
SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)))
|
SessionState.followScale = scale ?: 1f
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun applyFollowOrientation(config: android.content.res.Configuration) {
|
private fun applyFollowOrientation(config: android.content.res.Configuration) {
|
||||||
@@ -2979,6 +3042,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
|
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
|
||||||
}
|
}
|
||||||
cancelTouchGestures()
|
cancelTouchGestures()
|
||||||
|
applyFollowChoice()
|
||||||
applyFollowOrientation(newConfig)
|
applyFollowOrientation(newConfig)
|
||||||
applyNotchInset()
|
applyNotchInset()
|
||||||
applyUnfoldedControls()
|
applyUnfoldedControls()
|
||||||
@@ -3031,17 +3095,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private fun displayMode(): String = SessionPrefs.displayMode(this,
|
private fun displayMode(): String = SessionPrefs.displayMode(this,
|
||||||
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
|
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
|
||||||
|
|
||||||
|
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted()
|
||||||
|
|
||||||
private fun outputSize(): Pair<Int, Int> =
|
private fun outputSize(): Pair<Int, Int> =
|
||||||
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
||||||
resolutionChoice(), SessionPrefs.portrait(this) && !controlsBelowWanted())
|
resolutionChoice(), portraitOutput())
|
||||||
|
|
||||||
private fun resolutionChoice(): String {
|
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String {
|
||||||
val mode = displayMode()
|
val mode = displayMode()
|
||||||
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||||
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
|
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
|
||||||
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
|
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode, portrait))
|
||||||
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
|
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
|
||||||
else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), portrait)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshHz(): Float = refreshHz(null)
|
private fun refreshHz(): Float = refreshHz(null)
|
||||||
@@ -3358,8 +3424,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
if (status == 0) SessionState.takeRelaunch()?.let { next ->
|
if (status == 0) SessionState.takeRelaunch()?.let { next ->
|
||||||
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
|
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
|
||||||
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
|
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
|
||||||
setIntent(next)
|
relaunch(next)
|
||||||
recreate()
|
|
||||||
return@runOnUiThread
|
return@runOnUiThread
|
||||||
}
|
}
|
||||||
showEnded(status, hint)
|
showEnded(status, hint)
|
||||||
@@ -3367,6 +3432,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}, "session-end-hint").start()
|
}, "session-end-hint").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// recreate() keeps this window, and Compose content added to it afterwards never recomposes, so the
|
||||||
|
// loading screen of the next session stays up over a running session. A new instance gets its own window.
|
||||||
|
// This instance finishes first because the activity is singleTask and would otherwise take the intent itself.
|
||||||
|
private fun relaunch(next: Intent) {
|
||||||
|
closeAtOnce = true
|
||||||
|
super.finish()
|
||||||
|
startActivity(next)
|
||||||
|
overridePendingTransition(0, 0)
|
||||||
|
}
|
||||||
|
|
||||||
private fun showEnded(status: Int, hint: EndHint?) {
|
private fun showEnded(status: Int, hint: EndHint?) {
|
||||||
if (status == 0 && hint?.evenOnSuccess != true) {
|
if (status == 0 && hint?.evenOnSuccess != true) {
|
||||||
finish()
|
finish()
|
||||||
@@ -3511,13 +3586,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
|
|
||||||
|
|
||||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||||
|
val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event)
|
||||||
|
if (normalized === event) return dispatchSessionKeyEvent(event)
|
||||||
|
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||||
|
Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}")
|
||||||
|
}
|
||||||
|
return dispatchSessionKeyEvent(normalized)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean {
|
||||||
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
|
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
|
||||||
when (event.keyCode) {
|
when (event.keyCode) {
|
||||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
|
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
|
||||||
val steamVolume =
|
val steamVolume =
|
||||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
|
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
|
||||||
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
|
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
|
||||||
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
!pipUi && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
|
||||||
!gestureSettingsOpen && !inputSettingsOpen && !appTextFocus && window.decorView.hasWindowFocus()
|
!gestureSettingsOpen && !inputSettingsOpen && !appTextFocus && window.decorView.hasWindowFocus()
|
||||||
if (steamVolume) {
|
if (steamVolume) {
|
||||||
val audio = getSystemService(android.media.AudioManager::class.java)
|
val audio = getSystemService(android.media.AudioManager::class.java)
|
||||||
@@ -3531,13 +3615,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
if (penStream.holdsKey(event) || (penSettings.mode != SessionPrefs.PEN_TOUCH && PenStream.isPenKey(event))) return penStream.onKey(event)
|
if (penStream.holdsKey(event) || (penSettings.mode != SessionPrefs.PEN_TOUCH && PenStream.isPenKey(event))) return penStream.onKey(event)
|
||||||
if (appTextFocus) return super.dispatchKeyEvent(event)
|
if (appTextFocus) return super.dispatchKeyEvent(event)
|
||||||
if (!pipUi) {
|
if (!pipUi) {
|
||||||
if (physicalInputBindings?.onKey(event, resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
if (physicalInputBindings?.onKey(event, resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
|
||||||
!inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true
|
!inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true
|
||||||
if (physicalShortcuts.onKey(
|
if (physicalShortcuts.onKey(
|
||||||
event,
|
event,
|
||||||
enabled = resumed && SessionState.running && !SessionState.suspended &&
|
enabled = resumed && SessionState.running && !SessionState.suspended &&
|
||||||
!(drawerOpen && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) &&
|
!(menuOwnsController && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) &&
|
||||||
!(drawerOpen && PhysicalShortcuts.isDrawerNavigationKey(event)) &&
|
!(menuOwnsController && PhysicalShortcuts.isDrawerNavigationKey(event)) &&
|
||||||
(event.deviceId to event.keyCode) !in resumeKeysDown &&
|
(event.deviceId to event.keyCode) !in resumeKeysDown &&
|
||||||
!(::loading.isInitialized && (loading.visible || loading.ended)) &&
|
!(::loading.isInitialized && (loading.visible || loading.ended)) &&
|
||||||
!pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen,
|
!pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen,
|
||||||
@@ -3545,12 +3629,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
) { action ->
|
) { action ->
|
||||||
pendingBackAction?.let(uiHandler::removeCallbacks)
|
pendingBackAction?.let(uiHandler::removeCallbacks)
|
||||||
pendingBackAction = null
|
pendingBackAction = null
|
||||||
drawerControllerActive = true
|
if (!dockedMenuIdle) drawerControllerActive = true
|
||||||
Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}")
|
Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}")
|
||||||
when (action) {
|
when (action) {
|
||||||
PhysicalShortcuts.Action.STEAM -> sendSteamGuide()
|
PhysicalShortcuts.Action.STEAM -> sendSteamGuide()
|
||||||
PhysicalShortcuts.Action.QAM -> triggerSteamQam()
|
PhysicalShortcuts.Action.QAM -> triggerSteamQam()
|
||||||
PhysicalShortcuts.Action.DROIDDECK -> drawerOpen = !drawerOpen
|
PhysicalShortcuts.Action.DROIDDECK -> if (!dockedTouchOnly) drawerOpen = !drawerOpen
|
||||||
}
|
}
|
||||||
}) return true
|
}) return true
|
||||||
}
|
}
|
||||||
@@ -3576,7 +3660,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (mouseBackHandled) return true
|
if (mouseBackHandled) return true
|
||||||
val backToQam = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
val backToQam = !pipUi && !appTextFocus && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
|
||||||
!inputSettingsOpen && !gestureSettingsOpen &&
|
!inputSettingsOpen && !gestureSettingsOpen &&
|
||||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
|
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
|
||||||
!SessionState.suspended && padBridge?.canHoldQam() == true
|
!SessionState.suspended && padBridge?.canHoldQam() == true
|
||||||
@@ -3589,12 +3673,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
|
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
|
||||||
if (pad !== event) return dispatchKeyEvent(pad)
|
if (pad !== event) return dispatchKeyEvent(pad)
|
||||||
val fromController = PadBridge.isControllerKeyEvent(event)
|
val fromController = PadBridge.isControllerKeyEvent(event)
|
||||||
if (fromController && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
|
if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
|
||||||
padBridge?.setInputEnabled(false)
|
padBridge?.setInputEnabled(false)
|
||||||
padBridge?.onKeyEvent(event)
|
padBridge?.onKeyEvent(event)
|
||||||
}
|
}
|
||||||
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
|
if (fromController && event.action == KeyEvent.ACTION_DOWN && !dockedMenuIdle) {
|
||||||
if (drawerOpen && !drawerControllerActive) focusDrawer()
|
if (menuOwnsController && !drawerControllerActive) focusDrawer()
|
||||||
drawerControllerActive = true
|
drawerControllerActive = true
|
||||||
}
|
}
|
||||||
if (fromController && event.keyCode == KeyEvent.KEYCODE_BUTTON_B && ::loading.isInitialized && loading.visible && !loading.ended && !drawerOpen) {
|
if (fromController && event.keyCode == KeyEvent.KEYCODE_BUTTON_B && ::loading.isInitialized && loading.visible && !loading.ended && !drawerOpen) {
|
||||||
@@ -3613,7 +3697,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
val drawerShortcutKey = event.deviceId to event.keyCode
|
val drawerShortcutKey = event.deviceId to event.keyCode
|
||||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) &&
|
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) &&
|
||||||
((drawerOpen && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) {
|
((menuOwnsController && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) {
|
||||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||||
drawerShortcutKeysDown.add(drawerShortcutKey)
|
drawerShortcutKeysDown.add(drawerShortcutKey)
|
||||||
if (event.repeatCount == 0) {
|
if (event.repeatCount == 0) {
|
||||||
@@ -3625,11 +3709,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if (drawerOpen) {
|
if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) {
|
||||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||||
drawerPage = sessionDrawerPages(glasses.present)
|
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
|
||||||
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
val pages = sessionDrawerPages(glasses.present)
|
||||||
|
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||||
releaseDrawerDirection()
|
releaseDrawerDirection()
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
@@ -3695,11 +3780,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||||
if (pipUi) return true
|
if (pipUi) return true
|
||||||
notePress(event)
|
notePress(event)
|
||||||
if (PadBridge.isControllerMotionEvent(event) && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
|
if (PadBridge.isControllerMotionEvent(event) && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
|
||||||
padBridge?.setInputEnabled(false)
|
padBridge?.setInputEnabled(false)
|
||||||
padBridge?.onMotionEvent(event)
|
padBridge?.onMotionEvent(event)
|
||||||
}
|
}
|
||||||
if (drawerOpen && PadBridge.isControllerMotionEvent(event)) {
|
if (menuOwnsController && PadBridge.isControllerMotionEvent(event)) {
|
||||||
if (!drawerControllerActive) focusDrawer()
|
if (!drawerControllerActive) focusDrawer()
|
||||||
drawerControllerActive = true
|
drawerControllerActive = true
|
||||||
if (event.actionMasked == MotionEvent.ACTION_MOVE &&
|
if (event.actionMasked == MotionEvent.ACTION_MOVE &&
|
||||||
@@ -3876,6 +3961,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun closeDockedMenu() {
|
private fun closeDockedMenu() {
|
||||||
|
SessionState.bottomMenu = false
|
||||||
drawerDocked = false
|
drawerDocked = false
|
||||||
val presentation = secondScreenPresentation ?: return
|
val presentation = secondScreenPresentation ?: return
|
||||||
presentation.showMenu(false)
|
presentation.showMenu(false)
|
||||||
@@ -4301,7 +4387,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
?: if (SessionState.gameOnBottom) bottomGameDisplay()?.displayId else null
|
?: if (SessionState.gameOnBottom) bottomGameDisplay()?.displayId else null
|
||||||
SessionState.secondScreenAutoOpened = true
|
SessionState.secondScreenAutoOpened = true
|
||||||
if (gameDisplay != null && gameDisplay != target.displayId && secondScreenDisplays.any { it.id == gameDisplay }) {
|
if (gameDisplay != null && gameDisplay != target.displayId && secondScreenDisplays.any { it.id == gameDisplay }) {
|
||||||
panelMode(openingPanel())
|
panelMode(openingSurface())
|
||||||
} else {
|
} else {
|
||||||
val selectionChanged = selectedSecondScreenDisplay != target.displayId
|
val selectionChanged = selectedSecondScreenDisplay != target.displayId
|
||||||
selectedSecondScreenDisplay = target.displayId
|
selectedSecondScreenDisplay = target.displayId
|
||||||
@@ -4320,14 +4406,69 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun openingPanel() = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this, desktopSession), SessionState.deckPad,
|
private fun openingPanel() = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this, desktopSession), SessionState.deckPad,
|
||||||
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available(), desktopSession)
|
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available())
|
||||||
|
|
||||||
|
private fun openingSurface() = openingPanel().takeIf { it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD
|
||||||
|
|
||||||
|
private fun menuShownOnBottom() = drawerDocked && (drawerOpen || drawerPinned)
|
||||||
|
|
||||||
|
private fun pinDockedMenu() {
|
||||||
|
if (!dockDrawer()) return
|
||||||
|
drawerLayerOpen = false
|
||||||
|
if (!openDockedMenu()) return
|
||||||
|
drawerDocked = true
|
||||||
|
drawerOpenState = false
|
||||||
|
drawerPinned = true
|
||||||
|
updateKeyboardRoute()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showMenuMode() {
|
||||||
|
dualControlsProvisional = false
|
||||||
|
selectSecondScreenMode(secondScreenMode.takeIf { it != SecondScreenMode.NONE } ?: SecondScreenMode.KEYBOARD_TRACKPAD)
|
||||||
|
if (secondScreenMode != SecondScreenMode.NONE) pinDockedMenu()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pickMenuMode() {
|
||||||
|
typingReturnMode = null
|
||||||
|
automaticPanel = false
|
||||||
|
SessionPrefs.setSecondScreenPanel(this, desktopSession, SecondScreenMode.MENU.id)
|
||||||
|
drawerOpen = true
|
||||||
|
}
|
||||||
|
|
||||||
private fun settleDualScreenControls() {
|
private fun settleDualScreenControls() {
|
||||||
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
|
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
|
||||||
dualControlsProvisional = false
|
dualControlsProvisional = false
|
||||||
if (secondScreenMode == SecondScreenMode.NONE) return
|
if (secondScreenMode == SecondScreenMode.NONE) return
|
||||||
val wanted = openingPanel()
|
val wanted = openingPanel()
|
||||||
if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
|
if (wanted == SecondScreenMode.MENU) {
|
||||||
|
if (!menuShownOnBottom()) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
|
||||||
|
} else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun chooseDualScreenSessionMode(mode: String) {
|
||||||
|
if (mode !in com.droiddeck.launcher.input.DualScreen.modes || mode == dualScreenSessionMode) return
|
||||||
|
SessionPrefs.setDualScreenSessionMode(this, mode)
|
||||||
|
dualScreenSessionMode = mode
|
||||||
|
SessionState.secondScreenAutoOpened = false
|
||||||
|
val menuOnBottom = drawerDocked
|
||||||
|
val menuOnTop = drawerOpenState && !drawerDocked
|
||||||
|
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED) {
|
||||||
|
putGameOnBottom(true)
|
||||||
|
} else if (gameOnBottom && mode != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||||
|
putGameOnBottom(false)
|
||||||
|
}
|
||||||
|
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||||
|
if (gameOnBottom) putGameOnBottom(false)
|
||||||
|
if (secondScreenMode != SecondScreenMode.NONE || menuOnBottom) closeSecondScreen(reset = true)
|
||||||
|
if (menuOnBottom) drawerOpen = true
|
||||||
|
} else if (menuOnTop) {
|
||||||
|
// The menu moves to the second screen as the menu itself, not as one of the control panels.
|
||||||
|
SessionState.secondScreenAutoOpened = true
|
||||||
|
refreshSecondScreenDisplays()
|
||||||
|
pinDockedMenu()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
refreshSecondScreenDisplays()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun selectSecondScreenDisplay(displayId: Int) {
|
private fun selectSecondScreenDisplay(displayId: Int) {
|
||||||
@@ -4348,6 +4489,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
closeSecondScreen(reset = true)
|
closeSecondScreen(reset = true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (mode == SecondScreenMode.MENU) {
|
||||||
|
showMenuMode()
|
||||||
|
return
|
||||||
|
}
|
||||||
if (secondScreenDisplays.isEmpty()) {
|
if (secondScreenDisplays.isEmpty()) {
|
||||||
panelMode(SecondScreenMode.NONE)
|
panelMode(SecondScreenMode.NONE)
|
||||||
return
|
return
|
||||||
@@ -4364,7 +4509,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
|
|
||||||
private fun showSecondScreen(requested: SecondScreenMode) {
|
private fun showSecondScreen(requested: SecondScreenMode) {
|
||||||
if (pipUi || !started) return
|
if (pipUi || !started) return
|
||||||
val mode = if (requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) openingPanel() else requested
|
val mode = when {
|
||||||
|
requested == SecondScreenMode.MENU ->
|
||||||
|
secondScreenMode.takeIf { it != SecondScreenMode.NONE && it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD
|
||||||
|
requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> openingSurface()
|
||||||
|
else -> requested
|
||||||
|
}
|
||||||
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
|
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
|
||||||
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
|
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
|
||||||
closeSecondScreen(reset = false)
|
closeSecondScreen(reset = false)
|
||||||
@@ -4401,6 +4551,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private fun pickSecondScreenMode(mode: SecondScreenMode) {
|
private fun pickSecondScreenMode(mode: SecondScreenMode) {
|
||||||
typingReturnMode = null
|
typingReturnMode = null
|
||||||
automaticPanel = false
|
automaticPanel = false
|
||||||
|
SessionState.bottomMenu = false
|
||||||
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
|
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
|
||||||
selectSecondScreenMode(mode)
|
selectSecondScreenMode(mode)
|
||||||
}
|
}
|
||||||
@@ -4408,7 +4559,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private fun bottomScreenPicker(mode: SecondScreenMode) = com.droiddeck.launcher.ui.ScreenPicker(
|
private fun bottomScreenPicker(mode: SecondScreenMode) = com.droiddeck.launcher.ui.ScreenPicker(
|
||||||
com.droiddeck.launcher.ui.secondScreenModes(false, SessionState.deckPad, bottomPages().isNotEmpty(),
|
com.droiddeck.launcher.ui.secondScreenModes(false, SessionState.deckPad, bottomPages().isNotEmpty(),
|
||||||
com.droiddeck.launcher.session.BottomDesktop.available()),
|
com.droiddeck.launcher.session.BottomDesktop.available()),
|
||||||
mode, ::pickSecondScreenMode, onMenu = { drawerOpen = true },
|
mode, ::pickSecondScreenMode, onMenu = ::pickMenuMode,
|
||||||
)
|
)
|
||||||
|
|
||||||
private fun secondScreenPresentation(target: Display) = SecondScreenPresentation(
|
private fun secondScreenPresentation(target: Display) = SecondScreenPresentation(
|
||||||
@@ -4620,7 +4771,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let {
|
val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let {
|
||||||
it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()
|
it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()
|
||||||
} ?: 0
|
} ?: 0
|
||||||
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow)
|
val outputAspect = if (!wanted || SessionState.followScreen) 0f
|
||||||
|
else outputSize().let { it.first.toFloat() / it.second.coerceAtLeast(1) }
|
||||||
|
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, outputAspect)
|
||||||
else FrameLayout.LayoutParams.MATCH_PARENT
|
else FrameLayout.LayoutParams.MATCH_PARENT
|
||||||
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
|
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
|
||||||
if (params.height != gameHeight) {
|
if (params.height != gameHeight) {
|
||||||
@@ -4629,7 +4782,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
else "unfolded controls: game full screen")
|
else "unfolded controls: game full screen")
|
||||||
}
|
}
|
||||||
val portrait = !com.droiddeck.launcher.session.SessionDisplay.foldable(this)
|
val portrait = !com.droiddeck.launcher.session.SessionDisplay.foldable(this)
|
||||||
val dock = if (SessionState.deckPad) com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD])
|
val kit = com.droiddeck.launcher.input.PadKit.forOverlay(this, primaryInputLayout)
|
||||||
|
val dock = if (SessionState.deckPad && kit?.steam != false)
|
||||||
|
com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD])
|
||||||
else com.droiddeck.launcher.input.OnScreenLayout.Dock(portrait, false)
|
else com.droiddeck.launcher.input.OnScreenLayout.Dock(portrait, false)
|
||||||
var panel = unfoldedPanel
|
var panel = unfoldedPanel
|
||||||
if (panel != null && (!wanted || panel.dock != dock)) {
|
if (panel != null && (!wanted || panel.dock != dock)) {
|
||||||
@@ -4830,6 +4985,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun dropDockedDrawer() {
|
private fun dropDockedDrawer() {
|
||||||
|
if (drawerDocked && (drawerOpenState || drawerPinned)) SessionState.bottomMenu = true
|
||||||
drawerPinned = false
|
drawerPinned = false
|
||||||
if (!drawerDocked) return
|
if (!drawerDocked) return
|
||||||
drawerDocked = false
|
drawerDocked = false
|
||||||
@@ -4848,6 +5004,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
if (reset) {
|
if (reset) {
|
||||||
panelMode(SecondScreenMode.NONE)
|
panelMode(SecondScreenMode.NONE)
|
||||||
automaticPanel = false
|
automaticPanel = false
|
||||||
|
SessionState.bottomMenu = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5039,10 +5196,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private var sessionTouchDown = false
|
private var sessionTouchDown = false
|
||||||
private var screenTapsClick = true
|
private var screenTapsClick = true
|
||||||
|
|
||||||
private fun onScreenMouseButtonShown(): Boolean = listOfNotNull(
|
private fun onScreenLeftMouseButtonShown(): Boolean = listOfNotNull(
|
||||||
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
|
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
|
||||||
secondScreenPresentation?.controlsView, swappedInputSurface,
|
secondScreenPresentation?.controlsView, swappedInputSurface,
|
||||||
).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
|
).any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
|
||||||
|
|
||||||
override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) }
|
override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) }
|
||||||
|
|
||||||
@@ -5078,7 +5235,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
val snapshot = fingerTouchSnapshot(uiBlocking)
|
val snapshot = fingerTouchSnapshot(uiBlocking)
|
||||||
val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot)
|
val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot)
|
||||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
||||||
screenTapsClick = !onScreenMouseButtonShown()
|
screenTapsClick = !onScreenLeftMouseButtonShown()
|
||||||
if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick
|
if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick
|
||||||
if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick
|
if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick
|
||||||
}
|
}
|
||||||
@@ -5400,8 +5557,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private fun onlyPcKeyboardOpen(): Boolean =
|
private fun onlyPcKeyboardOpen(): Boolean =
|
||||||
pcKeyboardOpen && !drawerOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !glassesOutputActive && !touchEditorOpen && !wowChatOnTop
|
pcKeyboardOpen && !drawerOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !glassesOutputActive && !touchEditorOpen && !wowChatOnTop
|
||||||
|
|
||||||
private fun appUiOwnsPointer(): Boolean =
|
private fun otherUiOwnsPointer(): Boolean =
|
||||||
drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop
|
pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop
|
||||||
|
|
||||||
|
private fun appUiOwnsPointer(): Boolean = drawerOpen || otherUiOwnsPointer()
|
||||||
|
|
||||||
|
/** A touch-only docked menu leaves the game cursor alone, so controller pointer moves stay visible. */
|
||||||
|
private fun cursorHiddenByUi(): Boolean = menuOwnsController || otherUiOwnsPointer()
|
||||||
|
|
||||||
private fun applyPlatformPointer(shown: Boolean) {
|
private fun applyPlatformPointer(shown: Boolean) {
|
||||||
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
|
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
|
||||||
@@ -5510,6 +5672,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
.takeIf { it.isFile }
|
.takeIf { it.isFile }
|
||||||
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
|
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
|
||||||
?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM)
|
?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM)
|
||||||
|
unfoldedColumn?.let { column ->
|
||||||
|
val shown = if (inputSettingsOpen) View.INVISIBLE else View.VISIBLE
|
||||||
|
if (column.visibility != shown) { unfoldedPanel?.releaseAll(); unfoldedDeckSurface?.releaseInputs(); column.visibility = shown }
|
||||||
|
}
|
||||||
val controls = onScreenControls ?: return
|
val controls = onScreenControls ?: return
|
||||||
fun showPinned() {
|
fun showPinned() {
|
||||||
controls.setPinnedOnly(true)
|
controls.setPinnedOnly(true)
|
||||||
@@ -5675,31 +5841,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
heldKeys.set(owner, code, down)
|
heldKeys.set(owner, code, down)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun capturePausedFrame(manual: Boolean = false) {
|
private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) {
|
||||||
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) return
|
fun skipped(reason: String) {
|
||||||
|
if (manual) SessionEvents.record("pause.frame_skipped", mapOf("reason" to reason))
|
||||||
|
onDone()
|
||||||
|
}
|
||||||
|
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) {
|
||||||
|
return skipped("state running=${SessionState.running} pip=$pipUi glasses=$glassesOutputActive bottom=$bottomOutputActive")
|
||||||
|
}
|
||||||
if (SessionState.suspended && pausedFrame != null) return
|
if (SessionState.suspended && pausedFrame != null) return
|
||||||
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return
|
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return skipped("policy")
|
||||||
if (surfaceView.holder.surface?.isValid != true) return
|
if (surfaceView.holder.surface?.isValid != true) return skipped("surface invalid")
|
||||||
val width = surfaceView.width
|
val width = surfaceView.width
|
||||||
val height = surfaceView.height
|
val height = surfaceView.height
|
||||||
if (width <= 0 || height <= 0) return
|
if (width <= 0 || height <= 0) return skipped("size ${width}x$height")
|
||||||
val scale = minOf(1f, PAUSED_FRAME_MAX_EDGE / maxOf(width, height).toFloat())
|
val scale = minOf(1f, PAUSED_FRAME_MAX_EDGE / maxOf(width, height).toFloat())
|
||||||
val bitmap = try {
|
val bitmap = try {
|
||||||
android.graphics.Bitmap.createBitmap(
|
android.graphics.Bitmap.createBitmap(
|
||||||
maxOf(1, (width * scale).toInt()), maxOf(1, (height * scale).toInt()), android.graphics.Bitmap.Config.ARGB_8888,
|
maxOf(1, (width * scale).toInt()), maxOf(1, (height * scale).toInt()), android.graphics.Bitmap.Config.ARGB_8888,
|
||||||
)
|
)
|
||||||
} catch (_: OutOfMemoryError) {
|
} catch (_: OutOfMemoryError) {
|
||||||
return
|
return skipped("oom")
|
||||||
}
|
}
|
||||||
val surfaceAt = IntArray(2).also { surfaceView.getLocationInWindow(it) }
|
val surfaceAt = IntArray(2).also { surfaceView.getLocationInWindow(it) }
|
||||||
val overlayAt = IntArray(2).also { sessionOverlay.getLocationInWindow(it) }
|
val overlayAt = IntArray(2).also { sessionOverlay.getLocationInWindow(it) }
|
||||||
val left = surfaceAt[0] - overlayAt[0]
|
val left = surfaceAt[0] - overlayAt[0]
|
||||||
val top = surfaceAt[1] - overlayAt[1]
|
val top = surfaceAt[1] - overlayAt[1]
|
||||||
val bounds = android.graphics.Rect(left, top, left + width, top + height)
|
val bounds = android.graphics.Rect(left, top, left + width, top + height)
|
||||||
|
val requestedAt = SystemClock.elapsedRealtime()
|
||||||
withPictureFrame { done ->
|
withPictureFrame { done ->
|
||||||
try {
|
try {
|
||||||
android.view.PixelCopy.request(surfaceView, bitmap, { result ->
|
android.view.PixelCopy.request(surfaceView, bitmap, { result ->
|
||||||
done()
|
done()
|
||||||
|
onDone()
|
||||||
|
if (manual) SessionEvents.record("pause.frame_copy", mapOf(
|
||||||
|
"result" to result, "ms" to SystemClock.elapsedRealtime() - requestedAt,
|
||||||
|
"zeroCopy" to SessionPrefs.zeroCopy(this, SessionState.mode), "size" to "${width}x$height",
|
||||||
|
"lit" to (result == android.view.PixelCopy.SUCCESS && bitmapHasPicture(bitmap)),
|
||||||
|
))
|
||||||
if (result == android.view.PixelCopy.SUCCESS && !isDestroyed) {
|
if (result == android.view.PixelCopy.SUCCESS && !isDestroyed) {
|
||||||
pausedFrame = com.droiddeck.launcher.ui.PausedFrame(bitmap.asImageBitmap(), bounds)
|
pausedFrame = com.droiddeck.launcher.ui.PausedFrame(bitmap.asImageBitmap(), bounds)
|
||||||
pausedFrameWanted = false
|
pausedFrameWanted = false
|
||||||
@@ -5710,6 +5889,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
} catch (_: IllegalArgumentException) {
|
} catch (_: IllegalArgumentException) {
|
||||||
done()
|
done()
|
||||||
bitmap.recycle()
|
bitmap.recycle()
|
||||||
|
skipped("copy rejected")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5717,12 +5897,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private fun pauseNow() {
|
private fun pauseNow() {
|
||||||
if (!SessionState.running || SessionState.suspended) return
|
if (!SessionState.running || SessionState.suspended) return
|
||||||
pauseAnimated = true
|
pauseAnimated = true
|
||||||
drawerOpen = false
|
if (!dockedTouchOnly) drawerOpen = false
|
||||||
pausedFrame = null
|
pausedFrame = null
|
||||||
capturePausedFrame(manual = true)
|
if (zeroCopyActive()) {
|
||||||
|
WaylandCompositor.nativeSetZeroCopy(false)
|
||||||
|
val restore = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||||
|
val back = { if (restore.compareAndSet(false, true)) WaylandCompositor.nativeSetZeroCopy(true) }
|
||||||
|
uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS)
|
||||||
|
uiHandler.postDelayed({ back() }, ZERO_COPY_RESTORE_MS)
|
||||||
|
} else {
|
||||||
|
capturePausedFrame(manual = true)
|
||||||
|
}
|
||||||
SessionService.pause(this)
|
SessionService.pause(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun zeroCopyActive(): Boolean =
|
||||||
|
CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy(this, SessionState.mode)
|
||||||
|
|
||||||
|
private fun bitmapHasPicture(bitmap: android.graphics.Bitmap): Boolean {
|
||||||
|
val w = bitmap.width
|
||||||
|
val h = bitmap.height
|
||||||
|
if (w <= 0 || h <= 0) return false
|
||||||
|
var lit = 0
|
||||||
|
for (i in 0 until 64) {
|
||||||
|
val c = bitmap.getPixel((w * (i % 8 + 1)) / 9, (h * (i / 8 + 1)) / 9)
|
||||||
|
if (android.graphics.Color.red(c) + android.graphics.Color.green(c) + android.graphics.Color.blue(c) > 24) lit++
|
||||||
|
}
|
||||||
|
return lit >= 3
|
||||||
|
}
|
||||||
|
|
||||||
private fun requestPausedFrame() {
|
private fun requestPausedFrame() {
|
||||||
if (pausedFrame != null) return
|
if (pausedFrame != null) return
|
||||||
pausedFrameWanted = true
|
pausedFrameWanted = true
|
||||||
@@ -5826,8 +6029,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
reconcileDock(shownOnDisplayId)
|
reconcileDock(shownOnDisplayId)
|
||||||
settleDualScreenControls()
|
settleDualScreenControls()
|
||||||
refreshSecondScreenDisplays()
|
refreshSecondScreenDisplays()
|
||||||
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
if (secondScreenMode != SecondScreenMode.NONE) {
|
||||||
else openDualScreenControls()
|
if (secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||||
|
if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu()
|
||||||
|
SessionState.bottomMenu = false
|
||||||
|
} else {
|
||||||
|
if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu()
|
||||||
|
SessionState.bottomMenu = false
|
||||||
|
if (!menuShownOnBottom()) openDualScreenControls()
|
||||||
|
}
|
||||||
startedScreens++
|
startedScreens++
|
||||||
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
|
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
|
||||||
Glasses.rescan()
|
Glasses.rescan()
|
||||||
@@ -5859,8 +6069,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
Log.w(TAG, "ignoring agent start while session phase is ${SessionState.phase}")
|
Log.w(TAG, "ignoring agent start while session phase is ${SessionState.phase}")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setIntent(intent)
|
relaunch(android.content.Intent(intent).setClass(this, SessionActivity::class.java))
|
||||||
recreate()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
|
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
|
||||||
@@ -5978,7 +6187,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
heldKeys.clear()
|
heldKeys.clear()
|
||||||
heldButtons.clear()
|
heldButtons.clear()
|
||||||
if (!screenOff) {
|
if (!screenOff) {
|
||||||
|
val menuUp = menuShownOnBottom()
|
||||||
drawerOpen = false
|
drawerOpen = false
|
||||||
|
if (menuUp) SessionState.bottomMenu = true
|
||||||
pcKeyboardOpen = false
|
pcKeyboardOpen = false
|
||||||
achievementsOpen = false
|
achievementsOpen = false
|
||||||
}
|
}
|
||||||
@@ -6750,6 +6961,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private const val LEAVE_TIMEOUT_MS = 1_500L
|
private const val LEAVE_TIMEOUT_MS = 1_500L
|
||||||
private const val TEXT_FIELD_TAP_MS = 1_000L
|
private const val TEXT_FIELD_TAP_MS = 1_000L
|
||||||
private const val PAUSED_FRAME_MAX_EDGE = 1920f
|
private const val PAUSED_FRAME_MAX_EDGE = 1920f
|
||||||
|
private const val ZERO_COPY_SETTLE_MS = 150L
|
||||||
|
private const val ZERO_COPY_RESTORE_MS = 1200L
|
||||||
private const val BFI_PICTURE_SETTLE_MS = 50L
|
private const val BFI_PICTURE_SETTLE_MS = 50L
|
||||||
private const val PAUSED_FRAME_REDRAW_MS = 150L
|
private const val PAUSED_FRAME_REDRAW_MS = 150L
|
||||||
private const val BOTTOM_RECOVERY_MS = 1_000L
|
private const val BOTTOM_RECOVERY_MS = 1_000L
|
||||||
|
|||||||
@@ -143,9 +143,9 @@ object AgentSetup {
|
|||||||
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
|
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
|
||||||
"apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " +
|
"apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " +
|
||||||
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " +
|
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " +
|
||||||
"for i in 1 2 3; do apt update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
|
"for i in 1 2 3; do apt -o APT::Update::Error-Mode=any update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
|
||||||
"apt -f install -y --fix-missing; " +
|
"apt -f install -y --fix-missing; " +
|
||||||
"apt install -y --fix-missing --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
|
"apt install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
|
||||||
}
|
}
|
||||||
Step.SIGN_IN -> harness.signIn
|
Step.SIGN_IN -> harness.signIn
|
||||||
Step.GITHUB -> listOf("dd-gh-login")
|
Step.GITHUB -> listOf("dd-gh-login")
|
||||||
|
|||||||
@@ -53,6 +53,13 @@ object AppUiPrefs {
|
|||||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply()
|
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun pageSwipe(context: Context): Boolean =
|
||||||
|
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("page-swipe", true)
|
||||||
|
|
||||||
|
fun setPageSwipe(context: Context, on: Boolean) {
|
||||||
|
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("page-swipe", on).apply()
|
||||||
|
}
|
||||||
|
|
||||||
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
||||||
|
|
||||||
fun scale(context: Context): Int = normalizeScale(
|
fun scale(context: Context): Int = normalizeScale(
|
||||||
|
|||||||
@@ -207,9 +207,11 @@ object DeviceReport {
|
|||||||
k("refresh_rate_mode", runCatching { Settings.Secure.getString(context.contentResolver, "refresh_rate_mode") }.getOrNull() ?: "not set")
|
k("refresh_rate_mode", runCatching { Settings.Secure.getString(context.contentResolver, "refresh_rate_mode") }.getOrNull() ?: "not set")
|
||||||
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context)
|
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context)
|
||||||
for ((label, mode) in listOf("Resolution (Steam)" to SessionService.MODE_STEAM, "Resolution (Desktop)" to SessionService.MODE_DESKTOP)) {
|
for ((label, mode) in listOf("Resolution (Steam)" to SessionService.MODE_STEAM, "Resolution (Desktop)" to SessionService.MODE_DESKTOP)) {
|
||||||
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize)
|
for ((suffix, portrait) in listOf("landscape" to false, "portrait" to true)) {
|
||||||
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice)
|
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize, portrait)
|
||||||
k(label, "$choice (${size.first}x${size.second})")
|
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice, portrait)
|
||||||
|
k("$label $suffix", "$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"))
|
||||||
|
|
||||||
@@ -291,6 +293,7 @@ object DeviceReport {
|
|||||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||||
k("Avoid notch", SessionPrefs.avoidNotch(context))
|
k("Avoid notch", SessionPrefs.avoidNotch(context))
|
||||||
k("Return to launcher after a game", SessionPrefs.returnAfterGame(context))
|
k("Return to launcher after a game", SessionPrefs.returnAfterGame(context))
|
||||||
|
k("Valve Proton only when needed", SessionPrefs.valveProtonOnDemand(context))
|
||||||
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))
|
||||||
|
|||||||
@@ -28,7 +28,9 @@ object DeviceSupport {
|
|||||||
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
|
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists()
|
fun bridgeUsable(): Boolean = bridgeUsable(adreno(), SystemVulkanDriver.isAvailable())
|
||||||
|
|
||||||
|
internal fun bridgeUsable(adreno: Boolean, systemDriverReady: Boolean): Boolean = !adreno && !systemDriverReady
|
||||||
|
|
||||||
fun openDriverActive(context: Context): Boolean {
|
fun openDriverActive(context: Context): Boolean {
|
||||||
if (adreno()) return false
|
if (adreno()) return false
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ object SteamIntegration {
|
|||||||
const val EXTRA_FEATURE = "integration_feature"
|
const val EXTRA_FEATURE = "integration_feature"
|
||||||
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
|
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
|
||||||
private const val SHORTCUTS_ASSET = "shortcuts.apk"
|
private const val SHORTCUTS_ASSET = "shortcuts.apk"
|
||||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH }
|
||||||
|
|
||||||
data class State(
|
data class State(
|
||||||
val wifi: Boolean = false,
|
val wifi: Boolean = false,
|
||||||
@@ -28,6 +28,7 @@ object SteamIntegration {
|
|||||||
val shortcuts: Boolean = false,
|
val shortcuts: Boolean = false,
|
||||||
val shortcutsRestricted: Boolean = false,
|
val shortcutsRestricted: Boolean = false,
|
||||||
val shortcutsTried: Boolean = false,
|
val shortcutsTried: Boolean = false,
|
||||||
|
val bluetooth: Boolean = false,
|
||||||
val suggested: Boolean = true,
|
val suggested: Boolean = true,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -39,9 +40,16 @@ object SteamIntegration {
|
|||||||
home = HomeApp.isDefault(context),
|
home = HomeApp.isDefault(context),
|
||||||
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
|
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
|
||||||
shortcutsRestricted = restrictedSettings(context),
|
shortcutsRestricted = restrictedSettings(context),
|
||||||
|
bluetooth = bluetoothAllowed(context),
|
||||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
fun bluetoothAllowed(context: Context): Boolean =
|
||||||
|
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S ||
|
||||||
|
context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
|
||||||
|
|
||||||
|
fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
|
||||||
|
|
||||||
private fun restrictedSettings(context: Context): Boolean {
|
private fun restrictedSettings(context: Context): Boolean {
|
||||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
||||||
val mode = runCatching {
|
val mode = runCatching {
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ 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
|
||||||
|
@Volatile private var limitEnabled = false
|
||||||
|
@Volatile private var session = 0
|
||||||
private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) }
|
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
|
||||||
@@ -50,12 +52,15 @@ class WirelessAdbPairingService : Service() {
|
|||||||
onCode(code)
|
onCode(code)
|
||||||
}
|
}
|
||||||
ACTION_CANCEL -> finish(Stage.Idle)
|
ACTION_CANCEL -> finish(Stage.Idle)
|
||||||
else -> begin()
|
else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true)
|
||||||
}
|
}
|
||||||
return START_NOT_STICKY
|
return START_NOT_STICKY
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun begin() {
|
private fun begin(enableLimit: Boolean) {
|
||||||
|
if (working) return
|
||||||
|
session++
|
||||||
|
limitEnabled = enableLimit
|
||||||
pairingHost = null
|
pairingHost = null
|
||||||
pairingPort = null
|
pairingPort = null
|
||||||
working = false
|
working = false
|
||||||
@@ -68,12 +73,13 @@ class WirelessAdbPairingService : Service() {
|
|||||||
|
|
||||||
private fun startDiscovery() {
|
private fun startDiscovery() {
|
||||||
stopDiscovery()
|
stopDiscovery()
|
||||||
|
val owner = session
|
||||||
val manager = getSystemService(Context.NSD_SERVICE) as NsdManager
|
val manager = getSystemService(Context.NSD_SERVICE) as NsdManager
|
||||||
val listener = object : NsdManager.DiscoveryListener {
|
val listener = object : NsdManager.DiscoveryListener {
|
||||||
override fun onDiscoveryStarted(serviceType: String) = Unit
|
override fun onDiscoveryStarted(serviceType: String) = Unit
|
||||||
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
|
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
|
||||||
if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return
|
if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return
|
||||||
runCatching { manager.resolveService(serviceInfo, resolveListener()) }
|
runCatching { manager.resolveService(serviceInfo, resolveListener(owner)) }
|
||||||
}
|
}
|
||||||
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
|
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
|
||||||
override fun onDiscoveryStopped(serviceType: String) = Unit
|
override fun onDiscoveryStopped(serviceType: String) = Unit
|
||||||
@@ -87,18 +93,20 @@ class WirelessAdbPairingService : Service() {
|
|||||||
.onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) }
|
.onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun resolveListener() = object : NsdManager.ResolveListener {
|
private fun resolveListener(owner: Int): NsdManager.ResolveListener {
|
||||||
|
return object : NsdManager.ResolveListener {
|
||||||
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit
|
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit
|
||||||
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
|
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
|
||||||
val address = serviceInfo.host ?: return
|
val address = serviceInfo.host ?: return
|
||||||
if (!WirelessAdbFix.isLocalAddress(address)) return
|
if (!WirelessAdbFix.isLocalAddress(address)) return
|
||||||
main.post {
|
main.post {
|
||||||
if (working || current.value == Stage.Done) return@post
|
if (owner != session || working || current.value == Stage.Done) return@post
|
||||||
pairingHost = address.hostAddress
|
pairingHost = address.hostAddress
|
||||||
pairingPort = serviceInfo.port
|
pairingPort = serviceInfo.port
|
||||||
if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded())
|
if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onCode(code: String) {
|
private fun onCode(code: String) {
|
||||||
@@ -114,29 +122,34 @@ class WirelessAdbPairingService : Service() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
working = true
|
working = true
|
||||||
|
val owner = session
|
||||||
|
val enable = limitEnabled
|
||||||
show(Stage.Working(getString(R.string.adbpair_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
|
||||||
|
if (owner != session) return@post
|
||||||
pairingPort = null
|
pairingPort = null
|
||||||
show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected)))
|
show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected)))
|
||||||
}
|
}
|
||||||
return@Thread
|
return@Thread
|
||||||
}
|
}
|
||||||
main.post {
|
main.post {
|
||||||
|
if (owner != session) return@post
|
||||||
stopDiscovery()
|
stopDiscovery()
|
||||||
show(Stage.Working(getString(R.string.adbpair_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(getString(R.string.adbpair_port_not_found))
|
?: error(getString(R.string.adbpair_port_not_found))
|
||||||
main.post { show(Stage.Working(getString(R.string.adbpair_applying))) }
|
main.post { if (owner == session) show(Stage.Working(getString(R.string.adbpair_applying))) }
|
||||||
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
|
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, enable)
|
||||||
}
|
}
|
||||||
main.post {
|
main.post {
|
||||||
working = false
|
working = false
|
||||||
|
if (owner != session) return@post
|
||||||
finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_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()
|
||||||
@@ -148,6 +161,7 @@ class WirelessAdbPairingService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun finish(stage: Stage) {
|
private fun finish(stage: Stage) {
|
||||||
|
session++
|
||||||
main.removeCallbacks(timeout)
|
main.removeCallbacks(timeout)
|
||||||
stopDiscovery()
|
stopDiscovery()
|
||||||
publish(stage)
|
publish(stage)
|
||||||
@@ -248,6 +262,7 @@ class WirelessAdbPairingService : Service() {
|
|||||||
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
||||||
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
|
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
|
||||||
private const val KEY_CODE = "code"
|
private const val KEY_CODE = "code"
|
||||||
|
private const val EXTRA_ENABLE_LIMIT = "enable_limit"
|
||||||
private const val TIMEOUT_MS = 5 * 60_000L
|
private const val TIMEOUT_MS = 5 * 60_000L
|
||||||
|
|
||||||
private val current = MutableStateFlow<Stage>(Stage.Idle)
|
private val current = MutableStateFlow<Stage>(Stage.Idle)
|
||||||
@@ -255,10 +270,10 @@ class WirelessAdbPairingService : Service() {
|
|||||||
|
|
||||||
private fun publish(stage: Stage) { current.value = stage }
|
private fun publish(stage: Stage) { current.value = stage }
|
||||||
|
|
||||||
fun start(context: Context) {
|
fun start(context: Context, enableLimit: Boolean = false) {
|
||||||
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
|
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
|
||||||
publish(Stage.Waiting)
|
publish(Stage.Waiting)
|
||||||
val intent = Intent(context, WirelessAdbPairingService::class.java)
|
val intent = Intent(context, WirelessAdbPairingService::class.java).putExtra(EXTRA_ENABLE_LIMIT, enableLimit)
|
||||||
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
|
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,6 +286,12 @@ class WirelessAdbPairingService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun notificationsEnabled(context: Context): Boolean =
|
fun notificationsEnabled(context: Context): Boolean =
|
||||||
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false
|
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false && !channelBlocked(context)
|
||||||
|
|
||||||
|
/** The code is typed into a notification on this channel; a channel the user switched off leaves pairing with nothing to type into. */
|
||||||
|
fun channelBlocked(context: Context): Boolean =
|
||||||
|
context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
|
||||||
|
|
||||||
|
fun channelId(): String = CHANNEL_ID
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -28,6 +28,7 @@ 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
|
||||||
|
import androidx.compose.material.icons.filled.FileOpen
|
||||||
import androidx.compose.material.icons.filled.Folder
|
import androidx.compose.material.icons.filled.Folder
|
||||||
import androidx.compose.material.icons.filled.Info
|
import androidx.compose.material.icons.filled.Info
|
||||||
import androidx.compose.material.icons.filled.InsertDriveFile
|
import androidx.compose.material.icons.filled.InsertDriveFile
|
||||||
@@ -101,8 +102,18 @@ private fun FileContextMenuItems(
|
|||||||
onToggleFavorite: () -> Unit,
|
onToggleFavorite: () -> Unit,
|
||||||
onProperties: () -> Unit,
|
onProperties: () -> Unit,
|
||||||
onDismissMenu: () -> Unit,
|
onDismissMenu: () -> Unit,
|
||||||
|
onOpen: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val isDir = file.isDirectory
|
val isDir = file.isDirectory
|
||||||
|
if (!isDir) {
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(stringResource(R.string.fm_edit_open)) },
|
||||||
|
leadingIcon = { Icon(Icons.Filled.FileOpen, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
|
onClick = { onDismissMenu(); onOpen() },
|
||||||
|
modifier = Modifier.focusGlide(),
|
||||||
|
)
|
||||||
|
MenuItemDivider()
|
||||||
|
}
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(stringResource(R.string.fm_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) },
|
||||||
@@ -180,6 +191,7 @@ internal fun FileItemRow(
|
|||||||
onCut: () -> Unit,
|
onCut: () -> Unit,
|
||||||
onDelete: () -> Unit,
|
onDelete: () -> Unit,
|
||||||
onRename: () -> Unit,
|
onRename: () -> Unit,
|
||||||
|
onOpen: () -> Unit = {},
|
||||||
isFavorite: Boolean = false,
|
isFavorite: Boolean = false,
|
||||||
onToggleFavorite: () -> Unit = {},
|
onToggleFavorite: () -> Unit = {},
|
||||||
onProperties: () -> Unit = {},
|
onProperties: () -> Unit = {},
|
||||||
@@ -291,6 +303,7 @@ internal fun FileItemRow(
|
|||||||
file = file,
|
file = file,
|
||||||
isFavorite = isFavorite,
|
isFavorite = isFavorite,
|
||||||
onSelect = onSelect,
|
onSelect = onSelect,
|
||||||
|
onOpen = onOpen,
|
||||||
onRename = onRename,
|
onRename = onRename,
|
||||||
onCopy = onCopy,
|
onCopy = onCopy,
|
||||||
onCut = onCut,
|
onCut = onCut,
|
||||||
@@ -517,6 +530,7 @@ internal fun FileGridTile(
|
|||||||
isFavorite: Boolean = false,
|
isFavorite: Boolean = false,
|
||||||
onSelect: () -> Unit = {},
|
onSelect: () -> Unit = {},
|
||||||
onRename: () -> Unit = {},
|
onRename: () -> Unit = {},
|
||||||
|
onOpen: () -> Unit = {},
|
||||||
onCopy: () -> Unit = {},
|
onCopy: () -> Unit = {},
|
||||||
onCut: () -> Unit = {},
|
onCut: () -> Unit = {},
|
||||||
onDelete: () -> Unit = {},
|
onDelete: () -> Unit = {},
|
||||||
@@ -605,6 +619,7 @@ internal fun FileGridTile(
|
|||||||
file = file,
|
file = file,
|
||||||
isFavorite = isFavorite,
|
isFavorite = isFavorite,
|
||||||
onSelect = onSelect,
|
onSelect = onSelect,
|
||||||
|
onOpen = onOpen,
|
||||||
onRename = onRename,
|
onRename = onRename,
|
||||||
onCopy = onCopy,
|
onCopy = onCopy,
|
||||||
onCut = onCut,
|
onCut = onCut,
|
||||||
|
|||||||
@@ -191,6 +191,7 @@ fun FileManagerScreen(
|
|||||||
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
|
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
|
||||||
var showNewFolderDialog by remember { mutableStateOf(false) }
|
var showNewFolderDialog by remember { mutableStateOf(false) }
|
||||||
var renameTarget by remember { mutableStateOf<File?>(null) }
|
var renameTarget by remember { mutableStateOf<File?>(null) }
|
||||||
|
var editingTarget by remember { mutableStateOf<File?>(null) }
|
||||||
var propertiesTarget by remember { mutableStateOf<File?>(null) }
|
var propertiesTarget by remember { mutableStateOf<File?>(null) }
|
||||||
var isOperationRunning by remember { mutableStateOf(false) }
|
var isOperationRunning by remember { mutableStateOf(false) }
|
||||||
var operationLabel by remember { mutableStateOf("") }
|
var operationLabel by remember { mutableStateOf("") }
|
||||||
@@ -294,7 +295,7 @@ fun FileManagerScreen(
|
|||||||
if (isOperationActive()) pendingNavigation = action else navigate(action)
|
if (isOperationActive()) pendingNavigation = action else navigate(action)
|
||||||
}
|
}
|
||||||
|
|
||||||
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
|
BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) {
|
||||||
requestNavigation(FileManagerNavigation.BACK)
|
requestNavigation(FileManagerNavigation.BACK)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -696,6 +697,14 @@ fun FileManagerScreen(
|
|||||||
|
|
||||||
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
|
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
|
||||||
Column(modifier = Modifier.fillMaxSize()) {
|
Column(modifier = Modifier.fillMaxSize()) {
|
||||||
|
editingTarget?.let { target ->
|
||||||
|
TextEditorScreen(
|
||||||
|
file = target,
|
||||||
|
onExit = { editingTarget = null },
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
)
|
||||||
|
return@Column
|
||||||
|
}
|
||||||
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
text = pickerTitle,
|
text = pickerTitle,
|
||||||
@@ -1194,6 +1203,8 @@ fun FileManagerScreen(
|
|||||||
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
||||||
onPick?.invoke(file)
|
onPick?.invoke(file)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
editingTarget = file
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onMenu = { showMenuFor = file },
|
onMenu = { showMenuFor = file },
|
||||||
@@ -1205,6 +1216,7 @@ fun FileManagerScreen(
|
|||||||
selectedPaths = selectedPaths + file.absolutePath
|
selectedPaths = selectedPaths + file.absolutePath
|
||||||
showMenuFor = null
|
showMenuFor = null
|
||||||
},
|
},
|
||||||
|
onOpen = { editingTarget = file; showMenuFor = null },
|
||||||
onRename = { renameTarget = file; showMenuFor = null },
|
onRename = { renameTarget = file; showMenuFor = null },
|
||||||
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
|
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
|
||||||
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
||||||
@@ -1273,6 +1285,8 @@ fun FileManagerScreen(
|
|||||||
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
||||||
onPick?.invoke(file)
|
onPick?.invoke(file)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
editingTarget = file
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onMenu = { showMenuFor = file },
|
onMenu = { showMenuFor = file },
|
||||||
@@ -1286,6 +1300,7 @@ fun FileManagerScreen(
|
|||||||
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
|
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
|
||||||
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
||||||
onDelete = { selectedEntry = file; showMenuFor = null },
|
onDelete = { selectedEntry = file; showMenuFor = null },
|
||||||
|
onOpen = { editingTarget = file; showMenuFor = null },
|
||||||
onRename = { renameTarget = file; showMenuFor = null },
|
onRename = { renameTarget = file; showMenuFor = null },
|
||||||
isFavorite = isFav,
|
isFavorite = isFav,
|
||||||
onToggleFavorite = {
|
onToggleFavorite = {
|
||||||
|
|||||||
@@ -0,0 +1,726 @@
|
|||||||
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
import androidx.compose.foundation.ScrollState
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.horizontalScroll
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.IntrinsicSize
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.text.BasicTextField
|
||||||
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.ArrowBack
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||||
|
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||||
|
import androidx.compose.material.icons.filled.Save
|
||||||
|
import androidx.compose.material.icons.filled.Search
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.SolidColor
|
||||||
|
import androidx.compose.ui.layout.onSizeChanged
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.TextRange
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
|
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.input.TextFieldValue
|
||||||
|
import androidx.compose.ui.text.rememberTextMeasurer
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.ui.focusGlide
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.nio.charset.CharacterCodingException
|
||||||
|
import java.nio.charset.Charset
|
||||||
|
import java.nio.charset.CodingErrorAction
|
||||||
|
import java.nio.file.Files
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
internal const val EDITOR_FONT_SIZE_SP = 13
|
||||||
|
internal const val EDITOR_LINE_HEIGHT_SP = 18
|
||||||
|
internal const val EDITOR_TAB_WIDTH = 4
|
||||||
|
internal const val EDITOR_MAX_OPEN_BYTES = 4L * 1024 * 1024
|
||||||
|
internal const val EDITOR_MAX_EDIT_BYTES = 512L * 1024
|
||||||
|
|
||||||
|
internal enum class EditorCharset(val label: String, private val charsetName: String) {
|
||||||
|
UTF8("UTF-8", "UTF-8"),
|
||||||
|
GB18030("GB18030", "GB18030"),
|
||||||
|
;
|
||||||
|
|
||||||
|
val charset: Charset get() = Charset.forName(charsetName)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum class EditorLock { NONE, BINARY, TOO_LARGE, PERMISSION, LOSSY }
|
||||||
|
|
||||||
|
internal enum class EditorLoadState { LOADING, READY, TOO_LARGE, UNREADABLE }
|
||||||
|
|
||||||
|
internal data class DecodedEditorText(val text: String, val charset: EditorCharset, val lossy: Boolean)
|
||||||
|
|
||||||
|
internal fun editorIsBinary(bytes: ByteArray, sample: Int = 8192): Boolean {
|
||||||
|
val limit = minOf(bytes.size, sample)
|
||||||
|
for (i in 0 until limit) if (bytes[i].toInt() == 0) return true
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun strictDecode(bytes: ByteArray, charset: Charset): String? = try {
|
||||||
|
charset.newDecoder()
|
||||||
|
.onMalformedInput(CodingErrorAction.REPORT)
|
||||||
|
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||||
|
.decode(ByteBuffer.wrap(bytes))
|
||||||
|
.toString()
|
||||||
|
} catch (e: CharacterCodingException) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun decodeEditorText(bytes: ByteArray): DecodedEditorText {
|
||||||
|
strictDecode(bytes, Charsets.UTF_8)?.let { return DecodedEditorText(it, EditorCharset.UTF8, false) }
|
||||||
|
strictDecode(bytes, EditorCharset.GB18030.charset)?.let { return DecodedEditorText(it, EditorCharset.GB18030, false) }
|
||||||
|
return DecodedEditorText(String(bytes, Charsets.UTF_8), EditorCharset.UTF8, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun resolveEditorSaveTarget(file: File): File {
|
||||||
|
val isLink = runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false)
|
||||||
|
if (!isLink) return file
|
||||||
|
// rename(2) replaces the link itself, so stage next to and rename onto the real target
|
||||||
|
return runCatching { file.canonicalFile }.getOrDefault(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun readCapped(input: InputStream, limit: Long): ByteArray? {
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
val buffer = ByteArray(64 * 1024)
|
||||||
|
var total = 0L
|
||||||
|
while (true) {
|
||||||
|
val n = input.read(buffer)
|
||||||
|
if (n < 0) return out.toByteArray()
|
||||||
|
total += n
|
||||||
|
if (total > limit) return null
|
||||||
|
out.write(buffer, 0, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun expandEditorTabs(text: String, width: Int = EDITOR_TAB_WIDTH): String {
|
||||||
|
if (text.indexOf('\t') < 0) return text
|
||||||
|
val out = StringBuilder(text.length)
|
||||||
|
var column = 0
|
||||||
|
for (c in text) {
|
||||||
|
when (c) {
|
||||||
|
'\n' -> {
|
||||||
|
out.append(c)
|
||||||
|
column = 0
|
||||||
|
}
|
||||||
|
'\t' -> {
|
||||||
|
val pad = width - (column % width)
|
||||||
|
repeat(pad) { out.append(' ') }
|
||||||
|
column += pad
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
out.append(c)
|
||||||
|
column++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun lineCountOf(text: String): Int {
|
||||||
|
var lines = 1
|
||||||
|
for (i in text.indices) if (text[i] == '\n') lines++
|
||||||
|
return lines
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun lineIndexOfOffset(text: String, offset: Int): Int {
|
||||||
|
val end = offset.coerceIn(0, text.length)
|
||||||
|
var line = 0
|
||||||
|
var i = 0
|
||||||
|
while (i < end) {
|
||||||
|
if (text[i] == '\n') line++
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return line
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun columnOfOffset(text: String, offset: Int): Int {
|
||||||
|
val end = offset.coerceIn(0, text.length)
|
||||||
|
var start = end
|
||||||
|
while (start > 0 && text[start - 1] != '\n') start--
|
||||||
|
return end - start + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun findEditorMatches(
|
||||||
|
text: String,
|
||||||
|
query: String,
|
||||||
|
matchCase: Boolean = false,
|
||||||
|
limit: Int = 10000,
|
||||||
|
): List<IntRange> {
|
||||||
|
if (query.isEmpty()) return emptyList()
|
||||||
|
val out = ArrayList<IntRange>()
|
||||||
|
var at = 0
|
||||||
|
while (out.size < limit) {
|
||||||
|
val found = text.indexOf(query, at, ignoreCase = !matchCase)
|
||||||
|
if (found < 0) break
|
||||||
|
out.add(found until found + query.length)
|
||||||
|
at = found + query.length
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun replaceEditorMatches(text: String, matches: List<IntRange>, replacement: String): String {
|
||||||
|
if (matches.isEmpty()) return text
|
||||||
|
val out = StringBuilder(text.length)
|
||||||
|
var cursor = 0
|
||||||
|
for (m in matches) {
|
||||||
|
if (m.first < cursor || m.last >= text.length) continue
|
||||||
|
out.append(text, cursor, m.first).append(replacement)
|
||||||
|
cursor = m.last + 1
|
||||||
|
}
|
||||||
|
out.append(text, cursor, text.length)
|
||||||
|
return out.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun TextEditorScreen(
|
||||||
|
file: File,
|
||||||
|
onExit: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val density = LocalDensity.current
|
||||||
|
|
||||||
|
var text by remember { mutableStateOf("") }
|
||||||
|
var selection by remember { mutableStateOf(TextRange.Zero) }
|
||||||
|
var composing by remember { mutableStateOf<TextRange?>(null) }
|
||||||
|
var loadState by remember { mutableStateOf(EditorLoadState.LOADING) }
|
||||||
|
var lock by remember { mutableStateOf(EditorLock.NONE) }
|
||||||
|
var charset by remember { mutableStateOf(EditorCharset.UTF8) }
|
||||||
|
var dirty by remember { mutableStateOf(false) }
|
||||||
|
var saving by remember { mutableStateOf(false) }
|
||||||
|
var showDiscard by remember { mutableStateOf(false) }
|
||||||
|
var showSearch by remember { mutableStateOf(false) }
|
||||||
|
var query by remember { mutableStateOf("") }
|
||||||
|
var replacement by remember { mutableStateOf("") }
|
||||||
|
var matchCase by remember { mutableStateOf(false) }
|
||||||
|
var matchIndex by remember { mutableIntStateOf(0) }
|
||||||
|
|
||||||
|
val scrollState = rememberScrollState()
|
||||||
|
val textHorizontalState = rememberScrollState()
|
||||||
|
var viewportHeight by remember { mutableIntStateOf(0) }
|
||||||
|
var viewportWidth by remember { mutableIntStateOf(0) }
|
||||||
|
|
||||||
|
val lineHeightDp = with(density) { EDITOR_LINE_HEIGHT_SP.sp.toDp() }
|
||||||
|
val lineHeightPx = with(density) { lineHeightDp.toPx() }
|
||||||
|
val totalLines = remember(text) { lineCountOf(text) }
|
||||||
|
val cursorLine = lineIndexOfOffset(text, selection.end)
|
||||||
|
val cursorColumn = columnOfOffset(text, selection.end)
|
||||||
|
val matches = remember(text, query, matchCase) { findEditorMatches(text, query, matchCase) }
|
||||||
|
val readOnly = lock != EditorLock.NONE
|
||||||
|
val bodyStyle = TextStyle(
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
fontSize = EDITOR_FONT_SIZE_SP.sp,
|
||||||
|
lineHeight = EDITOR_LINE_HEIGHT_SP.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
)
|
||||||
|
val textMeasurer = rememberTextMeasurer()
|
||||||
|
val charWidthPx = remember(bodyStyle) { textMeasurer.measure(text = "0", style = bodyStyle).size.width.toFloat() }
|
||||||
|
|
||||||
|
LaunchedEffect(file) {
|
||||||
|
loadState = EditorLoadState.LOADING
|
||||||
|
val size = withContext(Dispatchers.IO) { file.length() }
|
||||||
|
if (size > EDITOR_MAX_OPEN_BYTES) {
|
||||||
|
loadState = EditorLoadState.TOO_LARGE
|
||||||
|
return@LaunchedEffect
|
||||||
|
}
|
||||||
|
val read = withContext(Dispatchers.IO) {
|
||||||
|
runCatching { file.inputStream().use { readCapped(it, EDITOR_MAX_OPEN_BYTES) } }
|
||||||
|
}
|
||||||
|
val bytes = read.getOrNull()
|
||||||
|
if (bytes == null) {
|
||||||
|
loadState = if (read.isFailure) EditorLoadState.UNREADABLE else EditorLoadState.TOO_LARGE
|
||||||
|
return@LaunchedEffect
|
||||||
|
}
|
||||||
|
val decoded = decodeEditorText(bytes)
|
||||||
|
text = expandEditorTabs(decoded.text)
|
||||||
|
charset = decoded.charset
|
||||||
|
lock = when {
|
||||||
|
editorIsBinary(bytes) -> EditorLock.BINARY
|
||||||
|
decoded.lossy -> EditorLock.LOSSY
|
||||||
|
bytes.size > EDITOR_MAX_EDIT_BYTES -> EditorLock.TOO_LARGE
|
||||||
|
!file.canWrite() -> EditorLock.PERMISSION
|
||||||
|
else -> EditorLock.NONE
|
||||||
|
}
|
||||||
|
selection = TextRange.Zero
|
||||||
|
loadState = EditorLoadState.READY
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun revealLine(line: Int) {
|
||||||
|
val current = scrollState.value
|
||||||
|
val top = line * lineHeightPx
|
||||||
|
val target = when {
|
||||||
|
top < current -> top
|
||||||
|
top + lineHeightPx > current + viewportHeight -> top + lineHeightPx - viewportHeight
|
||||||
|
else -> return
|
||||||
|
}
|
||||||
|
val clamped = target.roundToInt().coerceIn(0, scrollState.maxValue)
|
||||||
|
if (clamped != current) scrollState.scrollTo(clamped)
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(text, selection.end, viewportHeight, viewportWidth) {
|
||||||
|
if (loadState != EditorLoadState.READY) return@LaunchedEffect
|
||||||
|
revealLine(lineIndexOfOffset(text, selection.end))
|
||||||
|
if (viewportWidth > 0 && charWidthPx > 0) {
|
||||||
|
val x = (columnOfOffset(text, selection.end) - 1) * charWidthPx
|
||||||
|
val current = textHorizontalState.value
|
||||||
|
val target = when {
|
||||||
|
x < current -> x
|
||||||
|
x + charWidthPx > current + viewportWidth -> x + charWidthPx - viewportWidth
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
if (target != null) {
|
||||||
|
val clamped = target.roundToInt().coerceIn(0, textHorizontalState.maxValue)
|
||||||
|
if (clamped != current) textHorizontalState.scrollTo(clamped)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(query, matchCase) {
|
||||||
|
if (query.isEmpty()) return@LaunchedEffect
|
||||||
|
matchIndex = 0
|
||||||
|
val first = matches.firstOrNull() ?: return@LaunchedEffect
|
||||||
|
selection = TextRange(first.first, first.last + 1)
|
||||||
|
composing = TextRange.Zero
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(text) { matchIndex = 0 }
|
||||||
|
|
||||||
|
fun gotoMatch(delta: Int) {
|
||||||
|
if (matches.isEmpty()) return
|
||||||
|
matchIndex = Math.floorMod(matchIndex + delta, matches.size)
|
||||||
|
val m = matches[matchIndex]
|
||||||
|
selection = TextRange(m.first, m.last + 1)
|
||||||
|
composing = TextRange.Zero
|
||||||
|
}
|
||||||
|
|
||||||
|
fun replaceCurrent() {
|
||||||
|
if (readOnly) return
|
||||||
|
val m = matches.getOrNull(matchIndex) ?: return
|
||||||
|
text = text.replaceRange(m.first, m.last + 1, replacement)
|
||||||
|
dirty = true
|
||||||
|
matchIndex = 0
|
||||||
|
selection = TextRange(m.first + replacement.length)
|
||||||
|
composing = TextRange.Zero
|
||||||
|
}
|
||||||
|
|
||||||
|
fun replaceAll() {
|
||||||
|
if (readOnly || matches.isEmpty()) return
|
||||||
|
val all = findEditorMatches(text, query, matchCase, limit = Int.MAX_VALUE)
|
||||||
|
text = replaceEditorMatches(text, all, replacement)
|
||||||
|
dirty = true
|
||||||
|
matchIndex = 0
|
||||||
|
selection = TextRange.Zero
|
||||||
|
composing = TextRange.Zero
|
||||||
|
}
|
||||||
|
|
||||||
|
fun save() {
|
||||||
|
if (readOnly || saving || loadState != EditorLoadState.READY) return
|
||||||
|
val snapshot = text
|
||||||
|
val bytes = snapshot.toByteArray(charset.charset)
|
||||||
|
saving = true
|
||||||
|
scope.launch {
|
||||||
|
val ok = withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
val target = resolveEditorSaveTarget(file)
|
||||||
|
val parent = target.parentFile
|
||||||
|
if (parent == null) {
|
||||||
|
target.writeBytes(bytes)
|
||||||
|
} else {
|
||||||
|
val tmp = File.createTempFile(".${target.name}.", ".droiddeck-tmp", parent)
|
||||||
|
try {
|
||||||
|
tmp.writeBytes(bytes)
|
||||||
|
runCatching {
|
||||||
|
Files.setPosixFilePermissions(tmp.toPath(), Files.getPosixFilePermissions(target.toPath()))
|
||||||
|
}
|
||||||
|
if (!tmp.renameTo(target)) error("rename to ${target.name} failed")
|
||||||
|
} finally {
|
||||||
|
tmp.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.isSuccess
|
||||||
|
}
|
||||||
|
saving = false
|
||||||
|
if (ok) {
|
||||||
|
if (text == snapshot) dirty = false
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, context.getString(R.string.fm_edit_save_failed, file.name), Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun tryExit() {
|
||||||
|
if (saving) return
|
||||||
|
if (dirty && !readOnly) showDiscard = true else onExit()
|
||||||
|
}
|
||||||
|
|
||||||
|
BackHandler { tryExit() }
|
||||||
|
|
||||||
|
if (showDiscard) {
|
||||||
|
OutlinedAlertDialog(
|
||||||
|
onDismissRequest = { showDiscard = false },
|
||||||
|
title = { Text(stringResource(R.string.fm_edit_discard_title)) },
|
||||||
|
text = { Text(stringResource(R.string.fm_edit_discard_text, file.name)) },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = onExit, modifier = Modifier.focusGlide(CircleShape)) {
|
||||||
|
Text(stringResource(R.string.fm_edit_discard))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showDiscard = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||||
|
Text(stringResource(R.string.common_cancel))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(MaterialTheme.colorScheme.background),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.background(MaterialTheme.colorScheme.surfaceContainer)
|
||||||
|
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||||
|
) {
|
||||||
|
IconButton(onClick = { tryExit() }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.ArrowBack,
|
||||||
|
stringResource(R.string.fm_back),
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Column(modifier = Modifier.weight(1f).padding(horizontal = 4.dp)) {
|
||||||
|
Text(
|
||||||
|
text = file.name,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
if (dirty) {
|
||||||
|
Text(
|
||||||
|
text = "\u2022 " + stringResource(R.string.fm_edit_modified),
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
maxLines = 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (loadState == EditorLoadState.READY && lock != EditorLock.NONE) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(
|
||||||
|
if (lock == EditorLock.BINARY) R.string.fm_edit_binary else R.string.fm_edit_read_only,
|
||||||
|
),
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 10.sp,
|
||||||
|
maxLines = 1,
|
||||||
|
modifier = Modifier
|
||||||
|
.background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.small)
|
||||||
|
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
}
|
||||||
|
IconButton(
|
||||||
|
onClick = { showSearch = !showSearch },
|
||||||
|
enabled = loadState == EditorLoadState.READY,
|
||||||
|
modifier = Modifier.focusGlide(CircleShape),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Search,
|
||||||
|
stringResource(R.string.fm_edit_find),
|
||||||
|
tint = if (showSearch) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(
|
||||||
|
onClick = { save() },
|
||||||
|
enabled = loadState == EditorLoadState.READY && !readOnly && dirty && !saving,
|
||||||
|
modifier = Modifier.focusGlide(CircleShape),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Save,
|
||||||
|
stringResource(R.string.fm_edit_save),
|
||||||
|
tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showSearch && loadState == EditorLoadState.READY) {
|
||||||
|
Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainer)) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp, top = 4.dp),
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = query,
|
||||||
|
onValueChange = { query = it; matchIndex = 0 },
|
||||||
|
singleLine = true,
|
||||||
|
placeholder = { Text(stringResource(R.string.fm_edit_find), fontSize = 13.sp) },
|
||||||
|
textStyle = MaterialTheme.typography.bodySmall,
|
||||||
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||||
|
keyboardActions = KeyboardActions(onSearch = { gotoMatch(1) }),
|
||||||
|
modifier = Modifier.weight(1f).focusGlide(),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = if (matches.isEmpty()) "0/${matches.size}" else "${matchIndex.coerceAtMost(matches.size - 1) + 1}/${matches.size}",
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.padding(horizontal = 6.dp).widthIn(min = 44.dp, max = 80.dp),
|
||||||
|
)
|
||||||
|
IconButton(
|
||||||
|
onClick = { gotoMatch(-1) },
|
||||||
|
enabled = matches.isNotEmpty(),
|
||||||
|
modifier = Modifier.focusGlide(CircleShape),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.KeyboardArrowUp,
|
||||||
|
stringResource(R.string.fm_edit_find_previous),
|
||||||
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(
|
||||||
|
onClick = { gotoMatch(1) },
|
||||||
|
enabled = matches.isNotEmpty(),
|
||||||
|
modifier = Modifier.focusGlide(CircleShape),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.KeyboardArrowDown,
|
||||||
|
stringResource(R.string.fm_edit_find_next),
|
||||||
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
TextButton(onClick = { matchCase = !matchCase }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||||
|
Text(
|
||||||
|
text = "Aa",
|
||||||
|
color = if (matchCase) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(onClick = { showSearch = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Close,
|
||||||
|
stringResource(R.string.common_cancel),
|
||||||
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 2.dp, end = 4.dp, bottom = 2.dp),
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = replacement,
|
||||||
|
onValueChange = { replacement = it },
|
||||||
|
singleLine = true,
|
||||||
|
placeholder = { Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) },
|
||||||
|
textStyle = MaterialTheme.typography.bodySmall,
|
||||||
|
modifier = Modifier.weight(1f).focusGlide(),
|
||||||
|
)
|
||||||
|
TextButton(
|
||||||
|
onClick = { replaceCurrent() },
|
||||||
|
enabled = !readOnly && matches.isNotEmpty(),
|
||||||
|
modifier = Modifier.focusGlide(CircleShape),
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp)
|
||||||
|
}
|
||||||
|
TextButton(
|
||||||
|
onClick = { replaceAll() },
|
||||||
|
enabled = !readOnly && matches.isNotEmpty(),
|
||||||
|
modifier = Modifier.focusGlide(CircleShape),
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.fm_edit_replace_all), fontSize = 13.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.fillMaxWidth()
|
||||||
|
.onSizeChanged { viewportHeight = it.height },
|
||||||
|
) {
|
||||||
|
when (loadState) {
|
||||||
|
EditorLoadState.LOADING -> CircularProgressIndicator(
|
||||||
|
modifier = Modifier.align(Alignment.Center),
|
||||||
|
)
|
||||||
|
|
||||||
|
EditorLoadState.TOO_LARGE, EditorLoadState.UNREADABLE -> Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
modifier = Modifier.align(Alignment.Center).padding(24.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(
|
||||||
|
if (loadState == EditorLoadState.TOO_LARGE) R.string.fm_edit_too_large
|
||||||
|
else R.string.fm_edit_open_failed,
|
||||||
|
if (loadState == EditorLoadState.TOO_LARGE) FileOps.formatBytes(context, file.length())
|
||||||
|
else file.name,
|
||||||
|
),
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
EditorLoadState.READY -> Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.verticalScroll(scrollState),
|
||||||
|
) {
|
||||||
|
Row(modifier = Modifier.fillMaxWidth().height(lineHeightDp * totalLines.toFloat())) {
|
||||||
|
LineNumbers(
|
||||||
|
scrollState = scrollState,
|
||||||
|
viewportHeight = viewportHeight,
|
||||||
|
lineHeightDp = lineHeightDp,
|
||||||
|
lineHeightPx = lineHeightPx,
|
||||||
|
totalLines = totalLines,
|
||||||
|
cursorLine = cursorLine,
|
||||||
|
style = bodyStyle,
|
||||||
|
mutedColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
cursorColor = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
Box(modifier = Modifier.weight(1f).onSizeChanged { viewportWidth = it.width }.horizontalScroll(textHorizontalState)) {
|
||||||
|
BasicTextField(
|
||||||
|
value = TextFieldValue(text = text, selection = selection, composition = composing),
|
||||||
|
onValueChange = { next ->
|
||||||
|
val changed = next.text != text
|
||||||
|
text = next.text
|
||||||
|
selection = next.selection
|
||||||
|
composing = next.composition
|
||||||
|
if (changed) dirty = true
|
||||||
|
},
|
||||||
|
readOnly = readOnly,
|
||||||
|
textStyle = bodyStyle,
|
||||||
|
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
|
||||||
|
keyboardOptions = KeyboardOptions(
|
||||||
|
keyboardType = KeyboardType.Text,
|
||||||
|
capitalization = KeyboardCapitalization.None,
|
||||||
|
),
|
||||||
|
modifier = Modifier.fillMaxHeight().focusGlide(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loadState == EditorLoadState.READY) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.fm_edit_position, cursorLine + 1, cursorColumn),
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
maxLines = 1,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
Text(
|
||||||
|
text = charset.label + " \u2022 " + FileOps.formatBytes(context, file.length()),
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
maxLines = 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LineNumbers(
|
||||||
|
scrollState: ScrollState,
|
||||||
|
viewportHeight: Int,
|
||||||
|
lineHeightDp: Dp,
|
||||||
|
lineHeightPx: Float,
|
||||||
|
totalLines: Int,
|
||||||
|
cursorLine: Int,
|
||||||
|
style: TextStyle,
|
||||||
|
mutedColor: Color,
|
||||||
|
cursorColor: Color,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val firstLine = (scrollState.value / lineHeightPx).toInt().coerceIn(0, totalLines - 1)
|
||||||
|
val lastLine = ((scrollState.value + viewportHeight) / lineHeightPx)
|
||||||
|
.toInt()
|
||||||
|
.coerceIn(firstLine, totalLines - 1)
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.End,
|
||||||
|
modifier = modifier
|
||||||
|
.width(IntrinsicSize.Min)
|
||||||
|
.padding(top = lineHeightDp * firstLine.toFloat()),
|
||||||
|
) {
|
||||||
|
for (line in firstLine..lastLine) {
|
||||||
|
Text(
|
||||||
|
text = (line + 1).toString(),
|
||||||
|
color = if (line == cursorLine) cursorColor else mutedColor,
|
||||||
|
textAlign = TextAlign.End,
|
||||||
|
maxLines = 1,
|
||||||
|
style = style,
|
||||||
|
modifier = Modifier.fillMaxWidth().height(lineHeightDp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,6 +31,7 @@ object AddedGames {
|
|||||||
val exeUncertain: Boolean = false,
|
val exeUncertain: Boolean = false,
|
||||||
val launchOptions: String = "",
|
val launchOptions: String = "",
|
||||||
val single: Boolean = false,
|
val single: Boolean = false,
|
||||||
|
val steamProgram: Boolean = true,
|
||||||
) {
|
) {
|
||||||
fun folderName(): String = folder.name
|
fun folderName(): String = folder.name
|
||||||
}
|
}
|
||||||
@@ -238,6 +239,7 @@ object AddedGames {
|
|||||||
for (entry in AddedExes.list(context)) {
|
for (entry in AddedExes.list(context)) {
|
||||||
val folder = File(entry.folder)
|
val folder = File(entry.folder)
|
||||||
if (folder.path in removed || !folder.isDirectory) continue
|
if (folder.path in removed || !folder.isDirectory) continue
|
||||||
|
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
|
||||||
scanGame(context, folder, out, single = entry, reuse = true)
|
scanGame(context, folder, out, single = entry, reuse = true)
|
||||||
}
|
}
|
||||||
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
|
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
|
||||||
@@ -336,7 +338,11 @@ object AddedGames {
|
|||||||
val owner = ownerFolder(app, exe)
|
val owner = ownerFolder(app, exe)
|
||||||
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
|
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
|
||||||
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
|
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
|
||||||
if (guestPath(app, exe) != null) AddedExes.put(app, AddedExes.Entry(owner.path, exe.path))
|
val keep = listOf(it.exe, exe).firstOrNull { f -> guestPath(app, f) != null }
|
||||||
|
if (keep != null) {
|
||||||
|
SessionPrefs.setAddedGameExe(app, owner.path, keep.path)
|
||||||
|
AddedExes.put(app, AddedExes.Entry(owner.path, keep.path))
|
||||||
|
}
|
||||||
return AddResult.Existing(it)
|
return AddResult.Existing(it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -442,9 +448,9 @@ object AddedGames {
|
|||||||
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||||
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
|
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
|
||||||
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
|
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
|
||||||
val epicLauncher = sidecar?.takeIf { it.store == Store.EPIC && (chosen == null || canonical(chosen) == canonical(it.exeFile(folder))) }
|
val storeLauncher = sidecar?.takeIf { chosen == null || canonical(chosen) == canonical(it.exeFile(folder)) }
|
||||||
?.launcherFile(folder)?.takeIf { it.isFile }
|
?.launcherFile(folder)?.takeIf { it.isFile }
|
||||||
val launch = epicLauncher ?: if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
|
val launch = storeLauncher ?: found
|
||||||
val foundGuest = guestPath(context, launch)
|
val foundGuest = guestPath(context, launch)
|
||||||
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
|
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
|
||||||
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
|
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
|
||||||
@@ -470,7 +476,13 @@ object AddedGames {
|
|||||||
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
|
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
|
||||||
?: sidecarDir
|
?: sidecarDir
|
||||||
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
|
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
|
||||||
val steamId = config?.let { steamRoute(it, appId) }
|
if (adopted == null && SessionPrefs.addedGameAdopted(context, folder.path, "Exe") == null &&
|
||||||
|
guestPath(context, folder)?.let { steamEditedTo(it, record, guestExe) } == true) {
|
||||||
|
SessionPrefs.setAddedGameAdopted(context, folder.path, "Exe", exe.path)
|
||||||
|
}
|
||||||
|
val steamProgram = candidates.firstOrNull()?.let { canonical(it) == canonical(exe) } ?: true ||
|
||||||
|
SessionPrefs.addedGameAdopted(context, folder.path, "Exe")?.let { canonical(File(it)) == canonical(exe) } == true
|
||||||
|
val steamId = config?.takeIf { steamProgram }?.let { steamRoute(it, appId) }
|
||||||
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
|
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,
|
||||||
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
|
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
|
||||||
@@ -480,7 +492,7 @@ object AddedGames {
|
|||||||
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
|
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
|
||||||
else -> ""
|
else -> ""
|
||||||
},
|
},
|
||||||
single = single != null))
|
single = single != null, steamProgram = steamProgram))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -520,6 +532,11 @@ object AddedGames {
|
|||||||
return file.takeIf { inside && it.isFile }
|
return file.takeIf { inside && it.isFile }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun steamEditedTo(folderGuest: String, record: JSONObject?, guestExe: String): Boolean {
|
||||||
|
val steam = unquote(record?.optJSONObject("steam")?.optString("Exe"))
|
||||||
|
return steam == guestExe && steam != unquote(record?.optJSONObject("app")?.optString("Exe")) && steam.startsWith("$folderGuest/")
|
||||||
|
}
|
||||||
|
|
||||||
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
|
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
|
||||||
|
|
||||||
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
|
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
|
||||||
@@ -568,6 +585,7 @@ object AddedGames {
|
|||||||
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
|
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
|
||||||
if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions))
|
if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions))
|
||||||
if (g.source != Library.ADDED) json.append(",\"store\":").append(quote(g.source))
|
if (g.source != Library.ADDED) json.append(",\"store\":").append(quote(g.source))
|
||||||
|
if (!g.steamProgram) json.append(",\"route\":false")
|
||||||
val art = AddedGameArt.resolve(context, g)
|
val art = AddedGameArt.resolve(context, g)
|
||||||
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
|
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
|
||||||
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
|
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ object AutoComponents {
|
|||||||
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
|
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
|
||||||
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
|
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
|
||||||
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
|
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
|
||||||
|
@VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) }
|
||||||
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
|
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
|
||||||
@VisibleForTesting @Volatile internal var runNow = false
|
@VisibleForTesting @Volatile internal var runNow = false
|
||||||
|
|
||||||
@@ -533,6 +534,10 @@ object AutoComponents {
|
|||||||
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun powerSaveOrMetered(context: Context): Boolean =
|
||||||
|
context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true ||
|
||||||
|
context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
|
||||||
|
|
||||||
fun constrained(context: Context): Boolean {
|
fun constrained(context: Context): Boolean {
|
||||||
val power = context.getSystemService(PowerManager::class.java)
|
val power = context.getSystemService(PowerManager::class.java)
|
||||||
if (power?.isPowerSaveMode == true) return true
|
if (power?.isPowerSaveMode == true) return true
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ object GameLaunchIntent {
|
|||||||
|
|
||||||
fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION
|
fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION
|
||||||
|
|
||||||
|
fun replayed(intent: Intent, restored: Boolean, savedProcess: String?, process: String): Boolean =
|
||||||
|
!(intent.data?.scheme == "droiddeck" && intent.data?.host == "settings") &&
|
||||||
|
(intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0 || restored && savedProcess != process)
|
||||||
|
|
||||||
fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) {
|
fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) {
|
||||||
Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent)
|
Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent)
|
||||||
ACTION, GAMENATIVE_ACTION -> readExtras(intent)
|
ACTION, GAMENATIVE_ACTION -> readExtras(intent)
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ object GamesFolderMigration {
|
|||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun run(context: Context) {
|
fun run(context: Context) {
|
||||||
|
repathInternalGuest(context)
|
||||||
val dirs = SessionPrefs.addedGamesDirs(context)
|
val dirs = SessionPrefs.addedGamesDirs(context)
|
||||||
if (dirs.isEmpty()) return
|
if (dirs.isEmpty()) return
|
||||||
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
|
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
|
||||||
@@ -58,12 +59,30 @@ object GamesFolderMigration {
|
|||||||
SessionPrefs.setGamesFoldersMigrated(context)
|
SessionPrefs.setGamesFoldersMigrated(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun repathInternalGuest(context: Context) {
|
||||||
|
val binds = SessionPrefs.gameFolderBinds(context)
|
||||||
|
if (binds.none { it.second == StoreInstallRoot.INTERNAL_GUEST }) return
|
||||||
|
val hosts = binds.map { it.first }
|
||||||
|
val roots = legacyRoots(hosts).associateBy { it.host.path }
|
||||||
|
val taken = binds.map { it.second }.filter { it != StoreInstallRoot.INTERNAL_GUEST }.toMutableSet()
|
||||||
|
SessionPrefs.setGameFolderBinds(context, binds.map { (host, guest) ->
|
||||||
|
if (guest != StoreInstallRoot.INTERNAL_GUEST) return@map host to guest
|
||||||
|
val base = roots.getValue(host).guest
|
||||||
|
var next = base
|
||||||
|
var n = 2
|
||||||
|
while (next in taken) next = "$base-${n++}"
|
||||||
|
taken.add(next)
|
||||||
|
host to next
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
|
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
|
||||||
val hosts = paths.distinct().map { File(it) }
|
val hosts = paths.distinct().map { File(it) }
|
||||||
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
|
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
|
||||||
return hosts.map { host ->
|
return hosts.map { host ->
|
||||||
val name = host.name.ifEmpty { "games" }
|
val name = host.name.ifEmpty { "games" }
|
||||||
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
|
val clash = (names[name.lowercase()] ?: 0) > 1 || "${AddedGames.GUEST_DIR}/$name" == StoreInstallRoot.INTERNAL_GUEST
|
||||||
|
val guestName = if (clash) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
|
||||||
AddedGames.Root(host, "${AddedGames.GUEST_DIR}/$guestName")
|
AddedGames.Root(host, "${AddedGames.GUEST_DIR}/$guestName")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ object SteamRedists {
|
|||||||
val SCRIPTED = mapOf(
|
val SCRIPTED = mapOf(
|
||||||
72850 to listOf("xact" to "DirectX XACT audio"),
|
72850 to listOf("xact" to "DirectX XACT audio"),
|
||||||
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
|
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
|
||||||
|
// Warband compiles its postFX .fx effects at launch through d3dx9_42; Wine's own d3dcompiler_42 stops with E5017/E5033 on fx_2_0.
|
||||||
|
48700 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_42" to "D3DCompiler 42"),
|
||||||
|
// DST's bundled ANGLE compiles SM3 shaders through d3dcompiler_43; DXVK's SM3 parser asserts on what Wine's own one emits.
|
||||||
|
322330 to listOf("d3dcompiler_43" to "D3DCompiler 43"),
|
||||||
|
// EU4 builds its map effects through native d3dx9_43, which calls d3dcompiler_43; Wine's own one fails them with E5005, so the map draws black.
|
||||||
|
236850 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_43" to "D3DCompiler 43"),
|
||||||
)
|
)
|
||||||
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
||||||
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
||||||
|
|||||||
@@ -45,9 +45,8 @@ internal class XrealLink internal constructor(
|
|||||||
if (msgId == VitureProtocol.MSG_GET_IMU) return true
|
if (msgId == VitureProtocol.MSG_GET_IMU) return true
|
||||||
val valid = when (msgId) {
|
val valid = when (msgId) {
|
||||||
VitureProtocol.MSG_GET_DISPLAY -> true
|
VitureProtocol.MSG_GET_DISPLAY -> true
|
||||||
VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ
|
VitureProtocol.MSG_DISPLAY -> model.supportsDisplayMode(value)
|
||||||
else value in 2..5 || value == XrealModel.NATIVE_60HZ
|
VitureProtocol.MSG_BRIGHTNESS -> model.hardwareControls && value in 0..model.brightnessMax
|
||||||
VitureProtocol.MSG_BRIGHTNESS -> !model.stereoOnlyControl && value in 0..9
|
|
||||||
VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1
|
VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1
|
||||||
else -> false
|
else -> false
|
||||||
}
|
}
|
||||||
@@ -64,12 +63,12 @@ internal class XrealLink internal constructor(
|
|||||||
channels = connector.connect()
|
channels = connector.connect()
|
||||||
connection.set(channels)
|
connection.set(channels)
|
||||||
if (!running) break
|
if (!running) break
|
||||||
val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl)
|
val control = XrealControl(channels, model = model)
|
||||||
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
|
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
|
||||||
val current = channels
|
val current = channels
|
||||||
reports = Thread({
|
reports = Thread({
|
||||||
try {
|
try {
|
||||||
var filter = XrealOrientationFilter(model.flipsYz)
|
var filter = XrealOrientationFilter(model)
|
||||||
var wasTracking = false
|
var wasTracking = false
|
||||||
var lastSensor = System.nanoTime()
|
var lastSensor = System.nanoTime()
|
||||||
while (running && connection.get() === current) {
|
while (running && connection.get() === current) {
|
||||||
@@ -78,7 +77,7 @@ internal class XrealLink internal constructor(
|
|||||||
if (sample != null) {
|
if (sample != null) {
|
||||||
lastSensor = System.nanoTime()
|
lastSensor = System.nanoTime()
|
||||||
val enabled = tracking
|
val enabled = tracking
|
||||||
if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz)
|
if (enabled && !wasTracking) filter = XrealOrientationFilter(model)
|
||||||
wasTracking = enabled
|
wasTracking = enabled
|
||||||
if (enabled) filter.update(sample)?.let {
|
if (enabled) filter.update(sample)?.let {
|
||||||
if (running && ready && tracking && connection.get() === current)
|
if (running && ready && tracking && connection.get() === current)
|
||||||
@@ -155,8 +154,9 @@ internal class XrealLink internal constructor(
|
|||||||
internal class XrealControl(
|
internal class XrealControl(
|
||||||
private val channels: XrealChannels,
|
private val channels: XrealChannels,
|
||||||
private val settleDelayMs: Long = 150,
|
private val settleDelayMs: Long = 150,
|
||||||
private val stereoOnly: Boolean = false,
|
private val model: XrealModel = XrealModel.ONE_S,
|
||||||
) {
|
) {
|
||||||
|
private val stereoOnly get() = model.stereoOnlyControl
|
||||||
private var transaction = 0
|
private var transaction = 0
|
||||||
private fun exchange(command: Int, value: Int? = null): ByteArray {
|
private fun exchange(command: Int, value: Int? = null): ByteArray {
|
||||||
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
|
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
|
||||||
@@ -172,7 +172,7 @@ internal class XrealControl(
|
|||||||
fun display(): Int {
|
fun display(): Int {
|
||||||
if (stereoOnly) return stereoDisplay()
|
if (stereoOnly) return stereoDisplay()
|
||||||
val reply = exchange(XrealProtocol.GET_DISPLAY)
|
val reply = exchange(XrealProtocol.GET_DISPLAY)
|
||||||
return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ }
|
return XrealProtocol.numeric(reply)?.takeIf(model::supportsDisplayMode)
|
||||||
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
|
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
|
||||||
}
|
}
|
||||||
private fun stereoDisplay(): Int {
|
private fun stereoDisplay(): Int {
|
||||||
@@ -187,6 +187,7 @@ internal class XrealControl(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
fun changeDisplay(mode: Int): Int {
|
fun changeDisplay(mode: Int): Int {
|
||||||
|
require(model.supportsDisplayMode(mode))
|
||||||
val stereo = mode == 5
|
val stereo = mode == 5
|
||||||
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
|
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
|
||||||
val current = awaitDisplay { (it == 5) == stereo }
|
val current = awaitDisplay { (it == 5) == stereo }
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ internal class XrealModel private constructor(
|
|||||||
override val name: String,
|
override val name: String,
|
||||||
val family: Family,
|
val family: Family,
|
||||||
override val diagonalFovDeg: Float,
|
override val diagonalFovDeg: Float,
|
||||||
|
private val native60Hz: Int = NATIVE_60HZ,
|
||||||
) : GlassesModel {
|
) : GlassesModel {
|
||||||
enum class Family {
|
enum class Family {
|
||||||
ONE_S,
|
ONE_S,
|
||||||
@@ -14,23 +15,25 @@ internal class XrealModel private constructor(
|
|||||||
override val controllable = true
|
override val controllable = true
|
||||||
override val brightnessMax = 9
|
override val brightnessMax = 9
|
||||||
override val volumeMax = 0
|
override val volumeMax = 0
|
||||||
override val hasSunblock get() = family == Family.ONE_S
|
override val hasSunblock get() = !stereoOnlyControl
|
||||||
override val hardwareControls get() = family == Family.ONE_S
|
override val hardwareControls get() = !stereoOnlyControl
|
||||||
override val sbs90 = false
|
override val sbs90 = false
|
||||||
override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60)
|
override val rates2d get() = if (stereoOnlyControl) listOf(60) else super.rates2d
|
||||||
|
|
||||||
// Only the 1S has been exercised with SET_DISPLAY; the Aura is known to reboot on an unexpected index.
|
val stereoOnlyControl get() = family != Family.ONE_S && this !== ONE_PRO_PLUS
|
||||||
val stereoOnlyControl get() = family != Family.ONE_S
|
|
||||||
|
internal fun supportsDisplayMode(mode: Int) = if (stereoOnlyControl) mode == 5 || mode == native60Hz
|
||||||
|
else mode in 3..5 || mode == native60Hz || (this === ONE_S && mode == 2)
|
||||||
|
|
||||||
// The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it.
|
// The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it.
|
||||||
val flipsYz get() = family != Family.AURA
|
val flipsYz get() = family != Family.AURA
|
||||||
|
|
||||||
override fun mode(hz: Int, sbs: Boolean) = when {
|
override fun mode(hz: Int, sbs: Boolean) = when {
|
||||||
sbs -> 5
|
sbs -> 5
|
||||||
stereoOnlyControl -> NATIVE_60HZ
|
stereoOnlyControl -> native60Hz
|
||||||
hz >= 120 -> 4
|
hz >= 120 -> 4
|
||||||
hz >= 90 -> 3
|
hz >= 90 -> 3
|
||||||
else -> NATIVE_60HZ
|
else -> native60Hz
|
||||||
}
|
}
|
||||||
override fun modeForStep(step: Int): Int? = null
|
override fun modeForStep(step: Int): Int? = null
|
||||||
|
|
||||||
@@ -44,7 +47,7 @@ internal class XrealModel private constructor(
|
|||||||
val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f)
|
val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f)
|
||||||
val ONE = XrealModel("XREAL One", Family.ONE, 50f)
|
val ONE = XrealModel("XREAL One", Family.ONE, 50f)
|
||||||
val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f)
|
val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f)
|
||||||
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f)
|
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f, 9)
|
||||||
val AURA = XrealModel("XREAL Aura", Family.AURA, 70f)
|
val AURA = XrealModel("XREAL Aura", Family.AURA, 70f)
|
||||||
|
|
||||||
// The odd product ids one below these are the glasses' recovery mode.
|
// The odd product ids one below these are the glasses' recovery mode.
|
||||||
|
|||||||
@@ -2,13 +2,18 @@ package com.droiddeck.launcher.glasses
|
|||||||
|
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
|
|
||||||
internal class XrealOrientationFilter(private val flipYz: Boolean = true) {
|
internal class XrealOrientationFilter(private val model: XrealModel = XrealModel.ONE_S) {
|
||||||
private val fusion = ImuFusion()
|
private val fusion = ImuFusion()
|
||||||
|
private val sensorToDisplay = if (model === XrealModel.ONE_PRO_PLUS)
|
||||||
|
Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.toRadians(35.0).toFloat()) else null
|
||||||
|
|
||||||
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
|
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
|
||||||
sample.accel.headAxes(), sample.gyro.headAxes())
|
sample.accel.headAxes(), sample.gyro.headAxes())
|
||||||
|
|
||||||
private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this
|
private fun Vec3.headAxes(): Vec3 {
|
||||||
|
val display = sensorToDisplay?.rotate(this) ?: this
|
||||||
|
return if (model.flipsYz) Vec3(display.x, -display.y, -display.z) else display
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class ImuFusion {
|
internal class ImuFusion {
|
||||||
|
|||||||
@@ -7,29 +7,50 @@ object SocNames {
|
|||||||
"SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870",
|
"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",
|
"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",
|
"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",
|
"SM8635" to "Snapdragon 8s Gen 3", "SM8735" to "Snapdragon 8s Gen 4",
|
||||||
|
"SM8750" to "Snapdragon 8 Elite", "SM8750P" to "Snapdragon 8 Elite",
|
||||||
|
"SM8850" to "Snapdragon 8 Elite Gen 5",
|
||||||
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
|
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
|
||||||
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
||||||
|
"SM7675" to "Snapdragon 7+ Gen 3",
|
||||||
"SM6375" to "Snapdragon 695",
|
"SM6375" to "Snapdragon 695",
|
||||||
|
// Handheld parts: AYANEO Pocket FIT (SG8350P), Retroid Pocket Duo (CQ7790S).
|
||||||
|
"SG8350P" to "Snapdragon G3 Gen 3", "CQ7790S" to "Dragonwing Q-7790",
|
||||||
)
|
)
|
||||||
|
|
||||||
private val PLATFORMS = mapOf(
|
private val PLATFORMS = mapOf(
|
||||||
"msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888",
|
"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",
|
"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",
|
"pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite", "canoe" to "Snapdragon 8 Elite Gen 5",
|
||||||
)
|
)
|
||||||
|
|
||||||
fun model(prop: (String) -> String = GpuInfo::systemProperty): String {
|
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 ""
|
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"))
|
return listOf(prop("ro.soc.model"), prop("ro.vendor.qti.soc_model"), sdk, prop("ro.fota.platform"))
|
||||||
.map { it.trim() }
|
.map { it.trim() }
|
||||||
.firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
|
.firstOrNull { it.isNotEmpty() && !it.equals(Build.UNKNOWN, ignoreCase = true) && !Regex("(?i)^msm_\\d").containsMatchIn(it) }
|
||||||
|
.orEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
|
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
|
||||||
|
|
||||||
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
|
/**
|
||||||
MODELS[normalizedModel(model)] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
* The exact model's name; the board platform's family only for an empty model or a phone "SM" part, since
|
||||||
|
* different chips share a platform (the Retroid Pocket Duo's CQ7790S and the Snapdragon 8 Elite are both "sun").
|
||||||
|
*/
|
||||||
|
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? {
|
||||||
|
val m = normalizedModel(model)
|
||||||
|
MODELS[m]?.let { return it }
|
||||||
|
if (m.isNotEmpty() && !m.startsWith("SM")) return null
|
||||||
|
return PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without label's platform-family guess: a rebadged chip such as the Duo's CQ7790S reports a platform it is not.
|
||||||
|
fun plainName(model: String = model(), maker: String = manufacturer()): String =
|
||||||
|
MODELS[normalizedModel(model)]?.let { "$it ($model)" } ?: "$maker $model".trim()
|
||||||
|
|
||||||
|
private fun manufacturer(): String =
|
||||||
|
if (Build.VERSION.SDK_INT >= 31) Build.SOC_MANUFACTURER.takeIf { it != Build.UNKNOWN }.orEmpty() else ""
|
||||||
|
|
||||||
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
|
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
|
||||||
val name = name(model, platform)
|
val name = name(model, platform)
|
||||||
|
|||||||
@@ -308,8 +308,7 @@ public final class TurnipDriver {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (chosen != null && !chosen.isEmpty()) {
|
if (chosen != null && !chosen.isEmpty()) {
|
||||||
if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))
|
if (SessionPrefs.INSTANCE.displayDriverFromAuto(context)
|
||||||
&& SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen)
|
|
||||||
&& gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) {
|
&& gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) {
|
||||||
Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system");
|
Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system");
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -44,6 +44,35 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
private var protonPid = 0
|
private var protonPid = 0
|
||||||
private var proton = ""
|
private var proton = ""
|
||||||
@Volatile private var lastWindow: String? = null
|
@Volatile private var lastWindow: String? = null
|
||||||
|
@Volatile private var lastCompositorFrameNanos = 0L
|
||||||
|
@Volatile private var lastVisibilityGameActive = false
|
||||||
|
private var candidateGameActive = false
|
||||||
|
private var candidateGameActiveSinceNs = 0L
|
||||||
|
private var stableGameActive = false
|
||||||
|
|
||||||
|
private fun isGameActive(): Boolean {
|
||||||
|
val now = System.nanoTime()
|
||||||
|
val compositorLive = lastCompositorFrameNanos > 0L &&
|
||||||
|
now - lastCompositorFrameNanos <= 1_000_000_000L
|
||||||
|
val detected = if (feed.live) {
|
||||||
|
feed.steamFocusKnown && !feed.steamFocused
|
||||||
|
} else {
|
||||||
|
compositorLive
|
||||||
|
}
|
||||||
|
|
||||||
|
if (detected != candidateGameActive) {
|
||||||
|
candidateGameActive = detected
|
||||||
|
candidateGameActiveSinceNs = now
|
||||||
|
}
|
||||||
|
|
||||||
|
if (detected != stableGameActive &&
|
||||||
|
now - candidateGameActiveSinceNs >= GAME_ACTIVITY_STABLE_NS
|
||||||
|
) {
|
||||||
|
stableGameActive = detected
|
||||||
|
}
|
||||||
|
|
||||||
|
return stableGameActive
|
||||||
|
}
|
||||||
|
|
||||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||||
|
|
||||||
@@ -66,6 +95,12 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onGameFrame() {
|
override fun onGameFrame() {
|
||||||
|
if (feed.live && (!feed.steamFocusKnown || feed.steamFocused)) return
|
||||||
|
lastCompositorFrameNanos = System.nanoTime()
|
||||||
|
feed.onCompositorFrame(lastCompositorFrameNanos)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCompositorFrame() {
|
||||||
feed.onCompositorFrame(System.nanoTime())
|
feed.onCompositorFrame(System.nanoTime())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,7 +108,9 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
private val frameCallback = object : Choreographer.FrameCallback {
|
private val frameCallback = object : Choreographer.FrameCallback {
|
||||||
override fun doFrame(frameTimeNanos: Long) {
|
override fun doFrame(frameTimeNanos: Long) {
|
||||||
if (!running || !polling) return
|
if (!running || !polling) return
|
||||||
|
reconcileGameActivity()
|
||||||
if (feed.poll(System.nanoTime())) view?.onFrames()
|
if (feed.poll(System.nanoTime())) view?.onFrames()
|
||||||
|
reconcileGameActivity()
|
||||||
Choreographer.getInstance().postFrameCallback(this)
|
Choreographer.getInstance().postFrameCallback(this)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -151,7 +188,7 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
|
|
||||||
fun refresh() {
|
fun refresh() {
|
||||||
applyConfig()
|
applyConfig()
|
||||||
if (!enabled) stop() else if (!running) start()
|
if (!enabled) stop() else if (!running) start() else applyShown()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun start() {
|
fun start() {
|
||||||
@@ -181,14 +218,26 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
applyShown()
|
applyShown()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun reconcileGameActivity() {
|
||||||
|
if (!SessionPrefs.hudOnlyDuringGame(context)) {
|
||||||
|
lastVisibilityGameActive = isGameActive()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (isGameActive() != lastVisibilityGameActive) applyShown()
|
||||||
|
}
|
||||||
|
|
||||||
private fun applyShown() {
|
private fun applyShown() {
|
||||||
if (!running) return
|
if (!running) return
|
||||||
val show = !hidden && !backgrounded
|
val onlyDuringGame = SessionPrefs.hudOnlyDuringGame(context)
|
||||||
|
val gameActive = isGameActive()
|
||||||
|
val show = !hidden && !backgrounded && (!onlyDuringGame || gameActive)
|
||||||
view?.visibility = if (show) View.VISIBLE else View.GONE
|
view?.visibility = if (show) View.VISIBLE else View.GONE
|
||||||
showing = show
|
showing = show
|
||||||
if (show != polling) {
|
lastVisibilityGameActive = gameActive
|
||||||
polling = show
|
val shouldPoll = !hidden && !backgrounded && (show || onlyDuringGame)
|
||||||
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
|
if (shouldPoll != polling) {
|
||||||
|
polling = shouldPoll
|
||||||
|
if (shouldPoll) Choreographer.getInstance().postFrameCallback(frameCallback)
|
||||||
else Choreographer.getInstance().removeFrameCallback(frameCallback)
|
else Choreographer.getInstance().removeFrameCallback(frameCallback)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -532,6 +581,7 @@ class DroidDeckHudHost(context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
private const val GAME_ACTIVITY_STABLE_NS = 350_000_000L
|
||||||
private const val DOCK_OVERHANG = 0.4f
|
private const val DOCK_OVERHANG = 0.4f
|
||||||
private const val PREVIEW_FROM = 0.55f
|
private const val PREVIEW_FROM = 0.55f
|
||||||
private const val STRIP_PULL_ACROSS_DP = 360f
|
private const val STRIP_PULL_ACROSS_DP = 360f
|
||||||
|
|||||||
@@ -183,6 +183,8 @@ internal class GameFrameFeed(
|
|||||||
private set
|
private set
|
||||||
@Volatile var steamFocused = false
|
@Volatile var steamFocused = false
|
||||||
private set
|
private set
|
||||||
|
@Volatile var steamFocusKnown = false
|
||||||
|
private set
|
||||||
@Volatile var pid = 0
|
@Volatile var pid = 0
|
||||||
private set
|
private set
|
||||||
@Volatile var outputWidth = 0
|
@Volatile var outputWidth = 0
|
||||||
@@ -198,10 +200,16 @@ internal class GameFrameFeed(
|
|||||||
val compositorAdded = compositorFrames != seenCompositorFrames
|
val compositorAdded = compositorFrames != seenCompositorFrames
|
||||||
seenCompositorFrames = compositorFrames
|
seenCompositorFrames = compositorFrames
|
||||||
if (handle == 0L) {
|
if (handle == 0L) {
|
||||||
if (nowNs < nextOpenNs) return compositorAdded
|
if (nowNs < nextOpenNs) {
|
||||||
|
|
||||||
|
return compositorAdded
|
||||||
|
}
|
||||||
nextOpenNs = nowNs + REOPEN_NS
|
nextOpenNs = nowNs + REOPEN_NS
|
||||||
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
|
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
|
||||||
if (handle == 0L) return compositorAdded
|
if (handle == 0L) {
|
||||||
|
|
||||||
|
return compositorAdded
|
||||||
|
}
|
||||||
HudFrames.nativePoll(handle, frametimes, times)
|
HudFrames.nativePoll(handle, frametimes, times)
|
||||||
}
|
}
|
||||||
val n = HudFrames.nativePoll(handle, frametimes, times)
|
val n = HudFrames.nativePoll(handle, frametimes, times)
|
||||||
@@ -219,6 +227,7 @@ internal class GameFrameFeed(
|
|||||||
fromGamescope = false
|
fromGamescope = false
|
||||||
}
|
}
|
||||||
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
|
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
|
||||||
|
|
||||||
if (nowNs - lastInfoNs >= INFO_NS) {
|
if (nowNs - lastInfoNs >= INFO_NS) {
|
||||||
lastInfoNs = nowNs
|
lastInfoNs = nowNs
|
||||||
readInfo()
|
readInfo()
|
||||||
@@ -250,6 +259,7 @@ internal class GameFrameFeed(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun close() {
|
fun close() {
|
||||||
|
fromGamescope = false
|
||||||
if (handle != 0L) HudFrames.nativeClose(handle)
|
if (handle != 0L) HudFrames.nativeClose(handle)
|
||||||
handle = 0L
|
handle = 0L
|
||||||
}
|
}
|
||||||
@@ -265,6 +275,7 @@ internal class GameFrameFeed(
|
|||||||
outputHeight = info[2]
|
outputHeight = info[2]
|
||||||
refreshMilliHz = info[3]
|
refreshMilliHz = info[3]
|
||||||
steamFocused = info[4] != 0
|
steamFocused = info[4] != 0
|
||||||
|
steamFocusKnown = true
|
||||||
engine = engineLabel(name)
|
engine = engineLabel(name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
internal class AxisPacing(private val intervalMs: Long) {
|
||||||
|
private var lastWriteAt = 0L
|
||||||
|
private var written = false
|
||||||
|
private var heldUntil = NOT_HELD
|
||||||
|
|
||||||
|
fun dueAt(now: Long, axesOnly: Boolean): Long =
|
||||||
|
if (axesOnly && written && now - lastWriteAt < intervalMs) lastWriteAt + intervalMs else now
|
||||||
|
|
||||||
|
fun wrote(at: Long) {
|
||||||
|
lastWriteAt = at
|
||||||
|
written = true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hold(due: Long): Boolean {
|
||||||
|
if (heldUntil != NOT_HELD) return false
|
||||||
|
heldUntil = due
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun release(now: Long): Boolean {
|
||||||
|
if (heldUntil == NOT_HELD || now < heldUntil) return false
|
||||||
|
heldUntil = NOT_HELD
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancel(): Boolean {
|
||||||
|
if (heldUntil == NOT_HELD) return false
|
||||||
|
heldUntil = NOT_HELD
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val NOT_HELD = Long.MIN_VALUE
|
||||||
|
|
||||||
|
@JvmStatic fun keepsMoving(before: Int, after: Int): Boolean = before == after || (before != 0 && after != 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
import android.graphics.Rect
|
||||||
|
import android.util.DisplayMetrics
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
internal class ControllerOverlayGeometry(
|
||||||
|
width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float,
|
||||||
|
) {
|
||||||
|
private val w = width.toFloat()
|
||||||
|
private val h = height.toFloat()
|
||||||
|
private val density = metrics.density
|
||||||
|
private val dpi = metrics.ydpi.takeIf { it in metrics.densityDpi * .6f..metrics.densityDpi * 1.6f }
|
||||||
|
?: metrics.densityDpi.toFloat()
|
||||||
|
private val fit = minOf(
|
||||||
|
min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)),
|
||||||
|
(w - safe.left - safe.right).coerceAtLeast(1f) / 1200f,
|
||||||
|
(h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f,
|
||||||
|
)
|
||||||
|
private val unit = fit * min(scale, 1f)
|
||||||
|
private val size = fit * scale
|
||||||
|
|
||||||
|
private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float {
|
||||||
|
val low = start + value * unit
|
||||||
|
val high = extent - end - (reference - value) * unit
|
||||||
|
return when {
|
||||||
|
value < reference / 3f -> low
|
||||||
|
value > reference * 2f / 3f -> high
|
||||||
|
else -> (extent / 2f + (value - reference / 2f) * unit).coerceIn(low, max(low, high))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun x(ref: Float) = anchor(ref, 1600f, w, safe.left, safe.right)
|
||||||
|
|
||||||
|
private fun y(ref: Float) = max(safe.top + ref * unit, h - safe.bottom - (900f - ref) * unit)
|
||||||
|
|
||||||
|
fun place(elements: List<InputSurfaceElement>, kit: PadKit, rearButtons: Boolean, trackpads: Boolean): List<InputSurfaceElement> {
|
||||||
|
if (!kit.steam) return placeStandardPad(elements, kit)
|
||||||
|
val leftEdge = safe.left + 52f * density
|
||||||
|
val middle = (w + safe.left - safe.right) / 2f
|
||||||
|
val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
|
||||||
|
val row = fitRow(listOfNotNull(keyboard,
|
||||||
|
Box(max(x(370f), leftEdge + 66f * size), y(852f), 66f, 30f),
|
||||||
|
Box(middle - 140f * unit, y(850f), 46f, 26f),
|
||||||
|
Box(middle + 140f * unit, y(850f), 46f, 26f),
|
||||||
|
Box(x(1230f), y(852f), 66f, 30f)), leftEdge)
|
||||||
|
val (guide, select, start, qam) = row.takeLast(4)
|
||||||
|
val positions = shoulders() + face(1375f, 345f, 96f) + mapOf(
|
||||||
|
InputControl.UP to Box(x(220f), y(345f) - 102.5f * size, 55.5f, 47.5f),
|
||||||
|
InputControl.RIGHT to Box(x(220f) + 102.5f * size, y(345f), 47.5f, 55.5f),
|
||||||
|
InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * size, 55.5f, 47.5f),
|
||||||
|
InputControl.LEFT to Box(x(220f) - 102.5f * size, y(345f), 47.5f, 55.5f),
|
||||||
|
InputControl.LS to Box(x(290f), y(640f), 96f),
|
||||||
|
InputControl.RS to Box(x(1310f), y(640f), 96f),
|
||||||
|
InputControl.SELECT to select,
|
||||||
|
InputControl.START to start,
|
||||||
|
InputControl.GUIDE to guide,
|
||||||
|
InputControl.QAM to qam,
|
||||||
|
)
|
||||||
|
val rear = mapOf(
|
||||||
|
InputControl.L4 to Box(x(30f), y(470f), 30f, 58f),
|
||||||
|
InputControl.L5 to Box(x(30f), y(590f), 30f, 58f),
|
||||||
|
InputControl.R4 to Box(x(1570f), y(470f), 30f, 58f),
|
||||||
|
InputControl.R5 to Box(x(1570f), y(590f), 30f, 58f),
|
||||||
|
)
|
||||||
|
val pads = mapOf(
|
||||||
|
InputControl.LEFT_PAD to Box(x(470f), y(360f), 88f),
|
||||||
|
InputControl.RIGHT_PAD to Box(x(1130f), y(360f), 88f),
|
||||||
|
)
|
||||||
|
val optional = rear.filterKeys { rearButtons } + pads.filterKeys { trackpads }
|
||||||
|
val placed = elements.mapNotNull { element ->
|
||||||
|
when {
|
||||||
|
element.id == KEYBOARD -> row.first().place(element)
|
||||||
|
element.id != "legacy:${element.control.id}" -> element
|
||||||
|
element.control in rear || element.control in pads -> optional[element.control]?.place(element)
|
||||||
|
else -> positions[element.control]?.place(element) ?: element
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val chosen = placed.filter { it.id == "legacy:${it.control.id}" }.map { it.control }
|
||||||
|
return placed + optional.mapNotNull { (control, box) ->
|
||||||
|
if (chosen.any { if (control in rear) it in rear else it in pads }) null else box.place(InputSurfaceElement(control,
|
||||||
|
0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun placeStandardPad(elements: List<InputSurfaceElement>, kit: PadKit): List<InputSurfaceElement> {
|
||||||
|
val leftEdge = safe.left + 52f * density
|
||||||
|
val middle = (w + safe.left - safe.right) / 2f
|
||||||
|
val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
|
||||||
|
val controls = if (kit.playStation) listOf(
|
||||||
|
InputControl.QAM to Box(x(220f), y(848f), 46f),
|
||||||
|
InputControl.SELECT to Box(middle - 160f * unit, y(850f), 50f, 30f),
|
||||||
|
InputControl.GUIDE to Box(middle, y(850f), 46f),
|
||||||
|
InputControl.START to Box(middle + 160f * unit, y(850f), 50f, 30f),
|
||||||
|
) else listOf(
|
||||||
|
InputControl.QAM to Box(x(220f), y(848f), 46f),
|
||||||
|
InputControl.SELECT to Box(middle - 110f * unit, y(850f), 38f),
|
||||||
|
InputControl.GUIDE to Box(middle, y(850f), 46f),
|
||||||
|
InputControl.START to Box(middle + 110f * unit, y(850f), 38f),
|
||||||
|
)
|
||||||
|
val row = fitRow(listOfNotNull(keyboard) + controls.map { it.second }, leftEdge)
|
||||||
|
val positions = controls.map { it.first }.zip(row.takeLast(controls.size)).toMap() + shoulders() +
|
||||||
|
if (kit.playStation) {
|
||||||
|
face(1350f, 395f, 96f) + dpad(250f, 395f, 125f, kit.dpad) + mapOf(
|
||||||
|
InputControl.LS to Box(x(565f), y(690f), 100f),
|
||||||
|
InputControl.RS to Box(x(1035f), y(690f), 100f),
|
||||||
|
InputControl.L3 to Box(x(565f) - 135f * size, y(690f) - 100f * size, 42f),
|
||||||
|
InputControl.R3 to Box(x(1035f) + 135f * size, y(690f) - 100f * size, 42f),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
face(1375f, 400f, 94f) + dpad(470f, 675f, 118f, kit.dpad) + mapOf(
|
||||||
|
InputControl.LS to Box(x(235f), y(400f), 104f),
|
||||||
|
InputControl.RS to Box(x(1130f), y(690f), 104f),
|
||||||
|
InputControl.L3 to Box(x(235f) + 150f * size, y(400f) - 110f * size, 42f),
|
||||||
|
InputControl.R3 to Box(x(1130f) + 160f * size, y(690f) + 100f * size, 42f),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return elements.map { element ->
|
||||||
|
when (element.id) {
|
||||||
|
KEYBOARD -> row.first().place(element)
|
||||||
|
"legacy:${element.control.id}" -> positions[element.control]?.place(element) ?: element
|
||||||
|
else -> element
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun shoulders() = mapOf(
|
||||||
|
InputControl.LT to Box(x(120f), y(96f), 80f, 34f),
|
||||||
|
InputControl.LB to Box(x(310f), y(96f), 80f, 34f),
|
||||||
|
InputControl.RB to Box(x(1290f), y(96f), 80f, 34f),
|
||||||
|
InputControl.RT to Box(x(1480f), y(96f), 80f, 34f),
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun face(cx: Float, cy: Float, offset: Float) = mapOf(
|
||||||
|
InputControl.Y to Box(x(cx), y(cy) - offset * size, 58f),
|
||||||
|
InputControl.X to Box(x(cx) - offset * size, y(cy), 58f),
|
||||||
|
InputControl.B to Box(x(cx) + offset * size, y(cy), 58f),
|
||||||
|
InputControl.A to Box(x(cx), y(cy) + offset * size, 58f),
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun dpad(cx: Float, cy: Float, radius: Float, style: DpadStyle): Map<InputControl, Box> {
|
||||||
|
val inner = radius * if (style == DpadStyle.DISC) .25f else .14f
|
||||||
|
val depth = (radius - inner) / 2f
|
||||||
|
val offset = (radius - depth) * size
|
||||||
|
val side = radius * .25f
|
||||||
|
return mapOf(
|
||||||
|
InputControl.UP to Box(x(cx), y(cy) - offset, side, depth),
|
||||||
|
InputControl.RIGHT to Box(x(cx) + offset, y(cy), depth, side),
|
||||||
|
InputControl.DOWN to Box(x(cx), y(cy) + offset, side, depth),
|
||||||
|
InputControl.LEFT to Box(x(cx) - offset, y(cy), depth, side),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fitRow(row: List<Box>, start: Float): List<Box> {
|
||||||
|
val end = w - safe.right
|
||||||
|
val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density)
|
||||||
|
var edge = start - gap
|
||||||
|
val pushed = row.map { box -> box.at(max(box.cx, edge + gap + box.width / 2f)).also { edge = it.cx + it.width / 2f } }
|
||||||
|
edge = end + gap
|
||||||
|
return pushed.asReversed().map { box -> box.at(min(box.cx, edge - gap - box.width / 2f)).also { edge = it.cx - it.width / 2f } }.asReversed()
|
||||||
|
}
|
||||||
|
|
||||||
|
private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) {
|
||||||
|
val width get() = max(hw * 2f * size, w * .03f)
|
||||||
|
|
||||||
|
fun at(cx: Float) = Box(cx, cy, hw, hh)
|
||||||
|
|
||||||
|
fun place(element: InputSurfaceElement): InputSurfaceElement {
|
||||||
|
val height = max(hh * 2f * size, h * .03f)
|
||||||
|
return element.copy(
|
||||||
|
x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w,
|
||||||
|
y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h,
|
||||||
|
width = width / w, height = height / h,
|
||||||
|
).bounded()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val KEYBOARD = "builtin:keyboard"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
import android.graphics.Rect
|
||||||
|
import com.droiddeck.launcher.input.GamepadGeometry.Box
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
internal class ControllerPortraitGeometry(
|
||||||
|
private val width: Float,
|
||||||
|
private val height: Float,
|
||||||
|
private val safe: Rect,
|
||||||
|
private val density: Float,
|
||||||
|
) {
|
||||||
|
fun place(
|
||||||
|
elements: List<InputSurfaceElement>, kit: PadKit, docked: Boolean, scale: Float,
|
||||||
|
rearButtons: Boolean, trackpads: Boolean,
|
||||||
|
): List<InputSurfaceElement> {
|
||||||
|
val w = width - safe.left - safe.right
|
||||||
|
val h = height - safe.top - safe.bottom
|
||||||
|
if (w <= 0 || h <= 0) return elements
|
||||||
|
val presented = elements.toMutableList()
|
||||||
|
val buttons = mutableMapOf<String, Box>()
|
||||||
|
val rear = presented.filter { it.control in REAR && isStock(it) }
|
||||||
|
val pads = presented.filter { it.control.isTrackpad && isStock(it) }
|
||||||
|
if (!docked && kit.steam) {
|
||||||
|
if (!rearButtons) presented.removeAll(rear) else if (rear.isEmpty()) REAR.forEach { addOptional(presented, it) }
|
||||||
|
if (!trackpads) presented.removeAll(pads) else if (pads.isEmpty()) {
|
||||||
|
addOptional(presented, InputControl.LEFT_PAD)
|
||||||
|
addOptional(presented, InputControl.RIGHT_PAD)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun put(control: InputControl, box: Box) { buttons["legacy:${control.id}"] = box }
|
||||||
|
val reserve = if (docked) 0f else min(60f * density, h * .15f)
|
||||||
|
val panel = if (docked) h else min(minOf(h * .60f, w * 1.15f, PANEL_DP * density) * scale, h - reserve)
|
||||||
|
val top = height - safe.bottom - reserve - panel
|
||||||
|
val unit = min(density, min(w / 275f, panel / 300f))
|
||||||
|
val pad = 8f * unit
|
||||||
|
val gap = 8f * unit
|
||||||
|
val buttonHeight = 44f * unit
|
||||||
|
val shoulders = if (docked) listOf(InputControl.LT, InputControl.LB, InputControl.SELECT, InputControl.START, InputControl.RB, InputControl.RT)
|
||||||
|
else listOf(InputControl.LT, InputControl.LB, InputControl.RB, InputControl.RT)
|
||||||
|
fun row(controls: List<InputControl>, y: Float, rowHeight: Float, spacing: Float) {
|
||||||
|
val cell = (w - 2f * pad - (controls.size - 1) * spacing) / controls.size
|
||||||
|
controls.forEachIndexed { index, control ->
|
||||||
|
put(control, Box(safe.left + pad + cell / 2f + index * (cell + spacing), y, cell, rowHeight))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit)
|
||||||
|
var bodyTop = top + pad + buttonHeight + gap
|
||||||
|
if (presented.any { it.control in REAR && isStock(it) }) {
|
||||||
|
val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight)
|
||||||
|
row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap)
|
||||||
|
bodyTop += rearHeight + gap
|
||||||
|
}
|
||||||
|
val floor = height - safe.bottom - reserve - pad
|
||||||
|
val bodyHeight = floor - bodyTop - gap
|
||||||
|
if (bodyHeight <= 0f) return elements
|
||||||
|
val hasLeftPad = presented.any { it.control == InputControl.LEFT_PAD && isStock(it) }
|
||||||
|
val hasRightPad = presented.any { it.control == InputControl.RIGHT_PAD && isStock(it) }
|
||||||
|
val hasLeftStick = presented.any { it.control == InputControl.LS && isStock(it) }
|
||||||
|
val hasRightStick = presented.any { it.control == InputControl.RS && isStock(it) }
|
||||||
|
val four = hasLeftPad && hasLeftStick || hasRightPad && hasRightStick
|
||||||
|
val main = min(w * .46f, bodyHeight * .53f)
|
||||||
|
val second = min(w * .42f, bodyHeight - main)
|
||||||
|
val mainY = floor - main / 2f
|
||||||
|
val secondY = bodyTop + second / 2f
|
||||||
|
val left = safe.left + w * .25f
|
||||||
|
val right = safe.left + w * .75f
|
||||||
|
if (four) {
|
||||||
|
val col = (w - 2f * pad - 3f * gap) / 4f
|
||||||
|
val stick = min(col, main)
|
||||||
|
put(InputControl.LEFT_PAD, Box(safe.left + pad + col * .5f, mainY, col, main))
|
||||||
|
put(InputControl.LS, Box(safe.left + pad + col * 1.5f + gap, mainY, stick, stick))
|
||||||
|
put(InputControl.RS, Box(safe.left + w - pad - col * 1.5f - gap, mainY, stick, stick))
|
||||||
|
put(InputControl.RIGHT_PAD, Box(safe.left + w - pad - col * .5f, mainY, col, main))
|
||||||
|
} else {
|
||||||
|
put(if (hasLeftPad) InputControl.LEFT_PAD else InputControl.LS, Box(left, mainY, main, main))
|
||||||
|
put(if (hasRightPad) InputControl.RIGHT_PAD else InputControl.RS, Box(right, mainY, main, main))
|
||||||
|
}
|
||||||
|
val radius = second / 2f
|
||||||
|
val armWidth = radius * if (kit.dpad == DpadStyle.CROSS) .37f else .25f
|
||||||
|
val inner = if (kit.dpad == DpadStyle.ARROWS) radius * .14f else armWidth
|
||||||
|
val depth = radius - inner
|
||||||
|
val distance = (radius + inner) / 2f
|
||||||
|
put(InputControl.UP, Box(left, secondY - distance, armWidth * 2f, depth))
|
||||||
|
put(InputControl.RIGHT, Box(left + distance, secondY, depth, armWidth * 2f))
|
||||||
|
put(InputControl.DOWN, Box(left, secondY + distance, armWidth * 2f, depth))
|
||||||
|
put(InputControl.LEFT, Box(left - distance, secondY, depth, armWidth * 2f))
|
||||||
|
val face = second * .34f
|
||||||
|
val spread = second * .30f
|
||||||
|
put(InputControl.Y, Box(right, secondY - spread, face, face))
|
||||||
|
put(InputControl.X, Box(right - spread, secondY, face, face))
|
||||||
|
put(InputControl.B, Box(right + spread, secondY, face, face))
|
||||||
|
put(InputControl.A, Box(right, secondY + spread, face, face))
|
||||||
|
if (!docked) {
|
||||||
|
val ids = listOf(KEYBOARD, "legacy:guide", "legacy:select", "legacy:start", "legacy:qam")
|
||||||
|
.filter { id -> presented.any { it.id == id } }
|
||||||
|
val inset = min(52f * density, w * .17f)
|
||||||
|
val rowWidth = (w - inset - pad - gap * (ids.size - 1)) / ids.size.coerceAtLeast(1)
|
||||||
|
val rowHeight = min(reserve * .8f, 44f * unit)
|
||||||
|
ids.forEachIndexed { i, id ->
|
||||||
|
val center = safe.left + inset + rowWidth / 2f + i * (rowWidth + gap)
|
||||||
|
buttons[id] = Box(center, height - safe.bottom - reserve / 2f, rowWidth, rowHeight)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return presented.map { element ->
|
||||||
|
val box = buttons[element.id]
|
||||||
|
if (box == null) element else element.copy(
|
||||||
|
x = box.left / width, y = box.top / height, width = box.width / width, height = box.height / height,
|
||||||
|
).bounded()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isStock(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}"
|
||||||
|
|
||||||
|
private fun addOptional(elements: MutableList<InputSurfaceElement>, control: InputControl) {
|
||||||
|
if (elements.none { it.control == control && isStock(it) }) {
|
||||||
|
elements += InputSurfaceElement(control, 0f, 0f, 0f, 0f, floating = false,
|
||||||
|
buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val KEYBOARD = "builtin:keyboard"
|
||||||
|
const val PANEL_DP = 504f
|
||||||
|
val REAR = listOf(InputControl.L4, InputControl.L5, InputControl.R5, InputControl.R4)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,8 @@ object DualScreen {
|
|||||||
const val MODE_AUTO = "auto"
|
const val MODE_AUTO = "auto"
|
||||||
const val MODE_ON = "on"
|
const val MODE_ON = "on"
|
||||||
const val MODE_OFF = "off"
|
const val MODE_OFF = "off"
|
||||||
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
|
const val MODE_SWAPPED = "swapped"
|
||||||
|
val modes = listOf(MODE_AUTO, MODE_ON, MODE_SWAPPED, MODE_OFF)
|
||||||
private const val TYPE_INTERNAL = 1
|
private const val TYPE_INTERNAL = 1
|
||||||
private const val TYPE_EXTERNAL = 2
|
private const val TYPE_EXTERNAL = 2
|
||||||
private val knownModels = setOf("retroid pocket duo", "ayn thor")
|
private val knownModels = setOf("retroid pocket duo", "ayn thor")
|
||||||
@@ -23,6 +24,14 @@ object DualScreen {
|
|||||||
@Volatile private var takenDisplays: Set<Int> = emptySet()
|
@Volatile private var takenDisplays: Set<Int> = emptySet()
|
||||||
private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
|
private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
|
||||||
|
|
||||||
|
fun menuOwnsController(open: Boolean, docked: Boolean, optIn: Boolean): Boolean = open && (!docked || optIn)
|
||||||
|
|
||||||
|
fun menuReturnsOnStart(selected: SecondScreenMode, menuWasShown: Boolean, menuUp: Boolean): Boolean =
|
||||||
|
!menuUp && (selected == SecondScreenMode.MENU || menuWasShown)
|
||||||
|
|
||||||
|
fun menuIdleOnBottom(open: Boolean, docked: Boolean, pinned: Boolean, optIn: Boolean): Boolean =
|
||||||
|
docked && (open || pinned) && !menuOwnsController(open, docked, optIn)
|
||||||
|
|
||||||
fun yieldsBottom(model: String): Boolean = model.trim().lowercase().let { m -> knownModels.any(m::startsWith) }
|
fun yieldsBottom(model: String): Boolean = model.trim().lowercase().let { m -> knownModels.any(m::startsWith) }
|
||||||
|
|
||||||
fun taken(displayId: Int): Boolean = displayId in takenDisplays
|
fun taken(displayId: Int): Boolean = displayId in takenDisplays
|
||||||
@@ -91,7 +100,7 @@ object DualScreen {
|
|||||||
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
|
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
|
||||||
when (mode) {
|
when (mode) {
|
||||||
MODE_OFF -> null
|
MODE_OFF -> null
|
||||||
MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
|
MODE_ON, MODE_SWAPPED -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
|
||||||
else -> if (dockedToDisplay(displayManager, primaryDisplayId)) null else builtInDisplay(displayManager, primaryDisplayId)
|
else -> if (dockedToDisplay(displayManager, primaryDisplayId)) null else builtInDisplay(displayManager, primaryDisplayId)
|
||||||
}?.takeUnless { taken(it.displayId) }
|
}?.takeUnless { taken(it.displayId) }
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
package com.droiddeck.launcher.input;
|
package com.droiddeck.launcher.input;
|
||||||
|
|
||||||
|
import android.os.Handler;
|
||||||
|
import android.os.HandlerThread;
|
||||||
|
import android.os.Process;
|
||||||
|
import android.os.SystemClock;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@@ -128,6 +132,16 @@ public class FakeInputWriter {
|
|||||||
|
|
||||||
private static final Object RING_LOCK = new Object();
|
private static final Object RING_LOCK = new Object();
|
||||||
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
|
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
|
||||||
|
private static final long AXIS_REPORT_INTERVAL_MS = 4;
|
||||||
|
|
||||||
|
private static final class Pacing {
|
||||||
|
static final Handler HANDLER;
|
||||||
|
static {
|
||||||
|
HandlerThread thread = new HandlerThread("pad-pacing", Process.THREAD_PRIORITY_DISPLAY);
|
||||||
|
thread.start();
|
||||||
|
HANDLER = new Handler(thread.getLooper());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static {
|
static {
|
||||||
System.loadLibrary("sdnative");
|
System.loadLibrary("sdnative");
|
||||||
@@ -156,6 +170,9 @@ public class FakeInputWriter {
|
|||||||
private boolean hasChanges = false;
|
private boolean hasChanges = false;
|
||||||
private boolean pendingFullResend = false;
|
private boolean pendingFullResend = false;
|
||||||
private boolean forceResend = false;
|
private boolean forceResend = false;
|
||||||
|
private final AxisPacing axisPacing = new AxisPacing(AXIS_REPORT_INTERVAL_MS);
|
||||||
|
private final PadState pacedPad = new PadState();
|
||||||
|
private final Runnable pacedWrite = this::writePacedPad;
|
||||||
|
|
||||||
public FakeInputWriter(String fakeInputPath, int slot) {
|
public FakeInputWriter(String fakeInputPath, int slot) {
|
||||||
this.slot = slot;
|
this.slot = slot;
|
||||||
@@ -711,10 +728,12 @@ public class FakeInputWriter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void close() {
|
public synchronized void close() {
|
||||||
|
cancelPacedWrite();
|
||||||
isOpen = false;
|
isOpen = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void reset() {
|
public synchronized void reset() {
|
||||||
|
cancelPacedWrite();
|
||||||
if (!isOpen && !open())
|
if (!isOpen && !open())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
@@ -822,6 +841,53 @@ public class FakeInputWriter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void writePad(PadState state) {
|
public synchronized void writePad(PadState state) {
|
||||||
|
long now = SystemClock.uptimeMillis();
|
||||||
|
long due = axisPacing.dueAt(now, !pendingFullResend && onlyAxesMove(state));
|
||||||
|
if (due > now) {
|
||||||
|
pacedPad.copyFrom(state);
|
||||||
|
if (axisPacing.hold(due))
|
||||||
|
Pacing.HANDLER.postAtTime(pacedWrite, due);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cancelPacedWrite();
|
||||||
|
writePadNow(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void writePacedPad() {
|
||||||
|
if (axisPacing.release(SystemClock.uptimeMillis()))
|
||||||
|
writePadNow(pacedPad);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cancelPacedWrite() {
|
||||||
|
if (axisPacing.cancel())
|
||||||
|
Pacing.HANDLER.removeCallbacks(pacedWrite);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean onlyAxesMove(PadState state) {
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
if (prevButtonStates[i] != state.isDown(i))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return prevButtonStates[SNAPSHOT_IDX_MODE] == state.isDown(PadState.GUIDE)
|
||||||
|
&& prevQam == state.isDown(PadState.QAM)
|
||||||
|
&& prevHatX == state.hatX() && prevHatY == state.hatY()
|
||||||
|
&& AxisPacing.keepsMoving(prevThumbLX, stickValue(state.leftX))
|
||||||
|
&& AxisPacing.keepsMoving(prevThumbLY, stickValue(state.leftY))
|
||||||
|
&& AxisPacing.keepsMoving(prevThumbRX, stickValue(state.rightX))
|
||||||
|
&& AxisPacing.keepsMoving(prevThumbRY, stickValue(state.rightY))
|
||||||
|
&& AxisPacing.keepsMoving(prevTriggerL, triggerValue(state.leftTrigger))
|
||||||
|
&& AxisPacing.keepsMoving(prevTriggerR, triggerValue(state.rightTrigger));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int stickValue(float value) {
|
||||||
|
return (int) (value * 32767);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int triggerValue(float value) {
|
||||||
|
return (int) (value * 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writePadNow(PadState state) {
|
||||||
if (!isOpen && !open())
|
if (!isOpen && !open())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
@@ -845,10 +911,10 @@ public class FakeInputWriter {
|
|||||||
hasChanges = true;
|
hasChanges = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
int lx = (int) (state.leftX * 32767);
|
int lx = stickValue(state.leftX);
|
||||||
int ly = (int) (state.leftY * 32767);
|
int ly = stickValue(state.leftY);
|
||||||
int rx = (int) (state.rightX * 32767);
|
int rx = stickValue(state.rightX);
|
||||||
int ry = (int) (state.rightY * 32767);
|
int ry = stickValue(state.rightY);
|
||||||
|
|
||||||
if (forceResend || lx != prevThumbLX) {
|
if (forceResend || lx != prevThumbLX) {
|
||||||
prevThumbLX = lx;
|
prevThumbLX = lx;
|
||||||
@@ -867,8 +933,8 @@ public class FakeInputWriter {
|
|||||||
writeEvent(EV_ABS, ABS_RY, ry);
|
writeEvent(EV_ABS, ABS_RY, ry);
|
||||||
}
|
}
|
||||||
|
|
||||||
int tl = (int) (state.leftTrigger * 255);
|
int tl = triggerValue(state.leftTrigger);
|
||||||
int tr = (int) (state.rightTrigger * 255);
|
int tr = triggerValue(state.rightTrigger);
|
||||||
if (forceResend || tl != prevTriggerL) {
|
if (forceResend || tl != prevTriggerL) {
|
||||||
prevTriggerL = tl;
|
prevTriggerL = tl;
|
||||||
writeEvent(EV_ABS, ABS_BRAKE, tl);
|
writeEvent(EV_ABS, ABS_BRAKE, tl);
|
||||||
@@ -895,6 +961,8 @@ public class FakeInputWriter {
|
|||||||
if (!flushBuffer()) {
|
if (!flushBuffer()) {
|
||||||
Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable");
|
Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable");
|
||||||
pendingFullResend = true;
|
pendingFullResend = true;
|
||||||
|
} else {
|
||||||
|
axisPacing.wrote(SystemClock.uptimeMillis());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
forceResend = false;
|
forceResend = false;
|
||||||
|
|||||||
@@ -27,8 +27,9 @@ internal class FloatingSteamOverlay(width: Int, height: Int, safe: Rect, density
|
|||||||
val lowered = if (lowerShortcuts) lower(visible) else visible
|
val lowered = if (lowerShortcuts) lower(visible) else visible
|
||||||
if (rearButtons != true && trackpads != true) return lowered
|
if (rearButtons != true && trackpads != true) return lowered
|
||||||
val placed = lowered.toMutableList()
|
val placed = lowered.toMutableList()
|
||||||
|
val chosen = lowered.filter(::isStock).map { it.control }
|
||||||
fun add(control: InputControl, x: Float, y: List<Float>, widthDp: Int, heightDp: Int, shape: InputButtonShape) {
|
fun add(control: InputControl, x: Float, y: List<Float>, widthDp: Int, heightDp: Int, shape: InputButtonShape) {
|
||||||
if (placed.any { it.id == "legacy:${control.id}" }) return
|
if (chosen.any { if (control in rear) it in rear else it.isTrackpad }) return
|
||||||
val element = InputSurfaceElement(control, 0f, 0f, (widthDp * dp / w).coerceAtLeast(.03f),
|
val element = InputSurfaceElement(control, 0f, 0f, (widthDp * dp / w).coerceAtLeast(.03f),
|
||||||
(heightDp * dp / h).coerceAtLeast(.03f), floating = false, buttonShape = shape, showLabel = !control.isTrackpad)
|
(heightDp * dp / h).coerceAtLeast(.03f), floating = false, buttonShape = shape, showLabel = !control.isTrackpad)
|
||||||
findSpace(element, x, y, placed)?.let(placed::add)
|
findSpace(element, x, y, placed)?.let(placed::add)
|
||||||
|
|||||||
@@ -3,6 +3,12 @@ package com.droiddeck.launcher.input
|
|||||||
import android.view.KeyEvent
|
import android.view.KeyEvent
|
||||||
|
|
||||||
object GuestKeys {
|
object GuestKeys {
|
||||||
|
fun normalizeKeyboardEscape(event: KeyEvent): KeyEvent {
|
||||||
|
if (!isKeyboardEscape(event.keyCode, event.scanCode)) return event
|
||||||
|
return KeyEvent(event.downTime, event.eventTime, event.action, KeyEvent.KEYCODE_ESCAPE,
|
||||||
|
event.repeatCount, event.metaState, event.deviceId, event.scanCode, event.flags, event.source)
|
||||||
|
}
|
||||||
|
|
||||||
/** Sends [event] as evdev presses, with Shift around characters typed by a keyboard that has no Shift key; false when it has no evdev code. */
|
/** Sends [event] as evdev presses, with Shift around characters typed by a keyboard that has no Shift key; false when it has no evdev code. */
|
||||||
fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean {
|
fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean {
|
||||||
val down = event.action == KeyEvent.ACTION_DOWN
|
val down = event.action == KeyEvent.ACTION_DOWN
|
||||||
|
|||||||
@@ -324,15 +324,27 @@ object InputLibraries {
|
|||||||
layout.copy(screen = screen)
|
layout.copy(screen = screen)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
private fun encodeElements(list: List<InputSurfaceElement>) = JSONArray().also { elements ->
|
||||||
|
for (e in list) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
|
||||||
|
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
|
||||||
|
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
|
||||||
|
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeElements(array: JSONArray) = array.objects(64).map { e ->
|
||||||
|
InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
|
||||||
|
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
|
||||||
|
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
|
||||||
|
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
|
||||||
|
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
|
||||||
|
}
|
||||||
|
|
||||||
internal fun encode(library: InputLibrary): String {
|
internal fun encode(library: InputLibrary): String {
|
||||||
val layouts = JSONArray()
|
val layouts = JSONArray()
|
||||||
for (layout in library.layouts) {
|
for (layout in library.layouts) {
|
||||||
val elements = JSONArray()
|
val encoded = JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", encodeElements(layout.elements))
|
||||||
for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
|
if (layout.rotated.isNotEmpty()) encoded.put("rotated", encodeElements(layout.rotated)).put("rotatedAspect", layout.rotatedAspect.toDouble()).put("rotatedScale", layout.rotatedScale.toDouble())
|
||||||
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
|
layouts.put(encoded
|
||||||
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
|
|
||||||
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
|
|
||||||
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
|
|
||||||
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
|
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
|
||||||
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
|
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
|
||||||
}
|
}
|
||||||
@@ -371,13 +383,7 @@ object InputLibraries {
|
|||||||
require(version in 2..VERSION || restore)
|
require(version in 2..VERSION || restore)
|
||||||
val generated = mutableSetOf<String>()
|
val generated = mutableSetOf<String>()
|
||||||
val layouts = doc.getJSONArray("layouts").objects(256).map { layout ->
|
val layouts = doc.getJSONArray("layouts").objects(256).map { layout ->
|
||||||
val stored = layout.getJSONArray("elements").objects(64).map { e ->
|
val stored = decodeElements(layout.getJSONArray("elements"))
|
||||||
InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
|
|
||||||
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
|
|
||||||
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
|
|
||||||
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
|
|
||||||
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
|
|
||||||
}
|
|
||||||
val id = layout.getString("id")
|
val id = layout.getString("id")
|
||||||
val origin = layout.optionalString("origin")
|
val origin = layout.optionalString("origin")
|
||||||
val followsGamepad = restore && !layout.optBoolean("kitless") &&
|
val followsGamepad = restore && !layout.optBoolean("kitless") &&
|
||||||
@@ -388,7 +394,8 @@ object InputLibraries {
|
|||||||
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
|
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
|
||||||
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
|
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
|
||||||
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin,
|
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin,
|
||||||
layout.optDouble("scale", 1.0).toFloat())
|
layout.optDouble("scale", 1.0).toFloat(), layout.optJSONArray("rotated")?.let(::decodeElements).orEmpty(),
|
||||||
|
layout.optDouble("rotatedAspect", 0.0).toFloat(), layout.optDouble("rotatedScale", layout.optDouble("scale", 1.0)).toFloat())
|
||||||
}
|
}
|
||||||
val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
|
val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
|
||||||
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
|
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
|
||||||
|
|||||||
@@ -22,8 +22,12 @@ data class SavedInputLayout(
|
|||||||
val aspect: Float = 0f,
|
val aspect: Float = 0f,
|
||||||
val origin: String? = null,
|
val origin: String? = null,
|
||||||
val scale: Float = 1f,
|
val scale: Float = 1f,
|
||||||
|
val rotated: List<InputSurfaceElement> = emptyList(),
|
||||||
|
val rotatedAspect: Float = 0f,
|
||||||
|
val rotatedScale: Float = 1f,
|
||||||
) {
|
) {
|
||||||
val editable get() = template == InputLayoutTemplate.CUSTOM
|
val editable get() = template == InputLayoutTemplate.CUSTOM
|
||||||
|
val overlay get() = (origin ?: id).let { it == InputLibraries.OVERLAY || it.startsWith("migrated.layout.") }
|
||||||
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
|
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
|
||||||
fun withQuickButton(button: InputCommand, shown: Boolean) =
|
fun withQuickButton(button: InputCommand, shown: Boolean) =
|
||||||
copy(style = style.copy(hidden = if (shown) style.hidden - button else style.hidden + button))
|
copy(style = style.copy(hidden = if (shown) style.hidden - button else style.hidden + button))
|
||||||
@@ -249,6 +253,8 @@ data class InputLibrary(
|
|||||||
for (layout in layouts) {
|
for (layout in layouts) {
|
||||||
require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS })
|
require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS })
|
||||||
require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f)
|
require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f)
|
||||||
|
require(layout.rotated.isEmpty() || layout.rotatedAspect.isFinite() && layout.rotatedAspect in .05f..20f && layout.rotatedScale.isFinite() && layout.rotatedScale in .5f..2f)
|
||||||
|
require(layout.rotated.size <= 64 && layout.rotated.all { r -> listOf(r.x, r.y, r.width, r.height).all { it.isFinite() } })
|
||||||
require(layout.scale.isFinite() && layout.scale in .5f..2f)
|
require(layout.scale.isFinite() && layout.scale in .5f..2f)
|
||||||
inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id })
|
inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id })
|
||||||
for (e in layout.elements) {
|
for (e in layout.elements) {
|
||||||
|
|||||||
@@ -53,14 +53,14 @@ data class InputProfile(
|
|||||||
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
|
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
|
||||||
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
|
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
|
||||||
|
|
||||||
fun showsMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
|
fun showsLeftMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
|
||||||
val action = elementAction(role, element.id, element.control).takeIf {
|
val action = elementAction(role, element.id, element.control).takeIf {
|
||||||
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
|
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
|
||||||
}
|
}
|
||||||
val click = elementClickAction(role, element).takeIf {
|
val click = elementClickAction(role, element).takeIf {
|
||||||
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
|
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
|
||||||
}
|
}
|
||||||
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) }
|
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.code == PointerGestures.BTN_LEFT }
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.input
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
enum class InputElementKind(val control: InputControl) {
|
enum class InputElementKind(val control: InputControl) {
|
||||||
BUTTON(InputControl.A), STICK(InputControl.LS), TRACKPAD(InputControl.LEFT_PAD),
|
BUTTON(InputControl.A), STICK(InputControl.LS), TRACKPAD(InputControl.LEFT_PAD),
|
||||||
@@ -63,6 +65,27 @@ internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceE
|
|||||||
width = w, height = h).bounded()
|
width = w, height = h).bounded()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
internal val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
|
||||||
|
internal val InputSurfaceElement.dpadPiece get() = id == "legacy:${control.id}" && control in DPAD
|
||||||
|
|
||||||
|
internal fun List<InputSurfaceElement>.groupOf(e: InputSurfaceElement) = if (e.dpadPiece) filter { it.dpadPiece } else listOf(e)
|
||||||
|
|
||||||
|
internal fun List<InputSurfaceElement>.frame(): InputSurfaceElement {
|
||||||
|
val left = minOf { it.x }; val top = minOf { it.y }
|
||||||
|
return first().copy(x = left, y = top, width = maxOf { it.x + it.width } - left, height = maxOf { it.y + it.height } - top)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun List<InputSurfaceElement>.resizedAroundCentre(factor: Float): List<InputSurfaceElement> {
|
||||||
|
if (isEmpty()) return this
|
||||||
|
val f = frame()
|
||||||
|
val k = factor.coerceIn(.03f / minOf { min(it.width, it.height) }, 1f / max(f.width, f.height))
|
||||||
|
val w = f.width * k; val h = f.height * k
|
||||||
|
val left = (f.x + f.width / 2 - w / 2).coerceIn(0f, 1f - w)
|
||||||
|
val top = (f.y + f.height / 2 - h / 2).coerceIn(0f, 1f - h)
|
||||||
|
return map { it.copy(x = left + (it.x - f.x) * k, y = top + (it.y - f.y) * k, width = it.width * k, height = it.height * k).bounded() }
|
||||||
|
}
|
||||||
|
|
||||||
internal fun List<InputSurfaceElement>.withPositionsOf(defaults: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
internal fun List<InputSurfaceElement>.withPositionsOf(defaults: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
||||||
val byId = defaults.associateBy { it.id }
|
val byId = defaults.associateBy { it.id }
|
||||||
return map { e -> byId[e.id]?.let { d -> e.copy(x = d.x, y = d.y, width = d.width, height = d.height).bounded() } ?: e }
|
return map { e -> byId[e.id]?.let { d -> e.copy(x = d.x, y = d.y, width = d.width, height = d.height).bounded() } ?: e }
|
||||||
|
|||||||
@@ -197,19 +197,8 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
|
|||||||
|
|
||||||
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
|
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
|
||||||
|
|
||||||
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> {
|
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> =
|
||||||
val before = from.elements().associateBy { it.id }
|
rescaleBetween(stored, from.elements(), elements())
|
||||||
val after = elements().associateBy { it.id }
|
|
||||||
return stored.map { e ->
|
|
||||||
val b = before[e.id] ?: return@map e
|
|
||||||
val a = after[e.id] ?: return@map e
|
|
||||||
val w = (a.width * e.width / b.width).coerceIn(.03f, 1f)
|
|
||||||
val h = (a.height * e.height / b.height).coerceIn(.03f, 1f)
|
|
||||||
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
|
|
||||||
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
|
|
||||||
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
||||||
val inset = dp(BUTTONS_ONLY_INSET_DP)
|
val inset = dp(BUTTONS_ONLY_INSET_DP)
|
||||||
@@ -345,7 +334,6 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
|
|||||||
const val STICK_REACH = 1.25f
|
const val STICK_REACH = 1.25f
|
||||||
const val LEGACY_DPAD_RADIUS_DP = 26f
|
const val LEGACY_DPAD_RADIUS_DP = 26f
|
||||||
const val LEGACY_DPAD_OFFSET_DP = 52f
|
const val LEGACY_DPAD_OFFSET_DP = 52f
|
||||||
val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
|
|
||||||
const val KEYBOARD_ID = "builtin:keyboard"
|
const val KEYBOARD_ID = "builtin:keyboard"
|
||||||
const val KEYBOARD_RADIUS_DP = 18f
|
const val KEYBOARD_RADIUS_DP = 18f
|
||||||
const val KEYBOARD_X_DP = 90f
|
const val KEYBOARD_X_DP = 90f
|
||||||
@@ -360,3 +348,22 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
|
|||||||
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
|
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun rescaleBetween(stored: List<InputSurfaceElement>, from: List<InputSurfaceElement>, to: List<InputSurfaceElement>,
|
||||||
|
sizeFrom: List<InputSurfaceElement> = from, sizeTo: List<InputSurfaceElement> = to): List<InputSurfaceElement> {
|
||||||
|
val before = from.associateBy { it.id }
|
||||||
|
val after = to.associateBy { it.id }
|
||||||
|
val smaller = sizeFrom.associateBy { it.id }
|
||||||
|
val larger = sizeTo.associateBy { it.id }
|
||||||
|
return stored.map { e ->
|
||||||
|
val b = before[e.id] ?: return@map e
|
||||||
|
val a = after[e.id] ?: return@map e
|
||||||
|
val sb = smaller[e.id] ?: b
|
||||||
|
val sa = larger[e.id] ?: a
|
||||||
|
val w = (sa.width * e.width / sb.width).coerceIn(.03f, 1f)
|
||||||
|
val h = (sa.height * e.height / sb.height).coerceIn(.03f, 1f)
|
||||||
|
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
|
||||||
|
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
|
||||||
|
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,9 +14,6 @@ import android.view.View
|
|||||||
import android.view.WindowInsets
|
import android.view.WindowInsets
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
import com.droiddeck.launcher.ui.InputSurfaceView
|
import com.droiddeck.launcher.ui.InputSurfaceView
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import com.droiddeck.launcher.session.SessionService
|
|
||||||
import com.droiddeck.launcher.session.SessionState
|
|
||||||
|
|
||||||
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
|
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
|
||||||
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
|
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
|
||||||
@@ -75,15 +72,15 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
|||||||
render()
|
render()
|
||||||
}
|
}
|
||||||
|
|
||||||
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
|
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean,
|
||||||
|
val kit: PadKit?, val optional: Pair<Boolean?, Boolean?>)
|
||||||
|
|
||||||
private fun placed(): List<InputSurfaceElement> {
|
private fun placed(): List<InputSurfaceElement> {
|
||||||
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
|
val optional = OnScreenLayout.optionalControls(context)
|
||||||
|
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly, PadKit.forOverlay(context, layout), optional)
|
||||||
return placements.getOrPut(key) {
|
return placements.getOrPut(key) {
|
||||||
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
|
|
||||||
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock,
|
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock,
|
||||||
rearButtons = SessionPrefs.oscRearButtons(context).takeIf { steam },
|
rearButtons = optional.first, trackpads = optional.second)
|
||||||
trackpads = SessionPrefs.oscTrackpads(context).takeIf { steam })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,9 +97,9 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
|||||||
|
|
||||||
private fun refreshAppearance() {
|
private fun refreshAppearance() {
|
||||||
val style = layout?.style ?: InputSurfaceStyle()
|
val style = layout?.style ?: InputSurfaceStyle()
|
||||||
val deck = dock == null && OnScreenLayout.usesSteamDeckButtons(context, layout)
|
val artwork = PadKit.forOverlay(context, layout)
|
||||||
surface.updateStyle(style, steamDeckButtons = deck)
|
surface.updateStyle(style, artwork)
|
||||||
quickToggle.tint = style.tint.takeUnless { deck }
|
quickToggle.tint = style.tint.takeUnless { artwork != null }
|
||||||
quickToggle.alpha = style.opacity / 100f
|
quickToggle.alpha = style.opacity / 100f
|
||||||
quickToggle.invalidate()
|
quickToggle.invalidate()
|
||||||
}
|
}
|
||||||
@@ -136,7 +133,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
|||||||
params.bottomMargin = bottom
|
params.bottomMargin = bottom
|
||||||
quickToggle.layoutParams = params
|
quickToggle.layoutParams = params
|
||||||
}
|
}
|
||||||
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
|
val fresh = OnScreenLayout.safeInsets(insets, dock != null)
|
||||||
if (fresh != safe) {
|
if (fresh != safe) {
|
||||||
safe.set(fresh)
|
safe.set(fresh)
|
||||||
render()
|
render()
|
||||||
|
|||||||
@@ -3,17 +3,16 @@ package com.droiddeck.launcher.input
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.graphics.Rect
|
import android.graphics.Rect
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
import com.droiddeck.launcher.session.SessionService
|
||||||
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
import kotlin.math.max
|
import kotlin.math.max
|
||||||
import kotlin.math.min
|
import kotlin.math.min
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
object OnScreenLayout {
|
object OnScreenLayout {
|
||||||
internal fun usesSteamDeckButtons(context: Context, layout: SavedInputLayout?) =
|
|
||||||
layout?.id == InputLibraries.OVERLAY && SessionPrefs.steamController(context) == SessionPrefs.CONTROLLER_DECK
|
|
||||||
|
|
||||||
internal fun supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) =
|
internal fun supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) =
|
||||||
layout?.id == InputLibraries.OVERLAY &&
|
layout?.overlay == true &&
|
||||||
(controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM)
|
(controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM)
|
||||||
|
|
||||||
data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) {
|
data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) {
|
||||||
@@ -31,41 +30,96 @@ object OnScreenLayout {
|
|||||||
|
|
||||||
private const val TOLERANCE = .01f
|
private const val TOLERANCE = .01f
|
||||||
private const val KEYBOARD_ID = "builtin:keyboard"
|
private const val KEYBOARD_ID = "builtin:keyboard"
|
||||||
|
private val REAR = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
|
||||||
|
private val BAR = setOf(InputControl.GUIDE, InputControl.QAM)
|
||||||
|
|
||||||
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
|
fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
|
||||||
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
|
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
|
||||||
trackpads: Boolean? = null): List<InputSurfaceElement> {
|
trackpads: Boolean? = null): List<InputSurfaceElement> {
|
||||||
val stored = layout?.elements ?: return emptyList()
|
if (saved == null) return emptyList()
|
||||||
if (width <= 0 || height <= 0) return stored
|
if (width <= 0 || height <= 0) return saved.elements
|
||||||
|
val layout = oriented(saved, dock?.portrait ?: (height > width))
|
||||||
|
val stored = layout.elements
|
||||||
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
|
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
|
||||||
val (reference, generated) = reference(context, layout, width, height)
|
val (reference, matched) = reference(context, layout, width, height)
|
||||||
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
|
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
|
||||||
|
if (dock?.portrait == true && !dock.grips && !matched && layout.aspect > 0f && layout.aspect < 1f && stored.any(::isGamepad))
|
||||||
|
return cluster(stored.filterNot { it.alwaysShown || isGamepad(it) && (it.id == KEYBOARD_ID || it.control in BAR) }, layout.aspect, width, height, safe)
|
||||||
|
val generated = matched || PadKit.forOverlay(context, layout) != null && stored.any(::isGamepad) &&
|
||||||
|
(dock != null || height > width && layout.aspect >= 1f || height <= width && layout.aspect > 0f && layout.aspect < 1f)
|
||||||
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
|
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
|
||||||
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
|
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
|
||||||
val placed = when {
|
val regenerated = when {
|
||||||
gamepad.isEmpty() -> emptyList()
|
gamepad.isEmpty() -> emptyList()
|
||||||
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
|
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
|
||||||
else -> generator.regenerate(gamepad)
|
else -> generator.regenerate(gamepad)
|
||||||
}
|
}
|
||||||
|
val placed = regenerated + gamepad.filter { g -> dock == null && optional(g) && regenerated.none { it.id == g.id } }
|
||||||
val byId = (placed + others).associateBy { it.id }
|
val byId = (placed + others).associateBy { it.id }
|
||||||
val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
|
val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
|
||||||
if (dock != null || !supportsFloatingSteamControls(SessionPrefs.steamController(context), layout)) return ordered
|
val kit = PadKit.forOverlay(context, layout) ?: return ordered
|
||||||
if (generated && width >= height && usesSteamDeckButtons(context, layout) &&
|
if (generated &&
|
||||||
ControllerPrefs.layout(context, reference.first.toInt(), reference.second.toInt()).isEmpty() &&
|
ControllerPrefs.layout(context, reference.first.toInt(), reference.second.toInt()).isEmpty() &&
|
||||||
ControllerPrefs.layout(context, width, height).isEmpty()) {
|
ControllerPrefs.layout(context, width, height).isEmpty()) {
|
||||||
return SteamDeckOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale)
|
if (dock != null || height > width) {
|
||||||
.place(ordered, rearButtons == true, trackpads == true)
|
return ControllerPortraitGeometry(width.toFloat(), height.toFloat(), safe, context.resources.displayMetrics.density)
|
||||||
|
.place(ordered, kit, dock != null, layout.scale, rearButtons == true, trackpads == true)
|
||||||
|
}
|
||||||
|
return ControllerOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale)
|
||||||
|
.place(ordered, kit, rearButtons == true, trackpads == true)
|
||||||
}
|
}
|
||||||
|
if (dock != null || !kit.steam) return ordered
|
||||||
return FloatingSteamOverlay(width, height, safe, context.resources.displayMetrics.density)
|
return FloatingSteamOverlay(width, height, safe, context.resources.displayMetrics.density)
|
||||||
.place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads)
|
.place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
|
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout = oriented(layout, height > width)
|
||||||
elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect())
|
|
||||||
|
private fun oriented(layout: SavedInputLayout, portrait: Boolean): SavedInputLayout {
|
||||||
|
if (layout.rotated.isEmpty() || layout.aspect <= 0f || (layout.aspect < 1f) == portrait || (layout.rotatedAspect < 1f) != portrait) return layout
|
||||||
|
val rotated = layout.rotated.associateBy { it.id }
|
||||||
|
return layout.copy(elements = layout.elements.map { e -> rotated[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } ?: e } +
|
||||||
|
layout.rotated.filter { r -> optional(r) && layout.elements.none { it.id == r.id } },
|
||||||
|
aspect = layout.rotatedAspect, scale = layout.rotatedScale, rotated = emptyList(), rotatedAspect = 0f, rotatedScale = 1f)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun withFrame(context: Context, saved: SavedInputLayout, elements: List<InputSurfaceElement>, aspect: Float, scale: Float = saved.scale): SavedInputLayout {
|
||||||
|
val (_, metrics) = InputLibraries.primaryDisplay(context)
|
||||||
|
val generated = generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels) != null
|
||||||
|
val portraitMain = saved.aspect > 0f && saved.aspect < 1f
|
||||||
|
if (aspect <= 0f || aspect >= 1f || portraitMain && !generated) {
|
||||||
|
val rotated = if (aspect >= 1f && portraitMain && !generated) Triple(saved.elements, saved.aspect, saved.scale) else Triple(saved.rotated, saved.rotatedAspect, saved.rotatedScale)
|
||||||
|
return saved.copy(elements = elements, aspect = aspect, scale = scale, rotated = rotated.first,
|
||||||
|
rotatedAspect = if (rotated.first.isEmpty()) 0f else rotated.second, rotatedScale = if (rotated.first.isEmpty()) 1f else rotated.third)
|
||||||
|
}
|
||||||
|
val main = if (portraitMain) 1f / saved.aspect else saved.aspect.takeIf { it > 0f } ?: (1f / aspect)
|
||||||
|
val ids = elements.associateBy { it.id }
|
||||||
|
val kept = saved.elements.mapNotNull { e -> ids[e.id]?.copy(x = e.x, y = e.y, width = e.width, height = e.height) }
|
||||||
|
val added = fit(elements.filter { d -> !optional(d) && saved.elements.none { it.id == d.id } }, aspect, 1f, (main * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
|
||||||
|
return saved.copy(elements = kept + added, aspect = main, rotated = elements, rotatedAspect = aspect, rotatedScale = scale)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun optionalControls(context: Context): Pair<Boolean?, Boolean?> {
|
||||||
|
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
|
||||||
|
return SessionPrefs.oscRearButtons(context).takeIf { steam } to SessionPrefs.oscTrackpads(context).takeIf { steam }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false, safe: Rect = Rect()): List<InputSurfaceElement> {
|
||||||
|
val (rear, pads) = optionalControls(context)
|
||||||
|
return elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, safe,
|
||||||
|
rearButtons = rear, trackpads = pads)
|
||||||
|
}
|
||||||
|
|
||||||
fun editorFrame(layout: SavedInputLayout, displayed: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
fun editorFrame(layout: SavedInputLayout, displayed: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
||||||
val byId = displayed.associateBy { it.id }
|
val byId = displayed.associateBy { it.id }
|
||||||
return layout.elements.map { byId[it.id] ?: it }
|
return layout.elements.map { byId[it.id] ?: it } + displayed.filter { d ->
|
||||||
|
optional(d) && layout.elements.none { it.id == d.id }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun safeInsets(insets: android.view.WindowInsets?, docked: Boolean): Rect {
|
||||||
|
val cutout = if (android.os.Build.VERSION.SDK_INT >= 28) insets?.displayCutout else null
|
||||||
|
return Rect(cutout?.safeInsetLeft ?: 0, if (docked) 0 else cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
|
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
|
||||||
@@ -81,6 +135,23 @@ object OnScreenLayout {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun cluster(elements: List<InputSurfaceElement>, aspect: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
|
||||||
|
if (elements.isEmpty()) return elements
|
||||||
|
val left = elements.minOf { it.x } * aspect
|
||||||
|
val top = elements.minOf { it.y }
|
||||||
|
val spanX = (elements.maxOf { it.x + it.width } * aspect - left).coerceAtLeast(.0001f)
|
||||||
|
val spanY = (elements.maxOf { it.y + it.height } - top).coerceAtLeast(.0001f)
|
||||||
|
val w = (width - safe.left - safe.right).toFloat().coerceAtLeast(1f)
|
||||||
|
val h = (height - safe.top - safe.bottom).toFloat().coerceAtLeast(1f)
|
||||||
|
val scale = minOf(w / aspect, w / spanX, h / spanY)
|
||||||
|
val originX = safe.left + (w - spanX * scale) / 2f - left * scale
|
||||||
|
val originY = safe.top + (h - spanY * scale) / 2f - top * scale
|
||||||
|
return elements.map { e ->
|
||||||
|
e.copy(x = (originX + e.x * aspect * scale) / width, y = (originY + e.y * scale) / height,
|
||||||
|
width = e.width * aspect * scale / width, height = e.height * scale / height)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float {
|
private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float {
|
||||||
val centre = start + size / 2f
|
val centre = start + size / 2f
|
||||||
val scaled = size * reference * scale
|
val scaled = size * reference * scale
|
||||||
@@ -91,6 +162,8 @@ object OnScreenLayout {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun optional(e: InputSurfaceElement) = e.id == "legacy:${e.control.id}" && (e.control.isTrackpad || e.control in REAR)
|
||||||
|
|
||||||
private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
|
private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
|
||||||
|
|
||||||
fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
|
fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
|
||||||
@@ -104,7 +177,7 @@ object OnScreenLayout {
|
|||||||
if (gamepad.any { it.id.startsWith("legacy:") }) {
|
if (gamepad.any { it.id.startsWith("legacy:") }) {
|
||||||
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
|
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
|
||||||
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
|
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
|
||||||
val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f }
|
val aspectSize = layout.aspect.takeIf { layout.overlay && it > 0f }
|
||||||
?.let { (it * height).roundToInt().coerceAtLeast(1) to height }
|
?.let { (it * height).roundToInt().coerceAtLeast(1) to height }
|
||||||
for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) {
|
for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) {
|
||||||
val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale)
|
val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale)
|
||||||
|
|||||||
@@ -273,7 +273,8 @@ public final class PadBridge {
|
|||||||
static boolean isSystemVirtualInputName(String name) {
|
static boolean isSystemVirtualInputName(String name) {
|
||||||
if (name == null) return false;
|
if (name == null) return false;
|
||||||
String lower = name.trim().toLowerCase(java.util.Locale.ROOT);
|
String lower = name.trim().toLowerCase(java.util.Locale.ROOT);
|
||||||
return lower.startsWith("uinput-") || lower.startsWith("uinput_");
|
// Xiaomi's "ui-input-xiaomi" is a system uinput device that also reports gamepad sources.
|
||||||
|
return lower.startsWith("uinput-") || lower.startsWith("uinput_") || lower.equals("ui-input-xiaomi");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isFromController(InputDevice device) {
|
public static boolean isFromController(InputDevice device) {
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
|
||||||
|
internal enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS }
|
||||||
|
internal enum class DpadStyle { CROSS, DISC, ARROWS }
|
||||||
|
internal enum class StickCap { RINGED, DISHED, KNURLED }
|
||||||
|
|
||||||
|
internal enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) {
|
||||||
|
STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
|
||||||
|
STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
|
||||||
|
XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true),
|
||||||
|
DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED),
|
||||||
|
DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED);
|
||||||
|
|
||||||
|
val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER
|
||||||
|
val playStation get() = this == DUALSHOCK || this == DUALSENSE
|
||||||
|
|
||||||
|
fun label(control: InputControl): String = when (control) {
|
||||||
|
InputControl.LB -> if (xbox) "LB" else "L1"
|
||||||
|
InputControl.RB -> if (xbox) "RB" else "R1"
|
||||||
|
InputControl.LT -> if (xbox) "LT" else "L2"
|
||||||
|
InputControl.RT -> if (xbox) "RT" else "R2"
|
||||||
|
else -> control.label
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the player calls [control] on this controller. */
|
||||||
|
fun name(control: InputControl): String = if (!playStation) label(control) else when (control) {
|
||||||
|
InputControl.A -> "Cross"
|
||||||
|
InputControl.B -> "Circle"
|
||||||
|
InputControl.X -> "Square"
|
||||||
|
InputControl.Y -> "Triangle"
|
||||||
|
else -> label(control)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun native(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" && element.icon == 0 &&
|
||||||
|
(element.name == element.control.label || element.name == name(element.control))
|
||||||
|
|
||||||
|
fun artwork(element: InputSurfaceElement) = element.image.isEmpty() && element.showLabel &&
|
||||||
|
(native(element) || element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun forOverlay(context: Context, layout: SavedInputLayout?): PadKit? =
|
||||||
|
if (layout?.overlay != true) null else when (SessionPrefs.steamController(context)) {
|
||||||
|
SessionPrefs.CONTROLLER_DECK -> STEAM_DECK
|
||||||
|
SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER
|
||||||
|
SessionPrefs.CONTROLLER_XBOX360 -> XBOX
|
||||||
|
SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK
|
||||||
|
SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.session.SessionPrefs
|
|||||||
|
|
||||||
enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindings: String? = null) {
|
enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindings: String? = null) {
|
||||||
NONE("none", R.string.second_mode_none),
|
NONE("none", R.string.second_mode_none),
|
||||||
|
MENU("menu", R.string.touch_droiddeck_menu),
|
||||||
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad, InputStockLayouts.TRACKPAD),
|
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad, InputStockLayouts.TRACKPAD),
|
||||||
TERMINAL("terminal", R.string.second_mode_terminal),
|
TERMINAL("terminal", R.string.second_mode_terminal),
|
||||||
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls, InputStockLayouts.DECK),
|
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls, InputStockLayouts.DECK),
|
||||||
@@ -21,19 +22,12 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
|
|||||||
fun panel(context: Context): String? = if (this == DECK_CONTROLS) SessionPrefs.deckPanel(context).bindings else bindings
|
fun panel(context: Context): String? = if (this == DECK_CONTROLS) SessionPrefs.deckPanel(context).bindings else bindings
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false, desktopSession: Boolean = false): SecondScreenMode {
|
/** The mode the bottom screen opens in: the one picked last if it is still available, else the DroidDeck menu. */
|
||||||
|
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false): SecondScreenMode =
|
||||||
entries.firstOrNull {
|
entries.firstOrNull {
|
||||||
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard) &&
|
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard) &&
|
||||||
(it != DESKTOP || bottomDesktop)
|
(it != DESKTOP || bottomDesktop)
|
||||||
}?.let { return it }
|
} ?: MENU
|
||||||
val picked = entries.any { it != NONE && it.id == remembered }
|
|
||||||
return when {
|
|
||||||
desktopSession -> KEYBOARD_TRACKPAD
|
|
||||||
deckPad -> DECK_CONTROLS
|
|
||||||
dashboard && !picked -> DASHBOARD
|
|
||||||
else -> KEYBOARD_TRACKPAD
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,116 +0,0 @@
|
|||||||
package com.droiddeck.launcher.input
|
|
||||||
|
|
||||||
import android.graphics.Rect
|
|
||||||
import android.util.DisplayMetrics
|
|
||||||
import kotlin.math.max
|
|
||||||
import kotlin.math.min
|
|
||||||
|
|
||||||
internal class SteamDeckOverlayGeometry(
|
|
||||||
width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float,
|
|
||||||
) {
|
|
||||||
private val w = width.toFloat()
|
|
||||||
private val h = height.toFloat()
|
|
||||||
private val density = metrics.density
|
|
||||||
private val dpi = metrics.ydpi.takeIf { it in metrics.densityDpi * .6f..metrics.densityDpi * 1.6f }
|
|
||||||
?: metrics.densityDpi.toFloat()
|
|
||||||
private val unit = minOf(
|
|
||||||
min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)) * scale,
|
|
||||||
(w - safe.left - safe.right).coerceAtLeast(1f) / 1200f,
|
|
||||||
(h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f,
|
|
||||||
)
|
|
||||||
|
|
||||||
private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float {
|
|
||||||
val low = start + value * unit
|
|
||||||
val high = extent - end - (reference - value) * unit
|
|
||||||
return when {
|
|
||||||
value < reference / 3f -> low
|
|
||||||
value > reference * 2f / 3f -> high
|
|
||||||
else -> (extent / 2f + (value - reference / 2f) * unit).coerceIn(low, max(low, high))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun place(elements: List<InputSurfaceElement>, rearButtons: Boolean, trackpads: Boolean): List<InputSurfaceElement> {
|
|
||||||
val x = { ref: Float -> anchor(ref, 1600f, w, safe.left, safe.right) }
|
|
||||||
val y = { ref: Float -> anchor(ref, 900f, h, safe.top, safe.bottom) }
|
|
||||||
val leftEdge = safe.left + 52f * density
|
|
||||||
val middle = (w + safe.left - safe.right) / 2f
|
|
||||||
val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
|
|
||||||
val row = fitRow(listOfNotNull(keyboard,
|
|
||||||
Box(max(x(370f), leftEdge + 66f * unit), y(852f), 66f, 30f),
|
|
||||||
Box(middle - 140f * unit, y(850f), 46f, 26f),
|
|
||||||
Box(middle + 140f * unit, y(850f), 46f, 26f),
|
|
||||||
Box(x(1230f), y(852f), 66f, 30f)), leftEdge)
|
|
||||||
val (guide, select, start, qam) = row.takeLast(4)
|
|
||||||
val positions = mapOf(
|
|
||||||
InputControl.LT to Box(x(140f), y(66f), 88f, 34f),
|
|
||||||
InputControl.LB to Box(x(140f), y(148f), 88f, 30f),
|
|
||||||
InputControl.RT to Box(x(1460f), y(66f), 88f, 34f),
|
|
||||||
InputControl.RB to Box(x(1460f), y(148f), 88f, 30f),
|
|
||||||
InputControl.Y to Box(x(1375f), y(345f) - 96f * unit, 58f),
|
|
||||||
InputControl.X to Box(x(1375f) - 96f * unit, y(345f), 58f),
|
|
||||||
InputControl.B to Box(x(1375f) + 96f * unit, y(345f), 58f),
|
|
||||||
InputControl.A to Box(x(1375f), y(345f) + 96f * unit, 58f),
|
|
||||||
InputControl.UP to Box(x(220f), y(345f) - 102.5f * unit, 55.5f, 47.5f),
|
|
||||||
InputControl.RIGHT to Box(x(220f) + 102.5f * unit, y(345f), 47.5f, 55.5f),
|
|
||||||
InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * unit, 55.5f, 47.5f),
|
|
||||||
InputControl.LEFT to Box(x(220f) - 102.5f * unit, y(345f), 47.5f, 55.5f),
|
|
||||||
InputControl.LS to Box(x(290f), y(640f), 96f),
|
|
||||||
InputControl.RS to Box(x(1310f), y(640f), 96f),
|
|
||||||
InputControl.SELECT to select,
|
|
||||||
InputControl.START to start,
|
|
||||||
InputControl.GUIDE to guide,
|
|
||||||
InputControl.QAM to qam,
|
|
||||||
)
|
|
||||||
val rear = mapOf(
|
|
||||||
InputControl.L4 to Box(x(30f), y(470f), 30f, 58f),
|
|
||||||
InputControl.L5 to Box(x(30f), y(590f), 30f, 58f),
|
|
||||||
InputControl.R4 to Box(x(1570f), y(470f), 30f, 58f),
|
|
||||||
InputControl.R5 to Box(x(1570f), y(590f), 30f, 58f),
|
|
||||||
)
|
|
||||||
val pads = mapOf(
|
|
||||||
InputControl.LEFT_PAD to Box(x(470f), y(360f), 88f),
|
|
||||||
InputControl.RIGHT_PAD to Box(x(1130f), y(360f), 88f),
|
|
||||||
)
|
|
||||||
val optional = rear.filterKeys { rearButtons } + pads.filterKeys { trackpads }
|
|
||||||
val placed = elements.mapNotNull { element ->
|
|
||||||
when {
|
|
||||||
element.id == KEYBOARD -> row.first().place(element)
|
|
||||||
element.id != "legacy:${element.control.id}" -> element
|
|
||||||
element.control in rear || element.control in pads -> optional[element.control]?.place(element)
|
|
||||||
else -> positions[element.control]?.place(element) ?: element
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return placed + optional.mapNotNull { (control, box) ->
|
|
||||||
if (placed.any { it.id == "legacy:${control.id}" }) null else box.place(InputSurfaceElement(control,
|
|
||||||
0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun fitRow(row: List<Box>, start: Float): List<Box> {
|
|
||||||
val end = w - safe.right
|
|
||||||
val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density)
|
|
||||||
var edge = start - gap
|
|
||||||
val pushed = row.map { box -> box.at(max(box.cx, edge + gap + box.width / 2f)).also { edge = it.cx + it.width / 2f } }
|
|
||||||
edge = end + gap
|
|
||||||
return pushed.asReversed().map { box -> box.at(min(box.cx, edge - gap - box.width / 2f)).also { edge = it.cx - it.width / 2f } }.asReversed()
|
|
||||||
}
|
|
||||||
|
|
||||||
private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) {
|
|
||||||
val width get() = max(hw * 2f * unit, w * .03f)
|
|
||||||
|
|
||||||
fun at(cx: Float) = Box(cx, cy, hw, hh)
|
|
||||||
|
|
||||||
fun place(element: InputSurfaceElement): InputSurfaceElement {
|
|
||||||
val height = max(hh * 2f * unit, h * .03f)
|
|
||||||
return element.copy(
|
|
||||||
x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w,
|
|
||||||
y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h,
|
|
||||||
width = width / w, height = height / h,
|
|
||||||
).bounded()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private companion object {
|
|
||||||
const val KEYBOARD = "builtin:keyboard"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.os.SystemClock
|
||||||
|
import android.view.InputDevice
|
||||||
|
import android.view.KeyEvent
|
||||||
|
import android.view.MotionEvent
|
||||||
|
|
||||||
|
internal class TriggerKeys(private val dispatch: (KeyEvent) -> Unit) {
|
||||||
|
private class Pull {
|
||||||
|
val held = BooleanArray(2)
|
||||||
|
val sent = BooleanArray(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
private val keyed = HashSet<Int>()
|
||||||
|
private val pulls = HashMap<Int, Pull>()
|
||||||
|
var synthesizing = false
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** True when this real trigger key belongs to a pull that already went out as a synthetic press. */
|
||||||
|
fun nativeKey(event: KeyEvent): Boolean {
|
||||||
|
val i = index(event.keyCode) ?: return false
|
||||||
|
keyed += event.deviceId
|
||||||
|
val pull = pulls[event.deviceId] ?: return false
|
||||||
|
if (!pull.sent[i]) return false
|
||||||
|
if (event.action == KeyEvent.ACTION_UP) pull.sent[i] = false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMotion(event: MotionEvent) {
|
||||||
|
if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) return
|
||||||
|
val device = event.deviceId
|
||||||
|
if (device in keyed) return
|
||||||
|
val pull = pulls.getOrPut(device) { Pull() }
|
||||||
|
update(pull, 0, maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)), event)
|
||||||
|
update(pull, 1, maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)), event)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancel() {
|
||||||
|
handler.removeCallbacksAndMessages(null)
|
||||||
|
pulls.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun update(pull: Pull, i: Int, value: Float, event: MotionEvent) {
|
||||||
|
if (!pull.held[i] && value >= PRESS) {
|
||||||
|
pull.held[i] = true
|
||||||
|
pull.sent[i] = false
|
||||||
|
val device = event.deviceId
|
||||||
|
val source = event.source
|
||||||
|
// A pad that also sends trigger keys delivers them close to the axis; waiting lets that key win.
|
||||||
|
handler.postDelayed({
|
||||||
|
if (device !in keyed && pulls[device] === pull) {
|
||||||
|
pull.sent[i] = true
|
||||||
|
press(CODES[i], device, source)
|
||||||
|
}
|
||||||
|
}, KEY_WAIT_MS)
|
||||||
|
} else if (pull.held[i] && value <= RELEASE) pull.held[i] = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun press(code: Int, device: Int, source: Int) {
|
||||||
|
val now = SystemClock.uptimeMillis()
|
||||||
|
synthesizing = true
|
||||||
|
try {
|
||||||
|
dispatch(KeyEvent(now, now, KeyEvent.ACTION_DOWN, code, 0, 0, device, 0, 0, source))
|
||||||
|
dispatch(KeyEvent(now, now, KeyEvent.ACTION_UP, code, 0, 0, device, 0, 0, source))
|
||||||
|
} finally {
|
||||||
|
synthesizing = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun index(code: Int): Int? = CODES.indexOf(code).takeIf { it >= 0 }
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
val CODES = intArrayOf(KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2)
|
||||||
|
const val PRESS = 0.6f
|
||||||
|
const val RELEASE = 0.3f
|
||||||
|
const val KEY_WAIT_MS = 40L
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,9 +12,6 @@ object BattleNet {
|
|||||||
|
|
||||||
const val APP_ID = 2596113170L
|
const val APP_ID = 2596113170L
|
||||||
|
|
||||||
const val FEX_REQUEST = "battlenet-fex.request"
|
|
||||||
const val FEX_RESULT = "battlenet-fex.result"
|
|
||||||
|
|
||||||
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
|
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
|
||||||
|
|
||||||
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null, val flavor: String? = null)
|
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null, val flavor: String? = null)
|
||||||
@@ -59,7 +56,7 @@ object BattleNet {
|
|||||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
|
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
|
||||||
)
|
)
|
||||||
|
|
||||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" }
|
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
|
||||||
|
|
||||||
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
|
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
|
||||||
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
|
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
|
||||||
@@ -162,8 +159,6 @@ object BattleNet {
|
|||||||
source = com.droiddeck.launcher.stores.Store.BATTLENET.id,
|
source = com.droiddeck.launcher.stores.Store.BATTLENET.id,
|
||||||
)
|
)
|
||||||
|
|
||||||
fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"]
|
|
||||||
|
|
||||||
internal fun title(uid: String): Title? {
|
internal fun title(uid: String): Title? {
|
||||||
val id = uid.lowercase()
|
val id = uid.lowercase()
|
||||||
TITLES.firstOrNull { it.uid == id }?.let { return it }
|
TITLES.firstOrNull { it.uid == id }?.let { return it }
|
||||||
@@ -212,7 +207,8 @@ object BattleNet {
|
|||||||
val taken = HashSet<File>()
|
val taken = HashSet<File>()
|
||||||
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
|
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
|
||||||
for ((code, game) in games) {
|
for ((code, game) in games) {
|
||||||
val keep = saved[code]?.let(::File)?.takeIf { it in options(game.first, game.second) && it !in taken } ?: continue
|
val want = saved[code]?.let { runCatching { File(it).canonicalFile }.getOrNull() } ?: continue
|
||||||
|
val keep = options(game.first, game.second).firstOrNull { runCatching { it.canonicalFile }.getOrNull() == want }?.takeIf { it !in taken } ?: continue
|
||||||
out[code] = keep
|
out[code] = keep
|
||||||
taken.add(keep)
|
taken.add(keep)
|
||||||
}
|
}
|
||||||
@@ -249,6 +245,14 @@ object BattleNet {
|
|||||||
"/" + rootfs.relativize(resolved).joinToString("/")
|
"/" + rootfs.relativize(resolved).joinToString("/")
|
||||||
}
|
}
|
||||||
}.trimEnd('/')
|
}.trimEnd('/')
|
||||||
|
if (mapped?.startsWith("/") == true) {
|
||||||
|
val rootfs = LinuxRuntime.rootDir(context)
|
||||||
|
runCatching {
|
||||||
|
val home = rootfs.canonicalFile.toPath()
|
||||||
|
val host = File("$target/$relative").canonicalFile.toPath()
|
||||||
|
if (host.startsWith(home)) File(rootfs, home.relativize(host).toString()) else null
|
||||||
|
}.getOrNull()?.let { return it }
|
||||||
|
}
|
||||||
return com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "$target/$relative")
|
return com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "$target/$relative")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -391,54 +395,6 @@ object BattleNet {
|
|||||||
Log.i(TAG, "removed")
|
Log.i(TAG, "removed")
|
||||||
}
|
}
|
||||||
|
|
||||||
private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""")
|
|
||||||
|
|
||||||
private const val LISTING_MAX_AGE = 6 * 3600L
|
|
||||||
|
|
||||||
private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b ->
|
|
||||||
for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i])
|
|
||||||
if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second)
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun d2rfix(file: String): Pair<List<Long>, Long>? {
|
|
||||||
val m = D2RFIX.matchEntire(file) ?: return null
|
|
||||||
val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
|
|
||||||
return version to (m.groupValues[2].toLongOrNull() ?: return null)
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? =
|
|
||||||
items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } }
|
|
||||||
.maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first
|
|
||||||
|
|
||||||
fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items }
|
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String {
|
|
||||||
val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing")
|
|
||||||
val file = ComponentsManager.safeName(item.file)
|
|
||||||
if (ComponentsManager.packages(context).none { it.file == file }) {
|
|
||||||
Log.i(TAG, "downloading ${item.file}")
|
|
||||||
ComponentsManager.download(context, item) {}
|
|
||||||
}
|
|
||||||
val scope = APP_ID.toString()
|
|
||||||
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
|
|
||||||
ComponentsManager.setGameComponent(context, scope, "fex", file)
|
|
||||||
Log.i(TAG, "FEX for the Battle.net prefix: $file")
|
|
||||||
} else if (ComponentsManager.republish(context)) {
|
|
||||||
Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton")
|
|
||||||
}
|
|
||||||
return file
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> {
|
|
||||||
val cached = ComponentsManager.catalog(context, false)
|
|
||||||
val age = System.currentTimeMillis() / 1000 - cached.fetchedAt
|
|
||||||
if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items
|
|
||||||
val fetched = runCatching { refresh(context) }
|
|
||||||
.onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty()
|
|
||||||
return if (newestD2rFix(fetched) != null) fetched else cached.items
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt()
|
internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt()
|
||||||
|
|
||||||
internal fun videoMemoryOptions(megabytes: Int): String =
|
internal fun videoMemoryOptions(megabytes: Int): String =
|
||||||
@@ -464,21 +420,9 @@ object BattleNet {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
fun answerFexRequest(context: Context, dir: File) {
|
fun ensureDefaults(context: Context, program: String?) {
|
||||||
val app = context.applicationContext
|
if (program != PROGRAM && !installed(context)) return
|
||||||
Thread({
|
runCatching { ensureVideoMemory(context) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
|
||||||
runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
|
runCatching { ensureNoSteam(context) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
|
||||||
runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
|
|
||||||
val answer = try {
|
|
||||||
"ok " + ensureFex(app)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "FEX for the Battle.net prefix", e)
|
|
||||||
"error " + (e.message ?: e.javaClass.simpleName)
|
|
||||||
}
|
|
||||||
Log.i(TAG, "FEX request: $answer")
|
|
||||||
val result = File(dir, FEX_RESULT)
|
|
||||||
val partial = File(dir, "$FEX_RESULT.tmp")
|
|
||||||
runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) }
|
|
||||||
}, "battlenet-fex").start()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -112,9 +112,16 @@ object BwrapSpawner {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun withKernelPaths(sessionBinds: List<Bind>, canonical: (String) -> String): List<Bind> =
|
||||||
|
sessionBinds + sessionBinds.filter { it.host == it.guest }.mapNotNull { bind ->
|
||||||
|
runCatching { canonical(bind.host) }.getOrNull()
|
||||||
|
?.takeIf { it != bind.guest && sessionBinds.none { other -> other.guest == it } }
|
||||||
|
?.let { Bind(bind.host, it) }
|
||||||
|
}
|
||||||
|
|
||||||
internal fun plan(context: Context, request: JSONObject, dir: File): Plan {
|
internal fun plan(context: Context, request: JSONObject, dir: File): Plan {
|
||||||
val rootfs = LinuxRuntime.rootDir(context).path
|
val rootfs = LinuxRuntime.rootDir(context).path
|
||||||
val session = LinuxRuntime.lastBinds(context).map { Bind.parse(it) }
|
val session = withKernelPaths(LinuxRuntime.lastBinds(context).map { Bind.parse(it) }) { File(it).canonicalPath }
|
||||||
val root = File(dir, "root").apply { mkdirs() }
|
val root = File(dir, "root").apply { mkdirs() }
|
||||||
val binds = ArrayList<Bind>()
|
val binds = ArrayList<Bind>()
|
||||||
var scratch = 0
|
var scratch = 0
|
||||||
@@ -184,7 +191,10 @@ object BwrapSpawner {
|
|||||||
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
|
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
|
||||||
withoutRootfsSettings(env, rootfs)
|
withoutRootfsSettings(env, rootfs)
|
||||||
val envTool = request.optString("envTool").takeIf { it.startsWith("/") }
|
val envTool = request.optString("envTool").takeIf { it.startsWith("/") }
|
||||||
if (envTool == null && binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
|
if (envTool == null && binds.any { it.guest == "/dev" }) {
|
||||||
|
val glIcd = coveringBind(GL_ICD_DIR) != null && File(hostPath(binds, root.path, GL_ICD_DIR)).isDirectory
|
||||||
|
gpu(rootfs, root, env, glIcd = glIcd)?.forEach { addBind(it) }
|
||||||
|
}
|
||||||
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
|
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
|
||||||
if (envTool == null && preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) }
|
if (envTool == null && preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) }
|
||||||
zypakShims(binds, root, dir).forEach { addBind(it) }
|
zypakShims(binds, root, dir).forEach { addBind(it) }
|
||||||
@@ -211,6 +221,7 @@ object BwrapSpawner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private const val GPU_DIR = "/run/droiddeck-gpu"
|
private const val GPU_DIR = "/run/droiddeck-gpu"
|
||||||
|
private const val GL_ICD_DIR = "/usr/lib/aarch64-linux-gnu/GL/vulkan/icd.d"
|
||||||
|
|
||||||
private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib")
|
private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib")
|
||||||
private val GPU_LIBS = listOf("libdisplay-info.so.3", "libdisplay-info.so.2", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")
|
private val GPU_LIBS = listOf("libdisplay-info.so.3", "libdisplay-info.so.2", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")
|
||||||
@@ -220,9 +231,9 @@ object BwrapSpawner {
|
|||||||
|
|
||||||
internal fun gpu(
|
internal fun gpu(
|
||||||
rootfs: String, root: File, env: MutableMap<String, String>,
|
rootfs: String, root: File, env: MutableMap<String, String>,
|
||||||
kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(),
|
kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), glIcd: Boolean = false,
|
||||||
): List<Bind>? {
|
): List<Bind>? {
|
||||||
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
|
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock, glIcd) }
|
||||||
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
|
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
|
||||||
if (driver == null || !kgslAvailable) return null
|
if (driver == null || !kgslAvailable) return null
|
||||||
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
|
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
|
||||||
@@ -235,6 +246,7 @@ object BwrapSpawner {
|
|||||||
val icd = File(root.parentFile, "freedreno_icd.json")
|
val icd = File(root.parentFile, "freedreno_icd.json")
|
||||||
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_freedreno.so\", \"api_version\": \"1.4.0\"}}\n")
|
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_freedreno.so\", \"api_version\": \"1.4.0\"}}\n")
|
||||||
binds.add(Bind(icd.path, "$GPU_DIR/freedreno_icd.json"))
|
binds.add(Bind(icd.path, "$GPU_DIR/freedreno_icd.json"))
|
||||||
|
if (glIcd) binds.add(icdDir(root, icd))
|
||||||
env["VK_DRIVER_FILES"] = "$GPU_DIR/freedreno_icd.json"
|
env["VK_DRIVER_FILES"] = "$GPU_DIR/freedreno_icd.json"
|
||||||
env["VK_ICD_FILENAMES"] = "$GPU_DIR/freedreno_icd.json"
|
env["VK_ICD_FILENAMES"] = "$GPU_DIR/freedreno_icd.json"
|
||||||
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
|
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
|
||||||
@@ -245,7 +257,14 @@ object BwrapSpawner {
|
|||||||
return binds
|
return binds
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<Bind>? {
|
private fun icdDir(root: File, icd: File): Bind {
|
||||||
|
val dir = File(root.parentFile, "icd.d")
|
||||||
|
dir.mkdirs()
|
||||||
|
icd.copyTo(File(dir, icd.name), overwrite = true)
|
||||||
|
return Bind(dir.path, GL_ICD_DIR)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String, glIcd: Boolean): List<Bind>? {
|
||||||
val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so")
|
val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so")
|
||||||
if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null }
|
if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null }
|
||||||
val binds = ArrayList<Bind>()
|
val binds = ArrayList<Bind>()
|
||||||
@@ -258,6 +277,7 @@ object BwrapSpawner {
|
|||||||
}.getOrNull() ?: run { Log.w(TAG, "gpu: vkbridge session but the runtime's bridge manifest is unreadable"); return null }
|
}.getOrNull() ?: run { Log.w(TAG, "gpu: vkbridge session but the runtime's bridge manifest is unreadable"); return null }
|
||||||
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"$api\"}}\n")
|
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"$api\"}}\n")
|
||||||
binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json"))
|
binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json"))
|
||||||
|
if (glIcd) binds.add(icdDir(root, icd))
|
||||||
env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json"
|
env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json"
|
||||||
env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json"
|
env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json"
|
||||||
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
|
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
|
||||||
@@ -416,6 +436,7 @@ object BwrapSpawner {
|
|||||||
"DDNATV_ROOT" to sandbox,
|
"DDNATV_ROOT" to sandbox,
|
||||||
"DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(),
|
"DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(),
|
||||||
"DDNATV_LINK_ROOT" to rootfs.path,
|
"DDNATV_LINK_ROOT" to rootfs.path,
|
||||||
|
"DDNATV_REAL_EXE" to program.path,
|
||||||
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
|
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
|
||||||
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
|
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
|
||||||
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
|
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
|
||||||
@@ -537,6 +558,9 @@ object BwrapSpawner {
|
|||||||
return f
|
return f
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun prootEnvironment(plan: Plan, startsThroughEnvTool: Boolean): Map<String, String> =
|
||||||
|
if (startsThroughEnvTool) emptyMap() else plan.env - "LD_PRELOAD"
|
||||||
|
|
||||||
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
|
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
|
||||||
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
|
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
|
||||||
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
|
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
|
||||||
@@ -558,7 +582,7 @@ object BwrapSpawner {
|
|||||||
ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b ->
|
ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b ->
|
||||||
b.environment().apply {
|
b.environment().apply {
|
||||||
clear()
|
clear()
|
||||||
if (!envTool) putAll(plan.env)
|
putAll(prootEnvironment(plan, envTool))
|
||||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||||
|
|||||||
@@ -0,0 +1,293 @@
|
|||||||
|
package com.droiddeck.launcher.runtime
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
|
object CurseForgeApp {
|
||||||
|
const val NAME = "CurseForge"
|
||||||
|
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
|
||||||
|
internal const val WOW = 1
|
||||||
|
const val HELPER = "/usr/local/bin/droiddeck-curseforge"
|
||||||
|
internal const val AGENT = "/usr/local/bin/droiddeck-agent"
|
||||||
|
private const val READY_MS = 120_000L
|
||||||
|
private const val INSTALL_MS = 300_000L
|
||||||
|
private const val OUT_OF_DATE = 2
|
||||||
|
|
||||||
|
enum class Start { READY, BUSY, FAILED }
|
||||||
|
|
||||||
|
class Started(val state: Start, val inspector: String? = null)
|
||||||
|
|
||||||
|
class Project(val id: String, val installedModId: String, val folders: List<String>, val update: Boolean)
|
||||||
|
|
||||||
|
internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||||
|
|
||||||
|
class Failure(message: String, val code: String? = null) : Exception(message) {
|
||||||
|
val gone get() = code == "DEVTOOLS_UNREACHABLE"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED }
|
||||||
|
|
||||||
|
fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null)
|
||||||
|
|
||||||
|
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
|
||||||
|
|
||||||
|
internal fun helperArgv(command: String, dir: String): List<String> = listOf(HELPER, command, dir)
|
||||||
|
|
||||||
|
internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List<String> =
|
||||||
|
listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression)
|
||||||
|
|
||||||
|
internal fun lastJson(lines: List<String>): JSONObject? =
|
||||||
|
lines.asReversed().firstNotNullOfOrNull { line -> runCatching { JSONObject(line.trim()) }.getOrNull() }
|
||||||
|
|
||||||
|
internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) }
|
||||||
|
|
||||||
|
internal fun startState(exitCode: Int): Start = when (exitCode) {
|
||||||
|
0 -> Start.READY
|
||||||
|
3 -> Start.BUSY
|
||||||
|
else -> Start.FAILED
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun sortOf(sort: WowAddonCatalog.Sort): Pair<Int, Int> = when (sort) {
|
||||||
|
WowAddonCatalog.Sort.POPULAR -> 8 to 2
|
||||||
|
WowAddonCatalog.Sort.UPDATED -> 16 to 2
|
||||||
|
WowAddonCatalog.Sort.NAME -> 1 to 1
|
||||||
|
WowAddonCatalog.Sort.DOWNLOADS -> 7 to 2
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun searchRequest(guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): JSONObject {
|
||||||
|
val (column, order) = sortOf(sort)
|
||||||
|
return JSONObject().put("gameId", WOW).put("searchText", text.trim()).put("page", page + 1)
|
||||||
|
.put("sortColumn", column).put("sortOrder", order).put("gameInstanceGuid", guid)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun installRequest(guid: String, projectId: String): JSONObject =
|
||||||
|
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
|
||||||
|
.put("installLatestFile", true).put("installSource", 4)
|
||||||
|
|
||||||
|
private const val CACHE = "__droiddeckServices"
|
||||||
|
|
||||||
|
private const val SERVICES = """(() => {
|
||||||
|
const seen = new Set(), out = {};
|
||||||
|
const walk = (o, d) => {
|
||||||
|
if (!o || typeof o !== 'object' || seen.has(o) || d > 4) return;
|
||||||
|
seen.add(o);
|
||||||
|
if (typeof o._nameOfService === 'string') { out[o._nameOfService] = o; return; }
|
||||||
|
let keys; try { keys = Object.keys(o); } catch (e) { return; }
|
||||||
|
for (const k of keys.slice(0, 4000)) {
|
||||||
|
let v; try { v = o[k]; } catch (e) { continue; }
|
||||||
|
if (v instanceof Map) { for (const x of v.values()) walk(x, d + 1); } else walk(v, d + 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(window, 0);
|
||||||
|
return out;
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
private val CORE = JSONObject.quote("CoreService")
|
||||||
|
|
||||||
|
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r", connect: Boolean = true): String {
|
||||||
|
val name = JSONObject.quote(method)
|
||||||
|
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
|
||||||
|
val key = JSONObject.quote(service)
|
||||||
|
val link = if (connect && args != null) "const c = m[$CORE]; if (!c || typeof c.connect !== 'function') return { missing: true }; await c.connect(); " else ""
|
||||||
|
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
|
||||||
|
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
|
||||||
|
link + "return { value: $run }; })()"
|
||||||
|
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
|
||||||
|
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
|
||||||
|
"if (!w) return JSON.stringify({ missing: true }); " +
|
||||||
|
"return w.webContents.executeJavaScript(${JSONObject.quote(inner)}).then(v => JSON.stringify(v)); })()"
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun unwrap(answer: JSONObject): Any? {
|
||||||
|
if (!answer.optBoolean("ok")) {
|
||||||
|
val error = answer.optJSONObject("error")
|
||||||
|
throw Failure(error?.optString("message")?.takeIf { it.isNotBlank() } ?: answer.toString(), error?.optString("code")?.takeIf { it.isNotBlank() })
|
||||||
|
}
|
||||||
|
val text = answer.opt("value") as? String ?: throw Failure("CurseForge gave no answer")
|
||||||
|
val reply = JSONObject(text)
|
||||||
|
if (reply.optBoolean("missing")) throw Failure("CurseForge is not ready")
|
||||||
|
return reply.opt("value")
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun parseSearch(value: Any?): WowAddonCatalog.Page {
|
||||||
|
val reply = value as? JSONObject ?: throw Failure("CurseForge search failed")
|
||||||
|
if (reply.has("success") && !reply.optBoolean("success")) throw Failure("CurseForge search failed")
|
||||||
|
val mods = reply.optJSONArray("mods") ?: JSONArray()
|
||||||
|
val items = (0 until mods.length()).mapNotNull { mods.optJSONObject(it) }.mapNotNull { mod ->
|
||||||
|
val id = mod.optLong("id", 0L).takeIf { it > 0 } ?: return@mapNotNull null
|
||||||
|
val name = mod.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
|
||||||
|
val author = mod.optJSONObject("primaryAuthor")?.optString("name")?.takeIf { it.isNotBlank() }
|
||||||
|
?: mod.optJSONArray("authors")?.optJSONObject(0)?.optString("name").orEmpty()
|
||||||
|
val date = mod.optJSONObject("updateVersion")?.optString("fileDate")?.takeIf { it.isNotBlank() }
|
||||||
|
?: mod.optString("projectLatestReleaseDate")
|
||||||
|
WowAddonCatalog.Addon(
|
||||||
|
id.toString(), name, author, "", mod.optLong("downloads", 0L).coerceAtLeast(0L),
|
||||||
|
runCatching { Instant.parse(date).toEpochMilli() }.getOrDefault(0L),
|
||||||
|
mod.optString("thumbnailUrl").takeIf { WowAddonCatalog.isHttps(it) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val page = reply.optJSONObject("pagination")
|
||||||
|
val more = page != null && page.optInt("index") + page.optInt("resultCount") < page.optInt("totalCount")
|
||||||
|
return WowAddonCatalog.Page(items, more)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun samePath(a: String, b: String) = a.trimEnd('/') == b.trimEnd('/')
|
||||||
|
|
||||||
|
internal fun instanceFor(instances: Any?, flavorDir: String, detected: String?): String? {
|
||||||
|
val list = instances as? JSONArray
|
||||||
|
val match = list?.let { all ->
|
||||||
|
(0 until all.length()).mapNotNull { all.optJSONObject(it) }
|
||||||
|
.firstOrNull { samePath(it.optString("installPath"), flavorDir) }?.optString("guid")
|
||||||
|
}
|
||||||
|
if (list != null && list.length() > 0) return match?.takeIf { it.isNotBlank() }
|
||||||
|
return detected?.takeIf { it.isNotBlank() }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun parseProjects(value: Any?): List<Project> {
|
||||||
|
val list = value as? JSONArray ?: return emptyList()
|
||||||
|
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.mapNotNull { p ->
|
||||||
|
val id = p.optString("id").takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
|
||||||
|
val folders = p.optJSONArray("folders")?.let { f -> (0 until f.length()).mapNotNull { f.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
|
||||||
|
Project(id, p.optString("installedModId"), folders, p.optInt("status") == OUT_OF_DATE && !p.optBoolean("locked"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun owner(projects: List<Project>, folder: String): Project? =
|
||||||
|
projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } }
|
||||||
|
|
||||||
|
internal fun byFolder(projects: List<Project>): Map<String, Project> = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap()
|
||||||
|
|
||||||
|
internal fun onDisk(projects: List<Project>, addOns: File): List<Project> {
|
||||||
|
val names = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }.map { it.name.lowercase() }.toSet()
|
||||||
|
return projects.filter { project -> WowAddons.present(project.folders) { it.lowercase() in names } }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal var guest: (Context, List<String>, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine ->
|
||||||
|
GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true,
|
||||||
|
cancelled = cancelled, redact = INSPECTOR, onLine = onLine)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
|
||||||
|
|
||||||
|
private fun lines(context: Context, argv: List<String>): List<String> {
|
||||||
|
val out = ArrayList<String>()
|
||||||
|
guest(context, argv, null) { out += it }
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r", connect: Boolean = true): Any? =
|
||||||
|
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick, connect), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
|
||||||
|
|
||||||
|
private sealed class Launch {
|
||||||
|
class Url(val inspector: String) : Launch()
|
||||||
|
class Exit(val code: Int) : Launch()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? {
|
||||||
|
val first = LinkedBlockingQueue<Launch>()
|
||||||
|
Thread({
|
||||||
|
val code = runCatching {
|
||||||
|
guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } }
|
||||||
|
}.getOrDefault(-1)
|
||||||
|
first.offer(Launch.Exit(code))
|
||||||
|
}, "curseforge-headless").apply { isDaemon = true; start() }
|
||||||
|
return first.poll(READY_MS, TimeUnit.MILLISECONDS)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started {
|
||||||
|
val dir = dir(app) ?: return Started(Start.FAILED)
|
||||||
|
if (hold.get()) return Started(Start.FAILED)
|
||||||
|
holds.put(dir, hold)?.takeIf { it !== hold }?.let {
|
||||||
|
it.set(true)
|
||||||
|
runCatching { lines(context, helperArgv("stop", dir)) }
|
||||||
|
}
|
||||||
|
val inspector = when (val first = launch(context, dir, hold)) {
|
||||||
|
is Launch.Url -> first.inspector
|
||||||
|
is Launch.Exit -> if (startState(first.code) == Start.BUSY) {
|
||||||
|
holds.remove(dir, hold)
|
||||||
|
return Started(Start.BUSY)
|
||||||
|
} else null
|
||||||
|
null -> null
|
||||||
|
}
|
||||||
|
if (inspector == null) {
|
||||||
|
stop(context, app, null, hold)
|
||||||
|
return Started(Start.FAILED)
|
||||||
|
}
|
||||||
|
val deadline = System.currentTimeMillis() + READY_MS
|
||||||
|
while (System.currentTimeMillis() < deadline && !hold.get()) {
|
||||||
|
if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector)
|
||||||
|
Thread.sleep(1_000)
|
||||||
|
}
|
||||||
|
stop(context, app, inspector, hold)
|
||||||
|
return Started(Start.FAILED)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) {
|
||||||
|
val dir = dir(app) ?: return
|
||||||
|
if (holds[dir] !== hold) {
|
||||||
|
hold.set(true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true", connect = false) }
|
||||||
|
hold.set(true)
|
||||||
|
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun instances(context: Context, inspector: String): Any? =
|
||||||
|
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 120_000,
|
||||||
|
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
|
||||||
|
|
||||||
|
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
|
||||||
|
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
|
||||||
|
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
|
||||||
|
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
|
||||||
|
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
|
||||||
|
|
||||||
|
fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> {
|
||||||
|
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000)
|
||||||
|
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " +
|
||||||
|
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
|
||||||
|
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
|
||||||
|
|
||||||
|
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? {
|
||||||
|
val deadline = System.currentTimeMillis() + INSTALL_MS
|
||||||
|
while (System.currentTimeMillis() < deadline) {
|
||||||
|
val listed = runCatching { projects(context, inspector, guid) }
|
||||||
|
val error = listed.exceptionOrNull()
|
||||||
|
if (error is Failure && error.gone) throw error
|
||||||
|
listed.getOrNull()?.let { if (done(it)) return it }
|
||||||
|
Thread.sleep(1_000)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||||
|
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
|
||||||
|
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||||
|
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
|
||||||
|
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
|
||||||
|
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
||||||
|
if (failed == null || failed.length() > 0) return null
|
||||||
|
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package com.droiddeck.launcher.runtime
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.core.Downloader
|
||||||
|
import com.droiddeck.launcher.session.SessionState
|
||||||
|
import java.io.File
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
object DeckyStore {
|
||||||
|
private const val TAG = "DeckyStore"
|
||||||
|
private const val LISTING = "https://plugins.deckbrew.xyz/plugins"
|
||||||
|
private const val ARTIFACTS = "https://cdn.tzatzikiweeb.moe/file/steam-deck-homebrew/versions/"
|
||||||
|
|
||||||
|
data class Version(val name: String, val hash: String)
|
||||||
|
data class Plugin(val name: String, val author: String, val description: String, val tags: List<String>, val downloads: Long, val imageUrl: String, val versions: List<Version>) {
|
||||||
|
val latest: Version? get() = versions.firstOrNull()
|
||||||
|
}
|
||||||
|
data class Installed(val name: String, val folder: String, val author: String, val version: String)
|
||||||
|
|
||||||
|
fun parseListing(body: String): List<Plugin> {
|
||||||
|
val array = JSONArray(body)
|
||||||
|
return (0 until array.length()).mapNotNull { i ->
|
||||||
|
val row = array.optJSONObject(i) ?: return@mapNotNull null
|
||||||
|
val name = row.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
|
||||||
|
val versions = row.optJSONArray("versions")?.let { list ->
|
||||||
|
(0 until list.length()).mapNotNull { v ->
|
||||||
|
val version = list.optJSONObject(v) ?: return@mapNotNull null
|
||||||
|
val hash = version.optString("hash")
|
||||||
|
if (!hash.matches(Regex("(?i)[0-9a-f]{64}"))) null else Version(version.optString("name"), hash.lowercase())
|
||||||
|
}
|
||||||
|
}.orEmpty()
|
||||||
|
if (versions.isEmpty()) return@mapNotNull null
|
||||||
|
val tags = row.optJSONArray("tags")?.let { list -> (0 until list.length()).map { list.optString(it) } }.orEmpty()
|
||||||
|
val downloads = row.optJSONArray("versions")?.let { list -> (0 until list.length()).sumOf { list.optJSONObject(it)?.optLong("downloads") ?: 0L } } ?: 0L
|
||||||
|
val image = row.optString("image_url").takeIf { it.startsWith("https://") }.orEmpty()
|
||||||
|
Plugin(name, row.optString("author"), row.optString("description"), tags, downloads, image, versions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fetch(): List<Plugin>? {
|
||||||
|
val body = Downloader.downloadString(LISTING) ?: return null
|
||||||
|
return runCatching { parseListing(body) }.onFailure { Log.w(TAG, "store listing", it) }.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun pluginsDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins")
|
||||||
|
|
||||||
|
fun installed(context: Context): List<Installed> =
|
||||||
|
pluginsDir(context).listFiles().orEmpty()
|
||||||
|
.filter { it.isDirectory && !it.name.startsWith(".droiddeck-") }
|
||||||
|
.mapNotNull { folder ->
|
||||||
|
runCatching {
|
||||||
|
val meta = JSONObject(File(folder, "plugin.json").readText())
|
||||||
|
val version = runCatching { JSONObject(File(folder, "package.json").readText()).optString("version") }.getOrDefault("")
|
||||||
|
Installed(meta.getString("name"), folder.name, meta.optString("author"), version)
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
.sortedBy { it.name.lowercase() }
|
||||||
|
|
||||||
|
fun updateAvailable(installed: Installed, plugin: Plugin?): Boolean {
|
||||||
|
val latest = plugin?.latest?.name ?: return false
|
||||||
|
return installed.version.isNotEmpty() && latest != installed.version
|
||||||
|
}
|
||||||
|
|
||||||
|
fun install(context: Context, plugin: Plugin, version: Version, progress: (String, Int) -> Unit): String? {
|
||||||
|
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin)
|
||||||
|
if (DeckyManager.installed(context) == null) return context.getString(R.string.deckymgr_loader_required)
|
||||||
|
val cache = File(context.cacheDir, "decky-store").apply { mkdirs() }
|
||||||
|
val zip = File(cache, "${version.hash}.zip")
|
||||||
|
try {
|
||||||
|
val label = context.getString(R.string.decky_store_downloading, plugin.name)
|
||||||
|
progress(label, -1)
|
||||||
|
val ok = Downloader.downloadFile("$ARTIFACTS${version.hash}.zip", zip, true, version.hash) { fraction ->
|
||||||
|
progress(label, if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100))
|
||||||
|
}
|
||||||
|
if (!ok) return context.getString(R.string.decky_store_download_failed, plugin.name)
|
||||||
|
return DeckyManager.installPluginZip(context, zip, progress)
|
||||||
|
} finally {
|
||||||
|
zip.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun remove(context: Context, plugin: Installed): String? {
|
||||||
|
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin)
|
||||||
|
val plugins = pluginsDir(context)
|
||||||
|
val folder = File(plugins, plugin.folder)
|
||||||
|
if (folder.parentFile?.canonicalFile != plugins.canonicalFile) return context.getString(R.string.decky_store_remove_failed)
|
||||||
|
if (!folder.deleteRecursively()) return context.getString(R.string.decky_store_remove_failed)
|
||||||
|
val settings = File(plugins.parentFile, "settings/loader.json")
|
||||||
|
runCatching {
|
||||||
|
val json = JSONObject(settings.readText())
|
||||||
|
for (key in listOf("pluginOrder", "frozenPlugins", "hiddenPlugins", "disabled_plugins")) {
|
||||||
|
val values = json.optJSONArray(key) ?: continue
|
||||||
|
json.put(key, JSONArray((0 until values.length()).map { values.get(it) }.filter { it != plugin.name }))
|
||||||
|
}
|
||||||
|
settings.writeText(json.toString(4))
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -109,9 +109,15 @@ object DesktopCatalog {
|
|||||||
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
|
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
|
||||||
fun protonSeedNeeded(context: Context): Boolean =
|
fun protonSeedNeeded(context: Context): Boolean =
|
||||||
installed(context, PROTON_SEED_ID) == null &&
|
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(context)) ownProtonMissing(context)
|
||||||
|
else installed(context, PROTON_SEED_ID) == null &&
|
||||||
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
|
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
|
||||||
|
|
||||||
|
fun ownProtonMissing(context: Context): Boolean {
|
||||||
|
val extras = com.droiddeck.launcher.session.ProtonExtras
|
||||||
|
return extras.installedAll(context, extras.tools.first { it.id == extras.OWN }).isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
const val DESKTOP_ID = "desktop-kde"
|
const val DESKTOP_ID = "desktop-kde"
|
||||||
const val EMULATORS_ID = "emulators"
|
const val EMULATORS_ID = "emulators"
|
||||||
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
|
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ object DesktopLanguage {
|
|||||||
|
|
||||||
internal fun baseUrl(desktopUrl: String) = desktopUrl.substringBeforeLast('/') + "/"
|
internal fun baseUrl(desktopUrl: String) = desktopUrl.substringBeforeLast('/') + "/"
|
||||||
|
|
||||||
|
/** The index carries every pack's sha256, so it never goes through a download mirror. */
|
||||||
|
internal fun fetchIndex(base: String): Map<String, Pack>? = Downloader.downloadDirect(base + INDEX)?.let(::parseIndex)
|
||||||
|
|
||||||
private fun marker(root: File, tag: String, name: String) = File(root, ".droiddeck-i18n-$tag-$name")
|
private fun marker(root: File, tag: String, name: String) = File(root, ".droiddeck-i18n-$tag-$name")
|
||||||
|
|
||||||
/** Installs the desktop's translations for [locale]; false when a download failed and is worth retrying. */
|
/** Installs the desktop's translations for [locale]; false when a download failed and is worth retrying. */
|
||||||
@@ -44,7 +47,7 @@ object DesktopLanguage {
|
|||||||
val pending = candidates(locale).filterNot { marker(root, tag, it).isFile }
|
val pending = candidates(locale).filterNot { marker(root, tag, it).isFile }
|
||||||
if (pending.isEmpty()) return true
|
if (pending.isEmpty()) return true
|
||||||
val base = baseUrl(BuildConfig.DESKTOP_KDE_URL)
|
val base = baseUrl(BuildConfig.DESKTOP_KDE_URL)
|
||||||
val index = parseIndex(Downloader.downloadString(base + INDEX) ?: return false)
|
val index = fetchIndex(base) ?: return false
|
||||||
var complete = true
|
var complete = true
|
||||||
for (name in pending) {
|
for (name in pending) {
|
||||||
val pack = index[name]
|
val pack = index[name]
|
||||||
|
|||||||
@@ -14,20 +14,22 @@ import java.util.concurrent.atomic.AtomicBoolean
|
|||||||
object GuestCommand {
|
object GuestCommand {
|
||||||
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
||||||
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
|
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
|
||||||
onLine: (String) -> Unit): Int {
|
redact: Regex? = null, onLine: (String) -> Unit): Int {
|
||||||
val log = logName?.let {
|
val log = logName?.let {
|
||||||
try {
|
try {
|
||||||
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
||||||
} catch (e: Exception) { null }
|
} catch (e: Exception) { null }
|
||||||
}
|
}
|
||||||
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
|
log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}")
|
||||||
try {
|
try {
|
||||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) }
|
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) }
|
||||||
} finally {
|
} finally {
|
||||||
log?.close()
|
log?.close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "<redacted>") ?: text
|
||||||
|
|
||||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
|
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
|
||||||
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
||||||
val root = LinuxRuntime.rootDir(context)
|
val root = LinuxRuntime.rootDir(context)
|
||||||
|
|||||||
@@ -275,12 +275,15 @@ class LinuxNetworkLinkComponent(
|
|||||||
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
|
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
|
||||||
*/
|
*/
|
||||||
private fun replace(file: File, text: String) {
|
private fun replace(file: File, text: String) {
|
||||||
val staged = File(file.path + ".staged")
|
synchronized(WRITES) {
|
||||||
java.io.FileOutputStream(staged).use { out ->
|
if (runCatching { file.isFile && file.readText() == text }.getOrDefault(false)) return
|
||||||
out.write(text.toByteArray())
|
val staged = File(file.path + ".staged")
|
||||||
out.fd.sync()
|
java.io.FileOutputStream(staged).use { out ->
|
||||||
|
out.write(text.toByteArray())
|
||||||
|
out.fd.sync()
|
||||||
|
}
|
||||||
|
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
|
||||||
}
|
}
|
||||||
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun writeResolver(properties: LinkProperties?) {
|
private fun writeResolver(properties: LinkProperties?) {
|
||||||
@@ -333,6 +336,8 @@ class LinuxNetworkLinkComponent(
|
|||||||
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
|
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
private val WRITES = Any()
|
||||||
|
|
||||||
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
|
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
|
||||||
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
|
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
|
||||||
properties?.routes.orEmpty()
|
properties?.routes.orEmpty()
|
||||||
|
|||||||
@@ -199,6 +199,7 @@ public final class LinuxRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
|
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
|
||||||
|
NativeGuest.relinkAfterProot(root);
|
||||||
List<String> cmd = new ArrayList<>();
|
List<String> cmd = new ArrayList<>();
|
||||||
cmd.addAll(com.droiddeck.launcher.core.HostProcess.dataExecutable(prootBinary(context).getPath()));
|
cmd.addAll(com.droiddeck.launcher.core.HostProcess.dataExecutable(prootBinary(context).getPath()));
|
||||||
cmd.add("--kill-on-exit");
|
cmd.add("--kill-on-exit");
|
||||||
|
|||||||
@@ -73,10 +73,10 @@ object NativeGuest {
|
|||||||
fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path }
|
fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path }
|
||||||
|
|
||||||
/** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */
|
/** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */
|
||||||
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
|
fun environment(root: File, program: String, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
|
||||||
"DDNATV_ROOT" to root.path,
|
"DDNATV_ROOT" to root.path,
|
||||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||||
"LD_LIBRARY_PATH" to libraryPath(root),
|
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
|
||||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||||
).filterValues { it.isNotEmpty() }
|
).filterValues { it.isNotEmpty() }
|
||||||
|
|
||||||
@@ -84,23 +84,25 @@ object NativeGuest {
|
|||||||
* The host command line for the guest program at [program] (an absolute guest path to a real
|
* The host command line for the guest program at [program] (an absolute guest path to a real
|
||||||
* file, not a symlink).
|
* file, not a symlink).
|
||||||
*/
|
*/
|
||||||
fun command(root: File, program: String, args: List<String>): List<String> {
|
fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> {
|
||||||
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
|
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
|
||||||
val host = File(root, program.removePrefix("/"))
|
val host = hostProgram(root, program)
|
||||||
val launch = listOf(loader.path, "--argv0", host.name, host.path) + args
|
val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args
|
||||||
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
|
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/"))
|
||||||
|
|
||||||
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
|
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
|
||||||
fun sessionEnvironment(root: File, binds: List<String>, hostname: String? = null): Map<String, String> {
|
fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> {
|
||||||
val preload = preloadList(root)
|
val preload = preloadList(root)
|
||||||
return linkedMapOf(
|
return linkedMapOf(
|
||||||
"DDNATV_ROOT" to root.path,
|
"DDNATV_ROOT" to root.path,
|
||||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||||
|
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
|
||||||
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
||||||
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
||||||
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
||||||
"LD_LIBRARY_PATH" to libraryPath(root),
|
|
||||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||||
).filterValues { it.isNotEmpty() }
|
).filterValues { it.isNotEmpty() }
|
||||||
}
|
}
|
||||||
@@ -116,7 +118,7 @@ object NativeGuest {
|
|||||||
.also { builder ->
|
.also { builder ->
|
||||||
builder.environment().apply {
|
builder.environment().apply {
|
||||||
remove("LD_AUDIT")
|
remove("LD_AUDIT")
|
||||||
putAll(sessionEnvironment(root, binds, SessionPrefs.guestHostname(context)))
|
putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,8 +169,15 @@ object NativeGuest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private const val RELINK_STAMP = "etc/droiddeck/native-symlinks"
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
fun relinkAfterProot(root: File) {
|
||||||
|
File(root, RELINK_STAMP).delete()
|
||||||
|
}
|
||||||
|
|
||||||
private val HOST_LINK_TARGETS = listOf("/proc", "/dev", "/sys", "/sdcard", "/storage", "/data", "/system", "/vendor", "/apex",
|
private val HOST_LINK_TARGETS = listOf("/proc", "/dev", "/sys", "/sdcard", "/storage", "/data", "/system", "/vendor", "/apex",
|
||||||
"/system_ext", "/product", "/odm", "/linkerconfig", "/mnt")
|
"/system_ext", "/product", "/odm", "/linkerconfig", "/mnt", "/root/Storage")
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Symbolic links the kernel follows by itself (ld.so, Steam, anything that skips the hook) read
|
* Symbolic links the kernel follows by itself (ld.so, Steam, anything that skips the hook) read
|
||||||
@@ -176,9 +185,9 @@ object NativeGuest {
|
|||||||
* which reads the target inside the rootfs, so each is rewritten as a relative link, which
|
* which reads the target inside the rootfs, so each is rewritten as a relative link, which
|
||||||
* resolves the same way under proot and without it. Rerun when the runtime changes.
|
* resolves the same way under proot and without it. Rerun when the runtime changes.
|
||||||
*/
|
*/
|
||||||
fun relinkAbsoluteSymlinks(context: Context, root: File): Int {
|
fun relinkAbsoluteSymlinks(context: Context, root: File, commands: () -> Sequence<List<String>> = ::procCommands): Int {
|
||||||
val stamp = File(root, "etc/droiddeck/native-symlinks")
|
val stamp = File(root, RELINK_STAMP)
|
||||||
val version = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(context).orEmpty() + "/2"
|
val version = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(context).orEmpty() + "/3"
|
||||||
if (stamp.isFile && stamp.readText() == version) return 0
|
if (stamp.isFile && stamp.readText() == version) return 0
|
||||||
val rootPath = root.toPath()
|
val rootPath = root.toPath()
|
||||||
var rewritten = 0
|
var rewritten = 0
|
||||||
@@ -204,11 +213,20 @@ object NativeGuest {
|
|||||||
|
|
||||||
override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException) = java.nio.file.FileVisitResult.CONTINUE
|
override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException) = java.nio.file.FileVisitResult.CONTINUE
|
||||||
})
|
})
|
||||||
stamp.parentFile?.mkdirs()
|
if (!prootRunning(LinuxRuntime.prootBinary(context).path, commands())) {
|
||||||
stamp.writeText(version)
|
stamp.parentFile?.mkdirs()
|
||||||
|
stamp.writeText(version)
|
||||||
|
}
|
||||||
return rewritten
|
return rewritten
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun prootRunning(proot: String, commands: Sequence<List<String>>): Boolean =
|
||||||
|
commands.any { args -> args.take(2).any { it == proot } }
|
||||||
|
|
||||||
|
private fun procCommands(): Sequence<List<String>> = (File("/proc").listFiles() ?: emptyArray()).asSequence()
|
||||||
|
.filter { it.name.all(Char::isDigit) }
|
||||||
|
.mapNotNull { runCatching { File(it, "cmdline").readText().split('\u0000') }.getOrNull() }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The guest path that host path [target] stands for in a session with [binds] ("src:dst"), or null
|
* The guest path that host path [target] stands for in a session with [binds] ("src:dst"), or null
|
||||||
* when it is a guest path already: the rootfs, or the longest mount source holding it (the first
|
* when it is a guest path already: the rootfs, or the longest mount source holding it (the first
|
||||||
@@ -273,12 +291,14 @@ object NativeGuest {
|
|||||||
|
|
||||||
fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder {
|
fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder {
|
||||||
val program = argv.first()
|
val program = argv.first()
|
||||||
val cmd = command(root, program, argv.drop(1))
|
val callerDirs = env["LD_LIBRARY_PATH"]?.takeIf { it.isNotEmpty() }?.split(':').orEmpty()
|
||||||
|
val rootDirs = libraryPath(root).split(':').filterNot { it in callerDirs }
|
||||||
|
val cmd = command(root, program, argv.drop(1), (callerDirs + rootDirs).joinToString(":"))
|
||||||
val builder = ProcessBuilder(cmd).redirectErrorStream(false)
|
val builder = ProcessBuilder(cmd).redirectErrorStream(false)
|
||||||
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
|
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
|
||||||
builder.environment().apply {
|
builder.environment().apply {
|
||||||
clear()
|
clear()
|
||||||
putAll(environment(root, preload))
|
putAll(environment(root, program, preload))
|
||||||
putAll(env)
|
putAll(env)
|
||||||
}
|
}
|
||||||
return builder
|
return builder
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ class RuntimeInstallService : Service() {
|
|||||||
if (intent?.action == ACTION_PACKAGE) return holdPackage(startId)
|
if (intent?.action == ACTION_PACKAGE) return holdPackage(startId)
|
||||||
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(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
|
val foreground = enterForeground(notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else 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
|
||||||
@@ -31,7 +31,7 @@ class RuntimeInstallService : Service() {
|
|||||||
val manager = getSystemService(NotificationManager::class.java)
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
var shown = ""
|
var shown = ""
|
||||||
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
|
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
|
||||||
if ("$stage:$percent" != shown) {
|
if (foreground && "$stage:$percent" != shown) {
|
||||||
shown = "$stage:$percent"
|
shown = "$stage:$percent"
|
||||||
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
|
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
|
||||||
}
|
}
|
||||||
@@ -46,7 +46,10 @@ class RuntimeInstallService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun holdPackage(startId: Int): Int {
|
private fun holdPackage(startId: Int): Int {
|
||||||
startForeground(NOTIFICATION_ID, notification(packageStage, packagePercent, packageTitle))
|
if (!enterForeground(notification(packageStage, packagePercent, packageTitle))) {
|
||||||
|
stopSelf(startId)
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
Thread({
|
Thread({
|
||||||
val manager = getSystemService(NotificationManager::class.java)
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
var shown = ""
|
var shown = ""
|
||||||
@@ -65,6 +68,15 @@ class RuntimeInstallService : Service() {
|
|||||||
return START_NOT_STICKY
|
return START_NOT_STICKY
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Android 12+ refuses a foreground start while the app is in the background; the work then goes on without the notification. */
|
||||||
|
private fun enterForeground(notification: Notification): Boolean = try {
|
||||||
|
startForeground(NOTIFICATION_ID, notification)
|
||||||
|
true
|
||||||
|
} catch (e: IllegalStateException) {
|
||||||
|
android.util.Log.w("RuntimeInstallService", "running without a foreground service: $e")
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
private fun notification(stage: String, percent: Int, title: String? = null): Notification {
|
private fun notification(stage: String, percent: Int, title: String? = null): Notification {
|
||||||
val manager = getSystemService(NotificationManager::class.java)
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime),
|
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime),
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ object UserApps {
|
|||||||
private const val GITHUB_TAG = "github-tag"
|
private const val GITHUB_TAG = "github-tag"
|
||||||
private const val GITHUB_PUBLISHED = "github-published"
|
private const val GITHUB_PUBLISHED = "github-published"
|
||||||
private const val GITHUB_ASSET = "github-asset"
|
private const val GITHUB_ASSET = "github-asset"
|
||||||
|
private const val FEED = "update-feed"
|
||||||
|
|
||||||
enum class Kind { SCRIPT, APPIMAGE, FLATPAK }
|
enum class Kind { SCRIPT, APPIMAGE, FLATPAK }
|
||||||
|
|
||||||
@@ -43,10 +44,15 @@ object UserApps {
|
|||||||
val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?,
|
val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?,
|
||||||
val program: String, val args: List<String>, val copied: Boolean = false,
|
val program: String, val args: List<String>, val copied: Boolean = false,
|
||||||
val repo: String? = null, val version: String? = null,
|
val repo: String? = null, val version: String? = null,
|
||||||
val fex: String = LinuxFex.AUTO, val arch: String? = null,
|
val fex: String = LinuxFex.AUTO, val arch: String? = null, val feed: String? = null,
|
||||||
)
|
) {
|
||||||
|
val updatable get() = repo != null || feed != null
|
||||||
|
}
|
||||||
|
|
||||||
class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String? = null)
|
class Release(
|
||||||
|
val tag: String, val published: String, val asset: String, val url: String,
|
||||||
|
val sha256: String? = null, val sha512: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
sealed class UpdateCheck {
|
sealed class UpdateCheck {
|
||||||
class Current(val tag: String) : UpdateCheck()
|
class Current(val tag: String) : UpdateCheck()
|
||||||
@@ -58,6 +64,7 @@ object UserApps {
|
|||||||
class Script(val file: File) : Source()
|
class Script(val file: File) : Source()
|
||||||
class AppImage(val file: File) : Source()
|
class AppImage(val file: File) : Source()
|
||||||
class GitHub(val repo: String, val asset: String? = null) : Source()
|
class GitHub(val repo: String, val asset: String? = null) : Source()
|
||||||
|
class Feed(val url: String) : Source()
|
||||||
class Flatpak(val id: String) : Source()
|
class Flatpak(val id: String) : Source()
|
||||||
class FlatpakBundle(val file: File) : Source()
|
class FlatpakBundle(val file: File) : Source()
|
||||||
}
|
}
|
||||||
@@ -91,6 +98,7 @@ object UserApps {
|
|||||||
"appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir),
|
"appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir),
|
||||||
repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(),
|
repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(),
|
||||||
fex = LinuxFex.mode(dir), arch = FileUtils.readString(File(dir, "arch"))?.trim()?.takeIf { it.isNotEmpty() },
|
fex = LinuxFex.mode(dir), arch = FileUtils.readString(File(dir, "arch"))?.trim()?.takeIf { it.isNotEmpty() },
|
||||||
|
feed = FileUtils.readString(File(dir, FEED))?.trim()?.takeIf { it.isNotEmpty() },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
val flatpaks = FlatpakManager.installedApps(context).map { app ->
|
val flatpaks = FlatpakManager.installedApps(context).map { app ->
|
||||||
@@ -115,6 +123,7 @@ object UserApps {
|
|||||||
is Source.Script -> addScript(context, s.file, name, icon, request.meta, onProgress)
|
is Source.Script -> addScript(context, s.file, name, icon, request.meta, onProgress)
|
||||||
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon, request.meta) { onProgress(it, -1) }
|
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon, request.meta) { onProgress(it, -1) }
|
||||||
is Source.GitHub -> addFromGitHub(context, s.repo, s.asset, name, icon, onProgress)
|
is Source.GitHub -> addFromGitHub(context, s.repo, s.asset, name, icon, onProgress)
|
||||||
|
is Source.Feed -> addFromFeed(context, s.url, 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)
|
is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress)
|
||||||
}
|
}
|
||||||
@@ -346,11 +355,15 @@ object UserApps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? {
|
private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? {
|
||||||
val download = File(context.cacheDir, "github-${release.asset}")
|
val download = File(File(context.cacheDir, "user-apps").apply { mkdirs() }, release.asset)
|
||||||
try {
|
try {
|
||||||
val label = context.getString(R.string.user_apps_downloading, release.asset)
|
val label = context.getString(R.string.user_apps_downloading, release.asset)
|
||||||
val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
|
val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
|
||||||
return if (ok) use(download) else context.getString(R.string.user_apps_download_failed)
|
if (!ok) return context.getString(R.string.user_apps_download_failed)
|
||||||
|
if (release.sha512 != null && !Hashes.sha512(download).equals(release.sha512, ignoreCase = true)) {
|
||||||
|
return context.getString(R.string.selfinst_checksum_mismatch)
|
||||||
|
}
|
||||||
|
return use(download)
|
||||||
} finally {
|
} finally {
|
||||||
download.delete()
|
download.delete()
|
||||||
}
|
}
|
||||||
@@ -392,20 +405,57 @@ object UserApps {
|
|||||||
return urls + listOfNotNull(avatar)
|
return urls + listOfNotNull(avatar)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun parseFeed(feed: String, body: String): Release? {
|
||||||
|
val top = body.lineSequence().filter { it.isNotEmpty() && !it[0].isWhitespace() && ':' in it }
|
||||||
|
.associate { it.substringBefore(':').trim() to it.substringAfter(':').trim().trim('\'', '"') }
|
||||||
|
val version = top["version"]?.takeIf { it.isNotEmpty() } ?: return null
|
||||||
|
val path = top["path"]?.takeIf { it.endsWith(".AppImage", ignoreCase = true) && '/' !in it && ".." !in it } ?: return null
|
||||||
|
val sha512 = top["sha512"]?.let { runCatching { java.util.Base64.getDecoder().decode(it) }.getOrNull() }
|
||||||
|
?.takeIf { it.size == 64 }?.joinToString("") { "%02x".format(it) } ?: return null
|
||||||
|
val base = feed.substringBeforeLast('/', "").takeIf { it.startsWith("https://") } ?: return null
|
||||||
|
return Release(version, top["releaseDate"].orEmpty(), path, "$base/$path", sha512 = sha512)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun feedRelease(context: Context, feed: String): Release? =
|
||||||
|
Downloader.downloadString(feed)?.let { parseFeed(feed, it) }
|
||||||
|
|
||||||
|
private fun feedMeta(feed: String, release: Release) =
|
||||||
|
mapOf(FEED to feed, GITHUB_TAG to release.tag, GITHUB_PUBLISHED to release.published, GITHUB_ASSET to release.asset)
|
||||||
|
|
||||||
|
private fun addFromFeed(context: Context, feed: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
||||||
|
onProgress(context.getString(R.string.user_apps_github_checking, name ?: feed), -1)
|
||||||
|
val release = feedRelease(context, feed) ?: return context.getString(R.string.user_apps_update_failed)
|
||||||
|
return withDownload(context, release, onProgress) { file ->
|
||||||
|
AppImageManager.import(context, file, name ?: release.asset.substringBefore('-'), icon, feedMeta(feed, release)) { onProgress(it, -1) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun isNewer(release: Release, published: String, installed: String?): Boolean =
|
||||||
|
if (published.isNotEmpty() && release.published.isNotEmpty()) {
|
||||||
|
val feed = runCatching { java.time.Instant.parse(release.published) }.getOrNull()
|
||||||
|
val have = runCatching { java.time.Instant.parse(published) }.getOrNull()
|
||||||
|
if (feed != null && have != null) feed > have else release.published > published
|
||||||
|
} else release.tag != installed
|
||||||
|
|
||||||
fun checkUpdate(context: Context, app: App): UpdateCheck {
|
fun checkUpdate(context: Context, app: App): UpdateCheck {
|
||||||
|
app.feed?.let { feed ->
|
||||||
|
val release = feedRelease(context, feed) ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
|
||||||
|
val published = FileUtils.readString(File(AppImageManager.dir(context, app.key.substringAfter(':')), GITHUB_PUBLISHED))?.trim().orEmpty()
|
||||||
|
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
||||||
|
}
|
||||||
val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
|
val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
|
||||||
val dir = AppImageManager.dir(context, app.key.substringAfter(':'))
|
val dir = AppImageManager.dir(context, app.key.substringAfter(':'))
|
||||||
val (release, problem) = latestRelease(context, repo, FileUtils.readString(File(dir, GITHUB_ASSET))?.trim()?.takeIf { it.isNotEmpty() })
|
val (release, problem) = latestRelease(context, repo, FileUtils.readString(File(dir, GITHUB_ASSET))?.trim()?.takeIf { it.isNotEmpty() })
|
||||||
if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed))
|
if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed))
|
||||||
val published = FileUtils.readString(File(dir, GITHUB_PUBLISHED))?.trim().orEmpty()
|
val published = FileUtils.readString(File(dir, GITHUB_PUBLISHED))?.trim().orEmpty()
|
||||||
val newer = if (published.isNotEmpty() && release.published.isNotEmpty()) release.published > published else release.tag != app.version
|
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
||||||
return if (newer) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? {
|
fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? {
|
||||||
val repo = app.repo ?: return context.getString(R.string.user_apps_update_failed)
|
val meta = app.feed?.let { feedMeta(it, release) }
|
||||||
|
?: app.repo?.let { githubMeta(it, release) } ?: return context.getString(R.string.user_apps_update_failed)
|
||||||
return withDownload(context, release, onProgress) { file ->
|
return withDownload(context, release, onProgress) { file ->
|
||||||
AppImageManager.replace(context, app.key.substringAfter(':'), file, githubMeta(repo, release)) { onProgress(it, -1) }
|
AppImageManager.replace(context, app.key.substringAfter(':'), file, meta) { onProgress(it, -1) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ object WowAddonCatalog {
|
|||||||
val downloads: Long,
|
val downloads: Long,
|
||||||
val updated: Long,
|
val updated: Long,
|
||||||
val thumb: String?,
|
val thumb: String?,
|
||||||
|
val folders: List<String> = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
class Page(val items: List<Addon>, val more: Boolean)
|
class Page(val items: List<Addon>, val more: Boolean)
|
||||||
@@ -38,7 +39,6 @@ object WowAddonCatalog {
|
|||||||
internal class Cat(val id: String, val name: String, val parents: List<String>)
|
internal class Cat(val id: String, val name: String, val parents: List<String>)
|
||||||
|
|
||||||
private const val WOWI = "https://api.mmoui.com/v3/game/WOW/"
|
private const val WOWI = "https://api.mmoui.com/v3/game/WOW/"
|
||||||
private const val CURSEFORGE = "https://www.curseforge.com/wow/search?class=addons"
|
|
||||||
private const val WOWI_FILES = "wowi-filelist.json"
|
private const val WOWI_FILES = "wowi-filelist.json"
|
||||||
internal const val FRESH_MS = 6L * 60 * 60 * 1000
|
internal const val FRESH_MS = 6L * 60 * 60 * 1000
|
||||||
|
|
||||||
@@ -94,8 +94,7 @@ object WowAddonCatalog {
|
|||||||
Client(folder, version?.let(::flavorOf) ?: folderFamily(folder))
|
Client(folder, version?.let(::flavorOf) ?: folderFamily(folder))
|
||||||
|
|
||||||
fun client(target: WowAddons.Target): Client {
|
fun client(target: WowAddons.Target): Client {
|
||||||
val dir = target.addOns.parentFile?.parentFile
|
return client(target.flavor, WowAddons.flavorDir(target)?.let(::clientVersion))
|
||||||
return client(target.flavor, dir?.let(::clientVersion))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun flavorMatches(flavors: Set<String>?, family: String?): Boolean =
|
internal fun flavorMatches(flavors: Set<String>?, family: String?): Boolean =
|
||||||
@@ -116,9 +115,11 @@ object WowAddonCatalog {
|
|||||||
}
|
}
|
||||||
val thumbs = o.optJSONArray("UIIMG_Thumbs")
|
val thumbs = o.optJSONArray("UIIMG_Thumbs")
|
||||||
val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null
|
val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null
|
||||||
|
val dirs = o.optJSONArray("UIDir")
|
||||||
|
val folders = if (dirs == null) emptyList() else (0 until dirs.length()).map { dirs.optString(it).trim() }.filter { it.isNotEmpty() }
|
||||||
val addon = Addon(
|
val addon = Addon(
|
||||||
id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"),
|
id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"),
|
||||||
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb,
|
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders,
|
||||||
)
|
)
|
||||||
out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L))
|
out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L))
|
||||||
}
|
}
|
||||||
@@ -209,10 +210,12 @@ object WowAddonCatalog {
|
|||||||
|
|
||||||
fun categories(context: Context): List<Category> = wowiCategories(context).map { Category(it.id, it.name) }
|
fun categories(context: Context): List<Category> = wowiCategories(context).map { Category(it.id, it.name) }
|
||||||
|
|
||||||
internal fun parseWowiDetails(json: String): Pair<String, String?>? {
|
internal class Details(val url: String, val md5: String?, val version: String?)
|
||||||
|
|
||||||
|
internal fun parseWowiDetails(json: String): Details? {
|
||||||
val o = JSONArray(json).optJSONObject(0) ?: return null
|
val o = JSONArray(json).optJSONObject(0) ?: return null
|
||||||
val url = o.optString("UIDownload").ifEmpty { return null }
|
val url = o.optString("UIDownload").ifEmpty { return null }
|
||||||
return url to o.optString("UIMD5").ifEmpty { null }
|
return Details(url, o.optString("UIMD5").ifEmpty { null }, o.optString("UIVersion").trim().ifEmpty { null })
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun isHttps(url: String) = url.startsWith("https://", ignoreCase = true)
|
internal fun isHttps(url: String) = url.startsWith("https://", ignoreCase = true)
|
||||||
@@ -220,10 +223,11 @@ object WowAddonCatalog {
|
|||||||
internal fun md5Matches(file: File, expected: String?): Boolean =
|
internal fun md5Matches(file: File, expected: String?): Boolean =
|
||||||
expected.isNullOrBlank() || Hashes.md5(file).equals(expected.trim(), ignoreCase = true)
|
expected.isNullOrBlank() || Hashes.md5(file).equals(expected.trim(), ignoreCase = true)
|
||||||
|
|
||||||
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): File {
|
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): String? {
|
||||||
val body = StoreNet.get(WOWI + "filedetails/${URLEncoder.encode(addon.id, "UTF-8")}.json", timeoutMs = 30_000)
|
val body = StoreNet.get(WOWI + "filedetails/${URLEncoder.encode(addon.id, "UTF-8")}.json", timeoutMs = 30_000)
|
||||||
?: throw unreachable(context)
|
?: throw unreachable(context)
|
||||||
val (url, md5) = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
|
val details = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
|
||||||
|
val url = details.url
|
||||||
if (!isHttps(url)) throw IOException(context.getString(R.string.addons_no_file))
|
if (!isHttps(url)) throw IOException(context.getString(R.string.addons_no_file))
|
||||||
dest.parentFile?.mkdirs()
|
dest.parentFile?.mkdirs()
|
||||||
dest.delete()
|
dest.delete()
|
||||||
@@ -232,14 +236,56 @@ object WowAddonCatalog {
|
|||||||
dest.delete()
|
dest.delete()
|
||||||
throw unreachable(context)
|
throw unreachable(context)
|
||||||
}
|
}
|
||||||
if (!md5Matches(dest, md5)) {
|
if (!md5Matches(dest, details.md5)) {
|
||||||
dest.delete()
|
dest.delete()
|
||||||
throw IOException(context.getString(R.string.selfinst_checksum_mismatch))
|
throw IOException(context.getString(R.string.selfinst_checksum_mismatch))
|
||||||
}
|
}
|
||||||
progress(100)
|
progress(100)
|
||||||
return dest
|
return details.version
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun curseForgeUrl(text: String): String =
|
private fun normVersion(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
||||||
text.trim().let { if (it.isEmpty()) CURSEFORGE else CURSEFORGE + "&search=" + URLEncoder.encode(it, "UTF-8") }
|
|
||||||
|
internal fun sameVersion(a: String, b: String): Boolean = normVersion(a) == normVersion(b)
|
||||||
|
|
||||||
|
private val NUMERIC_VERSION = Regex("""^(\d+(?:\.\d+)*)(.*)$""")
|
||||||
|
|
||||||
|
private fun numericVersion(v: String): Pair<List<Long>, String>? {
|
||||||
|
val match = NUMERIC_VERSION.matchEntire(normVersion(v)) ?: return null
|
||||||
|
val parts = match.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
|
||||||
|
return parts to match.groupValues[2]
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun newer(have: String, latest: String): Boolean? {
|
||||||
|
val (a, aRest) = numericVersion(have) ?: return null
|
||||||
|
val (b, bRest) = numericVersion(latest) ?: return null
|
||||||
|
for (i in 0 until maxOf(a.size, b.size)) {
|
||||||
|
val x = a.getOrElse(i) { 0L }
|
||||||
|
val y = b.getOrElse(i) { 0L }
|
||||||
|
if (x != y) return y > x
|
||||||
|
}
|
||||||
|
return if (aRest == bRest) false else null
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun offersUpdate(have: String?, latest: String, sameSource: Boolean): Boolean {
|
||||||
|
if (have.isNullOrBlank() || latest.isBlank() || sameVersion(have, latest)) return false
|
||||||
|
return newer(have, latest) ?: sameSource
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
|
||||||
|
val byId = entries.associateBy { it.addon.id }
|
||||||
|
val seen = HashSet<String>()
|
||||||
|
return installed.mapNotNull { item ->
|
||||||
|
val id = item.wowiId ?: return@mapNotNull null
|
||||||
|
val version = item.version ?: return@mapNotNull null
|
||||||
|
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
|
||||||
|
if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest
|
||||||
|
}.toMap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updates(context: Context, installed: List<WowAddons.Installed>, target: WowAddons.Target): Map<String, Addon> {
|
||||||
|
if (installed.none { it.wowiId != null }) return emptyMap()
|
||||||
|
val family = client(target).family
|
||||||
|
return runCatching { findUpdates(wowiEntries(context).filter { flavorMatches(it.flavors, family) }, installed) }.getOrDefault(emptyMap())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,15 +2,25 @@ package com.droiddeck.launcher.runtime
|
|||||||
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableIntStateOf
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import android.content.Context
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.frontend.Library
|
import com.droiddeck.launcher.frontend.Library
|
||||||
import com.droiddeck.launcher.stores.Store
|
import com.droiddeck.launcher.stores.Store
|
||||||
|
import com.droiddeck.launcher.stores.StoreArchiveUnpacker
|
||||||
import com.droiddeck.launcher.stores.StoreInstalls
|
import com.droiddeck.launcher.stores.StoreInstalls
|
||||||
|
import com.droiddeck.launcher.stores.itch.ItchArchives
|
||||||
import org.apache.commons.compress.archivers.zip.ZipFile
|
import org.apache.commons.compress.archivers.zip.ZipFile
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.nio.file.FileVisitResult
|
||||||
import java.nio.file.Files
|
import java.nio.file.Files
|
||||||
import java.nio.file.LinkOption
|
import java.nio.file.LinkOption
|
||||||
|
import java.nio.file.Path
|
||||||
|
import java.nio.file.SimpleFileVisitor
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
object WowAddons {
|
object WowAddons {
|
||||||
var imports by mutableIntStateOf(0)
|
var imports by mutableIntStateOf(0)
|
||||||
@@ -18,10 +28,28 @@ object WowAddons {
|
|||||||
|
|
||||||
class TooLarge : IOException()
|
class TooLarge : IOException()
|
||||||
|
|
||||||
|
fun changed() {
|
||||||
|
imports++
|
||||||
|
}
|
||||||
|
|
||||||
|
fun flavorDir(target: Target): File? = target.addOns.parentFile?.parentFile
|
||||||
|
|
||||||
|
fun root(target: Target): File? = flavorDir(target)?.parentFile
|
||||||
|
|
||||||
class Target(val flavor: String, val addOns: File)
|
class Target(val flavor: String, val addOns: File)
|
||||||
|
|
||||||
class Addon(val name: String, val root: String)
|
class Addon(val name: String, val root: String)
|
||||||
|
|
||||||
|
class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null)
|
||||||
|
|
||||||
|
class Origin(val id: String, val version: String)
|
||||||
|
|
||||||
|
private const val ORIGINS = ".droiddeck-sources"
|
||||||
|
private const val TOC_VERSION = "Version"
|
||||||
|
private const val TOC_WOWI_ID = "X-WoWI-ID"
|
||||||
|
private const val TOC_CURSE_ID = "X-Curse-Project-ID"
|
||||||
|
private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID, TOC_CURSE_ID)
|
||||||
|
|
||||||
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
|
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
|
||||||
|
|
||||||
private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE)
|
private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE)
|
||||||
@@ -45,53 +73,168 @@ object WowAddons {
|
|||||||
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||||
.map { it.name }.sortedBy { it.lowercase() }
|
.map { it.name }.sortedBy { it.lowercase() }
|
||||||
|
|
||||||
|
fun present(folders: List<String>, exists: (String) -> Boolean): Boolean = folders.isNotEmpty() && folders.all(exists)
|
||||||
|
|
||||||
|
fun folder(addOns: File, name: String): File? {
|
||||||
|
val dirs = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||||
|
return dirs.firstOrNull { it.name == name } ?: dirs.firstOrNull { it.name.equals(name, ignoreCase = true) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun details(target: Target): List<Installed> {
|
||||||
|
val origins = origins(target)
|
||||||
|
return installed(target).map { name ->
|
||||||
|
val toc = toc(File(target.addOns, name))
|
||||||
|
val origin = origins[name]
|
||||||
|
Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun tocFields(lines: Sequence<String>, keys: Set<String> = TOC_KEYS): Map<String, String> {
|
||||||
|
val out = LinkedHashMap<String, String>()
|
||||||
|
for (raw in lines) {
|
||||||
|
val line = raw.trim().removePrefix("\uFEFF")
|
||||||
|
if (!line.startsWith("##") || ':' !in line) continue
|
||||||
|
val key = line.removePrefix("##").substringBefore(':').trim()
|
||||||
|
if (key !in keys || key in out) continue
|
||||||
|
val value = line.substringAfter(':').trim()
|
||||||
|
if (value.isNotEmpty() && '@' !in value) out[key] = value
|
||||||
|
if (out.size == keys.size) break
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun toc(folder: File): Map<String, String> {
|
||||||
|
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }.sortedWith(
|
||||||
|
compareBy<File>(
|
||||||
|
{ !it.name.dropLast(4).equals(folder.name, ignoreCase = true) },
|
||||||
|
{ !it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) },
|
||||||
|
{ it.name.length },
|
||||||
|
{ it.name },
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val out = LinkedHashMap<String, String>()
|
||||||
|
for (file in tocs) {
|
||||||
|
if (out.size == TOC_KEYS.size) break
|
||||||
|
val missing = TOC_KEYS - out.keys
|
||||||
|
runCatching { file.bufferedReader().useLines { tocFields(it, missing) } }.getOrNull()?.let(out::putAll)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
|
||||||
|
val parts = line.split('\t')
|
||||||
|
if (parts.size != 3 || parts.any { it.isBlank() }) null else parts[0] to Origin(parts[1], parts[2])
|
||||||
|
}.toMap()
|
||||||
|
|
||||||
|
internal fun formatOrigins(origins: Map<String, Origin>): String =
|
||||||
|
origins.entries.sortedBy { it.key.lowercase() }.joinToString("") { (name, o) -> "$name\t${o.id}\t${o.version.replace(Regex("\\s+"), " ")}\n" }
|
||||||
|
|
||||||
|
private fun originsFile(target: Target) = File(target.addOns, ORIGINS)
|
||||||
|
|
||||||
|
private fun origins(target: Target): Map<String, Origin> =
|
||||||
|
runCatching { parseOrigins(originsFile(target).readText()) }.getOrDefault(emptyMap())
|
||||||
|
|
||||||
|
private val originsLock = Any()
|
||||||
|
|
||||||
|
private fun keepOrigins(target: Target, names: List<String>, origin: Origin?) = synchronized(originsLock) {
|
||||||
|
val current = origins(target)
|
||||||
|
val next = current - names.toSet() + (origin?.let { o -> names.associateWith { o } } ?: emptyMap())
|
||||||
|
if (next != current) {
|
||||||
|
val file = originsFile(target)
|
||||||
|
if (next.isEmpty()) file.delete() else {
|
||||||
|
val temp = File(target.addOns, "$ORIGINS.tmp")
|
||||||
|
temp.writeText(formatOrigins(next))
|
||||||
|
if (!temp.renameTo(file)) {
|
||||||
|
temp.delete()
|
||||||
|
throw IOException("Cannot save $ORIGINS")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun delete(target: Target, name: String) {
|
fun delete(target: Target, name: String) {
|
||||||
val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") }
|
val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") }
|
||||||
?: throw IOException("Cannot find $name")
|
?: throw IOException("Cannot find $name")
|
||||||
StoreInstalls.deleteTree(folder)
|
StoreInstalls.deleteTree(folder)
|
||||||
if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name")
|
if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name")
|
||||||
|
runCatching { keepOrigins(target, listOf(name), null) }
|
||||||
imports++
|
imports++
|
||||||
}
|
}
|
||||||
|
|
||||||
fun import(zipFile: File, target: Target): List<String> {
|
fun import(archive: File, target: Target, origin: Origin? = null, context: Context? = null): List<String> {
|
||||||
|
if (context == null || ItchArchives.kind(archive, archive.name) == "zip") return importZip(archive, target, origin)
|
||||||
|
val work = File(File(context.cacheDir, "wowaddons"), "unpack-${System.nanoTime()}")
|
||||||
|
try {
|
||||||
|
if (!work.mkdirs()) throw IOException("Cannot create ${work.path}")
|
||||||
|
val unpacker = StoreArchiveUnpacker(context, AtomicBoolean(), "Addons", R.string.stores_itch_archive, R.string.stores_itch_extract_failed, "addon-unpack")
|
||||||
|
unpacker.work = work
|
||||||
|
unpacker.limit = MAX_EXPANDED_BYTES
|
||||||
|
try {
|
||||||
|
unpacker.unpack(archive, archive.name, { _, _ -> }, {})
|
||||||
|
} catch (_: StoreArchiveUnpacker.TooLarge) {
|
||||||
|
throw TooLarge()
|
||||||
|
}
|
||||||
|
return importFolder(work, target, origin)
|
||||||
|
} finally {
|
||||||
|
StoreInstalls.deleteTree(work)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Entry(val path: String, val open: () -> InputStream)
|
||||||
|
|
||||||
|
private fun importZip(zipFile: File, target: Target, origin: Origin?): List<String> =
|
||||||
ZipFile.builder().setFile(zipFile).get().use { zip ->
|
ZipFile.builder().setFile(zipFile).get().use { zip ->
|
||||||
val all = zip.entries.toList()
|
val all = zip.entries.toList()
|
||||||
if (all.any { it.isUnixSymlink }) return emptyList()
|
if (all.any { it.isUnixSymlink }) return emptyList()
|
||||||
val entries = all.filter { clean(it.name) != null }
|
importEntries(all.filter { !it.isDirectory }.mapNotNull { entry -> clean(entry.name)?.let { Entry(it) { zip.getInputStream(entry) } } }, target, origin)
|
||||||
val addons = addons(entries.filter { !it.isDirectory }.mapNotNull { clean(it.name) })
|
}
|
||||||
if (addons.isEmpty()) return emptyList()
|
|
||||||
val addOns = target.addOns
|
internal fun importFolder(folder: File, target: Target, origin: Origin?): List<String> {
|
||||||
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
|
val entries = ArrayList<Entry>()
|
||||||
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
|
var links = false
|
||||||
try {
|
Files.walkFileTree(folder.toPath(), object : SimpleFileVisitor<Path>() {
|
||||||
val fresh = File(stage, "new")
|
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||||
val buffer = ByteArray(64 * 1024)
|
if (!attrs.isRegularFile) links = true
|
||||||
var written = 0L
|
else clean(folder.toPath().relativize(file).joinToString("/"))?.let { entries.add(Entry(it) { Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS) }) }
|
||||||
for (entry in entries) {
|
return if (links) FileVisitResult.TERMINATE else FileVisitResult.CONTINUE
|
||||||
if (entry.isDirectory) continue
|
}
|
||||||
val path = clean(entry.name) ?: continue
|
})
|
||||||
val addon = addons.firstOrNull { path.startsWith(it.root) } ?: continue
|
return if (links) emptyList() else importEntries(entries, target, origin)
|
||||||
val out = inside(fresh, addon.name + "/" + path.removePrefix(addon.root)) ?: continue
|
}
|
||||||
out.parentFile?.mkdirs()
|
|
||||||
zip.getInputStream(entry).use { input ->
|
private fun importEntries(entries: List<Entry>, target: Target, origin: Origin?): List<String> {
|
||||||
out.outputStream().use { output ->
|
val addons = addons(entries.map { it.path })
|
||||||
while (true) {
|
if (addons.isEmpty()) return emptyList()
|
||||||
val read = input.read(buffer)
|
val addOns = target.addOns
|
||||||
if (read < 0) break
|
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
|
||||||
written += read
|
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
|
||||||
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
|
try {
|
||||||
output.write(buffer, 0, read)
|
val fresh = File(stage, "new")
|
||||||
}
|
val buffer = ByteArray(64 * 1024)
|
||||||
|
var written = 0L
|
||||||
|
for (entry in entries) {
|
||||||
|
val addon = addons.firstOrNull { entry.path.startsWith(it.root) } ?: continue
|
||||||
|
val out = inside(fresh, addon.name + "/" + entry.path.removePrefix(addon.root)) ?: continue
|
||||||
|
out.parentFile?.mkdirs()
|
||||||
|
entry.open().use { input ->
|
||||||
|
out.outputStream().use { output ->
|
||||||
|
while (true) {
|
||||||
|
val read = input.read(buffer)
|
||||||
|
if (read < 0) break
|
||||||
|
written += read
|
||||||
|
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
|
||||||
|
output.write(buffer, 0, read)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
|
|
||||||
} finally {
|
|
||||||
StoreInstalls.deleteTree(stage)
|
|
||||||
}
|
}
|
||||||
imports++
|
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
|
||||||
return addons.map { it.name }
|
} finally {
|
||||||
|
StoreInstalls.deleteTree(stage)
|
||||||
}
|
}
|
||||||
|
runCatching { keepOrigins(target, addons.map { it.name }, origin) }
|
||||||
|
imports++
|
||||||
|
return addons.map { it.name }
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun addons(files: List<String>): List<Addon> {
|
internal fun addons(files: List<String>): List<Addon> {
|
||||||
|
|||||||
@@ -328,7 +328,7 @@ object BottomDesktop {
|
|||||||
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
||||||
}
|
}
|
||||||
val environment = if (current.nativeUserland) {
|
val environment = if (current.nativeUserland) {
|
||||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, SessionPrefs.guestHostname(context))
|
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
|
||||||
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||||
} else current.hostEnvironment
|
} else current.hostEnvironment
|
||||||
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||||
|
|||||||
@@ -88,8 +88,8 @@ object ComponentUpdater {
|
|||||||
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
|
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
|
||||||
|
|
||||||
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
|
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
|
||||||
if (!ComponentUpdates.follows(p) || !ComponentsManager.supports(p, comp)) return null
|
if (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
|
||||||
if (comp == "fex") return ComponentUpdates.line("fex", false)
|
if (comp == "fex") return ComponentUpdates.fexLine(p)
|
||||||
val key = "${p.id}|${p.version}"
|
val key = "${p.id}|${p.version}"
|
||||||
val flavors = state.obj("flavors").obj(key)
|
val flavors = state.obj("flavors").obj(key)
|
||||||
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
|
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ object ComponentUpdates {
|
|||||||
const val BOOTED_SECONDS = 60L
|
const val BOOTED_SECONDS = 60L
|
||||||
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
|
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
|
||||||
|
|
||||||
data class Line(val key: String, val comp: String, val prefix: String)
|
data class Line(val key: String, val comp: String, val prefix: String, val release: String = ComponentsManager.DD_NIGHTLY)
|
||||||
|
|
||||||
val LINES = listOf(
|
val LINES = listOf(
|
||||||
Line("dxvk", "dxvk", "DD-dxvk-"),
|
Line("dxvk", "dxvk", "DD-dxvk-"),
|
||||||
@@ -21,12 +21,19 @@ object ComponentUpdates {
|
|||||||
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
|
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
|
||||||
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
|
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
|
||||||
Line("fex", "fex", "DD-FEXCore-"),
|
Line("fex", "fex", "DD-FEXCore-"),
|
||||||
|
Line("fex-bionic", "fex", "FEXCore-", ComponentsManager.DD_BIONIC),
|
||||||
)
|
)
|
||||||
|
|
||||||
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
|
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
|
||||||
|
|
||||||
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
|
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
|
||||||
|
|
||||||
|
fun autoFollows(p: ComponentsManager.Proton, comp: String): Boolean =
|
||||||
|
follows(p) || (comp == "fex" && !p.valve && ComponentsManager.bionicTool(p.dir.name))
|
||||||
|
|
||||||
|
fun fexLine(p: ComponentsManager.Proton): Line =
|
||||||
|
if (ComponentsManager.bionicTool(p.dir.name)) LINES.first { it.release == ComponentsManager.DD_BIONIC } else line("fex", false)
|
||||||
|
|
||||||
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
|
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
|
||||||
|
|
||||||
fun strays(
|
fun strays(
|
||||||
@@ -34,8 +41,8 @@ object ComponentUpdates {
|
|||||||
choices: Map<String, Map<String, ComponentsManager.Choice>>,
|
choices: Map<String, Map<String, ComponentsManager.Choice>>,
|
||||||
placed: Set<String>,
|
placed: Set<String>,
|
||||||
): List<Pair<ComponentsManager.Proton, String>> =
|
): List<Pair<ComponentsManager.Proton, String>> =
|
||||||
protons.filterNot(::follows).flatMap { p ->
|
protons.flatMap { p ->
|
||||||
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
|
choices[p.id].orEmpty().filter { (comp, c) -> !autoFollows(p, comp) && !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun unseen(
|
fun unseen(
|
||||||
@@ -53,13 +60,14 @@ object ComponentUpdates {
|
|||||||
|
|
||||||
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
|
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
|
||||||
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
|
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
|
||||||
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
|
return items.filter { it.release == line.release && it.comp == line.comp && belongs(it.file, line) }
|
||||||
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
|
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
|
||||||
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
|
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun belongs(file: String, line: Line): Boolean =
|
fun belongs(file: String, line: Line): Boolean =
|
||||||
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
|
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true &&
|
||||||
|
(line.comp != "fex" || ComponentsManager.bionicFex(file) == (line.release == ComponentsManager.DD_BIONIC))
|
||||||
|
|
||||||
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
|
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
|
||||||
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
|
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
|
||||||
@@ -161,7 +169,7 @@ object ComponentUpdates {
|
|||||||
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
|
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
|
||||||
val ranked = line?.takeIf { belongs(current, it) }
|
val ranked = line?.takeIf { belongs(current, it) }
|
||||||
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
|
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
|
||||||
return (owned + stored.filter { ranked != null && belongs(it, ranked) })
|
return (owned + stored.filter { ranked != null && ranked.release == ComponentsManager.DD_NIGHTLY && belongs(it, ranked) })
|
||||||
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
|
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,6 +29,7 @@ object ComponentsManager {
|
|||||||
private const val NIGHTLIES = "The412Banner/Nightlies"
|
private const val NIGHTLIES = "The412Banner/Nightlies"
|
||||||
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
|
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
|
||||||
internal const val DD_NIGHTLY = "linux-nightly"
|
internal const val DD_NIGHTLY = "linux-nightly"
|
||||||
|
internal const val DD_BIONIC = "bionic-stable"
|
||||||
private val RELEASES = linkedMapOf(
|
private val RELEASES = linkedMapOf(
|
||||||
"FexCore-Linux" to "fex",
|
"FexCore-Linux" to "fex",
|
||||||
"Dxvk-Linux" to "dxvk",
|
"Dxvk-Linux" to "dxvk",
|
||||||
@@ -37,9 +38,9 @@ object ComponentsManager {
|
|||||||
"Vkd3d-proton-Linux" to "vkd3d",
|
"Vkd3d-proton-Linux" to "vkd3d",
|
||||||
)
|
)
|
||||||
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
|
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
|
||||||
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
|
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
|
||||||
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
|
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
|
||||||
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
|
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
|
||||||
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
|
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
|
||||||
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
||||||
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
|
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
|
||||||
@@ -201,8 +202,34 @@ object ComponentsManager {
|
|||||||
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
|
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) {
|
||||||
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
|
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
|
||||||
|
if (comp == "fex" && file != null) fetchFexTwin(context, safeName(file))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Twin downloads in flight: one worker per name, so two profile changes cannot share one partial download.
|
||||||
|
private val twinDownloads = HashSet<String>()
|
||||||
|
|
||||||
|
private fun fetchFexTwin(context: Context, file: String) {
|
||||||
|
val twin = fexTwin(file) ?: return
|
||||||
|
if (protons(context).all { fexFits(it.dir.name, file) }) return
|
||||||
|
synchronized(lock) { if (isStored(context, twin) || !twinDownloads.add(twin)) return }
|
||||||
|
val app = context.applicationContext
|
||||||
|
Thread({
|
||||||
|
try {
|
||||||
|
runCatching {
|
||||||
|
val item = catalogItem(app, twin, if (bionicFex(twin)) DD_BIONIC else "FexCore-Linux")
|
||||||
|
if (item == null) Log.i(TAG, "$twin is not listed")
|
||||||
|
else {
|
||||||
|
download(app, item) {}
|
||||||
|
republish(app)
|
||||||
|
}
|
||||||
|
}.onFailure { Log.w(TAG, "download $twin", it) }
|
||||||
|
} finally {
|
||||||
|
synchronized(lock) { twinDownloads.remove(twin) }
|
||||||
|
}
|
||||||
|
}, "fex-twin").start()
|
||||||
|
}
|
||||||
|
|
||||||
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
|
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
|
||||||
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
||||||
@@ -238,6 +265,20 @@ object ComponentsManager {
|
|||||||
saveState(context, state)
|
saveState(context, state)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val UNPINNED_FEX = Regex("""(?i)FEXCore-\d+(?:\.\d+)*-d2rfix\d+-linux\.wcp""")
|
||||||
|
|
||||||
|
fun migrateBattleNetFex(context: Context) = synchronized(lock) {
|
||||||
|
val marker = File(dataDir(context), ".battlenet-fex-unpinned")
|
||||||
|
if (marker.isFile) return@synchronized
|
||||||
|
migratePlugin(context)
|
||||||
|
val scope = com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
|
||||||
|
if (gameComponents(context, scope)["fex"]?.let(UNPINNED_FEX::matches) == true) {
|
||||||
|
setGameComponent(context, scope, "fex", null)
|
||||||
|
Log.i(TAG, "Battle.net follows the selected FEX again")
|
||||||
|
}
|
||||||
|
marker.writeText("1\n")
|
||||||
|
}
|
||||||
|
|
||||||
private fun migratePlugin(context: Context) {
|
private fun migratePlugin(context: Context) {
|
||||||
val marker = File(dataDir(context), ".plugin-imported")
|
val marker = File(dataDir(context), ".plugin-imported")
|
||||||
if (marker.isFile) return
|
if (marker.isFile) return
|
||||||
@@ -399,7 +440,7 @@ object ComponentsManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
|
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
|
||||||
if (comp == "fex") FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
|
if (comp == "fex" && !bionicTool(dir.name)) FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
|
||||||
COMP_DIR[comp]?.let { compDir ->
|
COMP_DIR[comp]?.let { compDir ->
|
||||||
for (arch in PE_ARCHES) {
|
for (arch in PE_ARCHES) {
|
||||||
val target = File(dir, "$compDir/$arch")
|
val target = File(dir, "$compDir/$arch")
|
||||||
@@ -487,6 +528,7 @@ object ComponentsManager {
|
|||||||
|
|
||||||
fun snapshotAll(context: Context) = synchronized(lock) {
|
fun snapshotAll(context: Context) = synchronized(lock) {
|
||||||
migratePlugin(context)
|
migratePlugin(context)
|
||||||
|
runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
|
||||||
val state = loadState(context)
|
val state = loadState(context)
|
||||||
for (p in protons(context)) for (comp in COMPONENTS) {
|
for (p in protons(context)) for (comp in COMPONENTS) {
|
||||||
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
|
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
|
||||||
@@ -497,6 +539,7 @@ object ComponentsManager {
|
|||||||
|
|
||||||
fun snapshot(context: Context): Snapshot = synchronized(lock) {
|
fun snapshot(context: Context): Snapshot = synchronized(lock) {
|
||||||
migratePlugin(context)
|
migratePlugin(context)
|
||||||
|
runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
|
||||||
val state = loadState(context)
|
val state = loadState(context)
|
||||||
val reapplied = HashMap<String, Long>()
|
val reapplied = HashMap<String, Long>()
|
||||||
runCatching {
|
runCatching {
|
||||||
@@ -587,7 +630,9 @@ object ComponentsManager {
|
|||||||
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
||||||
.filter { owned(comp, it) }.associateWith { File(base, it) }
|
.filter { owned(comp, it) }.associateWith { File(base, it) }
|
||||||
}
|
}
|
||||||
for (rel in managed(comp) - files.keys) {
|
// A bionic tool never loses a FEX file: its launch.sh would put the whole bundled FEX back.
|
||||||
|
val removed = if (comp == "fex" && bionicTool(p.dir.name)) emptySet() else managed(comp) - files.keys
|
||||||
|
for (rel in removed) {
|
||||||
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
|
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
|
||||||
.append('\t').append(rel).append("\t-\t-\n")
|
.append('\t').append(rel).append("\t-\t-\n")
|
||||||
}
|
}
|
||||||
@@ -604,7 +649,8 @@ object ComponentsManager {
|
|||||||
val version = safeName(file.removePrefix("original "))
|
val version = safeName(file.removePrefix("original "))
|
||||||
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
||||||
} else {
|
} else {
|
||||||
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
|
val fit = (if (comp == "fex") launchFex(p.dir.name, file) { File(packagesDir(context), it).isFile } else file) ?: return null
|
||||||
|
safeName(fit.removeSuffix(".wcp")) to File(packagesDir(context), fit)
|
||||||
}.takeIf { it.second.isFile }
|
}.takeIf { it.second.isFile }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -635,12 +681,14 @@ object ComponentsManager {
|
|||||||
for (scope in profiles.keys()) {
|
for (scope in profiles.keys()) {
|
||||||
val profile = profiles.optJSONObject(scope) ?: continue
|
val profile = profiles.optJSONObject(scope) ?: continue
|
||||||
for (comp in COMPONENTS) {
|
for (comp in COMPONENTS) {
|
||||||
val file = profile.optString(comp)
|
val chosen = profile.optString(comp)
|
||||||
if (file.isEmpty()) continue
|
if (chosen.isEmpty()) continue
|
||||||
val wcp = File(packagesDir(context), file)
|
for (p in all) {
|
||||||
if (!wcp.isFile) continue
|
val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
|
||||||
val key = safeName(file.removeSuffix(".wcp"))
|
val wcp = File(packagesDir(context), file)
|
||||||
for (p in all) append(scope, p, comp, key, wcp)
|
if (!wcp.isFile) continue
|
||||||
|
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return PreparedLaunchState(lines.toString(), keep)
|
return PreparedLaunchState(lines.toString(), keep)
|
||||||
@@ -661,6 +709,7 @@ object ComponentsManager {
|
|||||||
val wcp = File(packagesDir(context), safeName(file))
|
val wcp = File(packagesDir(context), safeName(file))
|
||||||
val info = packageInfo(context, wcp)
|
val info = packageInfo(context, wcp)
|
||||||
requireSelectable(context, info.comp)
|
requireSelectable(context, info.comp)
|
||||||
|
requireFits(p, info)
|
||||||
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)
|
||||||
@@ -674,7 +723,11 @@ object ComponentsManager {
|
|||||||
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
|
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun requireFits(p: Proton, info: Package) =
|
||||||
|
check(info.comp != "fex" || fexFits(p.dir.name, info.file)) { "${info.file} is not a FEX build for ${p.name}" }
|
||||||
|
|
||||||
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
|
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
|
||||||
|
requireFits(p, info)
|
||||||
ensureOriginal(context, p, info.comp, state)
|
ensureOriginal(context, p, info.comp, state)
|
||||||
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
||||||
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
||||||
@@ -787,6 +840,18 @@ object ComponentsManager {
|
|||||||
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
|
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
|
||||||
installs?.any { liveSelection(key, entry, it) } == true
|
installs?.any { liveSelection(key, entry, it) } == true
|
||||||
|
|
||||||
|
// An installed tool that launches with `name` as the stored twin of a game's FEX choice (a Linux choice on
|
||||||
|
// DroidDeck-Bionic, a -bionic one on another Proton): deleting the twin would drop that choice for that tool.
|
||||||
|
internal fun twinUser(state: JSONObject, installed: List<Proton>, name: String): Proton? {
|
||||||
|
val profiles = state.optJSONObject("profiles") ?: return null
|
||||||
|
for (scope in profiles.keys()) {
|
||||||
|
val chosen = profiles.optJSONObject(scope)?.optString("fex")?.takeIf { it.isNotEmpty() } ?: continue
|
||||||
|
if (fexTwin(chosen) != name) continue
|
||||||
|
installed.firstOrNull { !fexFits(it.dir.name, chosen) }?.let { return it }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
|
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
|
||||||
val byId = installed.groupBy { it.id }
|
val byId = installed.groupBy { it.id }
|
||||||
val names = HashSet<String>()
|
val names = HashSet<String>()
|
||||||
@@ -803,7 +868,11 @@ object ComponentsManager {
|
|||||||
val profiles = state.optJSONObject("profiles")
|
val profiles = state.optJSONObject("profiles")
|
||||||
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
|
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
|
||||||
val profile = profiles?.optJSONObject(scope) ?: continue
|
val profile = profiles?.optJSONObject(scope) ?: continue
|
||||||
COMPONENTS.forEach { comp -> profile.optString(comp).takeIf { it.isNotEmpty() }?.let(names::add) }
|
COMPONENTS.forEach { comp ->
|
||||||
|
val file = profile.optString(comp).takeIf { it.isNotEmpty() } ?: return@forEach
|
||||||
|
names.add(file)
|
||||||
|
if (comp == "fex" && installed.any { !fexFits(it.dir.name, file) }) fexTwin(file)?.let(names::add)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return names
|
return names
|
||||||
}
|
}
|
||||||
@@ -874,6 +943,7 @@ object ComponentsManager {
|
|||||||
val queued = state.sub("queued").sub(target.id)
|
val queued = state.sub("queued").sub(target.id)
|
||||||
var changed = false
|
var changed = false
|
||||||
wanted.forEach { (comp, entry) ->
|
wanted.forEach { (comp, entry) ->
|
||||||
|
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
|
||||||
if (active?.has(comp) != true && !queued.has(comp)) {
|
if (active?.has(comp) != true && !queued.has(comp)) {
|
||||||
queued.put(comp, entry)
|
queued.put(comp, entry)
|
||||||
changed = true
|
changed = true
|
||||||
@@ -954,6 +1024,8 @@ object ComponentsManager {
|
|||||||
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
|
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
|
||||||
val name = safeName(file)
|
val name = safeName(file)
|
||||||
val state = loadState(context)
|
val state = loadState(context)
|
||||||
|
val twinTool = twinUser(state, protons(context), name)
|
||||||
|
check(twinTool == null) { context.getString(R.string.cmgr_package_in_use, name, twinTool?.name ?: "") }
|
||||||
val installed = protons(context).groupBy { it.id }
|
val installed = protons(context).groupBy { it.id }
|
||||||
var changed = false
|
var changed = false
|
||||||
for (key in listOf("queued", "active")) {
|
for (key in listOf("queued", "active")) {
|
||||||
@@ -1050,8 +1122,11 @@ object ComponentsManager {
|
|||||||
return Catalog(items, o.optLong("fetchedAt"))
|
return Catalog(items, o.optLong("fetchedAt"))
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun assetComp(release: String, name: String): String? =
|
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
|
||||||
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
|
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
|
||||||
|
DD_BIONIC -> "fex"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
internal val CATALOG_ORDER: Comparator<CatalogItem> =
|
internal val CATALOG_ORDER: Comparator<CatalogItem> =
|
||||||
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
|
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
|
||||||
@@ -1139,6 +1214,25 @@ object ComponentsManager {
|
|||||||
return runCatching { readWcpEntry(original, rel) }.getOrNull()
|
return runCatching { readWcpEntry(original, rel) }.getOrNull()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DroidDeck-Bionic loads only Android builds of FEX's unix libraries; other Protons only glibc builds.
|
||||||
|
internal fun bionicTool(dirName: String?): Boolean = dirName?.startsWith("DroidDeck-Bionic") == true
|
||||||
|
|
||||||
|
internal fun bionicFex(file: String): Boolean = file.endsWith("-bionic.wcp", ignoreCase = true)
|
||||||
|
|
||||||
|
internal fun fexFits(toolDir: String?, file: String): Boolean = bionicTool(toolDir) == bionicFex(file)
|
||||||
|
|
||||||
|
internal fun fexTwin(file: String): String? = when {
|
||||||
|
file.endsWith("-linux.wcp", ignoreCase = true) -> file.dropLast("-linux.wcp".length) + "-bionic.wcp"
|
||||||
|
file.endsWith("-bionic.wcp", ignoreCase = true) -> file.dropLast("-bionic.wcp".length) + "-linux.wcp"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun launchFex(toolDir: String, file: String, stored: (String) -> Boolean): String? =
|
||||||
|
if (fexFits(toolDir, file)) file else fexTwin(file)?.takeIf(stored)
|
||||||
|
|
||||||
|
internal fun <T> forTool(comp: String, toolDir: String?, items: List<T>, selected: String? = null, file: (T) -> String): List<T> =
|
||||||
|
if (comp != "fex") items else items.filter { file(it) == selected || fexFits(toolDir, file(it)) }
|
||||||
|
|
||||||
fun supports(p: Proton, comp: String): Boolean =
|
fun supports(p: Proton, comp: String): Boolean =
|
||||||
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
|
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.stores.StoreInstalls
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
object CpuCacheSysfs {
|
||||||
|
private const val TAG = "SessionService"
|
||||||
|
private val FEX_CPUID_SIZE_KB = mapOf(1 to 32, 2 to 512, 3 to 8192)
|
||||||
|
|
||||||
|
private val PROCESS = java.util.UUID.randomUUID().toString()
|
||||||
|
private val STARTS = java.util.concurrent.atomic.AtomicInteger()
|
||||||
|
|
||||||
|
fun binds(root: File, start: Int = STARTS.incrementAndGet(), host: File = File("/sys/devices/system/cpu"), process: String = PROCESS): List<String> = try {
|
||||||
|
root.listFiles()?.forEach { old -> if (old.name != process) StoreInstalls.deleteTree(old) }
|
||||||
|
val dir = File(root, "$process/$start")
|
||||||
|
StoreInstalls.deleteTree(dir)
|
||||||
|
val cpus = host.list { _, name -> name.matches(Regex("cpu\\d+")) }?.sorted().orEmpty()
|
||||||
|
val binds = cpus.mapNotNull { cpu ->
|
||||||
|
val staged = try {
|
||||||
|
stage(File(host, "$cpu/cache"), File(dir, cpu))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "cpu cache: could not stage $cpu: $e")
|
||||||
|
false
|
||||||
|
}
|
||||||
|
if (staged) File(dir, cpu).path + ":" + File(host, "$cpu/cache").path else null
|
||||||
|
}
|
||||||
|
Log.i(TAG, "cpu cache: ${binds.size} of ${cpus.size} cores report the sizes the x86 CPUID reports")
|
||||||
|
binds
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "cpu cache: could not stage the core caches: $e")
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stage(cache: File, out: File): Boolean {
|
||||||
|
val indexes = cache.listFiles { f -> f.isDirectory && f.name.matches(Regex("index\\d+")) } ?: return false
|
||||||
|
var staged = false
|
||||||
|
for (index in indexes) {
|
||||||
|
val target = File(out, index.name).apply { mkdirs() }
|
||||||
|
val kb = runCatching { File(index, "level").readText().trim().toInt() }.getOrNull()?.let { FEX_CPUID_SIZE_KB[it] }
|
||||||
|
val files = index.listFiles { f -> f.isFile } ?: throw java.io.IOException("cannot list $index")
|
||||||
|
for (f in files) {
|
||||||
|
if (kb != null && f.name == "size") continue
|
||||||
|
File(target, f.name).writeText(f.readText())
|
||||||
|
}
|
||||||
|
if (kb == null) continue
|
||||||
|
File(target, "size").writeText("${kb}K\n")
|
||||||
|
staged = true
|
||||||
|
}
|
||||||
|
return staged
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -935,9 +935,9 @@ internal object EnhancedSessionLogShare {
|
|||||||
|
|
||||||
private fun category(entry: String): Category {
|
private fun category(entry: String): Category {
|
||||||
val value = entry.lowercase(Locale.US)
|
val value = entry.lowercase(Locale.US)
|
||||||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
|
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
|
||||||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
||||||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
|
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
|
||||||
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
||||||
return Category.SESSION
|
return Category.SESSION
|
||||||
}
|
}
|
||||||
@@ -948,8 +948,9 @@ internal object EnhancedSessionLogShare {
|
|||||||
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
||||||
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
|
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
|
||||||
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
||||||
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
|
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "droiddeck-bionic.log",
|
||||||
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
|
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
|
||||||
|
"rpcs3", "RPCS3.log",
|
||||||
)
|
)
|
||||||
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
||||||
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
|
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
|
||||||
|
|||||||
@@ -74,10 +74,16 @@ object ExperimentalProtons {
|
|||||||
return PREFIX + base + (tag?.let { "-$it" } ?: "")
|
return PREFIX + base + (tag?.let { "-$it" } ?: "")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** DroidDeck-Bionic test builds are prereleases of the same repository and have their own row in the Proton list. */
|
||||||
|
internal fun listed(assets: List<ProtonExtras.Asset>): List<ProtonExtras.Asset> {
|
||||||
|
val bionic = ProtonExtras.tools.first { it.id == ProtonExtras.BIONIC }
|
||||||
|
return assets.filterNot { bionic.assetPattern.containsMatchIn(it.name) }
|
||||||
|
}
|
||||||
|
|
||||||
fun refresh(context: Context): List<Release>? {
|
fun refresh(context: Context): List<Release>? {
|
||||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||||
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
|
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
|
||||||
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
|
val assets = listed(ProtonExtras.assets(tool, fetched.releases, prerelease = true))
|
||||||
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
|
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
|
||||||
if (!SessionState.running) {
|
if (!SessionState.running) {
|
||||||
reconcile(context, fetched)
|
reconcile(context, fetched)
|
||||||
|
|||||||
@@ -43,6 +43,17 @@ object GameStorage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun isFat32(path: String): Boolean = runCatching { isFat32(path, File("/proc/mounts").readText()) }.getOrDefault(false)
|
||||||
|
|
||||||
|
/** Android mounts FAT32 as vfat and exFAT as exfat; /storage is a FUSE view, so the lookup uses the raw mount. */
|
||||||
|
internal fun isFat32(path: String, mounts: String): Boolean {
|
||||||
|
val raw = UsbLink.rawPath(path)
|
||||||
|
return mounts.lineSequence().map { it.split(' ') }
|
||||||
|
.filter { it.size >= 3 }
|
||||||
|
.filter { val point = it[1].replace("\\040", " "); raw == point || raw.startsWith("${point.trimEnd('/')}/") }
|
||||||
|
.maxByOrNull { it[1].length }?.get(2) == "vfat"
|
||||||
|
}
|
||||||
|
|
||||||
fun effective(context: Context): Option? {
|
fun effective(context: Context): Option? {
|
||||||
val pref = SessionPrefs.gameStorage(context)
|
val pref = SessionPrefs.gameStorage(context)
|
||||||
return when {
|
return when {
|
||||||
|
|||||||
@@ -27,14 +27,14 @@ object GameThreadHints {
|
|||||||
private const val PACE_TOLERANCE = 0.08
|
private const val PACE_TOLERANCE = 0.08
|
||||||
|
|
||||||
private val NOT_GAMES = setOf("steam", "steamwebhelper")
|
private val NOT_GAMES = setOf("steam", "steamwebhelper")
|
||||||
private val SOCS = setOf("CQ8725S", "SM8750")
|
private val SOCS = setOf("CQ8725S", "SM8750", "SM8750P")
|
||||||
|
|
||||||
private var worker: Thread? = null
|
private var worker: Thread? = null
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun start(context: Context): String {
|
fun start(context: Context): String {
|
||||||
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
|
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
|
||||||
if (Build.VERSION.SDK_INT < 31 || !supported(Build.SOC_MODEL)) return "game thread hints: Snapdragon 8 Elite only"
|
if (Build.VERSION.SDK_INT < 31 || !supported(SocNames.model())) return "game thread hints: Snapdragon 8 Elite only"
|
||||||
val hm = context.getSystemService(PerformanceHintManager::class.java)
|
val hm = context.getSystemService(PerformanceHintManager::class.java)
|
||||||
?: return "game thread hints: no PerformanceHintManager"
|
?: return "game thread hints: no PerformanceHintManager"
|
||||||
val pm = context.getSystemService(PowerManager::class.java)
|
val pm = context.getSystemService(PowerManager::class.java)
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Orders launch attempts and at most one pending game link.
|
||||||
|
*
|
||||||
|
* This is main-thread state: call it from the UI thread. A ticket is an identity,
|
||||||
|
* not a counter comparison, so a stale callback can only act on its own request.
|
||||||
|
*/
|
||||||
|
internal class LaunchTicket internal constructor(val serial: Long)
|
||||||
|
|
||||||
|
internal class LaunchCoordinator<O : Any, R : Any> {
|
||||||
|
internal class Link<O : Any, R : Any> internal constructor(
|
||||||
|
val ticket: LaunchTicket,
|
||||||
|
val owner: O,
|
||||||
|
val request: R?,
|
||||||
|
) {
|
||||||
|
/** Only the activity intent that delivered this link may finish it by a refresh. */
|
||||||
|
fun ownedBy(owner: O?): Boolean = this.owner === owner
|
||||||
|
}
|
||||||
|
|
||||||
|
private var next = 0L
|
||||||
|
private var current: LaunchTicket? = null
|
||||||
|
private var pending: Link<O, R>? = null
|
||||||
|
private var handling: LaunchTicket? = null
|
||||||
|
|
||||||
|
/** A launch that is allowed to proceed; it supersedes any pending link. */
|
||||||
|
fun beginLaunch(): LaunchTicket {
|
||||||
|
val ticket = LaunchTicket(++next)
|
||||||
|
current = ticket
|
||||||
|
pending = null
|
||||||
|
handling = null
|
||||||
|
return ticket
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A game-link intent; it supersedes any earlier launch or link. */
|
||||||
|
fun beginLink(owner: O): LaunchTicket {
|
||||||
|
val ticket = LaunchTicket(++next)
|
||||||
|
current = ticket
|
||||||
|
pending = Link(ticket, owner, null)
|
||||||
|
handling = null
|
||||||
|
return ticket
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The asynchronous link read returned; false means a newer request won. */
|
||||||
|
fun resolve(ticket: LaunchTicket, request: R?): Boolean {
|
||||||
|
val link = pending ?: return false
|
||||||
|
if (link.ticket !== ticket) return false
|
||||||
|
pending = Link(ticket, link.owner, request)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun beginHandling(ticket: LaunchTicket): Boolean {
|
||||||
|
val link = pending ?: return false
|
||||||
|
if (link.ticket !== ticket || link.request == null) return false
|
||||||
|
handling = ticket
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun releaseHandling(ticket: LaunchTicket) {
|
||||||
|
if (handling === ticket) handling = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isHandling(ticket: LaunchTicket): Boolean = handling === ticket
|
||||||
|
fun isCurrent(ticket: LaunchTicket): Boolean = current === ticket
|
||||||
|
fun hasPending(): Boolean = pending != null
|
||||||
|
fun pendingLink(): Link<O, R>? = pending
|
||||||
|
|
||||||
|
fun consume(ticket: LaunchTicket): Boolean {
|
||||||
|
val link = pending ?: return false
|
||||||
|
if (link.ticket !== ticket) return false
|
||||||
|
pending = null
|
||||||
|
handling = null
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancelAll() {
|
||||||
|
next++
|
||||||
|
current = null
|
||||||
|
pending = null
|
||||||
|
handling = null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,15 @@ import java.io.RandomAccessFile
|
|||||||
import java.nio.charset.StandardCharsets
|
import java.nio.charset.StandardCharsets
|
||||||
|
|
||||||
class LoadingState(context: Context, private val steam: Boolean = true) {
|
class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||||
var visible by mutableStateOf(true)
|
private val prefs = context.getSharedPreferences("loading", Context.MODE_PRIVATE)
|
||||||
|
private val firstRun = steam && !prefs.getBoolean(FIRST_DONE, false)
|
||||||
|
private var shown by mutableStateOf(true)
|
||||||
|
var visible: Boolean
|
||||||
|
get() = shown
|
||||||
|
set(value) {
|
||||||
|
shown = value
|
||||||
|
if (!value && steam) prefs.edit().putBoolean(FIRST_DONE, true).apply()
|
||||||
|
}
|
||||||
var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting))
|
var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting))
|
||||||
private set
|
private set
|
||||||
var topic by mutableStateOf(Topic.SESSION)
|
var topic by mutableStateOf(Topic.SESSION)
|
||||||
@@ -33,7 +41,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
|||||||
fun tick() {
|
fun tick() {
|
||||||
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
|
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
|
||||||
elapsed = res.getString(com.droiddeck.launcher.R.string.loadstate_elapsed, 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 = if (firstRun) res.getString(com.droiddeck.launcher.R.string.loading_first_run) else hints[((seconds / 8) % hints.size).toInt()]
|
||||||
}
|
}
|
||||||
|
|
||||||
fun say(line: String, topic: Topic, readable: Boolean) {
|
fun say(line: String, topic: Topic, readable: Boolean) {
|
||||||
@@ -59,6 +67,8 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
|||||||
|
|
||||||
private class Line(val line: String, val percent: Int, val topic: Topic, val readable: Boolean)
|
private class Line(val line: String, val percent: Int, val topic: Topic, val readable: Boolean)
|
||||||
|
|
||||||
|
private var scriptStep: Line? = null
|
||||||
|
|
||||||
private fun read(context: Context, log: File?): Line? {
|
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 {
|
||||||
@@ -81,6 +91,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
|||||||
var clientDownloadAt = -1
|
var clientDownloadAt = -1
|
||||||
var clientDownload: String? = null
|
var clientDownload: String? = null
|
||||||
var clientPercent = -1
|
var clientPercent = -1
|
||||||
|
var unknownAt = -1
|
||||||
var offset = 0
|
var offset = 0
|
||||||
for (line in text.split('\n')) {
|
for (line in text.split('\n')) {
|
||||||
val at = offset
|
val at = offset
|
||||||
@@ -95,16 +106,34 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
val m = UPDATE_PROGRESS.find(line)
|
val m = UPDATE_PROGRESS.find(line)
|
||||||
|
val p = if (m == null && steam) UPDATE_PERCENT.find(line) else null
|
||||||
if (m != null) {
|
if (m != null) {
|
||||||
downloadAt = at
|
downloadAt = at
|
||||||
val done = m.groupValues[1].toLong()
|
val done = m.groupValues[1].replace(",", "").toLong()
|
||||||
val total = maxOf(1L, m.groupValues[2].toLong())
|
val total = maxOf(1L, m.groupValues[2].replace(",", "").toLong())
|
||||||
downloadPercent = (done * 100 / total).toInt()
|
downloadPercent = (done * 100 / total).toInt()
|
||||||
|
} else if (p != null) {
|
||||||
|
val percent = p.groupValues[1].toIntOrNull() ?: continue
|
||||||
|
if (percent < 0) {
|
||||||
|
downloadAt = -1
|
||||||
|
unknownAt = at
|
||||||
|
} else if (percent > 0 && applyingAt <= stepAt) {
|
||||||
|
downloadAt = at
|
||||||
|
downloadPercent = percent.coerceAtMost(100)
|
||||||
|
}
|
||||||
} else if (steam && UPDATE_APPLYING.matches(line)) {
|
} else if (steam && UPDATE_APPLYING.matches(line)) {
|
||||||
applyingAt = at
|
applyingAt = at
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val stepLine = when {
|
||||||
|
clientDownloadAt == stepAt && clientDownload != null -> Line(
|
||||||
|
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent,
|
||||||
|
Topic.STEAM, readable = true,
|
||||||
|
)
|
||||||
|
stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText))
|
||||||
|
else -> null
|
||||||
|
}?.also { scriptStep = it }
|
||||||
return when {
|
return when {
|
||||||
applyingAt > stepAt && applyingAt > downloadAt -> Line(
|
applyingAt > stepAt && applyingAt > downloadAt -> Line(
|
||||||
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1,
|
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1,
|
||||||
@@ -114,11 +143,10 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
|||||||
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent,
|
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent,
|
||||||
Topic.STEAM, readable = true,
|
Topic.STEAM, readable = true,
|
||||||
)
|
)
|
||||||
clientDownloadAt == stepAt && clientDownload != null -> Line(
|
stepLine != null -> stepLine
|
||||||
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent,
|
unknownAt >= 0 -> scriptStep ?: Line(
|
||||||
Topic.STEAM, readable = true,
|
context.getString(com.droiddeck.launcher.R.string.loadstate_starting), -1, Topic.SESSION, readable = false,
|
||||||
)
|
)
|
||||||
stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText))
|
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -126,6 +154,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
|||||||
enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER }
|
enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER }
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
private const val FIRST_DONE = "first_done"
|
||||||
internal fun topicOf(scriptStep: String, steam: Boolean): Topic {
|
internal fun topicOf(scriptStep: String, steam: Boolean): Topic {
|
||||||
val t = scriptStep.lowercase()
|
val t = scriptStep.lowercase()
|
||||||
return when {
|
return when {
|
||||||
@@ -157,7 +186,8 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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 UPDATE_PERCENT = Regex("""^\[[^\]]+\] Set percent complete: (-?\d+)\s*$""")
|
||||||
private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""")
|
private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""")
|
||||||
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
|
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
|
||||||
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
|
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
|
||||||
|
|||||||
@@ -2,16 +2,20 @@ package com.droiddeck.launcher.session
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.agent.AgentGuest
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
object OfflineMode {
|
object OfflineMode {
|
||||||
private const val TAG = "OfflineMode"
|
private const val TAG = "OfflineMode"
|
||||||
private const val KEY = "steam_offline"
|
private const val KEY = "steam_offline"
|
||||||
|
private const val AUTO_KEY = "steam_offline_auto"
|
||||||
|
private const val NETWORK_KEY = "steam_offline_by_network"
|
||||||
private val WANTS = Regex("""^(\s*"WantsOfflineMode"\s*")([01])(".*)$""")
|
private val WANTS = Regex("""^(\s*"WantsOfflineMode"\s*")([01])(".*)$""")
|
||||||
private val SKIP = Regex("""^(\s*"SkipOfflineModeWarning"\s*")([01])(".*)$""")
|
private val SKIP = Regex("""^(\s*"SkipOfflineModeWarning"\s*")([01])(".*)$""")
|
||||||
private val REMEMBER = Regex(""""RememberPassword"\s*"1"""")
|
private val REMEMBER = Regex(""""RememberPassword"\s*"1"""")
|
||||||
private val PERSONA = Regex(""""PersonaName"\s*"([^"]*)"""")
|
private val PERSONA = Regex(""""PersonaName"\s*"([^"]*)"""")
|
||||||
|
private const val EVAL_TIMEOUT_MS = 10_000L
|
||||||
|
|
||||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
@@ -19,10 +23,12 @@ object OfflineMode {
|
|||||||
|
|
||||||
private fun x64LoginUsers(root: File) = File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf")
|
private fun x64LoginUsers(root: File) = File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf")
|
||||||
|
|
||||||
fun account(context: Context): String? {
|
private fun activeLoginUsers(context: Context, root: File) =
|
||||||
val root = LinuxRuntime.rootDir(context)
|
x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
|
||||||
val file = x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
|
|
||||||
?: loginUsers(root)
|
?: loginUsers(root)
|
||||||
|
|
||||||
|
fun account(context: Context): String? {
|
||||||
|
val file = activeLoginUsers(context, LinuxRuntime.rootDir(context))
|
||||||
val text = try {
|
val text = try {
|
||||||
if (file.isFile) file.readText() else return null
|
if (file.isFile) file.readText() else return null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -32,21 +38,114 @@ object OfflineMode {
|
|||||||
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty()
|
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
|
private fun steamWants(context: Context, root: File): Boolean? {
|
||||||
|
val file = activeLoginUsers(context, root)
|
||||||
|
val lines = try {
|
||||||
|
if (file.isFile) file.readLines() else return null
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "could not read loginusers.vdf", e); return null
|
||||||
|
}
|
||||||
|
val values = lines.mapNotNull { WANTS.matchEntire(it)?.groupValues?.get(2) }
|
||||||
|
return if (values.isEmpty()) null else "1" in values
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun manual(steamWants: Boolean?, automatic: Boolean, saved: Boolean): Boolean =
|
||||||
|
if (steamWants == null) saved else steamWants && !automatic
|
||||||
|
|
||||||
|
internal fun offline(manual: Boolean, online: Boolean, auto: Boolean = true): Boolean = manual || (auto && !online)
|
||||||
|
|
||||||
|
internal fun afterNetworkChange(manual: Boolean, online: Boolean): Boolean = manual && !online
|
||||||
|
|
||||||
|
fun auto(context: Context): Boolean = prefs(context).getBoolean(AUTO_KEY, true)
|
||||||
|
|
||||||
|
fun enabled(context: Context): Boolean = saved(context, LinuxRuntime.rootDir(context))
|
||||||
|
|
||||||
|
fun active(context: Context): Boolean =
|
||||||
|
offline(enabled(context), isOnline(context), auto(context))
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
fun setEnabled(context: Context, on: Boolean) {
|
fun setEnabled(context: Context, on: Boolean) {
|
||||||
prefs(context).edit().putBoolean(KEY, on).apply()
|
write(context, LinuxRuntime.rootDir(context), on)
|
||||||
apply(context, LinuxRuntime.rootDir(context))
|
SteamOfflineFollow.request()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun apply(context: Context, root: File) {
|
@Synchronized
|
||||||
applyTo(context, loginUsers(root))
|
fun setAuto(context: Context, on: Boolean) {
|
||||||
applyTo(context, x64LoginUsers(root))
|
val manual = if (on) false else steamWants(context, LinuxRuntime.rootDir(context)) ?: active(context)
|
||||||
|
prefs(context).edit().putBoolean(AUTO_KEY, on).commit()
|
||||||
|
setEnabled(context, manual)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun applyTo(context: Context, file: File) {
|
fun apply(context: Context, root: File): Boolean = write(context, root, saved(context, root))
|
||||||
|
|
||||||
|
fun sync(context: Context): Boolean? {
|
||||||
|
val root = LinuxRuntime.rootDir(context)
|
||||||
|
val offline = synchronized(this) { write(context, root, saved(context, root)) }
|
||||||
|
return switchLive(context, offline)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun follow(context: Context): Boolean? {
|
||||||
|
val root = LinuxRuntime.rootDir(context)
|
||||||
|
val (byNetwork, offline) = synchronized(this) {
|
||||||
|
if (!auto(context)) return false
|
||||||
|
prefs(context).getBoolean(NETWORK_KEY, false) to
|
||||||
|
write(context, root, afterNetworkChange(saved(context, root), isOnline(context)))
|
||||||
|
}
|
||||||
|
val result = switchLive(context, offline)
|
||||||
|
if (result == null && !offline && byNetwork) restoreNetworkOffline(context)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
internal fun restoreNetworkOffline(context: Context) {
|
||||||
|
val prefs = prefs(context)
|
||||||
|
if (!auto(context) || prefs.getBoolean(KEY, false) || prefs.getBoolean(NETWORK_KEY, false)) return
|
||||||
|
prefs.edit().putBoolean(NETWORK_KEY, true).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isOnline(context: Context) = com.droiddeck.launcher.frontend.AutoComponents.isOnline(context)
|
||||||
|
|
||||||
|
private fun saved(context: Context, root: File): Boolean {
|
||||||
|
val prefs = prefs(context)
|
||||||
|
return manual(steamWants(context, root), prefs.getBoolean(NETWORK_KEY, false), prefs.getBoolean(KEY, false))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun remember(context: Context, manual: Boolean): Boolean {
|
||||||
|
val online = isOnline(context)
|
||||||
|
val auto = auto(context)
|
||||||
|
val offline = offline(manual, online, auto)
|
||||||
|
prefs(context).edit().putBoolean(KEY, manual).putBoolean(NETWORK_KEY, offline && !manual).apply()
|
||||||
|
Log.i(TAG, "auto=$auto manual=$manual online=$online offline=$offline")
|
||||||
|
return offline
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun switchLive(context: Context, offline: Boolean): Boolean? {
|
||||||
|
val answer = try {
|
||||||
|
AgentGuest.steamEval(context, "$SWITCH($offline)", EVAL_TIMEOUT_MS)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "steam not reachable: ${e.javaClass.simpleName}: ${e.message}")
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val result = if (answer.optBoolean("ok")) answer.optString("value") else answer.optJSONObject("error")?.optString("message")
|
||||||
|
Log.i(TAG, "live offline=$offline: $result")
|
||||||
|
return when (result) {
|
||||||
|
"switched" -> true
|
||||||
|
"same" -> false
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun write(context: Context, root: File, manual: Boolean): Boolean {
|
||||||
|
val offline = remember(context, manual)
|
||||||
|
applyTo(loginUsers(root), offline)
|
||||||
|
applyTo(x64LoginUsers(root), offline)
|
||||||
|
return offline
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applyTo(file: File, offline: Boolean) {
|
||||||
if (!file.isFile) return
|
if (!file.isFile) return
|
||||||
val want = if (enabled(context)) "1" else "0"
|
val want = if (offline) "1" else "0"
|
||||||
try {
|
try {
|
||||||
val lines = file.readLines()
|
val lines = file.readLines()
|
||||||
val out = ArrayList<String>(lines.size + 4)
|
val out = ArrayList<String>(lines.size + 4)
|
||||||
@@ -94,4 +193,25 @@ object OfflineMode {
|
|||||||
Log.w(TAG, "could not write loginusers.vdf", e)
|
Log.w(TAG, "could not write loginusers.vdf", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val SWITCH = """(async want => {
|
||||||
|
const user = globalThis.SteamClient?.User;
|
||||||
|
if (typeof user?.GoOffline !== 'function' || typeof user?.GoOnline !== 'function') return "missing";
|
||||||
|
const seen = globalThis.__droiddeckSteamOffline ??= { value: null };
|
||||||
|
seen.want = want;
|
||||||
|
if (!seen.registered) {
|
||||||
|
seen.registered = true;
|
||||||
|
user.RegisterForCurrentUserChanges(u => { seen.value = !!u?.bIsOfflineMode; });
|
||||||
|
globalThis.SteamClient.GameSessions?.RegisterForAppLifetimeNotifications?.(n => {
|
||||||
|
if (n?.bRunning) return;
|
||||||
|
setTimeout(() => { if (seen.want === true && seen.value === false) user.GoOffline(); }, 2000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (let waited = 0; seen.value === null && waited < 4000; waited += 100) await new Promise(done => setTimeout(done, 100));
|
||||||
|
const current = seen.value;
|
||||||
|
if (current === null) return "unknown";
|
||||||
|
if (current === want) return "same";
|
||||||
|
if (want) user.GoOffline(); else user.GoOnline();
|
||||||
|
return "switched";
|
||||||
|
})"""
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||||
|
import com.droiddeck.launcher.runtime.RuntimeInstallService
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
|
||||||
|
/** What first run installs by itself, in the order it is needed, and how far each part has got. */
|
||||||
|
object Onboarding {
|
||||||
|
enum class Step { RUNTIME, PROTON, STEAM }
|
||||||
|
|
||||||
|
data class Progress(val label: String, val percent: Int)
|
||||||
|
|
||||||
|
data class Facts(val runtime: Boolean = true, val proton: Boolean = true, val steam: Boolean = true)
|
||||||
|
|
||||||
|
enum class State { DONE, ACTIVE, WAITING, FAILED }
|
||||||
|
|
||||||
|
data class Row(val step: Step, val state: State, val label: String?, val percent: Int)
|
||||||
|
|
||||||
|
val active = MutableStateFlow<Map<Step, Progress>>(emptyMap())
|
||||||
|
val failed = MutableStateFlow<Map<Step, String>>(emptyMap())
|
||||||
|
val facts = MutableStateFlow(Facts())
|
||||||
|
|
||||||
|
@Volatile private var appContext: Context? = null
|
||||||
|
private var hold: (() -> Unit)? = null
|
||||||
|
|
||||||
|
/** The setup screens belong to the first run; later runtime, Proton and Steam client updates keep the usual Play button. */
|
||||||
|
val firstRun = MutableStateFlow(true)
|
||||||
|
|
||||||
|
fun attach(context: Context) {
|
||||||
|
appContext = context.applicationContext
|
||||||
|
val prefs = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
|
var done = prefs.getBoolean(KEY_FIRST_RUN_DONE, false)
|
||||||
|
if (!done && runCatching { installedAndReady(context) }.getOrDefault(false)) {
|
||||||
|
done = true
|
||||||
|
prefs.edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
|
||||||
|
}
|
||||||
|
firstRun.value = !done
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Everything first run installs is in place, with the same Proton rule as [recheck]. */
|
||||||
|
private fun installedAndReady(context: Context): Boolean {
|
||||||
|
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||||
|
return LinuxRuntime.isInstalled(context) && !SteamClientPrefetch.pending(context) &&
|
||||||
|
(ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val PREFS = "onboarding"
|
||||||
|
private const val KEY_FIRST_RUN_DONE = "first_run_done"
|
||||||
|
|
||||||
|
private fun markFirstRunDone() {
|
||||||
|
val context = appContext ?: return
|
||||||
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
|
||||||
|
firstRun.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
|
||||||
|
@Synchronized private fun keepAlive() {
|
||||||
|
val context = appContext ?: return
|
||||||
|
val running = active.value
|
||||||
|
if (running.isNotEmpty() && !LinuxRuntimeInstaller.isBusy()) {
|
||||||
|
if (hold == null) hold = RuntimeInstallService.holdForPackage(context, context.getString(R.string.onboarding_title))
|
||||||
|
val rows = rows(running, failed.value, facts.value)
|
||||||
|
RuntimeInstallService.packageProgress(running.values.first().label, overall(rows))
|
||||||
|
} else {
|
||||||
|
hold?.invoke()
|
||||||
|
hold = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized fun recheck(context: Context) {
|
||||||
|
val runtime = LinuxRuntime.isInstalled(context)
|
||||||
|
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||||
|
facts.value = Facts(
|
||||||
|
runtime = runtime,
|
||||||
|
proton = ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty(),
|
||||||
|
steam = runtime && !SteamClientPrefetch.pending(context),
|
||||||
|
)
|
||||||
|
settle()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A new attempt starts from zero once everything is ready, whichever screen is showing. */
|
||||||
|
@Synchronized fun settle() {
|
||||||
|
if (!pending(rows(active.value, failed.value, facts.value))) {
|
||||||
|
resetProgress()
|
||||||
|
markFirstRunDone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun report(step: Step, label: String, percent: Int) {
|
||||||
|
failed.value = failed.value - step
|
||||||
|
active.value = active.value + (step to Progress(label, percent))
|
||||||
|
keepAlive()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun finish(step: Step) {
|
||||||
|
active.value = active.value - step
|
||||||
|
failed.value = failed.value - step
|
||||||
|
keepAlive()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fail(step: Step, message: String) {
|
||||||
|
active.value = active.value - step
|
||||||
|
failed.value = failed.value + (step to message)
|
||||||
|
keepAlive()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun rows(active: Map<Step, Progress>, failed: Map<Step, String>, facts: Facts): List<Row> = Step.entries.map { step ->
|
||||||
|
val ready = when (step) { Step.RUNTIME -> facts.runtime; Step.PROTON -> facts.proton; Step.STEAM -> facts.steam }
|
||||||
|
val progress = active[step]
|
||||||
|
when {
|
||||||
|
progress != null -> Row(step, State.ACTIVE, progress.label, progress.percent)
|
||||||
|
failed[step] != null -> Row(step, State.FAILED, failed[step], -1)
|
||||||
|
ready -> Row(step, State.DONE, null, 100)
|
||||||
|
else -> Row(step, State.WAITING, null, -1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE }
|
||||||
|
|
||||||
|
/** Whether first-run downloads are under way, as the home screen decides it. */
|
||||||
|
fun settling(): Boolean = firstRun.value && active.value.isNotEmpty() && pending(rows(active.value, failed.value, facts.value))
|
||||||
|
|
||||||
|
@Volatile private var highWater = 0
|
||||||
|
|
||||||
|
@Synchronized internal fun resetProgress() { highWater = 0 }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The aggregate fraction of the whole first-run work, weighting each step by what it downloads: about 290 MB, 630 MB and 1,050 MB.
|
||||||
|
* Steps download first and install later, restarting their own percent, so the figure only moves forward until everything is done.
|
||||||
|
*/
|
||||||
|
@Synchronized fun overall(rows: List<Row>): Int {
|
||||||
|
val measured = measure(rows)
|
||||||
|
if (!pending(rows)) {
|
||||||
|
highWater = 0
|
||||||
|
return measured
|
||||||
|
}
|
||||||
|
highWater = maxOf(highWater, measured)
|
||||||
|
return highWater
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun measure(rows: List<Row>): Int {
|
||||||
|
val weights = mapOf(Step.RUNTIME to 20, Step.PROTON to 30, Step.STEAM to 50)
|
||||||
|
val total = weights.values.sum()
|
||||||
|
val got = rows.sumOf { row ->
|
||||||
|
val w = weights.getValue(row.step)
|
||||||
|
when (row.state) {
|
||||||
|
State.DONE -> w
|
||||||
|
State.ACTIVE -> if (row.percent >= 0) w * row.percent / 100 else 0
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return got * 100 / total
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,8 @@ object ProtonDefault {
|
|||||||
|
|
||||||
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
|
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
|
||||||
data class Request(val seq: Long, val valve: Boolean, val dir: String)
|
data class Request(val seq: Long, val valve: Boolean, val dir: String)
|
||||||
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
|
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>,
|
||||||
|
val source: String? = null)
|
||||||
data class GameChoice(val valve: Boolean, val dir: String)
|
data class GameChoice(val valve: Boolean, val dir: String)
|
||||||
|
|
||||||
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
||||||
@@ -34,6 +35,7 @@ object ProtonDefault {
|
|||||||
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
|
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
|
||||||
}?.takeIf { it.name.isNotEmpty() }
|
}?.takeIf { it.name.isNotEmpty() }
|
||||||
},
|
},
|
||||||
|
source = o.optString("source").ifEmpty { null },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +101,13 @@ object ProtonDefault {
|
|||||||
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
|
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
|
||||||
val d = dir(context)
|
val d = dir(context)
|
||||||
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
|
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
|
||||||
val body = JSONObject().put("seq", seq).put("valve", proton.valve).put("dir", proton.dir.name).toString(1) + "\n"
|
writeRequest(d, Request(seq, proton.valve, proton.dir.name))
|
||||||
|
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
|
||||||
|
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun writeRequest(d: File, request: Request) {
|
||||||
|
val body = JSONObject().put("seq", request.seq).put("valve", request.valve).put("dir", request.dir).toString(1) + "\n"
|
||||||
val staged = File(d, "request.json.staged")
|
val staged = File(d, "request.json.staged")
|
||||||
try {
|
try {
|
||||||
d.mkdirs()
|
d.mkdirs()
|
||||||
@@ -110,8 +118,45 @@ object ProtonDefault {
|
|||||||
Log.w(TAG, "could not write the Proton request", e)
|
Log.w(TAG, "could not write the Proton request", e)
|
||||||
throw e
|
throw e
|
||||||
}
|
}
|
||||||
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
|
}
|
||||||
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
|
||||||
|
// The default that names a tool an update replaces moves to the new one, as the per-game picks do: otherwise the guest
|
||||||
|
// no longer finds it and falls back to DroidDeck-Proton.
|
||||||
|
internal fun movedDefault(state: State, request: Request?, from: Set<String>, to: String, now: Long): Request? {
|
||||||
|
val (valve, dir) = chosen(state, request) ?: return null
|
||||||
|
if (valve || dir !in from) return null
|
||||||
|
return Request(nextSeq(now, state, request), false, to)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun moveDefault(context: Context, from: Set<String>, to: String) {
|
||||||
|
val d = dir(context)
|
||||||
|
val moved = movedDefault(state(context), parseRequest(read(File(d, "request.json"))), from, to, System.currentTimeMillis()) ?: return
|
||||||
|
writeRequest(d, moved)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DroidDeck-Bionic keeps one build. A default naming another one moves to the installed build: an app from before
|
||||||
|
// updates carried the default over left it, or the guest fell back to its own tool when that build was gone (the
|
||||||
|
// request the app last wrote still names it).
|
||||||
|
internal fun bionicDefault(state: State, request: Request?, prefix: String, newest: String, now: Long): Request? {
|
||||||
|
val current = chosen(state, request)
|
||||||
|
val stale = when {
|
||||||
|
current != null && !current.first && current.second.startsWith(prefix) -> current.second
|
||||||
|
state.source == "fallback" && request != null && !request.valve && request.dir.startsWith(prefix) -> request.dir
|
||||||
|
else -> return null
|
||||||
|
}
|
||||||
|
return if (stale == newest) null else Request(nextSeq(now, state, request), false, newest)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The default and the per-game picks that name a DroidDeck-Bionic build other than [newest] move to it. */
|
||||||
|
@Synchronized
|
||||||
|
fun keepBionicCurrent(context: Context, prefix: String, newest: String) {
|
||||||
|
val d = dir(context)
|
||||||
|
bionicDefault(state(context), parseRequest(read(File(d, "request.json"))), prefix, newest, System.currentTimeMillis())
|
||||||
|
?.let { writeRequest(d, it) }
|
||||||
|
val games = parseGames(read(File(d, GAMES)))
|
||||||
|
val stale = games.values.filterNotNull().filter { !it.valve && it.dir.startsWith(prefix) && it.dir != newest }.map { it.dir }.toSet()
|
||||||
|
if (stale.isNotEmpty()) movedGames(games, stale, newest)?.let { writeGames(d, it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
|
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ 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.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.runtime.NativeGuest
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
@@ -23,24 +24,36 @@ object ProtonExtras {
|
|||||||
const val CHECK_EVERY_MS = 60L * 60 * 1000
|
const val CHECK_EVERY_MS = 60L * 60 * 1000
|
||||||
@Volatile
|
@Volatile
|
||||||
var installInProgress = false
|
var installInProgress = false
|
||||||
|
@Volatile var prefetching = false
|
||||||
private set
|
private set
|
||||||
|
@Volatile private var checkedArchive: Triple<String, Long, Long>? = null
|
||||||
|
@Volatile private var checkedDigest: String? = null
|
||||||
|
|
||||||
|
private fun fingerprint(archive: File) = Triple(archive.path, archive.length(), archive.lastModified())
|
||||||
@Volatile
|
@Volatile
|
||||||
private var replacing = false
|
private var replacing = false
|
||||||
|
|
||||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex,
|
||||||
|
val prereleases: Boolean = false)
|
||||||
|
|
||||||
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
||||||
val sha256: String? = null, val releaseName: String = tag)
|
val sha256: String? = null, val releaseName: String = tag)
|
||||||
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
|
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
|
||||||
|
|
||||||
const val OWN = "droiddeck"
|
const val OWN = "droiddeck"
|
||||||
|
const val BIONIC = "bionic"
|
||||||
|
|
||||||
val tools = listOf(
|
val tools = listOf(
|
||||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||||
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
||||||
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")),
|
||||||
|
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only.
|
||||||
|
Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** The sources offered on this device: DroidDeck-Bionic only with Run without proot on. */
|
||||||
|
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) }
|
||||||
|
|
||||||
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||||
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
|
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
|
||||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||||
@@ -115,10 +128,11 @@ object ProtonExtras {
|
|||||||
private var lastAttempt = 0L
|
private var lastAttempt = 0L
|
||||||
|
|
||||||
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
||||||
|
keepBionicCurrent(context)
|
||||||
synchronized(checkLock) {
|
synchronized(checkLock) {
|
||||||
val file = latestFile(context)
|
val file = latestFile(context)
|
||||||
val cache = readJson(file)
|
val cache = readJson(file)
|
||||||
val due = tools.filter { tool ->
|
val due = offered(context).filter { tool ->
|
||||||
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
|
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
|
||||||
force || (now - at) !in 0 until CHECK_EVERY_MS
|
force || (now - at) !in 0 until CHECK_EVERY_MS
|
||||||
}
|
}
|
||||||
@@ -168,15 +182,32 @@ object ProtonExtras {
|
|||||||
|
|
||||||
fun remove(context: Context, tool: Tool, dir: String? = null) {
|
fun remove(context: Context, tool: Tool, dir: String? = null) {
|
||||||
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
|
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
|
||||||
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name)
|
if (deleteTool(context, name)) ComponentsManager.forgetProton(context, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A tool folder can hold links that point out of it (a prefix template's dosdevices/z: -> /), and
|
||||||
|
// File.deleteRecursively() follows links into directories: remove each link itself, never what it points to.
|
||||||
|
private fun deleteTool(context: Context, name: String): Boolean {
|
||||||
|
val dir = File(toolsDir(context), name)
|
||||||
|
FileUtils.delete(dir)
|
||||||
|
return !dir.exists() && !java.nio.file.Files.isSymbolicLink(dir.toPath())
|
||||||
}
|
}
|
||||||
|
|
||||||
fun removeOlder(context: Context, tool: Tool) {
|
fun removeOlder(context: Context, tool: Tool) {
|
||||||
installedAll(context, tool).dropLast(1).forEach {
|
installedAll(context, tool).dropLast(1).forEach {
|
||||||
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
|
if (deleteTool(context, it)) ComponentsManager.forgetProton(context, it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DroidDeck-Bionic: the default and the game picks name the installed build, also when they were left on one an
|
||||||
|
// older app deleted without moving them.
|
||||||
|
private fun keepBionicCurrent(context: Context) {
|
||||||
|
if (SessionState.running) return
|
||||||
|
val tool = tools.firstOrNull { it.id == BIONIC } ?: return
|
||||||
|
val newest = installedAll(context, tool).lastOrNull() ?: return
|
||||||
|
runCatching { ProtonDefault.keepBionicCurrent(context, tool.prefix, newest) }.onFailure { Log.w(TAG, "bionic default and picks", it) }
|
||||||
|
}
|
||||||
|
|
||||||
private fun replaceOlder(context: Context, tool: Tool) {
|
private fun replaceOlder(context: Context, tool: Tool) {
|
||||||
val all = installedAll(context, tool)
|
val all = installedAll(context, tool)
|
||||||
val newest = all.lastOrNull() ?: return
|
val newest = all.lastOrNull() ?: return
|
||||||
@@ -189,7 +220,9 @@ object ProtonExtras {
|
|||||||
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
|
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
|
||||||
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
|
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
|
||||||
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
|
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
|
||||||
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
|
// DroidDeck-Bionic only: the guest finds no default for a deleted Bionic build and falls back to DroidDeck-Proton
|
||||||
|
if (tool.id == BIONIC && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue
|
||||||
|
if (deleteTool(context, old)) ComponentsManager.forgetProton(context, old)
|
||||||
else Log.w(TAG, "could not remove $old")
|
else Log.w(TAG, "could not remove $old")
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@@ -216,13 +249,59 @@ object ProtonExtras {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
fun install(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier? = null,
|
||||||
if (installInProgress) return context.getString(R.string.pextra_busy)
|
onProgress: (String, Int) -> Unit): String? {
|
||||||
|
if (installInProgress || prefetching) 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, cancelled, onProgress) } finally { installInProgress = false }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit,
|
||||||
|
cancelled: java.util.function.BooleanSupplier? = null): String? {
|
||||||
|
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
||||||
|
onProgress(downloading, 0)
|
||||||
|
var downloaded = false
|
||||||
|
for (attempt in 0 until 5) {
|
||||||
|
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256, cancelled) { fraction ->
|
||||||
|
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
||||||
|
}
|
||||||
|
if (downloaded) break
|
||||||
|
if (cancelled?.asBoolean == true) return context.getString(R.string.pextra_interrupted)
|
||||||
|
if (attempt < 4) {
|
||||||
|
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1)
|
||||||
|
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
return context.getString(R.string.pextra_interrupted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!downloaded) return context.getString(R.string.pextra_download_failed)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Downloads the newest build of [tool] ahead of the runtime it installs into; [install] verifies and unpacks it later. */
|
||||||
|
@Synchronized
|
||||||
|
fun prefetch(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||||
|
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||||
|
prefetching = true
|
||||||
|
try { return prefetchNow(context, tool, onProgress) } finally { prefetching = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||||
|
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||||
|
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||||
|
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||||
|
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||||
|
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||||
|
if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name)
|
||||||
|
val problem = fetchArchive(context, tool, asset, archive, onProgress)
|
||||||
|
checkedArchive = if (problem == null && asset.sha256 != null && asset.size > 0 && archive.length() == asset.size) fingerprint(archive) else null
|
||||||
|
checkedDigest = if (checkedArchive != null) asset.sha256 else null
|
||||||
|
return problem
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun installNow(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier?,
|
||||||
|
onProgress: (String, Int) -> Unit): String? {
|
||||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||||
|
|
||||||
@@ -235,23 +314,9 @@ object ProtonExtras {
|
|||||||
return context.getString(R.string.pextra_no_space, tool.name)
|
return context.getString(R.string.pextra_no_space, tool.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) &&
|
||||||
onProgress(downloading, 0)
|
checkedDigest.equals(asset.sha256, ignoreCase = true)
|
||||||
var downloaded = false
|
if (!checked) fetchArchive(context, tool, asset, archive, onProgress, cancelled)?.let { return it }
|
||||||
for (attempt in 0 until 5) {
|
|
||||||
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256) { fraction ->
|
|
||||||
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
|
||||||
}
|
|
||||||
if (downloaded) break
|
|
||||||
if (attempt < 4) {
|
|
||||||
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1)
|
|
||||||
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
|
||||||
Thread.currentThread().interrupt()
|
|
||||||
return context.getString(R.string.pextra_interrupted)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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()
|
||||||
@@ -262,6 +327,7 @@ object ProtonExtras {
|
|||||||
|
|
||||||
onProgress(context.getString(R.string.pextra_verifying), -1)
|
onProgress(context.getString(R.string.pextra_verifying), -1)
|
||||||
val verified = when {
|
val verified = when {
|
||||||
|
checked -> true
|
||||||
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.downloadDirect(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
|
val expected = Downloader.downloadDirect(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
|
||||||
@@ -308,7 +374,7 @@ object ProtonExtras {
|
|||||||
archive.delete()
|
archive.delete()
|
||||||
unqueue(context, tool)
|
unqueue(context, tool)
|
||||||
record(context, tool, placed, asset.tag)
|
record(context, tool, placed, asset.tag)
|
||||||
if (tool.id == OWN) replaceOlder(context, tool)
|
if (tool.id == OWN || tool.id == BIONIC) replaceOlder(context, tool)
|
||||||
if (EsyncPacks.enabled(context)) {
|
if (EsyncPacks.enabled(context)) {
|
||||||
onProgress(context.getString(R.string.esync_fetching), -1)
|
onProgress(context.getString(R.string.esync_fetching), -1)
|
||||||
try {
|
try {
|
||||||
@@ -393,7 +459,7 @@ object ProtonExtras {
|
|||||||
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
||||||
val candidates = (0 until array.length()).asSequence()
|
val candidates = (0 until array.length()).asSequence()
|
||||||
.mapNotNull { array.optJSONObject(it) }
|
.mapNotNull { array.optJSONObject(it) }
|
||||||
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
|
.filter { !it.optBoolean("draft", false) && (tool.prereleases || !it.optBoolean("prerelease", false)) }
|
||||||
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
|
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
/** A launch the user asked for that waits for something else to finish first, and is forgotten if it waits too long. */
|
||||||
|
class QueuedLaunch<T : Any>(private val lifetimeMs: Long = 15 * 60_000L) {
|
||||||
|
var launch: T? = null
|
||||||
|
private set
|
||||||
|
var queuedAt: Long = 0L
|
||||||
|
private set
|
||||||
|
|
||||||
|
fun queue(launch: T, now: Long) {
|
||||||
|
this.launch = launch
|
||||||
|
queuedAt = now
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Takes back a saved launch with the time it was first queued; one without a valid time or past its lifetime is dropped. */
|
||||||
|
fun restore(launch: T?, queuedAt: Long, now: Long) {
|
||||||
|
if (launch != null && fresh(queuedAt, now)) {
|
||||||
|
this.launch = launch
|
||||||
|
this.queuedAt = queuedAt
|
||||||
|
} else {
|
||||||
|
clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The launch if it is still wanted; an expired one is cleared. */
|
||||||
|
fun current(now: Long): T? {
|
||||||
|
val queued = launch ?: return null
|
||||||
|
if (fresh(queuedAt, now)) return queued
|
||||||
|
clear()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
launch = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fresh(queuedAt: Long, now: Long) = now - queuedAt in 0..lifetimeMs
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts a queued launch once nothing stands in its way and retries until it can or it expires. One runner belongs to one
|
||||||
|
* activity: destroying it clears its queue and cancels its retry, so a restored activity is the only one that starts the launch.
|
||||||
|
*/
|
||||||
|
class QueuedLaunchRunner<T : Any>(
|
||||||
|
private val queue: QueuedLaunch<T>,
|
||||||
|
private val now: () -> Long,
|
||||||
|
private val blocked: () -> Boolean,
|
||||||
|
private val busy: () -> Boolean,
|
||||||
|
private val schedule: (delayMs: Long, task: Runnable) -> Unit,
|
||||||
|
private val unschedule: (Runnable) -> Unit,
|
||||||
|
private val start: (T) -> Unit,
|
||||||
|
private val retryMs: Long = 2_000L,
|
||||||
|
) {
|
||||||
|
private var posted = false
|
||||||
|
private var retry: Runnable? = null
|
||||||
|
private var destroyed = false
|
||||||
|
|
||||||
|
/** Call whenever the blocking setting may have changed. */
|
||||||
|
fun poke() {
|
||||||
|
if (destroyed || posted) return
|
||||||
|
val launch = queue.current(now()) ?: return
|
||||||
|
if (blocked()) return
|
||||||
|
posted = true
|
||||||
|
schedule(0L, Runnable {
|
||||||
|
posted = false
|
||||||
|
attempt(launch)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun attempt(launch: T) {
|
||||||
|
if (destroyed || queue.current(now()) !== launch) return
|
||||||
|
if (busy()) {
|
||||||
|
val again = Runnable { if (!destroyed && queue.launch === launch) poke() }
|
||||||
|
retry = again
|
||||||
|
schedule(retryMs, again)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
queue.clear()
|
||||||
|
start(launch)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun destroy() {
|
||||||
|
destroyed = true
|
||||||
|
queue.clear()
|
||||||
|
retry?.let(unschedule)
|
||||||
|
retry = null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -75,6 +75,7 @@ object SessionArtifacts {
|
|||||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||||
val record = Record(dir)
|
val record = Record(dir)
|
||||||
copySteamLogs(context, dir, record, steamArch)
|
copySteamLogs(context, dir, record, steamArch)
|
||||||
|
copyRpcs3Log(context, dir, record)
|
||||||
VacDiagnostics.collect(context, dir)
|
VacDiagnostics.collect(context, dir)
|
||||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||||
SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log"))
|
SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log"))
|
||||||
@@ -321,6 +322,9 @@ object SessionArtifacts {
|
|||||||
runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" }
|
runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" }
|
||||||
|
|
||||||
private const val LOG_MARKS = "steam-log-marks.txt"
|
private const val LOG_MARKS = "steam-log-marks.txt"
|
||||||
|
private const val RPCS3_LOG_MARKS = "rpcs3-log-marks.txt"
|
||||||
|
private const val RPCS3_LOGS = "root/.cache/rpcs3"
|
||||||
|
private const val RPCS3_LOG = "RPCS3.log"
|
||||||
private const val MAX_STEAM_LOG = 8L * 1024 * 1024
|
private const val MAX_STEAM_LOG = 8L * 1024 * 1024
|
||||||
private const val HEAD = 4096L
|
private const val HEAD = 4096L
|
||||||
|
|
||||||
@@ -328,11 +332,19 @@ object SessionArtifacts {
|
|||||||
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
|
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
|
||||||
|
|
||||||
fun markSteamLogs(dir: File, logs: File) {
|
fun markSteamLogs(dir: File, logs: File) {
|
||||||
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
|
logs.listFiles { f -> f.isFile }?.let { markLogs(dir, LOG_MARKS, it.toList()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun markRpcs3Log(dir: File, root: File) {
|
||||||
|
markLogs(dir, RPCS3_LOG_MARKS, listOf(File(root, "$RPCS3_LOGS/$RPCS3_LOG")).filter { it.isFile })
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun markLogs(dir: File, marks: String, files: List<File>) {
|
||||||
|
val lines = files.mapNotNull { f ->
|
||||||
val size = f.length()
|
val size = f.length()
|
||||||
head(f, size)?.let { "$size\t$it\t${f.name}" }
|
head(f, size)?.let { "$size\t$it\t${f.name}" }
|
||||||
} ?: return
|
}
|
||||||
runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) }
|
runCatching { File(dir, marks).writeText(lines.joinToString("") { "$it\n" }) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun head(f: File, length: Long): String? = runCatching {
|
private fun head(f: File, length: Long): String? = runCatching {
|
||||||
@@ -348,8 +360,8 @@ object SessionArtifacts {
|
|||||||
java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) }
|
java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) }
|
||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
|
|
||||||
private fun steamLogMarks(dir: File): List<Mark>? = runCatching {
|
private fun logMarks(dir: File, marks: String): List<Mark>? = runCatching {
|
||||||
File(dir, LOG_MARKS).readLines().mapNotNull { line ->
|
File(dir, marks).readLines().mapNotNull { line ->
|
||||||
val parts = line.split('\t', limit = 3)
|
val parts = line.split('\t', limit = 3)
|
||||||
parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } }
|
parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } }
|
||||||
}
|
}
|
||||||
@@ -371,11 +383,32 @@ object SessionArtifacts {
|
|||||||
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
|
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
|
||||||
if (!logs.isDirectory) return
|
if (!logs.isDirectory) return
|
||||||
val out = File(dir, "steam").apply { mkdirs() }
|
val out = File(dir, "steam").apply { mkdirs() }
|
||||||
val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }
|
addCopied(record, copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running })
|
||||||
|
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun copyRpcs3Log(context: Context, dir: File, record: Record, stopWhenSessionStarts: Boolean = false) {
|
||||||
|
val out = File(dir, "rpcs3")
|
||||||
|
val logs = File(LinuxRuntime.rootDir(context), RPCS3_LOGS)
|
||||||
|
val copied = copyRpcs3LogResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } ?: return
|
||||||
|
addCopied(record, copied)
|
||||||
|
if (copied.files.isNotEmpty()) Log.i(TAG, "collected RPCS3's log, scrubbed, into $out")
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun copyRpcs3Log(logs: File, dir: File, out: File): List<File> = copyRpcs3LogResult(logs, dir, out) { false }?.files.orEmpty()
|
||||||
|
|
||||||
|
private fun copyRpcs3LogResult(logs: File, dir: File, out: File, shouldStop: () -> Boolean): CopyResult? {
|
||||||
|
if (!File(dir, RPCS3_LOG_MARKS).isFile || !File(logs, RPCS3_LOG).isFile) return null
|
||||||
|
out.mkdirs()
|
||||||
|
val result = copySessionLogsResult(logs, dir, out, marksName = RPCS3_LOG_MARKS, accept = { it.name == RPCS3_LOG }, shouldStop = shouldStop)
|
||||||
|
if (result.files.isEmpty()) out.delete()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun addCopied(record: Record, result: CopyResult) {
|
||||||
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
|
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
|
||||||
record.failed = record.failed || result.failed
|
record.failed = record.failed || result.failed
|
||||||
record.deferred = record.deferred || result.deferred
|
record.deferred = record.deferred || result.deferred
|
||||||
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun copySessionLogs(
|
internal fun copySessionLogs(
|
||||||
@@ -383,20 +416,22 @@ object SessionArtifacts {
|
|||||||
dir: File,
|
dir: File,
|
||||||
out: File,
|
out: File,
|
||||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||||
): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files
|
): List<File> = copySessionLogsResult(logs, dir, out, openWriter = openWriter) { false }.files
|
||||||
|
|
||||||
private fun copySessionLogsResult(
|
private fun copySessionLogsResult(
|
||||||
logs: File,
|
logs: File,
|
||||||
dir: File,
|
dir: File,
|
||||||
out: File,
|
out: File,
|
||||||
|
marksName: String = LOG_MARKS,
|
||||||
|
accept: (File) -> Boolean = { true },
|
||||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||||
shouldStop: () -> Boolean,
|
shouldStop: () -> Boolean,
|
||||||
): CopyResult {
|
): CopyResult {
|
||||||
val marks = steamLogMarks(dir)
|
val marks = logMarks(dir, marksName)
|
||||||
val copied = ArrayList<File>()
|
val copied = ArrayList<File>()
|
||||||
var failed = false
|
var failed = false
|
||||||
var deferred = false
|
var deferred = false
|
||||||
val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false)
|
val sources = logs.listFiles { f -> f.isFile && accept(f) } ?: return CopyResult(copied, true, false)
|
||||||
for (src in sources) {
|
for (src in sources) {
|
||||||
if (shouldStop()) {
|
if (shouldStop()) {
|
||||||
failed = true
|
failed = true
|
||||||
@@ -567,6 +602,7 @@ object SessionArtifacts {
|
|||||||
steamArch = recordedClient(dir),
|
steamArch = recordedClient(dir),
|
||||||
stopWhenSessionStarts = stopWhenSessionStarts,
|
stopWhenSessionStarts = stopWhenSessionStarts,
|
||||||
)
|
)
|
||||||
|
copyRpcs3Log(context, dir, record, stopWhenSessionStarts)
|
||||||
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
|
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
|
||||||
if (!record.failed && VacDiagnostics.collect(context, dir)) {
|
if (!record.failed && VacDiagnostics.collect(context, dir)) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ object SessionDisplay {
|
|||||||
const val FOLLOW_SCALE_MAX = 8f
|
const val FOLLOW_SCALE_MAX = 8f
|
||||||
private const val FOLLOW_SCALED_PREFIX = "follow/"
|
private const val FOLLOW_SCALED_PREFIX = "follow/"
|
||||||
|
|
||||||
|
const val LINK_LANDSCAPE = "link/landscape"
|
||||||
|
const val LINK_PORTRAIT = "link/portrait"
|
||||||
|
|
||||||
const val DEFAULT_RESOLUTION = "720p"
|
const val DEFAULT_RESOLUTION = "720p"
|
||||||
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
|
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
|
||||||
|
|
||||||
@@ -35,6 +38,23 @@ object SessionDisplay {
|
|||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun isLink(choice: String): Boolean = choice == LINK_LANDSCAPE || choice == LINK_PORTRAIT
|
||||||
|
|
||||||
|
fun orientCustom(choice: String, portrait: Boolean): String {
|
||||||
|
val parts = choice.split('x').map { it.toIntOrNull() }
|
||||||
|
if (parts.size != 2 || parts.any { it == null || it <= 0 }) return choice
|
||||||
|
val width = parts[0]!!
|
||||||
|
val height = parts[1]!!
|
||||||
|
return if ((portrait && width > height) || (!portrait && height > width)) "${height}x$width" else choice
|
||||||
|
}
|
||||||
|
|
||||||
|
fun effectiveChoice(landscape: String, portrait: String, forPortrait: Boolean): String {
|
||||||
|
val own = if (forPortrait) portrait else landscape
|
||||||
|
if (!isLink(own)) return own
|
||||||
|
val other = if (forPortrait) landscape else portrait
|
||||||
|
return if (isLink(other)) DEFAULT_RESOLUTION else orientCustom(other, forPortrait)
|
||||||
|
}
|
||||||
|
|
||||||
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
|
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
|
||||||
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
|
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
|
||||||
|
|
||||||
@@ -69,8 +89,12 @@ object SessionDisplay {
|
|||||||
|
|
||||||
const val UNFOLDED_MIN_DP = 600
|
const val UNFOLDED_MIN_DP = 600
|
||||||
|
|
||||||
fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0): Int =
|
fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0, aspect: Float = 0f): Int {
|
||||||
(minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) - tabRow.coerceAtLeast(0)).coerceAtLeast(0) and 1.inv()
|
val row = tabRow.coerceAtLeast(0)
|
||||||
|
val cap = (height * UNFOLDED_MAX_GAME_SHARE).toInt()
|
||||||
|
if (aspect > 0f && aspect < 16f / 9f) return minOf((width / aspect).toInt(), cap - row).coerceAtLeast(0) and 1.inv()
|
||||||
|
return (minOf(width * 9 / 16, cap) - row).coerceAtLeast(0) and 1.inv()
|
||||||
|
}
|
||||||
|
|
||||||
fun unfoldedControlsWanted(
|
fun unfoldedControlsWanted(
|
||||||
enabled: Boolean,
|
enabled: Boolean,
|
||||||
|
|||||||
Loaded 100 of 644 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user