Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae570cd5b7 | ||
|
|
0fd1dc4fce | ||
|
|
f0854e8518 | ||
|
|
ceffd3f759 | ||
|
|
dc1816612c | ||
|
|
1d04a7e0e3 | ||
|
|
1e523c4e93 | ||
|
|
d83f766cf3 | ||
|
|
bb5e1ae63d | ||
|
|
f27a4f6c95 | ||
|
|
d7ff92106a | ||
|
|
34a17acaba | ||
|
|
110aec0b6f | ||
|
|
06502bb49b | ||
|
|
c20a166134 | ||
|
|
162fa8e2de | ||
|
|
ae5614d212 | ||
|
|
b72d8a8bab | ||
|
|
d4cf890d8a | ||
|
|
82e494269d | ||
|
|
c982d65675 | ||
|
|
f4e606fb15 | ||
|
|
9dbdb5e771 | ||
|
|
fa12478fdd | ||
|
|
c3b0d8ef03 | ||
|
|
cbb9a168e6 | ||
|
|
73e2fc58a0 | ||
|
|
500f4c69eb | ||
|
|
911ad29004 | ||
|
|
aa843b5a31 | ||
|
|
f249acc50f | ||
|
|
8cdedbe18a | ||
|
|
0f39d71f95 | ||
|
|
1dc49b527b | ||
|
|
9422608960 | ||
|
|
cc3fec0768 | ||
|
|
de37ddcfb5 | ||
|
|
4c90196890 | ||
|
|
5270574e5a | ||
|
|
30f6ca6ffc | ||
|
|
a8af973726 | ||
|
|
ed1f8dd2b6 | ||
|
|
e8aaae1343 | ||
|
|
ecff3240a6 | ||
|
|
ddd4a0c24d | ||
|
|
019949847a | ||
|
|
4dcbf269d2 | ||
|
|
036317f371 | ||
|
|
ce0da01163 | ||
|
|
75ae619e21 | ||
|
|
3efa5acfa6 | ||
|
|
9369dc3031 | ||
|
|
5d84d3fef7 | ||
|
|
51baf75af1 | ||
|
|
20f2c98d18 | ||
|
|
e3ceae412b | ||
|
|
7e6affed12 | ||
|
|
40fc5463f3 | ||
|
|
039948f4d2 | ||
|
|
bbb95e8a60 | ||
|
|
7763d00b78 | ||
|
|
3452730725 | ||
|
|
e50f61f5d9 | ||
|
|
a7a4308e3c | ||
|
|
e811576e79 | ||
|
|
960abec0ed | ||
|
|
855ab88d6c | ||
|
|
f7ee6e78f0 | ||
|
|
293c58aeba | ||
|
|
95b8a4c3c4 | ||
|
|
b7fd52de79 | ||
|
|
53ce764548 | ||
|
|
157e74907a | ||
|
|
015ac26e07 | ||
|
|
1fe7faaa8d | ||
|
|
2e7f99897d | ||
|
|
d7fa65ad20 | ||
|
|
ae614ce476 | ||
|
|
7d6e1cce2f | ||
|
|
bbf46cad9d | ||
|
|
68c7b4b3c8 | ||
|
|
5d38a6c8c5 | ||
|
|
99a0c44f98 | ||
|
|
1812ba20e2 | ||
|
|
771d3c399c | ||
|
|
af74a4449e | ||
|
|
8c171dd2c7 | ||
|
|
3292ed6f1a | ||
|
|
96bbe0c4cc | ||
|
|
039e14de5a | ||
|
|
a419c8097f | ||
|
|
3fac2e8945 | ||
|
|
c2d6d272a3 | ||
|
|
846630e300 | ||
|
|
cc1f3d256b | ||
|
|
243a760a12 | ||
|
|
4f744fc8fe | ||
|
|
54adf9ad68 | ||
|
|
8b66adb8a5 | ||
|
|
9f0c1fc797 | ||
|
|
4a46e16702 | ||
|
|
608d011b44 | ||
|
|
0d52ba66cd | ||
|
|
431fac1fca | ||
|
|
35006d6031 | ||
|
|
7ae66337ef | ||
|
|
b75e0f9800 | ||
|
|
ee3fd4d6b8 | ||
|
|
0352f4b832 | ||
|
|
7fbfeb2edd | ||
|
|
8db69f073b | ||
|
|
226fa1c1ea | ||
|
|
6f41ae58db | ||
|
|
ae9186392f | ||
|
|
4279ffd887 | ||
|
|
ac058ea112 | ||
|
|
5d42e5e87a | ||
|
|
96ac6967e6 | ||
|
|
0c301f3cec | ||
|
|
d7cadd05d6 | ||
|
|
2f8464b7f5 | ||
|
|
96314749da | ||
|
|
33f06d744f | ||
|
|
d6ca48d80a | ||
|
|
c8b628393b | ||
|
|
e9d4eb1e1b | ||
|
|
89f78a9969 | ||
|
|
94f9935ad4 | ||
|
|
66c7db5a47 | ||
|
|
b959de3d26 | ||
|
|
b802485e31 | ||
|
|
ee20fd60c4 | ||
|
|
52174e2ab0 | ||
|
|
216f3c1d62 | ||
|
|
7e6954304a | ||
|
|
8718ae0aa8 | ||
|
|
615311ecd6 | ||
|
|
3a4ef4f6d6 | ||
|
|
403cfa77ae | ||
|
|
c7998a82d5 | ||
|
|
86bc9f4a64 | ||
|
|
2f4c4624ae | ||
|
|
b83e5f87cf | ||
|
|
b49e2753df | ||
|
|
3c09e1d736 | ||
|
|
0f07dafb36 | ||
|
|
38fdca0b97 | ||
|
|
e8efe2d290 | ||
|
|
a1ae55125a | ||
|
|
706692c1fe | ||
|
|
582f031243 | ||
|
|
9c78373c73 | ||
|
|
e9f3416438 | ||
|
|
ea44a77f8a | ||
|
|
63d7051c4b | ||
|
|
4803c9d221 | ||
|
|
6388edb706 | ||
|
|
0774ade030 | ||
|
|
e5ee766961 | ||
|
|
274f3d0c7a | ||
|
|
21be683768 | ||
|
|
695923aed7 | ||
|
|
649153257d | ||
|
|
cbcd3f8023 | ||
|
|
41c5ce8d4e | ||
|
|
78ce23258b | ||
|
|
3e864fda17 | ||
|
|
0cdb945d9c | ||
|
|
15a113f783 | ||
|
|
67f00d2123 | ||
|
|
d68dcd14e1 | ||
|
|
32994210ab | ||
|
|
cfec8ab88a | ||
|
|
87c44c3218 | ||
|
|
35446df6d5 | ||
|
|
921b38bfb4 | ||
|
|
82bb924d0b | ||
|
|
08a6769bc0 | ||
|
|
dce87061d1 | ||
|
|
f4302e4fa9 | ||
|
|
0436953451 | ||
|
|
7165907ba9 | ||
|
|
e938127c7a | ||
|
|
b5c9d6bc50 | ||
|
|
f7af5091cf | ||
|
|
7ac1786a2e | ||
|
|
19a919e096 | ||
|
|
10f5506829 | ||
|
|
d3c6d54a58 | ||
|
|
6980428f82 | ||
|
|
1a3b16f614 | ||
|
|
e0b9f462ce | ||
|
|
f6f7470385 | ||
|
|
214c708b49 | ||
|
|
d567185fc0 | ||
|
|
24188bda10 | ||
|
|
1a870c5c07 | ||
|
|
fa964802d9 | ||
|
|
793180ce12 | ||
|
|
79e7be470c | ||
|
|
921f156128 | ||
|
|
c771fc67ac | ||
|
|
7f2d2ffa4a | ||
|
|
2d9e1c6d95 | ||
|
|
66dafa6021 | ||
|
|
2df3d054e8 | ||
|
|
c9cfa2126e | ||
|
|
2220578cd1 | ||
|
|
5b18807f0e | ||
|
|
d984a4ba31 | ||
|
|
7dc00d9b23 | ||
|
|
c013252a59 | ||
|
|
7fa71dc5c5 |
No files matched your search
@@ -0,0 +1,46 @@
|
||||
name: Build wlroots (patched)
|
||||
|
||||
# The desktop's wlroots (Arch Linux ARM's wlroots0.20, what the desktop package's labwc links)
|
||||
# rebuilt with tools/wlroots/patches: a Vulkan DMA-BUF allocator for the Adreno node, which is not
|
||||
# a DRM device, so labwc's vulkan and gles2 renderers can start. Built in an Arch Linux ARM
|
||||
# container on an arm64 runner and published as a release asset the apk build fetches
|
||||
# (tools/wlroots/release.env names the tag and sha). The hosted desktop package is never changed.
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'tools/wlroots/**'
|
||||
- '.github/workflows/build-wlroots.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to publish as (e.g. wlroots-0.20.2-p1); empty = artifact only'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build in Arch Linux ARM
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker run --rm -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/wlroots/build-in-arch.sh
|
||||
sudo chown -R "$(id -u):$(id -g)" .
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wlroots-patched
|
||||
path: |
|
||||
wlroots.tzst
|
||||
wlroots.tzst.sha256
|
||||
- name: Publish
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh release create "${{ inputs.tag }}" --title "${{ inputs.tag }}" --notes "wlroots 0.20.2 with tools/wlroots/patches (Vulkan DMA-BUF allocator for non-DRM GPU nodes); staged by the apk at /usr/local/lib/droiddeck-wlroots for the desktop's GPU renderers. sha256 $(cut -d' ' -f1 wlroots.tzst.sha256)" wlroots.tzst wlroots.tzst.sha256 || gh release upload "${{ inputs.tag }}" wlroots.tzst wlroots.tzst.sha256 --clobber
|
||||
@@ -1,30 +1,14 @@
|
||||
name: Build APK
|
||||
|
||||
# One job: the two glibc preload libraries the session needs, then the app around them.
|
||||
# Nothing is built on a developer machine - this workflow is the only thing that produces an apk.
|
||||
#
|
||||
# This repo is private, so every minute here is billed. Three caches carry the cost of a rebuild
|
||||
# down to what actually changed:
|
||||
# • Gradle's own (dependencies, wrapper, build cache, configuration cache) via setup-gradle
|
||||
# • the CMake/ninja tree, so a Kotlin-only change does not recompile the compositor
|
||||
# • the two cross-compiled preloads, which also skips installing the cross toolchain
|
||||
# A run that changes only Kotlin should not touch the C compiler at all.
|
||||
run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1}', github.event.pull_request.number, github.event.pull_request.head.sha) || format('building {0} on {1}', github.ref_name, github.sha) }}
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
# Documentation changes cannot alter the apk, so they do not buy a build.
|
||||
paths-ignore:
|
||||
- '**/*.md'
|
||||
- 'LICENSE'
|
||||
- '.gitignore'
|
||||
# A pull request against main builds by itself: the contributor's branch, as it would be once
|
||||
# merged onto main, comes back as an apk on the run without anyone here pressing a button.
|
||||
# Every push to the pull request rebuilds it and cancels the build it replaces; a draft waits
|
||||
# until it is marked ready. pull_request_target rather than pull_request: GitHub does not run
|
||||
# the latter at all while a pull request conflicts with main, and saying what conflicts is the
|
||||
# point. The workflow file is always main's; the pull request's own code is checked out below.
|
||||
pull_request_target:
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
types: [ opened, synchronize, reopened, ready_for_review ]
|
||||
paths-ignore:
|
||||
@@ -35,38 +19,38 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
# The pull-request report below is one comment on the pull request, kept up to date.
|
||||
pull-requests: write
|
||||
|
||||
# A newer push makes the running build pointless; stop paying for it.
|
||||
concurrency:
|
||||
group: build-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
# Bump to force the preload cache to miss (e.g. after changing a compiler flag below).
|
||||
PRELOAD_CACHE_VERSION: v1
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.event_name != 'pull_request_target' || !github.event.pull_request.draft }}
|
||||
name: Build APK
|
||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
# A pull request is checked out at its own head with full history, not at GitHub's merge
|
||||
# ref: that ref does not exist while the pull request conflicts with main, and the point of
|
||||
# the next step is to say so and show where.
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || github.sha }}
|
||||
# Full history: the merge below needs it (a shallow clone refuses to merge at all).
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
|
||||
# The pull request as it would be once merged onto main is what gets built. When it cannot
|
||||
# be merged, the conflicting files and the conflicting hunks go into the run summary and the
|
||||
# pull-request comment, and the job stops here: there is nothing coherent to build.
|
||||
- name: No private key in the tree
|
||||
run: |
|
||||
set -euo pipefail
|
||||
keys=$(git ls-files | grep -iE '\.(jks|keystore|p12|pfx|pk8|pem|key)$' | grep -vx 'keystore/testkey.p12' || true)
|
||||
if [ -n "$keys" ]; then
|
||||
echo "::error::a private key is committed - remove it from the history and make a new one: $keys"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Merge onto main, or say what conflicts
|
||||
if: github.event_name == 'pull_request_target'
|
||||
if: github.event_name == 'pull_request'
|
||||
run: |
|
||||
set -uo pipefail
|
||||
git config user.name "ci"
|
||||
@@ -85,7 +69,6 @@ jobs:
|
||||
fi
|
||||
FILES=$(git diff --name-only --diff-filter=U)
|
||||
if [ -z "$FILES" ]; then
|
||||
# The merge did not even start (git said why): quote it rather than list nothing.
|
||||
{
|
||||
echo "### ERROR: Could not merge onto main (\`$BASE\`)"
|
||||
echo
|
||||
@@ -127,8 +110,6 @@ jobs:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
|
||||
# Caches ~/.gradle (dependencies, wrapper distribution, build cache, configuration cache)
|
||||
# and prunes what the run did not use, so the entry cannot grow without bound.
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
cache-cleanup: on-success
|
||||
@@ -137,20 +118,36 @@ jobs:
|
||||
run: |
|
||||
NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||
VERSION=$(sed -n 's/^Pkg.Revision *= *//p' "$NDK/source.properties")
|
||||
echo "NDK $VERSION at $NDK"
|
||||
echo "NDK_VERSION=$VERSION" >> "$GITHUB_ENV"
|
||||
|
||||
# ── The session's preloads ───────────────────────────────────────────────────────────
|
||||
# Both are glibc aarch64 libraries that live inside the rootfs, so they are cross-compiled
|
||||
# here rather than by the NDK. They ship in assets (not in the runtime tarball) so a fix in
|
||||
# either reaches an already-installed runtime on the next launch instead of waiting on a
|
||||
# ~790 MB runtime re-host. Their inputs change rarely, so most runs restore them.
|
||||
- name: Set the APK build label
|
||||
id: build-label
|
||||
env:
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
BUILD_REF: ${{ github.ref_name }}
|
||||
BUILD_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
if [[ -n "$(git status --porcelain)" ]]; then
|
||||
tree_state=dirty
|
||||
else
|
||||
tree_state=clean
|
||||
fi
|
||||
echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV"
|
||||
if [[ -n "$PR_NUMBER" ]]; then
|
||||
label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}"
|
||||
else
|
||||
label="${BUILD_REF} at ${BUILD_SHA:0:7}"
|
||||
fi
|
||||
echo "label=$label" >> "$GITHUB_OUTPUT"
|
||||
echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Cache the preloads
|
||||
id: preloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/mangoapp/*') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -162,9 +159,6 @@ jobs:
|
||||
sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu >/dev/null
|
||||
D=app/src/main/assets/linuxfs
|
||||
mkdir -p "$D"
|
||||
# Statically linked C++ runtime: this is preloaded into every Steam process, and Steam
|
||||
# ships its own libstdc++ while rewriting LD_LIBRARY_PATH. Pulling the system one in
|
||||
# ahead of it is a version conflict waiting to happen. Only libc is left as a dependency.
|
||||
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||
-pthread -std=c++17 -static-libstdc++ -static-libgcc \
|
||||
-o "$D/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
||||
@@ -172,28 +166,28 @@ jobs:
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so"
|
||||
# The session's scripts travel the same way, for the same reason.
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
# The SteamOS helpers the client calls in Deck mode, as no-op stubs (see each file).
|
||||
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
|
||||
[ -f "$f" ] && install -Dm644 "$f" "$D/${f#tools/linuxfs/overlay/}"
|
||||
done
|
||||
# The patched gamescope, when a build of it has been published (tools/gamescope/release.env
|
||||
# names the release and the archive's sha256); see tools/gamescope/PATCHES.md.
|
||||
if [ -f tools/gamescope/release.env ]; then
|
||||
. tools/gamescope/release.env
|
||||
# Through the API: the repository is private, so the plain download URL answers 404.
|
||||
gh release download "${GAMESCOPE_TAG}" -R "${GITHUB_REPOSITORY}" -p gamescope.tzst -O gamescope.tzst
|
||||
echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D"
|
||||
test -f "$D/usr/local/bin/gamescope"
|
||||
rm gamescope.tzst
|
||||
fi
|
||||
# Valve's aarch64 mangoapp for Deck mode's performance overlay, plus the five libraries the
|
||||
# runtime lacks, pinned by sha256 in tools/mangoapp/packages.txt. Stored under the SONAME
|
||||
# each is loaded by, as real files: assets cannot carry symlinks.
|
||||
if [ -f tools/wlroots/release.env ]; then
|
||||
. tools/wlroots/release.env
|
||||
gh release download "${WLROOTS_TAG}" -R "${GITHUB_REPOSITORY}" -p wlroots.tzst -O wlroots.tzst
|
||||
echo "${WLROOTS_SHA256} wlroots.tzst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf wlroots.tzst -C "$D"
|
||||
test -f "$D/usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so"
|
||||
rm wlroots.tzst
|
||||
fi
|
||||
M="$D/usr/local/lib/mangoapp"
|
||||
mkdir -p "$M" mango-pkgs
|
||||
grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do
|
||||
@@ -210,18 +204,15 @@ jobs:
|
||||
install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
|
||||
rm -rf mango-pkgs
|
||||
ls -l "$M"
|
||||
# And the desktop's launcher and labwc defaults, staged over the desktop package's copies.
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$D/usr/local/bin/droiddeck-desktop"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$D/usr/local/bin/droiddeck-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$D/usr/local/bin/droiddeck-desktop-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/autostart "$D/etc/xdg/labwc/autostart"
|
||||
install -Dm644 tools/linuxfs/desktop/rc.xml "$D/etc/xdg/labwc/rc.xml"
|
||||
install -Dm644 tools/linuxfs/desktop/panel.conf "$D/etc/xdg/lxqt/panel.conf"
|
||||
install -Dm644 tools/linuxfs/desktop/firefox-droiddeck.js "$D/usr/lib/firefox/defaults/pref/droiddeck.js"
|
||||
ls -lR "$D"
|
||||
|
||||
# The daemon's AAudio sink (tools/aaudio-sink), compiled here against upstream PulseAudio 13
|
||||
# headers and the app's own libpulse*, then put into the audio bundle the apk carries. The
|
||||
# committed bundle holds every other module and no sink, so a build without this step would
|
||||
# have no audio - the unpack check in PulseAudioComponent would then fail loudly, not quietly.
|
||||
- name: Cache PulseAudio 13.0 source
|
||||
id: pa-src
|
||||
uses: actions/cache@v4
|
||||
@@ -249,21 +240,32 @@ jobs:
|
||||
tar --use-compress-program=unzstd -tf app/src/main/assets/pulseaudio.tzst | grep -c '\.so$'
|
||||
rm -rf pa-bundle sink-out
|
||||
|
||||
# Runs whether the preloads were built or restored: readelf reads any ELF whatever the host,
|
||||
# so these assertions cost nothing and need no cross toolchain.
|
||||
- name: Cache proot
|
||||
id: proot
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
app/src/main/jniLibs/arm64-v8a/libproot.so
|
||||
app/src/main/jniLibs/arm64-v8a/libproot-loader.so
|
||||
key: proot-${{ env.NDK_VERSION }}-${{ hashFiles('tools/proot/**') }}
|
||||
- name: Build proot
|
||||
if: steps.proot.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||
tools/proot/build.sh app/src/main/jniLibs/arm64-v8a
|
||||
|
||||
- name: Check the preloads
|
||||
run: |
|
||||
set -euo pipefail
|
||||
D=app/src/main/assets/linuxfs
|
||||
NEED=$(readelf -d "$D/libfakeinput.so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p')
|
||||
echo "libfakeinput NEEDED: $NEED"
|
||||
for bad in libstdc++.so.6 libgcc_s.so.1; do
|
||||
if printf '%s\n' "$NEED" | grep -qx "$bad"; then
|
||||
echo "::error::libfakeinput.so links $bad - the C++ runtime must stay static"; exit 1
|
||||
fi
|
||||
done
|
||||
syms() { readelf -Ws "$1" | awk '$4 == "FUNC" && $5 == "GLOBAL" {sub(/@.*/, "", $8); print $8}'; }
|
||||
# The interposers are the whole point: if one is missing the client sees no controller.
|
||||
FAKE=$(syms "$D/libfakeinput.so")
|
||||
for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do
|
||||
grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; }
|
||||
@@ -274,12 +276,7 @@ jobs:
|
||||
done
|
||||
test -f "$D/usr/local/bin/bannerlator-session"
|
||||
test -f "$D/usr/local/bin/bannerlator-proton-extra"
|
||||
echo "preloads check out"
|
||||
|
||||
# ── The native build ─────────────────────────────────────────────────────────────────
|
||||
# The compositor and adrenotools are the slowest part of a build and change least often.
|
||||
# The key pins the C sources and the NDK; the restore-key still hands an older tree to
|
||||
# ninja, which then rebuilds only the files that differ.
|
||||
- name: Cache the CMake build tree
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
@@ -290,27 +287,14 @@ jobs:
|
||||
restore-keys: |
|
||||
cxx-${{ env.NDK_VERSION }}-
|
||||
|
||||
# Release, not debug: AGP quietly drops v1 (JAR) signing from a debug build once minSdk is
|
||||
# 24 or higher, and the apk has to carry all three schemes. Nothing is minified either way.
|
||||
# The whole log is kept so a failed build's errors can be quoted back on a pull request.
|
||||
- name: Build
|
||||
id: build
|
||||
env:
|
||||
DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }}
|
||||
run: |
|
||||
set -o pipefail
|
||||
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
|
||||
|
||||
- name: Describe the apk
|
||||
run: |
|
||||
set -euo pipefail
|
||||
APK=$(find app/build/outputs/apk -name '*.apk' | head -1)
|
||||
echo "apk: $APK"
|
||||
ls -l "$APK"
|
||||
sha256sum "$APK"
|
||||
unzip -l "$APK" | grep -E 'lib/arm64-v8a|assets/linuxfs' | head -30
|
||||
|
||||
# Every NEEDED of every library we ship must resolve inside the apk or on the device. The
|
||||
# first build shipped libwayland-server.so without libffi.so, and the app died on
|
||||
# System.loadLibrary the moment a session started - a check this step would have caught.
|
||||
- name: Check the native dependency closure
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -318,8 +302,6 @@ jobs:
|
||||
WORK=$(mktemp -d)
|
||||
unzip -q "$APK" 'lib/arm64-v8a/*' -d "$WORK"
|
||||
cd "$WORK/lib/arm64-v8a"
|
||||
# Provided by the platform, so never packaged. libstdc++.so is Android's minimal system
|
||||
# C++ runtime; the Termux PTY JNI library has this in its NEEDED list.
|
||||
SYSTEM="libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so libstdc++.so
|
||||
libGLESv2.so libEGL.so libnativewindow.so libjnigraphics.so libaaudio.so
|
||||
libOpenSLES.so libmediandk.so libcamera2ndk.so libsync.so libneuralnetworks.so"
|
||||
@@ -327,19 +309,13 @@ jobs:
|
||||
for so in *.so; do
|
||||
for need in $(readelf -d "$so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p'); do
|
||||
[ -f "$need" ] && continue
|
||||
# $SYSTEM spans lines; unquoted echo folds its newlines to spaces, or the last
|
||||
# name on each line could never match (libaaudio.so did not, for the relay helper).
|
||||
case " $(echo $SYSTEM) " in *" $need "*) continue ;; esac
|
||||
echo "::error::$so needs $need, which is neither in the apk nor a platform library"
|
||||
fail=1
|
||||
done
|
||||
done
|
||||
[ "$fail" = 0 ] && echo "every NEEDED resolves"
|
||||
exit $fail
|
||||
|
||||
# AGP signs with v2+v3 and drops v1 whenever minSdk is 24 or higher, and setting
|
||||
# enableV1Signing in the DSL does not move it. Re-signing here with apksigner is the one way
|
||||
# to be sure of what the apk carries: zipalign first, then all three schemes explicitly.
|
||||
- name: Sign with the testkey (v1 + v2 + v3)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -353,18 +329,12 @@ jobs:
|
||||
--out "$APK" "$APK.aligned"
|
||||
rm -f "$APK.aligned" "$APK.idsig"
|
||||
|
||||
# The apk must stay installable over the last one, and on every Android version: that means
|
||||
# one stable key and all three signature schemes. Cheap to assert, easy to lose silently.
|
||||
- name: Check the signature
|
||||
run: |
|
||||
set -euo pipefail
|
||||
APK=$(find app/build/outputs/apk -name '*.apk' | head -1)
|
||||
APKSIGNER=$(find "$ANDROID_HOME/build-tools" -name apksigner | sort -V | tail -1)
|
||||
# --min-sdk-version 21: apksigner only verifies the schemes an apk's own minSdk requires,
|
||||
# so at minSdk 26 it reports v1 as false whether or not the JAR signature is there.
|
||||
# Asking it to verify from 21 makes it actually look.
|
||||
"$APKSIGNER" verify --min-sdk-version 21 --verbose --print-certs "$APK" | tee /tmp/sig.txt
|
||||
# And the files themselves, which is what an old installer reads.
|
||||
unzip -l "$APK" | grep -qE 'META-INF/.*\.(SF|RSA|DSA)$' \
|
||||
|| { echo "::error::apk carries no JAR signature files"; exit 1; }
|
||||
for scheme in "v1 scheme (JAR signing): true" "v2 scheme (APK Signature Scheme v2): true" \
|
||||
@@ -374,12 +344,8 @@ jobs:
|
||||
grep -qi "CN=Android, OU=Android, O=Android" /tmp/sig.txt \
|
||||
|| { echo "::error::apk is not signed with the AOSP testkey"; exit 1; }
|
||||
|
||||
# ── The pull-request report ──────────────────────────────────────────────────────────
|
||||
# One comment per pull request, rewritten on every push: whether it merges, and when the
|
||||
# build failed, the compiler's own errors with paths made short. Fork pull requests carry a
|
||||
# read-only token and cannot comment; the same text is in the run summary either way.
|
||||
- name: Report on the pull request
|
||||
if: always() && github.event_name == 'pull_request_target'
|
||||
if: always() && github.event_name == 'pull_request'
|
||||
continue-on-error: true
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
@@ -399,7 +365,7 @@ jobs:
|
||||
success)
|
||||
echo "### Build passed"
|
||||
echo
|
||||
echo "The apk is the \`droiddeck-apk\` artifact on [this run]($RUN_URL) (signed with the same test key as every build, so it installs over any other)."
|
||||
echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key. After approval, a maintainer can run **PR Release Publish** from \`main\` to create an APK that installs over the release."
|
||||
;;
|
||||
failure)
|
||||
echo "### ERROR: Build failed"
|
||||
@@ -426,7 +392,6 @@ jobs:
|
||||
;;
|
||||
esac
|
||||
echo
|
||||
echo "_Updated on every push to this pull request._"
|
||||
} > /tmp/pr-report.md
|
||||
cat /tmp/pr-report.md >> "$GITHUB_STEP_SUMMARY"
|
||||
ID=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR}/comments" --paginate --jq ".[] | select(.body | startswith(\"$MARK\")) | .id" | head -1 || true)
|
||||
@@ -442,5 +407,16 @@ jobs:
|
||||
path: app/build/outputs/apk/release/*.apk
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
# An apk is a zip already; compressing it again buys nothing and costs seconds.
|
||||
compression-level: 0
|
||||
|
||||
sign:
|
||||
needs: build
|
||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
uses: ./.github/workflows/sign.yml
|
||||
with:
|
||||
environment: signing-main
|
||||
variants: '["standard"]'
|
||||
secrets: inherit
|
||||
@@ -0,0 +1,150 @@
|
||||
name: PR Release Publish
|
||||
run-name: sign PR #${{ inputs.pr_number }} with the release key
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr_number:
|
||||
description: Open, approved pull request
|
||||
required: true
|
||||
type: number
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
concurrency:
|
||||
group: pr-release-${{ inputs.pr_number }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
authorize:
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
run_id: ${{ steps.gate.outputs.run_id }}
|
||||
head_sha: ${{ steps.gate.outputs.head_sha }}
|
||||
label: ${{ steps.gate.outputs.label }}
|
||||
steps:
|
||||
- name: Check the PR, review, and build
|
||||
id: gate
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null
|
||||
head=$(jq -r '.head.sha' <<<"$pr")
|
||||
base=$(jq -r '.base.sha' <<<"$pr")
|
||||
|
||||
run_id=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml \
|
||||
--event pull_request --commit "$head" \
|
||||
--json databaseId,headSha,status,conclusion,createdAt,attempt -L 100 |
|
||||
jq -r --arg head "$head" '[.[] | select(.headSha == $head)] |
|
||||
sort_by([.createdAt, .attempt]) | last |
|
||||
select(.status == "completed" and .conclusion == "success") | .databaseId // empty')
|
||||
[[ -n "$run_id" ]] || { echo '::error::The latest PR build is not green'; exit 1; }
|
||||
run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")
|
||||
jq -e --arg head "$head" --arg base "$base" --argjson number "$PR_NUMBER" '
|
||||
.event == "pull_request" and .head_sha == $head and .conclusion == "success" and
|
||||
any(.pull_requests[]?; .number == $number and .head.sha == $head and .base.sha == $base)
|
||||
' <<<"$run" >/dev/null
|
||||
|
||||
approved=$(gh api --paginate --slurp \
|
||||
"repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/reviews?per_page=100" |
|
||||
jq -r --arg head "$head" '[.[][] | select(.commit_id == $head)] |
|
||||
group_by(.user.login) | map(max_by(.id)) | .[] |
|
||||
select(.state == "APPROVED") | .user.login')
|
||||
maintainer_approved=false
|
||||
while IFS= read -r reviewer; do
|
||||
[[ -n "$reviewer" ]] || continue
|
||||
permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$reviewer/permission" --jq .permission)
|
||||
[[ "$permission" == write || "$permission" == admin ]] && maintainer_approved=true
|
||||
done <<<"$approved"
|
||||
[[ "$maintainer_approved" == true ]] || { echo '::error::A maintainer must approve this commit'; exit 1; }
|
||||
|
||||
sdk=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}
|
||||
tools=$(find "$sdk/build-tools" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -1)
|
||||
stable_tag=$(gh api repos/The412Banner/DroidDeck/releases/latest --jq .tag_name)
|
||||
mkdir -p "$RUNNER_TEMP/stable" "$RUNNER_TEMP/pr"
|
||||
gh release download "$stable_tag" -R The412Banner/DroidDeck \
|
||||
-p "DroidDeck-$stable_tag.apk" -D "$RUNNER_TEMP/stable"
|
||||
gh run download "$run_id" -R "$GITHUB_REPOSITORY" -n droiddeck-apk -D "$RUNNER_TEMP/pr"
|
||||
mapfile -t apks < <(find "$RUNNER_TEMP/pr" -type f -name '*.apk')
|
||||
[[ ${#apks[@]} == 1 ]] || { echo '::error::Expected one PR APK'; exit 1; }
|
||||
package_line() {
|
||||
"$tools/aapt" dump badging "$1" | sed -n "s/^package: name='\\([^']*\\)' versionCode='\\([^']*\\)'.*/\\1 \\2/p"
|
||||
}
|
||||
stable=$(package_line "$RUNNER_TEMP/stable/DroidDeck-$stable_tag.apk")
|
||||
candidate=$(package_line "${apks[0]}")
|
||||
[[ "$stable" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && "$candidate" == "$stable" ]] || {
|
||||
echo "::error::PR package/versionCode '$candidate' differs from stable '$stable'"; exit 1;
|
||||
}
|
||||
|
||||
current=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||
jq -e --arg head "$head" --arg base "$base" '
|
||||
.state == "open" and .draft == false and .base.ref == "main" and
|
||||
.head.sha == $head and .base.sha == $base
|
||||
' <<<"$current" >/dev/null
|
||||
[[ $(gh pr view "$PR_NUMBER" -R "$GITHUB_REPOSITORY" --json reviewDecision --jq .reviewDecision) == APPROVED ]] || {
|
||||
echo '::error::The current PR revision still needs approval'; exit 1;
|
||||
}
|
||||
{
|
||||
echo "run_id=$run_id"
|
||||
echo "head_sha=$head"
|
||||
echo "label=PR.$PR_NUMBER-${head:0:7}"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
sign:
|
||||
needs: authorize
|
||||
uses: ./.github/workflows/sign.yml
|
||||
with:
|
||||
environment: signing-main
|
||||
variants: '["standard"]'
|
||||
run_id: ${{ needs.authorize.outputs.run_id }}
|
||||
label: ${{ needs.authorize.outputs.label }}
|
||||
artifact: droiddeck-pr-signed
|
||||
secrets: inherit
|
||||
|
||||
publish:
|
||||
needs: [authorize, sign]
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: droiddeck-pr-signed-standard
|
||||
path: signed
|
||||
- name: Publish to DroidDeck-CI when configured
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.DROIDDECK_CI_TOKEN }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
|
||||
LABEL: ${{ needs.authorize.outputs.label }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -z "$GH_TOKEN" ]]; then
|
||||
echo '::warning::No CI token; download the signed APK from this run'
|
||||
exit 0
|
||||
fi
|
||||
repo=Droid-Deck/DroidDeck-CI
|
||||
tag="pr-$PR_NUMBER"
|
||||
apk="DroidDeck-$LABEL.apk"
|
||||
sha=$(sha256sum "signed/$apk" | cut -d ' ' -f 1)
|
||||
notes="Source: https://github.com/$GITHUB_REPOSITORY/pull/$PR_NUMBER
|
||||
Commit: $HEAD_SHA
|
||||
APK SHA-256: $sha"
|
||||
if ! gh release view "$tag" -R "$repo" >/dev/null 2>&1; then
|
||||
gh release create "$tag" -R "$repo" --target main --title "PR #$PR_NUMBER" --notes "$notes" --prerelease
|
||||
fi
|
||||
gh release upload "$tag" "signed/$apk" -R "$repo" --clobber
|
||||
gh release edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease
|
||||
gh api "repos/$repo/releases/tags/$tag" |
|
||||
jq -r --arg keep "$apk" '.assets[] | select(.name | endswith(".apk")) | select(.name != $keep) | .id' |
|
||||
while IFS= read -r id; do
|
||||
gh api --method DELETE "repos/$repo/releases/assets/$id" >/dev/null
|
||||
done
|
||||
@@ -0,0 +1,60 @@
|
||||
name: Release APKs
|
||||
run-name: release ${{ inputs.version }} from main ${{ github.sha }}
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: Version for the file names, e.g. 0.1.7
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
concurrency:
|
||||
group: release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
find:
|
||||
name: find the main build
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
run_id: ${{ steps.find.outputs.run_id }}
|
||||
variants: ${{ steps.find.outputs.variants }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- id: find
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ $VERSION =~ ^[0-9A-Za-z._-]+$ ]] || { echo "::error::version '$VERSION': letters, digits, . _ - only"; exit 1; }
|
||||
runs=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml --branch main --commit "$GITHUB_SHA" \
|
||||
--status success --json databaseId,event,headSha -L 20)
|
||||
id=$(jq -r --arg sha "$GITHUB_SHA" \
|
||||
'[.[] | select(.headSha == $sha and (.event == "push" or .event == "workflow_dispatch"))][0].databaseId // empty' <<<"$runs")
|
||||
if [ -z "$id" ]; then
|
||||
echo "::error::main ${GITHUB_SHA::7} has no successful Build APK run yet: wait for it, then release"
|
||||
exit 1
|
||||
fi
|
||||
variants=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .)
|
||||
echo "run_id=$id" >> "$GITHUB_OUTPUT"
|
||||
echo "variants=$variants" >> "$GITHUB_OUTPUT"
|
||||
echo "Signing Build APK run $id (main ${GITHUB_SHA::7}) as $VERSION: $variants" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
sign:
|
||||
needs: find
|
||||
uses: ./.github/workflows/sign.yml
|
||||
with:
|
||||
environment: release
|
||||
variants: ${{ needs.find.outputs.variants }}
|
||||
run_id: ${{ needs.find.outputs.run_id }}
|
||||
label: ${{ inputs.version }}
|
||||
artifact: droiddeck-release
|
||||
secrets: inherit
|
||||
@@ -0,0 +1,95 @@
|
||||
name: Sign APKs
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
environment:
|
||||
type: string
|
||||
required: true
|
||||
variants:
|
||||
description: JSON array of names from tools/release/variants.txt
|
||||
type: string
|
||||
required: true
|
||||
run_id:
|
||||
description: The Build APK run whose apk to sign; empty for the calling run's own
|
||||
type: string
|
||||
default: ''
|
||||
label:
|
||||
description: Goes in the file names (a version); empty for <branch>-<short sha>
|
||||
type: string
|
||||
default: ''
|
||||
artifact:
|
||||
type: string
|
||||
default: droiddeck-signed
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
jobs:
|
||||
sign:
|
||||
name: sign ${{ matrix.variant }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
environment: ${{ inputs.environment }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
variant: ${{ fromJSON(inputs.variants) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: The apk (this run's build)
|
||||
if: inputs.run_id == ''
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: droiddeck-apk
|
||||
path: in
|
||||
|
||||
- name: The apk (a main build)
|
||||
if: inputs.run_id != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RUN: ${{ inputs.run_id }}
|
||||
run: gh run download "$RUN" -R "$GITHUB_REPOSITORY" -n droiddeck-apk -D in
|
||||
|
||||
- name: Sign
|
||||
env:
|
||||
RELEASE_KEYSTORE_B64: ${{ secrets.RELEASE_KEYSTORE_B64 }}
|
||||
RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }}
|
||||
RELEASE_KEY_ALIAS: droiddeck
|
||||
ENVIRONMENT: ${{ inputs.environment }}
|
||||
VARIANT: ${{ matrix.variant }}
|
||||
LABEL: ${{ inputs.label }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "$RELEASE_KEYSTORE_B64" ]; then
|
||||
echo "::error::environment '$ENVIRONMENT' has no signing key: run tools/release/make-release-key.sh once"
|
||||
exit 1
|
||||
fi
|
||||
export RELEASE_KEYSTORE="$RUNNER_TEMP/release.p12"
|
||||
( umask 077; base64 -d <<<"$RELEASE_KEYSTORE_B64" > "$RELEASE_KEYSTORE" )
|
||||
BUILD_TOOLS=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -n1)
|
||||
export BUILD_TOOLS
|
||||
[ -n "$LABEL" ] || LABEL="${GITHUB_REF_NAME//\//-}-${GITHUB_SHA::7}"
|
||||
suffix=$(awk -v v="$VARIANT" '!/^#/ && $1 == v { print $3 }' tools/release/variants.txt)
|
||||
[ "$suffix" = - ] && suffix=
|
||||
apks=(in/*.apk)
|
||||
[ ${#apks[@]} = 1 ] && [ -f "${apks[0]}" ] || { echo "::error::expected one apk in the build"; exit 1; }
|
||||
mkdir -p out
|
||||
out="out/DroidDeck-$LABEL$suffix.apk"
|
||||
tools/release/sign-apk.sh "${apks[0]}" "$VARIANT" "$out"
|
||||
( cd out && sha256sum -- *.apk > "SHA256SUMS-$VARIANT.txt" && cat "SHA256SUMS-$VARIANT.txt" )
|
||||
echo "- \`$(basename "$out")\` - $(cut -c1-16 "out/SHA256SUMS-$VARIANT.txt")…" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Forget the key
|
||||
if: always()
|
||||
run: rm -f "$RUNNER_TEMP/release.p12"
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ inputs.artifact }}-${{ matrix.variant }}
|
||||
path: out/*
|
||||
if-no-files-found: error
|
||||
@@ -11,6 +11,21 @@ captures/
|
||||
# Built in CI from tools/linuxfs and app/src/main/cpp/fakeinput.cpp, never committed, so the two
|
||||
# copies cannot drift.
|
||||
app/src/main/assets/linuxfs/
|
||||
app/src/main/jniLibs/arm64-v8a/libproot.so
|
||||
app/src/main/jniLibs/arm64-v8a/libproot-loader.so
|
||||
|
||||
# Kotlin compiler session files (build-tool state, never source).
|
||||
.kotlin/
|
||||
|
||||
# Signing keys never enter the repo (DroidDeck's lives in GitHub environment secrets; see
|
||||
# tools/release/make-release-key.sh). keystore/testkey.p12 is the public AOSP testkey.
|
||||
*.jks
|
||||
*.keystore
|
||||
*.p12
|
||||
*.pfx
|
||||
*.pk8
|
||||
*.pem
|
||||
!keystore/testkey.p12
|
||||
droiddeck-release-key/
|
||||
password.txt
|
||||
__pycache__/
|
||||
@@ -4,6 +4,51 @@ plugins {
|
||||
apply plugin: 'kotlin-android'
|
||||
apply plugin: 'org.jetbrains.kotlin.plugin.compose'
|
||||
|
||||
def gitValue = { List<String> arguments ->
|
||||
try {
|
||||
def output = providers.exec {
|
||||
commandLine(['git'] + arguments)
|
||||
workingDir rootProject.projectDir
|
||||
ignoreExitValue = true
|
||||
}
|
||||
output.result.get().exitValue == 0 ? output.standardOutput.asText.get().trim() : null
|
||||
} catch (Exception ignored) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
def buildLabel = providers.environmentVariable('DROIDDECK_BUILD_LABEL').getOrNull()
|
||||
if (buildLabel == null || buildLabel.trim().isEmpty()) {
|
||||
def eventName = providers.environmentVariable('GITHUB_EVENT_NAME').getOrNull()
|
||||
def eventPath = providers.environmentVariable('GITHUB_EVENT_PATH').getOrNull()
|
||||
if (eventName == 'pull_request_target' && eventPath) {
|
||||
try {
|
||||
def eventFile = layout.file(providers.provider { new File(eventPath) })
|
||||
def eventText = providers.fileContents(eventFile).asText.get()
|
||||
def pullRequest = new groovy.json.JsonSlurper().parseText(eventText).pull_request
|
||||
if (pullRequest?.number && pullRequest?.head?.sha) {
|
||||
buildLabel = "pr${pullRequest.number} at ${pullRequest.head.sha.take(7)}"
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
if (buildLabel == null || buildLabel.trim().isEmpty()) {
|
||||
def branch = providers.environmentVariable('GITHUB_REF_NAME').getOrNull()
|
||||
?: gitValue(['branch', '--show-current']) ?: 'local'
|
||||
def commit = providers.environmentVariable('GITHUB_SHA').getOrNull()
|
||||
?.take(7) ?: gitValue(['rev-parse', '--short=7', 'HEAD']) ?: 'unknown'
|
||||
buildLabel = "${branch} at ${commit}"
|
||||
}
|
||||
}
|
||||
def buildOrigin = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true' ? 'remote' : 'local'
|
||||
def treeState = providers.environmentVariable('DROIDDECK_BUILD_TREE_STATE').getOrNull()
|
||||
if (!(treeState in ['clean', 'dirty'])) {
|
||||
def status = gitValue(['status', '--porcelain'])
|
||||
treeState = status == null ? 'unknown' : (status.isEmpty() ? 'clean' : 'dirty')
|
||||
}
|
||||
buildLabel = "${buildOrigin} ${treeState} · ${buildLabel}"
|
||||
def escapedBuildLabel = buildLabel.replace('\\', '\\\\').replace('"', '\\"')
|
||||
|
||||
android {
|
||||
namespace 'com.droiddeck.launcher'
|
||||
compileSdk 34
|
||||
@@ -18,8 +63,9 @@ android {
|
||||
// file out of its own data directory, and this app's entire job is to exec a rootfs:
|
||||
// proot, gamescope, the Steam client and everything it launches all live under files/.
|
||||
targetSdkVersion 28
|
||||
versionCode 7
|
||||
versionName "0.1.6"
|
||||
versionCode 8
|
||||
versionName "0.1.7"
|
||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||
|
||||
ndk {
|
||||
abiFilters 'arm64-v8a'
|
||||
@@ -75,6 +121,10 @@ android {
|
||||
}
|
||||
|
||||
packagingOptions {
|
||||
resources {
|
||||
// Kadb's Bouncy Castle artifacts repeat the same multi-release JAR manifest.
|
||||
excludes += ['META-INF/versions/9/OSGI-INF/MANIFEST.MF']
|
||||
}
|
||||
jniLibs {
|
||||
// The PulseAudio daemon is executed from the native library directory and its
|
||||
// libraries are read out of the apk by the class loader: both want the old,
|
||||
@@ -87,6 +137,7 @@ android {
|
||||
|
||||
buildFeatures {
|
||||
compose true
|
||||
buildConfig true
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
@@ -113,6 +164,9 @@ dependencies {
|
||||
implementation 'androidx.compose.material:material-icons-extended'
|
||||
implementation 'io.coil-kt:coil-compose:2.6.0'
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
||||
// ADB-over-Wi-Fi pairing and authenticated shell client. Users still approve pairing from
|
||||
// Android's Wireless debugging screen; DroidDeck only runs its one fixed setting command.
|
||||
implementation 'com.flyfishxu:kadb-android:1.2.1'
|
||||
// Android terminal view/emulator used by the in-session secondary-display Linux shell.
|
||||
implementation 'com.termux.termux-app:terminal-view:0.118.0'
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application>
|
||||
<!-- Debug builds only. Android grants DUMP to adb shell; release APKs have no bridge. -->
|
||||
<activity
|
||||
android:name=".agent.AgentStartActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:permission="android.permission.DUMP"
|
||||
android:theme="@style/SessionTheme" />
|
||||
<provider
|
||||
android:name=".agent.AgentBridgeProvider"
|
||||
android:authorities="${applicationId}.agent"
|
||||
android:exported="true"
|
||||
android:permission="android.permission.DUMP"
|
||||
android:grantUriPermissions="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.Manifest
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.Binder
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** A shell-only control surface, installed only by debug builds. */
|
||||
class AgentBridgeProvider : ContentProvider() {
|
||||
override fun onCreate(): Boolean {
|
||||
val appContext = context?.applicationContext ?: return false
|
||||
Thread({
|
||||
try {
|
||||
SessionArtifacts.finishAbandoned(appContext)
|
||||
} finally {
|
||||
recoveryComplete.countDown()
|
||||
}
|
||||
}, "agent-recover-artifacts").start()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
|
||||
val context = requireNotNull(context)
|
||||
if (Binder.getCallingUid() != Process.myUid() &&
|
||||
context.checkCallingPermission(Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
throw SecurityException("android.permission.DUMP is required")
|
||||
}
|
||||
|
||||
val response = try {
|
||||
when (method) {
|
||||
"state" -> state(context).put("ok", true)
|
||||
"start" -> error("USE_DROIDDECKCTL", "Start sessions with tools/droiddeckctl so Android launches a visible Activity")
|
||||
"stop" -> stop(context)
|
||||
"resume" -> resume(context)
|
||||
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
error("COMMAND_FAILED", e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
return Bundle().apply { putString(RESULT_JSON, response.toString()) }
|
||||
}
|
||||
|
||||
private fun state(context: Context): JSONObject {
|
||||
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
|
||||
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: latestSessionDirectory()
|
||||
val session = JSONObject()
|
||||
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
|
||||
.put("phase", SessionState.phase.name)
|
||||
.put("running", SessionState.running)
|
||||
.put("mode", SessionState.mode)
|
||||
.put("program", SessionState.program ?: JSONObject.NULL)
|
||||
.put("steamUi", SessionState.steamUi ?: JSONObject.NULL)
|
||||
.put("steamUrl", SessionState.steamUrl ?: JSONObject.NULL)
|
||||
.put("suspended", SessionState.suspended)
|
||||
.put("firstFrame", SessionState.firstFrameSeen)
|
||||
.put("output", JSONArray().put(SessionState.outputSize.first).put(SessionState.outputSize.second))
|
||||
.put("refreshHz", SessionState.refreshHz.toDouble())
|
||||
.put("lastTransitionAt", SessionState.lastTransitionAt)
|
||||
.put("guestPid", SessionState.guestPid.takeIf { it > 1 } ?: JSONObject.NULL)
|
||||
.put("installing", SessionState.installing ?: JSONObject.NULL)
|
||||
.put("logDir", dir?.absolutePath ?: JSONObject.NULL)
|
||||
.put("eventsFile", dir?.let { File(it, "events.jsonl").absolutePath } ?: JSONObject.NULL)
|
||||
.put("artifactsAvailable", dir?.isDirectory ?: false)
|
||||
.put("artifactsComplete", dir?.let { File(it, ".complete").isFile } ?: false)
|
||||
|
||||
val failure = if (SessionState.failureCode == null) JSONObject.NULL else JSONObject()
|
||||
.put("code", SessionState.failureCode)
|
||||
.put("message", SessionState.failureMessage ?: JSONObject.NULL)
|
||||
.put("status", SessionState.failureStatus ?: JSONObject.NULL)
|
||||
session.put("failure", failure)
|
||||
|
||||
return JSONObject()
|
||||
.put("schema", 1)
|
||||
.put("build", BuildConfig.BUILD_LABEL)
|
||||
.put("appVersion", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
||||
.put("runtime", JSONObject()
|
||||
.put("installed", LinuxRuntime.isInstalled(context))
|
||||
.put("version", runtimeVersion ?: JSONObject.NULL))
|
||||
.put("session", session)
|
||||
}
|
||||
|
||||
private fun latestSessionDirectory(): File? {
|
||||
val parent = LinuxRuntime.debugLogDir()
|
||||
return parent.listFiles { file -> file.isDirectory && file.name.startsWith("session-") }
|
||||
?.maxWithOrNull(compareBy<File> { it.lastModified() }.thenBy { it.name })
|
||||
}
|
||||
|
||||
private fun stop(context: Context): JSONObject {
|
||||
if (SessionState.running) {
|
||||
SessionService.stop(context)
|
||||
return JSONObject().put("ok", true).put("command", "stop")
|
||||
}
|
||||
if (SessionState.phase == SessionPhase.STOPPING) {
|
||||
return JSONObject().put("ok", true).put("command", "stop")
|
||||
}
|
||||
if (SessionState.phase in STARTING_PHASES) {
|
||||
SessionState.stopRequested = true
|
||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stop_requested")
|
||||
return JSONObject().put("ok", true).put("command", "stop")
|
||||
}
|
||||
return error("NO_ACTIVE_SESSION", "There is no session to stop")
|
||||
}
|
||||
|
||||
private fun resume(context: Context): JSONObject {
|
||||
if (!SessionState.running || !SessionState.suspended) {
|
||||
return error("SESSION_NOT_SUSPENDED", "There is no suspended session to resume")
|
||||
}
|
||||
SessionService.resume(context)
|
||||
return JSONObject().put("ok", true).put("command", "resume")
|
||||
}
|
||||
|
||||
private fun error(code: String, message: String) = JSONObject()
|
||||
.put("ok", false)
|
||||
.put("error", JSONObject().put("code", code).put("message", message))
|
||||
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
|
||||
override fun getType(uri: Uri): String? = null
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
|
||||
companion object {
|
||||
const val RESULT_JSON = "json"
|
||||
private val recoveryComplete = CountDownLatch(1)
|
||||
|
||||
fun awaitRecovery() {
|
||||
try {
|
||||
if (!recoveryComplete.await(90, TimeUnit.SECONDS)) {
|
||||
throw IllegalStateException("Session artifact recovery did not finish")
|
||||
}
|
||||
} catch (e: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
throw IllegalStateException("Interrupted while recovering session artifacts", e)
|
||||
}
|
||||
}
|
||||
|
||||
private val STARTING_PHASES = setOf(
|
||||
SessionPhase.PREPARING,
|
||||
SessionPhase.INSTALLING_RUNTIME,
|
||||
SessionPhase.STARTING_COMPOSITOR,
|
||||
SessionPhase.STARTING_GUEST,
|
||||
SessionPhase.STARTING_STEAM,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Shell-launched trampoline: Android permits the shell to start this protected debug Activity. */
|
||||
class AgentStartActivity : Activity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val request = decodeRequest(intent.getStringExtra(EXTRA_REQUEST))
|
||||
if (request == null) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
|
||||
Thread({
|
||||
try {
|
||||
AgentBridgeProvider.awaitRecovery()
|
||||
runOnUiThread {
|
||||
if (!isFinishing) startSession(request)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "waiting for agent recovery", e)
|
||||
runOnUiThread { finish() }
|
||||
}
|
||||
}, "agent-start-recovery").start()
|
||||
}
|
||||
|
||||
private fun decodeRequest(encoded: String?): JSONObject? {
|
||||
if (encoded.isNullOrBlank()) {
|
||||
Log.e(TAG, "missing agent start request")
|
||||
return null
|
||||
}
|
||||
return try {
|
||||
JSONObject(String(Base64.decode(encoded, Base64.DEFAULT), Charsets.UTF_8))
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "invalid agent start request", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun startSession(request: JSONObject) {
|
||||
val requestedMode = request.optString("mode")
|
||||
val sessionMode = when (requestedMode) {
|
||||
"steam" -> SessionService.MODE_STEAM
|
||||
"desktop" -> SessionService.MODE_DESKTOP
|
||||
"run" -> SessionService.MODE_RUN
|
||||
else -> {
|
||||
Log.e(TAG, "invalid agent session mode: $requestedMode")
|
||||
finish()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
val program = if (sessionMode == SessionService.MODE_RUN) {
|
||||
request.optString("program").takeIf { it.isNotBlank() }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (sessionMode == SessionService.MODE_RUN && program == null) {
|
||||
Log.e(TAG, "run mode requires a program path")
|
||||
finish()
|
||||
return
|
||||
}
|
||||
|
||||
val sessionIntent = Intent(this, SessionActivity::class.java).apply {
|
||||
action = SessionService.ACTION_AGENT_START
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
putExtra(SessionService.EXTRA_MODE, sessionMode)
|
||||
if (program != null) {
|
||||
val args = request.optJSONArray("programArgs") ?: JSONArray()
|
||||
putExtra(SessionService.EXTRA_PROGRAM, program)
|
||||
putExtra(SessionService.EXTRA_PROGRAM_ARGS, Array(args.length()) { index -> args.optString(index) })
|
||||
}
|
||||
if (sessionMode == SessionService.MODE_STEAM) {
|
||||
request.optString("steamUi").takeIf { it == "desktop" }?.let {
|
||||
putExtra(SessionService.EXTRA_STEAM_UI, it)
|
||||
}
|
||||
request.optString("steamUrl").takeIf { it.startsWith("steam://") }?.let {
|
||||
putExtra(SessionService.EXTRA_STEAM_URL, it)
|
||||
}
|
||||
}
|
||||
}
|
||||
startActivity(sessionIntent)
|
||||
finish()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_REQUEST = "request"
|
||||
private const val TAG = "AgentStartActivity"
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<!-- Session logs go to Downloads so a failed run can be handed over as one folder. -->
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
@@ -55,9 +56,12 @@
|
||||
</activity>
|
||||
|
||||
<!-- Android owns the Home key. This small translucent Home handler routes the resulting
|
||||
Home launch either back into a running Steam session or to the regular front end. -->
|
||||
Home launch either back into a running Steam session or to the regular front end.
|
||||
Off until the user turns on "Use as a Home screen" (Setup): while it is disabled the
|
||||
app is not a Home app at all - not offered, not in the "choose Home" list. -->
|
||||
<activity
|
||||
android:name=".HomeActivity"
|
||||
android:enabled="false"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
@@ -81,6 +85,14 @@
|
||||
fixed-shape window instead and STRETCHES it onto the other panel - the app never sees a
|
||||
size change, so nothing it does can help.
|
||||
-->
|
||||
<activity
|
||||
android:name=".input.ControllerEditorActivity"
|
||||
android:exported="false"
|
||||
android:theme="@style/SessionTheme"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<activity
|
||||
android:name=".files.FileManagerActivity"
|
||||
android:exported="false"
|
||||
@@ -123,5 +135,17 @@
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/log_share_paths" />
|
||||
</provider>
|
||||
<!-- The app's data folder in Android's file picker ("Open from" > DroidDeck). Only the
|
||||
system's documents UI may bind it; apps get a file only when the user picks it. -->
|
||||
<provider
|
||||
android:name=".files.AppFilesProvider"
|
||||
android:authorities="${applicationId}.documents"
|
||||
android:exported="true"
|
||||
android:grantUriPermissions="true"
|
||||
android:permission="android.permission.MANAGE_DOCUMENTS">
|
||||
<intent-filter>
|
||||
<action android:name="android.content.action.DOCUMENTS_PROVIDER" />
|
||||
</intent-filter>
|
||||
</provider>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -1231,6 +1231,8 @@ EXPORT int close(int fd) {
|
||||
return my_close(fd);
|
||||
}
|
||||
|
||||
static constexpr int kMaxRingWaitMs = 2;
|
||||
|
||||
EXPORT ssize_t read(int fd, void *buf, size_t count) {
|
||||
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
||||
auto controller = controller_map().find(fd);
|
||||
@@ -1323,7 +1325,7 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) {
|
||||
int result = nanosleep(&sleep_time, nullptr);
|
||||
guard.lock();
|
||||
if (result < 0) return -1;
|
||||
if (backoff_ns < 16 * 1000 * 1000) backoff_ns *= 2;
|
||||
if (backoff_ns < kMaxRingWaitMs * 1000 * 1000) backoff_ns *= 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1469,7 +1471,7 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
|
||||
if (deadline_ms >= 0 && monotonic_ms() >= deadline_ms)
|
||||
return 0;
|
||||
|
||||
if (backoff_ms < 16)
|
||||
if (backoff_ms < kMaxRingWaitMs)
|
||||
backoff_ms *= 2;
|
||||
}
|
||||
}
|
||||
@@ -1644,7 +1646,7 @@ EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
||||
if (deadline_ms >= 0 && monotonic_ms() >= deadline_ms)
|
||||
return 0;
|
||||
|
||||
if (backoff_ms < 16)
|
||||
if (backoff_ms < kMaxRingWaitMs)
|
||||
backoff_ms *= 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,8 +139,6 @@ namespace winfg { class Engine; }
|
||||
|
||||
static constexpr uint32_t MAX_FRAMES_IN_FLIGHT = 2;
|
||||
|
||||
struct WindowPushConstants { float ndcX0, ndcY0, ndcX1, ndcY1; int useTexAlpha; };
|
||||
|
||||
// Push-constant layouts for the spatial-upscaler post passes. The leading vec4
|
||||
// `ndc` matches upscale.vert; the remaining members are read only by the
|
||||
// fragment stage. std430 offsets line up with these C structs.
|
||||
@@ -164,11 +162,6 @@ struct RcasPushConstants { // 40 bytes
|
||||
uint32_t con[4]; // con.x = bit-packed sharpness
|
||||
float outW, outH;
|
||||
};
|
||||
struct DownscalePushConstants { // 32 bytes
|
||||
float ndc[4];
|
||||
float srcW, srcH; // render (source) resolution
|
||||
float dstW, dstH; // display (output) resolution
|
||||
};
|
||||
// Composable post effects (AMD CAS sharpen + fake-HDR). Both lead with vec4 ndc
|
||||
// (offset 0) like the upscaler PCs and stay well under the 88-byte PC range.
|
||||
struct CasPushConstants { // 32 bytes
|
||||
@@ -741,7 +734,6 @@ private:
|
||||
NisPushConstants nisPC{};
|
||||
EasuPushConstants easuPC{};
|
||||
RcasPushConstants rcasPC{};
|
||||
DownscalePushConstants dsPC{};
|
||||
CasPushConstants casPC{};
|
||||
HdrPushConstants hdrPC{};
|
||||
FxaaPushConstants fxaaPC{};
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
// 1116.2.0
|
||||
#pragma once
|
||||
const uint32_t downscale_code[] = {
|
||||
0x07230203,0x00010000,0x0008000b,0x000000b5,0x00000000,0x00020011,0x00000001,0x00020011,
|
||||
0x00000032,0x0006000b,0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,
|
||||
0x00000000,0x00000001,0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000046,
|
||||
0x000000ab,0x00030010,0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,
|
||||
0x00000004,0x6e69616d,0x00000000,0x00060005,0x0000000a,0x636e616c,0x32736f7a,0x3b316628,
|
||||
0x00000000,0x00030005,0x00000009,0x00000078,0x00030005,0x0000001d,0x00007870,0x00040005,
|
||||
0x00000031,0x6c616373,0x00000065,0x00030005,0x00000033,0x00004350,0x00040006,0x00000033,
|
||||
0x00000000,0x0063646e,0x00050006,0x00000033,0x00000001,0x53637273,0x00657a69,0x00050006,
|
||||
0x00000033,0x00000002,0x53747364,0x00657a69,0x00030005,0x00000035,0x00006370,0x00050005,
|
||||
0x00000041,0x53766e69,0x656c6163,0x00000000,0x00030005,0x00000044,0x00000063,0x00060005,
|
||||
0x00000046,0x67617266,0x43786554,0x64726f6f,0x00000000,0x00040005,0x0000004d,0x65736162,
|
||||
0x00000000,0x00030005,0x00000051,0x00007a73,0x00030005,0x00000055,0x00637273,0x00030005,
|
||||
0x0000005c,0x00636361,0x00040005,0x0000005e,0x6d757377,0x00000000,0x00030005,0x00000060,
|
||||
0x00007964,0x00030005,0x0000006a,0x00007864,0x00030005,0x00000072,0x00000069,0x00030005,
|
||||
0x00000078,0x00000074,0x00030005,0x00000081,0x00000077,0x00040005,0x00000082,0x61726170,
|
||||
0x0000006d,0x00040005,0x00000088,0x61726170,0x0000006d,0x00030005,0x00000093,0x00006969,
|
||||
0x00050005,0x000000ab,0x4374756f,0x726f6c6f,0x00000000,0x00030047,0x00000033,0x00000002,
|
||||
0x00050048,0x00000033,0x00000000,0x00000023,0x00000000,0x00050048,0x00000033,0x00000001,
|
||||
0x00000023,0x00000010,0x00050048,0x00000033,0x00000002,0x00000023,0x00000018,0x00040047,
|
||||
0x00000046,0x0000001e,0x00000000,0x00040047,0x00000055,0x00000021,0x00000000,0x00040047,
|
||||
0x00000055,0x00000022,0x00000000,0x00040047,0x000000ab,0x0000001e,0x00000000,0x00020013,
|
||||
0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040020,
|
||||
0x00000007,0x00000007,0x00000006,0x00040021,0x00000008,0x00000006,0x00000007,0x0004002b,
|
||||
0x00000006,0x0000000f,0x3727c5ac,0x00020014,0x00000010,0x0004002b,0x00000006,0x00000014,
|
||||
0x3f800000,0x0004002b,0x00000006,0x00000017,0x40000000,0x0004002b,0x00000006,0x0000001b,
|
||||
0x00000000,0x0004002b,0x00000006,0x0000001e,0x40490fdb,0x0004002b,0x00000006,0x00000025,
|
||||
0x3f000000,0x00040017,0x0000002f,0x00000006,0x00000002,0x00040020,0x00000030,0x00000007,
|
||||
0x0000002f,0x00040017,0x00000032,0x00000006,0x00000004,0x0005001e,0x00000033,0x00000032,
|
||||
0x0000002f,0x0000002f,0x00040020,0x00000034,0x00000009,0x00000033,0x0004003b,0x00000034,
|
||||
0x00000035,0x00000009,0x00040015,0x00000036,0x00000020,0x00000001,0x0004002b,0x00000036,
|
||||
0x00000037,0x00000001,0x00040020,0x00000038,0x00000009,0x0000002f,0x0004002b,0x00000036,
|
||||
0x0000003b,0x00000002,0x0005002c,0x0000002f,0x0000003f,0x00000014,0x00000014,0x00040020,
|
||||
0x00000045,0x00000001,0x0000002f,0x0004003b,0x00000045,0x00000046,0x00000001,0x00040017,
|
||||
0x0000004b,0x00000036,0x00000002,0x00040020,0x0000004c,0x00000007,0x0000004b,0x00090019,
|
||||
0x00000052,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,0x00000001,0x00000000,
|
||||
0x0003001b,0x00000053,0x00000052,0x00040020,0x00000054,0x00000000,0x00000053,0x0004003b,
|
||||
0x00000054,0x00000055,0x00000000,0x0004002b,0x00000036,0x00000057,0x00000000,0x00040017,
|
||||
0x0000005a,0x00000006,0x00000003,0x00040020,0x0000005b,0x00000007,0x0000005a,0x0006002c,
|
||||
0x0000005a,0x0000005d,0x0000001b,0x0000001b,0x0000001b,0x00040020,0x0000005f,0x00000007,
|
||||
0x00000036,0x0004002b,0x00000036,0x00000061,0xfffffffc,0x0004002b,0x00000036,0x00000068,
|
||||
0x00000004,0x0005002c,0x0000002f,0x0000007b,0x00000025,0x00000025,0x00040015,0x00000083,
|
||||
0x00000020,0x00000000,0x0004002b,0x00000083,0x00000084,0x00000000,0x0004002b,0x00000083,
|
||||
0x00000089,0x00000001,0x0005002c,0x0000004b,0x00000095,0x00000057,0x00000057,0x0005002c,
|
||||
0x0000004b,0x00000097,0x00000037,0x00000037,0x00040020,0x000000aa,0x00000003,0x00000032,
|
||||
0x0004003b,0x000000aa,0x000000ab,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,
|
||||
0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000030,0x00000031,0x00000007,0x0004003b,
|
||||
0x00000030,0x00000041,0x00000007,0x0004003b,0x00000030,0x00000044,0x00000007,0x0004003b,
|
||||
0x0000004c,0x0000004d,0x00000007,0x0004003b,0x0000004c,0x00000051,0x00000007,0x0004003b,
|
||||
0x0000005b,0x0000005c,0x00000007,0x0004003b,0x00000007,0x0000005e,0x00000007,0x0004003b,
|
||||
0x0000005f,0x00000060,0x00000007,0x0004003b,0x0000005f,0x0000006a,0x00000007,0x0004003b,
|
||||
0x0000004c,0x00000072,0x00000007,0x0004003b,0x00000030,0x00000078,0x00000007,0x0004003b,
|
||||
0x00000007,0x00000081,0x00000007,0x0004003b,0x00000007,0x00000082,0x00000007,0x0004003b,
|
||||
0x00000007,0x00000088,0x00000007,0x0004003b,0x0000004c,0x00000093,0x00000007,0x00050041,
|
||||
0x00000038,0x00000039,0x00000035,0x00000037,0x0004003d,0x0000002f,0x0000003a,0x00000039,
|
||||
0x00050041,0x00000038,0x0000003c,0x00000035,0x0000003b,0x0004003d,0x0000002f,0x0000003d,
|
||||
0x0000003c,0x00050088,0x0000002f,0x0000003e,0x0000003a,0x0000003d,0x0007000c,0x0000002f,
|
||||
0x00000040,0x00000001,0x00000028,0x0000003e,0x0000003f,0x0003003e,0x00000031,0x00000040,
|
||||
0x0004003d,0x0000002f,0x00000042,0x00000031,0x00050088,0x0000002f,0x00000043,0x0000003f,
|
||||
0x00000042,0x0003003e,0x00000041,0x00000043,0x0004003d,0x0000002f,0x00000047,0x00000046,
|
||||
0x00050041,0x00000038,0x00000048,0x00000035,0x00000037,0x0004003d,0x0000002f,0x00000049,
|
||||
0x00000048,0x00050085,0x0000002f,0x0000004a,0x00000047,0x00000049,0x0003003e,0x00000044,
|
||||
0x0000004a,0x0004003d,0x0000002f,0x0000004e,0x00000044,0x0006000c,0x0000002f,0x0000004f,
|
||||
0x00000001,0x00000008,0x0000004e,0x0004006e,0x0000004b,0x00000050,0x0000004f,0x0003003e,
|
||||
0x0000004d,0x00000050,0x0004003d,0x00000053,0x00000056,0x00000055,0x00040064,0x00000052,
|
||||
0x00000058,0x00000056,0x00050067,0x0000004b,0x00000059,0x00000058,0x00000057,0x0003003e,
|
||||
0x00000051,0x00000059,0x0003003e,0x0000005c,0x0000005d,0x0003003e,0x0000005e,0x0000001b,
|
||||
0x0003003e,0x00000060,0x00000061,0x000200f9,0x00000062,0x000200f8,0x00000062,0x000400f6,
|
||||
0x00000064,0x00000065,0x00000000,0x000200f9,0x00000066,0x000200f8,0x00000066,0x0004003d,
|
||||
0x00000036,0x00000067,0x00000060,0x000500b3,0x00000010,0x00000069,0x00000067,0x00000068,
|
||||
0x000400fa,0x00000069,0x00000063,0x00000064,0x000200f8,0x00000063,0x0003003e,0x0000006a,
|
||||
0x00000061,0x000200f9,0x0000006b,0x000200f8,0x0000006b,0x000400f6,0x0000006d,0x0000006e,
|
||||
0x00000000,0x000200f9,0x0000006f,0x000200f8,0x0000006f,0x0004003d,0x00000036,0x00000070,
|
||||
0x0000006a,0x000500b3,0x00000010,0x00000071,0x00000070,0x00000068,0x000400fa,0x00000071,
|
||||
0x0000006c,0x0000006d,0x000200f8,0x0000006c,0x0004003d,0x0000004b,0x00000073,0x0000004d,
|
||||
0x0004003d,0x00000036,0x00000074,0x0000006a,0x0004003d,0x00000036,0x00000075,0x00000060,
|
||||
0x00050050,0x0000004b,0x00000076,0x00000074,0x00000075,0x00050080,0x0000004b,0x00000077,
|
||||
0x00000073,0x00000076,0x0003003e,0x00000072,0x00000077,0x0004003d,0x0000004b,0x00000079,
|
||||
0x00000072,0x0004006f,0x0000002f,0x0000007a,0x00000079,0x00050081,0x0000002f,0x0000007c,
|
||||
0x0000007a,0x0000007b,0x0004003d,0x0000002f,0x0000007d,0x00000044,0x00050083,0x0000002f,
|
||||
0x0000007e,0x0000007c,0x0000007d,0x0004003d,0x0000002f,0x0000007f,0x00000041,0x00050085,
|
||||
0x0000002f,0x00000080,0x0000007e,0x0000007f,0x0003003e,0x00000078,0x00000080,0x00050041,
|
||||
0x00000007,0x00000085,0x00000078,0x00000084,0x0004003d,0x00000006,0x00000086,0x00000085,
|
||||
0x0003003e,0x00000082,0x00000086,0x00050039,0x00000006,0x00000087,0x0000000a,0x00000082,
|
||||
0x00050041,0x00000007,0x0000008a,0x00000078,0x00000089,0x0004003d,0x00000006,0x0000008b,
|
||||
0x0000008a,0x0003003e,0x00000088,0x0000008b,0x00050039,0x00000006,0x0000008c,0x0000000a,
|
||||
0x00000088,0x00050085,0x00000006,0x0000008d,0x00000087,0x0000008c,0x0003003e,0x00000081,
|
||||
0x0000008d,0x0004003d,0x00000006,0x0000008e,0x00000081,0x000500b4,0x00000010,0x0000008f,
|
||||
0x0000008e,0x0000001b,0x000300f7,0x00000091,0x00000000,0x000400fa,0x0000008f,0x00000090,
|
||||
0x00000091,0x000200f8,0x00000090,0x000200f9,0x0000006e,0x000200f8,0x00000091,0x0004003d,
|
||||
0x0000004b,0x00000094,0x00000072,0x0004003d,0x0000004b,0x00000096,0x00000051,0x00050082,
|
||||
0x0000004b,0x00000098,0x00000096,0x00000097,0x0008000c,0x0000004b,0x00000099,0x00000001,
|
||||
0x0000002d,0x00000094,0x00000095,0x00000098,0x0003003e,0x00000093,0x00000099,0x0004003d,
|
||||
0x00000053,0x0000009a,0x00000055,0x0004003d,0x0000004b,0x0000009b,0x00000093,0x00040064,
|
||||
0x00000052,0x0000009c,0x0000009a,0x0007005f,0x00000032,0x0000009d,0x0000009c,0x0000009b,
|
||||
0x00000002,0x00000057,0x0008004f,0x0000005a,0x0000009e,0x0000009d,0x0000009d,0x00000000,
|
||||
0x00000001,0x00000002,0x0004003d,0x00000006,0x0000009f,0x00000081,0x0005008e,0x0000005a,
|
||||
0x000000a0,0x0000009e,0x0000009f,0x0004003d,0x0000005a,0x000000a1,0x0000005c,0x00050081,
|
||||
0x0000005a,0x000000a2,0x000000a1,0x000000a0,0x0003003e,0x0000005c,0x000000a2,0x0004003d,
|
||||
0x00000006,0x000000a3,0x00000081,0x0004003d,0x00000006,0x000000a4,0x0000005e,0x00050081,
|
||||
0x00000006,0x000000a5,0x000000a4,0x000000a3,0x0003003e,0x0000005e,0x000000a5,0x000200f9,
|
||||
0x0000006e,0x000200f8,0x0000006e,0x0004003d,0x00000036,0x000000a6,0x0000006a,0x00050080,
|
||||
0x00000036,0x000000a7,0x000000a6,0x00000037,0x0003003e,0x0000006a,0x000000a7,0x000200f9,
|
||||
0x0000006b,0x000200f8,0x0000006d,0x000200f9,0x00000065,0x000200f8,0x00000065,0x0004003d,
|
||||
0x00000036,0x000000a8,0x00000060,0x00050080,0x00000036,0x000000a9,0x000000a8,0x00000037,
|
||||
0x0003003e,0x00000060,0x000000a9,0x000200f9,0x00000062,0x000200f8,0x00000064,0x0004003d,
|
||||
0x0000005a,0x000000ac,0x0000005c,0x0004003d,0x00000006,0x000000ad,0x0000005e,0x0007000c,
|
||||
0x00000006,0x000000ae,0x00000001,0x00000028,0x000000ad,0x0000000f,0x00060050,0x0000005a,
|
||||
0x000000af,0x000000ae,0x000000ae,0x000000ae,0x00050088,0x0000005a,0x000000b0,0x000000ac,
|
||||
0x000000af,0x00050051,0x00000006,0x000000b1,0x000000b0,0x00000000,0x00050051,0x00000006,
|
||||
0x000000b2,0x000000b0,0x00000001,0x00050051,0x00000006,0x000000b3,0x000000b0,0x00000002,
|
||||
0x00070050,0x00000032,0x000000b4,0x000000b1,0x000000b2,0x000000b3,0x00000014,0x0003003e,
|
||||
0x000000ab,0x000000b4,0x000100fd,0x00010038,0x00050036,0x00000006,0x0000000a,0x00000000,
|
||||
0x00000008,0x00030037,0x00000007,0x00000009,0x000200f8,0x0000000b,0x0004003b,0x00000007,
|
||||
0x0000001d,0x00000007,0x0004003d,0x00000006,0x0000000c,0x00000009,0x0006000c,0x00000006,
|
||||
0x0000000d,0x00000001,0x00000004,0x0000000c,0x0003003e,0x00000009,0x0000000d,0x0004003d,
|
||||
0x00000006,0x0000000e,0x00000009,0x000500b8,0x00000010,0x00000011,0x0000000e,0x0000000f,
|
||||
0x000300f7,0x00000013,0x00000000,0x000400fa,0x00000011,0x00000012,0x00000013,0x000200f8,
|
||||
0x00000012,0x000200fe,0x00000014,0x000200f8,0x00000013,0x0004003d,0x00000006,0x00000016,
|
||||
0x00000009,0x000500be,0x00000010,0x00000018,0x00000016,0x00000017,0x000300f7,0x0000001a,
|
||||
0x00000000,0x000400fa,0x00000018,0x00000019,0x0000001a,0x000200f8,0x00000019,0x000200fe,
|
||||
0x0000001b,0x000200f8,0x0000001a,0x0004003d,0x00000006,0x0000001f,0x00000009,0x00050085,
|
||||
0x00000006,0x00000020,0x0000001e,0x0000001f,0x0003003e,0x0000001d,0x00000020,0x0004003d,
|
||||
0x00000006,0x00000021,0x0000001d,0x0006000c,0x00000006,0x00000022,0x00000001,0x0000000d,
|
||||
0x00000021,0x00050085,0x00000006,0x00000023,0x00000017,0x00000022,0x0004003d,0x00000006,
|
||||
0x00000024,0x0000001d,0x00050085,0x00000006,0x00000026,0x00000024,0x00000025,0x0006000c,
|
||||
0x00000006,0x00000027,0x00000001,0x0000000d,0x00000026,0x00050085,0x00000006,0x00000028,
|
||||
0x00000023,0x00000027,0x0004003d,0x00000006,0x00000029,0x0000001d,0x0004003d,0x00000006,
|
||||
0x0000002a,0x0000001d,0x00050085,0x00000006,0x0000002b,0x00000029,0x0000002a,0x00050088,
|
||||
0x00000006,0x0000002c,0x00000028,0x0000002b,0x000200fe,0x0000002c,0x00010038
|
||||
};
|
||||
@@ -1,49 +0,0 @@
|
||||
// 1116.3.0
|
||||
#pragma once
|
||||
const uint32_t window_frag_code[] = {
|
||||
0x07230203,0x00010000,0x0008000b,0x00000033,0x00000000,0x00020011,0x00000001,0x0006000b,
|
||||
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
|
||||
0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000011,0x00000015,0x00030010,
|
||||
0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
|
||||
0x00000000,0x00030005,0x00000009,0x00000063,0x00050005,0x0000000d,0x53786574,0x6c706d61,
|
||||
0x00007265,0x00060005,0x00000011,0x67617266,0x43786554,0x64726f6f,0x00000000,0x00050005,
|
||||
0x00000015,0x4374756f,0x726f6c6f,0x00000000,0x00030005,0x0000001a,0x00004350,0x00050006,
|
||||
0x0000001a,0x00000000,0x5863646e,0x00000030,0x00050006,0x0000001a,0x00000001,0x5963646e,
|
||||
0x00000030,0x00050006,0x0000001a,0x00000002,0x5863646e,0x00000031,0x00050006,0x0000001a,
|
||||
0x00000003,0x5963646e,0x00000031,0x00060006,0x0000001a,0x00000004,0x54657375,0x6c417865,
|
||||
0x00616870,0x00030005,0x0000001c,0x00006370,0x00040047,0x0000000d,0x00000021,0x00000000,
|
||||
0x00040047,0x0000000d,0x00000022,0x00000000,0x00040047,0x00000011,0x0000001e,0x00000000,
|
||||
0x00040047,0x00000015,0x0000001e,0x00000000,0x00030047,0x0000001a,0x00000002,0x00050048,
|
||||
0x0000001a,0x00000000,0x00000023,0x00000000,0x00050048,0x0000001a,0x00000001,0x00000023,
|
||||
0x00000004,0x00050048,0x0000001a,0x00000002,0x00000023,0x00000008,0x00050048,0x0000001a,
|
||||
0x00000003,0x00000023,0x0000000c,0x00050048,0x0000001a,0x00000004,0x00000023,0x00000010,
|
||||
0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,
|
||||
0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000007,0x00000007,
|
||||
0x00090019,0x0000000a,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,0x00000001,
|
||||
0x00000000,0x0003001b,0x0000000b,0x0000000a,0x00040020,0x0000000c,0x00000000,0x0000000b,
|
||||
0x0004003b,0x0000000c,0x0000000d,0x00000000,0x00040017,0x0000000f,0x00000006,0x00000002,
|
||||
0x00040020,0x00000010,0x00000001,0x0000000f,0x0004003b,0x00000010,0x00000011,0x00000001,
|
||||
0x00040020,0x00000014,0x00000003,0x00000007,0x0004003b,0x00000014,0x00000015,0x00000003,
|
||||
0x00040017,0x00000016,0x00000006,0x00000003,0x00040015,0x00000019,0x00000020,0x00000001,
|
||||
0x0007001e,0x0000001a,0x00000006,0x00000006,0x00000006,0x00000006,0x00000019,0x00040020,
|
||||
0x0000001b,0x00000009,0x0000001a,0x0004003b,0x0000001b,0x0000001c,0x00000009,0x0004002b,
|
||||
0x00000019,0x0000001d,0x00000004,0x00040020,0x0000001e,0x00000009,0x00000019,0x0004002b,
|
||||
0x00000019,0x00000021,0x00000000,0x00020014,0x00000022,0x00040020,0x00000024,0x00000007,
|
||||
0x00000006,0x00040015,0x00000028,0x00000020,0x00000000,0x0004002b,0x00000028,0x00000029,
|
||||
0x00000003,0x0004002b,0x00000006,0x0000002d,0x3f800000,0x00050036,0x00000002,0x00000004,
|
||||
0x00000000,0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000008,0x00000009,0x00000007,
|
||||
0x0004003b,0x00000024,0x00000025,0x00000007,0x0004003d,0x0000000b,0x0000000e,0x0000000d,
|
||||
0x0004003d,0x0000000f,0x00000012,0x00000011,0x00050057,0x00000007,0x00000013,0x0000000e,
|
||||
0x00000012,0x0003003e,0x00000009,0x00000013,0x0004003d,0x00000007,0x00000017,0x00000009,
|
||||
0x0008004f,0x00000016,0x00000018,0x00000017,0x00000017,0x00000000,0x00000001,0x00000002,
|
||||
0x00050041,0x0000001e,0x0000001f,0x0000001c,0x0000001d,0x0004003d,0x00000019,0x00000020,
|
||||
0x0000001f,0x000500ab,0x00000022,0x00000023,0x00000020,0x00000021,0x000300f7,0x00000027,
|
||||
0x00000000,0x000400fa,0x00000023,0x00000026,0x0000002c,0x000200f8,0x00000026,0x00050041,
|
||||
0x00000024,0x0000002a,0x00000009,0x00000029,0x0004003d,0x00000006,0x0000002b,0x0000002a,
|
||||
0x0003003e,0x00000025,0x0000002b,0x000200f9,0x00000027,0x000200f8,0x0000002c,0x0003003e,
|
||||
0x00000025,0x0000002d,0x000200f9,0x00000027,0x000200f8,0x00000027,0x0004003d,0x00000006,
|
||||
0x0000002e,0x00000025,0x00050051,0x00000006,0x0000002f,0x00000018,0x00000000,0x00050051,
|
||||
0x00000006,0x00000030,0x00000018,0x00000001,0x00050051,0x00000006,0x00000031,0x00000018,
|
||||
0x00000002,0x00070050,0x00000007,0x00000032,0x0000002f,0x00000030,0x00000031,0x0000002e,
|
||||
0x0003003e,0x00000015,0x00000032,0x000100fd,0x00010038
|
||||
};
|
||||
@@ -1,68 +0,0 @@
|
||||
// 1116.3.0
|
||||
#pragma once
|
||||
const uint32_t window_vert_code[] = {
|
||||
0x07230203,0x00010000,0x0008000b,0x0000004a,0x00000000,0x00020011,0x00000001,0x0006000b,
|
||||
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
|
||||
0x0008000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000a,0x0000003a,0x00000044,
|
||||
0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,0x00000000,0x00030005,
|
||||
0x00000008,0x00006978,0x00060005,0x0000000a,0x565f6c67,0x65747265,0x646e4978,0x00007865,
|
||||
0x00030005,0x0000000f,0x00006979,0x00030005,0x00000014,0x00000078,0x00030005,0x0000001b,
|
||||
0x00004350,0x00050006,0x0000001b,0x00000000,0x5863646e,0x00000030,0x00050006,0x0000001b,
|
||||
0x00000001,0x5963646e,0x00000030,0x00050006,0x0000001b,0x00000002,0x5863646e,0x00000031,
|
||||
0x00050006,0x0000001b,0x00000003,0x5963646e,0x00000031,0x00030005,0x0000001d,0x00006370,
|
||||
0x00030005,0x00000027,0x00000079,0x00060005,0x00000038,0x505f6c67,0x65567265,0x78657472,
|
||||
0x00000000,0x00060006,0x00000038,0x00000000,0x505f6c67,0x7469736f,0x006e6f69,0x00070006,
|
||||
0x00000038,0x00000001,0x505f6c67,0x746e696f,0x657a6953,0x00000000,0x00070006,0x00000038,
|
||||
0x00000002,0x435f6c67,0x4470696c,0x61747369,0x0065636e,0x00070006,0x00000038,0x00000003,
|
||||
0x435f6c67,0x446c6c75,0x61747369,0x0065636e,0x00030005,0x0000003a,0x00000000,0x00060005,
|
||||
0x00000044,0x67617266,0x43786554,0x64726f6f,0x00000000,0x00040047,0x0000000a,0x0000000b,
|
||||
0x0000002a,0x00030047,0x0000001b,0x00000002,0x00050048,0x0000001b,0x00000000,0x00000023,
|
||||
0x00000000,0x00050048,0x0000001b,0x00000001,0x00000023,0x00000004,0x00050048,0x0000001b,
|
||||
0x00000002,0x00000023,0x00000008,0x00050048,0x0000001b,0x00000003,0x00000023,0x0000000c,
|
||||
0x00030047,0x00000038,0x00000002,0x00050048,0x00000038,0x00000000,0x0000000b,0x00000000,
|
||||
0x00050048,0x00000038,0x00000001,0x0000000b,0x00000001,0x00050048,0x00000038,0x00000002,
|
||||
0x0000000b,0x00000003,0x00050048,0x00000038,0x00000003,0x0000000b,0x00000004,0x00040047,
|
||||
0x00000044,0x0000001e,0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,
|
||||
0x00040015,0x00000006,0x00000020,0x00000001,0x00040020,0x00000007,0x00000007,0x00000006,
|
||||
0x00040020,0x00000009,0x00000001,0x00000006,0x0004003b,0x00000009,0x0000000a,0x00000001,
|
||||
0x0004002b,0x00000006,0x0000000c,0x00000001,0x00030016,0x00000012,0x00000020,0x00040020,
|
||||
0x00000013,0x00000007,0x00000012,0x00020014,0x00000016,0x0006001e,0x0000001b,0x00000012,
|
||||
0x00000012,0x00000012,0x00000012,0x00040020,0x0000001c,0x00000009,0x0000001b,0x0004003b,
|
||||
0x0000001c,0x0000001d,0x00000009,0x0004002b,0x00000006,0x0000001e,0x00000002,0x00040020,
|
||||
0x0000001f,0x00000009,0x00000012,0x0004002b,0x00000006,0x00000023,0x00000000,0x0004002b,
|
||||
0x00000006,0x0000002d,0x00000003,0x00040017,0x00000034,0x00000012,0x00000004,0x00040015,
|
||||
0x00000035,0x00000020,0x00000000,0x0004002b,0x00000035,0x00000036,0x00000001,0x0004001c,
|
||||
0x00000037,0x00000012,0x00000036,0x0006001e,0x00000038,0x00000034,0x00000012,0x00000037,
|
||||
0x00000037,0x00040020,0x00000039,0x00000003,0x00000038,0x0004003b,0x00000039,0x0000003a,
|
||||
0x00000003,0x0004002b,0x00000012,0x0000003d,0x00000000,0x0004002b,0x00000012,0x0000003e,
|
||||
0x3f800000,0x00040020,0x00000040,0x00000003,0x00000034,0x00040017,0x00000042,0x00000012,
|
||||
0x00000002,0x00040020,0x00000043,0x00000003,0x00000042,0x0004003b,0x00000043,0x00000044,
|
||||
0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,
|
||||
0x0004003b,0x00000007,0x00000008,0x00000007,0x0004003b,0x00000007,0x0000000f,0x00000007,
|
||||
0x0004003b,0x00000013,0x00000014,0x00000007,0x0004003b,0x00000013,0x00000018,0x00000007,
|
||||
0x0004003b,0x00000013,0x00000027,0x00000007,0x0004003b,0x00000013,0x0000002a,0x00000007,
|
||||
0x0004003d,0x00000006,0x0000000b,0x0000000a,0x000500c3,0x00000006,0x0000000d,0x0000000b,
|
||||
0x0000000c,0x000500c7,0x00000006,0x0000000e,0x0000000d,0x0000000c,0x0003003e,0x00000008,
|
||||
0x0000000e,0x0004003d,0x00000006,0x00000010,0x0000000a,0x000500c7,0x00000006,0x00000011,
|
||||
0x00000010,0x0000000c,0x0003003e,0x0000000f,0x00000011,0x0004003d,0x00000006,0x00000015,
|
||||
0x00000008,0x000500aa,0x00000016,0x00000017,0x00000015,0x0000000c,0x000300f7,0x0000001a,
|
||||
0x00000000,0x000400fa,0x00000017,0x00000019,0x00000022,0x000200f8,0x00000019,0x00050041,
|
||||
0x0000001f,0x00000020,0x0000001d,0x0000001e,0x0004003d,0x00000012,0x00000021,0x00000020,
|
||||
0x0003003e,0x00000018,0x00000021,0x000200f9,0x0000001a,0x000200f8,0x00000022,0x00050041,
|
||||
0x0000001f,0x00000024,0x0000001d,0x00000023,0x0004003d,0x00000012,0x00000025,0x00000024,
|
||||
0x0003003e,0x00000018,0x00000025,0x000200f9,0x0000001a,0x000200f8,0x0000001a,0x0004003d,
|
||||
0x00000012,0x00000026,0x00000018,0x0003003e,0x00000014,0x00000026,0x0004003d,0x00000006,
|
||||
0x00000028,0x0000000f,0x000500aa,0x00000016,0x00000029,0x00000028,0x0000000c,0x000300f7,
|
||||
0x0000002c,0x00000000,0x000400fa,0x00000029,0x0000002b,0x00000030,0x000200f8,0x0000002b,
|
||||
0x00050041,0x0000001f,0x0000002e,0x0000001d,0x0000002d,0x0004003d,0x00000012,0x0000002f,
|
||||
0x0000002e,0x0003003e,0x0000002a,0x0000002f,0x000200f9,0x0000002c,0x000200f8,0x00000030,
|
||||
0x00050041,0x0000001f,0x00000031,0x0000001d,0x0000000c,0x0004003d,0x00000012,0x00000032,
|
||||
0x00000031,0x0003003e,0x0000002a,0x00000032,0x000200f9,0x0000002c,0x000200f8,0x0000002c,
|
||||
0x0004003d,0x00000012,0x00000033,0x0000002a,0x0003003e,0x00000027,0x00000033,0x0004003d,
|
||||
0x00000012,0x0000003b,0x00000014,0x0004003d,0x00000012,0x0000003c,0x00000027,0x00070050,
|
||||
0x00000034,0x0000003f,0x0000003b,0x0000003c,0x0000003d,0x0000003e,0x00050041,0x00000040,
|
||||
0x00000041,0x0000003a,0x00000023,0x0003003e,0x00000041,0x0000003f,0x0004003d,0x00000006,
|
||||
0x00000045,0x00000008,0x0004006f,0x00000012,0x00000046,0x00000045,0x0004003d,0x00000006,
|
||||
0x00000047,0x0000000f,0x0004006f,0x00000012,0x00000048,0x00000047,0x00050050,0x00000042,
|
||||
0x00000049,0x00000046,0x00000048,0x0003003e,0x00000044,0x00000049,0x000100fd,0x00010038
|
||||
};
|
||||
@@ -226,7 +226,7 @@ static void on_client_created(struct wl_listener *l, void *data) {
|
||||
|
||||
/* ------------------------------------------------------------------ surfaces */
|
||||
|
||||
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP };
|
||||
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP, ROLE_CURSOR };
|
||||
|
||||
struct surface {
|
||||
struct wl_resource *resource;
|
||||
@@ -275,6 +275,7 @@ struct surface {
|
||||
int sub_x, sub_y, sub_pending_x, sub_pending_y, sub_pending;
|
||||
int below_parent;
|
||||
int fullscreen; /* xdg_toplevel.set_fullscreen: no client decorations */
|
||||
int toplevel_committed; /* the toplevel's initial commit was answered */
|
||||
|
||||
char *title; /* xdg_toplevel title, for the session log */
|
||||
int announced_vulkan; /* logged its first dmabuf frame */
|
||||
@@ -464,17 +465,86 @@ static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_
|
||||
/* Each Wine process is a separate client with its own wl_pointer / wl_keyboard. */
|
||||
struct seat_pointer { struct wl_resource *ptr; struct wl_resource *focus; };
|
||||
struct seat_keyboard { struct wl_resource *kb; struct wl_resource *focus; };
|
||||
struct seat_touch { struct wl_resource *touch; struct wl_resource *focus; };
|
||||
#define MAX_PTRS 32
|
||||
#define MAX_TOUCH_POINTS 32
|
||||
static struct seat_pointer g_ptrs[MAX_PTRS];
|
||||
static int g_nptrs;
|
||||
static struct seat_keyboard g_kbs[MAX_PTRS];
|
||||
static int g_nkbs;
|
||||
static struct seat_touch g_touches[MAX_PTRS];
|
||||
static int g_ntouches;
|
||||
|
||||
/* ---- the client's cursor (wl_pointer.set_cursor) -------------------------------------------
|
||||
* Not composited: under zero-copy the program's buffer goes straight to an Android layer and there
|
||||
* is nothing to composite into. The cursor surface is snapshotted here instead and the app draws it
|
||||
* as its overlay, above every present path (Bannerlator's design). What it buys: the real SHAPE -
|
||||
* labwc's resize arrows at a window's edges and corners, a text field's I-beam - and an
|
||||
* authoritative HIDE (set_cursor with a NULL surface, what a mouse-look game does).
|
||||
* wl_shm cursors (Wine, pixman) are copied directly; a GPU cursor (labwc on Vulkan/GLES, which
|
||||
* wlroots hands over as a dma-buf, usually UBWC) is read back through vkp_image_readback. */
|
||||
#define CURSOR_MAX_PX (256 * 256)
|
||||
static pthread_mutex_t g_cursor_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct surface *g_cursor_surface; /* compositor thread only */
|
||||
static int g_cursor_hx, g_cursor_hy; /* hotspot, surface-local */
|
||||
static uint32_t g_cursor_px[CURSOR_MAX_PX]; /* guarded by g_cursor_lock: ARGB8888 snapshot */
|
||||
static uint32_t g_cursor_rb[CURSOR_MAX_PX]; /* compositor thread: GPU readback staging */
|
||||
static int g_cursor_w, g_cursor_h; /* 0 = nothing to draw */
|
||||
static int g_cursor_hidden = 1; /* the client asked for no pointer */
|
||||
static int g_cursor_serial; /* bumped on every change; the app polls it */
|
||||
|
||||
static void cursor_publish_hidden(void) {
|
||||
pthread_mutex_lock(&g_cursor_lock);
|
||||
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
|
||||
pthread_mutex_unlock(&g_cursor_lock);
|
||||
}
|
||||
|
||||
static void cursor_publish_pixels(const uint8_t *src, int w, int h, size_t stride, int hx, int hy) {
|
||||
if (w <= 0 || h <= 0 || w * h > CURSOR_MAX_PX) return;
|
||||
pthread_mutex_lock(&g_cursor_lock);
|
||||
for (int y = 0; y < h; y++)
|
||||
memcpy(&g_cursor_px[y * w], src + (size_t)y * stride, (size_t)w * 4);
|
||||
g_cursor_w = w; g_cursor_h = h;
|
||||
g_cursor_hx = hx; g_cursor_hy = hy;
|
||||
g_cursor_hidden = 0;
|
||||
g_cursor_serial++;
|
||||
pthread_mutex_unlock(&g_cursor_lock);
|
||||
}
|
||||
|
||||
static void cursor_publish_shm(struct wl_shm_buffer *shm, int hx, int hy) {
|
||||
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
|
||||
if (w <= 0 || h <= 0 || w * h > CURSOR_MAX_PX) return;
|
||||
wl_shm_buffer_begin_access(shm);
|
||||
cursor_publish_pixels((const uint8_t *)wl_shm_buffer_get_data(shm), w, h,
|
||||
(size_t)wl_shm_buffer_get_stride(shm), hx, hy);
|
||||
wl_shm_buffer_end_access(shm);
|
||||
}
|
||||
|
||||
/* Read by the app (UI thread). out = [serial, hidden, w, h, hotspotX, hotspotY, pixels...].
|
||||
* Returns the number of ints written, or 0 if out is too small. */
|
||||
int banner_cursor_snapshot(int *out, int cap) {
|
||||
int n = 0;
|
||||
pthread_mutex_lock(&g_cursor_lock);
|
||||
int need = 6 + (g_cursor_hidden ? 0 : g_cursor_w * g_cursor_h);
|
||||
if (cap >= need) {
|
||||
out[0] = g_cursor_serial; out[1] = g_cursor_hidden;
|
||||
out[2] = g_cursor_w; out[3] = g_cursor_h;
|
||||
out[4] = g_cursor_hx; out[5] = g_cursor_hy;
|
||||
if (!g_cursor_hidden)
|
||||
memcpy(out + 6, g_cursor_px, (size_t)g_cursor_w * g_cursor_h * 4);
|
||||
n = need;
|
||||
}
|
||||
pthread_mutex_unlock(&g_cursor_lock);
|
||||
return n;
|
||||
}
|
||||
struct active_touch { struct surface *surface; int pointer_fallback; };
|
||||
static struct active_touch g_touch_points[MAX_TOUCH_POINTS];
|
||||
static void touch_cancel_surface(struct surface *surface);
|
||||
static struct surface *g_grab; /* no-desktop fallback: surface holding the button */
|
||||
static struct surface *g_key_target; /* no-desktop fallback: last clicked surface */
|
||||
static struct surface *g_ime_click; /* last clicked program window: where text input goes */
|
||||
static int g_input_pipe[2] = {-1, -1};
|
||||
/* type 0 = pointer (p1=action 0down/1move/2up, p2=x, p3=y); type 1 = key (p1=evdev, p2=state 1down/0up) */
|
||||
struct input_msg { int type; int p1; int p2; int p3; };
|
||||
struct input_msg { int type; int p1; int p2; int p3; int p4; };
|
||||
|
||||
/* Pointer constraints (zwp_pointer_constraints_v1) and relative pointers
|
||||
* (zwp_relative_pointer_manager_v1); see the "pointer constraints" section. */
|
||||
@@ -589,6 +659,10 @@ static void map_toplevel(struct surface *s) {
|
||||
s->placed ? "" : " (no desktop position yet)");
|
||||
}
|
||||
wl_list_insert(g_toplevels.prev, &s->toplevel_link); /* new windows start on top */
|
||||
/* Without a Wine desktop the clients are whole programs (the Linux desktop, a gamescope a
|
||||
* program on it started over it): a window that opens on top takes the keys too, as it would
|
||||
* on any desktop, rather than the one clicked last that is now underneath it. */
|
||||
if (!g_desktop) g_key_target = s;
|
||||
apply_zorder();
|
||||
}
|
||||
|
||||
@@ -675,9 +749,11 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
||||
if (ci && ci->asked_feedback) ci->shm_frames++; /* since it asked for GPU buffers */
|
||||
}
|
||||
|
||||
/* The window the app's performance HUD follows: the latest one to start presenting GPU frames
|
||||
* (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */
|
||||
/* The window the app's performance HUD follows: the latest one at least as big as the last to
|
||||
* start presenting GPU frames (take_dmabuf) (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */
|
||||
static struct surface *g_hud_surface;
|
||||
/* When the HUD's window last presented a frame (now_ns), to let a replacement take over. */
|
||||
static int64_t g_hud_last_ns;
|
||||
extern void banner_on_game_surface(const char *window, const char *gpu); /* window NULL = gone */
|
||||
extern void banner_on_game_frame(void);
|
||||
/* The program behind that window: its Linux pid (the Wayland client's credentials) and executable name
|
||||
@@ -720,6 +796,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
s->buf_h = b->height;
|
||||
s->has_content = b->img != NULL;
|
||||
g_stat_dmabuf++;
|
||||
const int announced_now = !s->announced_vulkan;
|
||||
if (!s->announced_vulkan) {
|
||||
char name[160];
|
||||
s->announced_vulkan = 1;
|
||||
@@ -740,14 +817,23 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
else
|
||||
banner_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)",
|
||||
name, b->width, b->height, (unsigned long long)b->modifier);
|
||||
/* The HUD follows the window whether its frames are copied or go straight to the layer:
|
||||
* a zero-copy frame the compositor never imported is still a presented game frame. */
|
||||
if (b->img || ahb_swapchain_has_ahb(b)) {
|
||||
g_hud_surface = s;
|
||||
banner_on_game_surface(name, vkp_gpu_name());
|
||||
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
||||
if (ci) banner_on_game_program((int)ci->pid, strncmp(ci->name, "pid ", 4) ? ci->name : "");
|
||||
}
|
||||
}
|
||||
/* The HUD follows the window whether its frames are copied or go straight to the layer: a
|
||||
* zero-copy frame the compositor never imported is still a presented game frame. A
|
||||
* program's small surfaces - gamescope's 1x1 cursor, Qt's menus and tooltips (melonDS) -
|
||||
* came after the game's and drew too rarely to count, which left the HUD on 0 fps while the
|
||||
* game ran at 60. So a new window takes the HUD only when it is at least as big (a
|
||||
* full-screen gamescope over the desktop still does), and a window gone quiet for a second
|
||||
* gives way to whatever draws next. */
|
||||
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
||||
(!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL ||
|
||||
(announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||
char name[160];
|
||||
describe(s, name, sizeof(name));
|
||||
g_hud_surface = s;
|
||||
banner_on_game_surface(name, vkp_gpu_name());
|
||||
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
||||
if (ci) banner_on_game_program((int)ci->pid, strncmp(ci->name, "pid ", 4) ? ci->name : "");
|
||||
}
|
||||
/* HDR session (gate open): a DXVK game switches to HDR by REBUILDING its swapchain on the same
|
||||
* surface, so the one-shot line above never sees the 10-bit buffers - name every format change. */
|
||||
@@ -769,7 +855,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
* Asking whether the compositor could import it, as this used to, is a question about the
|
||||
* copy path and not about whether a frame happened: a game whose buffers go straight to
|
||||
* the display layer draws on screen while the counter sat at 0.0 fps and 1000.0 ms. */
|
||||
if (s == g_hud_surface) banner_on_game_frame();
|
||||
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); banner_on_game_frame(); }
|
||||
}
|
||||
|
||||
/* ---- hooks for ahb_swapchain.c (zero-copy layers) */
|
||||
@@ -884,10 +970,21 @@ static void surface_set_opaque(struct wl_client *c, struct wl_resource *r,
|
||||
static void surface_set_input(struct wl_client *c, struct wl_resource *r,
|
||||
struct wl_resource *region) {}
|
||||
|
||||
static void send_toplevel_configure(struct surface *s);
|
||||
|
||||
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
struct surface *child;
|
||||
|
||||
/* xdg-shell: the initial commit of a toplevel is answered with a configure. One is also sent
|
||||
* at get_toplevel, which Wine's driver has always had; a client that waits for the reply to its
|
||||
* commit on a queue of its own (wlroots' Wayland backend - the desktop's labwc) can read that
|
||||
* early one onto the wrong queue and would wait for ever. */
|
||||
if (s->xdg_toplevel && !s->toplevel_committed) {
|
||||
s->toplevel_committed = 1;
|
||||
send_toplevel_configure(s);
|
||||
}
|
||||
|
||||
if (s->pending_src_set) {
|
||||
s->src_set = s->pending_src[2] > 0;
|
||||
memcpy(s->src, s->pending_src, sizeof(s->src));
|
||||
@@ -914,8 +1011,26 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
s->pending_buffer = NULL;
|
||||
s->pending_attach = 0;
|
||||
|
||||
if (s->role == ROLE_NONE) {
|
||||
/* Cursor or role-less surface: never drawn (the app draws its own pointer). */
|
||||
if (s->role == ROLE_CURSOR) {
|
||||
/* The client's pointer image, copied out for the app's overlay (see cursor_publish_*)
|
||||
* rather than composited, so it survives the zero-copy and HDR layer paths. */
|
||||
if (!buffer) {
|
||||
cursor_publish_hidden(); /* wlroots clears its cursor surface to hide the pointer */
|
||||
} else if (shm) {
|
||||
cursor_publish_shm(shm, g_cursor_hx, g_cursor_hy);
|
||||
} else if (db && db->n_planes >= 1 && db->width * db->height <= CURSOR_MAX_PX) {
|
||||
if (!db->img && !db->import_failed) {
|
||||
db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height,
|
||||
db->stride[0], db->offset[0]);
|
||||
if (!db->img) db->import_failed = 1;
|
||||
}
|
||||
if (db->img && vkp_image_readback(db->img, g_cursor_rb, CURSOR_MAX_PX) == 0)
|
||||
cursor_publish_pixels((const uint8_t *)g_cursor_rb, db->width, db->height,
|
||||
(size_t)db->width * 4, g_cursor_hx, g_cursor_hy);
|
||||
}
|
||||
if (buffer) wl_buffer_send_release(buffer);
|
||||
} else if (s->role == ROLE_NONE) {
|
||||
/* Role-less surface: never drawn. */
|
||||
if (buffer) wl_buffer_send_release(buffer);
|
||||
} else if (db) {
|
||||
take_dmabuf(s, db, buffer);
|
||||
@@ -986,6 +1101,8 @@ static void surface_resource_destroy(struct wl_resource *r) {
|
||||
if (!s) return;
|
||||
for (int i = 0; i < g_nptrs; i++) if (g_ptrs[i].focus == r) g_ptrs[i].focus = NULL;
|
||||
for (int i = 0; i < g_nkbs; i++) if (g_kbs[i].focus == r) g_kbs[i].focus = NULL;
|
||||
touch_cancel_surface(s);
|
||||
if (g_cursor_surface == s) { g_cursor_surface = NULL; cursor_publish_hidden(); }
|
||||
if (g_grab == s) g_grab = NULL;
|
||||
if (g_key_target == s) g_key_target = NULL;
|
||||
if (g_ime_click == s) g_ime_click = NULL;
|
||||
@@ -1298,6 +1415,7 @@ static void xdg_toplevel_resource_destroy(struct wl_resource *r) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
if (!s) return;
|
||||
s->xdg_toplevel = NULL;
|
||||
s->toplevel_committed = 0;
|
||||
unmap_toplevel(s);
|
||||
s->placed = 0;
|
||||
s->hwnd = 0;
|
||||
@@ -1315,8 +1433,23 @@ static void xdg_surface_get_toplevel(struct wl_client *c, struct wl_resource *r,
|
||||
s->xdg_toplevel = tl;
|
||||
send_toplevel_configure(s);
|
||||
}
|
||||
/* A popup is dismissed as soon as it is made (see the positioner below). */
|
||||
static void popup_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static void popup_grab(struct wl_client *c, struct wl_resource *r, struct wl_resource *seat, uint32_t serial) {}
|
||||
static void popup_reposition(struct wl_client *c, struct wl_resource *r, struct wl_resource *positioner,
|
||||
uint32_t token) {}
|
||||
static const struct xdg_popup_interface popup_impl = {
|
||||
.destroy = popup_destroy,
|
||||
.grab = popup_grab,
|
||||
.reposition = popup_reposition,
|
||||
};
|
||||
static void xdg_surface_get_popup(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
||||
struct wl_resource *parent, struct wl_resource *positioner) {}
|
||||
struct wl_resource *parent, struct wl_resource *positioner) {
|
||||
struct wl_resource *p = wl_resource_create(c, &xdg_popup_interface, wl_resource_get_version(r), id);
|
||||
if (!p) { wl_client_post_no_memory(c); return; }
|
||||
wl_resource_set_implementation(p, &popup_impl, NULL, NULL);
|
||||
xdg_popup_send_popup_done(p);
|
||||
}
|
||||
static void xdg_surface_set_geometry(struct wl_client *c, struct wl_resource *r,
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {}
|
||||
static void xdg_surface_ack_configure(struct wl_client *c, struct wl_resource *r, uint32_t serial) {}
|
||||
@@ -1333,9 +1466,40 @@ static void xdg_surface_resource_destroy(struct wl_resource *r) {
|
||||
}
|
||||
|
||||
static void xdg_wm_base_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
|
||||
/* Popups are not drawn here, but their requests must still land somewhere: a resource without an
|
||||
* implementation makes libwayland abort on the first request to it - the whole compositor, and the
|
||||
* app with it. A positioner takes every request and keeps nothing; a popup is dismissed at once
|
||||
* (popup_done), which is what a client does with a popup it cannot show. Seen with a gamescope
|
||||
* started from the Linux desktop beside labwc. */
|
||||
static void positioner_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static void positioner_set_size(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h) {}
|
||||
static void positioner_set_anchor_rect(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y,
|
||||
int32_t w, int32_t h) {}
|
||||
static void positioner_set_anchor(struct wl_client *c, struct wl_resource *r, uint32_t a) {}
|
||||
static void positioner_set_gravity(struct wl_client *c, struct wl_resource *r, uint32_t g) {}
|
||||
static void positioner_set_constraint_adjustment(struct wl_client *c, struct wl_resource *r, uint32_t a) {}
|
||||
static void positioner_set_offset(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y) {}
|
||||
static void positioner_set_reactive(struct wl_client *c, struct wl_resource *r) {}
|
||||
static void positioner_set_parent_size(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h) {}
|
||||
static void positioner_set_parent_configure(struct wl_client *c, struct wl_resource *r, uint32_t serial) {}
|
||||
static const struct xdg_positioner_interface positioner_impl = {
|
||||
.destroy = positioner_destroy,
|
||||
.set_size = positioner_set_size,
|
||||
.set_anchor_rect = positioner_set_anchor_rect,
|
||||
.set_anchor = positioner_set_anchor,
|
||||
.set_gravity = positioner_set_gravity,
|
||||
.set_constraint_adjustment = positioner_set_constraint_adjustment,
|
||||
.set_offset = positioner_set_offset,
|
||||
.set_reactive = positioner_set_reactive,
|
||||
.set_parent_size = positioner_set_parent_size,
|
||||
.set_parent_configure = positioner_set_parent_configure,
|
||||
};
|
||||
|
||||
static void xdg_wm_base_create_positioner(struct wl_client *c, struct wl_resource *r, uint32_t id) {
|
||||
struct wl_resource *p = wl_resource_create(c, &xdg_positioner_interface, wl_resource_get_version(r), id);
|
||||
if (p) wl_resource_set_implementation(p, NULL, NULL, NULL);
|
||||
if (!p) { wl_client_post_no_memory(c); return; }
|
||||
wl_resource_set_implementation(p, &positioner_impl, NULL, NULL);
|
||||
}
|
||||
static void xdg_wm_base_get_xdg_surface(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
||||
struct wl_resource *surf) {
|
||||
@@ -1721,9 +1885,15 @@ static void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t
|
||||
|
||||
/* ------------------------------------------------------------------ wl_output */
|
||||
|
||||
/* wl_output v3+ has a request (release); without an implementation the first client to send it
|
||||
* aborted the compositor. */
|
||||
static void output_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static const struct wl_output_interface output_impl = { .release = output_release };
|
||||
|
||||
static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
|
||||
struct wl_resource *r = wl_resource_create(c, &wl_output_interface, ver, id);
|
||||
wl_resource_set_implementation(r, NULL, NULL, NULL);
|
||||
if (!r) { wl_client_post_no_memory(c); return; }
|
||||
wl_resource_set_implementation(r, &output_impl, NULL, NULL);
|
||||
wl_output_send_geometry(r, 0, 0, 340, 190, WL_OUTPUT_SUBPIXEL_UNKNOWN,
|
||||
"Bannerlator", "Wayland", WL_OUTPUT_TRANSFORM_NORMAL);
|
||||
wl_output_send_mode(r, WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED,
|
||||
@@ -2309,9 +2479,23 @@ static uint32_t now_ms(void) {
|
||||
return (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
|
||||
}
|
||||
|
||||
/* wl_pointer.set_cursor: the client tells us its pointer image, or asks for none. A NULL surface
|
||||
* means "no cursor" and is authoritative. The surface itself is snapshotted on its next commit. */
|
||||
static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint32_t serial,
|
||||
struct wl_resource *surface, int32_t hx, int32_t hy) {
|
||||
/* The app draws its own pointer; cursor surfaces stay role-less and aren't drawn. */
|
||||
if (!surface) {
|
||||
if (g_cursor_surface) g_cursor_surface->role = ROLE_NONE;
|
||||
g_cursor_surface = NULL;
|
||||
cursor_publish_hidden();
|
||||
return;
|
||||
}
|
||||
struct surface *s = wl_resource_get_user_data(surface);
|
||||
if (!s) return;
|
||||
if (s->role != ROLE_NONE && s->role != ROLE_CURSOR) return; /* already has another role */
|
||||
s->role = ROLE_CURSOR;
|
||||
g_cursor_surface = s;
|
||||
g_cursor_hx = hx;
|
||||
g_cursor_hy = hy;
|
||||
}
|
||||
static void pointer_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static const struct wl_pointer_interface pointer_impl = {
|
||||
@@ -2332,6 +2516,10 @@ static void keyboard_res_destroy(struct wl_resource *r) {
|
||||
}
|
||||
static void touch_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static const struct wl_touch_interface touch_impl = { .release = touch_release };
|
||||
static void touch_res_destroy(struct wl_resource *r) {
|
||||
for (int i = 0; i < g_ntouches; i++)
|
||||
if (g_touches[i].touch == r) { g_touches[i] = g_touches[--g_ntouches]; break; }
|
||||
}
|
||||
|
||||
static void seat_get_pointer(struct wl_client *c, struct wl_resource *r, uint32_t id) {
|
||||
struct wl_resource *p = wl_resource_create(c, &wl_pointer_interface, wl_resource_get_version(r), id);
|
||||
@@ -2363,7 +2551,13 @@ static void seat_get_keyboard(struct wl_client *c, struct wl_resource *r, uint32
|
||||
}
|
||||
static void seat_get_touch(struct wl_client *c, struct wl_resource *r, uint32_t id) {
|
||||
struct wl_resource *t = wl_resource_create(c, &wl_touch_interface, wl_resource_get_version(r), id);
|
||||
if (t) wl_resource_set_implementation(t, &touch_impl, NULL, NULL);
|
||||
if (!t) { wl_client_post_no_memory(c); return; }
|
||||
wl_resource_set_implementation(t, &touch_impl, NULL, touch_res_destroy);
|
||||
if (g_ntouches < MAX_PTRS) {
|
||||
g_touches[g_ntouches].touch = t;
|
||||
g_touches[g_ntouches].focus = NULL;
|
||||
g_ntouches++;
|
||||
}
|
||||
}
|
||||
static void seat_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static const struct wl_seat_interface seat_impl = {
|
||||
@@ -2373,7 +2567,7 @@ static const struct wl_seat_interface seat_impl = {
|
||||
static void bind_seat(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
|
||||
struct wl_resource *r = wl_resource_create(c, &wl_seat_interface, ver, id);
|
||||
wl_resource_set_implementation(r, &seat_impl, NULL, NULL);
|
||||
wl_seat_send_capabilities(r, WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_KEYBOARD);
|
||||
wl_seat_send_capabilities(r, WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_KEYBOARD | WL_SEAT_CAPABILITY_TOUCH);
|
||||
if (ver >= 2) wl_seat_send_name(r, "bannerlator-seat");
|
||||
}
|
||||
|
||||
@@ -2397,6 +2591,9 @@ static struct seat_keyboard *keyboard_for(struct wl_client *client) {
|
||||
#define for_each_keyboard_of(client, sk) \
|
||||
for (int _i = 0; _i < g_nkbs; _i++) \
|
||||
if (((sk) = &g_kbs[_i]), wl_resource_get_client((sk)->kb) == (client))
|
||||
#define for_each_touch_of(client, st) \
|
||||
for (int _i = 0; _i < g_ntouches; _i++) \
|
||||
if (((st) = &g_touches[_i]), wl_resource_get_client((st)->touch) == (client))
|
||||
|
||||
/* Topmost window whose scene rectangle contains the point (no-desktop fallback). */
|
||||
static struct surface *toplevel_at(double x, double y) {
|
||||
@@ -2931,6 +3128,188 @@ static void deliver_pointer(const struct input_msg *m) {
|
||||
pointer_event(x, y, m->p1 == 1 ? 0 : BTN_LEFT, m->p1 == 0);
|
||||
}
|
||||
|
||||
static void input_output_to_scene(int px, int py, double *x, double *y) {
|
||||
int w, h, ow, oh;
|
||||
scene_size(&w, &h);
|
||||
vkp_output_size(&ow, &oh);
|
||||
if (ow <= 0 || oh <= 0 ||
|
||||
!vkp_output_to_scene((double)px * ow / INPUT_SPACE_W, (double)py * oh / INPUT_SPACE_H, x, y)) {
|
||||
*x = (double)px * w / INPUT_SPACE_W;
|
||||
*y = (double)py * h / INPUT_SPACE_H;
|
||||
}
|
||||
if (*x < 0) *x = 0;
|
||||
if (*y < 0) *y = 0;
|
||||
if (*x > w - 1) *x = w - 1;
|
||||
if (*y > h - 1) *y = h - 1;
|
||||
}
|
||||
|
||||
static int touch_points_for_client(struct wl_client *client) {
|
||||
for (int i = 0; i < MAX_TOUCH_POINTS; i++) {
|
||||
struct surface *surface = g_touch_points[i].surface;
|
||||
if (surface && wl_resource_get_client(surface->resource) == client) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void touch_frame(struct wl_client *client) {
|
||||
struct seat_touch *st;
|
||||
for_each_touch_of(client, st)
|
||||
if (wl_resource_get_version(st->touch) >= WL_TOUCH_FRAME_SINCE_VERSION)
|
||||
wl_touch_send_frame(st->touch);
|
||||
}
|
||||
|
||||
static void touch_cancel_client(struct wl_client *client) {
|
||||
struct seat_touch *st;
|
||||
int release_pointer = 0;
|
||||
for_each_touch_of(client, st) {
|
||||
if (st->focus) wl_touch_send_cancel(st->touch);
|
||||
st->focus = NULL;
|
||||
}
|
||||
for (int i = 0; i < MAX_TOUCH_POINTS; i++) {
|
||||
struct surface *surface = g_touch_points[i].surface;
|
||||
if (surface && wl_resource_get_client(surface->resource) == client) {
|
||||
release_pointer |= g_touch_points[i].pointer_fallback;
|
||||
memset(&g_touch_points[i], 0, sizeof(g_touch_points[i]));
|
||||
}
|
||||
}
|
||||
if (release_pointer) pointer_button(BTN_LEFT, 0);
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
|
||||
static void touch_cancel_all(void) {
|
||||
int release_pointer = 0;
|
||||
for (int i = 0; i < g_ntouches; i++) {
|
||||
if (g_touches[i].focus) wl_touch_send_cancel(g_touches[i].touch);
|
||||
g_touches[i].focus = NULL;
|
||||
}
|
||||
for (int i = 0; i < MAX_TOUCH_POINTS; i++)
|
||||
release_pointer |= g_touch_points[i].pointer_fallback;
|
||||
memset(g_touch_points, 0, sizeof(g_touch_points));
|
||||
if (release_pointer) pointer_button(BTN_LEFT, 0);
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
|
||||
static void touch_cancel_surface(struct surface *surface) {
|
||||
struct wl_client *client = wl_resource_get_client(surface->resource);
|
||||
for (int i = 0; i < MAX_TOUCH_POINTS; i++)
|
||||
if (g_touch_points[i].surface == surface) {
|
||||
touch_cancel_client(client);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
static struct surface *touch_target_at(double x, double y) {
|
||||
struct surface *target = toplevel_at(x, y);
|
||||
if (target) return target;
|
||||
if (g_desktop) return g_desktop;
|
||||
return g_grab ? g_grab : g_key_target;
|
||||
}
|
||||
|
||||
static void touch_down(int id, double x, double y) {
|
||||
if (id < 0 || id >= MAX_TOUCH_POINTS) return;
|
||||
struct surface *target = touch_target_at(x, y);
|
||||
if (!target) return;
|
||||
struct wl_client *client = wl_resource_get_client(target->resource);
|
||||
/* A down on an id that is still held means that sequence's up was lost: end it first. The
|
||||
* fingers still down are counted only after that - counted before, a lost up left any_active
|
||||
* set, and on the pointer path every later touch was dropped (a tap or swipe did nothing). */
|
||||
if (g_touch_points[id].surface) touch_cancel_client(client);
|
||||
int any_active = 0;
|
||||
for (int i = 0; i < MAX_TOUCH_POINTS; i++) {
|
||||
struct surface *active = g_touch_points[i].surface;
|
||||
if (!active) continue;
|
||||
if (active != target) {
|
||||
touch_cancel_all();
|
||||
any_active = 0;
|
||||
break;
|
||||
}
|
||||
any_active = 1;
|
||||
}
|
||||
struct seat_touch *st;
|
||||
int has_touch = 0;
|
||||
for_each_touch_of(client, st) has_touch = 1;
|
||||
/* One line per gesture (first finger), so a test can see where a touch went. */
|
||||
if (!any_active) {
|
||||
char name[160];
|
||||
describe(target, name, sizeof(name));
|
||||
banner_log("touch", "%s gets %s", name, has_touch ? "touch" : "the pointer (it takes no touch)");
|
||||
}
|
||||
if (!has_touch) {
|
||||
if (any_active) return; /* one finger drives the pointer; a second one is ignored */
|
||||
g_touch_points[id].surface = target;
|
||||
g_touch_points[id].pointer_fallback = 1;
|
||||
pointer_event(x, y, BTN_LEFT, 1);
|
||||
wl_display_flush_clients(g_display);
|
||||
return;
|
||||
}
|
||||
int tx = 0, ty = 0;
|
||||
if (target != g_desktop && target->placed) { tx = target->x; ty = target->y; }
|
||||
wl_fixed_t fx = wl_fixed_from_double(x - tx), fy = wl_fixed_from_double(y - ty);
|
||||
int sent = 0;
|
||||
for_each_touch_of(client, st) {
|
||||
st->focus = target->resource;
|
||||
wl_touch_send_down(st->touch, wl_display_next_serial(g_display), now_ms(),
|
||||
target->resource, id, fx, fy);
|
||||
sent = 1;
|
||||
}
|
||||
if (!sent) return;
|
||||
g_touch_points[id].surface = target;
|
||||
touch_frame(client);
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
|
||||
static void touch_motion(int id, double x, double y) {
|
||||
if (id < 0 || id >= MAX_TOUCH_POINTS) return;
|
||||
struct surface *target = g_touch_points[id].surface;
|
||||
if (!target) return;
|
||||
if (g_touch_points[id].pointer_fallback) {
|
||||
pointer_event(x, y, 0, 0);
|
||||
wl_display_flush_clients(g_display);
|
||||
return;
|
||||
}
|
||||
struct wl_client *client = wl_resource_get_client(target->resource);
|
||||
int tx = 0, ty = 0;
|
||||
if (target != g_desktop && target->placed) { tx = target->x; ty = target->y; }
|
||||
wl_fixed_t fx = wl_fixed_from_double(x - tx), fy = wl_fixed_from_double(y - ty);
|
||||
struct seat_touch *st;
|
||||
for_each_touch_of(client, st)
|
||||
if (st->focus == target->resource)
|
||||
wl_touch_send_motion(st->touch, now_ms(), id, fx, fy);
|
||||
touch_frame(client);
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
|
||||
static void touch_up(int id, double x, double y) {
|
||||
if (id < 0 || id >= MAX_TOUCH_POINTS) return;
|
||||
struct surface *target = g_touch_points[id].surface;
|
||||
if (!target) return;
|
||||
if (g_touch_points[id].pointer_fallback) {
|
||||
memset(&g_touch_points[id], 0, sizeof(g_touch_points[id]));
|
||||
pointer_event(x, y, BTN_LEFT, 0);
|
||||
wl_display_flush_clients(g_display);
|
||||
return;
|
||||
}
|
||||
struct wl_client *client = wl_resource_get_client(target->resource);
|
||||
struct seat_touch *st;
|
||||
for_each_touch_of(client, st)
|
||||
if (st->focus == target->resource)
|
||||
wl_touch_send_up(st->touch, wl_display_next_serial(g_display), now_ms(), id);
|
||||
memset(&g_touch_points[id], 0, sizeof(g_touch_points[id]));
|
||||
touch_frame(client);
|
||||
if (!touch_points_for_client(client))
|
||||
for_each_touch_of(client, st) st->focus = NULL;
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
|
||||
static void deliver_touch(const struct input_msg *m) {
|
||||
double x, y;
|
||||
input_output_to_scene(m->p3, m->p4, &x, &y);
|
||||
if (m->p1 == 0) touch_down(m->p2, x, y);
|
||||
else if (m->p1 == 1) touch_motion(m->p2, x, y);
|
||||
else if (m->p1 == 2) touch_up(m->p2, x, y);
|
||||
else if (m->p1 == 3) touch_cancel_all();
|
||||
}
|
||||
|
||||
static void key_event(uint32_t evdev, int pressed);
|
||||
struct wl_resource *banner_ime_target(void);
|
||||
static void deliver_key(const struct input_msg *m) {
|
||||
@@ -2999,6 +3378,7 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
case 4: scroll_event(m.p1); break;
|
||||
case 5: on_vsync(((int64_t)m.p1 << 32) | (uint32_t)m.p2); break;
|
||||
case 6: pointer_delta(m.p1 / 256.0, m.p2 / 256.0); break; /* relative motion, 1/256 px */
|
||||
case 7: deliver_touch(&m); break;
|
||||
default: deliver_pointer(&m); break;
|
||||
}
|
||||
}
|
||||
@@ -3009,7 +3389,14 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
* dispatches it. x/y are in INPUT_SPACE (0..1919, 0..1079) over the whole output. */
|
||||
void banner_wayland_send_pointer(int action, int x, int y) {
|
||||
if (g_input_pipe[1] < 0) return;
|
||||
struct input_msg m = { 0, action, x, y };
|
||||
struct input_msg m = { 0, action, x, y, 0 };
|
||||
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
|
||||
(void)n;
|
||||
}
|
||||
|
||||
void banner_wayland_send_touch(int action, int pointer_id, int x, int y) {
|
||||
if (g_input_pipe[1] < 0) return;
|
||||
struct input_msg m = { 7, action, pointer_id, x, y };
|
||||
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
|
||||
(void)n;
|
||||
}
|
||||
@@ -3017,7 +3404,7 @@ void banner_wayland_send_pointer(int action, int x, int y) {
|
||||
/* Called from JNI. Queues a key event. evdev = Linux input keycode (e.g. KEY_A=30); state 1=down 0=up. */
|
||||
void banner_wayland_send_key(int evdev, int state) {
|
||||
if (g_input_pipe[1] < 0) return;
|
||||
struct input_msg m = { 1, evdev, state, 0 };
|
||||
struct input_msg m = { 1, evdev, state, 0, 0 };
|
||||
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
|
||||
(void)n;
|
||||
}
|
||||
@@ -3025,7 +3412,7 @@ void banner_wayland_send_key(int evdev, int state) {
|
||||
/* Called from JNI on every screen refresh (Choreographer). */
|
||||
void banner_wayland_vsync(int64_t frame_time_ns) {
|
||||
if (g_input_pipe[1] < 0) return;
|
||||
struct input_msg m = { 5, (int)(frame_time_ns >> 32), (int)(uint32_t)frame_time_ns, 0 };
|
||||
struct input_msg m = { 5, (int)(frame_time_ns >> 32), (int)(uint32_t)frame_time_ns, 0, 0 };
|
||||
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
|
||||
(void)n;
|
||||
}
|
||||
@@ -3035,7 +3422,7 @@ void banner_wayland_vsync(int64_t frame_time_ns) {
|
||||
* 6 = relative motion by a,b in 1/256 pixel (the app's Relative Mouse / captured-mouse path). */
|
||||
void banner_wayland_send_scene_input(int type, int a, int b) {
|
||||
if (g_input_pipe[1] < 0) return;
|
||||
struct input_msg m = { type, a, b, 0 };
|
||||
struct input_msg m = { type, a, b, 0, 0 };
|
||||
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
|
||||
(void)n;
|
||||
}
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
/* Compositor-side dmabuf import into Turnip (see vk_import.h). */
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "vk_import.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#define MOD_INVALID 0x00ffffffffffffffULL
|
||||
|
||||
static int g_ready = -1; /* -1 = untried, 0 = ok, 1 = init failed */
|
||||
static VkInstance g_inst;
|
||||
static VkPhysicalDevice g_pd;
|
||||
static VkDevice g_dev;
|
||||
static PFN_vkGetMemoryFdPropertiesKHR p_getMemFdProps;
|
||||
|
||||
static int has_ext(VkExtensionProperties *e, uint32_t n, const char *name) {
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
if (!strcmp(e[i].extensionName, name)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int vk_init(void) {
|
||||
if (g_ready >= 0) return g_ready == 0 ? 0 : -1;
|
||||
|
||||
VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
|
||||
.pApplicationName = "spike-compositor-import",
|
||||
.apiVersion = VK_API_VERSION_1_1};
|
||||
VkInstanceCreateInfo ici = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
|
||||
.pApplicationInfo = &app};
|
||||
if (vkCreateInstance(&ici, NULL, &g_inst) != VK_SUCCESS) {
|
||||
fprintf(stderr, "[imp] vkCreateInstance failed\n");
|
||||
g_ready = 1; return -1;
|
||||
}
|
||||
uint32_t npd = 0;
|
||||
vkEnumeratePhysicalDevices(g_inst, &npd, NULL);
|
||||
if (!npd) { g_ready = 1; return -1; }
|
||||
VkPhysicalDevice pds[8];
|
||||
if (npd > 8) npd = 8;
|
||||
vkEnumeratePhysicalDevices(g_inst, &npd, pds);
|
||||
g_pd = pds[0]; /* Turnip is forced via VK_ICD_FILENAMES */
|
||||
|
||||
const char *want[] = {"VK_KHR_external_memory_fd",
|
||||
"VK_EXT_external_memory_dma_buf",
|
||||
"VK_EXT_image_drm_format_modifier",
|
||||
"VK_KHR_image_format_list"};
|
||||
uint32_t ne = 0;
|
||||
vkEnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
|
||||
VkExtensionProperties *exts = calloc(ne, sizeof(*exts));
|
||||
vkEnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
|
||||
for (unsigned i = 0; i < 4; i++)
|
||||
if (!has_ext(exts, ne, want[i]))
|
||||
fprintf(stderr, "[imp] WARNING device missing %s\n", want[i]);
|
||||
free(exts);
|
||||
|
||||
float prio = 1.0f;
|
||||
VkDeviceQueueCreateInfo qci = {.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
|
||||
.queueFamilyIndex = 0, .queueCount = 1,
|
||||
.pQueuePriorities = &prio};
|
||||
VkDeviceCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
|
||||
.queueCreateInfoCount = 1, .pQueueCreateInfos = &qci,
|
||||
.enabledExtensionCount = 4, .ppEnabledExtensionNames = want};
|
||||
if (vkCreateDevice(g_pd, &dci, NULL, &g_dev) != VK_SUCCESS) {
|
||||
fprintf(stderr, "[imp] vkCreateDevice failed\n");
|
||||
g_ready = 1; return -1;
|
||||
}
|
||||
p_getMemFdProps = (PFN_vkGetMemoryFdPropertiesKHR)vkGetDeviceProcAddr(
|
||||
g_dev, "vkGetMemoryFdPropertiesKHR");
|
||||
g_ready = 0;
|
||||
fprintf(stderr, "[imp] Vulkan import device ready (Turnip)\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static VkFormat drm_to_vk(uint32_t drm) {
|
||||
/* XR24/AR24 (XRGB/ARGB8888, little-endian bytes B,G,R,X) -> BGRA8. */
|
||||
return VK_FORMAT_B8G8R8A8_UNORM;
|
||||
}
|
||||
|
||||
int vk_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
|
||||
uint32_t stride, uint32_t offset) {
|
||||
if (modifier == MOD_INVALID) {
|
||||
fprintf(stderr, "[imp] skip: INVALID modifier (needs implicit path)\n");
|
||||
return -1;
|
||||
}
|
||||
if (vk_init() != 0) return -1;
|
||||
|
||||
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
|
||||
VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
|
||||
.drmFormatModifier = modifier,
|
||||
.drmFormatModifierPlaneCount = 1,
|
||||
.pPlaneLayouts = &plane};
|
||||
VkExternalMemoryImageCreateInfo extImg = {
|
||||
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
|
||||
.pNext = &modInfo,
|
||||
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
|
||||
VkImageCreateInfo ici = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
|
||||
.pNext = &extImg,
|
||||
.imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = drm_to_vk(drm_format),
|
||||
.extent = {w, h, 1},
|
||||
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
VkImage image;
|
||||
VkResult r = vkCreateImage(g_dev, &ici, NULL, &image);
|
||||
if (r != VK_SUCCESS) {
|
||||
fprintf(stderr, "[imp] vkCreateImage(drm_modifier) -> %d\n", r);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int dupfd = dup(fd);
|
||||
uint32_t allowed_types = 0xffffffff;
|
||||
if (p_getMemFdProps) {
|
||||
VkMemoryFdPropertiesKHR fp = {.sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR};
|
||||
if (p_getMemFdProps(g_dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
|
||||
dupfd, &fp) == VK_SUCCESS)
|
||||
allowed_types = fp.memoryTypeBits;
|
||||
}
|
||||
VkMemoryRequirements req;
|
||||
vkGetImageMemoryRequirements(g_dev, image, &req);
|
||||
uint32_t bits = req.memoryTypeBits & allowed_types;
|
||||
int type_idx = -1;
|
||||
for (int i = 0; i < 32; i++)
|
||||
if (bits & (1u << i)) { type_idx = i; break; }
|
||||
if (type_idx < 0) {
|
||||
fprintf(stderr, "[imp] no compatible memory type\n");
|
||||
vkDestroyImage(g_dev, image, NULL); close(dupfd); return -1;
|
||||
}
|
||||
|
||||
VkImportMemoryFdInfoKHR imp = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
|
||||
.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
|
||||
.fd = dupfd};
|
||||
VkMemoryDedicatedAllocateInfo ded = {
|
||||
.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
|
||||
.pNext = &imp, .image = image};
|
||||
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
|
||||
.pNext = &ded,
|
||||
.allocationSize = req.size,
|
||||
.memoryTypeIndex = (uint32_t)type_idx};
|
||||
VkDeviceMemory mem;
|
||||
r = vkAllocateMemory(g_dev, &mai, NULL, &mem);
|
||||
if (r != VK_SUCCESS) {
|
||||
fprintf(stderr, "[imp] vkAllocateMemory(import fd) -> %d\n", r);
|
||||
vkDestroyImage(g_dev, image, NULL); close(dupfd); return -1;
|
||||
}
|
||||
r = vkBindImageMemory(g_dev, image, mem, 0);
|
||||
if (r != VK_SUCCESS) {
|
||||
fprintf(stderr, "[imp] vkBindImageMemory -> %d\n", r);
|
||||
vkFreeMemory(g_dev, mem, NULL); vkDestroyImage(g_dev, image, NULL);
|
||||
return -1;
|
||||
}
|
||||
|
||||
fprintf(stderr,
|
||||
"[imp] *** IMPORTED dmabuf -> VkImage OK (memType %d, size %llu) "
|
||||
"==> compositor can turn game frames into VkImages\n",
|
||||
type_idx, (unsigned long long)req.size);
|
||||
/* import took ownership of dupfd; free our objects */
|
||||
vkFreeMemory(g_dev, mem, NULL);
|
||||
vkDestroyImage(g_dev, image, NULL);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
#ifndef VK_IMPORT_H
|
||||
#define VK_IMPORT_H
|
||||
#include <stdint.h>
|
||||
/*
|
||||
* Import a received dmabuf into the compositor's own Vulkan (Turnip) device as a
|
||||
* VkImage and bind its memory. This is the M4-import de-risk: if we can import +
|
||||
* bind, sampling/blitting it to screen is standard Vulkan. Non-fatal: returns 0
|
||||
* on success, negative on failure, and logs details. Does NOT consume `fd`
|
||||
* (dups internally).
|
||||
*/
|
||||
int vk_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier,
|
||||
int w, int h, uint32_t stride, uint32_t offset);
|
||||
#endif
|
||||
@@ -1910,6 +1910,104 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* A client's GPU cursor read back to the CPU, for the app's pointer overlay (compositor.c,
|
||||
* wl_pointer.set_cursor). wlroots hands a nested compositor its cursor as a dma-buf from the parent's
|
||||
* formats - on Adreno usually UBWC, which the CPU cannot read - so it is blitted into a small linear,
|
||||
* host-visible image first. Rare (a cursor changes shape, it is not redrawn per frame) and waited
|
||||
* for on the CPU. out: w*h pixels, B8G8R8A8 in memory = 0xAARRGGBB ints. 0 = ok. */
|
||||
static struct vkp_image *g_rb; /* the readback image, kept for the next shape */
|
||||
|
||||
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
|
||||
if (!src || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
|
||||
g_dev_state == -2 || dev_init() != 0)
|
||||
return -1;
|
||||
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
|
||||
if (!g_rb) {
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return -1;
|
||||
img->w = src->w; img->h = src->h;
|
||||
VkImageCreateInfo ici = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = VK_FORMAT_B8G8R8A8_UNORM, .extent = {src->w, src->h, 1}, .mipLevels = 1,
|
||||
.arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_LINEAR,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
if (g_vk.CreateImage(g_dev, &ici, NULL, &img->image) != VK_SUCCESS) { free(img); return -1; }
|
||||
VkMemoryRequirements req;
|
||||
g_vk.GetImageMemoryRequirements(g_dev, img->image, &req);
|
||||
int idx = memory_type(req.memoryTypeBits,
|
||||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
|
||||
.allocationSize = req.size, .memoryTypeIndex = (uint32_t)idx};
|
||||
if (idx < 0 || g_vk.AllocateMemory(g_dev, &mai, NULL, &img->mem) != VK_SUCCESS) {
|
||||
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return -1;
|
||||
}
|
||||
g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
|
||||
VkImageSubresource subr = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0};
|
||||
VkSubresourceLayout lay;
|
||||
g_vk.GetImageSubresourceLayout(g_dev, img->image, &subr, &lay);
|
||||
img->offset = lay.offset;
|
||||
img->row_pitch = lay.rowPitch;
|
||||
if (g_vk.MapMemory(g_dev, img->mem, 0, req.size, 0, &img->map) != VK_SUCCESS) {
|
||||
vkp_image_destroy(img); return -1;
|
||||
}
|
||||
g_rb = img;
|
||||
}
|
||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
VkCommandBuffer cmd = g_cmds[0];
|
||||
g_vk.ResetCommandBuffer(cmd, 0);
|
||||
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
|
||||
g_vk.BeginCommandBuffer(cmd, &bi);
|
||||
VkImageMemoryBarrier acq[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.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_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->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, 2, acq);
|
||||
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.srcOffsets = {{0, 0, 0}, {src->w, src->h, 1}},
|
||||
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.dstOffsets = {{0, 0, 0}, {src->w, src->h, 1}}};
|
||||
g_vk.CmdBlitImage(cmd, src->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
g_rb->image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST);
|
||||
VkImageMemoryBarrier done[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
|
||||
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT},
|
||||
/* the client's buffer goes back to it */
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.srcQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
|
||||
0, 0, NULL, 0, NULL, 2, done);
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
|
||||
g_vk.ResetFences(g_dev, 1, &g_fence);
|
||||
VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
|
||||
if (qr != VK_SUCCESS) {
|
||||
if (qr == VK_ERROR_DEVICE_LOST) device_lost("cursor readback");
|
||||
return -1;
|
||||
}
|
||||
VkResult fr = timed_wait(g_fence, 1000000000ULL);
|
||||
if (fr == VK_ERROR_DEVICE_LOST) { device_lost("cursor readback"); return -1; }
|
||||
if (fr != VK_SUCCESS) return -1;
|
||||
for (int y = 0; y < src->h; y++)
|
||||
memcpy(out + (size_t)y * src->w, (const uint8_t *)g_rb->map + g_rb->offset + (size_t)y * g_rb->row_pitch,
|
||||
(size_t)src->w * 4);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the compositor pass, off-screen
|
||||
*
|
||||
* Layer mode with screen effects on: the game's frame still has to go through the compositor pass
|
||||
|
||||
@@ -146,6 +146,9 @@ int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
* wait_fd: a sync_file the copy must wait for before writing dst (the display's release fence of that
|
||||
* buffer), -1 = none. Always consumed (handed to the GPU, or waited for and closed). */
|
||||
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd);
|
||||
/* A client's GPU cursor (an imported dma-buf, often UBWC) read back as w*h 0xAARRGGBB pixels through a
|
||||
* linear host-visible copy; waited for on the CPU. Compositor thread, between frames. 0 = ok. */
|
||||
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px);
|
||||
/* Refresh the scene -> output mapping for this scene size without presenting (creates the
|
||||
* swapchain if needed, since the mapping is in output pixels). 0 = mapping valid. */
|
||||
int vkp_update_map(int scene_w, int scene_h);
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
|
||||
extern int banner_wayland_run(void);
|
||||
extern void banner_wayland_send_pointer(int action, int x, int y);
|
||||
extern void banner_wayland_send_touch(int action, int pointer_id, int x, int y);
|
||||
extern int banner_cursor_snapshot(int *out, int cap);
|
||||
extern void banner_wayland_send_key(int evdev, int state);
|
||||
extern void banner_wayland_send_scene_input(int type, int a, int b);
|
||||
extern void banner_wayland_vsync(int64_t frame_time_ns);
|
||||
@@ -271,6 +273,27 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendPointer(
|
||||
banner_wayland_send_pointer(action, x, y);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendTouch(
|
||||
JNIEnv *env, jclass clazz, jint action, jint pointer_id, jint x, jint y) {
|
||||
banner_wayland_send_touch(action, pointer_id, x, y);
|
||||
}
|
||||
|
||||
/* The client's pointer image and whether it wants one at all (wl_pointer.set_cursor).
|
||||
* out = [serial, hidden, w, h, hotspotX, hotspotY, ARGB pixels...]; returns ints written, 0 if the
|
||||
* array is too small. The app polls the serial and only rebuilds its overlay when it changes. */
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
||||
JNIEnv *env, jclass clazz, jintArray out) {
|
||||
if (!out) return 0;
|
||||
jint cap = (*env)->GetArrayLength(env, out);
|
||||
jint *buf = (*env)->GetIntArrayElements(env, out, NULL);
|
||||
if (!buf) return 0;
|
||||
int n = banner_cursor_snapshot((int *)buf, (int)cap);
|
||||
(*env)->ReleaseIntArrayElements(env, out, buf, 0);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Inject a key event. evdev = Linux input keycode (KEY_A=30…); state 1=down 0=up. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.ActivityOptions
|
||||
import android.app.role.RoleManager
|
||||
import android.graphics.Bitmap
|
||||
import android.content.ComponentName
|
||||
@@ -21,6 +22,25 @@ object HomeApp {
|
||||
val icon: Bitmap?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Whether the app offers itself as a Home app at all. HomeActivity is declared disabled and
|
||||
* only enabled when the user turns on "Use as a Home screen": a player who does not want a
|
||||
* launcher never gets Android's "which Home app?" question, and it is one apk either way.
|
||||
* The setting is the component's own state, which Android keeps across updates.
|
||||
*/
|
||||
fun isHomeScreenEnabled(context: Context): Boolean =
|
||||
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
|
||||
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
|
||||
|
||||
/** Turned off while DroidDeck is the Home app, the phone goes back to its own launcher. */
|
||||
fun setHomeScreenEnabled(context: Context, enabled: Boolean) {
|
||||
context.packageManager.setComponentEnabledSetting(
|
||||
ComponentName(context, HomeActivity::class.java),
|
||||
if (enabled) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
|
||||
PackageManager.DONT_KILL_APP,
|
||||
)
|
||||
}
|
||||
|
||||
fun isDefault(context: Context): Boolean {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val roles = context.getSystemService(RoleManager::class.java)
|
||||
@@ -73,11 +93,19 @@ object HomeApp {
|
||||
return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
}
|
||||
|
||||
fun launch(context: Context, app: LaunchableApp) {
|
||||
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) {
|
||||
val intent = Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(ComponentName(app.packageName, app.className))
|
||||
context.startActivity(intent)
|
||||
if (displayId == null) {
|
||||
context.startActivity(intent)
|
||||
return
|
||||
}
|
||||
// Keep the target app's task separate from DroidDeck. Without this, Android can put the
|
||||
// app on top of the caller's task and move the entire task to the chosen display.
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
|
||||
context.startActivity(intent, options.toBundle())
|
||||
}
|
||||
|
||||
fun isActiveSteamSession(): Boolean =
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.Manifest
|
||||
import android.app.ActivityOptions
|
||||
import android.content.Intent
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import java.io.File
|
||||
import android.content.pm.PackageManager
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.KeyEvent
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -27,15 +33,21 @@ import com.droiddeck.launcher.gpu.LsfgNative
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.runtime.DeckyManager
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.ui.PackageRow
|
||||
import com.droiddeck.launcher.session.OfflineMode
|
||||
import com.droiddeck.launcher.session.ProtonExtras
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.ui.ComponentsPage
|
||||
import com.droiddeck.launcher.session.SessionLogShare
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.ui.ProtonPage
|
||||
import com.droiddeck.launcher.ui.ProtonRow
|
||||
import com.droiddeck.launcher.core.CpuCores
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import com.droiddeck.launcher.ui.CoreRow
|
||||
import com.droiddeck.launcher.ui.PerformancePage
|
||||
import com.droiddeck.launcher.ui.ModeSettingsPage
|
||||
@@ -43,10 +55,15 @@ import com.droiddeck.launcher.ui.ModeSettings
|
||||
import com.droiddeck.launcher.ui.ModeSettingsActions
|
||||
import com.droiddeck.launcher.ui.DriverRow
|
||||
import com.droiddeck.launcher.ui.ConfirmDialog
|
||||
import com.droiddeck.launcher.ui.ControllerActions
|
||||
import com.droiddeck.launcher.ui.ControllerMappingPage
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.input.ControllerEditorActivity
|
||||
import com.droiddeck.launcher.ui.CreditsDialog
|
||||
import com.droiddeck.launcher.ui.FrontEndScreen
|
||||
import com.droiddeck.launcher.ui.FrontEndState
|
||||
import com.droiddeck.launcher.ui.FrontEndActions
|
||||
import com.droiddeck.launcher.frontend.CoverArt
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.RomsDialog
|
||||
@@ -54,6 +71,8 @@ import com.droiddeck.launcher.files.InAppFilePicker
|
||||
import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplays
|
||||
|
||||
/**
|
||||
* The whole app outside a session: is the runtime installed, is there a newer one, frame
|
||||
@@ -77,9 +96,27 @@ class MainActivity : ComponentActivity() {
|
||||
private var glThread by mutableStateOf(true)
|
||||
private var noGlError by mutableStateOf(true)
|
||||
private var steamDeckMode by mutableStateOf(false)
|
||||
private var showFrameGen by mutableStateOf(false)
|
||||
private var showCredits by mutableStateOf(false)
|
||||
private var showProtons by mutableStateOf(false)
|
||||
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
|
||||
private var showComponents by mutableStateOf(false)
|
||||
private var compSnapshot by mutableStateOf<ComponentsManager.Snapshot?>(null)
|
||||
private var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList())
|
||||
private var compCatalogAt by mutableStateOf(0L)
|
||||
private var compProton by mutableStateOf<String?>(null)
|
||||
private var compComp by mutableStateOf("dxvk")
|
||||
private var compChecking by mutableStateOf(false)
|
||||
private var compBusy by mutableStateOf<String?>(null)
|
||||
private var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap())
|
||||
private var deckyInstalled by mutableStateOf<String?>(null)
|
||||
private var deckyReleases by mutableStateOf<List<DeckyManager.Release>>(emptyList())
|
||||
private var deckyChecking by mutableStateOf(false)
|
||||
private var deckyStage by mutableStateOf<String?>(null)
|
||||
private var deckyPercent by mutableIntStateOf(-1)
|
||||
private var deckySupervisor by mutableStateOf(false)
|
||||
private var deckyReleaseRequest = 0
|
||||
private var showMapping by mutableStateOf(false)
|
||||
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
|
||||
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
|
||||
private var catalogLoading by mutableStateOf(false)
|
||||
private var packageRows by mutableStateOf<List<PackageRow>?>(null)
|
||||
@@ -102,8 +139,11 @@ class MainActivity : ComponentActivity() {
|
||||
private var noXalia by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
||||
private var showPhantomGate by mutableStateOf(false)
|
||||
private var directAudio by mutableStateOf(false)
|
||||
private var clientDirectAudio by mutableStateOf(false)
|
||||
private var forceFullscreen by mutableStateOf(true)
|
||||
private var mic by mutableStateOf(false)
|
||||
private var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
|
||||
@@ -121,6 +161,9 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
// The app's own picker (files/), once per kind of pick: the two driver lists validate
|
||||
// differently, and the reason a zip is refused names the list it belongs in.
|
||||
private val pickComponent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importComponent(it) }
|
||||
}
|
||||
private val pickLinuxDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = true) }
|
||||
}
|
||||
@@ -169,7 +212,8 @@ class MainActivity : ComponentActivity() {
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var renderer by mutableStateOf("pixman")
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var renderer by mutableStateOf("vulkan")
|
||||
private var gameStorage by mutableStateOf("")
|
||||
private var storageOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
|
||||
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
@@ -182,8 +226,16 @@ class MainActivity : ComponentActivity() {
|
||||
private var logsEnabled by mutableStateOf(true)
|
||||
private var showRoms by mutableStateOf(false)
|
||||
private var homeAppSelected by mutableStateOf(false)
|
||||
private var homeScreenEnabled by mutableStateOf(false)
|
||||
private var defaultHomeLabel by mutableStateOf<String?>(null)
|
||||
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private lateinit var displayManager: DisplayManager
|
||||
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
refreshHomeAppState()
|
||||
@@ -209,7 +261,10 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||
refreshPhantomStatus()
|
||||
theme = SessionPrefs.theme(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
setContent {
|
||||
DroidDeckTheme(theme) {
|
||||
val sm = settingsMode
|
||||
@@ -217,6 +272,8 @@ class MainActivity : ComponentActivity() {
|
||||
sm != null -> { { ModeSettingsHost(sm) } }
|
||||
showPerformance -> { { PerformanceHost() } }
|
||||
showProtons -> { { ProtonHost() } }
|
||||
showComponents -> { { ComponentsHost() } }
|
||||
showMapping -> { { MappingHost() } }
|
||||
else -> null
|
||||
}
|
||||
FrontEndScreen(
|
||||
@@ -229,27 +286,38 @@ class MainActivity : ComponentActivity() {
|
||||
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
||||
frameGenEngine = FrameGen.engine(this), frameGenMultiplier = FrameGen.multiplier(this),
|
||||
lsfgReady = LsfgNative.isInstalled(this),
|
||||
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else null,
|
||||
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
|
||||
theme = theme,
|
||||
isHomeApp = homeAppSelected,
|
||||
homeScreenEnabled = homeScreenEnabled,
|
||||
defaultHomeLabel = defaultHomeLabel,
|
||||
androidApps = androidApps,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
packages = packageRows,
|
||||
packageCatalogLoading = catalogLoading,
|
||||
packageBusyId = pkgId,
|
||||
packageStage = pkgStage,
|
||||
packagePercent = pkgPercent,
|
||||
sessionRunning = SessionState.running,
|
||||
backActionsInverted = backActionsInverted,
|
||||
buildLabel = BuildConfig.BUILD_LABEL,
|
||||
oscMode = oscMode,
|
||||
controller = controllerSettings,
|
||||
phantomProcessStatus = phantomProcessStatus,
|
||||
showPhantomGate = showPhantomGate,
|
||||
),
|
||||
FrontEndActions(
|
||||
onPlay = { startSession(Intent(this, SessionActivity::class.java)) },
|
||||
onPlay = { startSession(Intent(this, SessionActivity::class.java), steamSession = true) },
|
||||
// Steam's desktop client as a window on the desktop: under gamescope the
|
||||
// client puts itself into Big Picture whatever it is started with.
|
||||
onPlayDesktopUi = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"))
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
|
||||
},
|
||||
onSteamGame = { g ->
|
||||
startActivity(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"))
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"), steamSession = true)
|
||||
},
|
||||
onDesktop = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
@@ -275,7 +343,8 @@ class MainActivity : ComponentActivity() {
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
},
|
||||
onProtons = { openProtons() },
|
||||
onPerformance = { refreshCores(); showProtons = false; showPerformance = true },
|
||||
onComponents = { openComponents() },
|
||||
onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true },
|
||||
onRoms = { showRoms = true },
|
||||
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
|
||||
onLogs = {
|
||||
@@ -296,10 +365,77 @@ class MainActivity : ComponentActivity() {
|
||||
offline = OfflineMode.enabled(this)
|
||||
},
|
||||
onCredits = { showCredits = true },
|
||||
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false },
|
||||
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false },
|
||||
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
||||
onHomeApp = { manageHomeApp() },
|
||||
onAndroidApp = { app -> launchAndroidApp(app) },
|
||||
onHomeScreen = { on ->
|
||||
HomeApp.setHomeScreenEnabled(this, on)
|
||||
refreshHomeAppState()
|
||||
},
|
||||
onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) },
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
onCheckLatestBuild = {
|
||||
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml")))
|
||||
},
|
||||
onRefreshPhantomStatus = { refreshPhantomStatus() },
|
||||
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) },
|
||||
onWirelessAdbPair = { host, port, code, complete ->
|
||||
Thread({
|
||||
val result = runCatching {
|
||||
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
|
||||
}
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB pairing failed" }
|
||||
ui.post { complete(error) }
|
||||
}, "wireless-adb-pair").start()
|
||||
},
|
||||
onFindWirelessAdbPort = { host, complete ->
|
||||
Thread({
|
||||
val port = WirelessAdbFix.findConnectPort(this@MainActivity, host)
|
||||
ui.post { complete(port) }
|
||||
}, "wireless-adb-discovery").start()
|
||||
},
|
||||
onWirelessAdbApply = { host, port, enabled, complete ->
|
||||
Thread({
|
||||
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB command failed" }
|
||||
ui.post {
|
||||
if (error == null) refreshPhantomStatus()
|
||||
complete(error)
|
||||
}
|
||||
}, "wireless-adb-fix").start()
|
||||
},
|
||||
onSetPhantomProcessLimit = { enabled, complete ->
|
||||
Thread({
|
||||
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB is unavailable" }
|
||||
ui.post {
|
||||
if (error == null) refreshPhantomStatus()
|
||||
complete(error)
|
||||
}
|
||||
}, "wireless-adb-setting").start()
|
||||
},
|
||||
onCopyPhantomCommand = { enabled ->
|
||||
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
|
||||
ClipData.newPlainText("DroidDeck child-process setting", PhantomProcessLimit.adbCommand(enabled)),
|
||||
)
|
||||
android.widget.Toast.makeText(this, "ADB command copied", android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDismissPhantomGate = { showPhantomGate = false },
|
||||
controller = ControllerActions(
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() },
|
||||
onOpacity = { o -> ControllerPrefs.setOpacity(this, o); refreshController() },
|
||||
onSize = { v -> ControllerPrefs.setSize(this, v); refreshController() },
|
||||
onStickClick = { on -> ControllerPrefs.setStickClick(this, on); refreshController() },
|
||||
onAdaptiveSticks = { on -> ControllerPrefs.setAdaptiveSticks(this, on); refreshController() },
|
||||
onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) },
|
||||
onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() },
|
||||
onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = true },
|
||||
onResetAll = { ControllerPrefs.resetAll(this); refreshController() },
|
||||
),
|
||||
),
|
||||
page = page,
|
||||
)
|
||||
@@ -348,13 +484,45 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
|
||||
// A session folder left without its ending - the process was killed - gets it now.
|
||||
if (!SessionState.running) Thread({ SessionArtifacts.finishAbandoned(this) }, "finish-abandoned").start()
|
||||
if (!SessionState.running) Thread({
|
||||
SessionArtifacts.finishAbandoned(this)
|
||||
SessionArtifacts.scrubOlder(this)
|
||||
}, "finish-abandoned").start()
|
||||
}
|
||||
|
||||
/** On the Components page the pad's LB / RB step through FEX, DXVK and VKD3D-Proton, wrapping around. */
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
val all = ComponentsManager.COMPONENTS
|
||||
val step = if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else all.size - 1
|
||||
compComp = all[(all.indexOf(compComp).coerceAtLeast(0) + step) % all.size]
|
||||
}
|
||||
return true
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
refreshPhantomStatus()
|
||||
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
|
||||
// session has just ended). Cheap when nothing is queued.
|
||||
if (!SessionState.running) Thread({
|
||||
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
|
||||
if (applied.isNotEmpty()) ui.post {
|
||||
android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
|
||||
if (showComponents) refreshComponents()
|
||||
}
|
||||
}, "components-queue").start()
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
refreshController()
|
||||
refreshHomeAppState()
|
||||
refreshSecondScreenDisplays()
|
||||
refresh()
|
||||
deckyInstalled = DeckyManager.installed(this)
|
||||
DeckyManager.syncCefMarker(this)
|
||||
deckySupervisor = DeckyManager.supervisorEnabled(this)
|
||||
// Added games' art (a store lookup for what the folders lack) starts here, not only when
|
||||
// the cog opens.
|
||||
refreshAddedGames()
|
||||
@@ -362,17 +530,36 @@ class MainActivity : ComponentActivity() {
|
||||
if (!busy) Thread({ checkCatalog() }, "catalog").start()
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
private fun refreshHomeAppState() {
|
||||
homeAppSelected = HomeApp.isDefault(this)
|
||||
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
|
||||
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
|
||||
defaultHomeLabel = HomeApp.defaultLabel(this)
|
||||
androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList()
|
||||
}
|
||||
|
||||
private fun launchAndroidApp(app: HomeApp.LaunchableApp) {
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
if (!::displayManager.isInitialized) return
|
||||
secondScreenDisplays = SecondScreenDisplays.available(displayManager)
|
||||
}
|
||||
|
||||
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
|
||||
try {
|
||||
HomeApp.launch(this, app)
|
||||
HomeApp.launch(this, app, displayId)
|
||||
} catch (_: Exception) {
|
||||
android.widget.Toast.makeText(this, "Could not open ${app.label}", android.widget.Toast.LENGTH_SHORT).show()
|
||||
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
|
||||
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
|
||||
android.widget.Toast.makeText(this, "Could not open ${app.label} on $target", android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -401,10 +588,158 @@ class MainActivity : ComponentActivity() {
|
||||
private fun openProtons() {
|
||||
settingsMode = null
|
||||
showPerformance = false
|
||||
showComponents = false
|
||||
showMapping = false
|
||||
showProtons = true
|
||||
refreshProtons()
|
||||
}
|
||||
|
||||
private fun refreshDecky() {
|
||||
val request = ++deckyReleaseRequest
|
||||
deckyChecking = true
|
||||
Thread({
|
||||
val channels = runCatching { DeckyManager.releaseChannels(this) }
|
||||
.getOrElse { DeckyManager.ReleaseChannels(emptyList(), emptyList()) }
|
||||
ui.post {
|
||||
if (request == deckyReleaseRequest) {
|
||||
// Use the newest compatible stable build, or the newest compatible
|
||||
// prerelease when the fork has not published a stable ARM64 asset.
|
||||
deckyReleases = channels.stable.ifEmpty { channels.prerelease }
|
||||
deckyChecking = false
|
||||
}
|
||||
}
|
||||
}, "decky-releases").start()
|
||||
}
|
||||
|
||||
private fun installDecky(release: DeckyManager.Release) {
|
||||
if (deckyStage != null || SessionState.running) return
|
||||
deckyStage = "Starting…"; deckyPercent = -1
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
DeckyManager.install(this, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
|
||||
}.getOrElse { error -> "Decky install failed: ${error.message ?: error.javaClass.simpleName}" }
|
||||
ui.post {
|
||||
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(this)
|
||||
if (problem != null) android.widget.Toast.makeText(this, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "install-decky").start()
|
||||
}
|
||||
|
||||
private fun refreshController() {
|
||||
controllerSettings = ControllerPrefs.read(this)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MappingHost() {
|
||||
val settings = controllerSettings ?: return
|
||||
ControllerMappingPage(
|
||||
mapping = settings.mapping,
|
||||
onPick = { id, target -> ControllerPrefs.setTarget(this, id, target); refreshController() },
|
||||
onReset = { ControllerPrefs.resetMapping(this); refreshController() },
|
||||
onBack = { showMapping = false },
|
||||
)
|
||||
}
|
||||
|
||||
private fun openComponents() {
|
||||
settingsMode = null
|
||||
showPerformance = false
|
||||
showProtons = false
|
||||
showMapping = false
|
||||
showComponents = true
|
||||
refreshComponents(snapshotFirst = true)
|
||||
}
|
||||
|
||||
/** Reads the Protons (and on first open saves their originals) off the UI thread; the Nightlies list comes from its cache. */
|
||||
private fun refreshComponents(snapshotFirst: Boolean = false) {
|
||||
Thread({
|
||||
if (snapshotFirst) runCatching { ComponentsManager.snapshotAll(this) }
|
||||
runCatching { ComponentsManager.applyQueued(this) }
|
||||
val snap = runCatching { ComponentsManager.snapshot(this) }.onFailure { Log.w(TAG, "components", it) }.getOrNull()
|
||||
val cat = runCatching { ComponentsManager.catalog(this, false) }.getOrNull()
|
||||
ui.post {
|
||||
compSnapshot = snap ?: ComponentsManager.Snapshot(emptyList(), emptyList())
|
||||
if (cat != null && cat.fetchedAt > 0) { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
||||
if (compProton == null || snap?.protons?.none { it.proton.id == compProton } == true) compProton = snap?.protons?.firstOrNull()?.proton?.id
|
||||
}
|
||||
}, "components").start()
|
||||
}
|
||||
|
||||
private fun componentAction(label: String, work: () -> String) {
|
||||
if (compBusy != null) return
|
||||
compBusy = label
|
||||
Thread({
|
||||
val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
|
||||
ui.post {
|
||||
compBusy = null
|
||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
refreshComponents()
|
||||
}
|
||||
}, "components-action").start()
|
||||
}
|
||||
|
||||
private fun refreshComponentCatalog() {
|
||||
if (compChecking) return
|
||||
compChecking = true
|
||||
Thread({
|
||||
val cat = runCatching { ComponentsManager.catalog(this, true) }.getOrNull()
|
||||
ui.post {
|
||||
compChecking = false
|
||||
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(this, "The Nightlies could not be reached", android.widget.Toast.LENGTH_LONG).show()
|
||||
else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
||||
}
|
||||
}, "components-catalog").start()
|
||||
}
|
||||
|
||||
private fun downloadComponent(item: ComponentsManager.CatalogItem) {
|
||||
if (compDownloads.containsKey(item.file)) return
|
||||
compDownloads = compDownloads + (item.file to -1)
|
||||
Thread({
|
||||
val message = runCatching {
|
||||
val pkg = ComponentsManager.download(this, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } }
|
||||
"Stored ${pkg.version}"
|
||||
}.getOrElse { e -> "Download failed: ${e.message ?: e.javaClass.simpleName}" }
|
||||
ui.post {
|
||||
compDownloads = compDownloads - item.file
|
||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||
refreshComponents()
|
||||
}
|
||||
}, "components-download").start()
|
||||
}
|
||||
|
||||
private fun importComponent(uri: Uri) {
|
||||
val name = displayNameOf(uri) ?: "imported.wcp"
|
||||
componentAction("Importing") {
|
||||
val tmp = File(cacheDir, "component-import.wcp")
|
||||
contentResolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("cannot read the file")
|
||||
try { "Imported ${ComponentsManager.importPackage(this, tmp, name).version}" } finally { tmp.delete() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ComponentsHost() {
|
||||
ComponentsPage(
|
||||
snapshot = compSnapshot,
|
||||
catalog = compCatalog,
|
||||
catalogAt = compCatalogAt,
|
||||
protonId = compProton,
|
||||
comp = compComp,
|
||||
checking = compChecking,
|
||||
busy = compBusy,
|
||||
downloads = compDownloads,
|
||||
onProton = { compProton = it },
|
||||
onComp = { compComp = it },
|
||||
onSwap = { file -> compProton?.let { pid -> componentAction("Swapping") { ComponentsManager.swap(this, pid, file) } } },
|
||||
onRestore = { version -> compProton?.let { pid -> componentAction("Restoring") { ComponentsManager.restore(this, pid, compComp, version) } } },
|
||||
onCancelQueued = { compProton?.let { pid -> componentAction("Cancelling") { ComponentsManager.cancelQueued(this, pid, compComp); "The waiting swap was cancelled." } } },
|
||||
onDeletePackage = { file -> componentAction("Deleting") { ComponentsManager.deletePackage(this, file) } },
|
||||
onDeleteOriginal = { version -> compProton?.let { pid -> componentAction("Deleting") { ComponentsManager.deleteOriginal(this, pid, compComp, version) } } },
|
||||
onDownload = { downloadComponent(it) },
|
||||
onRefresh = { refreshComponentCatalog() },
|
||||
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) },
|
||||
onBack = { showComponents = false },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProtonHost() {
|
||||
ProtonPage(
|
||||
@@ -500,9 +835,6 @@ class MainActivity : ComponentActivity() {
|
||||
}, "remove-pkg").start()
|
||||
}
|
||||
|
||||
/** Both driver lists as the dialog shows them, re-read from disk so an import or removal shows at once. */
|
||||
/** Everything the mode's cog shows, read fresh, then the dialog. */
|
||||
/** The Steam or Desktop settings page, in the front end's pane. */
|
||||
@Composable
|
||||
private fun ModeSettingsHost(mode: String) {
|
||||
ModeSettingsPage(
|
||||
@@ -515,8 +847,10 @@ class MainActivity : ComponentActivity() {
|
||||
touchMode = touchMode,
|
||||
suspendPolicy = suspendPolicy,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||
clientDirectAudio = clientDirectAudio,
|
||||
forceFullscreen = if (mode == SessionService.MODE_STEAM) forceFullscreen else null,
|
||||
mic = if (mode == SessionService.MODE_STEAM) mic else null,
|
||||
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
|
||||
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
|
||||
@@ -528,6 +862,10 @@ class MainActivity : ComponentActivity() {
|
||||
addedGamesArt = addedGamesArt,
|
||||
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, releaseStatus = releaseStatus,
|
||||
releaseChecking = releaseChecking, canRestoreBundled = canRestoreBundled,
|
||||
deckyInstalled = if (mode == SessionService.MODE_STEAM) deckyInstalled else null,
|
||||
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) deckyReleases.firstOrNull() else null,
|
||||
deckyChecking = deckyChecking, deckyStage = deckyStage, deckyPercent = deckyPercent,
|
||||
deckyEnabled = deckySupervisor, deckySessionRunning = SessionState.running,
|
||||
),
|
||||
ModeSettingsActions(
|
||||
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
|
||||
@@ -546,8 +884,13 @@ class MainActivity : ComponentActivity() {
|
||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
|
||||
onClientDirectAudio = { on -> SessionPrefs.setClientDirectAudio(this, on); clientDirectAudio = on },
|
||||
onForceFullscreen = { on -> SessionPrefs.setForceFullscreen(this, on); forceFullscreen = on },
|
||||
onMic = { on ->
|
||||
SessionPrefs.setMicEnabled(this, on)
|
||||
mic = on
|
||||
@@ -572,12 +915,19 @@ class MainActivity : ComponentActivity() {
|
||||
pendingAddedGame = folder
|
||||
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), "Choose the game's .exe", folder))
|
||||
},
|
||||
onDeckyInstall = { release -> installDecky(release) },
|
||||
onDeckyCheck = { refreshDecky() },
|
||||
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); deckySupervisor = enabled },
|
||||
onDeckyUninstall = {
|
||||
DeckyManager.uninstall(this, wipeData = false)
|
||||
deckyInstalled = null
|
||||
deckySupervisor = false
|
||||
},
|
||||
onDismiss = { settingsMode = null },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** The Performance page, in the front end's pane. */
|
||||
@Composable
|
||||
private fun PerformanceHost() {
|
||||
PerformancePage(
|
||||
@@ -628,6 +978,8 @@ class MainActivity : ComponentActivity() {
|
||||
private fun openModeSettings(mode: String) {
|
||||
showPerformance = false
|
||||
showProtons = false
|
||||
showComponents = false
|
||||
showMapping = false
|
||||
refreshDrivers()
|
||||
resolutionCap = SessionPrefs.resolutionCap(this, mode)
|
||||
customResolution = SessionPrefs.customResolution(this, mode)
|
||||
@@ -641,12 +993,19 @@ class MainActivity : ComponentActivity() {
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
directAudio = SessionPrefs.directAudio(this)
|
||||
clientDirectAudio = SessionPrefs.clientDirectAudio(this)
|
||||
forceFullscreen = SessionPrefs.forceFullscreen(this)
|
||||
mic = SessionPrefs.micEnabled(this)
|
||||
renderer = SessionPrefs.desktopRenderer(this)
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
storageOptions = GameStorage.options(this).map { it.label to it.path }
|
||||
if (mode == SessionService.MODE_STEAM) {
|
||||
deckyInstalled = DeckyManager.installed(this)
|
||||
deckySupervisor = DeckyManager.supervisorEnabled(this)
|
||||
refreshDecky()
|
||||
}
|
||||
settingsMode = mode
|
||||
}
|
||||
|
||||
@@ -847,17 +1206,7 @@ class MainActivity : ComponentActivity() {
|
||||
zinkLazy = SessionPrefs.zinkLazy(this)
|
||||
noXalia = SessionPrefs.noXalia(this)
|
||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||
// Android 12 kills the children an app forks itself once there are more than a handful.
|
||||
// A session is nothing but those, so where this is on the OS ends the session and no log
|
||||
// of ours says why. We cannot change a secure setting from here - only say so.
|
||||
phantomWarning = runCatching {
|
||||
android.provider.Settings.Global.getString(contentResolver, "settings_enable_monitor_phantom_procs")
|
||||
}.getOrNull().let { v ->
|
||||
when (v?.lowercase()) {
|
||||
"false", "0" -> null
|
||||
else -> "Android 12 and later kill the extra processes an app starts for itself once there are more than a few, and a session is made of dozens: proot, gamescope, the client and its helpers, Wine. Where that is left on, the client dies with nothing in its log, because nothing in the session did it. Some phones have a \"restrict child processes\" switch in Developer options - turn it off. Otherwise, over adb:\n\n adb shell settings put global settings_enable_monitor_phantom_procs false\n\nThis phone " + (if (v == null) "has not been set either way, so the ROM's default applies." else "currently reports it as on.")
|
||||
}
|
||||
}
|
||||
refreshPhantomStatus()
|
||||
}
|
||||
|
||||
private fun refreshProtons() {
|
||||
@@ -885,6 +1234,12 @@ class MainActivity : ComponentActivity() {
|
||||
} else emptyList()
|
||||
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
||||
ui.post { steamGames = games; emulatorList = emus }
|
||||
// Box art for the games that have none, fetched after the list is up; the list is
|
||||
// rebuilt once if any was found.
|
||||
if (!OfflineMode.enabled(this) && CoverArt.fetchMissing(this, emus.flatMap { it.games })) {
|
||||
val refreshed = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
||||
ui.post { emulatorList = refreshed }
|
||||
}
|
||||
}, "library").start()
|
||||
}
|
||||
|
||||
@@ -908,12 +1263,41 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
/** Starts a session; with no runtime on a non-Adreno, the same warning Setup gives comes first, before any download. */
|
||||
private fun startSession(intent: Intent) {
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false) {
|
||||
refreshPhantomStatus()
|
||||
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
showPhantomGate = true
|
||||
return
|
||||
}
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
|
||||
if (warn && available != null) showNonAdreno = available
|
||||
else startActivity(intent)
|
||||
}
|
||||
|
||||
private fun refreshPhantomStatus() {
|
||||
phantomProcessStatus = PhantomProcessLimit.read(contentResolver)
|
||||
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
"${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.ADB_COMMAND}"
|
||||
} else null
|
||||
}
|
||||
|
||||
private fun openDeveloperOptions(displayId: Int?) {
|
||||
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
try {
|
||||
if (displayId == null) startActivity(intent)
|
||||
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
|
||||
} catch (error: Exception) {
|
||||
if (displayId != null) {
|
||||
runCatching { startActivity(intent) }
|
||||
android.widget.Toast.makeText(this, "Could not open Settings on the bottom screen; opened it on the main screen.", android.widget.Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
android.widget.Toast.makeText(this, "Open Developer options in Settings", android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun install(release: LinuxRuntimeInstaller.Release) {
|
||||
busy = true
|
||||
failed = false
|
||||
@@ -941,5 +1325,6 @@ class MainActivity : ComponentActivity() {
|
||||
private const val TAG = "MainActivity"
|
||||
/** What the picker offers for a driver zip; some file apps label a zip as a plain stream. */
|
||||
private val ZIP_EXT = listOf("zip")
|
||||
private val WCP_EXT = listOf("wcp")
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,12 @@ import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.Display
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
@@ -21,11 +24,13 @@ import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.LsfgNative
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
@@ -35,6 +40,7 @@ import com.droiddeck.launcher.input.OnScreenControls
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplays
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
@@ -43,11 +49,16 @@ import com.droiddeck.launcher.session.PerfHints
|
||||
import com.droiddeck.launcher.session.PerfHud
|
||||
import com.droiddeck.launcher.session.PerfMode
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionLogShare
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.wayland.HdrSupport
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.ui.CursorOverlay
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import com.droiddeck.launcher.ui.DrawerActions
|
||||
import com.droiddeck.launcher.ui.HudText
|
||||
import com.droiddeck.launcher.ui.LoadingOverlay
|
||||
@@ -58,6 +69,9 @@ import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.wayland.CompositorHost
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.ui.DRAWER_PAGES
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* The session's screen: our Wayland compositor presenting onto this activity's Surface, and the
|
||||
@@ -72,27 +86,76 @@ import java.io.File
|
||||
*/
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var surfaceView: SurfaceView
|
||||
private lateinit var sessionOverlay: ComposeView
|
||||
private lateinit var loading: LoadingState
|
||||
private lateinit var hud: PerfHud
|
||||
private var padBridge: PadBridge? = null
|
||||
private var onScreenControls: OnScreenControls? = null
|
||||
private var keyboard: KeyboardHost? = null
|
||||
private var watching = true
|
||||
private lateinit var gestures: PointerGestures
|
||||
private lateinit var touchpad: TouchpadGestures
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f))
|
||||
private var cursorVisible by mutableStateOf(false)
|
||||
private val cursorHide = Runnable { cursorVisible = false }
|
||||
/** When the pad or the on-screen controls were last used (uptimeMillis); see [showCursor]. */
|
||||
private var lastPadInputMs = 0L
|
||||
// The program's own pointer, from wl_pointer.set_cursor (see syncClientCursor): its image in
|
||||
// session pixels, hotspot, and whether it asked for no pointer at all.
|
||||
private val cursorBuf = IntArray(WaylandCompositor.CURSOR_BUF_INTS)
|
||||
private var cursorSerial = 0
|
||||
private var clientHidesCursor = false
|
||||
private var cursorImage by mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null)
|
||||
private var cursorHotX by mutableStateOf(0)
|
||||
private var cursorHotY by mutableStateOf(0)
|
||||
private var cursorImageScale by mutableStateOf(1f)
|
||||
/** labwc changes the shape a moment after the move that reached an edge: look again then. */
|
||||
private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false }
|
||||
private val uiHandler = Handler(Looper.getMainLooper())
|
||||
private var pendingBackAction: Runnable? = null
|
||||
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
|
||||
private var drawerDirectionDownTime = 0L
|
||||
private var drawerDirectionDeviceId = -1
|
||||
private var drawerDirectionRepeatCount = 0
|
||||
private val drawerFirstRepeatDelayMs = ViewConfiguration.getKeyRepeatTimeout().toLong()
|
||||
private val drawerSlowRepeatIntervalMs = maxOf(
|
||||
ViewConfiguration.getKeyRepeatDelay().toLong(), DRAWER_SLOW_REPEAT_FLOOR_MS,
|
||||
)
|
||||
private val drawerDirectionRepeat = object : Runnable {
|
||||
override fun run() {
|
||||
if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) return
|
||||
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val heldMs = now - drawerDirectionDownTime
|
||||
val progress = ((heldMs - drawerFirstRepeatDelayMs).toFloat() / DRAWER_REPEAT_ACCELERATION_MS)
|
||||
.coerceIn(0f, 1f)
|
||||
val intervalMs = (
|
||||
drawerSlowRepeatIntervalMs +
|
||||
(DRAWER_FAST_REPEAT_INTERVAL_MS - drawerSlowRepeatIntervalMs) * progress
|
||||
).toLong()
|
||||
|
||||
dispatchDrawerKey(KeyEvent.ACTION_DOWN, ++drawerDirectionRepeatCount, now)
|
||||
uiHandler.postDelayed(this, intervalMs)
|
||||
}
|
||||
}
|
||||
private val resumeKeysDown = mutableSetOf<Pair<Int, Int>>()
|
||||
|
||||
// Compose reads these; the activity writes them.
|
||||
private var drawerOpen by mutableStateOf(false)
|
||||
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
|
||||
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
|
||||
private var drawerPage by mutableIntStateOf(0)
|
||||
private var drawerControllerActive by mutableStateOf(false)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
|
||||
private var pcKeyboardOpen by mutableStateOf(false)
|
||||
private var hudOn by mutableStateOf(true)
|
||||
private var fillScreen by mutableStateOf(true)
|
||||
private var frameGenLabel by mutableStateOf("Off")
|
||||
private var frameGenEngine by mutableStateOf(FrameGen.ENGINE_OFF)
|
||||
private var frameGenMultiplier by mutableStateOf(2)
|
||||
private var fexPreset by mutableStateOf("")
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
|
||||
private var secondScreenMode by mutableStateOf(SecondScreenMode.NONE)
|
||||
@@ -121,6 +184,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
SessionEvents.begin(this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
|
||||
}
|
||||
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
SessionState.steamUi = intent.getStringExtra(SessionService.EXTRA_STEAM_UI)
|
||||
SessionState.steamUrl = intent.getStringExtra(SessionService.EXTRA_STEAM_URL)
|
||||
if (intent.action == SessionService.ACTION_AGENT_START) {
|
||||
SessionEvents.record("agent.start_requested", mapOf("mode" to SessionState.mode))
|
||||
}
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
// Game-tier power policy for the whole session: a sustained clock floor, the panel's
|
||||
// fastest mode, and the OS told it is in gameplay. Logged so a slow device says why.
|
||||
@@ -143,9 +216,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
|
||||
padBridge = bridge
|
||||
// A player on the pad or the on-screen controls has no use for the mouse arrow; the next
|
||||
// touchpad or mouse move brings it back (showCursor), once the pad has been quiet a moment.
|
||||
bridge.setOnPlayerInput {
|
||||
lastPadInputMs = android.os.SystemClock.uptimeMillis()
|
||||
uiHandler.removeCallbacks(cursorHide)
|
||||
cursorVisible = false
|
||||
}
|
||||
onScreenControls = OnScreenControls(this, bridge).also { root.addView(it) }
|
||||
keyboard = KeyboardHost(this).also { root.addView(it) }
|
||||
gestures = PointerGestures(PointerGestures.slop(this), pointerListener)
|
||||
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
|
||||
// One arrow, ours: Android draws a system pointer for a mouse over any window, and the
|
||||
// session already draws the pointer it is sent.
|
||||
@@ -173,81 +252,134 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
// One Compose layer for every menu and overlay. Touches nothing in it consumes fall
|
||||
// through to the pad and the game underneath.
|
||||
root.addView(ComposeView(this).apply {
|
||||
sessionOverlay = ComposeView(this).apply {
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density)
|
||||
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density,
|
||||
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
||||
if (hud.text.isNotEmpty()) HudText(hud.text)
|
||||
if (loading.visible) LoadingOverlay(loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended)
|
||||
// Opening the drawer takes the controller away from the game: release its pad.
|
||||
androidx.compose.runtime.LaunchedEffect(drawerOpen) { if (drawerOpen) padBridge?.releaseAll() }
|
||||
SessionDrawer(drawerOpen, DrawerActions(
|
||||
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
|
||||
if (drawerOpen) {
|
||||
padBridge?.releaseAll()
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
val requested = sessionOverlay.requestFocus()
|
||||
Log.i(TAG, "drawer root focus requested=$requested focused=${sessionOverlay.hasFocus()}")
|
||||
} else {
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
}
|
||||
// The PC keyboard takes it too, for moving over the keys; the drawer opens over it.
|
||||
androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) padBridge?.releaseAll() }
|
||||
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
|
||||
sendKey = { code, down -> if (CompositorHost.isStarted) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) },
|
||||
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
|
||||
onClose = { pcKeyboardOpen = false },
|
||||
)
|
||||
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
|
||||
steam = SessionState.mode == SessionService.MODE_STEAM,
|
||||
title = if (SessionState.mode == SessionService.MODE_RUN)
|
||||
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "Game" else null,
|
||||
isHomeApp = isHomeApp,
|
||||
androidApps = androidApps,
|
||||
hudOn = hudOn,
|
||||
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
|
||||
frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier,
|
||||
lsfgReady = LsfgNative.isInstalled(this@SessionActivity),
|
||||
oscMode = oscMode, touchMode = touchMode,
|
||||
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
|
||||
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
|
||||
shapeMode = shapeMode, fexPreset = fexPreset,
|
||||
secondScreenMode = secondScreenMode,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
|
||||
onFrameGenPick = { engine, multiplier ->
|
||||
FrameGen.set(this@SessionActivity, engine, multiplier)
|
||||
readPrefs()
|
||||
applyFrameGen()
|
||||
},
|
||||
onKeyboard = { drawerOpen = false; keyboard?.toggle() },
|
||||
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() },
|
||||
onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen },
|
||||
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
|
||||
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({
|
||||
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
|
||||
// The desktop with Steam's desktop client in it, in this session's place: the
|
||||
// session ends with status 0 and onSessionEnded starts the relaunch (Stop's
|
||||
// finish() would skip it).
|
||||
onSwitchToDesktop = if (SessionState.mode == SessionService.MODE_STEAM) ({
|
||||
drawerOpen = false
|
||||
padBridge?.triggerQam()
|
||||
SessionState.relaunch = Intent(this@SessionActivity, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop")
|
||||
SessionService.stop(this@SessionActivity)
|
||||
}) else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
|
||||
onSuspendPolicy = { policy ->
|
||||
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
|
||||
suspendPolicy = policy
|
||||
SessionService.suspendPolicyChanged(this@SessionActivity)
|
||||
},
|
||||
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
||||
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
|
||||
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
||||
onSecondScreenMode = ::selectSecondScreenMode,
|
||||
onSecondScreenDisplay = ::selectSecondScreenDisplay,
|
||||
onLaunchAndroidApp = { app ->
|
||||
onLaunchAndroidApp = { app, displayId ->
|
||||
drawerOpen = false
|
||||
try {
|
||||
HomeApp.launch(this@SessionActivity, app)
|
||||
HomeApp.launch(this@SessionActivity, app, displayId)
|
||||
} catch (_: Exception) {
|
||||
Toast.makeText(this@SessionActivity, "Could not open ${app.label}", Toast.LENGTH_SHORT).show()
|
||||
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
|
||||
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
|
||||
Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
},
|
||||
onBackground = { drawerOpen = false; moveTaskToBack(true) },
|
||||
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
||||
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
||||
onClose = { drawerOpen = false },
|
||||
components = drawerComponents,
|
||||
onComponentsRefresh = { refreshDrawerComponents() },
|
||||
onComponentSwap = { pid, comp, value -> swapDrawerComponent(pid, comp, value) },
|
||||
))
|
||||
if (SessionState.suspended) SessionPausedOverlay {
|
||||
SessionService.resume(this@SessionActivity)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
root.addView(sessionOverlay)
|
||||
setContentView(root)
|
||||
handleHomeGuideIntent(intent)
|
||||
|
||||
updateOnScreenControls()
|
||||
WaylandCompositor.setFirstFrameListener {
|
||||
SessionState.firstFrameSeen = true
|
||||
SessionEvents.firstFrame()
|
||||
runOnUiThread {
|
||||
loading.visible = false
|
||||
hud.start()
|
||||
}
|
||||
}
|
||||
SessionEvents.markReadyIfPossible()
|
||||
SessionState.endListener = endListener
|
||||
// Back opens the drawer (and closes it again). Leaving the session running in the
|
||||
// background and ending it are both actions in there, so neither can happen by accident
|
||||
// from a button a game might also be reading.
|
||||
// A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord.
|
||||
// The single action waits out the double-press window so the two actions stay distinct.
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
drawerOpen = !drawerOpen
|
||||
// The PC keyboard closes first (B on a controller), then Back is the drawer again.
|
||||
when {
|
||||
drawerOpen -> drawerOpen = false
|
||||
pcKeyboardOpen -> pcKeyboardOpen = false
|
||||
else -> routeBackAction()
|
||||
}
|
||||
}
|
||||
})
|
||||
watchSession()
|
||||
@@ -266,6 +398,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}, 90)
|
||||
}
|
||||
|
||||
private fun triggerSteamQam() {
|
||||
drawerOpen = false
|
||||
padBridge?.triggerQam()
|
||||
}
|
||||
|
||||
private fun routeBackAction() {
|
||||
pendingBackAction?.let { pending ->
|
||||
uiHandler.removeCallbacks(pending)
|
||||
pendingBackAction = null
|
||||
performBackAction(double = true)
|
||||
return
|
||||
}
|
||||
val pending = Runnable {
|
||||
pendingBackAction = null
|
||||
performBackAction(double = false)
|
||||
}
|
||||
pendingBackAction = pending
|
||||
uiHandler.postDelayed(pending, BACK_DOUBLE_PRESS_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
private fun performBackAction(double: Boolean) {
|
||||
val isSteam = SessionState.mode == SessionService.MODE_STEAM
|
||||
val opensQam = isSteam && (double xor backActionsInverted)
|
||||
if (opensQam) triggerSteamQam() else drawerOpen = !drawerOpen
|
||||
}
|
||||
|
||||
private fun handleHomeGuideIntent(incoming: Intent?) {
|
||||
if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return
|
||||
incoming.action = null
|
||||
@@ -273,15 +431,76 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
|
||||
}
|
||||
|
||||
|
||||
/** Re-reads the Protons for the drawer's Components tab, first running swaps a closed game was holding back. */
|
||||
private fun refreshDrawerComponents() {
|
||||
Thread({
|
||||
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
|
||||
val snap = runCatching { ComponentsManager.snapshot(this) }.getOrNull()
|
||||
uiHandler.post {
|
||||
drawerComponents = snap
|
||||
if (applied.isNotEmpty()) android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "drawer-components").start()
|
||||
}
|
||||
|
||||
private fun swapDrawerComponent(protonId: String, comp: String, value: String) {
|
||||
Thread({
|
||||
val message = runCatching {
|
||||
val snap = ComponentsManager.snapshot(this)
|
||||
val queued = snap.protons.firstOrNull { it.proton.id == protonId }?.components?.get(comp)?.queued
|
||||
val active = snap.protons.firstOrNull { it.proton.id == protonId }?.components?.get(comp)?.activeFile
|
||||
val build = snap.protons.firstOrNull { it.proton.id == protonId }?.proton?.version?.let(ComponentsManager::safeName)
|
||||
val current = active ?: "orig:$build"
|
||||
if (queued != null && value == current) {
|
||||
// Picking what is already in place again cancels the swap waiting for the game.
|
||||
ComponentsManager.cancelQueued(this, protonId, comp); "The waiting swap was cancelled."
|
||||
} else if (value.startsWith("orig:")) ComponentsManager.restore(this, protonId, comp, value.removePrefix("orig:"))
|
||||
else ComponentsManager.swap(this, protonId, value)
|
||||
}.getOrElse { e -> "Swap failed: ${e.message ?: e.javaClass.simpleName}" }
|
||||
uiHandler.post {
|
||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
refreshDrawerComponents()
|
||||
}
|
||||
}, "drawer-components-swap").start()
|
||||
}
|
||||
|
||||
private fun shareCurrentSessionLogs() {
|
||||
val folder = SessionPaths.current()
|
||||
if (folder == null || !folder.isDirectory) {
|
||||
Toast.makeText(this, "No logs for this session.", Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
val zip = runCatching { SessionLogShare.zipFolder(this, folder) }
|
||||
.onFailure { Log.w(TAG, "could not package current session logs", it) }
|
||||
.getOrNull()
|
||||
uiHandler.post {
|
||||
if (zip == null) {
|
||||
Toast.makeText(this, "Could not create the session log archive.", Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
runCatching { startActivity(SessionLogShare.shareIntent(this, zip)) }
|
||||
.onFailure {
|
||||
Log.w(TAG, "could not share current session logs", it)
|
||||
Toast.makeText(this, "Could not share the session logs.", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}, "share-session-logs").start()
|
||||
}
|
||||
|
||||
private fun readPrefs() {
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
fillScreen = SessionPrefs.forceFullscreen(this)
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
frameGenEngine = FrameGen.engine(this)
|
||||
frameGenMultiplier = FrameGen.multiplier(this)
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
shapeMode = SessionPrefs.shapeMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
}
|
||||
|
||||
// ── Compositor ──────────────────────────────────────────────────────────────────────────
|
||||
@@ -295,14 +514,46 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
* starts when they are in. Nothing else changes.
|
||||
*/
|
||||
private fun installThenStart(runtime: Boolean, desktop: Boolean) {
|
||||
if (SessionState.stopRequested) return
|
||||
installingRuntime = true
|
||||
SessionState.installing = if (runtime) "runtime" else "desktop"
|
||||
SessionEvents.transition(
|
||||
SessionPhase.INSTALLING_RUNTIME,
|
||||
if (runtime) "runtime.installing" else "desktop.installing",
|
||||
mapOf("component" to SessionState.installing),
|
||||
)
|
||||
loading.step = if (runtime) "downloading the Linux runtime" else "downloading the desktop"
|
||||
loading.percent = -1
|
||||
Thread({
|
||||
val problem = (if (runtime) installRuntime() else null) ?: (if (desktop) installDesktop() else null)
|
||||
var failedComponent: String? = null
|
||||
var problem: String? = null
|
||||
if (runtime) {
|
||||
problem = installRuntime()
|
||||
if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime"
|
||||
}
|
||||
if (problem == null && desktop && !SessionState.stopRequested) {
|
||||
SessionState.installing = "desktop"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "desktop.installing", mapOf("component" to "desktop"))
|
||||
problem = installDesktop()
|
||||
if (problem == null) SessionEvents.record("desktop.ready") else failedComponent = "desktop"
|
||||
}
|
||||
uiHandler.post {
|
||||
installingRuntime = false
|
||||
if (problem != null) { loading.showEnded(problem); return@post }
|
||||
SessionState.installing = null
|
||||
if (SessionState.stopRequested) {
|
||||
SessionState.stopRequested = false
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
|
||||
collectStartArtifacts("session start cancelled")
|
||||
finish()
|
||||
return@post
|
||||
}
|
||||
if (problem != null) {
|
||||
val code = if (failedComponent == "runtime") "RUNTIME_INSTALL_FAILED" else "DESKTOP_INSTALL_FAILED"
|
||||
SessionEvents.fail(code, problem)
|
||||
collectStartArtifacts("session start failed")
|
||||
loading.showEnded(problem)
|
||||
return@post
|
||||
}
|
||||
loading.percent = -1
|
||||
loading.step = "Starting the session…"
|
||||
// The surface may have come and gone while the download ran; start on the live one.
|
||||
@@ -311,6 +562,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}, "runtime-install").start()
|
||||
}
|
||||
|
||||
private fun collectStartArtifacts(reason: String) {
|
||||
val dir = SessionPaths.take() ?: return
|
||||
val appContext = applicationContext
|
||||
Thread({
|
||||
SessionArtifacts.collect(appContext, dir, reason)
|
||||
SessionPaths.release(appContext, dir)
|
||||
}, "session-failure-artifacts").start()
|
||||
}
|
||||
|
||||
/** Reports one package's download on the loading screen: "<what> · 332 of 791 MB", checking, unpacking. */
|
||||
private fun progressFor(what: String, mb: Long) = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener { stage, p ->
|
||||
uiHandler.post {
|
||||
@@ -343,7 +603,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
if (installingRuntime) return
|
||||
if (installingRuntime || SessionState.stopRequested) return
|
||||
if (!SessionState.running) {
|
||||
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
|
||||
}
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
// The compositor hands this keymap to wl_keyboard clients, which is how the guest reads
|
||||
// the evdev codes we inject.
|
||||
@@ -360,7 +623,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// was 16:9 - the picture came back squashed sideways. While a session runs, keep its size.
|
||||
val size = if (SessionState.running) SessionState.outputSize else outputSize()
|
||||
SessionState.outputSize = size
|
||||
onScreenControls?.setPicture(drawnRect())
|
||||
if (!SessionState.running) SessionState.refreshHz = refreshHz()
|
||||
// Letterbox, never stretch or crop: the output can be a different shape from the panel,
|
||||
// and a game's picture must keep its proportions with bars, not lose its edges.
|
||||
@@ -407,6 +669,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
|
||||
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(),
|
||||
)
|
||||
if (!SessionState.running) SessionEvents.record("compositor.started")
|
||||
// ADPF: the compositor thread's frame intervals go to the power HAL against the panel's
|
||||
// period, so a long frame raises CPU clocks now rather than after the load averages up.
|
||||
PerfHints.arm(this, refreshHz())
|
||||
@@ -416,6 +679,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// start nothing, and leave the loading panel counting up over a dead session.
|
||||
if (!SessionState.running) {
|
||||
CompositorHost.newSession()
|
||||
SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting")
|
||||
SessionService.start(
|
||||
this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM,
|
||||
intent.getStringExtra(SessionService.EXTRA_PROGRAM),
|
||||
@@ -434,8 +698,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val resized = surfaceW != 0 && (width != surfaceW || height != surfaceH)
|
||||
surfaceW = width
|
||||
surfaceH = height
|
||||
// The on-screen controls follow the picture: into the bars beside or under it when there are any.
|
||||
onScreenControls?.setPicture(drawnRect())
|
||||
if (resized) {
|
||||
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
|
||||
CompositorHost.resize(holder.surface) { applyFrameGen() }
|
||||
@@ -470,7 +732,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// Wider than 16:9 is fine - games and the client cope with a phone's 20:9 - so the
|
||||
// panel's aspect is kept above that, unless the user pinned 16:9 for a foldable, and the
|
||||
// compositor letterboxes onto a squarer panel.
|
||||
// "Exactly this panel" drops that floor, for a 4:3 or 3:2 handheld whose games should
|
||||
// "Match screen" drops that floor, for a 4:3 or 3:2 handheld whose games should
|
||||
// fill it.
|
||||
val aspect = when (SessionPrefs.shapeMode(this)) {
|
||||
SessionPrefs.SHAPE_WIDE -> 16f / 9f
|
||||
@@ -484,7 +746,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
|
||||
// A custom resolution is taken as given; the compositor fits it to the panel.
|
||||
SessionPrefs.customResolution(this, mode)?.let { return it }
|
||||
val cap = SessionPrefs.resolutionCap(this, mode)
|
||||
// An emulator whose frames cost next to nothing (Library.drawsAtPanel) gets the panel,
|
||||
// unless the user chose a resolution for the mode.
|
||||
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
val cap = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
|
||||
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode)) 0
|
||||
else SessionPrefs.resolutionCap(this, mode)
|
||||
val height = (if (cap <= 0) panelH else minOf(panelH, cap.toFloat())).toInt()
|
||||
val width = (height * aspect).toInt()
|
||||
// Odd sizes upset the scaler; both dimensions even is what every mode here would be.
|
||||
@@ -518,6 +785,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val poll = object : Runnable {
|
||||
override fun run() {
|
||||
if (!watching) return
|
||||
if (SessionState.stopRequested && !SessionState.running && !installingRuntime) {
|
||||
SessionState.stopRequested = false
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
|
||||
collectStartArtifacts("session start cancelled")
|
||||
finish()
|
||||
return
|
||||
}
|
||||
if (loading.visible && !loading.ended) {
|
||||
if (!installingRuntime) loading.update(this@SessionActivity, SessionState.logFile)
|
||||
if (ticks++ % 2 == 0) loading.tick()
|
||||
@@ -533,11 +807,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (status == 0) {
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
// A session the guest asked for (the desktop's Steam launchers) takes this one's
|
||||
// place: the compositor stays, a new activity attaches and starts the service.
|
||||
// A session asked for in this one's place (the desktop's Steam launchers, the
|
||||
// drawer's DESKTOP) starts here: this activity restarts on its intent, as an agent
|
||||
// start does. startActivity(next) could not do it - the activity is singleTop, so
|
||||
// the request landed in this instance's onNewIntent and went with its finish().
|
||||
SessionState.relaunch?.let { next ->
|
||||
SessionState.relaunch = null
|
||||
startActivity(next)
|
||||
setIntent(next)
|
||||
recreate()
|
||||
return@runOnUiThread
|
||||
}
|
||||
finish()
|
||||
}
|
||||
@@ -609,10 +887,41 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
// With the drawer open the controller drives the drawer, not the game: Android's own
|
||||
// handling moves focus with the d-pad and stick, and its fallbacks make A select and B Back
|
||||
// (which closes the drawer) - the same as on the app's main screen.
|
||||
if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event)
|
||||
val fromController = event.device != null && PadBridge.isFromController(event.device)
|
||||
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
|
||||
if (drawerOpen && !drawerControllerActive) sessionOverlay.requestFocus()
|
||||
drawerControllerActive = true
|
||||
}
|
||||
if (drawerOpen) {
|
||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
drawerPage = (drawerPage + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else DRAWER_PAGES - 1) % DRAWER_PAGES
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
return true
|
||||
}
|
||||
val handled = super.dispatchKeyEvent(event)
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
Log.i(TAG, "drawer key=${KeyEvent.keyCodeToString(event.keyCode)} handled=$handled viewFocused=${sessionOverlay.hasFocus()}")
|
||||
}
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK) {
|
||||
if (!handled && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) drawerOpen = false
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
return true
|
||||
}
|
||||
val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START
|
||||
val resumeKeyId = event.deviceId to event.keyCode
|
||||
if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
resumeKeysDown.add(resumeKeyId)
|
||||
if (event.repeatCount == 0 && SessionState.suspended) SessionService.resume(this)
|
||||
} else if (event.action == KeyEvent.ACTION_UP) {
|
||||
resumeKeysDown.remove(resumeKeyId)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event)
|
||||
if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true
|
||||
// A hardware keyboard, forwarded to the compositor's wl_keyboard. Back is left to the
|
||||
// activity, which opens the drawer.
|
||||
@@ -654,18 +963,102 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event)
|
||||
if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) {
|
||||
if (!drawerControllerActive) sessionOverlay.requestFocus()
|
||||
drawerControllerActive = true
|
||||
if (event.actionMasked == MotionEvent.ACTION_MOVE &&
|
||||
event.isFromSource(InputDevice.SOURCE_JOYSTICK)
|
||||
) {
|
||||
dispatchDrawerDirection(event)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection()
|
||||
if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event)
|
||||
if (padBridge?.onMotionEvent(event) == true) return true
|
||||
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
/**
|
||||
* The pointer. Touch goes through [PointerGestures] (tap, hold, drag, two-finger scroll); a
|
||||
* mouse arrives with real buttons and a wheel and is forwarded as it is. Every position is
|
||||
* mapped through the letterboxed rectangle into the compositor's fixed 1920x1080 pointer
|
||||
* space, and the arrow is drawn where the app last sent the pointer.
|
||||
*/
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
drawerControllerActive = false
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
private fun dispatchDrawerDirection(event: MotionEvent) {
|
||||
val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X)
|
||||
val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
|
||||
val hatActive = maxOf(abs(hatX), abs(hatY)) >= DRAWER_HAT_THRESHOLD
|
||||
val x = if (hatActive) hatX else centeredStickAxis(event, MotionEvent.AXIS_X)
|
||||
val y = if (hatActive) hatY else centeredStickAxis(event, MotionEvent.AXIS_Y)
|
||||
val directionThreshold = if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) {
|
||||
DRAWER_STICK_ENTER_THRESHOLD
|
||||
} else {
|
||||
DRAWER_STICK_EXIT_THRESHOLD
|
||||
}
|
||||
val previousWasHorizontal = drawerDirectionKey == KeyEvent.KEYCODE_DPAD_LEFT ||
|
||||
drawerDirectionKey == KeyEvent.KEYCODE_DPAD_RIGHT
|
||||
val horizontalWins = if (previousWasHorizontal) {
|
||||
abs(x) >= abs(y) * DRAWER_ACTIVE_DIRECTION_MARGIN
|
||||
} else {
|
||||
abs(x) > abs(y) * DRAWER_DIRECTION_MARGIN
|
||||
}
|
||||
val keyCode = when {
|
||||
maxOf(abs(x), abs(y)) < directionThreshold -> KeyEvent.KEYCODE_UNKNOWN
|
||||
horizontalWins && x < 0f -> KeyEvent.KEYCODE_DPAD_LEFT
|
||||
horizontalWins -> KeyEvent.KEYCODE_DPAD_RIGHT
|
||||
y < 0f -> KeyEvent.KEYCODE_DPAD_UP
|
||||
else -> KeyEvent.KEYCODE_DPAD_DOWN
|
||||
}
|
||||
val now = SystemClock.uptimeMillis()
|
||||
if (keyCode == drawerDirectionKey) return
|
||||
|
||||
Log.i(TAG, "drawer axis source=${event.source} x=$x y=$y direction=$keyCode")
|
||||
releaseDrawerDirection()
|
||||
if (keyCode == KeyEvent.KEYCODE_UNKNOWN) return
|
||||
|
||||
drawerDirectionKey = keyCode
|
||||
drawerDirectionDeviceId = event.deviceId
|
||||
drawerDirectionDownTime = now
|
||||
drawerDirectionRepeatCount = 0
|
||||
dispatchDrawerKey(KeyEvent.ACTION_DOWN, 0, now)
|
||||
uiHandler.postDelayed(drawerDirectionRepeat, drawerFirstRepeatDelayMs)
|
||||
}
|
||||
|
||||
/** Use Android's per-device flat region, then rescale the remaining stick travel to 0..1. */
|
||||
private fun centeredStickAxis(event: MotionEvent, axis: Int): Float {
|
||||
val value = event.getAxisValue(axis)
|
||||
val flat = (event.device?.getMotionRange(axis, event.source)?.flat ?: 0f)
|
||||
.coerceIn(0f, 0.95f)
|
||||
val magnitude = abs(value)
|
||||
if (magnitude <= flat) return 0f
|
||||
|
||||
val centered = ((magnitude - flat) / (1f - flat)).coerceIn(0f, 1f)
|
||||
return if (value < 0f) -centered else centered
|
||||
}
|
||||
|
||||
private fun releaseDrawerDirection() {
|
||||
uiHandler.removeCallbacks(drawerDirectionRepeat)
|
||||
if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) return
|
||||
dispatchDrawerKey(KeyEvent.ACTION_UP, 0, SystemClock.uptimeMillis())
|
||||
drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
|
||||
drawerDirectionDeviceId = -1
|
||||
drawerDirectionRepeatCount = 0
|
||||
}
|
||||
|
||||
private fun dispatchDrawerKey(action: Int, repeatCount: Int, eventTime: Long) {
|
||||
val event = KeyEvent(
|
||||
drawerDirectionDownTime, eventTime, action, drawerDirectionKey,
|
||||
repeatCount, 0, drawerDirectionDeviceId, 0, 0, InputDevice.SOURCE_DPAD,
|
||||
)
|
||||
if (action == KeyEvent.ACTION_DOWN && repeatCount == 0) {
|
||||
Log.i(TAG, "drawer synthetic key=${KeyEvent.keyCodeToString(drawerDirectionKey)} viewFocused=${sessionOverlay.hasFocus()}")
|
||||
}
|
||||
super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
private val pointerListener = object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) = movePointer(x, y)
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
@@ -694,25 +1087,63 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
showCursor(x.coerceIn(left, left + drawnW), y.coerceIn(top, top + drawnH))
|
||||
}
|
||||
|
||||
/** The arrow stays on a desktop; in a Steam session it shows for a moment after each move. */
|
||||
/**
|
||||
* The arrow stays on a desktop; in a Steam session it shows for a moment after each move. While
|
||||
* a controller is driving (input in the last [CURSOR_PAD_HOLD_MS]) it stays hidden, so a touch
|
||||
* during play does not flash it up - Bannerlator's rule for its Wayland pointer.
|
||||
*/
|
||||
private fun showCursor(x: Float, y: Float) {
|
||||
cursorPos = androidx.compose.ui.geometry.Offset(x, y)
|
||||
syncClientCursor()
|
||||
uiHandler.removeCallbacks(cursorResync)
|
||||
uiHandler.postDelayed(cursorResync, 60)
|
||||
// A program that asked for no pointer (a mouse-look game) wins over everything below.
|
||||
if (clientHidesCursor) { cursorVisible = false; return }
|
||||
if (android.os.SystemClock.uptimeMillis() - lastPadInputMs < CURSOR_PAD_HOLD_MS) return
|
||||
cursorVisible = true
|
||||
uiHandler.removeCallbacks(cursorHide)
|
||||
if (SessionState.mode == SessionService.MODE_STEAM && SessionState.steamUi != "desktop") uiHandler.postDelayed(cursorHide, 2500)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls the program's pointer (wl_pointer.set_cursor) if it changed: labwc's resize arrows at a
|
||||
* window's edges and corners, a text field's I-beam, or a request for no pointer. Serial 0 = no
|
||||
* program has set one yet, and the built-in arrow stays. Returns true when something changed.
|
||||
*/
|
||||
private fun syncClientCursor(): Boolean {
|
||||
if (!CompositorHost.isStarted) return false
|
||||
val n = WaylandCompositor.nativeCursorSnapshot(cursorBuf)
|
||||
if (n < 6) return false
|
||||
val serial = cursorBuf[0]
|
||||
if (serial == 0 || serial == cursorSerial) return false
|
||||
cursorSerial = serial
|
||||
clientHidesCursor = cursorBuf[1] != 0
|
||||
if (clientHidesCursor) return true
|
||||
val w = cursorBuf[2]
|
||||
val h = cursorBuf[3]
|
||||
if (w <= 0 || h <= 0 || n < 6 + w * h) return false
|
||||
val bitmap = try {
|
||||
android.graphics.Bitmap.createBitmap(cursorBuf, 6, w, w, h, android.graphics.Bitmap.Config.ARGB_8888)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "cursor bitmap failed", e)
|
||||
return false
|
||||
}
|
||||
cursorImage = bitmap.asImageBitmap()
|
||||
cursorHotX = cursorBuf[4]
|
||||
cursorHotY = cursorBuf[5]
|
||||
// Session pixels -> screen pixels, as the session's picture is scaled (movePointer).
|
||||
val width = surfaceView.width.takeIf { it > 0 }
|
||||
val height = surfaceView.height.takeIf { it > 0 }
|
||||
val out = SessionState.outputSize
|
||||
if (width != null && height != null)
|
||||
cursorImageScale = minOf(width / out.first.toFloat(), height / out.second.toFloat())
|
||||
return true
|
||||
}
|
||||
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
if (!::displayManager.isInitialized) return
|
||||
val primaryId = display?.displayId ?: windowManager.defaultDisplay.displayId
|
||||
val candidates = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION)
|
||||
.asSequence()
|
||||
.filter { it.isValid && it.displayId != primaryId && (it.flags and Display.FLAG_PRESENTATION) != 0 }
|
||||
.map { target ->
|
||||
val mode = target.mode
|
||||
SecondScreenDisplay(target.displayId, "${target.name} · ${mode.physicalWidth}×${mode.physicalHeight}")
|
||||
}
|
||||
.toList()
|
||||
val candidates = SecondScreenDisplays.available(displayManager, primaryId)
|
||||
val oldIds = secondScreenDisplays.map { it.id }.toSet()
|
||||
secondScreenDisplays = candidates
|
||||
val newIds = candidates.map { it.id }.toSet()
|
||||
@@ -773,6 +1204,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onQam = {
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam()
|
||||
},
|
||||
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
|
||||
)
|
||||
secondScreenPresentation = presentation
|
||||
}
|
||||
@@ -833,7 +1265,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
return touchpad.onTouch(event)
|
||||
}
|
||||
return gestures.onTouch(event)
|
||||
val rect = drawnRect() ?: return false
|
||||
fun sendTouch(action: Int, index: Int) {
|
||||
val x = ((event.getX(index) - rect.left) / rect.width()).coerceIn(0f, 1f)
|
||||
val y = ((event.getY(index) - rect.top) / rect.height()).coerceIn(0f, 1f)
|
||||
WaylandCompositor.nativeSendTouch(action, event.getPointerId(index), (x * 1919f).toInt(), (y * 1079f).toInt())
|
||||
}
|
||||
when (event.actionMasked) {
|
||||
// A first finger starts a new gesture, and Android has ended every earlier one: whatever
|
||||
// the compositor still holds (an up lost to the drawer opening mid-touch) goes first.
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||
sendTouch(0, event.actionIndex)
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_DOWN -> sendTouch(0, event.actionIndex)
|
||||
MotionEvent.ACTION_MOVE -> for (index in 0 until event.pointerCount) sendTouch(1, index)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> sendTouch(2, event.actionIndex)
|
||||
MotionEvent.ACTION_CANCEL -> WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||
else -> return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** A mouse: hover moves, buttons press, the wheel scrolls. Android sends buttons as touch
|
||||
@@ -874,7 +1325,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionPrefs.OSC_ALWAYS -> true
|
||||
SessionPrefs.OSC_STEAM_QAM -> true
|
||||
SessionPrefs.OSC_NEVER -> false
|
||||
else -> !PadBridge.anyControllerConnected()
|
||||
// Auto: the touch pad when there is no controller - except on the desktop, where the
|
||||
// screen is a touchpad for the pointer and a pad over it would be in the way. A game
|
||||
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
|
||||
else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
|
||||
}
|
||||
if (show == (controls.visibility == View.VISIBLE)) return
|
||||
if (!show) controls.releaseAll()
|
||||
@@ -905,6 +1359,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onNewIntent(intent: android.content.Intent) {
|
||||
super.onNewIntent(intent)
|
||||
if (intent.action == SessionService.ACTION_AGENT_START) {
|
||||
if (SessionState.running || SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
Log.w(TAG, "ignoring agent start while session phase is ${SessionState.phase}")
|
||||
return
|
||||
}
|
||||
setIntent(intent)
|
||||
recreate()
|
||||
return
|
||||
}
|
||||
setIntent(intent)
|
||||
if (intent.action == SessionService.ACTION_HOME_GUIDE) {
|
||||
handleHomeGuideIntent(intent)
|
||||
@@ -923,6 +1386,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
(getSystemService(INPUT_SERVICE) as? InputManager)
|
||||
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
|
||||
onScreenControls?.reload()
|
||||
updateOnScreenControls()
|
||||
readPrefs()
|
||||
if (CompositorHost.isStarted) applyFrameGen()
|
||||
@@ -930,12 +1394,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onPause() {
|
||||
(getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener)
|
||||
releaseDrawerDirection()
|
||||
// A button held when the app goes away would stay held in the ring for the whole session.
|
||||
onScreenControls?.releaseAll()
|
||||
keyboard?.takeIf { it.shown }?.hide()
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return
|
||||
val decor = window.decorView
|
||||
decor.requestUnbufferedDispatch(UNBUFFERED_SOURCES)
|
||||
decor.viewTreeObserver.addOnGlobalFocusChangeListener { _, _ -> decor.post { decor.requestUnbufferedDispatch(UNBUFFERED_SOURCES) } }
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) goFullscreen()
|
||||
@@ -964,6 +1437,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// Deliberately does NOT end the session: this activity can be destroyed while the user is
|
||||
// in another app, and the whole point of the service is that Steam survives that.
|
||||
watching = false
|
||||
releaseDrawerDirection()
|
||||
pendingBackAction?.let(uiHandler::removeCallbacks)
|
||||
pendingBackAction = null
|
||||
closeSecondScreen(reset = true)
|
||||
if (::hud.isInitialized) hud.stop()
|
||||
padBridge?.stop()
|
||||
@@ -980,6 +1456,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionActivity"
|
||||
private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION
|
||||
private const val BACK_DOUBLE_PRESS_TIMEOUT_MS = 500L
|
||||
private const val CURSOR_PAD_HOLD_MS = 1200L
|
||||
private const val DRAWER_HAT_THRESHOLD = 0.5f
|
||||
private const val DRAWER_STICK_ENTER_THRESHOLD = 0.55f
|
||||
private const val DRAWER_STICK_EXIT_THRESHOLD = 0.35f
|
||||
private const val DRAWER_DIRECTION_MARGIN = 1.15f
|
||||
private const val DRAWER_ACTIVE_DIRECTION_MARGIN = 0.85f
|
||||
private const val DRAWER_SLOW_REPEAT_FLOOR_MS = 240L
|
||||
private const val DRAWER_FAST_REPEAT_INTERVAL_MS = 90L
|
||||
private const val DRAWER_REPEAT_ACCELERATION_MS = 1_400L
|
||||
/** Compositor scale modes (Container.FULLSCREEN_* values): 1 = fit with bars, centred. */
|
||||
private const val SCALE_FIT = 1
|
||||
private const val ALIGN_CENTER = 0
|
||||
|
||||
@@ -5,7 +5,6 @@ import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
@@ -149,6 +148,7 @@ object DeviceReport {
|
||||
k("Skip xalia", SessionPrefs.noXalia(context))
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Stretch games to fill", SessionPrefs.forceFullscreen(context))
|
||||
k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic")
|
||||
k("Microphone", SessionPrefs.micEnabled(context))
|
||||
k("On-screen controls", SessionPrefs.oscMode(context))
|
||||
@@ -161,21 +161,7 @@ object DeviceReport {
|
||||
})
|
||||
|
||||
h("Android process limits")
|
||||
// Android 12 kills "phantom" processes - the children an app forks itself rather than
|
||||
// starting through the framework - once there are more than a handful of them. A session is
|
||||
// nothing but those: proot, gamescope, Xwayland, the client, its helpers, Wine, FEX. Where
|
||||
// this is left on, the OS kills the session and nothing in our logs says why, because
|
||||
// nothing in the session did it. Some ROMs expose it in Developer options as a
|
||||
// "restrict child processes" switch; otherwise it is
|
||||
// adb shell settings put global settings_enable_monitor_phantom_procs false
|
||||
val phantom = runCatching {
|
||||
Settings.Global.getString(context.contentResolver, "settings_enable_monitor_phantom_procs")
|
||||
}.getOrNull()
|
||||
k("Phantom proc monitor", when (phantom?.lowercase()) {
|
||||
"false", "0" -> "disabled (good - the OS will not kill the session's children)"
|
||||
null, "" -> "not set (ROM default, usually ENABLED - see the note below)"
|
||||
else -> "ENABLED (the OS may kill the session with no log; turn off \"restrict child processes\")"
|
||||
})
|
||||
k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context.contentResolver)))
|
||||
|
||||
h("Device switch files in Download")
|
||||
for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver",
|
||||
|
||||
@@ -12,9 +12,16 @@ package com.droiddeck.launcher.core
|
||||
* client logs; the account-name registration is left out because this app never learns it.
|
||||
*
|
||||
* What is deliberately KEPT, because it is what makes a log worth reading: EResult codes, CM host
|
||||
* names and IP addresses, timings, token expiry dates, app IDs, pids, connection-state changes and
|
||||
* file paths. A SteamID is masked rather than deleted - first four and last four digits survive -
|
||||
* so a reader can still tell two accounts' lines apart without the value identifying either.
|
||||
* names and Valve's server addresses, timings, token expiry dates, app IDs, pids, connection-state
|
||||
* changes and file paths. A SteamID is masked rather than deleted - first four and last four digits
|
||||
* survive - so a reader can still tell two accounts' lines apart without the value identifying either.
|
||||
*
|
||||
* The device's OWN addresses are not kept: the client's IPv6 check logs "external address <ours>"
|
||||
* about twenty times a session, and a public IPv6 address is the user's. [learnOwnAddresses] reads
|
||||
* the link the session was given (etc/bannerlator-net) and every address on the same /64 - privacy
|
||||
* addresses rotate inside it - or an own public IPv4 is replaced wherever it appears. Likewise every
|
||||
* Steam account and persona name on the device ([learnAccounts]), for users who sign in with an
|
||||
* account name rather than an email.
|
||||
*/
|
||||
object LogRedactor {
|
||||
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
||||
@@ -48,6 +55,145 @@ object LogRedactor {
|
||||
private val LONG_TOKEN = Regex("[A-Za-z0-9_\\-]{88,}")
|
||||
private val STEAMID64 = Regex("\\b(76561)(\\d{8})(\\d{4})\\b")
|
||||
private val STEAMID3 = Regex("\\[U:1:(\\d+)]")
|
||||
/** "external address 2607:..." / "external IP: 203.0.113.9" - the client stating ours. */
|
||||
private val EXTERNAL_ADDR = Regex("(?i)(external\\s+(?:ip\\s+)?address\\s*[:=]?\\s*|external\\s+ip\\s*[:=]?\\s*)([0-9A-Fa-f:.]{7,})")
|
||||
private val IPV4 = Regex("(?<![0-9.])(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})(?![0-9.])")
|
||||
/** An IPv6 literal: "::" somewhere, or all eight groups (a clock's 10:03:05 is neither). */
|
||||
private val IPV6 = Regex("(?<![0-9A-Za-z:])[0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7}(?:%[A-Za-z0-9_.]+)?(?![0-9A-Za-z:])")
|
||||
|
||||
/**
|
||||
* The account a Steam UI login line names ("Login: OnLoginStateChange <account> 2 1 0 0"): a
|
||||
* user who signs in with a plain account name, not an email, had it in every log. The single
|
||||
* space then a non-space keeps "OnLoginStateChange 0 1 0 0" (no account yet) as it is.
|
||||
*/
|
||||
private val LOGIN_STATE = Regex("(OnLoginStateChange )(\\S+)")
|
||||
private val LOGIN_USERS = Regex("(OnLoginUsersChanged )(\\S.*)$")
|
||||
|
||||
/** The device's Steam accounts and persona names as patterns (see [learnAccounts]). */
|
||||
@Volatile
|
||||
private var accounts: List<Regex> = emptyList()
|
||||
|
||||
/**
|
||||
* Learns every Steam account on the device from the client's loginusers.vdf - its AccountName
|
||||
* and PersonaName - so they are replaced wherever a log mentions them, whoever the user is.
|
||||
* Names under three characters are skipped: blanking every "a" would ruin a log.
|
||||
*/
|
||||
fun learnAccounts(loginUsers: java.io.File) {
|
||||
val found = ArrayList<Regex>()
|
||||
try {
|
||||
if (loginUsers.isFile) {
|
||||
val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"")
|
||||
kv.findAll(loginUsers.readText()).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.distinct().forEach { name ->
|
||||
found += Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])")
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
return
|
||||
}
|
||||
accounts = found
|
||||
}
|
||||
|
||||
/** Everything the session's runtime can tell about whose logs these are: addresses and accounts. */
|
||||
fun learnFromRuntime(root: java.io.File) {
|
||||
learnOwnAddresses(java.io.File(root, "etc/bannerlator-net"))
|
||||
learnAccounts(java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"))
|
||||
}
|
||||
|
||||
/** This device's public addresses as patterns (see [learnOwnAddresses]); empty until learned. */
|
||||
@Volatile
|
||||
private var own: List<Regex> = emptyList()
|
||||
|
||||
/**
|
||||
* Learns the device's addresses from the link file the app writes for the session
|
||||
* (`addr <address> <prefix>` lines). Global IPv6 become their /64, public IPv4 stay exact;
|
||||
* private, link-local and loopback addresses identify nobody and are left out.
|
||||
*/
|
||||
fun learnOwnAddresses(linkFile: java.io.File) {
|
||||
val found = ArrayList<Regex>()
|
||||
try {
|
||||
if (linkFile.isFile) linkFile.forEachLine { line ->
|
||||
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine
|
||||
when (kind(addr)) {
|
||||
"public IPv6" -> {
|
||||
val groups = expand6(addr)?.take(4) ?: return@forEachLine
|
||||
// Any spelling of an address in this /64: leading zeros dropped, :: anywhere after.
|
||||
val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) }
|
||||
found += Regex("(?i)(?<![0-9A-Fa-f:])$prefix(?::[0-9A-Fa-f]{0,4}){1,4}(?:%[A-Za-z0-9_.]+)?")
|
||||
}
|
||||
"public IPv4" -> found += Regex("(?<![0-9.])" + Regex.escape(addr) + "(?![0-9.])")
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
return
|
||||
}
|
||||
own = found
|
||||
}
|
||||
|
||||
/** "public IPv6", "private IPv4", "link-local IPv6", ... for an address literal; null if it is not one. */
|
||||
fun kind(address: String): String? {
|
||||
val a = address.substringBefore('%')
|
||||
IPV4.matchEntire(a)?.let { m ->
|
||||
val o = m.groupValues.drop(1).map { it.toInt() }
|
||||
if (o.any { it > 255 }) return null
|
||||
return when {
|
||||
o[0] == 127 -> "loopback IPv4"
|
||||
o[0] == 10 || (o[0] == 172 && o[1] in 16..31) || (o[0] == 192 && o[1] == 168) -> "private IPv4"
|
||||
o[0] == 169 && o[1] == 254 -> "link-local IPv4"
|
||||
o[0] == 100 && o[1] in 64..127 -> "carrier-NAT IPv4"
|
||||
else -> "public IPv4"
|
||||
}
|
||||
}
|
||||
val g = expand6(a) ?: return null
|
||||
val first = g[0].toInt(16)
|
||||
return when {
|
||||
g.all { it.toInt(16) == 0 } || (g.take(7).all { it.toInt(16) == 0 } && g[7].toInt(16) == 1) -> "loopback IPv6"
|
||||
first and 0xffc0 == 0xfe80 -> "link-local IPv6"
|
||||
first and 0xfe00 == 0xfc00 -> "private IPv6"
|
||||
else -> "public IPv6"
|
||||
}
|
||||
}
|
||||
|
||||
/** The eight groups of an IPv6 literal, or null. */
|
||||
private fun expand6(address: String): List<String>? {
|
||||
val a = address.substringBefore('%')
|
||||
if (!a.contains(':') || a.count { it == ':' } > 7 || a.contains(":::")) return null
|
||||
if (!a.all { it.isDigit() || it in 'a'..'f' || it in 'A'..'F' || it == ':' }) return null
|
||||
val parts = if (a.contains("::")) {
|
||||
val (head, tail) = a.split("::", limit = 2)
|
||||
val h = if (head.isEmpty()) emptyList() else head.split(':')
|
||||
val t = if (tail.isEmpty()) emptyList() else tail.split(':')
|
||||
if (h.size + t.size > 7) return null
|
||||
h + List(8 - h.size - t.size) { "0" } + t
|
||||
} else a.split(':')
|
||||
if (parts.size != 8 || parts.any { it.isEmpty() || it.length > 4 }) return null
|
||||
return parts.map { it.lowercase() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Every IP address in [text] replaced by what kind it is ("<public IPv6>"), for reports whose
|
||||
* point is the shape of the network, not its numbers.
|
||||
*/
|
||||
fun describeAddresses(text: String): String {
|
||||
var out = IPV6.replace(text) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||
out = IPV4.replace(out) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||
return out
|
||||
}
|
||||
|
||||
/** A file worth scrubbing: text (no NUL in its first 4 KB) and not huge. */
|
||||
fun isText(file: java.io.File): Boolean = try {
|
||||
file.isFile && file.length() < 64L * 1024 * 1024 && file.inputStream().use { input ->
|
||||
val buf = ByteArray(4096)
|
||||
val n = input.read(buf)
|
||||
n <= 0 || (0 until n).none { buf[it].toInt() == 0 }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
|
||||
/** [src]'s lines, scrubbed, to [out]. */
|
||||
fun scrubTo(src: java.io.File, out: java.io.Writer) {
|
||||
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
|
||||
}
|
||||
|
||||
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
|
||||
fun redact(line: String): String {
|
||||
@@ -66,6 +212,11 @@ object LogRedactor {
|
||||
val id = m.groupValues[1]
|
||||
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
|
||||
}
|
||||
out = EXTERNAL_ADDR.replace(out) { "${it.groupValues[1]}<redacted:ip>" }
|
||||
for (r in own) out = r.replace(out, "<redacted:ip>")
|
||||
out = LOGIN_STATE.replace(out) { "${it.groupValues[1]}<redacted:account>" }
|
||||
out = LOGIN_USERS.replace(out) { "${it.groupValues[1]}<redacted:account>" }
|
||||
for (r in accounts) out = r.replace(out, "<redacted:account>")
|
||||
out = EMAIL.replace(out, "<redacted:email>")
|
||||
out = RESIDUAL.replace(out) { "${it.groupValues[1]}=<redacted:token>" }
|
||||
out = LONG_TOKEN.replace(out, "<redacted:token>")
|
||||
|
||||
@@ -27,7 +27,12 @@ object NetworkReport {
|
||||
|
||||
fun write(context: Context, target: File) {
|
||||
try {
|
||||
target.writeText(build(context))
|
||||
// Addresses as their kind ("<public IPv6>"), never the numbers: a public address is the
|
||||
// user's, and this file goes into shared session logs. The session's made-up hardware
|
||||
// address is stable per device (seeded from ANDROID_ID), so it is masked too.
|
||||
val text = LogRedactor.describeAddresses(build(context))
|
||||
.replace(Regex("(?m)^(\\s*mac )\\S+"), "$1<masked>")
|
||||
target.writeText(text)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not write $target", e)
|
||||
}
|
||||
@@ -36,7 +41,7 @@ object NetworkReport {
|
||||
private fun build(context: Context): String = buildString {
|
||||
append("Network as the session starts\n")
|
||||
append("=============================\n")
|
||||
append("The SSID is deliberately not recorded. Transport, address families and DNS are.\n\n")
|
||||
append("The SSID is deliberately not recorded, and addresses appear as their kind, not their numbers.\n\n")
|
||||
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||
val network = cm?.activeNetwork
|
||||
if (cm == null || network == null) {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
|
||||
/** Android's phantom process monitor can kill the many child processes used by a Steam session. */
|
||||
enum class PhantomProcessStatus {
|
||||
NOT_APPLICABLE,
|
||||
DISABLED,
|
||||
ENABLED,
|
||||
UNSET,
|
||||
UNREADABLE,
|
||||
}
|
||||
|
||||
object PhantomProcessLimit {
|
||||
const val ADB_COMMAND = "adb shell settings put global settings_enable_monitor_phantom_procs false"
|
||||
const val SHELL_COMMAND = "settings put global settings_enable_monitor_phantom_procs false"
|
||||
private const val SETTING = "settings_enable_monitor_phantom_procs"
|
||||
|
||||
fun adbCommand(enabled: Boolean): String =
|
||||
"adb shell settings put global $SETTING ${if (enabled) "true" else "false"}"
|
||||
|
||||
fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
|
||||
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
|
||||
val value = try {
|
||||
Settings.Global.getString(resolver, SETTING)
|
||||
} catch (_: Exception) {
|
||||
return PhantomProcessStatus.UNREADABLE
|
||||
}
|
||||
return when (value?.trim()?.lowercase()) {
|
||||
"false", "0" -> PhantomProcessStatus.DISABLED
|
||||
null, "" -> PhantomProcessStatus.UNSET
|
||||
else -> PhantomProcessStatus.ENABLED
|
||||
}
|
||||
}
|
||||
|
||||
fun blocksSteam(status: PhantomProcessStatus): Boolean =
|
||||
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
|
||||
|
||||
fun title(status: PhantomProcessStatus): String = when (status) {
|
||||
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
|
||||
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
|
||||
PhantomProcessStatus.UNREADABLE -> "Child-process limit could not be checked"
|
||||
PhantomProcessStatus.DISABLED -> "Child-process limit is off"
|
||||
PhantomProcessStatus.NOT_APPLICABLE -> "Child-process limit not required"
|
||||
}
|
||||
|
||||
fun instructions(status: PhantomProcessStatus): String = when (status) {
|
||||
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
|
||||
PhantomProcessStatus.UNSET -> "This setting is unset, so the ROM default applies and may enforce the limit. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
|
||||
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not read the setting. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
|
||||
PhantomProcessStatus.DISABLED -> "Steam sessions can start."
|
||||
PhantomProcessStatus.NOT_APPLICABLE -> "This Android version does not use this limit."
|
||||
}
|
||||
|
||||
fun gateInstructions(status: PhantomProcessStatus): String = when (status) {
|
||||
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options."
|
||||
PhantomProcessStatus.UNSET -> "The ROM default may enforce this limit. Explicitly turn off “Restrict child processes” in Developer options."
|
||||
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not check this setting. Turn off “Restrict child processes” in Developer options."
|
||||
else -> instructions(status)
|
||||
}
|
||||
|
||||
fun reportValue(status: PhantomProcessStatus): String = when (status) {
|
||||
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
|
||||
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
|
||||
PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)"
|
||||
PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)"
|
||||
PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.net.nsd.NsdManager
|
||||
import android.net.nsd.NsdServiceInfo
|
||||
import com.flyfishxu.kadb.Kadb
|
||||
import com.flyfishxu.kadb.cert.KadbCert
|
||||
import java.io.File
|
||||
import java.net.InetAddress
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.ArrayDeque
|
||||
|
||||
/** A narrowly scoped Wireless debugging client for the child-process setting repair. */
|
||||
object WirelessAdbFix {
|
||||
private const val CERT_FILE = "wireless-adb-cert.pem"
|
||||
private const val KEY_FILE = "wireless-adb-key.pem"
|
||||
private const val HOST_FILE = "wireless-adb-host.txt"
|
||||
private const val CONNECTION_FILE = "wireless-adb-connection.txt"
|
||||
|
||||
private data class SavedConnection(val host: String, val port: Int?)
|
||||
|
||||
@Synchronized
|
||||
private fun loadOrCreateIdentity(context: Context) {
|
||||
val directory = context.noBackupFilesDir
|
||||
val cert = File(directory, CERT_FILE)
|
||||
val key = File(directory, KEY_FILE)
|
||||
if (cert.isFile && key.isFile) {
|
||||
KadbCert.set(cert.readBytes(), key.readBytes())
|
||||
return
|
||||
}
|
||||
|
||||
val identity = KadbCert.get(notAfter = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650))
|
||||
KadbCert.set(identity.first, identity.second)
|
||||
writeAtomically(cert, identity.first)
|
||||
writeAtomically(key, identity.second)
|
||||
}
|
||||
|
||||
private fun writeAtomically(destination: File, contents: ByteArray) {
|
||||
val temporary = File(destination.parentFile, "${destination.name}.tmp")
|
||||
temporary.writeBytes(contents)
|
||||
check(temporary.renameTo(destination)) { "Could not save Wireless debugging identity" }
|
||||
}
|
||||
|
||||
suspend fun pair(context: Context, host: String, port: Int, pairingCode: String) {
|
||||
loadOrCreateIdentity(context.applicationContext)
|
||||
Kadb.pair(host, port, pairingCode, "DroidDeck")
|
||||
writeAtomically(File(context.noBackupFilesDir, HOST_FILE), host.toByteArray())
|
||||
writeAtomically(File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
|
||||
}
|
||||
|
||||
private fun savedConnection(context: Context): SavedConnection? {
|
||||
val directory = context.applicationContext.noBackupFilesDir
|
||||
if (!File(directory, CERT_FILE).isFile || !File(directory, KEY_FILE).isFile) return null
|
||||
val host = File(directory, HOST_FILE).takeIf(File::isFile)?.readText()?.trim()
|
||||
?.takeIf(String::isNotEmpty) ?: return null
|
||||
val lines = File(directory, CONNECTION_FILE).takeIf(File::isFile)?.readLines()
|
||||
val port = lines?.takeIf { it.size == 2 && it[0] == host }
|
||||
?.get(1)?.toIntOrNull()?.takeIf { it in 1..65535 }
|
||||
return SavedConnection(host, port)
|
||||
}
|
||||
|
||||
/** A saved pairing skips the PIN; an unknown connection port can be filled in from Settings. */
|
||||
fun savedConnectionAddress(context: Context): String? = savedConnection(context)?.let { saved ->
|
||||
val host = if (':' in saved.host) "[${saved.host}]" else saved.host
|
||||
"$host:${saved.port ?: ""}"
|
||||
}
|
||||
|
||||
private fun saveConnection(context: Context, host: String, port: Int) {
|
||||
writeAtomically(
|
||||
File(context.applicationContext.noBackupFilesDir, CONNECTION_FILE),
|
||||
"$host\n$port".toByteArray(),
|
||||
)
|
||||
}
|
||||
|
||||
/** Finds this paired device's separate TLS connection port from Android's ADB mDNS record. */
|
||||
fun findConnectPort(context: Context, pairedHost: String, timeoutSeconds: Long = 12): Int? {
|
||||
val manager = context.applicationContext.getSystemService(Context.NSD_SERVICE) as NsdManager
|
||||
val expectedAddress = runCatching { InetAddress.getByName(pairedHost).address }.getOrNull() ?: return null
|
||||
val resolvedPort = AtomicInteger(-1)
|
||||
val finished = AtomicBoolean(false)
|
||||
val latch = CountDownLatch(1)
|
||||
val queue = ArrayDeque<NsdServiceInfo>()
|
||||
val seen = mutableSetOf<String>()
|
||||
var resolving = false
|
||||
val lock = Any()
|
||||
|
||||
lateinit var resolveNext: () -> Unit
|
||||
resolveNext = {
|
||||
val next = synchronized(lock) {
|
||||
if (finished.get() || resolving || queue.isEmpty()) null
|
||||
else queue.removeFirst().also { resolving = true }
|
||||
}
|
||||
if (next != null) {
|
||||
val listener = object : NsdManager.ResolveListener {
|
||||
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
|
||||
synchronized(lock) { resolving = false }
|
||||
resolveNext()
|
||||
}
|
||||
|
||||
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
|
||||
val address = serviceInfo.host?.address
|
||||
if (address != null && address.contentEquals(expectedAddress) && finished.compareAndSet(false, true)) {
|
||||
resolvedPort.set(serviceInfo.port)
|
||||
latch.countDown()
|
||||
} else {
|
||||
synchronized(lock) { resolving = false }
|
||||
resolveNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
runCatching { manager.resolveService(next, listener) }.onFailure {
|
||||
synchronized(lock) { resolving = false }
|
||||
resolveNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val discoveryListener = object : NsdManager.DiscoveryListener {
|
||||
override fun onDiscoveryStarted(serviceType: String) = Unit
|
||||
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
|
||||
if (serviceInfo.serviceType?.contains("_adb-tls-connect._tcp") == true) {
|
||||
synchronized(lock) {
|
||||
if (seen.add(serviceInfo.serviceName)) queue.addLast(serviceInfo)
|
||||
}
|
||||
resolveNext()
|
||||
}
|
||||
}
|
||||
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
|
||||
override fun onDiscoveryStopped(serviceType: String) { latch.countDown() }
|
||||
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
|
||||
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
|
||||
}
|
||||
|
||||
try {
|
||||
manager.discoverServices("_adb-tls-connect._tcp.", NsdManager.PROTOCOL_DNS_SD, discoveryListener)
|
||||
latch.await(timeoutSeconds, TimeUnit.SECONDS)
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
} finally {
|
||||
runCatching { manager.stopServiceDiscovery(discoveryListener) }
|
||||
}
|
||||
return resolvedPort.get().takeIf { it in 1..65535 }
|
||||
}
|
||||
|
||||
fun setChildProcessLimit(context: Context, host: String, port: Int, enabled: Boolean) {
|
||||
loadOrCreateIdentity(context.applicationContext)
|
||||
Kadb.create(host, port).use { adb ->
|
||||
val value = if (enabled) "true" else "false"
|
||||
val change = adb.shell("settings put global settings_enable_monitor_phantom_procs $value")
|
||||
check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } }
|
||||
val result = adb.shell("settings get global settings_enable_monitor_phantom_procs")
|
||||
check(result.exitCode == 0 && result.output.trim() == value) {
|
||||
"Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}"
|
||||
}
|
||||
}
|
||||
saveConnection(context, host, port)
|
||||
}
|
||||
|
||||
/** Tries the app's saved pairing without asking for a new pairing code. */
|
||||
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
|
||||
val appContext = context.applicationContext
|
||||
val saved = savedConnection(appContext)
|
||||
?: error("No Wireless debugging pairing is saved")
|
||||
val cachedPort = saved.port
|
||||
if (cachedPort != null) {
|
||||
val cachedResult = runCatching {
|
||||
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
|
||||
}
|
||||
if (cachedResult.isSuccess) return
|
||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||
if (discoveredPort != null && discoveredPort != cachedPort) {
|
||||
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||
} else {
|
||||
cachedResult.getOrThrow()
|
||||
}
|
||||
} else {
|
||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||
?: error("Enter the current Wireless debugging IP address & Port")
|
||||
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ProviderInfo
|
||||
import android.content.res.AssetFileDescriptor
|
||||
import android.database.Cursor
|
||||
import android.database.MatrixCursor
|
||||
import android.graphics.Point
|
||||
import android.os.CancellationSignal
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.provider.DocumentsContract.Document
|
||||
import android.provider.DocumentsContract.Root
|
||||
import android.provider.DocumentsProvider
|
||||
import android.webkit.MimeTypeMap
|
||||
import com.droiddeck.launcher.R
|
||||
import java.io.File
|
||||
import java.io.FileNotFoundException
|
||||
import java.io.IOException
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
|
||||
/**
|
||||
* The app's own data folder (the Linux runtime, settings, logs) in Android's file picker, under the
|
||||
* app's name beside the phone's storage - what MT Manager's "documents provider" injection does, as
|
||||
* part of the app. Only the system's documents UI can bind it (MANAGE_DOCUMENTS); another app sees
|
||||
* a file only when the user picks it there.
|
||||
*
|
||||
* A document id is the file's absolute path, and nothing outside the data folder is ever handed out
|
||||
* or accepted: every id is resolved and checked to lie inside it.
|
||||
*/
|
||||
class AppFilesProvider : DocumentsProvider() {
|
||||
private lateinit var base: File
|
||||
private lateinit var baseCanonical: String
|
||||
|
||||
override fun attachInfo(context: Context, info: ProviderInfo) {
|
||||
super.attachInfo(context, info)
|
||||
base = context.dataDir
|
||||
baseCanonical = base.canonicalPath
|
||||
}
|
||||
|
||||
override fun onCreate() = true
|
||||
|
||||
override fun queryRoots(projection: Array<String>?): Cursor {
|
||||
val ctx = context!!
|
||||
val result = MatrixCursor(projection ?: ROOT_COLUMNS)
|
||||
result.newRow().apply {
|
||||
add(Root.COLUMN_ROOT_ID, ROOT_ID)
|
||||
add(Root.COLUMN_DOCUMENT_ID, base.absolutePath)
|
||||
add(Root.COLUMN_TITLE, titleFor(ctx))
|
||||
add(Root.COLUMN_SUMMARY, null)
|
||||
add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE or Root.FLAG_SUPPORTS_SEARCH or Root.FLAG_SUPPORTS_IS_CHILD)
|
||||
add(Root.COLUMN_MIME_TYPES, "*/*")
|
||||
add(Root.COLUMN_AVAILABLE_BYTES, base.freeSpace)
|
||||
add(Root.COLUMN_ICON, R.mipmap.ic_launcher)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
override fun queryDocument(documentId: String, projection: Array<String>?): Cursor =
|
||||
MatrixCursor(projection ?: DOCUMENT_COLUMNS).also { addRow(it, fileFor(documentId)) }
|
||||
|
||||
override fun queryChildDocuments(parentDocumentId: String, projection: Array<String>?, sortOrder: String?): Cursor {
|
||||
val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS)
|
||||
// A link in the runtime that leads out of the data folder (/etc/localtime and the like) is
|
||||
// left out rather than listed as something that cannot be opened.
|
||||
fileFor(parentDocumentId).listFiles()?.filter { inside(it) }?.forEach { addRow(result, it) }
|
||||
return result
|
||||
}
|
||||
|
||||
override fun openDocument(documentId: String, mode: String, signal: CancellationSignal?): ParcelFileDescriptor =
|
||||
ParcelFileDescriptor.open(fileFor(documentId), ParcelFileDescriptor.parseMode(mode))
|
||||
|
||||
override fun openDocumentThumbnail(documentId: String, sizeHint: Point?, signal: CancellationSignal?): AssetFileDescriptor {
|
||||
val file = fileFor(documentId)
|
||||
return AssetFileDescriptor(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY), 0, file.length())
|
||||
}
|
||||
|
||||
override fun createDocument(parentDocumentId: String, mimeType: String, displayName: String): String {
|
||||
val parent = fileFor(parentDocumentId)
|
||||
val name = displayName.substringAfterLast('/')
|
||||
var file = File(parent, name)
|
||||
var n = 2
|
||||
while (file.exists()) file = File(parent, "$name (${n++})")
|
||||
val made = try {
|
||||
if (mimeType == Document.MIME_TYPE_DIR) file.mkdir() else file.createNewFile()
|
||||
} catch (e: IOException) {
|
||||
false
|
||||
}
|
||||
if (!made) throw FileNotFoundException("could not create ${file.path}")
|
||||
return file.absolutePath
|
||||
}
|
||||
|
||||
override fun deleteDocument(documentId: String) {
|
||||
val file = fileFor(documentId)
|
||||
if (file.absolutePath == base.absolutePath) throw FileNotFoundException("the app folder itself is not deleted")
|
||||
try {
|
||||
deleteTree(file.toPath())
|
||||
} catch (e: IOException) {
|
||||
throw FileNotFoundException("could not delete $documentId: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a file or a folder and what is in it without ever following a link: the runtime holds
|
||||
* links to places outside it, and deleting a folder must remove the link, not what it points at.
|
||||
*/
|
||||
private fun deleteTree(root: Path) {
|
||||
if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
|
||||
Files.delete(root)
|
||||
return
|
||||
}
|
||||
Files.walkFileTree(root, object : SimpleFileVisitor<Path>() {
|
||||
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||
Files.delete(file)
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
|
||||
if (exc != null) throw exc
|
||||
Files.delete(dir)
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
override fun removeDocument(documentId: String, parentDocumentId: String) = deleteDocument(documentId)
|
||||
|
||||
override fun renameDocument(documentId: String, displayName: String): String {
|
||||
val file = fileFor(documentId)
|
||||
val target = File(file.parentFile, displayName.substringAfterLast('/'))
|
||||
if (target.exists() || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId")
|
||||
return target.absolutePath
|
||||
}
|
||||
|
||||
override fun moveDocument(sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String): String {
|
||||
val source = fileFor(sourceDocumentId)
|
||||
val targetParent = fileFor(targetParentDocumentId)
|
||||
if (!targetParent.isDirectory) throw FileNotFoundException("$targetParentDocumentId is not a folder")
|
||||
val target = File(targetParent, source.name)
|
||||
if (target.exists() || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId")
|
||||
return target.absolutePath
|
||||
}
|
||||
|
||||
override fun getDocumentType(documentId: String): String = mimeOf(fileFor(documentId))
|
||||
|
||||
override fun isChildDocument(parentDocumentId: String, documentId: String): Boolean {
|
||||
val parent = runCatching { fileFor(parentDocumentId).absolutePath }.getOrNull() ?: return false
|
||||
val child = runCatching { fileFor(documentId).absolutePath }.getOrNull() ?: return false
|
||||
return child == parent || child.startsWith("$parent/")
|
||||
}
|
||||
|
||||
override fun querySearchDocuments(rootId: String, query: String, projection: Array<String>?): Cursor {
|
||||
val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS)
|
||||
val needle = query.lowercase()
|
||||
val pending = ArrayDeque(listOf(base))
|
||||
var visited = 0
|
||||
// The runtime is tens of thousands of files: a bounded walk, not the whole tree.
|
||||
while (pending.isNotEmpty() && result.count < 50 && visited++ < 20000) {
|
||||
val f = pending.removeFirst()
|
||||
if (!inside(f)) continue
|
||||
if (f.isDirectory) f.listFiles()?.let { pending.addAll(it) }
|
||||
else if (f.name.lowercase().contains(needle)) addRow(result, f)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** The file an id names, when it exists and lies inside the data folder (links followed). */
|
||||
private fun fileFor(documentId: String): File {
|
||||
val f = File(documentId)
|
||||
if (!f.isAbsolute || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files")
|
||||
if (!f.exists()) throw FileNotFoundException("$documentId not found")
|
||||
return f
|
||||
}
|
||||
|
||||
private fun inside(f: File): Boolean {
|
||||
// The folder's own entries are listed as they are; a link is judged by where it leads.
|
||||
val abs = f.absoluteFile.normalize().path
|
||||
if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false
|
||||
val real = runCatching { f.canonicalPath }.getOrNull() ?: return false
|
||||
return real == baseCanonical || real.startsWith("$baseCanonical/")
|
||||
}
|
||||
|
||||
private fun addRow(result: MatrixCursor, file: File) {
|
||||
var flags = 0
|
||||
if (file.isDirectory) {
|
||||
if (file.canWrite()) flags = flags or Document.FLAG_DIR_SUPPORTS_CREATE
|
||||
} else if (file.canWrite()) {
|
||||
flags = flags or Document.FLAG_SUPPORTS_WRITE
|
||||
}
|
||||
if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true) {
|
||||
flags = flags or Document.FLAG_SUPPORTS_DELETE or Document.FLAG_SUPPORTS_RENAME or
|
||||
Document.FLAG_SUPPORTS_MOVE or Document.FLAG_SUPPORTS_REMOVE
|
||||
}
|
||||
val mime = mimeOf(file)
|
||||
if (mime.startsWith("image/")) flags = flags or Document.FLAG_SUPPORTS_THUMBNAIL
|
||||
result.newRow().apply {
|
||||
add(Document.COLUMN_DOCUMENT_ID, file.absolutePath)
|
||||
add(Document.COLUMN_DISPLAY_NAME, if (file.absolutePath == base.absolutePath) titleFor(context!!) else file.name)
|
||||
add(Document.COLUMN_SIZE, if (file.isDirectory) null else file.length())
|
||||
add(Document.COLUMN_MIME_TYPE, mime)
|
||||
add(Document.COLUMN_LAST_MODIFIED, file.lastModified())
|
||||
add(Document.COLUMN_FLAGS, flags)
|
||||
}
|
||||
}
|
||||
|
||||
private fun mimeOf(file: File): String {
|
||||
if (file.isDirectory) return Document.MIME_TYPE_DIR
|
||||
val ext = file.extension.lowercase()
|
||||
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) ?: "application/octet-stream"
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val ROOT_ID = "app"
|
||||
|
||||
private val ROOT_COLUMNS = arrayOf(
|
||||
Root.COLUMN_ROOT_ID, Root.COLUMN_MIME_TYPES, Root.COLUMN_FLAGS, Root.COLUMN_ICON,
|
||||
Root.COLUMN_TITLE, Root.COLUMN_SUMMARY, Root.COLUMN_DOCUMENT_ID, Root.COLUMN_AVAILABLE_BYTES,
|
||||
)
|
||||
private val DOCUMENT_COLUMNS = arrayOf(
|
||||
Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE, Document.COLUMN_DISPLAY_NAME,
|
||||
Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE,
|
||||
)
|
||||
|
||||
/**
|
||||
* The name in the picker. The same app ships under other package names (for the performance
|
||||
* modes some phones give only named apps); each says which it is, so four installs are not
|
||||
* four identical "DroidDeck" entries.
|
||||
*/
|
||||
fun titleFor(context: Context): String {
|
||||
val name = context.getString(R.string.app_name)
|
||||
return when (context.packageName) {
|
||||
"com.tencent.ig" -> "$name PUBG"
|
||||
"com.antutu.benchmark.full" -> "$name AnTuTu"
|
||||
"com.ludashi.benchmark" -> "$name Ludashi"
|
||||
else -> name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,7 +98,6 @@ import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.graphics.vector.rememberVectorPainter
|
||||
@@ -143,10 +142,6 @@ import java.util.Locale
|
||||
*/
|
||||
enum class ConflictChoice { OVERWRITE, MERGE, KEEP_BOTH, SKIP }
|
||||
|
||||
/**
|
||||
* Ordering for the file list. Folders always lead regardless of direction - a descending sort that
|
||||
* buries every folder under the files is never what someone means by "Z to A".
|
||||
*/
|
||||
/**
|
||||
* Shortens a path from the LEFT, keeping whole segments.
|
||||
*
|
||||
@@ -164,6 +159,7 @@ private fun elidePathStart(path: String, max: Int): String {
|
||||
return if (out.isEmpty()) "…" + path.takeLast(max - 1) else "…$out"
|
||||
}
|
||||
|
||||
/** Folder-first ordering stays fixed across both sort directions. */
|
||||
private fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
|
||||
val inner: Comparator<File> = when (sortBy) {
|
||||
"date" -> compareBy { it.lastModified() }
|
||||
@@ -176,17 +172,9 @@ private fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
|
||||
return compareBy<File> { if (it.isDirectory) 0 else 1 }.then(directed)
|
||||
}
|
||||
|
||||
private val FileTypeIcon: Map<String, ImageVector> = mapOf(
|
||||
"folder" to Icons.Filled.Folder,
|
||||
)
|
||||
|
||||
// Image extensions that get a real thumbnail (via Coil) instead of the generic file icon.
|
||||
private val IMAGE_THUMB_EXTS = setOf("jpg", "jpeg", "png", "webp", "bmp", "gif")
|
||||
|
||||
// Color-only sweep: the former card-fill / card-stroke / divider / icon-blue / icon-white
|
||||
// constants were rerouted onto MaterialTheme.colorScheme tokens (surface / outline / primary /
|
||||
// onSurface) at their use sites so a theme preset/accent recolors them.
|
||||
|
||||
// True when [child] is [ancestor] itself or lives anywhere inside it.
|
||||
private fun isWithin(child: File, ancestor: File): Boolean {
|
||||
val c = runCatching { child.canonicalPath }.getOrDefault(child.absolutePath)
|
||||
@@ -937,8 +925,7 @@ fun FileManagerScreen(
|
||||
}
|
||||
|
||||
if (!showFavorites) {
|
||||
// New Folder moved off a bottom bar into the toolbar (next to the grid/list toggle),
|
||||
// as a compact outlined button, so the file list reclaims that bottom strip.
|
||||
// Keep New Folder in the toolbar so the file list uses the full height.
|
||||
if (!pickMode) {
|
||||
OutlinedButton(
|
||||
onClick = { showNewFolderDialog = true },
|
||||
@@ -1425,7 +1412,6 @@ fun FileManagerScreen(
|
||||
}
|
||||
} // end content Box (beside the rail)
|
||||
} // end rail + content Row
|
||||
// (New Folder moved into the top toolbar; the bottom bar was removed to reclaim its strip.)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1447,7 +1433,6 @@ private fun FileContextMenuItems(
|
||||
onDismissMenu: () -> Unit,
|
||||
) {
|
||||
val isDir = file.isDirectory
|
||||
// Enter multi-select on this item (replaces the old long-press-only entry point).
|
||||
DropdownMenuItem(
|
||||
text = { Text("Select") },
|
||||
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
|
||||
@@ -56,10 +56,10 @@ object AddedGames {
|
||||
"|.*installer.*|.*uninstall.*|.*updater?.*|.*config(ur.*)?|.*settings.*|.*editor.*|.*server.*|.*benchmark.*|.*helper.*|.*eac.*|.*easyanticheat.*|.*battleye.*)\\.exe$",
|
||||
)
|
||||
|
||||
/** Where a host path appears inside the session, or null when the session cannot see it. */
|
||||
/** Under here the chosen Games folders are bound inside the session, one each. */
|
||||
const val GUEST_DIR = "/root/Games"
|
||||
|
||||
/** Where a host path appears inside the session, or null when the session cannot see it. */
|
||||
fun guestPath(context: Context, host: File): String? {
|
||||
val path = host.absolutePath
|
||||
// The Games folders are bound on their own, so a folder anywhere - an SD card, a USB
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
/**
|
||||
* Box art for the emulators' games, found and kept on the device: the front end shows a disc image
|
||||
* with nothing but its emulator's logo otherwise.
|
||||
*
|
||||
* In order: the name of the file against RetroArch's thumbnail collection for the system
|
||||
* (libretro-thumbnails, named after the standard disc-dump names - "Need for Speed - Underground 2
|
||||
* (USA)"), first exactly and then loosely (tags dropped, the same region preferred) against the
|
||||
* collection's list of names; then the disc's own ID, read from the image - PS2 serials against
|
||||
* xlenore/ps2-covers (what PCSX2 and ARMSX2 download from), GameCube/Wii IDs against GameTDB (what
|
||||
* Dolphin uses). A PS3 disc image gives its own PS3_GAME/ICON0.PNG first: the libretro PS3
|
||||
* collection is small. A cover is downloaded once into files/covers; a game none of them has is not
|
||||
* asked about again for a few days.
|
||||
*/
|
||||
object CoverArt {
|
||||
private const val TAG = "CoverArt"
|
||||
private const val MISS_RETRY_MS = 3L * 24 * 3600 * 1000
|
||||
private const val INDEX_TTL_MS = 14L * 24 * 3600 * 1000
|
||||
/** Downloads in one pass, so a first visit to a big library does not hold the network for long. */
|
||||
private const val MAX_PER_PASS = 40
|
||||
|
||||
/** The emulator's systems in libretro-thumbnails, in the order they are tried. */
|
||||
private val collections = mapOf(
|
||||
"rpcs3" to listOf("Sony_-_PlayStation_3"),
|
||||
"armsx2" to listOf("Sony_-_PlayStation_2"),
|
||||
"duckstation" to listOf("Sony_-_PlayStation"),
|
||||
"ppsspp" to listOf("Sony_-_PlayStation_Portable"),
|
||||
"dolphin" to listOf("Nintendo_-_GameCube", "Nintendo_-_Wii"),
|
||||
"melonds" to listOf("Nintendo_-_Nintendo_DS"),
|
||||
"cemu" to listOf("Nintendo_-_Wii_U"),
|
||||
)
|
||||
|
||||
private fun root(context: Context) = File(context.filesDir, "covers")
|
||||
|
||||
/** The file name, as the cover is kept under: a game keeps its art when its folder moves. */
|
||||
private fun keyOf(rom: Library.Rom): String =
|
||||
rom.hostPath.name.replace(Regex("[^A-Za-z0-9._() -]"), "_").take(150)
|
||||
|
||||
private fun coverFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.img")
|
||||
private fun missFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.miss")
|
||||
|
||||
/** A cover already on the device for this game, or null. */
|
||||
fun cached(context: Context, rom: Library.Rom): File? = coverFile(context, rom).takeIf { it.isFile && it.length() > 0 }
|
||||
|
||||
private fun wanted(context: Context, rom: Library.Rom): Boolean {
|
||||
if (rom.art != null || cached(context, rom) != null || rom.emulatorId !in collections) return false
|
||||
val miss = missFile(context, rom)
|
||||
return !(miss.isFile && System.currentTimeMillis() - miss.lastModified() < MISS_RETRY_MS)
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks for covers for the games that have none, on the calling (background) thread. True when
|
||||
* at least one was found, so the caller rebuilds the list to show it.
|
||||
*/
|
||||
fun fetchMissing(context: Context, roms: List<Library.Rom>): Boolean {
|
||||
var found = false
|
||||
var tries = 0
|
||||
for (rom in roms) {
|
||||
if (!wanted(context, rom)) continue
|
||||
if (++tries > MAX_PER_PASS) break
|
||||
val target = coverFile(context, rom)
|
||||
// A PS3 disc carries its own cover (PS3_GAME/ICON0.PNG, not encrypted): no download.
|
||||
if (rom.emulatorId == "rpcs3" && try { copyPs3Icon(rom.hostPath, target) } catch (e: Exception) { false }) {
|
||||
Log.i(TAG, "${rom.name}: ICON0.PNG from the disc")
|
||||
missFile(context, rom).delete()
|
||||
found = true
|
||||
continue
|
||||
}
|
||||
val url = try { findUrl(context, rom) } catch (e: Exception) { Log.w(TAG, "${rom.name}: $e"); null }
|
||||
if (url != null && download(url, target)) {
|
||||
Log.i(TAG, "${rom.name}: $url")
|
||||
missFile(context, rom).delete()
|
||||
found = true
|
||||
} else {
|
||||
missFile(context, rom).apply { parentFile?.mkdirs(); writeText(url ?: "") }
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private fun findUrl(context: Context, rom: Library.Rom): String? {
|
||||
val name = rom.hostPath.nameWithoutExtension.removeSuffix(".dec")
|
||||
for (collection in collections.getValue(rom.emulatorId)) {
|
||||
// Exactly the dump name first: no listing needed.
|
||||
val exact = thumbnailUrl(collection, name)
|
||||
if (exists(exact)) return exact
|
||||
// Then loosely, against the collection's names.
|
||||
nearest(name, names(context, collection))?.let { return thumbnailUrl(collection, it) }
|
||||
}
|
||||
// The disc's own ID.
|
||||
return when (rom.emulatorId) {
|
||||
"armsx2" -> ps2Serial(rom.hostPath)?.let { "https://raw.githubusercontent.com/xlenore/ps2-covers/main/covers/default/$it.jpg" }
|
||||
"dolphin" -> nintendoDiscId(rom.hostPath)?.let { id ->
|
||||
val region = when (id.getOrNull(3)) { 'P' -> "EN"; 'J' -> "JA"; 'K' -> "KO"; else -> "US" }
|
||||
"https://art.gametdb.com/wii/cover/$region/$id.png"
|
||||
}
|
||||
else -> null
|
||||
}?.takeIf { exists(it) }
|
||||
}
|
||||
|
||||
/** libretro-thumbnails replaces these in a title's file name. */
|
||||
private fun thumbName(title: String) = title.replace(Regex("[&*/:`<>?\\\\|\"]"), "_")
|
||||
|
||||
private fun thumbnailUrl(collection: String, title: String) =
|
||||
"https://raw.githubusercontent.com/libretro-thumbnails/$collection/master/Named_Boxarts/" +
|
||||
URLEncoder.encode("${thumbName(title)}.png", "UTF-8").replace("+", "%20")
|
||||
|
||||
// ---- loose matching ------------------------------------------------------------------------
|
||||
|
||||
private fun tags(name: String): List<String> = Regex("[(\\[]([^)\\]]*)[)\\]]").findAll(name).map { it.groupValues[1].lowercase() }.toList()
|
||||
|
||||
/** A title without its tags, articles and punctuation: "Legend of Zelda, The (USA)" = "legend of zelda". */
|
||||
private fun base(name: String): String = name
|
||||
.replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), " ")
|
||||
.lowercase()
|
||||
.replace(Regex("[^a-z0-9]+"), " ")
|
||||
.split(' ').filter { it.isNotEmpty() && it != "the" && it != "a" }
|
||||
.joinToString(" ")
|
||||
|
||||
private fun nearest(name: String, candidates: List<String>): String? {
|
||||
if (candidates.isEmpty()) return null
|
||||
val want = base(name)
|
||||
if (want.isEmpty()) return null
|
||||
val same = candidates.filter { base(it) == want }
|
||||
if (same.isEmpty()) return null
|
||||
val region = tags(name).firstOrNull { it in setOf("usa", "europe", "japan", "world", "korea") } ?: "usa"
|
||||
return same.firstOrNull { region in tags(it) } ?: same.firstOrNull { "usa" in tags(it) } ?: same.first()
|
||||
}
|
||||
|
||||
/** The titles in a collection's Named_Boxarts (no extension), kept for a fortnight. */
|
||||
private fun names(context: Context, collection: String): List<String> {
|
||||
val cache = File(root(context), "index-$collection.txt")
|
||||
if (cache.isFile && System.currentTimeMillis() - cache.lastModified() < INDEX_TTL_MS) return cache.readLines()
|
||||
val list = try {
|
||||
val top = JSONArray(get("https://api.github.com/repos/libretro-thumbnails/$collection/contents/") ?: return cachedOr(cache))
|
||||
val sha = (0 until top.length()).map { top.getJSONObject(it) }.firstOrNull { it.optString("name") == "Named_Boxarts" }
|
||||
?.optString("sha") ?: return cachedOr(cache)
|
||||
val tree = JSONObject(get("https://api.github.com/repos/libretro-thumbnails/$collection/git/trees/$sha") ?: return cachedOr(cache))
|
||||
.getJSONArray("tree")
|
||||
(0 until tree.length()).map { tree.getJSONObject(it).optString("path") }
|
||||
.filter { it.endsWith(".png") }.map { it.removeSuffix(".png") }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "index $collection: $e"); return cachedOr(cache)
|
||||
}
|
||||
cache.parentFile?.mkdirs()
|
||||
cache.writeText(list.joinToString("\n"))
|
||||
return list
|
||||
}
|
||||
|
||||
private fun cachedOr(cache: File): List<String> = if (cache.isFile) cache.readLines() else emptyList()
|
||||
|
||||
// ---- disc IDs ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A file's bytes from an ISO 9660 image by path ("PS3_GAME/ICON0.PNG"), or null. Primary volume
|
||||
* names only (upper case, ";1" suffix), which is what PS2 and PS3 discs use.
|
||||
*/
|
||||
private fun isoFile(file: File, path: String, maxSize: Int): ByteArray? {
|
||||
if (!file.name.endsWith(".iso", ignoreCase = true)) return null
|
||||
RandomAccessFile(file, "r").use { f ->
|
||||
fun read(lba: Long, length: Int): ByteArray = ByteArray(length).also { f.seek(lba * 2048); f.readFully(it) }
|
||||
fun le32(b: ByteArray, at: Int) = (b[at].toLong() and 0xff) or ((b[at + 1].toLong() and 0xff) shl 8) or
|
||||
((b[at + 2].toLong() and 0xff) shl 16) or ((b[at + 3].toLong() and 0xff) shl 24)
|
||||
val pvd = read(16, 2048)
|
||||
if (String(pvd, 1, 5, Charsets.US_ASCII) != "CD001") return null
|
||||
var lba = le32(pvd, 156 + 2)
|
||||
var size = le32(pvd, 156 + 10)
|
||||
val parts = path.split('/')
|
||||
for ((i, part) in parts.withIndex()) {
|
||||
val dir = read(lba, size.toInt().coerceAtMost(256 * 1024))
|
||||
var at = 0
|
||||
var hit = false
|
||||
while (at < dir.size) {
|
||||
val len = dir[at].toInt() and 0xff
|
||||
if (len == 0) { at = (at / 2048 + 1) * 2048; continue }
|
||||
val name = String(dir, at + 33, dir[at + 32].toInt() and 0xff, Charsets.US_ASCII).substringBefore(';')
|
||||
if (name.equals(part, ignoreCase = true)) {
|
||||
lba = le32(dir, at + 2); size = le32(dir, at + 10); hit = true; break
|
||||
}
|
||||
at += len
|
||||
}
|
||||
if (!hit) return null
|
||||
if (i == parts.lastIndex) return if (size in 1..maxSize) read(lba, size.toInt()) else null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun copyPs3Icon(file: File, target: File): Boolean {
|
||||
val png = isoFile(file, "PS3_GAME/ICON0.PNG", 4 * 1024 * 1024) ?: return false
|
||||
target.parentFile?.mkdirs()
|
||||
val tmp = File(target.path + ".part")
|
||||
tmp.writeBytes(png)
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(tmp.path, bounds)
|
||||
return if (bounds.outWidth > 0 && tmp.renameTo(target)) true else { tmp.delete(); false }
|
||||
}
|
||||
|
||||
/** "SLUS-21065" from a PS2 .iso's SYSTEM.CNF (BOOT2 = cdrom0:\SLUS_210.65;1), or null. */
|
||||
private fun ps2Serial(file: File): String? {
|
||||
val cnf = String(isoFile(file, "SYSTEM.CNF", 4096) ?: return null, Charsets.US_ASCII)
|
||||
val m = Regex("BOOT2\\s*=\\s*cdrom0:\\\\?([A-Z]{4})_(\\d{3})\\.(\\d{2})").find(cnf) ?: return null
|
||||
return "${m.groupValues[1]}-${m.groupValues[2]}${m.groupValues[3]}"
|
||||
}
|
||||
|
||||
/** The six-character ID of a GameCube/Wii disc image (.iso/.gcm, or .wbfs), or null. */
|
||||
private fun nintendoDiscId(file: File): String? {
|
||||
val offset = when (file.extension.lowercase()) { "iso", "gcm" -> 0L; "wbfs" -> 0x200L; else -> return null }
|
||||
RandomAccessFile(file, "r").use { f ->
|
||||
val b = ByteArray(6); f.seek(offset); f.readFully(b)
|
||||
val id = String(b, Charsets.US_ASCII)
|
||||
return id.takeIf { it.all { c -> c.isLetterOrDigit() } }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- network -------------------------------------------------------------------------------
|
||||
|
||||
private fun open(url: String, method: String = "GET"): HttpURLConnection =
|
||||
(URL(url).openConnection() as HttpURLConnection).apply {
|
||||
requestMethod = method
|
||||
connectTimeout = 10_000
|
||||
readTimeout = 20_000
|
||||
instanceFollowRedirects = true
|
||||
setRequestProperty("User-Agent", "DroidDeck")
|
||||
}
|
||||
|
||||
private fun exists(url: String): Boolean = try {
|
||||
val c = open(url, "HEAD"); val ok = c.responseCode == 200; c.disconnect(); ok
|
||||
} catch (e: Exception) { false }
|
||||
|
||||
private fun get(url: String): String? = try {
|
||||
val c = open(url)
|
||||
if (c.responseCode != 200) { c.disconnect(); null } else c.inputStream.bufferedReader().use { it.readText() }
|
||||
} catch (e: Exception) { Log.w(TAG, "$url: $e"); null }
|
||||
|
||||
/** Saves the image at [url] to [target] if it really is an image. */
|
||||
private fun download(url: String, target: File): Boolean = try {
|
||||
val c = open(url)
|
||||
if (c.responseCode != 200) { c.disconnect(); false } else {
|
||||
target.parentFile?.mkdirs()
|
||||
val tmp = File(target.path + ".part")
|
||||
c.inputStream.use { input -> tmp.outputStream().use { input.copyTo(it) } }
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(tmp.path, bounds)
|
||||
if (bounds.outWidth > 0 && tmp.renameTo(target)) true else { tmp.delete(); false }
|
||||
}
|
||||
} catch (e: Exception) { Log.w(TAG, "$url: $e"); false }
|
||||
}
|
||||
@@ -19,14 +19,42 @@ object Library {
|
||||
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
|
||||
/** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */
|
||||
val iconRes: Int get() = when (id) {
|
||||
"rpcs3" -> R.drawable.emu_rpcs3; "pcsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin
|
||||
"rpcs3" -> R.drawable.emu_rpcs3; "armsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin
|
||||
"duckstation" -> R.drawable.emu_duckstation; "melonds" -> R.drawable.emu_melonds; "cemu" -> R.drawable.emu_cemu
|
||||
"ppsspp" -> R.drawable.emu_ppsspp; else -> R.drawable.emu_retroarch
|
||||
}
|
||||
}
|
||||
|
||||
/** The client's own tools and runtimes live in steamapps beside the games; they are not titles. */
|
||||
private val NOT_GAMES = setOf(228980, 1493710, 3127680, 4183110, 4427310, 4185400)
|
||||
private val NOT_GAMES = setOf(
|
||||
858280, // Proton 3.7
|
||||
961940, // Proton 3.16
|
||||
993090, // Lossless Scaling
|
||||
1054830, // Proton 4.2
|
||||
1070560, // Steam Linux Runtime 1.0
|
||||
1113280, // Proton 4.11
|
||||
1245040, // Proton 5.0
|
||||
1391110, // Steam Linux Runtime 2.0
|
||||
1420170, // Proton 5.13
|
||||
1493710, // Proton Experimental
|
||||
1580130, // Proton 6.3
|
||||
1628350, // Steam Linux Runtime 3.0
|
||||
1887720, // Proton 7
|
||||
2180100, // Proton Hotfix
|
||||
228980, // Steamworks Common Redistributables
|
||||
2348590, // Proton 8
|
||||
2805730, // Proton 9
|
||||
3029110, // Lepton
|
||||
3127680, // FEX
|
||||
3658110, // Proton 10
|
||||
4183110, // Steam Linux Runtime 4.0
|
||||
4185400, // Steam Linux Runtime 4.0 for ARM64
|
||||
4427310, // Proton Experimental for ARM64
|
||||
4628710, // Proton 11 / Proton Next
|
||||
4628740, // Proton 11 for ARM64
|
||||
4690330, // Legacy Steam Runtime
|
||||
)
|
||||
private val STEAM_CAPSULES = listOf("library_capsule.jpg", "library_600x900.jpg")
|
||||
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
|
||||
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
||||
|
||||
@@ -49,31 +77,63 @@ object Library {
|
||||
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||
// StateFlags 4 = fully installed; anything else is downloading, updating or broken.
|
||||
if (name.isEmpty() || flags and 4 == 0) return@forEach
|
||||
val dir = File(cache, appId.toString())
|
||||
val art = listOf("library_600x900.jpg", "logo.png", "library_header.jpg", "header.jpg")
|
||||
.map { File(dir, it) }.firstOrNull { it.isFile }
|
||||
val art = steamCapsule(cache, appId)
|
||||
out[appId] = SteamGame(appId, name, art, label)
|
||||
}
|
||||
}
|
||||
return out.values.toList()
|
||||
}
|
||||
|
||||
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>)
|
||||
/** Steam stores current library capsules inside hash-named folders under the app's cache dir. */
|
||||
private fun steamCapsule(cache: File, appId: Int): File? {
|
||||
val appDir = File(cache, appId.toString())
|
||||
val dirs = listOf(appDir) + appDir.listFiles()
|
||||
.orEmpty().filter { it.isDirectory }.sortedBy { it.name }
|
||||
return STEAM_CAPSULES.asSequence()
|
||||
.flatMap { name -> dirs.asSequence().map { File(it, name) } }
|
||||
.firstOrNull { it.isFile && it.length() > 0L }
|
||||
}
|
||||
|
||||
/** [atPanel]: frames cheap enough to draw at the panel's own size (see [drawsAtPanel]). */
|
||||
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>, val atPanel: Boolean = false)
|
||||
private val specs = listOf(
|
||||
Spec("rpcs3", "RPCS3", "PS3", "/opt/appimages/rpcs3.AppImage", listOf("ps3"), setOf("iso")),
|
||||
Spec("pcsx2", "PCSX2", "PS2", "/opt/appimages/pcsx2.AppImage", listOf("ps2"), setOf("iso", "chd", "cso", "gz")),
|
||||
// PS2: ARMSX2, the PCSX2 fork with ARM64 recompilers. Upstream PCSX2 interprets the PS2's
|
||||
// CPUs on ARM64 (NFS Underground 2: 17 fps against ARMSX2's full 60), so it is not offered.
|
||||
Spec("armsx2", "ARMSX2", "PS2", "/opt/appimages/armsx2.AppImage", listOf("ps2"), setOf("iso", "chd", "cso", "gz")),
|
||||
Spec("dolphin", "Dolphin", "GameCube / Wii", "/opt/appimages/dolphin.AppImage", listOf("gc", "gamecube", "wii"), setOf("iso", "rvz", "gcz", "wbfs", "ciso")),
|
||||
Spec("duckstation", "DuckStation", "PS1", "/opt/appimages/duckstation.AppImage", listOf("ps1", "psx"), setOf("cue", "chd", "pbp", "iso", "bin", "img", "ecm", "m3u")),
|
||||
Spec("melonds", "melonDS", "DS", "/opt/appimages/melonds.AppImage", listOf("ds", "nds"), setOf("nds", "dsi")),
|
||||
Spec("melonds", "melonDS", "DS", "/opt/appimages/melonds.AppImage", listOf("ds", "nds"), setOf("nds", "dsi"), atPanel = true),
|
||||
Spec("cemu", "Cemu", "Wii U", "/opt/appimages/cemu.AppImage", listOf("wiiu", "wii u"), setOf("wua", "wud", "wux", "rpx")),
|
||||
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
|
||||
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
|
||||
)
|
||||
/**
|
||||
* A dump's file name as a title: its tags - (USA), (En,Fr,Es,Pt), [!], (v1.01) - identify the
|
||||
* file and are dropped for reading ("Tomb Raider (USA) (En,Fr,Es,Pt)" -> "Tomb Raider"). The
|
||||
* file keeps them, and the cover lookup still uses them.
|
||||
*/
|
||||
private fun displayTitle(name: String): String =
|
||||
name.replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), "").trim().ifEmpty { name }
|
||||
|
||||
/** Every system folder name the specs claim, so a loose-file scan of the root skips them. */
|
||||
private val systemFolders: Set<String> by lazy { specs.flatMap { it.folders }.toSet() }
|
||||
private val installedIds = mapOf(
|
||||
"rpcs3" to "rpcs3", "pcsx2" to "pcsx2", "dolphin" to "dolphin", "duckstation" to "duckstation",
|
||||
"rpcs3" to "rpcs3", "armsx2" to "armsx2", "dolphin" to "dolphin", "duckstation" to "duckstation",
|
||||
"melonds" to "melonds", "cemu" to "cemu", "ppsspp" to "emulators", "retroarch" to "emulators",
|
||||
)
|
||||
|
||||
/** The emulator's name for a program path from the rail ("ARMSX2"), or null. */
|
||||
fun nameForProgram(program: String?): String? = specs.firstOrNull { it.program == program }?.name
|
||||
|
||||
/**
|
||||
* Whether a program from the rail runs at the panel's own resolution rather than the session's
|
||||
* 720p default. melonDS draws two 256x192 screens on the CPU: the panel's size costs it
|
||||
* nothing, and 720p scaled up to the panel blurs the sharp pixels its screen layout is set
|
||||
* up for (bannerlator-pad-defaults).
|
||||
*/
|
||||
fun drawsAtPanel(program: String?): Boolean = specs.any { it.program == program && it.atPanel }
|
||||
|
||||
/** Desktop catalog package that supplies this emulator. */
|
||||
fun packageId(emulatorId: String): String? = installedIds[emulatorId]
|
||||
|
||||
@@ -83,37 +143,68 @@ object Library {
|
||||
return specs.map { spec ->
|
||||
val games = ArrayList<Rom>()
|
||||
if (romsRoot != null && spec.exts.isNotEmpty()) {
|
||||
// The system's folder(s), matched without regard to case, then the root itself for
|
||||
// a file left loose there - and one folder deeper, since a dump usually comes as a
|
||||
// folder named for the game with the image inside it.
|
||||
// The system's folder(s), matched without regard to case, and up to three folders
|
||||
// inside them - a dump usually comes as a folder named for the game with the image
|
||||
// inside it, and people sort those into folders of their own (ps2/games/<game>/).
|
||||
// The root itself only one deep, for a file left loose there.
|
||||
val systemDirs = romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() in spec.folders }.orEmpty().toList()
|
||||
val dirs = LinkedHashSet<File>()
|
||||
for (top in systemDirs + romsRoot) {
|
||||
dirs.add(top)
|
||||
top.listFiles { f -> f.isDirectory }?.forEach { dirs.add(it) }
|
||||
}
|
||||
// A BIOS folder holds the console's firmware, not games (psx/bios/SCPH1001.BIN).
|
||||
for (top in systemDirs) top.walkTopDown().maxDepth(3).onEnter { it.name.lowercase() !in firmwareFolders }
|
||||
.filter { it.isDirectory }.forEach { dirs.add(it) }
|
||||
dirs.add(romsRoot)
|
||||
// ...and not into another system's folder: a PS3 .iso in ps3/ is not a PS2 game.
|
||||
romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() !in systemFolders }?.forEach { dirs.add(it) }
|
||||
for (dir in dirs) {
|
||||
// A PS3 disc dump is a folder with PS3_GAME in it; RPCS3 boots the folder.
|
||||
if (spec.id == "rpcs3" && File(dir, "PS3_GAME").isDirectory) {
|
||||
val rel = dir.relativeTo(romsRoot).path
|
||||
games.add(Rom(dir.name, dir, "/root/ROMs/$rel", spec.id))
|
||||
games.add(Rom(displayTitle(dir.name), dir, "/root/ROMs/$rel", spec.id,
|
||||
// The dump carries its own art, as an installed package does.
|
||||
art = File(dir, "PS3_GAME/ICON0.PNG").takeIf { it.isFile }))
|
||||
continue
|
||||
}
|
||||
dir.listFiles()?.sortedBy { it.name.lowercase() }?.forEach { f ->
|
||||
val files = dir.listFiles()?.sortedBy { it.name.lowercase() }.orEmpty()
|
||||
// A disc sheet (.cue, .gdi) names its track files and a playlist (.m3u) its
|
||||
// discs: the sheet is the game, what it names is part of it. A .bin beside a
|
||||
// .cue of the same name is a track even when the sheet can't be read.
|
||||
val parts = files.filter { it.isFile && it.extension.lowercase() in sheetExts }.flatMap(::sheetParts).toSet()
|
||||
files.forEach { f ->
|
||||
val ext = f.extension.lowercase()
|
||||
// A .bin beside a .cue is a track, not a game.
|
||||
if (f.isFile && ext in spec.exts && !(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) {
|
||||
if (f.isFile && ext in spec.exts && f.name.lowercase() !in parts &&
|
||||
!(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) {
|
||||
val rel = f.relativeTo(romsRoot).path
|
||||
games.add(Rom(f.nameWithoutExtension.removeSuffix(".dec"), f, "/root/ROMs/$rel", spec.id))
|
||||
games.add(Rom(displayTitle(f.nameWithoutExtension.removeSuffix(".dec")), f, "/root/ROMs/$rel", spec.id))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (spec.id == "rpcs3") games.addAll(rpcs3Installed(context))
|
||||
Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), games)
|
||||
// A cover found for the game before (CoverArt) where it has no art of its own.
|
||||
val withArt = games.map { g -> if (g.art != null) g else CoverArt.cached(context, g)?.let { Rom(g.name, g.hostPath, g.guestPath, g.emulatorId, it) } ?: g }
|
||||
Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), withArt)
|
||||
}
|
||||
}
|
||||
|
||||
private val firmwareFolders = setOf("bios", "firmware")
|
||||
private val sheetExts = setOf("cue", "gdi", "m3u")
|
||||
|
||||
/** The file names (lower case) a .cue, .gdi or .m3u refers to, from its own folder. */
|
||||
private fun sheetParts(sheet: File): List<String> = runCatching {
|
||||
if (sheet.length() > 64 * 1024) return emptyList()
|
||||
sheet.readLines().mapNotNull { line ->
|
||||
val t = line.trim()
|
||||
when (sheet.extension.lowercase()) {
|
||||
// FILE "Tekken 3 (USA) (Track 1).bin" BINARY
|
||||
"cue" -> Regex("^FILE\\s+\"([^\"]+)\"", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1)
|
||||
?: Regex("^FILE\\s+(\\S+)", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1)
|
||||
// 1 0 4 2352 "track01.bin" 0 / 1 0 4 2352 track01.bin 0
|
||||
"gdi" -> Regex("\"([^\"]+)\"").find(t)?.groupValues?.get(1) ?: t.split(Regex("\\s+")).getOrNull(4)
|
||||
else -> t.takeIf { it.isNotEmpty() && !it.startsWith("#") }
|
||||
}
|
||||
}.map { File(it.replace('\\', '/')).name.lowercase() }
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
/**
|
||||
* What RPCS3 has installed on its own HDD - packages (PSN games) land in dev_hdd0/game/<ID>
|
||||
* with a PARAM.SFO for the title and an EBOOT to boot - as RPCS3's own file list would show
|
||||
@@ -168,8 +259,29 @@ object Library {
|
||||
/** How the emulator is told which game to boot, on its command line. */
|
||||
fun launchArgs(emulatorId: String, guestPath: String): List<String> = when (emulatorId) {
|
||||
"rpcs3" -> listOf("--no-gui", guestPath)
|
||||
"dolphin" -> listOf("-e", guestPath)
|
||||
// Straight into the game in its controller-driven full-screen UI (first-time setup there
|
||||
// too), and gone when the game is quit from its pause menu (guide button): -batch.
|
||||
"armsx2" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath)
|
||||
// DuckStation shares PCSX2's flags (src/duckstation-qt/qthost.cpp): the same launch and exit.
|
||||
"duckstation" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath)
|
||||
// Dolphin: full screen, drawn inside its own main window, without its "stop the emulation?"
|
||||
// question; no warning boxes either, which wait for a click a controller cannot give
|
||||
// (they still go to Dolphin's log). The guide button is Dolphin's Toggle Fullscreen hotkey
|
||||
// (bannerlator-pad-defaults), which shows Dolphin's window and its settings - so no -b, which
|
||||
// hides that window; closing Dolphin ends the session. Under gamescope Dolphin does not
|
||||
// always see its window as focused, and by default both its hotkeys and the game's
|
||||
// controller then stop: HotkeysRequireFocus off, BackgroundInput on. -C sets a Dolphin.ini
|
||||
// value for this run only, so Dolphin started from the desktop keeps its own settings.
|
||||
"dolphin" -> listOf(
|
||||
"-C", "Dolphin.Display.Fullscreen=True", "-C", "Dolphin.Display.RenderToMain=True",
|
||||
"-C", "Dolphin.Interface.ConfirmStop=False", "-C", "Dolphin.Interface.UsePanicHandlers=False",
|
||||
"-C", "Dolphin.General.HotkeysRequireFocus=False", "-C", "Dolphin.Input.BackgroundInput=True",
|
||||
"-e", guestPath,
|
||||
)
|
||||
"cemu" -> listOf("-g", guestPath)
|
||||
// Full screen (CLI.cpp --fullscreen); the guide button leaves it for melonDS's menus and
|
||||
// comes back (HK_FullscreenToggle, bannerlator-pad-defaults).
|
||||
"melonds" -> listOf("-f", guestPath)
|
||||
else -> listOf(guestPath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import android.widget.FrameLayout
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.LocalPalette
|
||||
|
||||
class ControllerEditorActivity : ComponentActivity() {
|
||||
private lateinit var controls: OnScreenControls
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
immersive()
|
||||
val root = FrameLayout(this)
|
||||
root.setBackgroundColor(0xFF0B0F14.toInt())
|
||||
controls = OnScreenControls(this, null, editing = true)
|
||||
root.addView(controls, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
|
||||
val bar = ComposeView(this).apply {
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier
|
||||
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.9f), RoundedCornerShape(50))
|
||||
.padding(start = 14.dp, end = 5.dp, top = 5.dp, bottom = 5.dp),
|
||||
) {
|
||||
Text("Drag to move", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(end = 4.dp))
|
||||
EditorButton("Reset", false) { controls.resetLayout() }
|
||||
EditorButton("Cancel", false) { finish() }
|
||||
EditorButton("Save", true) {
|
||||
controls.saveLayout()
|
||||
finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
root.addView(bar, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER))
|
||||
setContentView(root)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EditorButton(label: String, primary: Boolean, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Text(
|
||||
label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = if (primary) Color.White else MaterialTheme.colorScheme.onBackground,
|
||||
modifier = Modifier.clip(RoundedCornerShape(50))
|
||||
.background(if (primary) pal.signal else Color.White.copy(alpha = 0.06f))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) immersive()
|
||||
}
|
||||
|
||||
private fun immersive() {
|
||||
@Suppress("DEPRECATION")
|
||||
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
|
||||
or View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
if (Build.VERSION.SDK_INT >= 28) {
|
||||
window.attributes = window.attributes.apply {
|
||||
layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
|
||||
object ControllerPrefs {
|
||||
const val STEAM_BLUE = 0xFF1A9FFF.toInt()
|
||||
const val OFF = "off"
|
||||
|
||||
val tints = listOf(
|
||||
STEAM_BLUE to "Steam blue",
|
||||
0xFF66C0F4.toInt() to "Sky",
|
||||
0xFFE8EEF4.toInt() to "White",
|
||||
0xFFC77DFF.toInt() to "Violet",
|
||||
0xFF3DDC84.toInt() to "Green",
|
||||
0xFFFFA726.toInt() to "Amber",
|
||||
0xFFFF5252.toInt() to "Red",
|
||||
0xFFFF6FB5.toInt() to "Pink",
|
||||
)
|
||||
|
||||
val opacities = listOf(40, 60, 80, 100)
|
||||
|
||||
val sizes = listOf(80, 90, 100, 110, 125)
|
||||
|
||||
val mappable = listOf(
|
||||
"a" to "A button", "b" to "B button", "x" to "X button", "y" to "Y button",
|
||||
"lb" to "Left bumper", "rb" to "Right bumper", "lt" to "Left trigger", "rt" to "Right trigger",
|
||||
"select" to "View button", "start" to "Menu button",
|
||||
)
|
||||
|
||||
val targets = listOf(
|
||||
"a" to "A", "b" to "B", "x" to "X", "y" to "Y",
|
||||
"lb" to "LB", "rb" to "RB", "lt" to "LT", "rt" to "RT",
|
||||
"l3" to "L3", "r3" to "R3", "select" to "View", "start" to "Menu", "guide" to "Steam",
|
||||
"up" to "D-pad up", "down" to "D-pad down", "left" to "D-pad left", "right" to "D-pad right",
|
||||
OFF to "Hidden",
|
||||
)
|
||||
|
||||
class Settings(
|
||||
val tint: Int,
|
||||
val opacity: Int,
|
||||
val size: Int,
|
||||
val stickClick: Boolean,
|
||||
val adaptiveSticks: Boolean,
|
||||
val customLayout: Boolean,
|
||||
val mapping: Map<String, String>,
|
||||
)
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("controller", Context.MODE_PRIVATE)
|
||||
|
||||
fun read(context: Context): Settings {
|
||||
val p = prefs(context)
|
||||
return Settings(
|
||||
tint = p.getInt("tint", STEAM_BLUE),
|
||||
opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100,
|
||||
size = p.getInt("size", 100).takeIf { it in sizes } ?: 100,
|
||||
stickClick = p.getBoolean("stickClick", true),
|
||||
adaptiveSticks = p.getBoolean("adaptiveSticks", true),
|
||||
customLayout = p.all.keys.any { it.startsWith("layout.") },
|
||||
mapping = mappable.associate { (id, _) -> id to target(context, id) },
|
||||
)
|
||||
}
|
||||
|
||||
fun target(context: Context, id: String): String =
|
||||
prefs(context).getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id
|
||||
|
||||
fun setTarget(context: Context, id: String, target: String) {
|
||||
prefs(context).edit().putString("map.$id", target).apply()
|
||||
}
|
||||
|
||||
fun resetMapping(context: Context) {
|
||||
val p = prefs(context)
|
||||
p.edit().apply { p.all.keys.filter { it.startsWith("map.") }.forEach { remove(it) } }.apply()
|
||||
}
|
||||
|
||||
fun setTint(context: Context, tint: Int) {
|
||||
prefs(context).edit().putInt("tint", tint).apply()
|
||||
}
|
||||
|
||||
fun setOpacity(context: Context, percent: Int) {
|
||||
prefs(context).edit().putInt("opacity", percent).apply()
|
||||
}
|
||||
|
||||
fun setSize(context: Context, percent: Int) {
|
||||
prefs(context).edit().putInt("size", percent).apply()
|
||||
}
|
||||
|
||||
fun setStickClick(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("stickClick", on).apply()
|
||||
}
|
||||
|
||||
fun setAdaptiveSticks(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
|
||||
}
|
||||
|
||||
fun layout(context: Context, width: Int, height: Int): Map<String, Pair<Float, Float>> {
|
||||
val raw = prefs(context).getString("layout.${width}x$height", null) ?: return emptyMap()
|
||||
return raw.split(';').mapNotNull { entry ->
|
||||
val (group, pos) = entry.split(':').takeIf { it.size == 2 } ?: return@mapNotNull null
|
||||
val (x, y) = pos.split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 2 } ?: return@mapNotNull null
|
||||
group to (x to y)
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
fun setLayout(context: Context, width: Int, height: Int, positions: Map<String, Pair<Float, Float>>) {
|
||||
val raw = positions.entries.joinToString(";") { (group, pos) -> "$group:${pos.first},${pos.second}" }
|
||||
prefs(context).edit().putString("layout.${width}x$height", raw).apply()
|
||||
}
|
||||
|
||||
fun resetLayout(context: Context, width: Int, height: Int) {
|
||||
prefs(context).edit().remove("layout.${width}x$height").apply()
|
||||
}
|
||||
|
||||
fun resetAll(context: Context) {
|
||||
prefs(context).edit().clear().apply()
|
||||
}
|
||||
|
||||
fun resetAllLayouts(context: Context) {
|
||||
val p = prefs(context)
|
||||
p.edit().apply { p.all.keys.filter { it.startsWith("layout.") }.forEach { remove(it) } }.apply()
|
||||
}
|
||||
}
|
||||
@@ -5,251 +5,437 @@ import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import android.os.Build
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* A pad drawn on the screen for devices that have no controller attached.
|
||||
*
|
||||
* It writes into the same [PadBridge] a physical pad does, so the Steam client sees one Xbox pad
|
||||
* whichever is being used, and the two can be used at once. A d-pad, two sticks, the four face
|
||||
* buttons, the bumpers, and the three centre buttons: enough to drive Big Picture and to play,
|
||||
* and no control editor.
|
||||
*
|
||||
* Where the controls go follows the picture. The compositor letterboxes the session's output onto
|
||||
* the panel, and a foldable or a wide phone has bars beside or above and below it that are empty
|
||||
* black: the controls take the bars first, and only overlay the picture when there are none wide
|
||||
* enough. Only the controls themselves take touches; everything else falls through to the
|
||||
* activity, where it moves the mouse pointer.
|
||||
*/
|
||||
@SuppressLint("ViewConstructor")
|
||||
class OnScreenControls(context: Context, private val pad: PadBridge) : View(context) {
|
||||
class OnScreenControls(context: Context, private val pad: PadBridge?, private val editing: Boolean = false) : View(context) {
|
||||
|
||||
private class Control(
|
||||
val id: String,
|
||||
val label: String,
|
||||
/** A PadState button number, or -1. */
|
||||
val button: Int,
|
||||
/** A d-pad direction (0 up, 1 right, 2 down, 3 left), or -1. */
|
||||
val dpad: Int,
|
||||
/** 0 = left stick, 1 = right stick, -1 = a button. */
|
||||
val group: String,
|
||||
val stick: Int,
|
||||
val radius: Float,
|
||||
val radiusDp: Float,
|
||||
val offsetXDp: Float,
|
||||
val offsetYDp: Float,
|
||||
) {
|
||||
var target = id
|
||||
var radius = 0f
|
||||
var cx = 0f
|
||||
var cy = 0f
|
||||
var pressedBy = -1 // the pointer id holding it, or -1
|
||||
/** A stick's knob offset from its centre, in [-radius, radius]. */
|
||||
var pressedBy = -1
|
||||
var kx = 0f
|
||||
var ky = 0f
|
||||
/** A stick that moved or was let go: its axes are written once, then left alone. */
|
||||
var ax = 0f
|
||||
var ay = 0f
|
||||
var dirty = false
|
||||
fun contains(x: Float, y: Float, radius: Float = this.radius): Boolean {
|
||||
var clicked = false
|
||||
var lastUp = 0L
|
||||
val wide = id in shoulderIds
|
||||
val halfW get() = if (wide) radius * SHOULDER_WIDTH else radius
|
||||
val halfH get() = if (wide) radius * SHOULDER_HEIGHT else radius
|
||||
|
||||
fun contains(x: Float, y: Float, r: Float): Boolean {
|
||||
val dx = x - cx
|
||||
val dy = y - cy
|
||||
// A generous hit area: a finger on glass is not a mouse, and a miss in Big Picture
|
||||
// means the user thinks the pad does not work.
|
||||
val r = radius * 1.25f
|
||||
return dx * dx + dy * dy <= r * r
|
||||
if (wide) return abs(dx) <= halfW + r * 0.25f && abs(dy) <= halfH + r * 0.25f
|
||||
val hit = r * 1.25f
|
||||
return dx * dx + dy * dy <= hit * hit
|
||||
}
|
||||
/** Moves the knob towards the finger, clamped to the base. */
|
||||
|
||||
fun drag(x: Float, y: Float) {
|
||||
var dx = x - cx
|
||||
var dy = y - cy
|
||||
var dx = x - ax
|
||||
var dy = y - ay
|
||||
val d = sqrt(dx * dx + dy * dy)
|
||||
if (d > radius) { dx = dx / d * radius; dy = dy / d * radius }
|
||||
kx = dx; ky = dy; dirty = true
|
||||
}
|
||||
}
|
||||
|
||||
private val density = resources.displayMetrics.density
|
||||
private fun dp(value: Float) = value * density
|
||||
|
||||
private val controls = listOf(
|
||||
Control("up", "▲", -1, 0, -1, dp(26f)),
|
||||
Control("right", ">", -1, 1, -1, dp(26f)),
|
||||
Control("down", "▼", -1, 2, -1, dp(26f)),
|
||||
Control("left", "<", -1, 3, -1, dp(26f)),
|
||||
Control("ls", "L", -1, -1, 0, dp(48f)),
|
||||
Control("rs", "R", -1, -1, 1, dp(48f)),
|
||||
Control("a", "A", 0, -1, -1, dp(30f)),
|
||||
Control("b", "B", 1, -1, -1, dp(30f)),
|
||||
Control("x", "X", 2, -1, -1, dp(30f)),
|
||||
Control("y", "Y", 3, -1, -1, dp(30f)),
|
||||
Control("lb", "LB", 4, -1, -1, dp(24f)),
|
||||
Control("rb", "RB", 5, -1, -1, dp(24f)),
|
||||
Control("select", "⧉", 6, -1, -1, dp(20f)),
|
||||
Control("start", "☰", 7, -1, -1, dp(20f)),
|
||||
// The client's own in-game menu; the interposer publishes it as BTN_MODE.
|
||||
Control("guide", "◉", PadState.GUIDE, -1, -1, dp(22f)),
|
||||
Control("qam", "⋯", -1, -1, -1, dp(22f)),
|
||||
Control("up", "dpad", -1, 26f, 0f, -52f),
|
||||
Control("right", "dpad", -1, 26f, 52f, 0f),
|
||||
Control("down", "dpad", -1, 26f, 0f, 52f),
|
||||
Control("left", "dpad", -1, 26f, -52f, 0f),
|
||||
Control("ls", "ls", 0, 48f, 0f, 0f),
|
||||
Control("rs", "rs", 1, 48f, 0f, 0f),
|
||||
Control("a", "face", -1, 30f, 0f, 50f),
|
||||
Control("b", "face", -1, 30f, 50f, 0f),
|
||||
Control("x", "face", -1, 30f, -50f, 0f),
|
||||
Control("y", "face", -1, 30f, 0f, -50f),
|
||||
Control("lb", "lb", -1, 24f, 0f, 0f),
|
||||
Control("rb", "rb", -1, 24f, 0f, 0f),
|
||||
Control("lt", "lt", -1, 24f, 0f, 0f),
|
||||
Control("rt", "rt", -1, 24f, 0f, 0f),
|
||||
Control("select", "select", -1, 20f, 0f, 0f),
|
||||
Control("start", "start", -1, 20f, 0f, 0f),
|
||||
Control("guide", "guide", -1, 22f, 0f, 0f),
|
||||
Control("qam", "qam", -1, 22f, 0f, 0f),
|
||||
)
|
||||
|
||||
private val groups = controls.map { it.group }.distinct()
|
||||
|
||||
private var buttonsOnly = false
|
||||
private var settings = ControllerPrefs.read(context)
|
||||
private var safe = Rect()
|
||||
private var selected: String? = null
|
||||
private var grabX = 0f
|
||||
private var grabY = 0f
|
||||
private var ignoreSaved = false
|
||||
private var fit = 1f
|
||||
|
||||
private var idleFill = 0
|
||||
private var heldFill = 0
|
||||
private var idleStroke = 0
|
||||
private var heldStroke = 0
|
||||
private var idleText = 0
|
||||
private var stickFill = 0
|
||||
private var knobFill = 0
|
||||
|
||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = dp(1.5f)
|
||||
}
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
||||
private val arrow = Path()
|
||||
private val box = RectF()
|
||||
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textAlign = Paint.Align.CENTER
|
||||
typeface = android.graphics.Typeface.DEFAULT_BOLD
|
||||
}
|
||||
|
||||
/** Where the session's picture is drawn on this view, or null when the whole view is picture. */
|
||||
private var picture: RectF? = null
|
||||
init {
|
||||
applySettings()
|
||||
}
|
||||
|
||||
/** The activity tells the controls where the picture lands; the layout follows it. */
|
||||
fun setPicture(rect: RectF?) {
|
||||
val same = (rect == null && picture == null) || (rect != null && picture != null && rect == picture)
|
||||
if (same) return
|
||||
picture = rect?.let { RectF(it) }
|
||||
if (width > 0 && height > 0) { layoutControls(width.toFloat(), height.toFloat()); invalidate() }
|
||||
private fun dp(value: Float) = value * resources.displayMetrics.density
|
||||
|
||||
private fun scaled(value: Float) = dp(value) * settings.size / 100f * fit
|
||||
|
||||
private fun fitScale(): Float {
|
||||
val metrics = resources.displayMetrics
|
||||
val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi)
|
||||
val faceMm = dp(60f) / pxPerMm(metrics.xdpi)
|
||||
val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f)
|
||||
return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f)
|
||||
}
|
||||
|
||||
fun reload() {
|
||||
releaseAll()
|
||||
settings = ControllerPrefs.read(context)
|
||||
applySettings()
|
||||
relayout()
|
||||
}
|
||||
|
||||
private fun applySettings() {
|
||||
for (control in controls) control.target = settings.mapping[control.id] ?: control.id
|
||||
val tint = settings.tint
|
||||
val alpha = settings.opacity / 100f
|
||||
fun shade(a: Int, f: Float) = Color.argb((a * alpha).toInt(), (Color.red(tint) * f).toInt(), (Color.green(tint) * f).toInt(), (Color.blue(tint) * f).toInt())
|
||||
fun light(a: Int, f: Float) = Color.argb(
|
||||
(a * alpha).toInt(),
|
||||
(Color.red(tint) + (255 - Color.red(tint)) * f).toInt(),
|
||||
(Color.green(tint) + (255 - Color.green(tint)) * f).toInt(),
|
||||
(Color.blue(tint) + (255 - Color.blue(tint)) * f).toInt(),
|
||||
)
|
||||
idleFill = shade(80, 0.12f)
|
||||
heldFill = shade(160, 1f)
|
||||
idleStroke = light(150, 0.25f)
|
||||
heldStroke = light(230, 0.7f)
|
||||
idleText = light(210, 0.75f)
|
||||
stickFill = shade(60, 0.12f)
|
||||
knobFill = shade(120, 0.35f)
|
||||
stroke.strokeWidth = dp(1.5f)
|
||||
}
|
||||
|
||||
fun setButtonsOnly(enabled: Boolean) {
|
||||
if (buttonsOnly == enabled) return
|
||||
releaseAll()
|
||||
buttonsOnly = enabled
|
||||
if (width > 0 && height > 0) layoutControls(width.toFloat(), height.toFloat())
|
||||
invalidate()
|
||||
relayout()
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
super.onSizeChanged(w, h, oldw, oldh)
|
||||
layoutControls(w.toFloat(), h.toFloat())
|
||||
relayout()
|
||||
}
|
||||
|
||||
/**
|
||||
* Three layouts: side bars (a wide panel showing 16:9), bottom band (a squarer panel showing
|
||||
* a wide picture), and the overlay when neither bar is wide enough for a cluster. Thumbs reach
|
||||
* the bottom corners in every one; nothing is placed where a game's own HUD usually is.
|
||||
*/
|
||||
private fun layoutControls(w: Float, h: Float) {
|
||||
if (buttonsOnly) {
|
||||
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
|
||||
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
|
||||
val fresh = Rect(cutout?.safeInsetLeft ?: 0, cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
|
||||
if (fresh != safe) { safe = fresh; relayout() }
|
||||
return super.onApplyWindowInsets(insets)
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
releaseAll()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
private fun relayout() {
|
||||
if (width <= 0 || height <= 0) return
|
||||
fit = if (buttonsOnly && !editing) 1f else fitScale()
|
||||
for (control in controls) control.radius = if (buttonsOnly && !editing && (control.id == "guide" || control.id == "qam")) dp(30f) else scaled(control.radiusDp)
|
||||
if (buttonsOnly && !editing) {
|
||||
val inset = dp(44f)
|
||||
place("guide", inset, h - inset)
|
||||
place("qam", w - inset, h - inset)
|
||||
return
|
||||
put("guide", safe.left + inset, height - safe.bottom - inset)
|
||||
put("qam", width - safe.right - inset, height - safe.bottom - inset)
|
||||
} else {
|
||||
placeAuto(width.toFloat(), height.toFloat())
|
||||
if (!ignoreSaved) for ((group, pos) in ControllerPrefs.layout(context, width, height)) {
|
||||
if (group in groups) put(group, pos.first * width, pos.second * height)
|
||||
}
|
||||
}
|
||||
val p = picture
|
||||
val sideBar = if (p != null) minOf(p.left, w - p.right) else 0f
|
||||
val bottomBand = if (p != null) h - p.bottom else 0f
|
||||
val margin = dp(34f)
|
||||
when {
|
||||
// A cluster (d-pad or face buttons) is ~156 dp across; a stick above it needs the height.
|
||||
sideBar >= dp(160f) && p != null -> {
|
||||
val lx = p.left / 2f
|
||||
val rx = p.right + (w - p.right) / 2f
|
||||
val bottom = h - margin - dp(74f)
|
||||
dpadAt(lx, bottom)
|
||||
faceAt(rx, bottom)
|
||||
place("ls", lx, bottom - dp(196f))
|
||||
place("rs", rx, bottom - dp(196f))
|
||||
place("lb", lx, bottom - dp(196f) - dp(96f))
|
||||
place("rb", rx, bottom - dp(196f) - dp(96f))
|
||||
place("select", lx, h - margin + dp(8f))
|
||||
place("start", rx, h - margin + dp(8f))
|
||||
place("guide", w / 2f, h - dp(22f))
|
||||
}
|
||||
bottomBand >= dp(190f) && p != null -> {
|
||||
val cy = p.bottom + bottomBand / 2f + dp(12f)
|
||||
val dx = margin + dp(74f)
|
||||
val fx = w - margin - dp(74f)
|
||||
dpadAt(dx, cy)
|
||||
faceAt(fx, cy)
|
||||
place("ls", dx + dp(150f), cy)
|
||||
place("rs", fx - dp(150f), cy)
|
||||
place("lb", dx, p.bottom + dp(30f))
|
||||
place("rb", fx, p.bottom + dp(30f))
|
||||
val centre = w / 2f
|
||||
place("select", centre - dp(60f), h - dp(30f))
|
||||
place("guide", centre, h - dp(30f))
|
||||
place("start", centre + dp(60f), h - dp(30f))
|
||||
}
|
||||
else -> {
|
||||
val dx = margin + dp(74f)
|
||||
val fx = w - margin - dp(74f)
|
||||
val bottom = h - margin - dp(74f)
|
||||
dpadAt(dx, bottom)
|
||||
faceAt(fx, bottom)
|
||||
place("ls", dx + dp(142f), bottom)
|
||||
place("rs", fx - dp(142f), bottom)
|
||||
place("lb", margin + dp(46f), h - margin - dp(196f))
|
||||
place("rb", w - margin - dp(46f), h - margin - dp(196f))
|
||||
val centre = w / 2f
|
||||
place("select", centre - dp(60f), h - margin - dp(26f))
|
||||
place("guide", centre, h - margin - dp(26f))
|
||||
place("start", centre + dp(60f), h - margin - dp(26f))
|
||||
groups.forEach { clamp(it) }
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun pxPerMm(dpi: Float): Float {
|
||||
val nominal = resources.displayMetrics.densityDpi.toFloat()
|
||||
return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f
|
||||
}
|
||||
|
||||
private fun placeAuto(w: Float, h: Float) {
|
||||
val metrics = resources.displayMetrics
|
||||
val mmX = pxPerMm(metrics.xdpi)
|
||||
val mmY = pxPerMm(metrics.ydpi)
|
||||
val usableW = w - safe.left - safe.right
|
||||
val usableH = h - safe.top - safe.bottom
|
||||
val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX
|
||||
val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY
|
||||
val gap = dp(12f)
|
||||
val floor = BOTTOM_MARGIN_MM * mmY
|
||||
val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap))
|
||||
val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop)
|
||||
put("ls", safe.left + inboard, restY)
|
||||
put("face", w - safe.right - inboard, restY)
|
||||
besideBelow("dpad", "ls", 1f, gap, floor)
|
||||
besideBelow("rs", "face", -1f, gap, floor)
|
||||
val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM
|
||||
val shoulderY = if (phone) safe.top + floor + halfH("lb")
|
||||
else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb")
|
||||
shoulders("ls", "lb", "lt", 1f, gap, shoulderY)
|
||||
shoulders("face", "rb", "rt", -1f, gap, shoulderY)
|
||||
val bottom = h - safe.bottom - floor - extent("guide")
|
||||
val spread = extent("guide") + gap / 2f
|
||||
put("guide", w / 2f - spread, bottom)
|
||||
put("qam", w / 2f + spread, bottom)
|
||||
val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select")
|
||||
put("select", inner, restY)
|
||||
put("start", w - inner, restY)
|
||||
if (phone) {
|
||||
val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select")
|
||||
put("select", top, shoulderY)
|
||||
put("start", w - top, shoulderY)
|
||||
}
|
||||
if (crowded("select", gap) || crowded("start", gap)) {
|
||||
above("select", "dpad", gap)
|
||||
val (sx, sy) = centre("select")
|
||||
put("start", w - sx, sy)
|
||||
if (crowded("start", gap)) above("start", "rs", gap)
|
||||
}
|
||||
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
|
||||
val row = centre("select").second
|
||||
put("guide", w / 2f - spread, row)
|
||||
put("qam", w / 2f + spread, row)
|
||||
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
|
||||
val top = safe.top + dp(8f) + extent("guide")
|
||||
put("guide", w / 2f - spread, top)
|
||||
put("qam", w / 2f + spread, top)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun dpadAt(x: Float, y: Float) {
|
||||
val step = dp(52f)
|
||||
place("up", x, y - step)
|
||||
place("down", x, y + step)
|
||||
place("left", x - step, y)
|
||||
place("right", x + step, y)
|
||||
private fun drop(group: String, anchor: String, gap: Float): Float =
|
||||
(extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group)
|
||||
|
||||
private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) {
|
||||
val (ax, ay) = centre(anchor)
|
||||
val reach = extent(anchor) + extent(group) + gap
|
||||
val floor = height - safe.bottom - margin - extent(group)
|
||||
val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay)
|
||||
val dx = sqrt(max(0f, reach * reach - dy * dy))
|
||||
put(group, ax + inward * dx, ay + dy)
|
||||
}
|
||||
|
||||
private fun faceAt(x: Float, y: Float) {
|
||||
val step = dp(50f)
|
||||
place("a", x, y + step)
|
||||
place("b", x + step, y)
|
||||
place("x", x - step, y)
|
||||
place("y", x, y - step)
|
||||
private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) {
|
||||
val (ax, _) = centre(anchor)
|
||||
val spread = extent(bumper) + gap / 2f
|
||||
put(bumper, ax + inward * spread, y)
|
||||
put(trigger, ax - inward * spread, y)
|
||||
}
|
||||
|
||||
private fun place(id: String, x: Float, y: Float) {
|
||||
val control = controls.firstOrNull { it.id == id } ?: return
|
||||
control.cx = x
|
||||
control.cy = y
|
||||
private fun above(group: String, anchor: String, gap: Float) {
|
||||
val (ax, ay) = centre(anchor)
|
||||
put(group, ax, ay - extent(anchor) - gap - extent(group))
|
||||
}
|
||||
|
||||
private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean {
|
||||
val (x, y) = centre(group)
|
||||
return groups.any { other ->
|
||||
if (other == group || other == except) return@any false
|
||||
val (ox, oy) = centre(other)
|
||||
val dx = x - ox
|
||||
val dy = y - oy
|
||||
sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space
|
||||
}
|
||||
}
|
||||
|
||||
private fun members(group: String) = controls.filter { it.group == group }
|
||||
|
||||
private fun centre(group: String): Pair<Float, Float> {
|
||||
val first = members(group).first()
|
||||
return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp))
|
||||
}
|
||||
|
||||
private fun extent(group: String): Float = members(group).maxOf { control ->
|
||||
sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW
|
||||
}
|
||||
|
||||
private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH }
|
||||
|
||||
private fun put(group: String, x: Float, y: Float) {
|
||||
for (control in members(group)) {
|
||||
control.cx = x + scaled(control.offsetXDp)
|
||||
control.cy = y + scaled(control.offsetYDp)
|
||||
}
|
||||
}
|
||||
|
||||
private fun clamp(group: String) {
|
||||
val list = members(group)
|
||||
val margin = dp(4f)
|
||||
val minX = list.minOf { it.cx - it.halfW } - safe.left - margin
|
||||
val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin)
|
||||
val minY = list.minOf { it.cy - it.halfH } - safe.top - margin
|
||||
val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin)
|
||||
val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f
|
||||
val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f
|
||||
if (dx == 0f && dy == 0f) return
|
||||
for (control in list) { control.cx += dx; control.cy += dy }
|
||||
}
|
||||
|
||||
fun saveLayout() {
|
||||
if (width <= 0 || height <= 0) return
|
||||
if (ignoreSaved) { ControllerPrefs.resetLayout(context, width, height); return }
|
||||
ControllerPrefs.setLayout(context, width, height, groups.associateWith { group ->
|
||||
val (x, y) = centre(group)
|
||||
x / width to y / height
|
||||
})
|
||||
}
|
||||
|
||||
fun resetLayout() {
|
||||
ControllerPrefs.resetLayout(context, width, height)
|
||||
ignoreSaved = true
|
||||
selected = null
|
||||
relayout()
|
||||
}
|
||||
|
||||
private fun label(control: Control): String = when (control.target) {
|
||||
"ls" -> "L"
|
||||
"rs" -> "R"
|
||||
"select" -> "⧉"
|
||||
"start" -> "☰"
|
||||
"guide" -> if (buttonsOnly && !editing) "Steam" else "◉"
|
||||
"qam" -> "⋯"
|
||||
else -> control.target.uppercase()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
for (control in controls) {
|
||||
if (!isVisible(control)) continue
|
||||
val held = control.pressedBy != -1
|
||||
val radius = controlRadius(control)
|
||||
val radius = control.radius
|
||||
if (control.stick >= 0) {
|
||||
// The base, then the knob where the finger holds it.
|
||||
fill.color = if (held) Color.argb(60, 199, 125, 255) else Color.argb(50, 20, 12, 30)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, fill)
|
||||
stroke.color = if (held) Color.argb(200, 235, 212, 255) else Color.argb(90, 201, 160, 255)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, stroke)
|
||||
val bx = if (held) control.ax else control.cx
|
||||
val by = if (held) control.ay else control.cy
|
||||
fill.color = if (held) heldFill else stickFill
|
||||
canvas.drawCircle(bx, by, radius, fill)
|
||||
stroke.color = if (held) heldStroke else idleStroke
|
||||
canvas.drawCircle(bx, by, radius, stroke)
|
||||
val knob = radius * 0.46f
|
||||
fill.color = if (held) Color.argb(170, 199, 125, 255) else Color.argb(110, 60, 40, 90)
|
||||
canvas.drawCircle(control.cx + control.kx, control.cy + control.ky, knob, fill)
|
||||
stroke.color = if (held) Color.argb(230, 245, 230, 255) else Color.argb(140, 201, 160, 255)
|
||||
canvas.drawCircle(control.cx + control.kx, control.cy + control.ky, knob, stroke)
|
||||
text.color = if (held) Color.WHITE else Color.argb(150, 225, 210, 245)
|
||||
fill.color = if (held || control.clicked) heldFill else knobFill
|
||||
canvas.drawCircle(bx + control.kx, by + control.ky, knob, fill)
|
||||
stroke.color = if (held) heldStroke else idleStroke
|
||||
canvas.drawCircle(bx + control.kx, by + control.ky, knob, stroke)
|
||||
text.color = if (held) Color.WHITE else idleText
|
||||
text.textSize = knob * 0.8f
|
||||
canvas.drawText(control.label, control.cx + control.kx, control.cy + control.ky + text.textSize * 0.35f, text)
|
||||
continue
|
||||
canvas.drawText(label(control), bx + control.kx, by + control.ky + text.textSize * 0.35f, text)
|
||||
} else if (control.wide) {
|
||||
box.set(control.cx - control.halfW, control.cy - control.halfH, control.cx + control.halfW, control.cy + control.halfH)
|
||||
val corner = control.halfH * 0.55f
|
||||
fill.color = if (held) heldFill else idleFill
|
||||
canvas.drawRoundRect(box, corner, corner, fill)
|
||||
stroke.color = if (held) heldStroke else idleStroke
|
||||
canvas.drawRoundRect(box, corner, corner, stroke)
|
||||
text.color = if (held) Color.WHITE else idleText
|
||||
text.textSize = control.halfH * 0.8f
|
||||
canvas.drawText(label(control), control.cx, control.cy + text.textSize * 0.35f, text)
|
||||
} else {
|
||||
fill.color = if (held) heldFill else idleFill
|
||||
canvas.drawCircle(control.cx, control.cy, radius, fill)
|
||||
stroke.color = if (held) heldStroke else idleStroke
|
||||
canvas.drawCircle(control.cx, control.cy, radius, stroke)
|
||||
text.color = if (held) Color.WHITE else idleText
|
||||
val direction = directions.indexOf(control.target)
|
||||
if (direction >= 0) {
|
||||
drawArrow(canvas, control.cx, control.cy, radius * 0.34f, direction)
|
||||
continue
|
||||
}
|
||||
val name = label(control)
|
||||
text.textSize = if (name.length > 2) dp(11f) else radius * if (name.length == 2) 0.62f else 0.85f
|
||||
canvas.drawText(name, control.cx, control.cy + text.textSize * 0.35f, text)
|
||||
}
|
||||
fill.color = if (held) Color.argb(150, 199, 125, 255) else Color.argb(70, 20, 12, 30)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, fill)
|
||||
stroke.color = if (held) Color.argb(220, 235, 212, 255) else Color.argb(110, 201, 160, 255)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, stroke)
|
||||
text.color = if (held) Color.WHITE else Color.argb(190, 225, 210, 245)
|
||||
val label = if (buttonsOnly && control.id == "guide") "Steam" else control.label
|
||||
text.textSize = if (buttonsOnly && control.id == "guide") dp(11f) else radius * 0.85f
|
||||
canvas.drawText(label, control.cx, control.cy + text.textSize * 0.35f, text)
|
||||
}
|
||||
val group = selected ?: return
|
||||
val (x, y) = centre(group)
|
||||
stroke.color = heldStroke
|
||||
val single = members(group).singleOrNull()
|
||||
if (single?.wide == true) {
|
||||
val pad = dp(6f)
|
||||
box.set(x - single.halfW - pad, y - single.halfH - pad, x + single.halfW + pad, y + single.halfH + pad)
|
||||
canvas.drawRoundRect(box, single.halfH, single.halfH, stroke)
|
||||
} else canvas.drawCircle(x, y, extent(group) + dp(6f), stroke)
|
||||
}
|
||||
|
||||
private fun drawArrow(canvas: Canvas, x: Float, y: Float, size: Float, direction: Int) {
|
||||
val (fx, fy) = when (direction) {
|
||||
0 -> 0f to -1f
|
||||
1 -> 1f to 0f
|
||||
2 -> 0f to 1f
|
||||
else -> -1f to 0f
|
||||
}
|
||||
arrow.reset()
|
||||
arrow.moveTo(x + fx * size, y + fy * size)
|
||||
arrow.lineTo(x - fx * size * 0.7f - fy * size, y - fy * size * 0.7f + fx * size)
|
||||
arrow.lineTo(x - fx * size * 0.7f + fy * size, y - fy * size * 0.7f - fx * size)
|
||||
arrow.close()
|
||||
fill.color = text.color
|
||||
canvas.drawPath(arrow, fill)
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (editing) return onEditTouch(event)
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
val index = event.actionIndex
|
||||
val control = controlAt(event.getX(index), event.getY(index)) ?: return false
|
||||
control.pressedBy = event.getPointerId(index)
|
||||
if (control.stick >= 0) control.drag(event.getX(index), event.getY(index))
|
||||
if (control.stick >= 0) {
|
||||
control.clicked = settings.stickClick && event.eventTime - control.lastUp < DOUBLE_TAP_MS
|
||||
val adaptive = settings.adaptiveSticks
|
||||
control.ax = if (adaptive) event.getX(index) else control.cx
|
||||
control.ay = if (adaptive) event.getY(index) else control.cy
|
||||
control.drag(event.getX(index), event.getY(index))
|
||||
}
|
||||
requestUnbufferedDispatch(event)
|
||||
apply()
|
||||
return true
|
||||
}
|
||||
@@ -259,11 +445,8 @@ class OnScreenControls(context: Context, private val pad: PadBridge) : View(cont
|
||||
val pointer = event.getPointerId(index)
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
// A stick keeps its finger wherever it goes: the knob follows, clamped.
|
||||
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
|
||||
if (stick != null) { stick.drag(x, y); changed = true; continue }
|
||||
// A finger that slides off a button releases it, and one that slides onto
|
||||
// another presses that - which is how a d-pad is used in practice.
|
||||
val over = controlAt(x, y)?.takeIf { it.stick < 0 }
|
||||
for (control in controls) {
|
||||
if (control.stick < 0 && control.pressedBy == pointer && control !== over) {
|
||||
@@ -285,7 +468,9 @@ class OnScreenControls(context: Context, private val pad: PadBridge) : View(cont
|
||||
for (control in controls) {
|
||||
if (control.pressedBy == pointer || event.actionMasked == MotionEvent.ACTION_CANCEL) {
|
||||
if (control.pressedBy != -1) changed = true
|
||||
if (control.stick >= 0 && control.pressedBy != -1) control.lastUp = if (control.clicked) 0L else event.eventTime
|
||||
control.pressedBy = -1
|
||||
control.clicked = false
|
||||
if (control.stick >= 0 && (control.kx != 0f || control.ky != 0f)) control.dirty = true
|
||||
control.kx = 0f; control.ky = 0f
|
||||
}
|
||||
@@ -297,45 +482,114 @@ class OnScreenControls(context: Context, private val pad: PadBridge) : View(cont
|
||||
return false
|
||||
}
|
||||
|
||||
private fun onEditTouch(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
val control = controlAt(event.x, event.y)
|
||||
selected = control?.group
|
||||
val group = selected ?: run { invalidate(); return false }
|
||||
val (x, y) = centre(group)
|
||||
grabX = x - event.x
|
||||
grabY = y - event.y
|
||||
invalidate()
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val group = selected ?: return true
|
||||
ignoreSaved = false
|
||||
put(group, event.x + grabX, event.y + grabY)
|
||||
clamp(group)
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun controlAt(x: Float, y: Float): Control? =
|
||||
controls.firstOrNull { isVisible(it) && it.contains(x, y, controlRadius(it)) }
|
||||
controls.firstOrNull { isVisible(it) && it.contains(x, y, it.radius) }
|
||||
|
||||
private fun isVisible(control: Control): Boolean =
|
||||
!buttonsOnly || control.id == "guide" || control.id == "qam"
|
||||
|
||||
private fun controlRadius(control: Control): Float =
|
||||
if (buttonsOnly && (control.id == "guide" || control.id == "qam")) dp(30f) else control.radius
|
||||
private fun isVisible(control: Control): Boolean = when {
|
||||
buttonsOnly && !editing -> control.id == "guide" || control.id == "qam"
|
||||
else -> control.target != ControllerPrefs.OFF
|
||||
}
|
||||
|
||||
private fun apply() {
|
||||
val bridge = pad
|
||||
if (bridge == null || editing) { invalidate(); return }
|
||||
val qamHeld = controls.any { it.id == "qam" && it.pressedBy != -1 }
|
||||
if (buttonsOnly) {
|
||||
val guidePressed = controls.first { it.id == "guide" }.pressedBy != -1
|
||||
val qamPressed = controls.first { it.id == "qam" }.pressedBy != -1
|
||||
pad.setSystemButtons(guidePressed, qamPressed)
|
||||
bridge.setSystemButtons(controls.any { it.id == "guide" && it.pressedBy != -1 }, qamHeld)
|
||||
} else {
|
||||
pad.setSystemButtons(false, false)
|
||||
pad.applyTouch { state ->
|
||||
bridge.setSystemButtons(false, qamHeld)
|
||||
bridge.applyTouch { state ->
|
||||
val used = HashSet<String>()
|
||||
val held = HashSet<String>()
|
||||
for (control in controls) {
|
||||
val held = control.pressedBy != -1
|
||||
when {
|
||||
control.stick >= 0 && !control.dirty -> {}
|
||||
control.stick == 0 -> { state.leftX = control.kx / control.radius; state.leftY = control.ky / control.radius; control.dirty = false }
|
||||
control.stick == 1 -> { state.rightX = control.kx / control.radius; state.rightY = control.ky / control.radius; control.dirty = false }
|
||||
control.dpad == 0 -> state.up = held
|
||||
control.dpad == 1 -> state.right = held
|
||||
control.dpad == 2 -> state.down = held
|
||||
control.dpad == 3 -> state.left = held
|
||||
control.button >= 0 -> state.press(control.button, held)
|
||||
control.stick >= 0 -> {
|
||||
val click = if (control.stick == 0) "l3" else "r3"
|
||||
if (settings.stickClick) used.add(click)
|
||||
if (control.clicked) held.add(click)
|
||||
if (!control.dirty) continue
|
||||
if (control.stick == 0) { state.leftX = control.kx / control.radius; state.leftY = control.ky / control.radius }
|
||||
else { state.rightX = control.kx / control.radius; state.rightY = control.ky / control.radius }
|
||||
control.dirty = false
|
||||
}
|
||||
control.id == "qam" || control.target == ControllerPrefs.OFF -> {}
|
||||
else -> {
|
||||
used.add(control.target)
|
||||
if (control.pressedBy != -1) held.add(control.target)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (target in used) write(state, target, target in held)
|
||||
}
|
||||
}
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** Everything up, for when the controls are hidden mid-press. */
|
||||
private fun write(state: PadState, target: String, down: Boolean) {
|
||||
when (target) {
|
||||
"a" -> state.press(PadState.A, down)
|
||||
"b" -> state.press(PadState.B, down)
|
||||
"x" -> state.press(PadState.X, down)
|
||||
"y" -> state.press(PadState.Y, down)
|
||||
"lb" -> state.press(PadState.LB, down)
|
||||
"rb" -> state.press(PadState.RB, down)
|
||||
"select" -> state.press(PadState.SELECT, down)
|
||||
"start" -> state.press(PadState.START, down)
|
||||
"l3" -> state.press(PadState.L3, down)
|
||||
"r3" -> state.press(PadState.R3, down)
|
||||
"guide" -> state.press(PadState.GUIDE, down)
|
||||
"lt" -> state.leftTrigger = if (down) 1f else 0f
|
||||
"rt" -> state.rightTrigger = if (down) 1f else 0f
|
||||
"up" -> state.up = down
|
||||
"right" -> state.right = down
|
||||
"down" -> state.down = down
|
||||
"left" -> state.left = down
|
||||
}
|
||||
}
|
||||
|
||||
fun releaseAll() {
|
||||
if (controls.none { it.pressedBy != -1 } && !buttonsOnly) return
|
||||
controls.forEach { it.pressedBy = -1; if (it.stick >= 0 && (it.kx != 0f || it.ky != 0f)) it.dirty = true; it.kx = 0f; it.ky = 0f }
|
||||
if (controls.none { it.pressedBy != -1 || it.clicked } && !buttonsOnly) return
|
||||
controls.forEach {
|
||||
it.pressedBy = -1
|
||||
it.clicked = false
|
||||
if (it.stick >= 0 && (it.kx != 0f || it.ky != 0f)) it.dirty = true
|
||||
it.kx = 0f; it.ky = 0f
|
||||
}
|
||||
apply()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DOUBLE_TAP_MS = 300L
|
||||
const val MIN_FACE_MM = 9.5f
|
||||
const val FULL_SIZE_HEIGHT_MM = 85f
|
||||
const val BOTTOM_MARGIN_MM = 5f
|
||||
const val DROP_DEGREES = 35.0
|
||||
const val PHONE_MAX_HEIGHT_MM = 90f
|
||||
const val SHOULDER_WIDTH = 1.45f
|
||||
const val SHOULDER_HEIGHT = 0.8f
|
||||
val shoulderIds = setOf("lb", "rb", "lt", "rt")
|
||||
val directions = listOf("up", "right", "down", "left")
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,9 @@ public final class PadBridge {
|
||||
private boolean qamChordActive;
|
||||
private boolean qamSyntheticAPressed;
|
||||
private int qamChordGeneration;
|
||||
/** Told on the main thread when a player uses the pad or the on-screen controls; see [setOnPlayerInput]. */
|
||||
private volatile Runnable onPlayerInput;
|
||||
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
|
||||
public PadBridge(File fakeInputDir) {
|
||||
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
|
||||
@@ -87,6 +90,24 @@ public final class PadBridge {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called (main thread) when a player presses a button, pushes a stick, trigger or d-pad past
|
||||
* halfway, or uses the on-screen controls - the session hides its mouse cursor then. Resting
|
||||
* sticks and trigger noise do not count.
|
||||
*/
|
||||
public void setOnPlayerInput(Runnable listener) {
|
||||
onPlayerInput = listener;
|
||||
}
|
||||
|
||||
private void notePlayerInput() {
|
||||
Runnable listener = onPlayerInput;
|
||||
if (listener == null || !playerInputPosted.compareAndSet(false, true)) return;
|
||||
mainHandler.post(() -> {
|
||||
playerInputPosted.set(false);
|
||||
listener.run();
|
||||
});
|
||||
}
|
||||
|
||||
/** @return true when the event was a pad button and has been consumed. */
|
||||
public synchronized boolean onKeyEvent(KeyEvent event) {
|
||||
if (!isFromController(event.getDevice())) return false;
|
||||
@@ -116,6 +137,7 @@ public final class PadBridge {
|
||||
case KeyEvent.KEYCODE_DPAD_LEFT: state.left = pressed; break;
|
||||
default: return false;
|
||||
}
|
||||
if (pressed) notePlayerInput();
|
||||
publish();
|
||||
return true;
|
||||
}
|
||||
@@ -143,6 +165,10 @@ public final class PadBridge {
|
||||
state.right = hatX > 0.5f;
|
||||
state.down = hatY > 0.5f;
|
||||
state.left = hatX < -0.5f;
|
||||
if (Math.max(Math.max(Math.abs(state.leftX), Math.abs(state.leftY)), Math.max(Math.abs(state.rightX), Math.abs(state.rightY))) > 0.5f
|
||||
|| lt > 0.5f || rt > 0.5f || state.up || state.right || state.down || state.left) {
|
||||
notePlayerInput();
|
||||
}
|
||||
publish();
|
||||
return true;
|
||||
}
|
||||
@@ -153,6 +179,7 @@ public final class PadBridge {
|
||||
*/
|
||||
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
|
||||
mutation.accept(state);
|
||||
notePlayerInput();
|
||||
publish();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.view.Display
|
||||
|
||||
/** The control surface shown on a secondary Android display during a Linux session. */
|
||||
enum class SecondScreenMode(val id: String, val label: String) {
|
||||
NONE("none", "None"),
|
||||
@@ -8,3 +11,19 @@ enum class SecondScreenMode(val id: String, val label: String) {
|
||||
}
|
||||
|
||||
data class SecondScreenDisplay(val id: Int, val label: String)
|
||||
|
||||
/** The presentation-capable displays shared by the session controls and Android app launcher. */
|
||||
object SecondScreenDisplays {
|
||||
fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List<SecondScreenDisplay> =
|
||||
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION)
|
||||
.asSequence()
|
||||
.filter { it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 }
|
||||
.map { target ->
|
||||
val mode = target.mode
|
||||
SecondScreenDisplay(
|
||||
target.displayId,
|
||||
"${target.name} · ${mode.physicalWidth}×${mode.physicalHeight}",
|
||||
)
|
||||
}
|
||||
.toList()
|
||||
}
|
||||
@@ -16,6 +16,10 @@ import kotlin.math.abs
|
||||
* - two fingers up / down ............ scroll wheel
|
||||
* - hold still, then drag ............ left-button drag
|
||||
* - double-tap, hold, drag ........... left-button drag as well
|
||||
* - one finger held, another slides .. left-button drag, as on a laptop's pad: the held finger is
|
||||
* the button, the other moves the pointer (a window by its
|
||||
* title bar or edge, a desktop icon). The sliding finger may
|
||||
* lift and slide again; lifting the held one drops.
|
||||
*
|
||||
* Positions handed to the listener are the pointer's, in the view's pixels; the caller keeps them
|
||||
* inside the picture.
|
||||
@@ -45,6 +49,16 @@ class TouchpadGestures(
|
||||
private var twoFingers = false
|
||||
private var scrollAnchorY = 0f
|
||||
private var scrolled = false
|
||||
// Hold-and-slide: the first finger stays as the button, the second moves the pointer.
|
||||
private var anchorId = -1
|
||||
private var anchorStartX = 0f
|
||||
private var anchorStartY = 0f
|
||||
private var moverId = -1
|
||||
private var moverStartX = 0f
|
||||
private var moverStartY = 0f
|
||||
private var moverLastX = 0f
|
||||
private var moverLastY = 0f
|
||||
private var holdDrag = false
|
||||
private val longPress = Runnable {
|
||||
held = true
|
||||
dragging = true
|
||||
@@ -63,6 +77,7 @@ class TouchpadGestures(
|
||||
lastX = event.x; lastY = event.y
|
||||
downAt = event.eventTime
|
||||
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
|
||||
anchorId = event.getPointerId(0); moverId = -1; holdDrag = false
|
||||
// A tap shortly before this touch: holding now drags (double-tap-and-hold).
|
||||
if (event.eventTime - lastTapAt < DOUBLE_TAP_MS) {
|
||||
dragging = true
|
||||
@@ -75,6 +90,17 @@ class TouchpadGestures(
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
handler.removeCallbacks(longPress)
|
||||
val i = event.actionIndex
|
||||
if (moverId == -1 && event.getPointerId(i) != anchorId) {
|
||||
moverId = event.getPointerId(i)
|
||||
moverStartX = event.getX(i); moverStartY = event.getY(i)
|
||||
moverLastX = moverStartX; moverLastY = moverStartY
|
||||
event.findPointerIndex(anchorId).takeIf { it >= 0 }?.let {
|
||||
anchorStartX = event.getX(it); anchorStartY = event.getY(it)
|
||||
}
|
||||
}
|
||||
// Mid-drag, a finger coming back only picks the sliding up again.
|
||||
if (holdDrag) return true
|
||||
twoFingers = true
|
||||
secondDownAt = event.eventTime
|
||||
secondWasTap = true
|
||||
@@ -82,6 +108,38 @@ class TouchpadGestures(
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val ai = event.findPointerIndex(anchorId)
|
||||
val mi = if (moverId == -1) -1 else event.findPointerIndex(moverId)
|
||||
if (ai >= 0 && mi >= 0) {
|
||||
val mx = event.getX(mi); val my = event.getY(mi)
|
||||
// One finger still, the other on the move: that is a drag, not a scroll (which
|
||||
// moves both). Decided once, before anything has scrolled.
|
||||
if (!holdDrag && !scrolled) {
|
||||
val anchorMoved = abs(event.getX(ai) - anchorStartX) + abs(event.getY(ai) - anchorStartY)
|
||||
val moverMoved = abs(mx - moverStartX) + abs(my - moverStartY)
|
||||
if (moverMoved > slopPx && anchorMoved < slopPx) {
|
||||
holdDrag = true
|
||||
secondWasTap = false
|
||||
if (!dragging) {
|
||||
dragging = true
|
||||
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (holdDrag) {
|
||||
val dx = mx - moverLastX
|
||||
val dy = my - moverLastY
|
||||
moverLastX = mx; moverLastY = my
|
||||
val speed = abs(dx) + abs(dy)
|
||||
val gain = sensitivity * (1f + minOf(speed / 40f, 1.5f))
|
||||
place(x + dx * gain, y + dy * gain)
|
||||
listener.onMove(x, y)
|
||||
return true
|
||||
}
|
||||
} else if (holdDrag) {
|
||||
// Only the held finger is down: the drag waits for the next slide.
|
||||
return true
|
||||
}
|
||||
if (twoFingers && event.pointerCount >= 2) {
|
||||
val mid = (event.getY(0) + event.getY(1)) / 2f
|
||||
val dy = mid - scrollAnchorY
|
||||
@@ -109,6 +167,30 @@ class TouchpadGestures(
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_UP -> {
|
||||
val gone = event.getPointerId(event.actionIndex)
|
||||
if (holdDrag) {
|
||||
if (gone == anchorId) {
|
||||
// The held finger lifted: drop. The other finger carries on as the pointer.
|
||||
listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
|
||||
dragging = false; holdDrag = false; twoFingers = false
|
||||
anchorId = moverId; moverId = -1
|
||||
event.findPointerIndex(anchorId).takeIf { it >= 0 }?.let {
|
||||
lastX = event.getX(it); lastY = event.getY(it)
|
||||
}
|
||||
travelled = slopPx + 1f
|
||||
} else if (gone == moverId) {
|
||||
moverId = -1
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (gone == moverId) moverId = -1
|
||||
if (gone == anchorId) {
|
||||
// The first finger left a two-finger gesture: the other one is the pointer now.
|
||||
anchorId = event.getPointerId(if (event.actionIndex == 0) 1 else 0)
|
||||
event.findPointerIndex(anchorId).takeIf { it >= 0 }?.let {
|
||||
lastX = event.getX(it); lastY = event.getY(it)
|
||||
}
|
||||
}
|
||||
// The second finger lifting quickly, with nothing scrolled: a right click.
|
||||
if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TAP_MS && !scrolled) {
|
||||
listener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
|
||||
@@ -136,6 +218,7 @@ class TouchpadGestures(
|
||||
}
|
||||
}
|
||||
dragging = false; held = false; twoFingers = false
|
||||
holdDrag = false; anchorId = -1; moverId = -1
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.security.MessageDigest
|
||||
import org.json.JSONArray
|
||||
|
||||
/** Optional Decky Loader installation for the ARM64 Linux guest. */
|
||||
object DeckyManager {
|
||||
private const val TAG = "DeckyManager"
|
||||
const val REPOSITORY = "Droid-Deck/decky-loader"
|
||||
private const val RELEASES = "https://api.github.com/repos/$REPOSITORY/releases?per_page=30"
|
||||
private const val PATH = "root/homebrew/services/PluginLoader"
|
||||
private const val VERSION = "root/homebrew/services/.droiddeck-decky-version"
|
||||
private const val CEF_REMOTE_DEBUG_MARKER = "root/.local/share/Steam/.cef-enable-remote-debugging"
|
||||
|
||||
data class Release(val tag: String, val prerelease: Boolean, val asset: String, val url: String, val digest: String?, val shaUrl: String?, val size: Long, val machine: Int)
|
||||
data class ReleaseChannels(val stable: List<Release>, val prerelease: List<Release>)
|
||||
|
||||
fun installed(context: Context): String? {
|
||||
val loader = loader(context)
|
||||
if (!loader.isFile || !loader.canExecute()) return null
|
||||
return File(LinuxRuntime.rootDir(context), VERSION).takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: "Installed"
|
||||
}
|
||||
|
||||
fun loader(context: Context) = File(LinuxRuntime.rootDir(context), PATH)
|
||||
fun supervisorEnabled(context: Context) = File(LinuxRuntime.rootDir(context), "root/.droiddeck-decky-enabled").isFile
|
||||
|
||||
/** Remove the legacy install-time debugger marker unless the user opted into Decky. */
|
||||
fun syncCefMarker(context: Context) {
|
||||
val marker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER)
|
||||
if (!supervisorEnabled(context)) {
|
||||
marker.delete()
|
||||
return
|
||||
}
|
||||
runCatching {
|
||||
marker.parentFile?.mkdirs()
|
||||
marker.createNewFile()
|
||||
}
|
||||
}
|
||||
|
||||
fun setSupervisorEnabled(context: Context, enabled: Boolean) {
|
||||
val marker = File(LinuxRuntime.rootDir(context), "root/.droiddeck-decky-enabled")
|
||||
val cefMarker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER)
|
||||
if (enabled) {
|
||||
marker.parentFile?.mkdirs()
|
||||
marker.writeText("enabled\n")
|
||||
cefMarker.parentFile?.mkdirs()
|
||||
cefMarker.createNewFile()
|
||||
} else {
|
||||
marker.delete()
|
||||
cefMarker.delete()
|
||||
}
|
||||
}
|
||||
|
||||
fun releases(context: Context, prerelease: Boolean): List<Release> {
|
||||
val channels = releaseChannels(context)
|
||||
return if (prerelease) channels.prerelease else channels.stable
|
||||
}
|
||||
|
||||
fun releaseChannels(context: Context): ReleaseChannels {
|
||||
val body = Downloader.downloadString(RELEASES) ?: return ReleaseChannels(emptyList(), emptyList())
|
||||
return try {
|
||||
val array = JSONArray(body)
|
||||
val stable = mutableListOf<Release>()
|
||||
val prerelease = mutableListOf<Release>()
|
||||
for (i in 0 until array.length()) {
|
||||
val release = array.getJSONObject(i)
|
||||
if (release.optBoolean("draft", false)) continue
|
||||
val isPrerelease = release.optBoolean("prerelease", false)
|
||||
val assets = release.optJSONArray("assets") ?: continue
|
||||
val rows = (0 until assets.length()).map { assets.getJSONObject(it) }
|
||||
val arm = rows.firstOrNull { it.optString("name") == "PluginLoader-arm64" }
|
||||
val guest = LinuxRuntime.rootDir(context)
|
||||
val fexReady = File(guest, "usr/share/guestos/fex-mesa").isDirectory && File(guest, "usr/bin/FEX").canExecute()
|
||||
val binary = arm ?: if (fexReady) rows.firstOrNull { it.optString("name") == "PluginLoader" } else null
|
||||
val name = binary?.optString("name") ?: continue
|
||||
val url = binary.optString("browser_download_url").takeIf { it.startsWith("https://") } ?: continue
|
||||
val checksum = rows.firstOrNull {
|
||||
val n = it.optString("name")
|
||||
(n == "$name.sha256" || n == "$name.sha256sum" || n == "$name.sha256.txt") && it.optString("browser_download_url").startsWith("https://")
|
||||
}?.optString("browser_download_url")?.takeIf { it.startsWith("https://") }
|
||||
val digest = binary.optString("digest").takeIf { it.matches(Regex("(?i)sha256:[0-9a-f]{64}")) }
|
||||
if (digest == null && checksum == null) continue
|
||||
val size = binary.optLong("size", 0)
|
||||
if (size <= 0) continue
|
||||
val row = Release(release.optString("tag_name", "unknown"), isPrerelease, name, url, digest, checksum, size, if (name == "PluginLoader-arm64") 183 else 62)
|
||||
(if (isPrerelease) prerelease else stable).add(row)
|
||||
}
|
||||
ReleaseChannels(stable, prerelease)
|
||||
} catch (e: Exception) { Log.w(TAG, "release metadata", e); ReleaseChannels(emptyList(), emptyList()) }
|
||||
}
|
||||
|
||||
/** Downloads to a sibling temp file and atomically renames only after size, digest and ELF checks. */
|
||||
fun install(context: Context, release: Release, progress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return "Stop the active session before installing Decky Loader"
|
||||
val target = loader(context)
|
||||
target.parentFile?.mkdirs()
|
||||
val temp = File(target.parentFile, "PluginLoader.download")
|
||||
val ok = Downloader.downloadFile(release.url, temp, false) { f -> progress("Downloading ${release.tag}", if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }
|
||||
if (!ok) { temp.delete(); return "Decky Loader download failed" }
|
||||
if (temp.length() != release.size) { temp.delete(); return "Decky Loader size did not match the release metadata" }
|
||||
val expected = release.digest?.substringAfter(':') ?: release.shaUrl?.let { checksumUrl ->
|
||||
val checksumBody = Downloader.downloadString(checksumUrl) ?: run { temp.delete(); return "Could not download the release checksum" }
|
||||
Regex("(?i)\\b[0-9a-f]{64}\\b").find(checksumBody)?.value
|
||||
} ?: run { temp.delete(); return "Release checksum is missing" }
|
||||
if (!expected.matches(Regex("(?i)[0-9a-f]{64}"))) { temp.delete(); return "Release checksum is invalid" }
|
||||
if (!expected.equals(sha256(temp), true)) { temp.delete(); return "Decky Loader checksum mismatch" }
|
||||
if (!validElf(temp, release.machine)) { temp.delete(); return "Release asset is not a compatible 64-bit Linux executable" }
|
||||
if (SessionState.running) { temp.delete(); return "A session started during the download; stop it before installing Decky Loader" }
|
||||
if (!temp.setExecutable(true, false)) { temp.delete(); return "Could not mark PluginLoader executable" }
|
||||
// Decky needs Steam's local CEF debugger only when its session supervisor is enabled.
|
||||
val cefMarker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER)
|
||||
val cefReady = !supervisorEnabled(context) || cefMarker.isFile || runCatching {
|
||||
cefMarker.parentFile?.mkdirs()
|
||||
cefMarker.createNewFile() || cefMarker.isFile
|
||||
}.getOrDefault(false)
|
||||
if (!cefReady) { temp.delete(); return "Could not enable Steam CEF remote debugging" }
|
||||
val staged = File(target.parentFile, "PluginLoader.new")
|
||||
staged.delete()
|
||||
if (!temp.renameTo(staged)) { temp.delete(); return "Could not stage PluginLoader" }
|
||||
val old = File(target.parentFile, "PluginLoader.old")
|
||||
old.delete()
|
||||
if (target.exists() && !target.renameTo(old)) { staged.delete(); return "Could not preserve the existing PluginLoader" }
|
||||
if (!staged.renameTo(target)) {
|
||||
if (old.exists()) old.renameTo(target)
|
||||
staged.delete()
|
||||
return "Could not activate the new PluginLoader"
|
||||
}
|
||||
old.delete()
|
||||
File(target.parentFile, ".droiddeck-decky-version").writeText(release.tag + "\n")
|
||||
File(target.parentFile, ".droiddeck-decky-arch").writeText(if (release.machine == 183) "arm64\n" else "x86_64\n")
|
||||
if (!supervisorEnabled(context)) cefMarker.delete()
|
||||
return null
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, wipeData: Boolean) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
setSupervisorEnabled(context, false)
|
||||
File(root, PATH).delete()
|
||||
File(root, VERSION).delete()
|
||||
File(root, "root/homebrew/services/.droiddeck-decky-arch").delete()
|
||||
File(root, CEF_REMOTE_DEBUG_MARKER).delete()
|
||||
if (wipeData) File(root, "root/homebrew").deleteRecursively()
|
||||
}
|
||||
|
||||
private fun sha256(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
FileInputStream(file).buffered().use { input ->
|
||||
val buffer = ByteArray(1024 * 1024)
|
||||
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 255) }
|
||||
}
|
||||
|
||||
private fun validElf(file: File, machine: Int): Boolean = runCatching {
|
||||
file.inputStream().use { input ->
|
||||
val h = ByteArray(20)
|
||||
if (input.read(h) != h.size) return false
|
||||
h[0] == 0x7f.toByte() && h[1] == 'E'.code.toByte() && h[2] == 'L'.code.toByte() && h[3] == 'F'.code.toByte() &&
|
||||
h[4] == 2.toByte() && h[5] == 1.toByte() && (h[18].toInt() and 255) + ((h[19].toInt() and 255) shl 8) == machine
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
@@ -31,12 +31,18 @@ object DesktopCatalog {
|
||||
return try {
|
||||
val json = JSONObject(body)
|
||||
val arr = json.getJSONArray("packages")
|
||||
// A package built per memory page size (ARMSX2: 4K and 16K kernels) names the others
|
||||
// under "pages"; the device's own size picks one, and the top-level file is the 4K one.
|
||||
val pageSize = try {
|
||||
android.system.Os.sysconf(android.system.OsConstants._SC_PAGESIZE).toString()
|
||||
} catch (e: Exception) { "4096" }
|
||||
(0 until arr.length()).map { i ->
|
||||
val o = arr.getJSONObject(i)
|
||||
val file = o.optJSONObject("pages")?.optJSONObject(pageSize) ?: o
|
||||
Entry(
|
||||
o.getString("id"), o.getString("name"), o.optInt("tier", 1), o.optString("version", ""),
|
||||
o.optString("kind", "tar"), o.getString("url"), o.optString("sha256", ""),
|
||||
o.optLong("size", 0L), o.optString("notes", ""),
|
||||
o.optString("kind", "tar"), file.getString("url"), file.optString("sha256", ""),
|
||||
file.optLong("size", 0L), o.optString("notes", ""),
|
||||
o.optString("icon", "applications-games"), o.optString("category", "Game"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.os.Process;
|
||||
import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.system.StructStat;
|
||||
import android.system.StructUtsname;
|
||||
|
||||
|
||||
import java.io.File;
|
||||
@@ -32,6 +33,7 @@ public final class LinuxRuntime {
|
||||
/** Shortcut extra naming which of the modes above a Linux entry launches. */
|
||||
public static final String EXTRA_LINUX_MODE = "linux_mode";
|
||||
private static final String KGSL_DEVICE = "/dev/kgsl-3d0";
|
||||
private static final String GUEST_HOSTNAME = "DroidDeck";
|
||||
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
|
||||
public static final String DEBUG_LOG_DIR = "DroidDeck";
|
||||
|
||||
@@ -58,30 +60,22 @@ public final class LinuxRuntime {
|
||||
/** Where the runtime carries the host-side proot; see tools/linuxfs/prebuilt/proot/README.md. */
|
||||
private static final String HOST_DIR = "opt/android-host";
|
||||
|
||||
/**
|
||||
* proot, preferred from the installed runtime and falling back to the copy in the apk.
|
||||
*
|
||||
* <p>It is an Android binary rather than part of the rootfs - it is what creates the rootfs -
|
||||
* but it travels in the runtime tarball so that reinstalling the app cannot replace the one
|
||||
* binary everything else depends on, and so a device with no working packaged proot can still
|
||||
* run the runtime.
|
||||
*/
|
||||
public static File prootBinary(Context context) {
|
||||
File shipped = new File(rootDir(context), HOST_DIR + "/proot");
|
||||
if (shipped.isFile()) return shipped;
|
||||
return new File(context.getApplicationInfo().nativeLibraryDir, "libproot.so");
|
||||
File packaged = new File(context.getApplicationInfo().nativeLibraryDir, "libproot.so");
|
||||
if (packaged.isFile()) return packaged;
|
||||
return new File(rootDir(context), HOST_DIR + "/proot");
|
||||
}
|
||||
|
||||
public static File prootLoader(Context context) {
|
||||
File shipped = new File(rootDir(context), HOST_DIR + "/loader");
|
||||
if (shipped.isFile()) return shipped;
|
||||
return new File(context.getApplicationInfo().nativeLibraryDir, "libproot-loader.so");
|
||||
File packaged = new File(context.getApplicationInfo().nativeLibraryDir, "libproot-loader.so");
|
||||
if (packaged.isFile()) return packaged;
|
||||
return new File(rootDir(context), HOST_DIR + "/loader");
|
||||
}
|
||||
|
||||
/** proot links against libtalloc, which sits beside it; empty when the apk copy is in use. */
|
||||
public static String prootLibraryPath(Context context) {
|
||||
File dir = new File(rootDir(context), HOST_DIR);
|
||||
return new File(dir, "proot").isFile() ? dir.getPath() : "";
|
||||
return dir.equals(prootBinary(context).getParentFile()) ? dir.getPath() : "";
|
||||
}
|
||||
|
||||
/** The rootfs is present with gamescope and the session script the launcher hands control to. */
|
||||
@@ -124,6 +118,8 @@ public final class LinuxRuntime {
|
||||
List<String> cmd = new ArrayList<>();
|
||||
cmd.add(prootBinary(context).getPath());
|
||||
cmd.add("--kill-on-exit");
|
||||
// Preserve the host kernel identity while giving the guest the app's branded host name.
|
||||
cmd.add("--kernel-release=" + guestUtsname());
|
||||
// Android's app seccomp policy traps the whole set*id family. Xwayland's Popen() calls
|
||||
// setgid()/setuid() before it execs xkbcomp and _exit(127)s when they fail, so without
|
||||
// this the keymap never compiles and Xwayland dies. -i makes proot answer those calls
|
||||
@@ -253,6 +249,13 @@ public final class LinuxRuntime {
|
||||
cmd.add(spec);
|
||||
}
|
||||
|
||||
/** PRoot's complex -k format: sysname, nodename, release, version, machine, domain, HWCAP. */
|
||||
private static String guestUtsname() {
|
||||
StructUtsname host = Os.uname();
|
||||
return "\\" + host.sysname + "\\" + GUEST_HOSTNAME + "\\" + host.release
|
||||
+ "\\" + host.version + "\\" + host.machine + "\\localdomain\\-1\\";
|
||||
}
|
||||
|
||||
/** X access control and Steam look the session user up by uid: the app uid is root inside. */
|
||||
public static void writeAccounts(Context context) throws IOException {
|
||||
File root = rootDir(context);
|
||||
|
||||
@@ -0,0 +1,664 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.github.luben.zstd.ZstdInputStream
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.BufferedOutputStream
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* FEX, DXVK and VKD3D-Proton per Proton, for the Linux Steam client.
|
||||
*
|
||||
* Every Proton the client runs games with keeps its own copy of these three inside its tree. This
|
||||
* lists them, stores packages (.wcp: tar + zstd with a profile.json) downloaded from the Nightlies
|
||||
* "-Linux" releases or imported, swaps one into a Proton, keeps the Proton's shipped files as
|
||||
* "original bundles" - one per Proton build, so a Steam update adds a new one instead of replacing
|
||||
* the last - restores those, and deletes stored packages.
|
||||
*
|
||||
* Where a Proton reads each component (its own `proton` script, ARM64 host):
|
||||
* DXVK files/lib/wine/dxvk/{aarch64,i386}-windows -> the prefix's system32 / syswow64
|
||||
* VKD3D files/lib/wine/vkd3d-proton/{aarch64,i386}-windows -> the same, on every launch
|
||||
* FEX files/lib/wine/aarch64-windows/lib{arm64ec,wow64}fex.dll
|
||||
* files/lib/wine/aarch64-unix/lib{arm64ec,wow64}fex.so (FEX 2607 and newer)
|
||||
* Proton copies DXVK and VKD3D into the prefix on every normal launch, so a swap applies the next
|
||||
* time a game starts. A swap into a Proton a running game is using waits until that game exits.
|
||||
*
|
||||
* Same formats and data layout as the Decky "Components Manager" plugin, whose data is taken over
|
||||
* once on first use.
|
||||
*/
|
||||
object ComponentsManager {
|
||||
private const val TAG = "Components"
|
||||
private const val NIGHTLIES = "The412Banner/Nightlies"
|
||||
/** Release tag -> component. Only the Linux repacks: the Android releases carry bionic unixlibs. */
|
||||
private val RELEASES = linkedMapOf(
|
||||
"FexCore-Linux" to "fex",
|
||||
"Dxvk-Linux" to "dxvk",
|
||||
"Dxvk-arm64ec-Linux" to "dxvk",
|
||||
"Dxvk-gplasync-Linux" to "dxvk",
|
||||
"Vkd3d-proton-Linux" to "vkd3d",
|
||||
)
|
||||
private val TYPES = mapOf("FEXCore-Linux" 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")
|
||||
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
||||
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
|
||||
|
||||
private const val WINE = "files/lib/wine"
|
||||
private val FEX_FILES = listOf(
|
||||
"$WINE/aarch64-windows/libarm64ecfex.dll",
|
||||
"$WINE/aarch64-windows/libwow64fex.dll",
|
||||
"$WINE/aarch64-unix/libarm64ecfex.so",
|
||||
"$WINE/aarch64-unix/libwow64fex.so",
|
||||
)
|
||||
private val COMP_DIR = mapOf("dxvk" to "$WINE/dxvk", "vkd3d" to "$WINE/vkd3d-proton")
|
||||
/** The folders a Proton reads on ARM64. */
|
||||
private val PE_ARCHES = listOf("aarch64-windows", "i386-windows")
|
||||
/**
|
||||
* The DLLs that ARE the component. A swap clears exactly these before unpacking, so no file of
|
||||
* the previous version is left mixed in; anything else a Proton keeps beside them - GE's
|
||||
* openvr_api_dxvk.dll, which its launcher copies into every prefix and aborts without - stays.
|
||||
*/
|
||||
private val COMP_DLLS = mapOf(
|
||||
"dxvk" to setOf("d3d8.dll", "d3d9.dll", "d3d10.dll", "d3d10_1.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll"),
|
||||
"vkd3d" to setOf("d3d12.dll", "d3d12core.dll"),
|
||||
)
|
||||
private const val PLUGIN_DATA = "root/homebrew/data/decky-components-manager"
|
||||
|
||||
data class Proton(val id: String, val name: String, val dir: File, val guestPath: String, val version: String, val valve: Boolean)
|
||||
data class Component(val detected: String, val detail: String, val inUse: String, val activeFile: String?, val queued: String?)
|
||||
data class Original(val comp: String, val protonVersion: String, val label: String, val size: Long)
|
||||
data class Package(val file: String, val comp: String, val version: String, val description: String, val size: Long)
|
||||
data class CatalogItem(val file: String, val comp: String, val release: String, val url: String, val size: Long, val digest: String)
|
||||
data class ProtonView(
|
||||
val proton: Proton, val components: Map<String, Component>, val originals: List<Original>, val inUseByGame: Boolean,
|
||||
/** When a launch last had to put this Proton's chosen files back (epoch seconds), or 0. */
|
||||
val reappliedAt: Long = 0,
|
||||
)
|
||||
data class Snapshot(val protons: List<ProtonView>, val packages: List<Package>)
|
||||
data class Catalog(val items: List<CatalogItem>, val fetchedAt: Long)
|
||||
|
||||
private val lock = Any()
|
||||
|
||||
// ------------------------------------------------------------------ paths
|
||||
|
||||
private fun root(context: Context) = LinuxRuntime.rootDir(context)
|
||||
private fun steam(context: Context) = File(root(context), "root/.local/share/Steam")
|
||||
private fun host(context: Context, guest: String) = File(root(context), guest.removePrefix("/"))
|
||||
private fun dataDir(context: Context) = File(context.filesDir, "components").apply { mkdirs() }
|
||||
private fun packagesDir(context: Context) = File(dataDir(context), "packages").apply { mkdirs() }
|
||||
private fun originalsDir(context: Context) = File(dataDir(context), "originals").apply { mkdirs() }
|
||||
private fun stateFile(context: Context) = File(dataDir(context), "state.json")
|
||||
private fun catalogFile(context: Context) = File(dataDir(context), "catalog.json")
|
||||
/**
|
||||
* Inside the Linux runtime, read by the Proton launch wrappers (bannerlator-steam-compat's
|
||||
* bl_components) before every game launch: desired.tsv + an unpacked copy of each package in use.
|
||||
*/
|
||||
private const val LAUNCH_DIR = "root/.local/share/bannerlator-components"
|
||||
private fun launchDir(context: Context) = File(root(context), LAUNCH_DIR)
|
||||
|
||||
fun safeName(s: String): String = s.replace(Regex("[^A-Za-z0-9._+-]+"), "_").trim('_').ifEmpty { "unnamed" }
|
||||
|
||||
// ------------------------------------------------------------------ state
|
||||
|
||||
private fun loadState(context: Context): JSONObject =
|
||||
runCatching { JSONObject(stateFile(context).readText()) }.getOrElse { JSONObject() }.apply {
|
||||
if (!has("active")) put("active", JSONObject())
|
||||
if (!has("queued")) put("queued", JSONObject())
|
||||
}
|
||||
|
||||
private fun saveState(context: Context, state: JSONObject) {
|
||||
val f = stateFile(context)
|
||||
val tmp = File(f.parentFile, f.name + ".tmp")
|
||||
tmp.writeText(state.toString(2))
|
||||
tmp.renameTo(f)
|
||||
// Every change of choice reaches the launch wrappers at once.
|
||||
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
|
||||
}
|
||||
|
||||
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
|
||||
|
||||
/** Takes over the Decky plugin's packages, originals and swap records, once. */
|
||||
private fun migratePlugin(context: Context) {
|
||||
val marker = File(dataDir(context), ".plugin-imported")
|
||||
if (marker.isFile) return
|
||||
val plugin = File(root(context), PLUGIN_DATA)
|
||||
if (plugin.isDirectory) {
|
||||
runCatching {
|
||||
File(plugin, "packages").listFiles()?.forEach { f ->
|
||||
if (f.isFile && f.name.endsWith(".wcp")) {
|
||||
val dst = File(packagesDir(context), f.name)
|
||||
if (!dst.exists()) f.copyTo(dst)
|
||||
}
|
||||
}
|
||||
val originals = File(plugin, "originals")
|
||||
if (originals.isDirectory) originals.copyRecursively(originalsDir(context), overwrite = false)
|
||||
val ps = File(plugin, "state.json")
|
||||
if (ps.isFile && !stateFile(context).isFile) ps.copyTo(stateFile(context))
|
||||
Log.i(TAG, "took over the Decky plugin's data from $plugin")
|
||||
}.onFailure { Log.w(TAG, "plugin data import", it) }
|
||||
}
|
||||
marker.writeText("1\n")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Protons
|
||||
|
||||
private fun libraryRoots(context: Context): List<File> {
|
||||
val roots = mutableListOf(steam(context))
|
||||
val vdf = File(steam(context), "steamapps/libraryfolders.vdf")
|
||||
runCatching {
|
||||
Regex("\"path\"\\s+\"([^\"]+)\"").findAll(vdf.readText()).forEach {
|
||||
val h = host(context, it.groupValues[1])
|
||||
if (roots.none { r -> r.canonicalPath == h.canonicalPath }) roots.add(h)
|
||||
}
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
private fun displayName(dir: File): String = runCatching {
|
||||
Regex("\"display_name\"\\s+\"([^\"]+)\"").find(File(dir, "compatibilitytool.vdf").readText())?.groupValues?.get(1)
|
||||
}.getOrNull() ?: dir.name
|
||||
|
||||
private fun protonVersion(dir: File): String = runCatching {
|
||||
val parts = File(dir, "version").useLines { it.firstOrNull() ?: "" }.trim().split(Regex("\\s+"))
|
||||
if (parts.size > 1) parts[1] else parts.firstOrNull()?.ifEmpty { null } ?: "unknown"
|
||||
}.getOrDefault("unknown")
|
||||
|
||||
/** Every Proton tree with a Wine inside. Launch wrappers pointing at another Proton are left out. */
|
||||
fun protons(context: Context): List<Proton> {
|
||||
val found = LinkedHashMap<String, Proton>()
|
||||
val bases = listOf(File(steam(context), "compatibilitytools.d") to false) +
|
||||
libraryRoots(context).map { File(it, "steamapps/common") to true }
|
||||
// Not canonical: /data/user/0 is a link to /data/data on many devices, and the guest path is
|
||||
// what is left after removing the rootfs prefix exactly as the paths were built.
|
||||
val rootPath = root(context).absolutePath.trimEnd('/')
|
||||
for ((base, valve) in bases) {
|
||||
val entries = base.listFiles()?.sortedBy { it.name } ?: continue
|
||||
for (dir in entries) {
|
||||
if (!File(dir, WINE).isDirectory || !File(dir, "proton").isFile) continue
|
||||
val real = runCatching { dir.canonicalPath }.getOrDefault(dir.path)
|
||||
if (found.containsKey(real)) continue
|
||||
val guest = if (dir.absolutePath.startsWith(rootPath)) dir.absolutePath.removePrefix(rootPath) else dir.absolutePath
|
||||
found[real] = Proton(safeName(dir.name), displayName(dir), dir, guest, protonVersion(dir), valve)
|
||||
}
|
||||
}
|
||||
return found.values.toList()
|
||||
}
|
||||
|
||||
private fun proton(context: Context, id: String) = protons(context).firstOrNull { it.id == id }
|
||||
?: throw IllegalStateException("No Proton with id $id")
|
||||
|
||||
/**
|
||||
* Is anything running on this Proton right now - a game, or the client's own start-up runs,
|
||||
* whose Wine processes can outlive them? Swaps wait while it is. Read from the command lines.
|
||||
*/
|
||||
fun inUse(proton: Proton): Boolean = anyProcess(proton) { needle, text -> text.contains(needle + "proton ") || text.contains(needle + "files/bin") }
|
||||
|
||||
/**
|
||||
* Is a game running on this Proton? Only a launch runs proton with the verb waitforexitandrun
|
||||
* (Proton's own script stays up until the game exits); the client's start-up runs do not.
|
||||
*/
|
||||
fun gameRunning(proton: Proton): Boolean = anyProcess(proton) { needle, text -> text.contains(needle + "proton waitforexitandrun") }
|
||||
|
||||
private fun anyProcess(proton: Proton, match: (String, String) -> Boolean): Boolean {
|
||||
val needle = proton.guestPath.trimEnd('/') + "/"
|
||||
val procs = File("/proc").listFiles() ?: return false
|
||||
for (p in procs) {
|
||||
if (!p.name.all(Char::isDigit)) continue
|
||||
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
|
||||
if (cmd.isEmpty()) continue
|
||||
if (match(needle, String(cmd).replace('\u0000', ' '))) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ component files
|
||||
|
||||
private fun readVersionFile(f: File): String = runCatching {
|
||||
val text = f.readText().trim()
|
||||
Regex("\\(([^)]+)\\)").find(text)?.groupValues?.get(1) ?: text.split(Regex("\\s+")).last()
|
||||
}.getOrDefault("")
|
||||
|
||||
private fun fexVersion(dir: File): String {
|
||||
val dll = File(dir, FEX_FILES[0])
|
||||
if (!dll.isFile) return ""
|
||||
val text = runCatching { String(dll.readBytes(), Charsets.ISO_8859_1) }.getOrDefault("")
|
||||
return Regex("FEX-\\d{4}(?:\\.\\d+)?(?:-\\d+-g[0-9a-f]{6,})?").findAll(text).map { it.value }.maxByOrNull { it.length }
|
||||
?: "FEX (build without a version name)"
|
||||
}
|
||||
|
||||
private fun compFiles(dir: File, comp: String): List<String> {
|
||||
if (comp == "fex") return FEX_FILES.filter { File(dir, it).isFile }
|
||||
val base = File(dir, COMP_DIR.getValue(comp))
|
||||
return base.walkTopDown().filter { it.isFile }.map { it.relativeTo(dir).path }.sorted().toList()
|
||||
}
|
||||
|
||||
private fun owned(comp: String, rel: String) = comp == "fex" || PE_ARCHES.any { "/$it/" in rel }
|
||||
|
||||
private fun sha256(f: File): String {
|
||||
val md = MessageDigest.getInstance("SHA-256")
|
||||
FileInputStream(f).use { input ->
|
||||
val buf = ByteArray(1 shl 16)
|
||||
while (true) { val n = input.read(buf); if (n < 0) break; md.update(buf, 0, n) }
|
||||
}
|
||||
return md.digest().joinToString("") { "%02x".format(it.toInt() and 255) }
|
||||
}
|
||||
|
||||
private fun fingerprint(dir: File, comp: String): Map<String, String> =
|
||||
compFiles(dir, comp).filter { owned(comp, it) }.associateWith { sha256(File(dir, it)) }
|
||||
|
||||
// ------------------------------------------------------------------ packages
|
||||
|
||||
private fun normalize(name: String) = name.removePrefix("./").trimStart('/')
|
||||
|
||||
private inline fun <T> readWcp(f: File, block: (TarArchiveInputStream) -> T): T =
|
||||
TarArchiveInputStream(ZstdInputStream(BufferedInputStream(FileInputStream(f), 1 shl 16))).use(block)
|
||||
|
||||
private fun readProfile(f: File): JSONObject = readWcp(f) { tar ->
|
||||
while (true) {
|
||||
val e = tar.nextTarEntry ?: break
|
||||
if (!e.isDirectory && normalize(e.name) == "profile.json") return@readWcp JSONObject(tar.readBytes().decodeToString())
|
||||
}
|
||||
throw IllegalArgumentException("no profile.json in ${f.name}")
|
||||
}
|
||||
|
||||
private fun packageInfo(f: File): Package {
|
||||
val prof = readProfile(f)
|
||||
val comp = TYPES[prof.optString("type")] ?: throw IllegalArgumentException("${f.name} is not a Linux component package (type ${prof.optString("type")})")
|
||||
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
|
||||
}
|
||||
|
||||
fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
|
||||
?.filter { it.isFile && it.name.endsWith(".wcp") }?.sortedBy { it.name }
|
||||
?.mapNotNull { f -> runCatching { packageInfo(f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
|
||||
?: emptyList()
|
||||
|
||||
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
|
||||
private fun installFiles(context: Context, dir: File, comp: String, wcp: File): Map<String, String> {
|
||||
val staged = File(dataDir(context), "staging-${System.nanoTime()}")
|
||||
try {
|
||||
readWcp(wcp) { tar ->
|
||||
while (true) {
|
||||
val e = tar.nextTarEntry ?: break
|
||||
val rel = normalize(e.name)
|
||||
if (e.isDirectory || !rel.startsWith("files/")) continue
|
||||
require(rel.split('/').none { it == ".." }) { "unsafe path $rel" }
|
||||
val out = File(staged, rel)
|
||||
out.parentFile?.mkdirs()
|
||||
FileOutputStream(out).use { tar.copyTo(it) }
|
||||
}
|
||||
}
|
||||
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
|
||||
COMP_DIR[comp]?.let { compDir ->
|
||||
for (arch in PE_ARCHES) {
|
||||
val target = File(dir, "$compDir/$arch")
|
||||
if (!File(staged, "$compDir/$arch").isDirectory || !target.isDirectory) continue
|
||||
target.listFiles()?.filter { it.name.lowercase() in COMP_DLLS.getValue(comp) }?.forEach { it.delete() }
|
||||
}
|
||||
}
|
||||
val hashes = LinkedHashMap<String, String>()
|
||||
File(staged, "files").walkTopDown().filter { it.isFile }.forEach { src ->
|
||||
val rel = src.relativeTo(staged).path
|
||||
val dst = File(dir, rel)
|
||||
dst.parentFile?.mkdirs()
|
||||
val tmp = File(dst.parentFile, dst.name + ".dcm-new")
|
||||
src.copyTo(tmp, overwrite = true)
|
||||
if (rel.endsWith(".so")) tmp.setExecutable(true, false)
|
||||
tmp.setReadable(true, false)
|
||||
if (!tmp.renameTo(dst)) { dst.delete(); check(tmp.renameTo(dst)) { "could not place $rel" } }
|
||||
hashes[rel] = sha256(dst)
|
||||
}
|
||||
return hashes
|
||||
} finally {
|
||||
staged.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeWcp(dest: File, profile: JSONObject, dir: File, rels: List<String>) {
|
||||
val tmp = File(dest.parentFile, dest.name + ".part")
|
||||
TarArchiveOutputStream(ZstdOutputStream(BufferedOutputStream(FileOutputStream(tmp), 1 shl 16), 9)).use { tar ->
|
||||
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX)
|
||||
val bytes = profile.toString(2).toByteArray()
|
||||
tar.putArchiveEntry(TarArchiveEntry("./profile.json").apply { size = bytes.size.toLong() })
|
||||
tar.write(bytes); tar.closeArchiveEntry()
|
||||
for (rel in rels) {
|
||||
val f = File(dir, rel)
|
||||
tar.putArchiveEntry(TarArchiveEntry(f, "./$rel"))
|
||||
FileInputStream(f).use { it.copyTo(tar) }
|
||||
tar.closeArchiveEntry()
|
||||
}
|
||||
}
|
||||
tmp.renameTo(dest)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ originals
|
||||
|
||||
private fun originalFile(context: Context, p: Proton, comp: String) =
|
||||
File(originalsDir(context), "${p.id}/${safeName(p.version)}/$comp.wcp").apply { parentFile?.mkdirs() }
|
||||
|
||||
fun originals(context: Context, protonId: String): List<Original> {
|
||||
val base = File(originalsDir(context), protonId)
|
||||
val versions = base.listFiles()?.filter { it.isDirectory }?.sortedByDescending { it.lastModified() } ?: return emptyList()
|
||||
return versions.flatMap { v ->
|
||||
COMPONENTS.mapNotNull { comp ->
|
||||
val f = File(v, "$comp.wcp")
|
||||
if (!f.isFile) null else Original(comp, v.name, runCatching { readProfile(f).optString("description") }.getOrDefault(""), f.length())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a Proton's shipped files for this component before they are first replaced in this
|
||||
* Proton build. A build already swapped into is not saved again: its files are ours.
|
||||
*/
|
||||
private fun ensureOriginal(context: Context, p: Proton, comp: String, state: JSONObject) {
|
||||
val dest = originalFile(context, p, comp)
|
||||
if (dest.isFile) return
|
||||
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
|
||||
if (active != null && active.optString("protonVersion") == p.version) return
|
||||
val rels = compFiles(p.dir, comp)
|
||||
if (rels.isEmpty()) return
|
||||
val current = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
|
||||
val profile = JSONObject()
|
||||
.put("type", TYPE_OF.getValue(comp))
|
||||
.put("versionName", "original-${p.version}")
|
||||
.put("versionCode", 0)
|
||||
.put("description", "Original · ${p.name} · ${p.version} · ${LABEL.getValue(comp)} $current".trim())
|
||||
.put("files", JSONArray(rels.map { JSONObject().put("source", it).put("target", "\${proton}/$it") }))
|
||||
writeWcp(dest, profile, p.dir, rels)
|
||||
Log.i(TAG, "saved original $comp of ${p.name} ${p.version}")
|
||||
}
|
||||
|
||||
/** Saves the originals of every Proton build not seen yet (first open, and after a Steam update). */
|
||||
fun snapshotAll(context: Context) = synchronized(lock) {
|
||||
migratePlugin(context)
|
||||
val state = loadState(context)
|
||||
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 { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ view
|
||||
|
||||
fun snapshot(context: Context): Snapshot = synchronized(lock) {
|
||||
migratePlugin(context)
|
||||
val state = loadState(context)
|
||||
val reapplied = HashMap<String, Long>()
|
||||
runCatching {
|
||||
File(launchDir(context), "reapplied.log").forEachLine { line ->
|
||||
val parts = line.split('\t')
|
||||
if (parts.size >= 2) parts[0].toLongOrNull()?.let { reapplied[parts[1]] = maxOf(reapplied[parts[1]] ?: 0, it) }
|
||||
}
|
||||
}
|
||||
val views = protons(context).map { p ->
|
||||
val comps = COMPONENTS.associateWith { comp ->
|
||||
val detected = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
|
||||
val detail = if (comp == "fex") (if (File(p.dir, FEX_FILES[2]).isFile) "with Linux helpers" else "DLLs only") else ""
|
||||
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
|
||||
val inUseLabel = when {
|
||||
active == null -> "Original"
|
||||
active.optString("protonVersion") != p.version -> "Original (Proton updated since the last swap)"
|
||||
else -> {
|
||||
val want = active.optJSONObject("files") ?: JSONObject()
|
||||
val fp = fingerprint(p.dir, comp)
|
||||
if (want.keys().asSequence().all { fp[it] == want.optString(it) }) active.optString("label", active.optString("file"))
|
||||
else "Changed outside Components"
|
||||
}
|
||||
}
|
||||
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
|
||||
Component(
|
||||
detected.ifEmpty { "not present" }, detail, inUseLabel,
|
||||
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
|
||||
q?.optString("label"),
|
||||
)
|
||||
}
|
||||
ProtonView(p, comps, originals(context, p.id), gameRunning(p), reapplied[p.dir.name] ?: 0)
|
||||
}
|
||||
Snapshot(views, packages(context))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ launch-time enforcement
|
||||
|
||||
/**
|
||||
* Writes what each Proton should be using for the launch wrappers: desired.tsv, one line per
|
||||
* file (tool dir, Proton build, component, file, sha256, source copy), and an unpacked copy of
|
||||
* every package or older-build original in use to copy from. Rebuilt whole after every change, so
|
||||
* a restored or deleted choice simply stops being enforced. The Proton's own current-build
|
||||
* originals are not listed: the wrappers also give Steam's probe runs their own prefix, which is
|
||||
* what overwrote files in the first place.
|
||||
*/
|
||||
private fun syncLaunchState(context: Context, state: JSONObject) {
|
||||
val dir = launchDir(context)
|
||||
val store = File(dir, "store").apply { mkdirs() }
|
||||
val all = protons(context)
|
||||
val lines = StringBuilder()
|
||||
val keep = HashSet<String>()
|
||||
val active = state.sub("active")
|
||||
for (pid in active.keys()) {
|
||||
val p = all.firstOrNull { it.id == pid } ?: continue
|
||||
val comps = active.optJSONObject(pid) ?: continue
|
||||
for (comp in comps.keys()) {
|
||||
val a = comps.optJSONObject(comp) ?: continue
|
||||
if (a.optString("protonVersion") != p.version) continue
|
||||
val file = a.optString("file")
|
||||
val (key, wcp) = if (file.startsWith("original ")) {
|
||||
val v = file.removePrefix("original ")
|
||||
"original-$pid-${safeName(v)}-$comp" to File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp")
|
||||
} else safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
|
||||
if (!wcp.isFile) continue
|
||||
val unpacked = File(store, key)
|
||||
if (!File(unpacked, ".complete").isFile) {
|
||||
unpacked.deleteRecursively()
|
||||
readWcp(wcp) { tar ->
|
||||
while (true) {
|
||||
val e = tar.nextTarEntry ?: break
|
||||
val rel = normalize(e.name)
|
||||
if (e.isDirectory || !rel.startsWith("files/") || rel.split('/').any { it == ".." }) continue
|
||||
val out = File(unpacked, rel)
|
||||
out.parentFile?.mkdirs()
|
||||
FileOutputStream(out).use { tar.copyTo(it) }
|
||||
}
|
||||
}
|
||||
File(unpacked, ".complete").writeText("1\n")
|
||||
}
|
||||
keep += key
|
||||
val files = a.optJSONObject("files") ?: continue
|
||||
for (rel in files.keys()) {
|
||||
val src = File(unpacked, rel)
|
||||
if (!src.isFile) continue
|
||||
val guestSrc = "/" + src.absolutePath.removePrefix(root(context).absolutePath.trimEnd('/')).trimStart('/')
|
||||
lines.append(p.dir.name).append('\t').append(p.version).append('\t').append(comp).append('\t')
|
||||
.append(rel).append('\t').append(files.optString(rel)).append('\t').append(guestSrc).append('\n')
|
||||
}
|
||||
}
|
||||
}
|
||||
store.listFiles()?.filter { it.isDirectory && it.name !in keep }?.forEach { it.deleteRecursively() }
|
||||
val list = File(dir, "desired.tsv")
|
||||
val tmp = File(dir, "desired.tsv.tmp")
|
||||
tmp.writeText(lines.toString())
|
||||
tmp.renameTo(list)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ actions
|
||||
|
||||
/** Applies a package now, or queues it when a game is running on that Proton. Returns what happened. */
|
||||
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
|
||||
val p = proton(context, protonId)
|
||||
val wcp = File(packagesDir(context), safeName(file))
|
||||
val info = packageInfo(wcp)
|
||||
val state = loadState(context)
|
||||
if (inUse(p)) {
|
||||
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
|
||||
saveState(context, state)
|
||||
return "${LABEL[info.comp]} ${info.version} goes into ${p.name} when the game running on it closes."
|
||||
}
|
||||
applyPackage(context, p, info, wcp, state)
|
||||
state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
|
||||
saveState(context, state)
|
||||
"${LABEL[info.comp]} ${info.version} is now in ${p.name}. It applies the next time a game starts."
|
||||
}
|
||||
|
||||
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
|
||||
ensureOriginal(context, p, info.comp, state)
|
||||
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
||||
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
||||
.put("file", wcp.name).put("label", info.version).put("protonVersion", p.version)
|
||||
.put("files", JSONObject(hashes.filterKeys { owned(info.comp, it) } as Map<*, *>))
|
||||
.put("at", System.currentTimeMillis() / 1000))
|
||||
Log.i(TAG, "swapped ${info.comp} ${info.version} into ${p.name} ${p.version}")
|
||||
}
|
||||
|
||||
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
|
||||
val p = proton(context, protonId)
|
||||
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
|
||||
check(wcp.isFile) { "That original bundle is not stored" }
|
||||
val state = loadState(context)
|
||||
if (inUse(p)) {
|
||||
state.sub("queued").sub(p.id).put(comp, JSONObject().put("kind", "original").put("protonVersion", protonVersion).put("label", "Original $protonVersion"))
|
||||
saveState(context, state)
|
||||
return "${LABEL[comp]} of ${p.name} goes back to its original when the game running on it closes."
|
||||
}
|
||||
applyOriginal(context, p, comp, protonVersion, wcp, state)
|
||||
state.sub("queued").optJSONObject(p.id)?.remove(comp)
|
||||
saveState(context, state)
|
||||
"${LABEL[comp]} of ${p.name} restored from its $protonVersion original."
|
||||
}
|
||||
|
||||
private fun applyOriginal(context: Context, p: Proton, comp: String, protonVersion: String, wcp: File, state: JSONObject) {
|
||||
val current = protonVersion == safeName(p.version)
|
||||
if (!current) ensureOriginal(context, p, comp, state)
|
||||
installFiles(context, p.dir, comp, wcp)
|
||||
val active = state.sub("active").sub(p.id)
|
||||
if (current) active.remove(comp)
|
||||
else active.put(comp, JSONObject().put("file", "original $protonVersion").put("label", "Original from $protonVersion")
|
||||
.put("protonVersion", p.version).put("files", JSONObject(fingerprint(p.dir, comp) as Map<*, *>)).put("at", System.currentTimeMillis() / 1000))
|
||||
}
|
||||
|
||||
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
|
||||
fun applyQueued(context: Context): List<String> = synchronized(lock) {
|
||||
val state = loadState(context)
|
||||
val queued = state.sub("queued")
|
||||
if (queued.length() == 0) return emptyList()
|
||||
val done = mutableListOf<String>()
|
||||
val all = protons(context)
|
||||
for (pid in queued.keys().asSequence().toList()) {
|
||||
val p = all.firstOrNull { it.id == pid } ?: run { queued.remove(pid); null } ?: continue
|
||||
if (inUse(p)) continue
|
||||
val comps = queued.optJSONObject(pid) ?: continue
|
||||
for (comp in comps.keys().asSequence().toList()) {
|
||||
val q = comps.optJSONObject(comp) ?: continue
|
||||
runCatching {
|
||||
if (q.optString("kind") == "original") {
|
||||
val v = q.optString("protonVersion")
|
||||
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
|
||||
} else {
|
||||
val wcp = File(packagesDir(context), q.optString("file"))
|
||||
applyPackage(context, p, packageInfo(wcp), wcp, state)
|
||||
}
|
||||
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
|
||||
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
|
||||
comps.remove(comp)
|
||||
}
|
||||
if (comps.length() == 0) queued.remove(pid)
|
||||
}
|
||||
saveState(context, state)
|
||||
done
|
||||
}
|
||||
|
||||
fun cancelQueued(context: Context, protonId: String, comp: String) = synchronized(lock) {
|
||||
val state = loadState(context)
|
||||
state.sub("queued").optJSONObject(protonId)?.remove(comp)
|
||||
saveState(context, state)
|
||||
}
|
||||
|
||||
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
|
||||
val name = safeName(file)
|
||||
val state = loadState(context)
|
||||
val active = state.sub("active")
|
||||
for (pid in active.keys()) {
|
||||
val comps = active.optJSONObject(pid) ?: continue
|
||||
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { "$name is in use in $pid. Swap that Proton to something else first." }
|
||||
}
|
||||
val f = File(packagesDir(context), name)
|
||||
check(f.isFile) { "$name is not stored" }
|
||||
f.delete()
|
||||
"Deleted $name."
|
||||
}
|
||||
|
||||
fun deleteOriginal(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
|
||||
val p = proton(context, protonId)
|
||||
check(safeName(p.version) != protonVersion) { "The installed build's original is kept: it is the way back." }
|
||||
val f = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
|
||||
check(f.isFile) { "Not stored" }
|
||||
f.delete()
|
||||
f.parentFile?.takeIf { it.listFiles().isNullOrEmpty() }?.delete()
|
||||
"Deleted the $protonVersion original of ${LABEL[comp]}."
|
||||
}
|
||||
|
||||
/** Imports a -linux .wcp from anywhere the app can read (the file picker hands over a copy). */
|
||||
fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) {
|
||||
val info = packageInfo(source)
|
||||
val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" })
|
||||
source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest)
|
||||
info.copy(file = dest.name)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ catalog
|
||||
|
||||
/** The Nightlies listing: cached on disk, fetched again only when [force] (the refresh button). */
|
||||
fun catalog(context: Context, force: Boolean): Catalog {
|
||||
val cache = catalogFile(context)
|
||||
if (!force && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) }
|
||||
if (!force) return Catalog(emptyList(), 0)
|
||||
val items = JSONArray()
|
||||
for ((tag, comp) in RELEASES) {
|
||||
val body = Downloader.downloadString("https://api.github.com/repos/$NIGHTLIES/releases/tags/$tag") ?: continue
|
||||
val assets = runCatching { JSONObject(body).optJSONArray("assets") }.getOrNull() ?: continue
|
||||
for (i in 0 until assets.length()) {
|
||||
val a = assets.getJSONObject(i)
|
||||
val name = a.optString("name")
|
||||
if (!name.endsWith(".wcp")) continue
|
||||
items.put(JSONObject().put("file", name).put("comp", comp).put("release", tag)
|
||||
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
|
||||
}
|
||||
}
|
||||
val out = JSONObject().put("items", items).put("fetchedAt", System.currentTimeMillis() / 1000)
|
||||
val tmp = File(cache.parentFile, cache.name + ".tmp")
|
||||
tmp.writeText(out.toString()); tmp.renameTo(cache)
|
||||
return parseCatalog(out)
|
||||
}
|
||||
|
||||
private fun parseCatalog(o: JSONObject): Catalog {
|
||||
val arr = o.optJSONArray("items") ?: JSONArray()
|
||||
val items = (0 until arr.length()).map { arr.getJSONObject(it) }.map {
|
||||
CatalogItem(it.optString("file"), it.optString("comp"), it.optString("release"), it.optString("url"), it.optLong("size"), it.optString("digest"))
|
||||
}.sortedWith(compareBy({ it.comp }, { it.release }, { it.file }))
|
||||
return Catalog(items, o.optLong("fetchedAt"))
|
||||
}
|
||||
|
||||
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
|
||||
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
|
||||
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { "Downloads come only from the Nightlies releases" }
|
||||
val dest = File(packagesDir(context), safeName(item.file))
|
||||
val part = File(dest.parentFile, dest.name + ".part")
|
||||
part.delete()
|
||||
check(Downloader.downloadFile(item.url, part, false) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { "Download failed" }
|
||||
if (item.digest.startsWith("sha256:")) {
|
||||
if (!sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error("Checksum mismatch") }
|
||||
}
|
||||
val info = runCatching { packageInfo(part) }.getOrElse { part.delete(); throw it }
|
||||
synchronized(lock) { part.renameTo(dest) }
|
||||
return info.copy(file = dest.name)
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,9 @@ object SessionArtifacts {
|
||||
/** Written last; a folder without it did not get its ending. */
|
||||
const val COMPLETE_MARKER = ".complete"
|
||||
|
||||
/** Every file in the folder has been through the redactor, own addresses and accounts included (-2: accounts added). */
|
||||
private const val SCRUBBED_MARKER = ".scrubbed-2"
|
||||
|
||||
/** Everything the end of a session gathers, into [dir]. Safe to call for a dead session. */
|
||||
fun collect(context: Context, dir: File, reason: String) {
|
||||
try {
|
||||
@@ -40,15 +43,60 @@ object SessionArtifacts {
|
||||
src.copyTo(wayland, overwrite = true)
|
||||
}
|
||||
}
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
copySteamLogs(context, dir)
|
||||
// A session the system killed leaves its trace here and nowhere else.
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
scrubFolder(dir)
|
||||
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
|
||||
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "collecting session artifacts", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Once, for session folders written before every file was scrubbed and before the device's own
|
||||
* addresses were (network.txt listed them; the client's IPv6 check logs "external address"
|
||||
* into steam/connection_log.txt): the whole folder, steam/ included, through the redactor.
|
||||
* A marker records it. Runs at app start with [finishAbandoned].
|
||||
*/
|
||||
@Synchronized
|
||||
fun scrubOlder(context: Context) {
|
||||
val current = SessionPaths.current()
|
||||
val dirs = LinuxRuntime.debugLogDir().listFiles { f ->
|
||||
f.isDirectory && f.name.startsWith("session-") && f != current && !File(f, SCRUBBED_MARKER).exists()
|
||||
} ?: return
|
||||
if (dirs.isEmpty()) return
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
dirs.forEach { dir ->
|
||||
scrubFolder(dir)
|
||||
File(dir, "steam").takeIf { it.isDirectory }?.let { scrubFolder(it) }
|
||||
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
|
||||
}
|
||||
Log.i(TAG, "scrubbed ${dirs.size} older session folder(s)")
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's own files (session.log, app.log, desktop.log, the Steam desktop client's
|
||||
* steam-desktop.log, ...) were written as they happened, unscrubbed; this pass puts every one
|
||||
* through the redactor before the folder can be shared. A file is rewritten only if a line
|
||||
* changed. steam/ was scrubbed on the way in.
|
||||
*/
|
||||
private fun scrubFolder(dir: File) {
|
||||
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") }?.forEach { f ->
|
||||
if (!LogRedactor.isText(f)) return@forEach
|
||||
try {
|
||||
val tmp = File(dir, ".${f.name}.scrub")
|
||||
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
|
||||
if (tmp.length() != f.length() || tmp.readBytes().contentEquals(f.readBytes()).not()) tmp.renameTo(f) else tmp.delete()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not scrub ${f.name}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Steam's logs: redacted into steam/, never copied verbatim. */
|
||||
private fun copySteamLogs(context: Context, dir: File) {
|
||||
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
|
||||
@@ -72,6 +120,7 @@ object SessionArtifacts {
|
||||
* older folder would be handed logs that are not its own. Runs on a worker thread at app
|
||||
* start; nothing here touches the session that is about to begin.
|
||||
*/
|
||||
@Synchronized
|
||||
fun finishAbandoned(context: Context) {
|
||||
val parent = LinuxRuntime.debugLogDir()
|
||||
val abandoned = parent.listFiles { f ->
|
||||
@@ -79,6 +128,7 @@ object SessionArtifacts {
|
||||
}?.sortedBy { it.name } ?: return
|
||||
if (abandoned.isEmpty()) return
|
||||
val current = SessionPaths.current()
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
abandoned.forEachIndexed { i, dir ->
|
||||
if (dir == current) return@forEachIndexed
|
||||
val newest = i == abandoned.lastIndex
|
||||
@@ -97,6 +147,8 @@ object SessionArtifacts {
|
||||
copySteamLogs(context, dir)
|
||||
}
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
|
||||
scrubFolder(dir)
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
|
||||
Log.i(TAG, "finished the abandoned session folder $dir")
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
|
||||
/** Writes the machine-readable lifecycle stream beside the existing session artifacts. */
|
||||
object SessionEvents {
|
||||
private const val TAG = "SessionEvents"
|
||||
private val lock = Any()
|
||||
|
||||
fun begin(context: Context, mode: String) {
|
||||
// A runtime-install failure can leave the folder claimed before the service ever starts.
|
||||
// Keep that folder, but give the next attempt its own session directory.
|
||||
SessionPaths.take()
|
||||
val dir = SessionPaths.beginOrCurrent(context)
|
||||
synchronized(SessionState) {
|
||||
SessionState.phase = SessionPhase.PREPARING
|
||||
SessionState.mode = mode
|
||||
SessionState.sessionId = dir.name
|
||||
SessionState.lastTransitionAt = System.currentTimeMillis()
|
||||
SessionState.failureCode = null
|
||||
SessionState.failureMessage = null
|
||||
SessionState.failureStatus = null
|
||||
SessionState.logDirectory = dir
|
||||
SessionState.logFile = File(dir, "session.log")
|
||||
SessionState.eventsFile = File(dir, "events.jsonl")
|
||||
SessionState.guestPid = -1
|
||||
SessionState.installing = null
|
||||
SessionState.stopRequested = false
|
||||
SessionState.program = null
|
||||
SessionState.programArgs = emptyList()
|
||||
SessionState.steamUi = null
|
||||
SessionState.steamUrl = null
|
||||
SessionState.firstFrameSeen = false
|
||||
SessionState.suspended = false
|
||||
}
|
||||
record("session.created", mapOf("mode" to mode), dir)
|
||||
}
|
||||
|
||||
fun transition(
|
||||
phase: SessionPhase,
|
||||
event: String,
|
||||
fields: Map<String, Any?> = emptyMap(),
|
||||
) {
|
||||
synchronized(SessionState) {
|
||||
if (SessionState.phase != phase) {
|
||||
SessionState.phase = phase
|
||||
SessionState.lastTransitionAt = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
record(event, fields)
|
||||
}
|
||||
|
||||
fun record(event: String, fields: Map<String, Any?> = emptyMap(), directory: File? = null) {
|
||||
val dir = directory ?: SessionState.logDirectory ?: SessionPaths.current() ?: return
|
||||
val target = if (directory == null) SessionState.eventsFile ?: File(dir, "events.jsonl")
|
||||
else File(dir, "events.jsonl")
|
||||
val payload = JSONObject()
|
||||
.put("t", System.currentTimeMillis())
|
||||
.put("event", event)
|
||||
.put("sessionId", dir.name)
|
||||
fields.forEach { (key, value) -> payload.put(key, value ?: JSONObject.NULL) }
|
||||
|
||||
try {
|
||||
synchronized(lock) {
|
||||
target.parentFile?.mkdirs()
|
||||
FileOutputStream(target, true).use { stream ->
|
||||
stream.write((payload.toString() + "\n").toByteArray(Charsets.UTF_8))
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "writing ${target.name}", e)
|
||||
}
|
||||
}
|
||||
|
||||
fun fail(code: String, message: String, status: Int? = null) {
|
||||
synchronized(SessionState) {
|
||||
SessionState.phase = SessionPhase.FAILED
|
||||
SessionState.lastTransitionAt = System.currentTimeMillis()
|
||||
SessionState.failureCode = code
|
||||
SessionState.failureMessage = message
|
||||
SessionState.failureStatus = status
|
||||
}
|
||||
record("session.failed", mapOf("code" to code, "message" to message, "status" to status))
|
||||
}
|
||||
|
||||
fun firstFrame() {
|
||||
SessionState.firstFrameSeen = true
|
||||
record("frame.first")
|
||||
markReadyIfPossible()
|
||||
}
|
||||
|
||||
fun guestStarted(pid: Int) {
|
||||
SessionState.guestPid = pid
|
||||
record("guest.started", mapOf("pid" to pid))
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) {
|
||||
transition(SessionPhase.STARTING_STEAM, "steam.starting")
|
||||
}
|
||||
markReadyIfPossible()
|
||||
}
|
||||
|
||||
fun markReadyIfPossible() {
|
||||
if (!SessionState.running || SessionState.guestPid <= 1 || !SessionState.firstFrameSeen || SessionState.suspended) return
|
||||
if (SessionState.phase != SessionPhase.READY) {
|
||||
transition(SessionPhase.READY, "session.ready")
|
||||
}
|
||||
}
|
||||
|
||||
fun resumePhase(): SessionPhase = when {
|
||||
SessionState.firstFrameSeen && SessionState.guestPid > 1 -> SessionPhase.READY
|
||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.guestPid > 1 -> SessionPhase.STARTING_STEAM
|
||||
else -> SessionPhase.STARTING_GUEST
|
||||
}
|
||||
}
|
||||
@@ -38,10 +38,13 @@ object SessionFiles {
|
||||
"usr/local/bin/bannerlator-desktop-games" to "usr/local/bin/bannerlator-desktop-games",
|
||||
"usr/local/bin/bannerlator-steam-shim" to "usr/local/bin/bannerlator-steam-shim",
|
||||
"usr/local/bin/bannerlator-steam-shortcuts" to "usr/local/bin/bannerlator-steam-shortcuts",
|
||||
"usr/local/bin/bannerlator-pad-defaults" to "usr/local/bin/bannerlator-pad-defaults",
|
||||
// The SteamOS helpers the client calls in Deck mode: the two Armada found it needs, plus
|
||||
// the three under /usr/bin, all no-ops that answer "nothing to do" (see each file).
|
||||
"usr/bin/steamos-update" to "usr/bin/steamos-update",
|
||||
"usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch",
|
||||
// Big Picture's "Switch to Desktop": asks the app for the desktop with Steam in it.
|
||||
"usr/bin/steamos-session-select" to "usr/bin/steamos-session-select",
|
||||
"usr/bin/jupiter-biosupdate" to "usr/bin/jupiter-biosupdate",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-priv-write" to "usr/bin/steamos-polkit-helpers/steamos-priv-write",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-set-timezone" to "usr/bin/steamos-polkit-helpers/steamos-set-timezone",
|
||||
@@ -56,6 +59,9 @@ object SessionFiles {
|
||||
// staging them into a runtime without it would make the desktop look present when it is not.
|
||||
val desktop = arrayOf(
|
||||
"usr/local/bin/droiddeck-desktop" to "usr/local/bin/droiddeck-desktop",
|
||||
// Games and emulators from the menu, full screen in a gamescope of their own.
|
||||
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
|
||||
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
|
||||
"etc/xdg/labwc/autostart" to "etc/xdg/labwc/autostart",
|
||||
"etc/xdg/labwc/rc.xml" to "etc/xdg/labwc/rc.xml",
|
||||
"etc/xdg/lxqt/panel.conf" to "etc/xdg/lxqt/panel.conf",
|
||||
@@ -75,9 +81,13 @@ object SessionFiles {
|
||||
"usr/local/lib/mangoapp/libtraceevent.so.1",
|
||||
"usr/local/lib/mangoapp/libtracefs.so.1",
|
||||
).map { it to it }
|
||||
// The patched wlroots (tools/wlroots) the desktop loads for its vulkan / gles2 renderers.
|
||||
val wlroots = if (File(root, "usr/bin/labwc").isFile) {
|
||||
arrayOf("usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so" to "usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so")
|
||||
} else emptyArray()
|
||||
val optional = (arrayOf(
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
) + mangoapp).filter { (asset, _) ->
|
||||
) + wlroots + mangoapp).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
@@ -138,8 +148,142 @@ object SessionFiles {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write ld.so.preload")
|
||||
}
|
||||
|
||||
val startupMovie = File(root, "root/.local/share/Steam/config/uioverrides/movies/droiddeck-startup.webm")
|
||||
val stagedMovie = File(startupMovie.parentFile, startupMovie.name + ".staged")
|
||||
var movieInstalled = false
|
||||
try {
|
||||
startupMovie.parentFile?.mkdirs()
|
||||
context.assets.open("steam-startup/droiddeck-startup.webm").use { input ->
|
||||
stagedMovie.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
movieInstalled = stagedMovie.setReadable(true, false) && stagedMovie.renameTo(startupMovie)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not stage Steam startup movie", e)
|
||||
} finally {
|
||||
if (!movieInstalled) stagedMovie.delete()
|
||||
}
|
||||
if (!movieInstalled) Log.e(TAG, "Steam startup movie NOT staged")
|
||||
if (movieInstalled) ensureStartupMovieDefault(File(root, "root/.local/share/Steam/config/config.vdf"))
|
||||
}
|
||||
|
||||
private data class VdfBlock(val keyStart: Int, val open: Int, val close: Int)
|
||||
|
||||
private fun ensureStartupMovieDefault(config: File) {
|
||||
val path = "/uioverrides/movies/droiddeck-startup.webm"
|
||||
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config for startup movie", it)
|
||||
return
|
||||
} else ""
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val movie = findObject(text, "StartupMovie", 0, text.length)
|
||||
if (movie != null) {
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
val selectedId = scalar(block, "MovieID")
|
||||
val selectedPath = scalar(block, "LocalPath")
|
||||
if (selectedPath == path) {
|
||||
Log.i(TAG, "Steam startup movie is set to DroidDeck")
|
||||
return
|
||||
}
|
||||
if ((!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()) {
|
||||
Log.i(TAG, "Steam startup movie selection preserved")
|
||||
return
|
||||
}
|
||||
val updated = setScalar(block, "MovieID", "0", newline)
|
||||
.let { setScalar(it, "LocalPath", path, newline) }
|
||||
text = text.replaceRange(movie.keyStart, movie.close + 1, updated)
|
||||
} else {
|
||||
val steam = findSteamBlock(text)
|
||||
if (steam == null) {
|
||||
if (text.isNotBlank()) {
|
||||
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
|
||||
return
|
||||
}
|
||||
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
|
||||
val section = startupMovieSection("\t\t\t\t", path, newline)
|
||||
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
|
||||
val section = startupMovieSection(indent + "\t", path, newline)
|
||||
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
|
||||
}
|
||||
}
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
try {
|
||||
config.parentFile?.mkdirs()
|
||||
staged.writeText(text)
|
||||
if (!staged.renameTo(config)) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write Steam startup movie selection")
|
||||
} else {
|
||||
Log.i(TAG, "Steam startup movie default selected")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not write Steam startup movie selection", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun findSteamBlock(text: String): VdfBlock? {
|
||||
val install = findObject(text, "InstallConfigStore", 0, text.length) ?: return null
|
||||
val software = findObject(text, "Software", install.open + 1, install.close) ?: return null
|
||||
val valve = findObject(text, "Valve", software.open + 1, software.close) ?: return null
|
||||
return findObject(text, "Steam", valve.open + 1, valve.close)
|
||||
}
|
||||
|
||||
private fun findObject(text: String, key: String, start: Int, end: Int): VdfBlock? {
|
||||
val pattern = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]*(?:\\r?\\n[\\t ]*)?\\{")
|
||||
val match = pattern.find(text, start)?.takeIf { it.range.first < end && it.range.last < end } ?: return null
|
||||
val open = text.indexOf('{', match.range.first).takeIf { it < end } ?: return null
|
||||
var depth = 0
|
||||
var quoted = false
|
||||
var escaped = false
|
||||
for (index in open until end) {
|
||||
val char = text[index]
|
||||
if (quoted) {
|
||||
if (escaped) escaped = false
|
||||
else if (char == '\\') escaped = true
|
||||
else if (char == '\"') quoted = false
|
||||
} else {
|
||||
when (char) {
|
||||
'\"' -> quoted = true
|
||||
'{' -> depth++
|
||||
'}' -> {
|
||||
depth--
|
||||
if (depth == 0) return VdfBlock(match.range.first, open, index)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun scalar(block: String, key: String): String? {
|
||||
val pattern = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]+\"([^\"\\r\\n]*)\"")
|
||||
return pattern.find(block)?.groupValues?.get(1)
|
||||
}
|
||||
|
||||
private fun setScalar(block: String, key: String, value: String, newline: String): String {
|
||||
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*)$")
|
||||
val match = pattern.find(block)
|
||||
if (match != null) return block.replaceRange(match.range, match.groupValues[1] + "\"" + value + "\"" + match.groupValues[2])
|
||||
val close = block.lastIndexOf('}')
|
||||
if (close < 0) return block
|
||||
val lineStart = block.lastIndexOf('\n', close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = block.substring(lineStart, close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val entry = indent + "\"" + key + "\"\t\t\"" + value + "\"" + newline
|
||||
return block.substring(0, lineStart) + entry + block.substring(lineStart)
|
||||
}
|
||||
|
||||
private fun startupMovieSection(indent: String, path: String, newline: String): String = listOf(
|
||||
indent + "\"StartupMovie\"",
|
||||
indent + "{",
|
||||
indent + "\t\"MovieID\"\t\t\"0\"",
|
||||
indent + "\t\"LocalPath\"\t\t\"" + path + "\"",
|
||||
indent + "}",
|
||||
).joinToString(newline)
|
||||
|
||||
/**
|
||||
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
|
||||
* folder rather than dug out of app-private storage - but the session script redirects its own
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.ClipData
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.content.FileProvider
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.util.zip.ZipEntry
|
||||
@@ -22,14 +23,28 @@ object SessionLogShare {
|
||||
.maxByOrNull { it.name }
|
||||
|
||||
/** Builds the zip (blocking). Returns null when there is no session to share. */
|
||||
fun zipLatest(context: Context): File? {
|
||||
val folder = latest(context) ?: return null
|
||||
fun zipLatest(context: Context): File? = latest(context)?.let { zipFolder(context, it) }
|
||||
|
||||
/** Builds a zip for one specific session folder (blocking). */
|
||||
fun zipFolder(context: Context, folder: File): File? {
|
||||
if (!folder.isDirectory) return null
|
||||
val files = folder.walkTopDown().filter { it.isFile }.toList()
|
||||
if (files.isEmpty()) return null
|
||||
val out = File(context.cacheDir, "shared-logs").apply { deleteRecursively(); mkdirs() }
|
||||
val zip = File(out, "DroidDeck-${folder.name}.zip")
|
||||
// Scrubbed on the way into the zip: a session shared while it runs has not had its end-of-
|
||||
// session pass yet, and the redactor changes nothing in a line that is already clean.
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { z ->
|
||||
folder.walkTopDown().filter { it.isFile }.forEach { f ->
|
||||
files.forEach { f ->
|
||||
z.putNextEntry(ZipEntry(folder.name + "/" + f.relativeTo(folder).path))
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
if (LogRedactor.isText(f)) {
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubTo(f, w)
|
||||
w.flush()
|
||||
} else {
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
}
|
||||
z.closeEntry()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,14 +41,16 @@ object SessionPaths {
|
||||
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
|
||||
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
|
||||
else File(context.cacheDir, "session-logs")
|
||||
val made = File(parent, "session-$stamp")
|
||||
val baseName = "session-$stamp"
|
||||
var made = File(parent, baseName)
|
||||
var suffix = 2
|
||||
while (made.exists()) made = File(parent, "$baseName-${suffix++}")
|
||||
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
|
||||
dir = made
|
||||
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
|
||||
return made
|
||||
}
|
||||
|
||||
/** The current session's folder, or null between sessions. */
|
||||
fun current(): File? = dir
|
||||
|
||||
/**
|
||||
@@ -63,7 +65,6 @@ object SessionPaths {
|
||||
return ended
|
||||
}
|
||||
|
||||
/** A file in the current session's folder, or null between sessions. */
|
||||
fun file(name: String): File? = dir?.let { File(it, name) }
|
||||
|
||||
/** Let the next session claim a new folder. Called when a session ends. */
|
||||
|
||||
@@ -13,6 +13,12 @@ object SessionPrefs {
|
||||
const val OSC_STEAM_QAM = "steam-qam"
|
||||
const val OSC_NEVER = "never"
|
||||
|
||||
const val BACK_MENU_THEN_QAM = "1: menu 2: QAM"
|
||||
const val BACK_QAM_THEN_MENU = "1: QAM 2: menu"
|
||||
|
||||
fun backActionsOrder(inverted: Boolean): String =
|
||||
if (inverted) BACK_QAM_THEN_MENU else BACK_MENU_THEN_QAM
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean("hud", true)
|
||||
@@ -21,6 +27,13 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("hud", on).apply()
|
||||
}
|
||||
|
||||
/** When enabled, a single Back opens Steam QAM and a double Back opens the session menu. */
|
||||
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
|
||||
|
||||
fun setBackActionsInverted(context: Context, inverted: Boolean) {
|
||||
prefs(context).edit().putBoolean("backActionsInverted", inverted).apply()
|
||||
}
|
||||
|
||||
const val TOUCH_AUTO = "auto"
|
||||
const val TOUCH_PAD = "touchpad"
|
||||
const val TOUCH_DIRECT = "direct"
|
||||
@@ -39,9 +52,9 @@ object SessionPrefs {
|
||||
|
||||
/** The choices the settings offer, in order. */
|
||||
val shapeChoices = listOf(
|
||||
SHAPE_AUTO to "The panel's shape (16:9 or wider)",
|
||||
SHAPE_EXACT to "Exactly this panel (4:3, 3:2…)",
|
||||
SHAPE_WIDE to "16:9 with bars",
|
||||
SHAPE_AUTO to "Auto (16:9+)",
|
||||
SHAPE_EXACT to "Match screen",
|
||||
SHAPE_WIDE to "Always 16:9",
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -87,6 +100,32 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("clientDirectAudio", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Steam only: gamescope makes every game window the size of the screen. A game that resizes
|
||||
* its own window when it loses focus (FlatOut) otherwise comes back smaller, drawn in a
|
||||
* corner; a game that sets its own resolution and never looks at its window again (Quake 3)
|
||||
* instead draws small in the bottom-left of the stretched one. On unless turned off.
|
||||
*/
|
||||
fun forceFullscreen(context: Context): Boolean = prefs(context).getBoolean("forceFullscreen", true)
|
||||
|
||||
fun setForceFullscreen(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("forceFullscreen", on).apply()
|
||||
writeForceFullscreenFlag(context)
|
||||
}
|
||||
|
||||
/**
|
||||
* The same choice as a file the running session watches, so the drawer can change it live:
|
||||
* the session hands every change to gamescope, which reads GAMESCOPE_FORCE_WINDOWS_FULLSCREEN
|
||||
* off its root window whenever it changes. Written again at every session start so a file left
|
||||
* by an earlier session never disagrees with the setting.
|
||||
*/
|
||||
fun writeForceFullscreenFlag(context: Context) {
|
||||
runCatching {
|
||||
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.droiddeck-fill")
|
||||
.writeText(if (forceFullscreen(context)) "1\n" else "0\n")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DirectAudio for games: their Wine audio driver talks to the relay helper on this side. On
|
||||
* unless the user turned it off.
|
||||
@@ -243,6 +282,10 @@ object SessionPrefs {
|
||||
*/
|
||||
fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", defaultResolutionCap(mode))
|
||||
|
||||
/** Whether the user chose the mode's resolution (a cap or a custom size) rather than the default. */
|
||||
fun resolutionChosen(context: Context, mode: String): Boolean =
|
||||
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null
|
||||
|
||||
/** The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults. */
|
||||
fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", "") ?: ""
|
||||
|
||||
@@ -330,14 +373,18 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
/**
|
||||
* What the desktop shell composites with: pixman (software, the default - the Adreno stand-in
|
||||
* is not a DRM render node, so labwc's gbm allocator cannot use it), or gles2 / vulkan for a
|
||||
* device that has a real node. `Download/droiddeck-wlr-renderer` still overrides it.
|
||||
* What the desktop shell composites with: vulkan (the default) or gles2 on the GPU, through the
|
||||
* app's patched wlroots (tools/wlroots) - the Adreno stand-in is not a DRM device and stock
|
||||
* wlroots cannot allocate on it - or pixman in software. A GPU renderer a device cannot start
|
||||
* falls back to pixman by itself (droiddeck-desktop). `Download/droiddeck-wlr-renderer` still
|
||||
* overrides it.
|
||||
*/
|
||||
fun desktopRenderer(context: Context): String = prefs(context).getString("desktopRenderer", "pixman") ?: "pixman"
|
||||
fun desktopRenderer(context: Context): String = prefs(context).getString("desktopRenderer", "vulkan") ?: "vulkan"
|
||||
|
||||
fun setDesktopRenderer(context: Context, renderer: String) {
|
||||
prefs(context).edit().putString("desktopRenderer", renderer).apply()
|
||||
// A choice made again is a retry: forget that a renderer failed to start here before.
|
||||
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.droiddeck-renderer-failed").delete()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -144,6 +144,13 @@ class SessionService : Service() {
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_SUSPEND_POLICY_CHANGED -> {
|
||||
if (!SessionState.running) return START_NOT_STICKY
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_RESUME -> {
|
||||
activityVisible = true
|
||||
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn
|
||||
@@ -155,6 +162,11 @@ class SessionService : Service() {
|
||||
}
|
||||
startForeground(NOTIFICATION_ID, buildNotification())
|
||||
if (SessionState.running) return START_NOT_STICKY
|
||||
if (SessionState.stopRequested) {
|
||||
SessionState.running = true
|
||||
stopSession(0)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
activityVisible = true
|
||||
@@ -168,11 +180,18 @@ class SessionService : Service() {
|
||||
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
|
||||
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
|
||||
SessionState.running = true
|
||||
if (SessionState.stopRequested) {
|
||||
stopSession(0)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
// Another Steam client on the device signs ours out seconds after every login; the one that
|
||||
// does it here runs from boot without being opened. Only the Steam session signs in.
|
||||
if (SessionState.mode == MODE_STEAM) RivalClients.stopBeforeSession(this)
|
||||
SessionState.running = true
|
||||
// The desktop too: its Steam launchers run the client right there (bannerlator-steam-launch).
|
||||
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) RivalClients.stopBeforeSession(this)
|
||||
SessionState.firstFrameSeen = false
|
||||
SessionState.guestPid = -1
|
||||
SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode))
|
||||
// This session's number, claimed here and not when its process starts: the session it
|
||||
// replaces can report its own exit in the gap between the two, and that exit must not
|
||||
// be taken as this one's.
|
||||
@@ -249,6 +268,10 @@ class SessionService : Service() {
|
||||
val sessionDir = SessionPaths.beginOrCurrent(this)
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
SessionState.logFile = sessionLog
|
||||
SessionState.logDirectory = sessionDir
|
||||
SessionState.sessionId = sessionDir.name
|
||||
SessionState.eventsFile = File(sessionDir, "events.jsonl")
|
||||
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
|
||||
// Written first, so a session that dies in its first second still says what it ran on.
|
||||
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
|
||||
NetworkReport.write(this, File(sessionDir, "network.txt"))
|
||||
@@ -280,7 +303,12 @@ class SessionService : Service() {
|
||||
// An imported glibc Turnip for this mode, when the user chose one: the session script checks
|
||||
// the manifest and its library from inside and points the loader at it with VK_DRIVER_FILES,
|
||||
// so the runtime's own driver above stays untouched and is what a bad import falls back to.
|
||||
val linuxDriverId = SessionPrefs.linuxDriver(this, SessionPrefs.prefMode(SessionState.mode))
|
||||
// A program from the rail is one of the desktop's emulators, so it draws with the desktop's
|
||||
// Linux driver, not the Steam session's: the driver's shader cache is keyed on the driver
|
||||
// build, and with two drivers every emulator compiled its shaders twice - once per way of
|
||||
// starting it (RPCS3's 6650 interpreter variants on each first boot).
|
||||
val driverMode = if (SessionState.mode == MODE_RUN) MODE_DESKTOP else SessionPrefs.prefMode(SessionState.mode)
|
||||
val linuxDriverId = SessionPrefs.linuxDriver(this, driverMode)
|
||||
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
|
||||
@@ -298,7 +326,14 @@ class SessionService : Service() {
|
||||
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
|
||||
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
|
||||
// The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the
|
||||
// same set-up as a Steam session: it gets what the client and its games are started with.
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
|
||||
SessionPrefs.writeForceFullscreenFlag(this)
|
||||
}
|
||||
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
|
||||
// XALIA_SUPPORTED_ONLY itself otherwise). Off by default: xalia is Valve's, and on a device
|
||||
// whose seccomp answers its syscalls normally there is no reason to take it away.
|
||||
@@ -306,7 +341,7 @@ class SessionService : Service() {
|
||||
// The FEXCore preset for the x86 games the client launches: its FEX_* variables go in
|
||||
// here, before the script, so every game process inherits them from the client. The
|
||||
// default preset sets nothing, which is what every session ran on before.
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
if (steamHere) {
|
||||
val preset = SessionPrefs.fexPreset(this)
|
||||
val vars = com.droiddeck.launcher.core.FexPreset.env(preset)
|
||||
vars.forEach { guest.add(it) }
|
||||
@@ -321,13 +356,13 @@ class SessionService : Service() {
|
||||
// on, even naming every core: it exists to undo the pin Steam applies to its own interface
|
||||
// renderer, and the scheduler's default is exactly what that pin takes away. A game's is
|
||||
// sent only when it is a real restriction - a game has no pin of its own to undo.
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
if (SessionPrefs.clientCpusOverride(this)) {
|
||||
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
|
||||
}
|
||||
CpuCores.restrictionOrEmpty(SessionPrefs.gameCpus(this))
|
||||
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
|
||||
if (steamHere && SessionPrefs.clientCpusOverride(this)) {
|
||||
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
|
||||
}
|
||||
// The game cores also pin the desktop and a program from the rail; without a choice the
|
||||
// session script picks every core but the slowest cluster for those (program_cores).
|
||||
CpuCores.restrictionOrEmpty(SessionPrefs.gameCpus(this))
|
||||
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
|
||||
|
||||
// PulseAudio always: the client is a native Linux program and has no other way to make a
|
||||
// sound - its menus, its music and its voice chat all go through here. DirectAudio is not
|
||||
@@ -398,7 +433,11 @@ class SessionService : Service() {
|
||||
// identity gets the standard layout without the user configuring the pad by hand.
|
||||
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
|
||||
guest.add("FAKE_EVDEV_VIBRATION=1")
|
||||
guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
|
||||
// Steam Input's virtual-gamepad identity is for games the client starts, which are
|
||||
// meant to see that pad. Everywhere else (the desktop, a program from the rail) it
|
||||
// hides the pad: SDL ignores a Steam virtual gamepad unless it runs under Steam, so
|
||||
// every SDL emulator came up with no controller. There it is a plain Xbox 360 pad.
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
|
||||
guest.add("SDL_JOYSTICK_DISABLE_UDEV=1")
|
||||
guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1")
|
||||
guest.add("SDL_JOYSTICK_HIDAPI=0")
|
||||
@@ -407,12 +446,11 @@ class SessionService : Service() {
|
||||
}
|
||||
SessionState.fakeInputDir = fakeInputDir
|
||||
}
|
||||
// The desktop is wlroots (labwc), and wlroots allocates its buffers through gbm on a real
|
||||
// DRM render node. Ours is a KGSL stand-in that gbm cannot use - labwc dies at "unable to
|
||||
// create allocator" - so the desktop shell is composited by pixman (software, a shm
|
||||
// allocator, no DRM). Accelerated clients on it pay a CPU copy; a 2D emulator does not
|
||||
// notice, a demanding one does. droiddeck-wlr-renderer in Downloads (pixman/vulkan/gles2)
|
||||
// overrides it, for trying acceleration on a device that has a real node.
|
||||
// The desktop is wlroots (labwc). Stock wlroots allocates through gbm on a real DRM render
|
||||
// node, and ours is a KGSL stand-in - labwc died at "unable to create allocator" - so the
|
||||
// default is pixman (software, shm), where a Vulkan program cannot draw at all; those run
|
||||
// through droiddeck-gpu instead. vulkan / gles2 use the app's patched wlroots and fall back
|
||||
// to pixman by themselves. droiddeck-wlr-renderer in Downloads overrides the choice.
|
||||
if (SessionState.mode == MODE_DESKTOP) {
|
||||
val override = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-wlr-renderer")
|
||||
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }
|
||||
@@ -420,7 +458,7 @@ class SessionService : Service() {
|
||||
}
|
||||
// The user's own games, for the runtime's shortcuts writer to put in the client's library
|
||||
// before the client starts (see frontend/AddedGames and bannerlator-steam-shortcuts).
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
if (steamHere) {
|
||||
val added = com.droiddeck.launcher.frontend.AddedGames.scan(this)
|
||||
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
|
||||
guest.add("BL_ADDED_GAMES=" + listing.path)
|
||||
@@ -431,6 +469,9 @@ class SessionService : Service() {
|
||||
// The second library's name, for bannerlator-steam-library; the bind itself is made below.
|
||||
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
|
||||
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop")
|
||||
// The desktop asked for with Steam in it (the front end's "Steam Desktop UI", Big Picture's
|
||||
// "Switch to Desktop"): the desktop's autostart opens the client's desktop UI there.
|
||||
if (SessionState.mode == MODE_DESKTOP && SessionState.steamUi == "desktop") guest.add("BL_DESKTOP_STEAM=1")
|
||||
val shellGuest = ArrayList(guest).apply {
|
||||
add("SHELL=/bin/bash")
|
||||
add("TERM=xterm-256color")
|
||||
@@ -555,7 +596,7 @@ class SessionService : Service() {
|
||||
|
||||
// Whether the client signs in to Valve or starts offline: read once, while it starts, and
|
||||
// rewritten by the client when it exits, so it is set again here at every session start.
|
||||
if (SessionState.mode == MODE_STEAM) OfflineMode.apply(this, root)
|
||||
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) OfflineMode.apply(this, root)
|
||||
|
||||
val networkLink = LinuxNetworkLinkComponent(this, root)
|
||||
networkLink.attach(this)
|
||||
@@ -563,7 +604,9 @@ class SessionService : Service() {
|
||||
components.add(networkLink)
|
||||
components.forEach { it.start() }
|
||||
|
||||
val line = command.joinToString(" ") { it.replace(" ", "\\ ") }
|
||||
val line = command.joinToString(" ") {
|
||||
it.replace("\\", "\\\\").replace(" ", "\\ ")
|
||||
}
|
||||
watchLaunchRequests(sessionRoot)
|
||||
// One session replacing another (the desktop's Steam launchers): the old proot is killed
|
||||
// by the teardown a second after the new one has started, and its exit used to arrive
|
||||
@@ -578,6 +621,14 @@ class SessionService : Service() {
|
||||
stopSession(status ?: -1)
|
||||
}, null)
|
||||
Log.i(TAG, "session pid $sessionPid, log ${sessionLog.path}")
|
||||
if (gen == sessionGen && SessionState.running && sessionPid > 1) {
|
||||
SessionEvents.guestStarted(sessionPid)
|
||||
} else if (gen == sessionGen && SessionState.running) {
|
||||
SessionEvents.record("guest.start_failed", mapOf("pid" to sessionPid))
|
||||
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", sessionPid)
|
||||
stopSession(-1)
|
||||
return
|
||||
}
|
||||
if (gen == sessionGen && SessionState.running) {
|
||||
suspendController = SessionSuspendController(
|
||||
sessionRoot = { sessionPid },
|
||||
@@ -686,6 +737,8 @@ class SessionService : Service() {
|
||||
* The desktop's Steam launchers cannot start the client where they are (no dma-buf on the
|
||||
* desktop), so they leave `steam-launch` in the session directory instead: which UI, and a
|
||||
* steam:// URL or nothing. This ends the session and hands the activity the one to start.
|
||||
* `session=desktop` (Big Picture's "Switch to Desktop", steamos-session-select) asks for the
|
||||
* desktop instead, with Steam's desktop client started in it.
|
||||
*/
|
||||
private var launchWatcher: android.os.FileObserver? = null
|
||||
|
||||
@@ -700,15 +753,18 @@ class SessionService : Service() {
|
||||
file.delete()
|
||||
var ui = "desktop"
|
||||
var url = ""
|
||||
var session = MODE_STEAM
|
||||
text.lineSequence().forEach { line ->
|
||||
when {
|
||||
line.startsWith("ui=") -> ui = line.removePrefix("ui=").trim()
|
||||
line.startsWith("url=") -> url = line.removePrefix("url=").trim()
|
||||
line.startsWith("session=") && line.removePrefix("session=").trim() == "desktop" -> session = MODE_DESKTOP
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "launch request from the session: Steam $ui" + (if (url.isNotEmpty()) " $url" else ""))
|
||||
Log.i(TAG, "launch request from the session: " + (if (session == MODE_DESKTOP) "the desktop with " else "") +
|
||||
"Steam $ui" + (if (url.isNotEmpty()) " $url" else ""))
|
||||
val next = Intent(this@SessionService, com.droiddeck.launcher.SessionActivity::class.java)
|
||||
.putExtra(EXTRA_MODE, MODE_STEAM)
|
||||
.putExtra(EXTRA_MODE, session)
|
||||
.putExtra(EXTRA_STEAM_UI, ui)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (url.isNotEmpty()) next.putExtra(EXTRA_STEAM_URL, url)
|
||||
@@ -740,6 +796,7 @@ class SessionService : Service() {
|
||||
suspendOperationPending = false
|
||||
if (success) {
|
||||
SessionState.suspended = true
|
||||
SessionEvents.transition(SessionPhase.SUSPENDED, "session.suspended")
|
||||
releaseLocks()
|
||||
refreshNotification()
|
||||
} else {
|
||||
@@ -757,6 +814,7 @@ class SessionService : Service() {
|
||||
suspendOperationPending = false
|
||||
if (success) {
|
||||
SessionState.suspended = false
|
||||
SessionEvents.transition(SessionEvents.resumePhase(), "session.resumed")
|
||||
refreshNotification()
|
||||
} else {
|
||||
suspendAttemptFailed = true
|
||||
@@ -771,7 +829,16 @@ class SessionService : Service() {
|
||||
private fun finishSessionStop(status: Int) {
|
||||
mainHandler.post {
|
||||
SessionState.suspended = false
|
||||
SessionState.guestPid = -1
|
||||
releaseLocks()
|
||||
if (status == 0) {
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
|
||||
} else {
|
||||
val code = SessionState.failureCode ?: "GUEST_EXIT"
|
||||
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
|
||||
val failureStatus = SessionState.failureStatus ?: status
|
||||
SessionEvents.fail(code, message, failureStatus)
|
||||
}
|
||||
SessionState.notifyEnded(status)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
@@ -781,6 +848,9 @@ class SessionService : Service() {
|
||||
private fun stopSession(status: Int) {
|
||||
if (!SessionState.running) return
|
||||
SessionState.running = false
|
||||
SessionState.stopRequested = false
|
||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
|
||||
suspendOperationPending = false
|
||||
launchWatcher?.stopWatching()
|
||||
launchWatcher = null
|
||||
@@ -962,6 +1032,8 @@ class SessionService : Service() {
|
||||
const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION"
|
||||
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
|
||||
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
|
||||
const val ACTION_AGENT_START = "com.droiddeck.launcher.AGENT_START"
|
||||
private const val ACTION_SUSPEND_POLICY_CHANGED = "com.droiddeck.launcher.SUSPEND_POLICY_CHANGED"
|
||||
private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE"
|
||||
private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN"
|
||||
private const val ACTION_TRACK_AUXILIARY = "com.droiddeck.launcher.TRACK_AUXILIARY"
|
||||
@@ -970,7 +1042,7 @@ class SessionService : Service() {
|
||||
private const val EXTRA_AUXILIARY_PID = "auxiliaryPid"
|
||||
/** Command lines that can only belong to a session of ours. */
|
||||
private val STRAGGLERS = listOf("bannerlator-session", "gamescope", "Xwayland", "steamrtarm64",
|
||||
"steamwebhelper", "linuxfs/opt/android-host/proot", "pulseaudio/libpulseaudio.so")
|
||||
"steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so")
|
||||
/** How long proot gets to run its own cleanup before it is killed outright. */
|
||||
private const val GRACE_MS = 1200L
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
@@ -984,7 +1056,8 @@ class SessionService : Service() {
|
||||
const val EXTRA_PROGRAM = "program"
|
||||
/** MODE_RUN: arguments after the program (a game to boot). */
|
||||
const val EXTRA_PROGRAM_ARGS = "programArgs"
|
||||
/** MODE_STEAM: "desktop" for the client's desktop UI (default Big Picture); a steam:// URL to hand it. */
|
||||
/** MODE_STEAM: "desktop" for the client's desktop UI (default Big Picture); a steam:// URL to hand it.
|
||||
* MODE_DESKTOP: "desktop" = open Steam's desktop client in the desktop once it is up. */
|
||||
const val EXTRA_STEAM_UI = "steamUi"
|
||||
const val EXTRA_STEAM_URL = "steamUrl"
|
||||
|
||||
@@ -1016,6 +1089,11 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_RESUME))
|
||||
}
|
||||
|
||||
fun suspendPolicyChanged(context: Context) {
|
||||
if (!SessionState.running) return
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED))
|
||||
}
|
||||
|
||||
/** Let the session service clean up the PTY's proot tree if the control screen closes. */
|
||||
fun stopTerminalProcess(context: Context, pid: Int) {
|
||||
if (pid > 1) context.startService(
|
||||
|
||||
@@ -11,14 +11,51 @@ import androidx.compose.runtime.setValue
|
||||
* either can outlive the other.
|
||||
*/
|
||||
object SessionState {
|
||||
@Volatile
|
||||
var phase = SessionPhase.IDLE
|
||||
|
||||
@Volatile
|
||||
var sessionId: String? = null
|
||||
|
||||
@Volatile
|
||||
var lastTransitionAt = 0L
|
||||
|
||||
@Volatile
|
||||
var failureCode: String? = null
|
||||
|
||||
@Volatile
|
||||
var failureMessage: String? = null
|
||||
|
||||
@Volatile
|
||||
var failureStatus: Int? = null
|
||||
|
||||
@Volatile
|
||||
var logDirectory: File? = null
|
||||
|
||||
@Volatile
|
||||
var eventsFile: File? = null
|
||||
|
||||
@Volatile
|
||||
var guestPid = -1
|
||||
|
||||
@Volatile
|
||||
var installing: String? = null
|
||||
|
||||
@Volatile
|
||||
var stopRequested = false
|
||||
|
||||
@Volatile
|
||||
var running = false
|
||||
var suspended by mutableStateOf(false)
|
||||
/** MODE_RUN: the program inside the runtime the session was started for. */
|
||||
@Volatile
|
||||
var program: String? = null
|
||||
@Volatile
|
||||
var programArgs: List<String> = emptyList()
|
||||
/** MODE_STEAM: "desktop" for the client's desktop UI, else Big Picture; and a steam:// URL to hand it. */
|
||||
@Volatile
|
||||
var steamUi: String? = null
|
||||
@Volatile
|
||||
var steamUrl: String? = null
|
||||
/** A session the guest asked for (the desktop's Steam launchers): started by the activity once this one has ended. */
|
||||
var relaunch: android.content.Intent? = null
|
||||
@@ -57,3 +94,17 @@ object SessionState {
|
||||
endListener?.invoke(status)
|
||||
}
|
||||
}
|
||||
|
||||
/** Stable lifecycle values returned by the debug agent bridge. */
|
||||
enum class SessionPhase {
|
||||
IDLE,
|
||||
PREPARING,
|
||||
INSTALLING_RUNTIME,
|
||||
STARTING_COMPOSITOR,
|
||||
STARTING_GUEST,
|
||||
STARTING_STEAM,
|
||||
READY,
|
||||
SUSPENDED,
|
||||
STOPPING,
|
||||
FAILED,
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material.icons.outlined.Refresh
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.ComponentsManager.CatalogItem
|
||||
import com.droiddeck.launcher.session.ComponentsManager.Snapshot
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
|
||||
/** One installed row: a Proton's original bundle (one per Proton build) or a stored package. */
|
||||
private class InstalledItem(
|
||||
val name: String, val detail: String, val tag: String,
|
||||
val selected: Boolean, val removable: Boolean,
|
||||
/** Stored package file, or null for an original. */
|
||||
val file: String?,
|
||||
/** The Proton build an original belongs to. */
|
||||
val protonVersion: String?,
|
||||
)
|
||||
|
||||
private val ROW_HEIGHT: Dp = 40.dp
|
||||
private val DETAIL_WIDTH: Dp = 260.dp
|
||||
private val ACTION_WIDTH: Dp = 112.dp
|
||||
private val GOLD = Color(0xFFF2C66D)
|
||||
|
||||
/**
|
||||
* FEX, DXVK and VKD3D-Proton per Proton, as a full page opened from the rail's "Components" entry.
|
||||
* Compact on purpose (layout A of the mock): title, Proton drop-down, component tabs, what is in
|
||||
* use and refresh share one toolbar line, the explanation sits behind the (i), and installed rows
|
||||
* and the Nightlies' downloads run as one list of short rows - a landscape screen shows a dozen or
|
||||
* more instead of two. Tapping an installed row swaps it in; the refresh button is the only thing
|
||||
* that goes online.
|
||||
*/
|
||||
@Composable
|
||||
fun ComponentsPage(
|
||||
snapshot: Snapshot?,
|
||||
catalog: List<CatalogItem>,
|
||||
catalogAt: Long,
|
||||
protonId: String?,
|
||||
comp: String,
|
||||
checking: Boolean,
|
||||
busy: String?,
|
||||
downloads: Map<String, Int>,
|
||||
onProton: (String) -> Unit,
|
||||
onComp: (String) -> Unit,
|
||||
onSwap: (String) -> Unit,
|
||||
onRestore: (String) -> Unit,
|
||||
onCancelQueued: () -> Unit,
|
||||
onDeletePackage: (String) -> Unit,
|
||||
onDeleteOriginal: (String) -> Unit,
|
||||
onDownload: (CatalogItem) -> Unit,
|
||||
onRefresh: () -> Unit,
|
||||
onImport: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
BackHandler(onBack = onBack)
|
||||
var confirm by remember { mutableStateOf<Pair<String, () -> Unit>?>(null) }
|
||||
var confirmTitle by remember { mutableStateOf("") }
|
||||
var about by remember { mutableStateOf(false) }
|
||||
var protonMenu by remember { mutableStateOf(false) }
|
||||
fun ask(title: String, body: String, action: () -> Unit) { confirmTitle = title; confirm = body to action }
|
||||
|
||||
val views = snapshot?.protons ?: emptyList()
|
||||
val view = views.firstOrNull { it.proton.id == protonId } ?: views.firstOrNull()
|
||||
val label = ComponentsManager.LABEL[comp] ?: comp
|
||||
val checked = if (catalogAt > 0) DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(catalogAt * 1000)) else "never"
|
||||
|
||||
Column(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
// ---- the toolbar: one line ------------------------------------------------------------
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)) {
|
||||
FocusText("‹ Back", colors.onSurfaceVariant, onClick = onBack)
|
||||
Text("Components", fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
|
||||
if (view != null) {
|
||||
Box {
|
||||
ValueChip(view.proton.name, protonMenu, modifier = Modifier.widthIn(max = 260.dp)) { protonMenu = !protonMenu }
|
||||
AnchoredMenu(protonMenu, onDismiss = { protonMenu = false }, title = "Proton",
|
||||
note = "Valve's own Proton is replaced when Steam updates it; its originals are kept per build.") { first ->
|
||||
views.forEachIndexed { i, v ->
|
||||
val swaps = v.components.values.count { it.activeFile != null }
|
||||
MenuItem(
|
||||
v.proton.name, checked = v.proton.id == view.proton.id,
|
||||
detail = v.proton.version + (if (swaps > 0) " · $swaps swapped" else " · all original") + (if (v.inUseByGame) " · game running" else ""),
|
||||
focusRequester = if (i == 0) first else null,
|
||||
) { onProton(v.proton.id); protonMenu = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
BumperHint("LB")
|
||||
Segmented(ComponentsManager.COMPONENTS.map { it to ComponentsManager.LABEL.getValue(it) }, comp, onComp)
|
||||
BumperHint("RB")
|
||||
}
|
||||
val st = view.components.getValue(comp)
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
|
||||
Box(Modifier.size(8.dp).background(if (st.queued != null) Color(0xFFFFB86B) else pal.good, CircleShape))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
val fixedAt = if (view.reappliedAt > 0) " · re-applied at launch " + DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(view.reappliedAt * 1000)) else ""
|
||||
Text(
|
||||
(if (st.queued != null) "Next: ${st.queued} · after the game" else "In use: ${st.inUse}") + fixedAt,
|
||||
fontSize = 12.5.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (st.queued != null) { Spacer(Modifier.width(8.dp)); FocusText("Cancel", pal.signal, onClick = onCancelQueued) }
|
||||
}
|
||||
} else Spacer(Modifier.weight(1f))
|
||||
Text(if (busy != null) "$busy…" else "Nightlies · $checked", fontSize = 11.5.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
ToolIcon(Icons.Outlined.Info, "About Components") { about = true }
|
||||
ToolIcon(Icons.Outlined.Refresh, "Check the Nightlies for new packages", busy = checking, enabled = !checking, onClick = onRefresh)
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
|
||||
// ---- the list ---------------------------------------------------------------------------
|
||||
when {
|
||||
snapshot == null -> Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp)) {
|
||||
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text("Reading the Protons…", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
view == null -> Text(
|
||||
"No Proton is installed in the Linux runtime yet. Start the Steam client once so it downloads its ARM64 Proton, or add GE-Proton / CachyOS from Setup.",
|
||||
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(16.dp),
|
||||
)
|
||||
else -> {
|
||||
val p = view.proton
|
||||
val st = view.components.getValue(comp)
|
||||
val build = ComponentsManager.safeName(p.version)
|
||||
val originals = view.originals.filter { it.comp == comp }
|
||||
val stored = snapshot.packages.filter { it.comp == comp }
|
||||
val activeIsOriginal = st.activeFile == null
|
||||
val rows = originals.map { o ->
|
||||
val isCurrent = o.protonVersion == build
|
||||
InstalledItem(
|
||||
"Original · ${o.protonVersion}",
|
||||
o.label.substringAfterLast(" · ", "").ifEmpty { o.label } + if (isCurrent) " · this build" else " · earlier build",
|
||||
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
|
||||
)
|
||||
} + stored.map { s ->
|
||||
InstalledItem(s.version, String.format("%.1f MB", s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
|
||||
}
|
||||
val storedNames = snapshot.packages.map { it.file }.toSet()
|
||||
val available = catalog.filter { it.comp == comp && ComponentsManager.safeName(it.file) !in storedNames }
|
||||
val first = remember { FocusRequester() }
|
||||
LaunchedEffect(p.id, comp) { runCatching { first.requestFocus() } }
|
||||
|
||||
LazyColumn(Modifier.fillMaxWidth().weight(1f)) {
|
||||
item { SectionLabel("Installed · ${rows.size}") }
|
||||
if (rows.isEmpty()) item {
|
||||
Text("Nothing stored for $label yet. This Proton's own files are saved as its original when the page opens.",
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp))
|
||||
}
|
||||
items(rows.size) { i ->
|
||||
val item = rows[i]
|
||||
InstalledLine(
|
||||
item, modifier = if (i == 0) Modifier.focusRequester(first) else Modifier,
|
||||
onSelect = {
|
||||
if (item.selected) return@InstalledLine
|
||||
val waits = if (view.inUseByGame) " A game is running on this Proton, so it waits until the game closes." else " It applies the next time a game starts."
|
||||
if (item.file != null) ask("Swap $label?", "Put ${item.name} into ${p.name}? Its shipped files stay saved as an original bundle.$waits") { onSwap(item.file) }
|
||||
else ask("Restore $label?", "Put the ${item.protonVersion} original back into ${p.name}?$waits") { onRestore(item.protonVersion!!) }
|
||||
},
|
||||
onDelete = {
|
||||
if (item.file != null) ask("Delete ${item.name}?", "Its package file is removed from the app. You can download it again any time.") { onDeletePackage(item.file) }
|
||||
else ask("Delete this original?", "The ${item.protonVersion} original of $label belongs to an earlier build of ${p.name}. The installed build's original is always kept.") { onDeleteOriginal(item.protonVersion!!) }
|
||||
},
|
||||
)
|
||||
}
|
||||
item { SectionLabel("Available on the Nightlies · ${available.size}") }
|
||||
if (available.isEmpty()) item {
|
||||
Text(if (catalogAt == 0L) "Tap refresh to list the packages on the Nightlies." else "Nothing new from the last check.",
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp))
|
||||
}
|
||||
items(available.size) { i ->
|
||||
val d = available[i]
|
||||
AvailableLine(d, downloads[d.file], enabled = busy == null) { onDownload(d) }
|
||||
}
|
||||
item {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(horizontal = 8.dp, vertical = 10.dp)) {
|
||||
SmallButton("Import .wcp", onClick = onImport)
|
||||
if (!activeIsOriginal && originals.any { it.protonVersion == build }) FocusText("Restore this Proton's original", pal.signal) {
|
||||
ask("Restore $label?", "Put ${p.name}'s original $label back?") { onRestore(build) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (about) AlertDialog(
|
||||
onDismissRequest = { about = false },
|
||||
title = { Text("Components") },
|
||||
text = {
|
||||
Text(
|
||||
"FEX, DXVK and VKD3D-Proton for each Proton the Steam client runs games with.\n\n" +
|
||||
"Tap an installed row to swap it in; it applies the next time a game starts. If a game is running on that Proton, the swap waits until it closes.\n\n" +
|
||||
"Your choices are also checked right before every game launch: if anything changed a Proton's files (Steam's start-up tests, for one), they are put back first, and the page says \"re-applied at launch\".\n\n" +
|
||||
"Each Proton build's own files are kept as its ORIGINAL, so a Steam update never loses them. Packages come from the Nightlies \"-Linux\" releases (refresh) or Import .wcp.",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = { FocusText("OK", pal.signal) { about = false } },
|
||||
)
|
||||
confirm?.let { (body, action) ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirm = null },
|
||||
title = { Text(confirmTitle) },
|
||||
text = { Text(body, fontSize = 13.sp) },
|
||||
// Opens on Cancel, so a stray A press on a controller never swaps or deletes anything.
|
||||
confirmButton = {
|
||||
val del = confirmTitle.startsWith("Delete")
|
||||
FocusText(if (del) "Delete" else if (confirmTitle.startsWith("Restore")) "Restore" else "Swap", if (del) colors.error else pal.signal) { confirm = null; action() }
|
||||
},
|
||||
dismissButton = {
|
||||
val cancelFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { runCatching { cancelFocus.requestFocus() } }
|
||||
FocusText("Cancel", colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The pad's bumper that turns the component tabs, as a small badge beside them. */
|
||||
@Composable
|
||||
private fun BumperHint(text: String) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Text(
|
||||
text, fontSize = 10.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.5.sp, color = colors.onSurfaceVariant, maxLines = 1,
|
||||
modifier = Modifier.clip(RoundedCornerShape(5.dp)).border(1.dp, pal.line2, RoundedCornerShape(5.dp)).padding(horizontal = 5.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionLabel(text: String) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 10.dp, bottom = 4.dp)) {
|
||||
Text(text.uppercase(), fontSize = 10.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.6.sp, color = colors.onSurfaceVariant)
|
||||
Box(Modifier.weight(1f).height(1.dp).background(pal.line))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Segmented(options: List<Pair<String, String>>, selected: String, onPick: (String) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(Modifier.clip(RoundedCornerShape(9.dp)).background(colors.surfaceVariant).border(1.dp, pal.line2, RoundedCornerShape(9.dp)).padding(2.dp)) {
|
||||
for ((key, text) in options) {
|
||||
val on = key == selected
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val pick = { onPick(key) }
|
||||
Text(
|
||||
text, fontSize = 12.5.sp, fontWeight = FontWeight.Bold, maxLines = 1,
|
||||
color = if (on) Color.White else if (hot) colors.onBackground else colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(RoundedCornerShape(7.dp))
|
||||
.background(if (on) pal.signal else if (hot) pal.signal.copy(alpha = 0.18f) else Color.Transparent)
|
||||
.border(if (hot && !on) 1.dp else 0.dp, if (hot && !on) pal.signal else Color.Transparent, RoundedCornerShape(7.dp))
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = pick)
|
||||
.controllerConfirm(onClick = pick)
|
||||
.padding(horizontal = 12.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(34.dp).clip(RoundedCornerShape(9.dp))
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line2, RoundedCornerShape(9.dp))
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick),
|
||||
) {
|
||||
if (busy) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
|
||||
else Icon(icon, contentDescription = description, tint = colors.onBackground, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A small button. Resting: grey outline (blue text when [accent]). Focused or hovered: a solid blue
|
||||
* fill, white text and a white outline - unmistakable in a column of identical buttons.
|
||||
*/
|
||||
@Composable
|
||||
private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean = false, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = (src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value) && enabled
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.clip(RoundedCornerShape(8.dp))
|
||||
.background(if (hot) pal.signal else colors.surfaceVariant)
|
||||
.border(2.dp, if (hot) Color.White else pal.line2, RoundedCornerShape(8.dp))
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
) {
|
||||
Text(
|
||||
text, fontSize = 12.sp, fontWeight = FontWeight.Bold, maxLines = 1,
|
||||
color = if (!enabled) colors.onSurfaceVariant else if (hot) Color.White else if (accent) Color(0xFF5E9BFF) else colors.onBackground,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Tag(text: String) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val (fg, bg) = when (text) {
|
||||
"ORIGINAL" -> GOLD to Color(0x22F2C66D)
|
||||
"IN USE" -> Color.White to LocalPalette.current.signal
|
||||
"NEW" -> LocalPalette.current.good to Color(0x224CD37F)
|
||||
else -> colors.onSurfaceVariant to Color.White.copy(alpha = 0.07f)
|
||||
}
|
||||
Text(
|
||||
text, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.8.sp, color = fg, maxLines = 1,
|
||||
modifier = Modifier.clip(RoundedCornerShape(4.dp)).background(bg).padding(horizontal = 5.dp, vertical = 1.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InstalledLine(item: InstalledItem, modifier: Modifier = Modifier, onSelect: () -> Unit, onDelete: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = ROW_HEIGHT).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.14f) else if (item.selected) pal.signal.copy(alpha = 0.08f) else Color.Transparent)
|
||||
.border(2.dp, if (hot) pal.signal else Color.Transparent, shape),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.weight(1f).heightIn(min = ROW_HEIGHT).then(modifier)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect)
|
||||
.controllerConfirm(onClick = onSelect)
|
||||
.padding(horizontal = 10.dp),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(16.dp).border(2.dp, if (item.selected) pal.signal else colors.onSurfaceVariant, CircleShape)) {
|
||||
if (item.selected) Box(Modifier.size(7.dp).background(pal.signal, CircleShape))
|
||||
}
|
||||
Text(
|
||||
item.name, fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = if (item.selected) Color(0xFF5E9BFF) else colors.onBackground, modifier = Modifier.weight(1f),
|
||||
)
|
||||
Box(Modifier.width(72.dp)) { Tag(item.tag) }
|
||||
Text(item.detail, fontSize = 11.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.width(DETAIL_WIDTH))
|
||||
Box(Modifier.width(56.dp), contentAlignment = Alignment.CenterEnd) { if (item.selected) Tag("IN USE") }
|
||||
}
|
||||
// The trash column is always there (empty when the row can't be deleted) so rows line up.
|
||||
if (!item.removable) Spacer(Modifier.padding(end = 4.dp).size(32.dp))
|
||||
else {
|
||||
val delSrc = remember { MutableInteractionSource() }
|
||||
val delHot = delSrc.collectIsFocusedAsState().value || delSrc.collectIsHoveredAsState().value
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.padding(end = 4.dp).size(32.dp).clip(RoundedCornerShape(8.dp))
|
||||
.border(2.dp, if (delHot) colors.error else Color.Transparent, RoundedCornerShape(8.dp))
|
||||
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete)
|
||||
.controllerConfirm(onClick = onDelete),
|
||||
) { Icon(Icons.Outlined.Delete, contentDescription = "Delete", tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(17.dp)) }
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 8.dp).height(1.dp).background(pal.line.copy(alpha = 0.5f)))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AvailableLine(d: CatalogItem, progress: Int?, enabled: Boolean, onDownload: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = ROW_HEIGHT).padding(horizontal = 10.dp),
|
||||
) {
|
||||
// Fixed columns so every row's details and button line up: name | details | button.
|
||||
Tag("NEW")
|
||||
Text(d.file.removeSuffix(".wcp"), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text("${d.release} · " + String.format("%.1f MB", d.size / 1048576.0), fontSize = 11.5.sp, color = colors.onSurfaceVariant,
|
||||
fontFamily = FontFamily.Default, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.width(DETAIL_WIDTH))
|
||||
if (progress == null) SmallButton("Download", enabled = enabled, accent = true, modifier = Modifier.width(ACTION_WIDTH), onClick = onDownload)
|
||||
else Column(horizontalAlignment = Alignment.End, modifier = Modifier.width(ACTION_WIDTH)) {
|
||||
Text(if (progress < 0) "…" else "$progress%", fontSize = 11.sp, color = colors.onSurfaceVariant)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
if (progress < 0) LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
else LinearProgressIndicator(progress = { progress / 100f }, modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 8.dp).height(1.dp).background(pal.line.copy(alpha = 0.5f)))
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
class ControllerActions(
|
||||
val onOsc: (String) -> Unit,
|
||||
val onTint: (Int) -> Unit,
|
||||
val onOpacity: (Int) -> Unit,
|
||||
val onSize: (Int) -> Unit,
|
||||
val onStickClick: (Boolean) -> Unit,
|
||||
val onAdaptiveSticks: (Boolean) -> Unit,
|
||||
val onEditLayout: () -> Unit,
|
||||
val onResetLayout: () -> Unit,
|
||||
val onMapping: () -> Unit,
|
||||
val onResetAll: () -> Unit,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun Swatch(color: Int) {
|
||||
Box(Modifier.size(14.dp).background(Color(color), CircleShape).border(1.dp, Color.White.copy(alpha = 0.35f), CircleShape))
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPrefs.Settings, a: ControllerActions) {
|
||||
ChoiceRow(
|
||||
host, "controller-osc", "On-screen controls", "When the touch pad appears in a session",
|
||||
listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never"),
|
||||
oscMode, note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc,
|
||||
)
|
||||
val tintOpen = host.open == "controller-tint"
|
||||
SettingsRow("Colour", "Tint of the on-screen buttons", highlighted = tintOpen) {
|
||||
Box {
|
||||
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second ?: "Custom", tintOpen) {
|
||||
host.open = if (tintOpen) null else "controller-tint"
|
||||
}
|
||||
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = "Colour") { firstItemFocus ->
|
||||
ControllerPrefs.tints.forEachIndexed { index, (color, name) ->
|
||||
MenuItem(name, checked = c.tint == color, leading = { Swatch(color) }, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
a.onTint(color)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ChoiceRow(host, "controller-opacity", "Opacity", null, ControllerPrefs.opacities.map { it to "$it%" }, c.opacity, onPick = a.onOpacity)
|
||||
ChoiceRow(host, "controller-size", "Button size", "100% keeps the standard size", ControllerPrefs.sizes.map { it to "$it%" }, c.size, onPick = a.onSize)
|
||||
ToggleRow(host, "controller-stick-click", "Stick click", "Double-tap a stick and hold for L3 or R3", c.stickClick, onChange = a.onStickClick)
|
||||
ToggleRow(host, "controller-adaptive", "Adaptive sticks", "A stick centres where your thumb lands and returns home when you let go", c.adaptiveSticks, onChange = a.onAdaptiveSticks)
|
||||
SettingsRow("Layout", if (c.customLayout) "Custom positions saved" else "Placed for this screen's size and your grip") {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
SecondaryButton("Edit") { a.onEditLayout() }
|
||||
SecondaryButton("Reset", enabled = c.customLayout) { a.onResetLayout() }
|
||||
}
|
||||
}
|
||||
val remapped = c.mapping.count { (id, target) -> id != target }
|
||||
ActionRow("Button mapping", if (remapped == 0) "Every button sends its own input" else "$remapped of ${c.mapping.size} buttons remapped", "Configure", a.onMapping)
|
||||
ActionRow("Reset controller", "Restore the default colour, opacity, size, stick behaviour, mapping and layout", "Reset", a.onResetAll)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ControllerMappingPage(mapping: Map<String, String>, onPick: (String, String) -> Unit, onReset: () -> Unit, onBack: () -> Unit) {
|
||||
val host = rememberMenuHost()
|
||||
SettingsPage(
|
||||
host, title = "Button mapping", eyebrow = "Controller",
|
||||
lede = "Choose what each on-screen button sends to the game. Hidden removes the button.",
|
||||
onBack = onBack,
|
||||
) {
|
||||
SettingsGroup("On-screen buttons") {
|
||||
for ((id, name) in ControllerPrefs.mappable) {
|
||||
ChoiceRow(host, "map-$id", name, null, ControllerPrefs.targets, mapping[id] ?: id) { onPick(id, it) }
|
||||
}
|
||||
}
|
||||
SettingsGroup("Defaults") {
|
||||
ActionRow("Reset mapping", "Every button sends its own input again", "Reset", onReset)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,35 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.FilterQuality
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
|
||||
/**
|
||||
* The session's pointer. [image]: the program's own cursor (wl_pointer.set_cursor - labwc's resize
|
||||
* arrows, a text field's I-beam), in session pixels, drawn [imageScale] times larger with its hotspot
|
||||
* ([hotX], [hotY]) on [position]; null = the program has not set one, and the built-in arrow is drawn.
|
||||
*/
|
||||
@Composable
|
||||
fun CursorOverlay(position: Offset, visible: Boolean, scale: Float) {
|
||||
fun CursorOverlay(
|
||||
position: Offset, visible: Boolean, scale: Float,
|
||||
image: ImageBitmap? = null, hotX: Int = 0, hotY: Int = 0, imageScale: Float = 1f,
|
||||
) {
|
||||
if (!visible) return
|
||||
Canvas(modifier = Modifier.fillMaxSize()) {
|
||||
if (image != null) {
|
||||
val w = (image.width * imageScale).toInt().coerceAtLeast(1)
|
||||
val h = (image.height * imageScale).toInt().coerceAtLeast(1)
|
||||
drawImage(
|
||||
image,
|
||||
dstOffset = androidx.compose.ui.unit.IntOffset(
|
||||
(position.x - hotX * imageScale).toInt(), (position.y - hotY * imageScale).toInt()),
|
||||
dstSize = androidx.compose.ui.unit.IntSize(w, h),
|
||||
filterQuality = FilterQuality.Low,
|
||||
)
|
||||
return@Canvas
|
||||
}
|
||||
val s = 11f * scale
|
||||
val path = Path().apply {
|
||||
moveTo(position.x, position.y)
|
||||
|
||||
@@ -221,7 +221,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
|
||||
|
||||
/** A text button that shows where controller focus is: an outline in its own colour. */
|
||||
@Composable
|
||||
private fun FocusText(text: String, color: Color, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
|
||||
@@ -12,6 +12,34 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
|
||||
@Composable
|
||||
fun ChooseAppDisplayDialog(
|
||||
app: HomeApp.LaunchableApp,
|
||||
secondaryDisplay: SecondScreenDisplay?,
|
||||
onPrimary: () -> Unit,
|
||||
onSecondary: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Launch ${app.label}") },
|
||||
text = {
|
||||
Text(
|
||||
secondaryDisplay?.let { "Choose a screen. Secondary: ${it.label}." }
|
||||
?: "The secondary display is no longer available.",
|
||||
)
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onPrimary) { Text("Primary screen") } },
|
||||
dismissButton = {
|
||||
TextButton(onClick = onSecondary, enabled = secondaryDisplay != null) {
|
||||
Text("Secondary screen")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -15,6 +21,7 @@ import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.core.FexPreset
|
||||
import com.droiddeck.launcher.runtime.DeckyManager
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
|
||||
@@ -46,6 +53,8 @@ class ModeSettings(
|
||||
val suspendPolicy: String,
|
||||
/** Steam only. */
|
||||
val oscMode: String?,
|
||||
/** Steam only: whether single and double Back actions are swapped. */
|
||||
val backActionsInverted: Boolean = false,
|
||||
val directAudio: Boolean?,
|
||||
val clientDirectAudio: Boolean = false,
|
||||
val mic: Boolean?,
|
||||
@@ -53,10 +62,11 @@ class ModeSettings(
|
||||
val gameStorage: String? = null,
|
||||
val storageOptions: List<Pair<String, String>> = emptyList(),
|
||||
val fexPreset: String? = null,
|
||||
/** Steam only: games are stretched to fill the screen (null = not a Steam page). */
|
||||
val forceFullscreen: Boolean? = null,
|
||||
/** Steam only: the client branch forced on the command line. */
|
||||
val steamChannel: String? = null,
|
||||
/** Steam only: the user's own games folder and what was found in it. */
|
||||
/** The chosen Games folders (null = not a Steam page). */
|
||||
/** Steam only: the user's chosen Games folders; null outside Steam. */
|
||||
val addedGamesDirs: List<String>? = null,
|
||||
val addedGames: List<AddedGameRow> = emptyList(),
|
||||
val addedGamesArt: Boolean = true,
|
||||
@@ -67,6 +77,14 @@ class ModeSettings(
|
||||
val releaseChecking: Boolean = false,
|
||||
/** A bundled display driver was deleted: the page offers to restore it. */
|
||||
val canRestoreBundled: Boolean = false,
|
||||
/** Steam only: Decky Loader is managed from the Steam session settings. */
|
||||
val deckyInstalled: String? = null,
|
||||
val deckyLatestRelease: DeckyManager.Release? = null,
|
||||
val deckyChecking: Boolean = false,
|
||||
val deckyStage: String? = null,
|
||||
val deckyPercent: Int = -1,
|
||||
val deckyEnabled: Boolean = false,
|
||||
val deckySessionRunning: Boolean = false,
|
||||
)
|
||||
|
||||
/** One added game as the settings page shows it: its folder, the chosen .exe, the other .exe files it could be. */
|
||||
@@ -91,6 +109,7 @@ class ModeSettingsActions(
|
||||
val onTouch: (String) -> Unit,
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onOsc: (String) -> Unit,
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onDirectAudio: (Boolean) -> Unit,
|
||||
val onClientDirectAudio: (Boolean) -> Unit = {},
|
||||
val onMic: (Boolean) -> Unit,
|
||||
@@ -98,12 +117,17 @@ class ModeSettingsActions(
|
||||
val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> },
|
||||
val onPickGameStorageFolder: () -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit = {},
|
||||
val onForceFullscreen: (Boolean) -> Unit = {},
|
||||
val onSteamChannel: (String) -> Unit = {},
|
||||
val onPickAddedGamesDir: () -> Unit = {},
|
||||
val onForgetAddedGamesDir: (path: String) -> Unit = {},
|
||||
val onAddedGamesArt: (Boolean) -> Unit = {},
|
||||
val onAddedGameExe: (folderPath: String, path: String) -> Unit = { _, _ -> },
|
||||
val onPickAddedGameExe: (folderPath: String) -> Unit = {},
|
||||
val onDeckyInstall: (DeckyManager.Release) -> Unit = {},
|
||||
val onDeckyCheck: () -> Unit = {},
|
||||
val onDeckyEnabled: (Boolean) -> Unit = {},
|
||||
val onDeckyUninstall: () -> Unit = {},
|
||||
val onDismiss: () -> Unit,
|
||||
)
|
||||
|
||||
@@ -111,6 +135,7 @@ class ModeSettingsActions(
|
||||
fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
val steam = s.mode == SessionService.MODE_STEAM
|
||||
val host = rememberMenuHost()
|
||||
var confirmDeckyRemoval by remember { mutableStateOf(false) }
|
||||
// The two driver lists open as full pages over this one ("rt" = runtime, "panel" = display).
|
||||
// Coming back restores this page as it was left: the same scroll position, and controller focus
|
||||
// on the driver box that opened the page.
|
||||
@@ -177,8 +202,8 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
onPick = { v -> if (v == CUSTOM) editCustom = true else { a.onCustomResolution(null); a.onResolution(v) } },
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "shape", "Shape",
|
||||
if (custom != null) "Set by the custom resolution." else "The panel's shape stays at 16:9 or wider; pick Exactly this panel for a 4:3 or 3:2 screen.",
|
||||
host, "shape", "Screen ratio",
|
||||
if (custom != null) "Set by the custom resolution." else "Auto uses at least 16:9.",
|
||||
com.droiddeck.launcher.session.SessionPrefs.shapeChoices, s.shapeMode, enabled = custom == null, onPick = a.onShape,
|
||||
)
|
||||
if (editCustom) CustomResolutionDialog(
|
||||
@@ -226,6 +251,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
), s.oscMode,
|
||||
note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc,
|
||||
)
|
||||
if (steam) ChoiceRow(
|
||||
host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted),
|
||||
listOf(
|
||||
false to SessionPrefs.BACK_MENU_THEN_QAM,
|
||||
true to SessionPrefs.BACK_QAM_THEN_MENU,
|
||||
), s.backActionsInverted, onPick = a.onBackActionsInverted,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Session") {
|
||||
ChoiceRow(
|
||||
@@ -241,6 +273,58 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
onPick = a.onSuspendPolicy,
|
||||
)
|
||||
}
|
||||
if (steam) SettingsGroup("Decky") {
|
||||
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
|
||||
s.deckyInstalled != s.deckyLatestRelease.tag
|
||||
val status = when {
|
||||
s.deckyStage != null -> s.deckyStage
|
||||
s.deckyChecking -> "Checking compatible releases…"
|
||||
s.deckyInstalled == null && s.deckyLatestRelease != null -> "Ready to install ${s.deckyLatestRelease.tag}."
|
||||
s.deckyInstalled == null -> "No compatible build found. Check again later."
|
||||
s.deckyLatestRelease == null -> "Installed · ${s.deckyInstalled}"
|
||||
updateAvailable -> "Update available · ${s.deckyLatestRelease.tag}"
|
||||
else -> "Up to date · ${s.deckyInstalled}"
|
||||
}
|
||||
SettingsRow("Loader", status) {
|
||||
val action = when {
|
||||
s.deckyStage != null -> "Working…"
|
||||
s.deckyChecking -> "Checking…"
|
||||
s.deckyInstalled == null && s.deckyLatestRelease != null -> "Install latest"
|
||||
s.deckyInstalled != null && updateAvailable -> "Update"
|
||||
else -> "Check"
|
||||
}
|
||||
Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) {
|
||||
SecondaryButton(
|
||||
action,
|
||||
enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning,
|
||||
) {
|
||||
if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck()
|
||||
else s.deckyLatestRelease?.let(a.onDeckyInstall)
|
||||
}
|
||||
if (s.deckyInstalled != null) SecondaryButton(
|
||||
"Uninstall",
|
||||
enabled = s.deckyStage == null && !s.deckySessionRunning,
|
||||
) { confirmDeckyRemoval = true }
|
||||
}
|
||||
}
|
||||
if (s.deckyInstalled != null) SettingsRow(
|
||||
"Decky",
|
||||
if (s.deckyEnabled) "Starts with Steam. Other apps on this device may be able to control Steam while enabled."
|
||||
else "Off. Decky stays off and Steam's remote debugging port stays closed.",
|
||||
) {
|
||||
Switch(
|
||||
checked = s.deckyEnabled,
|
||||
onCheckedChange = a.onDeckyEnabled,
|
||||
enabled = !s.deckySessionRunning && s.deckyStage == null,
|
||||
)
|
||||
}
|
||||
if (s.deckyStage != null && s.deckyPercent >= 0) {
|
||||
LinearProgressIndicator(
|
||||
progress = { s.deckyPercent / 100f },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (steam && s.steamChannel != null) SettingsGroup("Client") {
|
||||
ChoiceRow(
|
||||
host, "channel", "Client branch", "The Steam client build the session forces. Applies at the next session start; the client may update itself once.",
|
||||
@@ -280,6 +364,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
FexPreset.all.map { it.id to it.label }, s.fexPreset,
|
||||
note = FexPreset.byId(s.fexPreset).detail, onPick = a.onFexPreset,
|
||||
)
|
||||
if (s.forceFullscreen != null) ToggleRow(
|
||||
host, "fill", "Stretch games to fill the screen",
|
||||
"Keeps games that resize their own window (FlatOut) full screen. Turn it off if a game shows up small in a corner (Quake 3). Applies next session.",
|
||||
s.forceFullscreen, onChange = a.onForceFullscreen,
|
||||
)
|
||||
}
|
||||
if (steam && s.directAudio != null && s.mic != null) SettingsGroup("Audio") {
|
||||
ToggleRow(host, "da", "DirectAudio for games", "Bypasses PulseAudio for lower latency in games.", s.directAudio, onChange = a.onDirectAudio)
|
||||
@@ -309,10 +398,12 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
AnchoredMenu(
|
||||
open, onDismiss = { if (host.open == "storage") host.open = null }, title = "Second library",
|
||||
note = "Games that stream assets from SD or shared storage may stutter. Keep them internal.",
|
||||
) {
|
||||
for ((path, label) in options) MenuItem(label, checked = path == s.gameStorage) {
|
||||
a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·"))
|
||||
host.open = null
|
||||
) { firstItemFocus ->
|
||||
options.forEachIndexed { index, (path, label) ->
|
||||
MenuItem(label, checked = path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·"))
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
MenuItem("Choose a folder…", checked = false) { host.open = null; a.onPickGameStorageFolder() }
|
||||
}
|
||||
@@ -322,11 +413,23 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
if (!steam && s.renderer != null) SettingsGroup("Renderer") {
|
||||
ChoiceRow(
|
||||
host, "renderer", "Desktop renderer", "Composites the desktop.",
|
||||
listOf("pixman" to "pixman - software", "gles2" to "gles2", "vulkan" to "vulkan"), s.renderer,
|
||||
note = "GLES2 and Vulkan require a DRM render node, unavailable on most devices.", onPick = a.onRenderer,
|
||||
listOf("vulkan" to "vulkan - GPU", "gles2" to "gles2 - GPU (experimental)", "pixman" to "pixman - software"), s.renderer,
|
||||
note = "On Vulkan, programs on the desktop draw with the GPU in their own windows; if it cannot start, " +
|
||||
"the desktop comes up on pixman. On pixman, games and emulators from the menu open full screen " +
|
||||
"on the GPU instead (right-click one for a desktop window).",
|
||||
onPick = a.onRenderer,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (confirmDeckyRemoval) AlertDialog(
|
||||
onDismissRequest = { confirmDeckyRemoval = false },
|
||||
title = { Text("Uninstall Decky Loader?") },
|
||||
text = { Text("Remove the loader and keep your plugins and settings.") },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { confirmDeckyRemoval = false; a.onDeckyUninstall() }) { Text("Uninstall") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmDeckyRemoval = false }) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
|
||||
/** The Resolution menu's "Custom…" entry. */
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.foundation.gestures.waitForUpOrCancellation
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
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.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.key.nativeKeyCode
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* A PC keyboard on screen: every key is a physical key (a Linux evdev code) pressed and released
|
||||
* on the session's wl_keyboard, as a USB keyboard would - Esc, the function row, Ctrl, Alt, Super,
|
||||
* the arrows and the editing block included, none of which the Android keyboard can send.
|
||||
*
|
||||
* A key goes down when a finger lands on it and up when it lifts, so holding one repeats it the way
|
||||
* the program's own key repeat does. Ctrl, Shift, Alt and Super are sticky: one tap holds the
|
||||
* modifier for the next key, a second tap locks it, a third lets it go. A controller moves over the
|
||||
* keys with the d-pad and presses with A.
|
||||
*/
|
||||
private data class PcKey(val label: String, val code: Int, val weight: Float = 1f, val shifted: String? = null)
|
||||
|
||||
private fun k(label: String, code: Int, weight: Float = 1f, shifted: String? = null) = PcKey(label, code, weight, shifted)
|
||||
|
||||
private val ROWS: List<List<PcKey>> = listOf(
|
||||
listOf(
|
||||
k("Esc", 1), k("F1", 59), k("F2", 60), k("F3", 61), k("F4", 62), k("F5", 63), k("F6", 64),
|
||||
k("F7", 65), k("F8", 66), k("F9", 67), k("F10", 68), k("F11", 87), k("F12", 88),
|
||||
k("Ins", 110), k("Del", 111), k("Home", 102), k("End", 107), k("PgUp", 104), k("PgDn", 109),
|
||||
),
|
||||
listOf(
|
||||
k("`", 41, shifted = "~"), k("1", 2, shifted = "!"), k("2", 3, shifted = "@"), k("3", 4, shifted = "#"),
|
||||
k("4", 5, shifted = "$"), k("5", 6, shifted = "%"), k("6", 7, shifted = "^"), k("7", 8, shifted = "&"),
|
||||
k("8", 9, shifted = "*"), k("9", 10, shifted = "("), k("0", 11, shifted = ")"), k("-", 12, shifted = "_"),
|
||||
k("=", 13, shifted = "+"), k("⌫ Backspace", 14, 2f),
|
||||
),
|
||||
listOf(
|
||||
k("Tab ⇥", 15, 1.5f), k("q", 16), k("w", 17), k("e", 18), k("r", 19), k("t", 20), k("y", 21),
|
||||
k("u", 22), k("i", 23), k("o", 24), k("p", 25), k("[", 26, shifted = "{"), k("]", 27, shifted = "}"),
|
||||
k("\\", 43, 1.5f, shifted = "|"),
|
||||
),
|
||||
listOf(
|
||||
k("Caps", 58, 1.75f), k("a", 30), k("s", 31), k("d", 32), k("f", 33), k("g", 34), k("h", 35),
|
||||
k("j", 36), k("k", 37), k("l", 38), k(";", 39, shifted = ":"), k("'", 40, shifted = "\""),
|
||||
k("Enter ⏎", 28, 2.25f),
|
||||
),
|
||||
listOf(
|
||||
k("⇧ Shift", 42, 2.25f), k("z", 44), k("x", 45), k("c", 46), k("v", 47), k("b", 48), k("n", 49),
|
||||
k("m", 50), k(",", 51, shifted = "<"), k(".", 52, shifted = ">"), k("/", 53, shifted = "?"),
|
||||
k("⇧ Shift", 54, 1.75f), k("↑", 103),
|
||||
),
|
||||
listOf(
|
||||
k("Ctrl", 29, 1.5f), k("Super", 125, 1.25f), k("Alt", 56, 1.25f), k("Space", 57, 6.25f),
|
||||
k("AltGr", 100, 1.25f), k("Ctrl", 97, 1.25f), k("←", 105), k("↓", 108), k("→", 106),
|
||||
),
|
||||
)
|
||||
|
||||
private val MODIFIERS = setOf(42, 54, 29, 97, 56, 100, 125)
|
||||
private const val MOD_OFF = 0
|
||||
private const val MOD_ONCE = 1
|
||||
private const val MOD_LOCKED = 2
|
||||
|
||||
@Composable
|
||||
fun PcKeyboard(
|
||||
/** evdev code, pressed. */
|
||||
sendKey: (Int, Boolean) -> Unit,
|
||||
onAndroidKeyboard: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val mods = remember { mutableStateMapOf<Int, Int>() }
|
||||
var capsOn by remember { mutableStateOf(false) }
|
||||
val firstKey = remember { FocusRequester() }
|
||||
val shifted = (mods[42] ?: MOD_OFF) != MOD_OFF || (mods[54] ?: MOD_OFF) != MOD_OFF
|
||||
|
||||
fun releaseOnceModifiers() {
|
||||
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { sendKey(code, false); mods[code] = MOD_OFF }
|
||||
}
|
||||
fun press(key: PcKey) {
|
||||
if (key.code in MODIFIERS) {
|
||||
when (mods[key.code] ?: MOD_OFF) {
|
||||
MOD_OFF -> { sendKey(key.code, true); mods[key.code] = MOD_ONCE }
|
||||
MOD_ONCE -> mods[key.code] = MOD_LOCKED
|
||||
else -> { sendKey(key.code, false); mods[key.code] = MOD_OFF }
|
||||
}
|
||||
return
|
||||
}
|
||||
sendKey(key.code, true)
|
||||
}
|
||||
fun release(key: PcKey) {
|
||||
if (key.code in MODIFIERS) return
|
||||
sendKey(key.code, false)
|
||||
if (key.code == 58) capsOn = !capsOn
|
||||
releaseOnceModifiers()
|
||||
}
|
||||
// Nothing is left held when the keyboard goes away.
|
||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||
onDispose { for ((code, state) in mods.toMap()) if (state != MOD_OFF) sendKey(code, false) }
|
||||
}
|
||||
LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } }
|
||||
|
||||
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
|
||||
// Slightly under half the screen, header included, so the program stays in view above it:
|
||||
// six rows share what is left of 47% after the header, the gaps and the padding.
|
||||
val rowHeight = ((maxHeight * 0.47f - 24.dp - 3.dp * 6 - 10.dp) / 6).coerceIn(24.dp, 44.dp)
|
||||
Box(
|
||||
Modifier.fillMaxWidth()
|
||||
.background(Color(0xE6101418), RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp))
|
||||
.border(1.dp, pal.line2, RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp))
|
||||
// Touches on the keyboard stop here; the program underneath never sees them.
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); waitForUpOrCancellation()?.consume() } }
|
||||
.padding(horizontal = 8.dp, vertical = 5.dp),
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(24.dp)) {
|
||||
Text("PC keyboard", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant)
|
||||
Spacer(Modifier.weight(1f))
|
||||
HeaderButton("Android keyboard", onAndroidKeyboard)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
HeaderButton("Hide ✕", onClose)
|
||||
}
|
||||
ROWS.forEachIndexed { r, row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) {
|
||||
row.forEachIndexed { i, key ->
|
||||
val state = mods[key.code] ?: MOD_OFF
|
||||
val lit = state != MOD_OFF || (key.code == 58 && capsOn)
|
||||
val label = when {
|
||||
shifted && key.shifted != null -> key.shifted
|
||||
key.label.length == 1 && key.label[0].isLetter() && (shifted xor capsOn) -> key.label.uppercase()
|
||||
else -> key.label
|
||||
}
|
||||
KeyCap(
|
||||
label, key.weight, lit, locked = state == MOD_LOCKED,
|
||||
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
|
||||
onDown = { press(key) }, onUp = { release(key) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RowScope.KeyCap(
|
||||
label: String, weight: Float, lit: Boolean, locked: Boolean,
|
||||
modifier: Modifier, onDown: () -> Unit, onUp: () -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val focused by src.collectIsFocusedAsState()
|
||||
var down by remember { mutableStateOf(false) }
|
||||
val fill by animateColorAsState(
|
||||
when {
|
||||
down -> pal.signal.copy(alpha = 0.55f)
|
||||
lit -> pal.signal.copy(alpha = if (locked) 0.45f else 0.28f)
|
||||
else -> Color.White.copy(alpha = 0.07f)
|
||||
}, label = "keyFill",
|
||||
)
|
||||
val edge = if (focused) pal.signal else if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.weight(weight).fillMaxHeight()
|
||||
.background(fill, RoundedCornerShape(7.dp))
|
||||
.border(if (focused) 2.dp else 1.dp, edge, RoundedCornerShape(7.dp))
|
||||
.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
awaitFirstDown().consume()
|
||||
down = true; onDown()
|
||||
waitForUpOrCancellation()?.consume()
|
||||
down = false; onUp()
|
||||
}
|
||||
}
|
||||
// A controller: A (or the d-pad's centre) is the finger.
|
||||
.onPreviewKeyEvent { e ->
|
||||
val kc = e.key.nativeKeyCode
|
||||
if (kc != KeyEvent.KEYCODE_BUTTON_A && kc != KeyEvent.KEYCODE_DPAD_CENTER && kc != KeyEvent.KEYCODE_ENTER) return@onPreviewKeyEvent false
|
||||
when (e.type) {
|
||||
KeyEventType.KeyDown -> if (!down) { down = true; onDown() }
|
||||
KeyEventType.KeyUp -> if (down) { down = false; onUp() }
|
||||
}
|
||||
true
|
||||
}
|
||||
.focusable(interactionSource = src),
|
||||
) {
|
||||
Text(
|
||||
label, fontSize = if (label.length > 2) 11.sp else 15.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = Color.White, textAlign = TextAlign.Center, maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HeaderButton(text: String, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val focused by src.collectIsFocusedAsState()
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxHeight()
|
||||
.background(Color.White.copy(alpha = 0.08f), RoundedCornerShape(7.dp))
|
||||
.border(if (focused) 2.dp else 1.dp, if (focused) pal.signal else Color.White.copy(alpha = 0.14f), RoundedCornerShape(7.dp))
|
||||
.clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.padding(horizontal = 12.dp),
|
||||
) { Text(text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = Color.White) }
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
|
||||
@Composable
|
||||
fun PhantomProcessGatePage(
|
||||
status: PhantomProcessStatus,
|
||||
onDismiss: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onSetUpWirelessAdb: () -> Unit,
|
||||
) {
|
||||
BackHandler(onBack = onDismiss)
|
||||
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val compact = maxWidth < 620.dp && maxHeight < 500.dp
|
||||
SettingsPage(
|
||||
host = rememberMenuHost(),
|
||||
title = if (compact) "Steam paused" else "Steam cannot start yet",
|
||||
eyebrow = "Steam",
|
||||
lede = if (compact) compactStatus(status) else "${PhantomProcessLimit.title(status)} · checking again every two seconds",
|
||||
onBack = onDismiss,
|
||||
scrollContent = false,
|
||||
compactLayout = compact,
|
||||
) {
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val wide = maxWidth >= 620.dp
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
when {
|
||||
compact -> CompactGateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
|
||||
wide -> Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
|
||||
}
|
||||
Column(Modifier.weight(1f)) { AdbFallback() }
|
||||
}
|
||||
else -> {
|
||||
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
|
||||
AdbFallback()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun compactStatus(status: PhantomProcessStatus): String {
|
||||
val state = when (status) {
|
||||
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
|
||||
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
|
||||
PhantomProcessStatus.UNREADABLE -> "Child-process limit is unreadable"
|
||||
else -> PhantomProcessLimit.title(status)
|
||||
}
|
||||
return "$state · retrying every 2 sec"
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CompactGateInstructions(
|
||||
status: PhantomProcessStatus,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onSetUpWirelessAdb: () -> Unit,
|
||||
) {
|
||||
SettingsGroup("1 · Developer options", compact = true) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 7.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(5.dp),
|
||||
) {
|
||||
Text(
|
||||
PhantomProcessLimit.gateInstructions(status),
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
|
||||
SecondaryButton("Use on-device ADB", compact = true, onClick = onSetUpWirelessAdb)
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsGroup("3 · Computer ADB last resort", compact = true) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
Text(
|
||||
"If the setting is missing and Wireless debugging is unavailable, run this from a computer:",
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontSize = 11.sp),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
PhantomProcessLimit.ADB_COMMAND,
|
||||
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace, fontSize = 9.sp),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GateInstructions(
|
||||
status: PhantomProcessStatus,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onSetUpWirelessAdb: () -> Unit,
|
||||
) {
|
||||
SettingsGroup("1 · Developer options first") {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
PhantomProcessLimit.gateInstructions(status),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions)
|
||||
SecondaryButton("Use on-device ADB", onClick = onSetUpWirelessAdb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AdbFallback() {
|
||||
SettingsGroup("3 · Computer ADB last resort") {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
"Use this only if Developer options has no setting and Wireless debugging is unavailable. Connect this device to a computer with ADB and run:",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Text(
|
||||
PhantomProcessLimit.ADB_COMMAND,
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun DeveloperDisplayChoiceDialog(
|
||||
displays: List<Pair<Int, String>>,
|
||||
onMainScreen: () -> Unit,
|
||||
onSecondaryScreen: (Int) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Open Developer options") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Choose which display to open Android Settings on.")
|
||||
TextButton(modifier = Modifier.fillMaxWidth(), onClick = onMainScreen) { Text("Main screen") }
|
||||
displays.forEach { (id, label) ->
|
||||
TextButton(modifier = Modifier.fillMaxWidth(), onClick = { onSecondaryScreen(id) }) { Text(label) }
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
@@ -44,6 +44,7 @@ class SecondScreenPresentation(
|
||||
private val sendWheel: (steps: Int) -> Unit,
|
||||
private val onSteamMenu: () -> Unit,
|
||||
private val onQam: () -> Unit,
|
||||
private val onClose: () -> Unit,
|
||||
) : Presentation(sessionActivity, display) {
|
||||
private val root = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
@@ -124,6 +125,12 @@ class SecondScreenPresentation(
|
||||
setPadding(dp(12), dp(8), dp(12), dp(8))
|
||||
setBackgroundColor(0xE6191E24.toInt())
|
||||
}
|
||||
controls.addView(Button(context).apply {
|
||||
text = "×"
|
||||
contentDescription = "Close second-screen controls"
|
||||
minWidth = dp(48)
|
||||
setOnClickListener { onClose() }
|
||||
})
|
||||
controls.addView(TextView(context).apply {
|
||||
text = "Trackpad"
|
||||
textSize = 14f
|
||||
@@ -169,6 +176,12 @@ class SecondScreenPresentation(
|
||||
setPadding(dp(8), dp(4), dp(8), dp(4))
|
||||
setBackgroundColor(Color.rgb(27, 32, 38))
|
||||
}
|
||||
bar.addView(Button(context).apply {
|
||||
text = "×"
|
||||
contentDescription = "Close second-screen controls"
|
||||
minWidth = dp(48)
|
||||
setOnClickListener { onClose() }
|
||||
})
|
||||
bar.addView(TextView(context).apply {
|
||||
text = "Linux terminal"
|
||||
textSize = 14f
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||
import androidx.compose.material.icons.outlined.Layers
|
||||
import androidx.compose.material.icons.outlined.Settings
|
||||
import androidx.compose.material.icons.outlined.SportsEsports
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import android.view.Display
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.interaction.PressInteraction
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
@@ -20,16 +33,18 @@ 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.ScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
@@ -50,6 +65,7 @@ import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
@@ -62,18 +78,51 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import com.droiddeck.launcher.core.FexPreset
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import kotlinx.coroutines.flow.collect
|
||||
|
||||
private val drawerPageTitles = listOf("Display", "Controls", "Components", "Settings")
|
||||
/** One icon per drawer page, in page order (QAM-style tabs). */
|
||||
private val drawerPageIcons = listOf(Icons.Outlined.DesktopWindows, Icons.Outlined.SportsEsports, Icons.Outlined.Layers, Icons.Outlined.Settings)
|
||||
private val drawerPageEntries = listOf("hud", "touch", "cmp-proton", "suspend")
|
||||
|
||||
private class DrawerFocus {
|
||||
private val requesters = HashMap<String, FocusRequester>()
|
||||
private val last = arrayOfNulls<String>(DRAWER_PAGES)
|
||||
var focused by mutableStateOf<String?>(null)
|
||||
private set
|
||||
|
||||
private fun requester(key: String) = requesters.getOrPut(key) { FocusRequester() }
|
||||
|
||||
fun track(page: Int, key: String): Modifier = Modifier.focusRequester(requester(key)).onFocusChanged {
|
||||
if (it.isFocused) {
|
||||
last[page] = key
|
||||
focused = key
|
||||
} else if (focused == key) focused = null
|
||||
}
|
||||
|
||||
fun target(page: Int) = last[page] ?: drawerPageEntries[page]
|
||||
fun request(key: String) = runCatching { requester(key).requestFocus() }
|
||||
fun forget(page: Int) { last[page] = null }
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun HudText(text: String) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) {
|
||||
@@ -121,6 +170,11 @@ fun LoadingOverlay(step: String, percent: Int, elapsed: String, hint: String, en
|
||||
@Composable
|
||||
fun SessionPausedOverlay(onResume: () -> Unit) {
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val resumeFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
runCatching { resumeFocus.requestFocus() }
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
@@ -132,7 +186,10 @@ fun SessionPausedOverlay(onResume: () -> Unit) {
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
) {
|
||||
OutlinedButton(onClick = onResume) {
|
||||
OutlinedButton(
|
||||
onClick = onResume,
|
||||
modifier = Modifier.focusRequester(resumeFocus).controllerConfirm(onClick = onResume),
|
||||
) {
|
||||
Text("Resume session")
|
||||
}
|
||||
}
|
||||
@@ -142,6 +199,8 @@ fun SessionPausedOverlay(onResume: () -> Unit) {
|
||||
/** Everything the drawer shows and does. */
|
||||
class DrawerActions(
|
||||
val steam: Boolean,
|
||||
/** The drawer's heading: the emulator for a program from the rail, else Steam or Desktop. */
|
||||
val title: String? = null,
|
||||
val isHomeApp: Boolean,
|
||||
val androidApps: List<HomeApp.LaunchableApp>,
|
||||
val hudOn: Boolean,
|
||||
@@ -149,45 +208,87 @@ class DrawerActions(
|
||||
val frameGenMultiplier: Int,
|
||||
val lsfgReady: Boolean,
|
||||
val oscMode: String,
|
||||
val suspendPolicy: String,
|
||||
val backActionsInverted: Boolean,
|
||||
val touchMode: String,
|
||||
val touchAuto: String,
|
||||
val shapeMode: String,
|
||||
val fexPreset: String,
|
||||
/** Steam only: games stretched to the screen's size, changed live (null = not Steam). */
|
||||
val fillScreen: Boolean? = null,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
val onHud: (Boolean) -> Unit,
|
||||
val onFrameGenPick: (engine: String, multiplier: Int) -> Unit,
|
||||
/** The Android keyboard (text, turned into key presses). */
|
||||
val onKeyboard: () -> Unit,
|
||||
/** The on-screen PC keyboard: real keys, Esc, F1-F12, Ctrl, Alt... */
|
||||
val onHardwareKeyboard: () -> Unit,
|
||||
val onSteamMenu: (() -> Unit)?,
|
||||
val onQam: (() -> Unit)?,
|
||||
/** Steam sessions: end Big Picture and open the desktop with Steam's desktop client in it. */
|
||||
val onSwitchToDesktop: (() -> Unit)? = null,
|
||||
val onOsc: (String) -> Unit,
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onBackActionsInverted: (Boolean) -> Unit,
|
||||
val onTouch: (String) -> Unit,
|
||||
val onShape: (String) -> Unit,
|
||||
val onFexPreset: (String) -> Unit,
|
||||
val onFillScreen: (Boolean) -> Unit = {},
|
||||
val onSecondScreenMode: (SecondScreenMode) -> Unit,
|
||||
val onSecondScreenDisplay: (Int) -> Unit,
|
||||
val onLaunchAndroidApp: (HomeApp.LaunchableApp) -> Unit,
|
||||
val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit,
|
||||
val onBackground: () -> Unit,
|
||||
val onShareLogs: () -> Unit,
|
||||
val onStop: () -> Unit,
|
||||
val onClose: () -> Unit,
|
||||
/** Components tab: every Proton with what it uses; null until first read. */
|
||||
val components: ComponentsManager.Snapshot? = null,
|
||||
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
|
||||
val onComponentsRefresh: () -> Unit = {},
|
||||
/** Swaps [value] ("orig:<build>" or a stored package file) into a Proton's component. */
|
||||
val onComponentSwap: (protonId: String, comp: String, value: String) -> Unit = { _, _, _ -> },
|
||||
)
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
fun SessionDrawer(open: Boolean, a: DrawerActions) {
|
||||
fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageChange: (Int) -> Unit, a: DrawerActions) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val host = rememberMenuHost()
|
||||
var androidAppsExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
var confirmStop by remember { mutableStateOf(false) }
|
||||
val pageScroll = remember { List(DRAWER_PAGES) { ScrollState(0) } }
|
||||
val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil")
|
||||
// A controller starts on the drawer's first control, highlighted, as on the app's main screen:
|
||||
// the STEAM button, or in a desktop session the first setting.
|
||||
val firstFocus = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
val steamButtons = a.onSteamMenu != null && a.onQam != null
|
||||
LaunchedEffect(open) {
|
||||
if (open) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
runCatching { firstFocus.requestFocus() }
|
||||
val focus = remember { DrawerFocus() }
|
||||
val inputModeManager = LocalInputModeManager.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
BackHandler(enabled = open) {
|
||||
if (host.open != null) host.open = null else a.onClose()
|
||||
}
|
||||
BackHandler(enabled = open && confirmStop) { confirmStop = false }
|
||||
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
|
||||
LaunchedEffect(open, page) { if (open && page == DRAWER_PAGE_COMPONENTS) a.onComponentsRefresh() }
|
||||
LaunchedEffect(open, controllerActive) {
|
||||
if (open && !controllerActive) focusManager.clearFocus(force = true)
|
||||
}
|
||||
LaunchedEffect(open, page, controllerActive, host.open, appToChooseDisplay, confirmStop) {
|
||||
if (!open) {
|
||||
host.open = null
|
||||
confirmStop = false
|
||||
} else if (controllerActive) {
|
||||
inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||
if (host.open != null || appToChooseDisplay != null || confirmStop) return@LaunchedEffect
|
||||
val target = focus.target(page)
|
||||
repeat(24) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
focus.request(target)
|
||||
if (focus.focused == target) return@LaunchedEffect
|
||||
}
|
||||
focus.forget(page)
|
||||
focus.request(drawerPageEntries[page])
|
||||
}
|
||||
}
|
||||
if (open || veil > 0.01f) Box(
|
||||
@@ -206,13 +307,23 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) {
|
||||
.width(340.dp)
|
||||
.background(pal.background.copy(alpha = 0.97f))
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
|
||||
.verticalScroll(rememberScrollState())
|
||||
.focusGroup()
|
||||
.controllerBack {
|
||||
if (host.open != null) host.open = null else a.onClose()
|
||||
}
|
||||
.padding(horizontal = 14.dp, vertical = 16.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 4.dp, bottom = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 4.dp, bottom = 6.dp)) {
|
||||
Box(modifier = Modifier.size(10.dp).clip(CircleShape).background(Brush.linearGradient(listOf(colors.primary, pal.primary2))))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(if (a.steam) "Steam" else "Desktop", fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(a.title ?: if (a.steam) "Steam" else "Desktop", fontSize = 17.sp, fontWeight = FontWeight.Bold,
|
||||
color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
ShareSessionLogsButton(modifier = focus.track(page, "share-logs")) {
|
||||
host.open = null
|
||||
a.onShareLogs()
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
StopSessionButton(modifier = focus.track(page, "stop")) { host.open = null; confirmStop = true }
|
||||
}
|
||||
if (a.onSteamMenu != null && a.onQam != null) {
|
||||
val qamInteraction = remember { MutableInteractionSource() }
|
||||
@@ -236,12 +347,16 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) {
|
||||
OutlinedButton(
|
||||
onClick = { host.open = null; a.onSteamMenu.invoke() },
|
||||
interactionSource = steamSrc,
|
||||
modifier = Modifier.weight(1f).height(48.dp).focusRequester(firstFocus),
|
||||
modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "steam")).controllerConfirm {
|
||||
host.open = null
|
||||
a.onSteamMenu.invoke()
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
|
||||
border = BorderStroke(if (steamHot) 2.dp else 1.dp, if (steamHot) pal.signal else colors.outline),
|
||||
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (steamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
|
||||
) {
|
||||
Text("STEAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
|
||||
Text("STEAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, maxLines = 1)
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
@@ -250,127 +365,467 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) {
|
||||
qamStartedOnPress = false
|
||||
},
|
||||
interactionSource = qamInteraction,
|
||||
modifier = Modifier.weight(1f).height(48.dp).semantics { contentDescription = "Open Quick Access Menu" },
|
||||
modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "qam"))
|
||||
.semantics { contentDescription = "Open Quick Access Menu" }.controllerConfirm {
|
||||
host.open = null
|
||||
a.onQam.invoke()
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
|
||||
border = BorderStroke(if (qamHot) 2.dp else 1.dp, if (qamHot) pal.signal else colors.outline),
|
||||
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (qamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
|
||||
) {
|
||||
Text("…", fontSize = 22.sp, fontWeight = FontWeight.SemiBold)
|
||||
Text("QAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (a.isHomeApp) SettingsGroup("Android apps") {
|
||||
ActionRow("Launch an app", null, if (androidAppsExpanded) "Hide" else "Show") {
|
||||
androidAppsExpanded = !androidAppsExpanded
|
||||
}
|
||||
if (androidAppsExpanded) {
|
||||
if (a.androidApps.isEmpty()) {
|
||||
Text("No launchable apps found", fontSize = 12.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
|
||||
} else {
|
||||
for (app in a.androidApps) {
|
||||
MenuItem(
|
||||
app.label,
|
||||
checked = false,
|
||||
leading = {
|
||||
app.icon?.let { icon ->
|
||||
Image(
|
||||
bitmap = icon.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(26.dp).clip(RoundedCornerShape(6.dp)),
|
||||
)
|
||||
}
|
||||
// Big Picture's own "Switch to Desktop" waits on SteamOS Manager for ever
|
||||
// here; this does the switch without the client.
|
||||
if (a.onSwitchToDesktop != null) {
|
||||
val deskSrc = remember { MutableInteractionSource() }
|
||||
val deskHot = deskSrc.collectIsFocusedAsState().value || deskSrc.collectIsHoveredAsState().value
|
||||
OutlinedButton(
|
||||
onClick = { host.open = null; a.onSwitchToDesktop.invoke() },
|
||||
interactionSource = deskSrc,
|
||||
modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "desktop"))
|
||||
.semantics { contentDescription = "Switch to Desktop" }.controllerConfirm {
|
||||
host.open = null
|
||||
a.onSwitchToDesktop.invoke()
|
||||
},
|
||||
) { a.onLaunchAndroidApp(app) }
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
|
||||
border = BorderStroke(if (deskHot) 2.dp else 1.dp, if (deskHot) pal.signal else colors.outline),
|
||||
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (deskHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
|
||||
) {
|
||||
Text("DESKTOP", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SettingsGroup("Now") {
|
||||
ToggleRow(
|
||||
host, "hud", "Performance HUD", null, a.hudOn,
|
||||
chipModifier = if (steamButtons) Modifier else Modifier.focusRequester(firstFocus), onChange = a.onHud,
|
||||
)
|
||||
val fgOpen = host.open == "fg"
|
||||
val fgLabel = when (a.frameGenEngine) {
|
||||
FrameGen.ENGINE_WINFG -> "Win-FG ${a.frameGenMultiplier}×"
|
||||
FrameGen.ENGINE_LSFG -> "LSFG ${a.frameGenMultiplier}×"
|
||||
else -> "Off"
|
||||
}
|
||||
SettingsRow("Frame generation", null, highlighted = fgOpen) {
|
||||
Box {
|
||||
ValueChip(fgLabel, fgOpen) { host.open = if (fgOpen) null else "fg" }
|
||||
AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") {
|
||||
val need = if (a.lsfgReady) null else "install Lossless Scaling in Steam"
|
||||
MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
|
||||
for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
|
||||
for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
ChoiceRow(
|
||||
host, "touch", "Touch", null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to "Auto (${a.touchAuto})", SessionPrefs.TOUCH_PAD to "Touchpad", SessionPrefs.TOUCH_DIRECT to "Direct"), a.touchMode,
|
||||
onPick = a.onTouch,
|
||||
)
|
||||
if (a.steam) ChoiceRow(
|
||||
host, "osc", "On-screen controls", null,
|
||||
listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never"), a.oscMode,
|
||||
onPick = a.onOsc,
|
||||
)
|
||||
ActionRow("Keyboard", null, "Show") { host.open = null; a.onKeyboard() }
|
||||
}
|
||||
|
||||
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
|
||||
ChoiceRow(
|
||||
host, "second-screen-mode", "Controls", null,
|
||||
listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL)
|
||||
.map { it to it.label }, a.secondScreenMode,
|
||||
onPick = a.onSecondScreenMode,
|
||||
)
|
||||
if (a.secondScreenDisplays.size > 1) ChoiceRow(
|
||||
host, "second-screen-display", "Display", null,
|
||||
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
|
||||
onPick = a.onSecondScreenDisplay,
|
||||
)
|
||||
}
|
||||
|
||||
SettingsGroup("Next session") {
|
||||
ChoiceRow(
|
||||
host, "shape", "Display shape", null,
|
||||
SessionPrefs.shapeChoices, a.shapeMode, onPick = a.onShape,
|
||||
)
|
||||
if (a.steam) ChoiceRow(
|
||||
host, "fex", "FEX preset", null,
|
||||
FexPreset.all.map { it.id to it.label }, a.fexPreset, note = FexPreset.byId(a.fexPreset).detail, onPick = a.onFexPreset,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Row(
|
||||
horizontalArrangement = if (a.isHomeApp) Arrangement.End else Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
) {
|
||||
if (!a.isHomeApp) SecondaryButton("Send to background") { host.open = null; a.onBackground() }
|
||||
DangerButton("Stop session") { host.open = null; a.onStop() }
|
||||
DrawerOutlineButton("LB ‹", modifier = Modifier.height(48.dp).then(focus.track(page, "prev"))) {
|
||||
host.open = null; onPageChange((page + DRAWER_PAGES - 1) % DRAWER_PAGES)
|
||||
}
|
||||
DrawerPageTabs(page = page, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
|
||||
DrawerOutlineButton("› RB", modifier = Modifier.height(48.dp).then(focus.track(page, "next"))) {
|
||||
host.open = null; onPageChange((page + 1) % DRAWER_PAGES)
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll[page]),
|
||||
) {
|
||||
when (page) {
|
||||
0 -> SettingsGroup("Display") {
|
||||
ToggleRow(host, "hud", "Performance HUD", null, a.hudOn,
|
||||
chipModifier = focus.track(page, "hud"), onChange = a.onHud)
|
||||
if (a.fillScreen != null) ToggleRow(
|
||||
host, "fill", "Stretch games to fill", null, a.fillScreen,
|
||||
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen,
|
||||
)
|
||||
val fgOpen = host.open == "fg"
|
||||
val fgLabel = when (a.frameGenEngine) {
|
||||
FrameGen.ENGINE_WINFG -> "Win-FG ${a.frameGenMultiplier}×"
|
||||
FrameGen.ENGINE_LSFG -> "LSFG ${a.frameGenMultiplier}×"
|
||||
else -> "Off"
|
||||
}
|
||||
SettingsRow("Frame generation", null, highlighted = fgOpen) {
|
||||
Box {
|
||||
ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" }
|
||||
AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
|
||||
val need = if (a.lsfgReady) null else "Requires Lossless Scaling"
|
||||
MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
|
||||
for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
|
||||
for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
DRAWER_PAGE_COMPONENTS -> ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
|
||||
1 -> {
|
||||
SettingsGroup("Controls") {
|
||||
ChoiceRow(host, "touch", "Touch", null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to "Auto (${a.touchAuto})", SessionPrefs.TOUCH_PAD to "Touchpad", SessionPrefs.TOUCH_DIRECT to "Direct"),
|
||||
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
|
||||
ChoiceRow(host, "osc", "On-screen controls", null,
|
||||
if (a.steam) listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never")
|
||||
else listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_NEVER to "Never"),
|
||||
a.oscMode, chipModifier = focus.track(page, "osc"), onPick = a.onOsc)
|
||||
if (a.steam) ChoiceRow(host, "back-actions", "Back", null,
|
||||
listOf(false to SessionPrefs.BACK_MENU_THEN_QAM, true to SessionPrefs.BACK_QAM_THEN_MENU),
|
||||
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
|
||||
}
|
||||
SettingsGroup("Keyboard") {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) {
|
||||
DrawerOutlineButton("Hardware", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "hardware"))) {
|
||||
host.open = null; a.onHardwareKeyboard()
|
||||
}
|
||||
DrawerOutlineButton("Android", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "android"))) {
|
||||
host.open = null; a.onKeyboard()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
|
||||
ChoiceRow(host, "second-screen-mode", "Controls", null,
|
||||
listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL).map { it to it.label },
|
||||
a.secondScreenMode, chipModifier = focus.track(page, "second-screen-mode"), onPick = a.onSecondScreenMode)
|
||||
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", "Display", null,
|
||||
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
|
||||
chipModifier = focus.track(page, "second-screen-display"), onPick = a.onSecondScreenDisplay)
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
if (a.isHomeApp) SettingsGroup("Android apps") {
|
||||
SettingsRow("Launch an app", null) {
|
||||
DrawerOutlineButton(if (androidAppsExpanded) "Hide" else "Show", modifier = focus.track(page, "apps")) {
|
||||
androidAppsExpanded = !androidAppsExpanded
|
||||
}
|
||||
}
|
||||
if (androidAppsExpanded) {
|
||||
if (a.androidApps.isEmpty()) {
|
||||
Text("No launchable apps", fontSize = 12.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
|
||||
} else for (app in a.androidApps) {
|
||||
MenuItem(
|
||||
app.label, checked = false,
|
||||
modifier = focus.track(page, "app:${app.packageName}/${app.className}"),
|
||||
leading = {
|
||||
app.icon?.let { icon ->
|
||||
Image(bitmap = icon.asImageBitmap(), contentDescription = null,
|
||||
modifier = Modifier.size(26.dp).clip(RoundedCornerShape(6.dp)))
|
||||
}
|
||||
},
|
||||
) {
|
||||
host.open = null
|
||||
if (a.secondScreenDisplays.isEmpty()) a.onLaunchAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsGroup("Session behavior") {
|
||||
ChoiceRow(
|
||||
host, "suspend", "Background behavior",
|
||||
"Applies now and to future sessions in this mode.",
|
||||
listOf(
|
||||
SessionPrefs.SUSPEND_AUTO to "Auto",
|
||||
SessionPrefs.SUSPEND_MANUAL to "Manual",
|
||||
SessionPrefs.SUSPEND_NEVER to "Never",
|
||||
),
|
||||
a.suspendPolicy,
|
||||
note = "Auto pauses in the background and resumes when visible. Manual pauses there and waits for Resume. Never keeps the session running.",
|
||||
chipModifier = focus.track(page, "suspend"),
|
||||
onPick = a.onSuspendPolicy,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Next session") {
|
||||
ChoiceRow(host, "shape", "Screen ratio", null,
|
||||
SessionPrefs.shapeChoices, a.shapeMode,
|
||||
chipModifier = focus.track(page, "shape"), onPick = a.onShape)
|
||||
if (a.steam) ChoiceRow(host, "fex", "FEX preset", null,
|
||||
FexPreset.all.map { it.id to it.label }, a.fexPreset,
|
||||
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
|
||||
}
|
||||
Spacer(Modifier.height(18.dp))
|
||||
if (!a.isHomeApp) DrawerOutlineButton("Background", modifier = focus.track(page, "background")) {
|
||||
host.open = null; a.onBackground()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
appToChooseDisplay?.let { app ->
|
||||
val secondaryDisplay = a.secondScreenDisplays.firstOrNull { it.id == a.selectedSecondScreenDisplay }
|
||||
?: a.secondScreenDisplays.firstOrNull()
|
||||
ChooseAppDisplayDialog(
|
||||
app = app,
|
||||
secondaryDisplay = secondaryDisplay,
|
||||
onPrimary = {
|
||||
appToChooseDisplay = null
|
||||
a.onLaunchAndroidApp(app, Display.DEFAULT_DISPLAY)
|
||||
},
|
||||
onSecondary = {
|
||||
appToChooseDisplay = null
|
||||
secondaryDisplay?.let { a.onLaunchAndroidApp(app, it.id) }
|
||||
},
|
||||
onDismiss = { appToChooseDisplay = null },
|
||||
)
|
||||
}
|
||||
if (confirmStop) {
|
||||
val cancelFocus = remember { FocusRequester() }
|
||||
val cancel = { confirmStop = false }
|
||||
val stop = { confirmStop = false; a.onStop() }
|
||||
LaunchedEffect(controllerActive) {
|
||||
if (controllerActive) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
runCatching { cancelFocus.requestFocus() }
|
||||
}
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = cancel,
|
||||
modifier = Modifier.controllerBack(onBack = cancel),
|
||||
title = { Text("Stop session?") },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = stop,
|
||||
modifier = Modifier.controllerConfirm(onClick = stop),
|
||||
colors = ButtonDefaults.textButtonColors(contentColor = colors.error),
|
||||
) { Text("Stop") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = cancel, modifier = Modifier.focusRequester(cancelFocus)
|
||||
.controllerConfirm(onClick = cancel)) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DangerButton(text: String, onClick: () -> Unit) {
|
||||
private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
OutlinedButton(
|
||||
onClick = onClick,
|
||||
interactionSource = source,
|
||||
modifier = modifier.controllerConfirm(onClick = onClick),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp),
|
||||
border = BorderStroke(if (hot) 2.dp else 1.dp, if (hot) pal.signal else colors.outline),
|
||||
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
|
||||
) { Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill")
|
||||
Box(
|
||||
modifier = Modifier.clip(RoundedCornerShape(12.dp)).background(fill).border(1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.5f), RoundedCornerShape(12.dp))
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.size(42.dp).semantics { contentDescription = "Stop session" }
|
||||
.clip(RoundedCornerShape(12.dp)).background(fill).border(1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.5f), RoundedCornerShape(12.dp))
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 11.dp),
|
||||
) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.error, maxLines = 1) }
|
||||
.controllerConfirm(onClick = onClick),
|
||||
) { Text("×", fontSize = 25.sp, fontWeight = FontWeight.Medium, color = colors.error) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ShareSessionLogsButton(modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.widthIn(min = 88.dp).height(42.dp)
|
||||
.semantics { contentDescription = "Send current session logs" }
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.border(1.dp, if (hot) pal.signal else colors.outline.copy(alpha = 0.5f), RoundedCornerShape(12.dp))
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick),
|
||||
) {
|
||||
Text("send logs", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = if (hot) pal.signal else colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The drawer's page tabs, QAM-style: one icon per page standing in a line in page order. The
|
||||
* selected one steps forward - full size, bright, a soft glow - while the others step back to
|
||||
* half size and fade, and the whole line leans a little toward the selection. LB / RB still turn
|
||||
* the page (the buttons beside it and the pad's bumpers); a tab can be tapped or picked with the
|
||||
* pad like the dots it replaces.
|
||||
*/
|
||||
@Composable
|
||||
private fun DrawerPageTabs(page: Int, modifier: Modifier = Modifier, onSelect: (Int) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val count = drawerPageIcons.size
|
||||
val middle = (count - 1) / 2f
|
||||
val motion = tween<Float>(durationMillis = 340, easing = FastOutSlowInEasing)
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.height(64.dp).clipToBounds(),
|
||||
) {
|
||||
// Fit the line to the room between LB and RB. Worst case is an end tab selected: full size
|
||||
// (56 dp) and pushed outward by the lean, which scales with the spacing. So
|
||||
// (count-1) * spacing * (1 + lean/64) + 56 <= width
|
||||
// - never more than the mock's 64 dp, never tighter than 32 dp.
|
||||
val spacing = ((maxWidth.value - 56f) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(32f, DRAWER_TAB_SPACING_DP)
|
||||
val leanStep = DRAWER_TAB_LEAN_DP * spacing / DRAWER_TAB_SPACING_DP
|
||||
val lean by animateFloatAsState(-(page - middle) * leanStep, motion, label = "tabLean")
|
||||
drawerPageIcons.forEachIndexed { index, icon ->
|
||||
val selected = index == page
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val focused = source.collectIsFocusedAsState().value
|
||||
val scale by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_SCALE, motion, label = "tabScale")
|
||||
val alpha by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_ALPHA, motion, label = "tabAlpha")
|
||||
val glow by animateFloatAsState(if (selected) 1f else 0f, motion, label = "tabGlow")
|
||||
val tint by animateColorAsState(if (selected) colors.onBackground else colors.onSurfaceVariant, tween(340), label = "tabTint")
|
||||
val select = { onSelect(index) }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier
|
||||
.offset(x = ((index - middle) * spacing + lean).dp)
|
||||
.size(56.dp)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale; this.alpha = alpha }
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(
|
||||
Brush.radialGradient(
|
||||
listOf(pal.signal.copy(alpha = 0.34f * glow), pal.signal.copy(alpha = 0.10f * glow), Color.Transparent),
|
||||
),
|
||||
)
|
||||
.border(if (focused) 2.dp else 0.dp, if (focused) colors.onBackground else Color.Transparent, RoundedCornerShape(16.dp))
|
||||
.semantics { contentDescription = "${drawerPageTitles[index]} page" }
|
||||
.hoverable(source)
|
||||
.clickable(interactionSource = source, indication = LocalIndication.current, onClick = select)
|
||||
.controllerConfirm(onClick = select),
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Display, Controls, Components, Settings. */
|
||||
const val DRAWER_PAGES = 4
|
||||
private const val DRAWER_PAGE_COMPONENTS = 2
|
||||
|
||||
/**
|
||||
* The drawer's Components tab: quick swaps between what is already installed, per Proton. A swap
|
||||
* into the Proton a running game uses waits until that game closes; downloading, importing and
|
||||
* deleting stay on the Components page in the app.
|
||||
*/
|
||||
@Composable
|
||||
private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val snap = a.components
|
||||
if (snap == null) {
|
||||
SettingsGroup("Components") {
|
||||
Text("Reading the Protons…", fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(14.dp))
|
||||
}
|
||||
return
|
||||
}
|
||||
val running = snap.protons.filter { it.inUseByGame }
|
||||
var pick by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
val view = snap.protons.firstOrNull { it.proton.id == pick } ?: running.firstOrNull() ?: snap.protons.firstOrNull()
|
||||
// Focusable, so the pad can climb from the Proton box up to it and the page scrolls it into view.
|
||||
SettingsGroup("Running now") {
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value
|
||||
val pal = LocalPalette.current
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().then(track("cmp-running"))
|
||||
.focusable(interactionSource = src)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.padding(horizontal = 14.dp, vertical = 11.dp),
|
||||
) {
|
||||
if (running.isEmpty()) {
|
||||
Text("No game is running on a Proton", fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Text("Changes apply the next time a game starts.", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
|
||||
} else for (r in running) {
|
||||
Text(r.proton.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
for (comp in ComponentsManager.COMPONENTS) {
|
||||
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
|
||||
Text(ComponentsManager.LABEL.getValue(comp), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(96.dp))
|
||||
Text(r.components.getValue(comp).inUse, fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (view == null) {
|
||||
SettingsGroup("Components") {
|
||||
Text("No Proton is installed yet.", fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(14.dp))
|
||||
}
|
||||
return
|
||||
}
|
||||
val p = view.proton
|
||||
SettingsGroup("Components") {
|
||||
DrawerStackedChoice(
|
||||
host, "cmp-proton", "Proton",
|
||||
listOfNotNull(
|
||||
p.version,
|
||||
"game running".takeIf { view.inUseByGame },
|
||||
view.reappliedAt.takeIf { it > 0 }?.let { "re-applied at launch " + java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(it * 1000)) },
|
||||
).joinToString(" · "),
|
||||
snap.protons.map { it.proton.id to it.proton.name }, p.id,
|
||||
chipModifier = track("cmp-proton"), onPick = { pick = it },
|
||||
)
|
||||
val build = ComponentsManager.safeName(p.version)
|
||||
for (comp in ComponentsManager.COMPONENTS) {
|
||||
val st = view.components.getValue(comp)
|
||||
val originals = view.originals.filter { it.comp == comp }
|
||||
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) "Original" else "Original · ${it.protonVersion}") } +
|
||||
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
||||
if (options.isEmpty()) continue
|
||||
val current = st.activeFile ?: "orig:$build"
|
||||
val shown = options.firstOrNull { it.first == current }?.second
|
||||
DrawerStackedChoice(
|
||||
host, "cmp-$comp", ComponentsManager.LABEL.getValue(comp),
|
||||
// The box already shows the choice: only say more when there is more to say.
|
||||
st.queued?.let { "Next: $it · after the game closes" } ?: st.inUse.takeIf { it != shown },
|
||||
options, current,
|
||||
note = if (view.inUseByGame) "A game is running on this Proton: the change waits until it closes." else "Applies the next time a game starts.",
|
||||
chipModifier = track("cmp-$comp"),
|
||||
onPick = { v -> if (v != current || st.queued != null) a.onComponentSwap(p.id, comp, v) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"Downloads, importing and deleting are on the Components page in the app.",
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A choice for the drawer's narrow column: label, then the box across the full width, then the
|
||||
* detail underneath - so a long Proton or package name never squeezes the text beside it.
|
||||
*/
|
||||
@Composable
|
||||
private fun <T> DrawerStackedChoice(
|
||||
host: MenuHost, key: String, label: String, hint: String?,
|
||||
options: List<Pair<T, String>>, selected: T, note: String? = null,
|
||||
chipModifier: Modifier = Modifier, onPick: (T) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val open = host.open == key
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.background(if (open) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
|
||||
.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Box(modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
|
||||
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, modifier = chipModifier.fillMaxWidth()) {
|
||||
host.open = if (open) null else key
|
||||
}
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
options.forEachIndexed { index, (value, text) ->
|
||||
MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
onPick(value)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hint != null) Text(hint, fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 5.dp))
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
|
||||
/** The tab row's measure, from the approved mock: side tabs at half size, a little faded. */
|
||||
private const val DRAWER_TAB_SPACING_DP = 64f
|
||||
private const val DRAWER_TAB_LEAN_DP = 12f
|
||||
private const val DRAWER_TAB_SIDE_SCALE = 0.5f
|
||||
private const val DRAWER_TAB_SIDE_ALPHA = 0.7f
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
@@ -39,6 +40,7 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -49,10 +51,15 @@ import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.TransformOrigin
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
@@ -69,6 +76,26 @@ import androidx.compose.ui.window.PopupProperties
|
||||
private val RowShape = RoundedCornerShape(12.dp)
|
||||
private val GroupShape = RoundedCornerShape(14.dp)
|
||||
|
||||
internal fun Modifier.controllerConfirm(enabled: Boolean = true, onClick: () -> Unit): Modifier = onPreviewKeyEvent { event ->
|
||||
val keyEvent = event.nativeKeyEvent
|
||||
if (keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_A) {
|
||||
false
|
||||
} else {
|
||||
if (enabled && keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) onClick()
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
internal fun Modifier.controllerBack(onBack: () -> Unit): Modifier = onPreviewKeyEvent { event ->
|
||||
val keyEvent = event.nativeKeyEvent
|
||||
if (keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_B && keyEvent.keyCode != KeyEvent.KEYCODE_BACK) {
|
||||
false
|
||||
} else {
|
||||
if (keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) onBack()
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
class MenuHost {
|
||||
var open by mutableStateOf<String?>(null)
|
||||
}
|
||||
@@ -88,10 +115,19 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.() -> Unit) {
|
||||
fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.(FocusRequester) -> Unit) {
|
||||
val state = remember { MutableTransitionState(false) }
|
||||
state.targetState = open
|
||||
if (!state.currentState && !state.targetState && state.isIdle) return
|
||||
val firstItemFocus = remember { FocusRequester() }
|
||||
val inputMode = LocalInputModeManager.current.inputMode
|
||||
LaunchedEffect(open, inputMode) {
|
||||
if (open && inputMode == InputMode.Keyboard) {
|
||||
repeat(2) { androidx.compose.runtime.withFrameNanos { } }
|
||||
runCatching { firstItemFocus.requestFocus() }
|
||||
android.util.Log.i("AnchoredMenu", "requested first option focus")
|
||||
}
|
||||
}
|
||||
val gap = with(LocalDensity.current) { 6.dp.roundToPx() }
|
||||
val provider = remember(gap) { BelowEndProvider(gap) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -114,13 +150,14 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no
|
||||
.clip(RowShape)
|
||||
.background(pal.surfaceVariant.copy(alpha = 0.95f))
|
||||
.border(1.dp, pal.signal.copy(alpha = 0.22f), RowShape)
|
||||
.controllerBack(onDismiss)
|
||||
.padding(6.dp),
|
||||
) {
|
||||
if (title != null) Text(
|
||||
title.uppercase(), fontSize = 10.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 6.dp),
|
||||
)
|
||||
Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content() }
|
||||
Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content(firstItemFocus) }
|
||||
if (note != null) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
@@ -134,7 +171,8 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no
|
||||
@Composable
|
||||
fun MenuItem(
|
||||
label: String, checked: Boolean, enabled: Boolean = true, detail: String? = null,
|
||||
trailing: (@Composable () -> Unit)? = null, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit,
|
||||
trailing: (@Composable () -> Unit)? = null, leading: (@Composable () -> Unit)? = null,
|
||||
focusRequester: FocusRequester? = null, modifier: Modifier = Modifier, onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
@@ -143,12 +181,14 @@ fun MenuItem(
|
||||
val shift by animateFloatAsState(if (hot) 2f else 0f, Motion.sp(0.5f), label = "miShift")
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
modifier = modifier.fillMaxWidth()
|
||||
.graphicsLayer { translationX = shift.dp.toPx() }
|
||||
.then(focusRequester?.let { Modifier.focusRequester(it) } ?: Modifier)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent)
|
||||
.alpha(if (enabled) 1f else 0.4f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 9.dp),
|
||||
) {
|
||||
Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f))
|
||||
@@ -181,6 +221,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
|
||||
.border(1.dp, edge, RoundedCornerShape(10.dp))
|
||||
.alpha(if (enabled) 1f else 0.5f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
AnimatedContent(
|
||||
@@ -194,10 +235,14 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SettingsGroup(title: String, content: @Composable ColumnScope.() -> Unit) {
|
||||
fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ColumnScope.() -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 6.dp)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(if (compact) 6.dp else 10.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = if (compact) 4.dp else 16.dp, bottom = if (compact) 3.dp else 6.dp),
|
||||
) {
|
||||
Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant)
|
||||
Box(modifier = Modifier.weight(1f).height(1.dp).background(pal.line))
|
||||
}
|
||||
@@ -234,8 +279,13 @@ fun <T> ChoiceRow(
|
||||
SettingsRow(label, hint, highlighted = open) {
|
||||
Box {
|
||||
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) {
|
||||
for ((value, text) in options) MenuItem(text, checked = value == selected) { onPick(value); host.open = null }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
options.forEachIndexed { index, (value, text) ->
|
||||
MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
onPick(value)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,10 +310,10 @@ fun MultiRow(
|
||||
SettingsRow(label, hint, highlighted = open) {
|
||||
Box {
|
||||
ValueChip(summary, open, enabled) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) {
|
||||
for ((value, text) in items) {
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
items.forEachIndexed { index, (value, text) ->
|
||||
val on = value in selected
|
||||
MenuItem(text, checked = on) { onToggle(value, !on) }
|
||||
MenuItem(text, checked = on, focusRequester = if (index == 0) firstItemFocus else null) { onToggle(value, !on) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -286,24 +336,32 @@ fun SettingsPage(
|
||||
action: (@Composable () -> Unit)? = null,
|
||||
/** Pass one held above the page to keep its scroll position across a page opened over it. */
|
||||
scroll: androidx.compose.foundation.ScrollState? = null,
|
||||
scrollContent: Boolean = true,
|
||||
compactLayout: Boolean = false,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val scrollState = scroll ?: rememberScrollState()
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val dim by animateFloatAsState(if (host.open != null) 0.6f else 1f, Motion.tw(220), label = "pageDim")
|
||||
Column(modifier = Modifier.fillMaxSize().padding(horizontal = 22.dp, vertical = 18.dp)) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(
|
||||
horizontal = if (compactLayout) 14.dp else 22.dp,
|
||||
vertical = if (compactLayout) 6.dp else 18.dp,
|
||||
),
|
||||
verticalArrangement = Arrangement.spacedBy(if (compactLayout) 2.dp else 0.dp),
|
||||
) {
|
||||
Rise(0) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
// Outlined when a controller's focus is on it, like every other control here.
|
||||
val backSrc = remember { MutableInteractionSource() }
|
||||
val backHot = backSrc.collectIsFocusedAsState().value || backSrc.collectIsHoveredAsState().value
|
||||
Text(
|
||||
"‹ Back", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
"‹ Back", fontSize = if (compactLayout) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = if (backHot) LocalPalette.current.signal else colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp))
|
||||
.border(2.dp, if (backHot) LocalPalette.current.signal else Color.Transparent, RoundedCornerShape(8.dp))
|
||||
.hoverable(backSrc).clickable(interactionSource = backSrc, indication = null, onClick = onBack)
|
||||
.padding(horizontal = 6.dp, vertical = 4.dp),
|
||||
.padding(horizontal = 6.dp, vertical = if (compactLayout) 2.dp else 4.dp),
|
||||
)
|
||||
if (eyebrow != null) {
|
||||
Spacer(Modifier.width(10.dp))
|
||||
@@ -313,13 +371,44 @@ fun SettingsPage(
|
||||
}
|
||||
Rise(1) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.weight(1f)) { Title(title) }
|
||||
Box(Modifier.weight(1f)) {
|
||||
if (compactLayout) {
|
||||
Text(
|
||||
title,
|
||||
fontSize = 20.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = colors.onBackground,
|
||||
modifier = Modifier.padding(vertical = 2.dp),
|
||||
)
|
||||
} else {
|
||||
Title(title)
|
||||
}
|
||||
}
|
||||
if (action != null) action()
|
||||
}
|
||||
}
|
||||
if (lede != null) Rise(2) { Lede(lede) }
|
||||
if (lede != null) Rise(2) {
|
||||
if (compactLayout) {
|
||||
Text(
|
||||
lede,
|
||||
fontSize = 11.sp,
|
||||
color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = 3.dp),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
} else {
|
||||
Lede(lede)
|
||||
}
|
||||
}
|
||||
Rise(3, Modifier.weight(1f).fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxSize().graphicsLayer { alpha = dim }.verticalScroll(scrollState).padding(bottom = 24.dp)) { content() }
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.graphicsLayer { alpha = dim }
|
||||
.then(if (scrollContent) Modifier.verticalScroll(scrollState) else Modifier)
|
||||
.padding(bottom = if (compactLayout) 0.dp else 24.dp),
|
||||
) { content() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.text.Editable
|
||||
import android.text.InputType
|
||||
import android.text.TextWatcher
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.EditText
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.focus.FocusManager
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
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.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@Composable
|
||||
fun WirelessAdbFixPage(
|
||||
onBack: () -> Unit,
|
||||
desiredEnabled: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onPair: (String, Int, String, (String?) -> Unit) -> Unit,
|
||||
onFindConnectPort: (String, (Int?) -> Unit) -> Unit,
|
||||
onApply: (String, Int, Boolean, (String?) -> Unit) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val savedAddress = remember { WirelessAdbFix.savedConnectionAddress(context) }
|
||||
var step by rememberSaveable { mutableStateOf(if (savedAddress == null) 0 else 1) }
|
||||
var pairingAddress by rememberSaveable { mutableStateOf("") }
|
||||
var connectionAddress by rememberSaveable { mutableStateOf(savedAddress.orEmpty()) }
|
||||
var pairingCode by rememberSaveable { mutableStateOf("") }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf(false) }
|
||||
var message by remember { mutableStateOf<String?>(null) }
|
||||
var messageIsError by remember { mutableStateOf(false) }
|
||||
val focusManager = LocalFocusManager.current
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
val pairingEndpoint = parseAdbAddress(pairingAddress)
|
||||
|
||||
val pairNow: () -> Unit = {
|
||||
parseAdbAddress(pairingAddress)?.let { endpoint ->
|
||||
keyboardController?.hide()
|
||||
focusManager.clearFocus()
|
||||
busy = true
|
||||
editing = false
|
||||
message = null
|
||||
messageIsError = false
|
||||
onPair(endpoint.host, endpoint.port, pairingCode) { error ->
|
||||
pairingCode = ""
|
||||
if (error != null) {
|
||||
busy = false
|
||||
message = error
|
||||
messageIsError = true
|
||||
} else {
|
||||
step = 1
|
||||
busy = true
|
||||
message = "Paired. Finding the Wireless debugging port…"
|
||||
onFindConnectPort(endpoint.host) { discoveredPort ->
|
||||
if (discoveredPort == null) {
|
||||
connectionAddress = formatAddressHost(endpoint.host) + ":"
|
||||
busy = false
|
||||
message = "Paired. Enter the port from Settings."
|
||||
} else {
|
||||
connectionAddress = formatAdbAddress(endpoint.host, discoveredPort)
|
||||
message = "Device found. Applying the setting…"
|
||||
onApply(endpoint.host, discoveredPort, desiredEnabled) { applyError ->
|
||||
busy = false
|
||||
if (applyError == null) {
|
||||
step = 2
|
||||
message = null
|
||||
} else {
|
||||
message = "Could not apply automatically. Check the address below and retry. $applyError"
|
||||
messageIsError = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val applyAddress: () -> Unit = {
|
||||
parseAdbAddress(connectionAddress)?.let { endpoint ->
|
||||
keyboardController?.hide()
|
||||
focusManager.clearFocus()
|
||||
busy = true
|
||||
editing = false
|
||||
message = null
|
||||
messageIsError = false
|
||||
onApply(endpoint.host, endpoint.port, desiredEnabled) { error ->
|
||||
busy = false
|
||||
if (error == null) {
|
||||
step = 2
|
||||
message = null
|
||||
} else {
|
||||
message = error
|
||||
messageIsError = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val pairAgain: () -> Unit = {
|
||||
step = 0
|
||||
pairingAddress = ""
|
||||
pairingCode = ""
|
||||
message = null
|
||||
messageIsError = false
|
||||
}
|
||||
|
||||
BackHandler { if (!busy) onBack() }
|
||||
|
||||
BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
val compactSplit = maxWidth < 620.dp && maxHeight < 500.dp
|
||||
val form: @Composable () -> Unit = {
|
||||
WirelessStepForm(
|
||||
step = step,
|
||||
pairingAddress = pairingAddress,
|
||||
onPairingAddressChange = { pairingAddress = it },
|
||||
pairingCode = pairingCode,
|
||||
onPairingCodeChange = { pairingCode = it.filter(Char::isDigit).take(6) },
|
||||
connectionAddress = connectionAddress,
|
||||
onConnectionAddressChange = { connectionAddress = it },
|
||||
busy = busy,
|
||||
message = message,
|
||||
messageIsError = messageIsError,
|
||||
compact = compactSplit,
|
||||
editing = editing,
|
||||
onEditingChanged = { editing = it },
|
||||
focusManager = focusManager,
|
||||
desiredEnabled = desiredEnabled,
|
||||
canPair = pairingEndpoint != null && pairingCode.length == 6,
|
||||
onPair = pairNow,
|
||||
onApply = applyAddress,
|
||||
onPairAgain = pairAgain,
|
||||
)
|
||||
}
|
||||
SettingsPage(
|
||||
host = rememberMenuHost(),
|
||||
title = when {
|
||||
compactSplit && step < 2 -> "Wireless ADB"
|
||||
step == 2 -> "Wireless ADB ready"
|
||||
else -> "Set up on-device ADB"
|
||||
},
|
||||
eyebrow = "Setup",
|
||||
lede = when {
|
||||
compactSplit && step == 0 -> "If the option is missing, pair over Wireless debugging."
|
||||
compactSplit && step == 1 -> "Paired. Check IP address & Port in Wireless debugging."
|
||||
compactSplit -> "The child-process limit was updated."
|
||||
step == 0 -> "Use step 2 if Developer options has no child-process setting. In Android Settings, open Developer options → Wireless debugging → Pair device with pairing code."
|
||||
step == 1 -> "Paired. Use the address below; update it from Wireless debugging → IP address & Port if needed."
|
||||
else -> "The child-process limit was updated over Wireless debugging."
|
||||
},
|
||||
onBack = { if (!busy) onBack() },
|
||||
action = if (compactSplit && step < 2) {
|
||||
{ SecondaryButton("Developer options", compact = true, enabled = !busy, onClick = onOpenDeveloperOptions) }
|
||||
} else null,
|
||||
scrollContent = !compactSplit,
|
||||
compactLayout = compactSplit,
|
||||
) {
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val wide = maxWidth >= 620.dp
|
||||
if (step == 2) {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 680.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
SettingsGroup("Child-process limit", compact = compactSplit) {
|
||||
Text(
|
||||
"Android confirmed the limit is ${if (desiredEnabled) "enabled" else "disabled"}.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(14.dp),
|
||||
)
|
||||
}
|
||||
PrimaryButton("Done", enabled = !busy, onClick = onBack)
|
||||
}
|
||||
} else if (compactSplit) {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
form()
|
||||
if (!editing) CompactComputerFallback(desiredEnabled)
|
||||
}
|
||||
} else {
|
||||
val routes: @Composable () -> Unit = {
|
||||
FallbackOrder(desiredEnabled, busy, onOpenDeveloperOptions)
|
||||
}
|
||||
if (wide) {
|
||||
Row(
|
||||
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) { routes() }
|
||||
Column(Modifier.weight(1f)) { form() }
|
||||
}
|
||||
} else {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
routes()
|
||||
form()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WirelessStepForm(
|
||||
step: Int,
|
||||
pairingAddress: String,
|
||||
onPairingAddressChange: (String) -> Unit,
|
||||
pairingCode: String,
|
||||
onPairingCodeChange: (String) -> Unit,
|
||||
connectionAddress: String,
|
||||
onConnectionAddressChange: (String) -> Unit,
|
||||
busy: Boolean,
|
||||
message: String?,
|
||||
messageIsError: Boolean,
|
||||
compact: Boolean,
|
||||
editing: Boolean,
|
||||
onEditingChanged: (Boolean) -> Unit,
|
||||
focusManager: FocusManager,
|
||||
desiredEnabled: Boolean,
|
||||
canPair: Boolean,
|
||||
onPair: () -> Unit,
|
||||
onApply: () -> Unit,
|
||||
onPairAgain: () -> Unit,
|
||||
) {
|
||||
if (step == 0) {
|
||||
SettingsGroup("2 · Pair Wireless debugging", compact = compact) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
|
||||
) {
|
||||
AdbTextField(
|
||||
value = pairingAddress,
|
||||
onValueChange = onPairingAddressChange,
|
||||
label = "Pairing pop-up IP address & Port",
|
||||
placeholder = "192.168.1.42:37123",
|
||||
keyboardType = KeyboardType.Ascii,
|
||||
imeAction = ImeAction.Next,
|
||||
compact = compact,
|
||||
onFocusChange = onEditingChanged,
|
||||
onNext = { focusManager.moveFocus(FocusDirection.Next) },
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.Bottom,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
AdbTextField(
|
||||
value = pairingCode,
|
||||
onValueChange = onPairingCodeChange,
|
||||
label = "Pairing code (PIN)",
|
||||
placeholder = "6 digits",
|
||||
keyboardType = KeyboardType.Number,
|
||||
imeAction = ImeAction.Done,
|
||||
compact = compact,
|
||||
onFocusChange = onEditingChanged,
|
||||
onDone = {
|
||||
focusManager.clearFocus()
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
PrimaryButton("Pair", compact = compact, enabled = !busy && canPair, onClick = onPair)
|
||||
}
|
||||
StatusMessage(busy, message, isError = messageIsError)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
SettingsGroup("2 · Apply over Wireless debugging", compact = compact) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
|
||||
) {
|
||||
AdbTextField(
|
||||
value = connectionAddress,
|
||||
onValueChange = onConnectionAddressChange,
|
||||
label = "Connection IP address & Port",
|
||||
placeholder = "192.168.1.42:45678",
|
||||
keyboardType = KeyboardType.Ascii,
|
||||
imeAction = ImeAction.Done,
|
||||
compact = compact,
|
||||
onFocusChange = onEditingChanged,
|
||||
onDone = { focusManager.clearFocus() },
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
StatusMessage(busy, message, Modifier.weight(1f), isError = messageIsError)
|
||||
SecondaryButton("Pair again", compact = compact, enabled = !busy, onClick = onPairAgain)
|
||||
PrimaryButton(
|
||||
if (desiredEnabled) "Enable limit" else "Disable limit",
|
||||
compact = compact,
|
||||
enabled = !busy && parseAdbAddress(connectionAddress) != null,
|
||||
onClick = onApply,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AdbTextField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
label: String,
|
||||
keyboardType: KeyboardType,
|
||||
imeAction: ImeAction,
|
||||
modifier: Modifier = Modifier,
|
||||
placeholder: String? = null,
|
||||
compact: Boolean = false,
|
||||
onFocusChange: (Boolean) -> Unit = {},
|
||||
onNext: (() -> Unit)? = null,
|
||||
onDone: (() -> Unit)? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val onValueChangeLatest = rememberUpdatedState(onValueChange)
|
||||
val onNextLatest = rememberUpdatedState(onNext)
|
||||
val onDoneLatest = rememberUpdatedState(onDone)
|
||||
val onFocusChangeLatest = rememberUpdatedState(onFocusChange)
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
val inputHeight = if (compact) 44.dp else 52.dp
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = colors.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(inputHeight)
|
||||
.background(colors.surfaceVariant, shape)
|
||||
.border(1.dp, if (focused) palette.signal else palette.line2, shape)
|
||||
.padding(horizontal = 10.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { viewContext ->
|
||||
EditText(viewContext).apply {
|
||||
isSingleLine = true
|
||||
setHorizontallyScrolling(true)
|
||||
background = null
|
||||
setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0)
|
||||
setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f)
|
||||
setTextColor(colors.onBackground.toArgb())
|
||||
setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
contentDescription = label
|
||||
inputType = if (keyboardType == KeyboardType.Number) {
|
||||
InputType.TYPE_CLASS_NUMBER
|
||||
} else {
|
||||
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
|
||||
}
|
||||
imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI
|
||||
hint = placeholder
|
||||
setOnEditorActionListener { _, actionId, event ->
|
||||
val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER
|
||||
when {
|
||||
imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> {
|
||||
onNextLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> {
|
||||
onDoneLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
setOnFocusChangeListener { _, hasFocus ->
|
||||
focused = hasFocus
|
||||
onFocusChangeLatest.value(hasFocus)
|
||||
}
|
||||
addTextChangedListener(object : TextWatcher {
|
||||
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
|
||||
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
|
||||
override fun afterTextChanged(s: Editable?) {
|
||||
onValueChangeLatest.value(s?.toString().orEmpty())
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
update = { editText ->
|
||||
editText.setTextColor(colors.onBackground.toArgb())
|
||||
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
editText.hint = placeholder
|
||||
editText.contentDescription = label
|
||||
if (editText.text.toString() != value) {
|
||||
val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length
|
||||
editText.setText(value)
|
||||
editText.setSelection(min(cursor, value.length))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FallbackOrder(
|
||||
desiredEnabled: Boolean,
|
||||
busy: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
) {
|
||||
SettingsGroup("Other ways to change it") {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text("1 · Developer options (try first)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text("Set “Restrict child processes” ${if (desiredEnabled) "on" else "off"}.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
SecondaryButton("Open Developer options", enabled = !busy, onClick = onOpenDeveloperOptions)
|
||||
Text("3 · Computer ADB (last resort)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text("Only if Wireless debugging is unavailable.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(
|
||||
PhantomProcessLimit.adbCommand(desiredEnabled),
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CompactComputerFallback(desiredEnabled: Boolean) {
|
||||
SettingsGroup("3 · Computer ADB last resort", compact = true) {
|
||||
Text(
|
||||
PhantomProcessLimit.adbCommand(desiredEnabled),
|
||||
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusMessage(busy: Boolean, message: String?, modifier: Modifier = Modifier, isError: Boolean = false) {
|
||||
if (busy) {
|
||||
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||
Text(message ?: "Working…", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
} else {
|
||||
message?.let {
|
||||
Text(
|
||||
it,
|
||||
modifier = modifier,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class AdbEndpoint(val host: String, val port: Int)
|
||||
|
||||
private fun parseAdbAddress(value: String): AdbEndpoint? {
|
||||
val address = value.trim()
|
||||
val host: String
|
||||
val portText: String
|
||||
if (address.startsWith("[")) {
|
||||
val closingBracket = address.indexOf(']')
|
||||
if (closingBracket <= 1 || address.getOrNull(closingBracket + 1) != ':') return null
|
||||
host = address.substring(1, closingBracket)
|
||||
if (':' !in host) return null
|
||||
portText = address.substring(closingBracket + 2)
|
||||
} else {
|
||||
val colon = address.lastIndexOf(':')
|
||||
if (colon <= 0 || address.indexOf(':') != colon) return null
|
||||
host = address.substring(0, colon)
|
||||
portText = address.substring(colon + 1)
|
||||
}
|
||||
if (host.isBlank() || host.any(Char::isWhitespace)) return null
|
||||
val port = portText.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null
|
||||
return AdbEndpoint(host, port)
|
||||
}
|
||||
|
||||
private fun formatAddressHost(host: String): String = if (':' in host) "[$host]" else host
|
||||
private fun formatAdbAddress(host: String, port: Int): String = "${formatAddressHost(host)}:$port"
|
||||
|
||||
private fun imeActionFlag(action: ImeAction): Int = when (action) {
|
||||
ImeAction.Next -> EditorInfo.IME_ACTION_NEXT
|
||||
ImeAction.Done -> EditorInfo.IME_ACTION_DONE
|
||||
ImeAction.Go -> EditorInfo.IME_ACTION_GO
|
||||
ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH
|
||||
else -> EditorInfo.IME_ACTION_UNSPECIFIED
|
||||
}
|
||||
@@ -169,6 +169,19 @@ public final class WaylandCompositor {
|
||||
* action: 0=down, 1=move, 2=up. x/y in compositor output space (0..1919, 0..1079). */
|
||||
public static native void nativeSendPointer(int action, int x, int y);
|
||||
|
||||
public static native void nativeSendTouch(int action, int pointerId, int x, int y);
|
||||
|
||||
/**
|
||||
* The client's pointer image, straight from wl_pointer.set_cursor (labwc's resize arrows, a text
|
||||
* field's I-beam). out = [serial, hidden, w, h, hotspotX, hotspotY, ARGB8888 pixels...]; returns
|
||||
* the number of ints written, or 0 if {@code out} is too small. Serial 0 = the client has not
|
||||
* set one yet; [1] = 1 means it asked for NO pointer.
|
||||
*/
|
||||
public static native int nativeCursorSnapshot(int[] out);
|
||||
|
||||
/** Enough for the header plus a 256x256 cursor, the largest the compositor snapshots. */
|
||||
public static final int CURSOR_BUF_INTS = 6 + 256 * 256;
|
||||
|
||||
/** Inject a key event. evdev = Linux input keycode (KEY_A=30…); state: 1=down, 0=up. */
|
||||
public static native void nativeSendKey(int evdev, int state);
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 78 KiB After Width: | Height: | Size: 19 KiB |
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@mipmap/ic_launcher_background" />
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
|
Before Width: | Height: | Size: 924 B After Width: | Height: | Size: 367 B |
|
Before Width: | Height: | Size: 6.3 KiB After Width: | Height: | Size: 2.9 KiB |
|
Before Width: | Height: | Size: 530 B After Width: | Height: | Size: 233 B |
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 508 B |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 897 B |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 6.1 KiB |
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 8.2 KiB |
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<dimen name="page_side">96dp</dimen>
|
||||
<dimen name="logo_size">80dp</dimen>
|
||||
</resources>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<dimen name="page_side">240dp</dimen>
|
||||
<dimen name="logo_size">88dp</dimen>
|
||||
</resources>
|
||||
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Side gutter of the main screen. Grows with the window so the buttons stay a readable
|
||||
width on a landscape phone or a tablet instead of spanning the whole panel. -->
|
||||
<dimen name="page_side">24dp</dimen>
|
||||
<dimen name="logo_size">72dp</dimen>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
# DroidDeck mark
|
||||
|
||||
`droiddeck-mark.svg` is the editable source for the split-D mark. The blue orb is `#1A9FFF`; its halo and the two separator bars are transparent cutouts. The bars are centered on x=63.97, the endpoint of the curved half in the original Steam Deck symbol, and use the halo's 15.83-unit thickness. The mark is optically centered in its view box with a small rightward offset to balance its asymmetric silhouette.
|
||||
|
||||
Android currently consumes raster resources for the launcher layers and the Compose logo. The `mipmap-*/ic_launcher_foreground.png` files are density-sized exports of the SVG, with the mark kept inside the adaptive icon safe area. The matching backgrounds are white. `drawable-nodpi/logo.png` composes the same mark on a white circular badge for use on the app's dark surfaces.
|
||||
@@ -0,0 +1,68 @@
|
||||
# DroidDeck boot animation
|
||||
|
||||
This source accompanies the single Steam startup movie bundled by the app:
|
||||
`app/src/main/assets/steam-startup/droiddeck-startup.webm` (1920×1080, pitch black background, VP9 video
|
||||
with Opus audio). `droiddeck-boot.html` is the editable animation; the scripts and WAV below
|
||||
reproduce the selected render. No alternate MP4 or WebM exports are kept in the repository.
|
||||
|
||||
From the repository root, render the movie with:
|
||||
|
||||
python3 artwork/boot-animation-source/render.py 1920 1080 60 app/src/main/assets/steam-startup/droiddeck-startup.webm dark
|
||||
|
||||
The app stages that file into Steam's `config/uioverrides/movies` folder before each session. If
|
||||
Steam still has its built-in startup movie selected, DroidDeck sets this movie as the device's
|
||||
startup default before Steam starts. A custom startup movie the user selected later is preserved.
|
||||
|
||||
To regenerate the soundtrack, run these commands from this directory:
|
||||
|
||||
python3 events.py
|
||||
python3 sound.py
|
||||
|
||||
The animation and audio are both procedurally generated; the included WAV is the soundtrack used
|
||||
for the bundled render.
|
||||
|
||||
`droiddeck-boot.html` holds the whole animation. Every frame is a pure function of time, so the
|
||||
preview page and the video render draw exactly the same thing. Open it in a browser to scrub, slow
|
||||
it down or step frame by frame (arrow keys).
|
||||
|
||||
## Re-render the video
|
||||
|
||||
pip install playwright && playwright install chromium # ffmpeg with libvpx-vp9 also required
|
||||
python3 render.py 1280 800 60 droiddeck-boot-1280x800.webm
|
||||
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.webm
|
||||
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.mp4 # .mp4 = H.264 for sharing
|
||||
python3 render.py 1280 800 60 droiddeck-boot-dark-1280x800.webm dark # dark version
|
||||
|
||||
Each frame gets real motion blur (180° shutter, adaptive sub-frames). Output is VP9 for .webm or H.264 for .mp4, both BT.709,
|
||||
so the orb stays #1A9FFF after compression.
|
||||
|
||||
## Sound
|
||||
|
||||
Every sound is synthesized in `sound.py` (no samples) and placed on the exact physics events the
|
||||
animation reports, so hits stay frame-accurate even after you change the timing. Key: D major.
|
||||
|
||||
python3 events.py # export impact times, rocking, piece speeds from the animation
|
||||
python3 sound.py # -> droiddeck-boot-sound.wav (-18 LUFS, -1 dBFS peak)
|
||||
python3 embed_sound.py # put it in the preview page
|
||||
python3 render.py ... # muxes the wav in automatically (Opus in .webm, AAC in .mp4)
|
||||
|
||||
The soundtrack is built from the final chord. Each piece lands on one of its notes as a soft, muted
|
||||
tone (legs D, ball A with a quieter echo, bowl F#), the wobble and jump play in silence, and the
|
||||
lock lands with the same soft voice and plays all the notes together. Tweak the cue sheet in `sound.py`: the `tock(...)` calls under
|
||||
`# 1. the stack`, the chord list under `# 4. lock`, and the room reverb mix (`.14 * wet`).
|
||||
|
||||
## Where to tweak
|
||||
|
||||
- Timing of the drops: `archDrop`, `ballDrop`, `domeDrop` (start time, height, bounciness `e`).
|
||||
- The balancing act: `SWAY` keyframes (time, lean). Bigger values = bigger wobble. The bowl leads,
|
||||
the ball chases it (`sway(t - .12)`), the legs follow (`sway(t - .10)`).
|
||||
- The catch-hop on the big wobble: `HOP` (start time, duration, sideways distance, height).
|
||||
- Crouch before the jump: `crouchA/B/D`.
|
||||
- Jump and lock-in: `FL` (rise time, apex height, lock time, how far pieces spread).
|
||||
- Colors for each version (pieces, background, shadows, lock glow): `THEMES` (light, dark).
|
||||
- Total length: `DUR`.
|
||||
|
||||
## Install as the Steam startup movie
|
||||
|
||||
Put the .webm in `~/.steam/root/config/uioverrides/movies/`, then pick it in
|
||||
Steam > Settings > Customization > Startup Movie.
|
||||
@@ -0,0 +1,700 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>DroidDeck boot animation</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root{
|
||||
box-sizing:border-box;
|
||||
padding-top:env(safe-area-inset-top,0px);
|
||||
padding-bottom:env(safe-area-inset-bottom,0px);
|
||||
--page:#E2E8EE; --panel:#F3F6F9; --ink:#131a21; --muted:#56636F; --line:rgba(19,26,33,.12);
|
||||
--track:rgba(19,26,33,.14); --accent:#1A9FFF; --accent-ink:#0B6FC2; --stage-edge:rgba(19,26,33,.10);
|
||||
--font:"Sora", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
--code:ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){
|
||||
:root:not([data-theme="light"]){
|
||||
--page:#0D1319; --panel:#151D25; --ink:#DCE5ED; --muted:#8A98A6; --line:rgba(220,229,237,.12);
|
||||
--track:rgba(220,229,237,.16); --accent-ink:#5CB8FF; --stage-edge:rgba(0,0,0,.5);
|
||||
}
|
||||
}
|
||||
:root[data-theme="dark"]{
|
||||
--page:#0D1319; --panel:#151D25; --ink:#DCE5ED; --muted:#8A98A6; --line:rgba(220,229,237,.12);
|
||||
--track:rgba(220,229,237,.16); --accent-ink:#5CB8FF; --stage-edge:rgba(0,0,0,.5);
|
||||
}
|
||||
*,*::before,*::after{box-sizing:inherit}
|
||||
html{scroll-padding-top:env(safe-area-inset-top,0px)}
|
||||
body{margin:0;background:var(--page);color:var(--ink);font-family:var(--font);font-size:15px;line-height:1.55;-webkit-font-smoothing:antialiased}
|
||||
main{max-width:980px;margin:0 auto;padding:28px 20px 40px}
|
||||
header{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:18px}
|
||||
h1{font-size:1.35rem;font-weight:600;letter-spacing:-.01em;margin:0}
|
||||
.meta{color:var(--muted);font-size:.9rem;margin:0}
|
||||
.stage{position:relative;width:100%;aspect-ratio:16/10;border-radius:14px;overflow:hidden;background:#D6E1EA;box-shadow:0 0 0 1px var(--stage-edge),0 18px 50px -24px rgba(10,20,30,.45)}
|
||||
.stage canvas{display:block;width:100%;height:100%;cursor:pointer}
|
||||
.stage.dark{background:#000}
|
||||
.stage.dark .hint{color:#C9D3DD}
|
||||
.head-l{display:flex;align-items:baseline;gap:14px;flex-wrap:wrap}
|
||||
.version{display:inline-flex;border-radius:999px;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:3px}
|
||||
.version button{border:0;background:none;border-radius:999px;padding:5px 14px;font-size:.85rem;cursor:pointer;color:var(--muted)}
|
||||
.version button[aria-pressed="true"]{background:var(--ink);color:var(--page)}
|
||||
.version button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
||||
.stage .hint{position:absolute;inset:auto 0 14px 0;text-align:center;font-size:.85rem;color:#2c3a47;opacity:0;transition:opacity .25s}
|
||||
.stage.ended .hint{opacity:.75}
|
||||
.controls{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:14px;margin-top:16px}
|
||||
button{font:inherit;color:inherit}
|
||||
.play{display:inline-flex;align-items:center;gap:8px;border:0;background:var(--accent);color:#fff;border-radius:999px;padding:9px 16px 9px 12px;font-weight:600;font-size:.9rem;cursor:pointer}
|
||||
.play svg{width:18px;height:18px}
|
||||
.play:hover{filter:brightness(1.06)}
|
||||
.play:focus-visible,.speed button:focus-visible,.beat:focus-visible,input[type=range]:focus-visible,.fs:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
.scrub{position:relative;padding-bottom:22px}
|
||||
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:28px;background:transparent;margin:0;cursor:pointer}
|
||||
input[type=range]::-webkit-slider-runnable-track{height:4px;border-radius:4px;background:linear-gradient(to right,var(--accent) var(--p,0%),var(--track) var(--p,0%))}
|
||||
input[type=range]::-moz-range-track{height:4px;border-radius:4px;background:linear-gradient(to right,var(--accent) var(--p,0%),var(--track) var(--p,0%))}
|
||||
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;border-radius:50%;background:var(--ink);margin-top:-6px;border:3px solid var(--page)}
|
||||
input[type=range]::-moz-range-thumb{width:12px;height:12px;border-radius:50%;background:var(--ink);border:3px solid var(--page)}
|
||||
.beats{position:absolute;left:8px;right:8px;bottom:0;height:20px}
|
||||
.beat{position:absolute;transform:translateX(-50%);border:0;background:none;padding:0 2px;font-size:.74rem;color:var(--muted);cursor:pointer;white-space:nowrap}
|
||||
.beat:first-child{transform:translateX(-4px)}
|
||||
.beat:first-child::before{left:4px}
|
||||
.beat::before{content:"";position:absolute;left:50%;top:-9px;width:1px;height:6px;background:var(--muted);opacity:.6}
|
||||
.beat:hover,.beat.on{color:var(--ink)}
|
||||
.right{display:flex;align-items:center;gap:10px}
|
||||
.time{font-variant-numeric:tabular-nums;font-size:.85rem;color:var(--muted);min-width:78px;text-align:right}
|
||||
.speed{display:inline-flex;border-radius:999px;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:3px}
|
||||
.speed button{border:0;background:none;border-radius:999px;padding:4px 10px;font-size:.8rem;cursor:pointer;color:var(--muted)}
|
||||
.speed button[aria-pressed="true"]{background:var(--ink);color:var(--page)}
|
||||
.snd{display:inline-flex;align-items:center;gap:6px;border:0;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);border-radius:999px;height:32px;padding:0 12px 0 9px;font-size:.8rem;cursor:pointer;color:var(--ink)}
|
||||
.snd svg{width:18px;height:18px}
|
||||
.snd[aria-pressed="true"]{background:var(--accent);color:#fff;box-shadow:none}
|
||||
.snd:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
.fs{border:0;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);border-radius:999px;width:32px;height:32px;display:grid;place-items:center;cursor:pointer;color:var(--ink)}
|
||||
.fs svg{width:16px;height:16px}
|
||||
.install{margin-top:34px;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:28px;border-top:1px solid var(--line);padding-top:24px}
|
||||
.install h2{font-size:1rem;font-weight:600;margin:0 0 8px}
|
||||
.install p,.install ol{margin:0;color:var(--muted);font-size:.9rem;max-width:62ch}
|
||||
.install ol{padding-left:1.2em}
|
||||
.install li+li{margin-top:6px}
|
||||
code{font-family:var(--code);font-size:.84em;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:1px 6px;border-radius:6px;color:var(--ink);overflow-wrap:anywhere}
|
||||
@media (max-width:640px){
|
||||
main{padding:18px 14px 32px}
|
||||
.controls{grid-template-columns:auto 1fr;row-gap:6px}
|
||||
.right{grid-column:1 / -1;justify-content:space-between}
|
||||
.install{grid-template-columns:1fr}
|
||||
.beat{font-size:.68rem}
|
||||
.snd span{display:none}
|
||||
.snd{padding:0 8px}
|
||||
.right{gap:8px}
|
||||
}
|
||||
body.render{background:#000;margin:0}
|
||||
body.render main{display:none}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<div class="head-l">
|
||||
<h1>DroidDeck boot animation</h1>
|
||||
<p class="meta" id="meta">6.3 s at 60 fps, with sound</p>
|
||||
</div>
|
||||
<div class="version" role="group" aria-label="Version">
|
||||
<button data-v="light" aria-pressed="true">Light</button>
|
||||
<button data-v="dark" aria-pressed="false">Dark</button>
|
||||
</div>
|
||||
</header>
|
||||
<div class="stage" id="stage">
|
||||
<canvas id="cv" aria-label="DroidDeck boot animation: three logo pieces stack into a little droid balancing a bowl on its head, then jump and lock into the DroidDeck mark"></canvas>
|
||||
<div class="hint" id="hint">Tap to replay</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<button class="play" id="play" aria-label="Pause">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path id="playIcon" fill="currentColor" d="M7 5h4v14H7zM13 5h4v14h-4z"/></svg>
|
||||
<span id="playLabel">Pause</span>
|
||||
</button>
|
||||
<div class="scrub">
|
||||
<input type="range" id="scrub" min="0" max="1000" step="1" value="0" aria-label="Timeline">
|
||||
<div class="beats" id="beats"></div>
|
||||
</div>
|
||||
<div class="right">
|
||||
<span class="time" id="time">0.00 / 6.30</span>
|
||||
<div class="speed" role="group" aria-label="Playback speed">
|
||||
<button data-s="1" aria-pressed="true">1×</button>
|
||||
<button data-s="0.5" aria-pressed="false">½×</button>
|
||||
<button data-s="0.25" aria-pressed="false">¼×</button>
|
||||
</div>
|
||||
<button class="snd" id="snd" aria-pressed="false" aria-label="Sound">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M3 9.5h4l5-4.2v13.4l-5-4.2H3z"/><path id="sndMark" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M16 9.5l5 5M21 9.5l-5 5"/></svg>
|
||||
<span>Sound</span>
|
||||
</button>
|
||||
<button class="fs" id="fs" aria-label="Full screen" hidden>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<section class="install">
|
||||
<div>
|
||||
<h2>Use it as the Steam startup movie</h2>
|
||||
<ol>
|
||||
<li>Put the <code>.webm</code> file in <code>~/.steam/<wbr>root/<wbr>config/<wbr>uioverrides/<wbr>movies/</code>. Create the folders if they don’t exist.</li>
|
||||
<li>In Steam, open Settings > Customization > Startup Movie and pick it.</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div>
|
||||
<h2>Which file to ship</h2>
|
||||
<p>Ship the dark version if your Steam UI is dark: it hands off to the library without a bright flash. The 1280×800 cut matches Steam Deck and is the safe default. The 1920×1080 cut is sharper on phones and TVs. Steam needs the <code>.webm</code>; the <code>.mp4</code> files are for sharing. Everything is drawn and synthesized in code, so the included scripts can output any other size.</p>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
/* =====================================================================
|
||||
DroidDeck boot animation engine
|
||||
Every frame is a pure function of time t, so the live preview and the
|
||||
offline video render draw exactly the same thing.
|
||||
Units: logo units from droiddeck-mark.svg. World origin = frame centre,
|
||||
y points down. The frame is always 690 units tall.
|
||||
===================================================================== */
|
||||
const DD = (() => {
|
||||
'use strict';
|
||||
const deg = Math.PI / 180;
|
||||
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
|
||||
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
|
||||
const eio = t => { t = clamp(t); return t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; };
|
||||
const eInQ = t => { t = clamp(t); return t * t; };
|
||||
const eOutC = t => { t = clamp(t); return 1 - Math.pow(1 - t, 3); };
|
||||
|
||||
// ---- 2D affine helpers. m = [a,b,c,d,e,f] (canvas setTransform order)
|
||||
const mul = (m, n) => [
|
||||
m[0]*n[0] + m[2]*n[1], m[1]*n[0] + m[3]*n[1],
|
||||
m[0]*n[2] + m[2]*n[3], m[1]*n[2] + m[3]*n[3],
|
||||
m[0]*n[4] + m[2]*n[5] + m[4], m[1]*n[4] + m[3]*n[5] + m[5]];
|
||||
const T = (x, y) => [1, 0, 0, 1, x, y];
|
||||
const R = a => { const c = Math.cos(a), s = Math.sin(a); return [c, s, -s, c, 0, 0]; };
|
||||
const S = (x, y) => [x, 0, 0, y, 0, 0];
|
||||
const chain = (...ms) => ms.reduce(mul);
|
||||
const ap = (m, p) => ({ x: m[0]*p.x + m[2]*p.y + m[4], y: m[1]*p.x + m[3]*p.y + m[5] });
|
||||
const rv = (a, x, y) => { const c = Math.cos(a), s = Math.sin(a); return { x: c*x - s*y, y: s*x + c*y }; };
|
||||
|
||||
// ---- Geometry straight from the SVG
|
||||
const G = { L: -31.98, B: 223.72, slotL: 56.055, slotR: 71.885, cy: 111.86,
|
||||
dcx: 63.97, dR: 111.86, hcx: 63.98, hR: 71.81, ocx: 63.98, oR: 55.98 };
|
||||
const ORB = '#1A9FFF';
|
||||
const THEMES = {
|
||||
light: { ink: '#1b1b1b', bg: ['#EDF3F8', '#DCE6EE', '#B6C7D6'], shadow: '22,40,58', shadowK: 1, ringA: 1, ringGlow: 0, glow: 0, noise: 3 },
|
||||
// Keep the shipped Steam render black between and around the animated pieces.
|
||||
dark: { ink: '#FFFFFF', bg: ['#000000', '#000000', '#000000'], shadow: '0,0,0', shadowK: 2.3, ringA: 1.5, ringGlow: 14, glow: .34, noise: 0 },
|
||||
};
|
||||
let TH = THEMES.light, THN = 'light';
|
||||
const setTheme = n => { THN = THEMES[n] ? n : 'light'; TH = THEMES[THN]; };
|
||||
const ORB_C = { x: G.ocx, y: G.cy };
|
||||
|
||||
function archPath() { // left piece: the "bridge"
|
||||
const p = new Path2D();
|
||||
const dx = G.slotL - G.hcx, hy = Math.sqrt(G.hR*G.hR - dx*dx);
|
||||
p.moveTo(G.L, 0); p.lineTo(G.slotL, 0); p.lineTo(G.slotL, G.cy - hy);
|
||||
p.arc(G.hcx, G.cy, G.hR, Math.atan2(-hy, dx), Math.atan2(hy, dx), true);
|
||||
p.lineTo(G.slotL, G.B); p.lineTo(G.L, G.B); p.closePath();
|
||||
return p;
|
||||
}
|
||||
function domePath() { // right piece: the curve of the D
|
||||
const dxo = G.slotR - G.dcx, hyo = Math.sqrt(G.dR*G.dR - dxo*dxo);
|
||||
const dxi = G.slotR - G.hcx, hyi = Math.sqrt(G.hR*G.hR - dxi*dxi);
|
||||
const p = new Path2D();
|
||||
p.moveTo(G.slotR, G.cy - hyo);
|
||||
p.arc(G.dcx, G.cy, G.dR, Math.atan2(-hyo, dxo), Math.atan2(hyo, dxo), false);
|
||||
p.lineTo(G.slotR, G.cy + hyi);
|
||||
p.arc(G.hcx, G.cy, G.hR, Math.atan2(hyi, dxi), Math.atan2(-hyi, dxi), true);
|
||||
p.closePath();
|
||||
return p;
|
||||
}
|
||||
function orbPath() { const p = new Path2D(); p.arc(G.ocx, G.cy, G.oR, 0, Math.PI*2); return p; }
|
||||
|
||||
const PATH = { arch: archPath(), dome: domePath(), orb: orbPath() };
|
||||
|
||||
// centroids (numerical, symmetric in y)
|
||||
function centroid(path, x0, x1) {
|
||||
const c = document.createElement('canvas').getContext('2d');
|
||||
let n = 0, sx = 0;
|
||||
for (let x = x0; x <= x1; x += .5) for (let y = 0; y <= G.B; y += .5)
|
||||
if (c.isPointInPath(path, x, y)) { n++; sx += x; }
|
||||
return { x: sx / n, y: G.cy };
|
||||
}
|
||||
const CEN = { arch: centroid(PATH.arch, G.L, G.slotL), dome: centroid(PATH.dome, G.slotR, 176) };
|
||||
|
||||
// anchors: the point of each piece that touches whatever it stands on
|
||||
const ANC = { arch: { x: G.slotL, y: G.cy }, ball: { x: G.ocx, y: G.cy + G.oR }, dome: { x: G.hcx + G.hR, y: G.cy } };
|
||||
const HA = G.slotL - G.L; // arch height when standing (88.035)
|
||||
const WA = G.cy; // arch half width (111.86)
|
||||
const FOOT_HALF = (G.cy - (G.cy - Math.sqrt(G.hR*G.hR - (G.slotL-G.hcx)**2))) ; // unused helper
|
||||
const FEET = [{ x: G.slotL, y: 20.24 }, { x: G.slotL, y: G.B - 20.24 }]; // foot centres (piece coords)
|
||||
|
||||
// ---- Scene constants
|
||||
const VIEW_H = 690; // world units visible vertically
|
||||
const FLOOR = 150;
|
||||
const GRAV = 6500;
|
||||
const DUR = 6.30;
|
||||
const T_L = 4.00; // lift-off
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Drops: exact ballistic bounces (height above whatever you land on)
|
||||
// ------------------------------------------------------------------
|
||||
function drop(o) {
|
||||
const g = GRAV, segs = [], impacts = [];
|
||||
let t = o.t0, v = o.v0;
|
||||
let tau = (-v + Math.sqrt(v*v + 2*g*o.h0)) / g;
|
||||
segs.push({ ts: t, te: t + tau, h0: o.h0, vu: -v });
|
||||
t += tau; v = v + g*tau; impacts.push({ t, v });
|
||||
for (;;) {
|
||||
const vu = o.e * v; if (vu < o.minV) break;
|
||||
const d = 2*vu / g; segs.push({ ts: t, te: t + d, h0: 0, vu });
|
||||
t += d; v = vu; impacts.push({ t, v });
|
||||
}
|
||||
const rest = t;
|
||||
const seg = tt => { for (const s of segs) if (tt < s.te) return s; return null; };
|
||||
return {
|
||||
o, impacts, rest, land: impacts[0].t,
|
||||
h(tt) { if (tt <= o.t0) return o.h0; const s = seg(tt); if (!s) return 0; const u = tt - s.ts; return Math.max(0, s.h0 + s.vu*u - .5*g*u*u); },
|
||||
v(tt) { if (tt <= o.t0 || tt >= rest) return 0; const s = seg(tt); return s ? s.vu - g*(tt - s.ts) : 0; },
|
||||
air(tt) { return tt > o.t0 && tt < rest; }
|
||||
};
|
||||
}
|
||||
|
||||
const archDrop = drop({ t0: 0.10, h0: 520, v0: 250, e: 0.20, minV: 300 });
|
||||
const ballDrop = drop({ t0: 0.50, h0: 440, v0: 250, e: 0.45, minV: 170 });
|
||||
const domeDrop = drop({ t0: 1.15, h0: 330, v0: 250, e: 0.24, minV: 250 });
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The balancing act: one master sway curve, everything else follows it
|
||||
// through springs so the parts lag, overshoot and settle on their own.
|
||||
// ------------------------------------------------------------------
|
||||
const SWAY = [[1.60, 0], [1.90, .42], [2.24, -.70], [2.62, .95], [2.82, 1.10],
|
||||
[3.08, -.44], [3.30, .16], [3.50, 0]];
|
||||
function sway(t) {
|
||||
if (t <= SWAY[0][0] || t >= SWAY[SWAY.length-1][0]) return 0;
|
||||
for (let i = 0; i < SWAY.length - 1; i++) {
|
||||
const [ta, va] = SWAY[i], [tb, vb] = SWAY[i+1];
|
||||
if (t < tb) { const p = (t - ta)/(tb - ta); return va + (vb - va)*(.5 - .5*Math.cos(Math.PI*p)); }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// legs hop sideways to get back under the bowl on the big wobble
|
||||
const HOP = { t: 2.70, d: .19, dx: 26, h: 16 };
|
||||
const hopX = t => HOP.dx*eio((t - HOP.t)/HOP.d);
|
||||
const hopH = t => (t > HOP.t && t < HOP.t + HOP.d) ? HOP.h*Math.sin(Math.PI*(t - HOP.t)/HOP.d) : 0;
|
||||
// crouch before the jump (added straight onto squash)
|
||||
function crouch(t, amt, a, b, hold) {
|
||||
if (t < a || t >= T_L) return 0;
|
||||
if (t < b) return amt * eio((t - a)/(b - a));
|
||||
if (t < hold) return amt;
|
||||
return amt * (1 - eInQ((t - hold)/(T_L - hold)));
|
||||
}
|
||||
const crouchA = t => crouch(t, .17, 3.56, 3.84, 3.91);
|
||||
const crouchB = t => crouch(t, .12, 3.60, 3.86, 3.91);
|
||||
const crouchD = t => crouch(t, .09, 3.64, 3.88, 3.91);
|
||||
|
||||
const PHI_FALL = 5*deg, PSI_FALL = -6*deg, U0 = 12;
|
||||
const ROLL = G.oR/G.dR; // bowl radius is 2x the ball: it turns 1.5x as it rolls
|
||||
const DT = 1/1200, N = Math.ceil((DUR + .2)/DT);
|
||||
const SIG = { phi: new Float32Array(N), u: new Float32Array(N), psi: new Float32Array(N),
|
||||
qA: new Float32Array(N), qB: new Float32Array(N), qD: new Float32Array(N) };
|
||||
|
||||
function peakFactor(w, z) { // peak of a unit-velocity kick
|
||||
const wd = w*Math.sqrt(1 - z*z), ts = Math.atan(wd/(z*w))/wd;
|
||||
return Math.exp(-z*w*ts)*Math.sin(wd*ts)/wd;
|
||||
}
|
||||
const SPR = { A: [40, .32], B: [34, .28], D: [36, .34] };
|
||||
const kick = (k, peak) => peak / peakFactor(SPR[k][0], SPR[k][1]);
|
||||
|
||||
(function simulate() {
|
||||
const K = [];
|
||||
const v1a = archDrop.impacts[0].v, v1b = ballDrop.impacts[0].v, v1d = domeDrop.impacts[0].v;
|
||||
archDrop.impacts.forEach(i => K.push({ t: i.t, k: 'A', dv: kick('A', .13 * i.v/v1a) }));
|
||||
ballDrop.impacts.forEach(i => { const r = i.v/v1b;
|
||||
K.push({ t: i.t, k: 'B', dv: kick('B', .24*r) }); K.push({ t: i.t, k: 'A', dv: kick('A', .06*r) });
|
||||
K.push({ t: i.t, k: 'phi', dv: .55*r }); });
|
||||
domeDrop.impacts.forEach(i => { const r = i.v/v1d;
|
||||
K.push({ t: i.t, k: 'D', dv: kick('D', .11*r) }); K.push({ t: i.t, k: 'B', dv: kick('B', .17*r) });
|
||||
K.push({ t: i.t, k: 'A', dv: kick('A', .07*r) }); });
|
||||
K.push({ t: HOP.t + HOP.d, k: 'A', dv: kick('A', .07) }); K.push({ t: HOP.t + HOP.d, k: 'B', dv: kick('B', .06) });
|
||||
K.push({ t: HOP.t + HOP.d, k: 'D', dv: kick('D', .04) });
|
||||
K.sort((a, b) => a.t - b.t);
|
||||
|
||||
let phi = PHI_FALL, phiV = 0, phiA = 0, u = U0, uV = 0, psi = PSI_FALL, psiV = 0;
|
||||
const q = { A: [0, 0], B: [0, 0], D: [0, 0] };
|
||||
let ki = 0, crossings = 0, lastSign = 1;
|
||||
for (let i = 0; i < N; i++) {
|
||||
const t = i*DT;
|
||||
while (ki < K.length && K[ki].t <= t) {
|
||||
const k = K[ki++];
|
||||
if (k.k === 'phi') phiV += k.dv; else q[k.k][1] += k.dv;
|
||||
}
|
||||
const s = sway(t);
|
||||
// arch rocking on its feet
|
||||
if (t < archDrop.land) { phi = PHI_FALL; phiV = 0; phiA = 0; }
|
||||
else {
|
||||
const w = 20, z = .38, tgt = 5.6*deg*sway(t - .10);
|
||||
phiA = -w*w*(phi - tgt) - 2*z*w*phiV; phiV += phiA*DT; phi += phiV*DT;
|
||||
const sg = Math.sign(phi) || lastSign;
|
||||
if (sg !== lastSign && crossings < 2 && t < 1.0) { q.A[1] += kick('A', .035); crossings++; }
|
||||
lastSign = sg;
|
||||
}
|
||||
// ball rolling along the arch top
|
||||
if (t < ballDrop.rest) { u = U0; uV = 0; }
|
||||
else { const w = 13, z = .5, tgt = 24*sway(t - .12); const a = -w*w*(u - tgt) - 2*z*w*uV; uV += a*DT; u += uV*DT; }
|
||||
// dome: floppy hat with inertia (it lags the body)
|
||||
if (t < domeDrop.land) { psi = PSI_FALL; psiV = 0; }
|
||||
else { const w = 13, z = .22, tgt = 11*deg*s; const a = -w*w*(psi - tgt) - 2*z*w*psiV - .6*phiA; psiV += a*DT; psi += psiV*DT; }
|
||||
// squash springs; falling pieces stretch along their velocity
|
||||
const tgA = archDrop.air(t) ? -Math.min(.12, Math.abs(archDrop.v(t))*4.6e-5) : 0;
|
||||
const tgB = ballDrop.air(t) ? -Math.min(.14, Math.abs(ballDrop.v(t))*6.5e-5) : 0;
|
||||
const tgD = domeDrop.air(t) ? -Math.min(.10, Math.abs(domeDrop.v(t))*4.0e-5) : 0;
|
||||
for (const [k, tg] of [['A', tgA], ['B', tgB], ['D', tgD]]) {
|
||||
const [w, z] = SPR[k]; const st = q[k];
|
||||
const a = -w*w*(st[0] - tg) - 2*z*w*st[1]; st[1] += a*DT; st[0] += st[1]*DT;
|
||||
}
|
||||
SIG.phi[i] = phi; SIG.u[i] = u; SIG.psi[i] = psi;
|
||||
SIG.qA[i] = q.A[0]; SIG.qB[i] = q.B[0]; SIG.qD[i] = q.D[0];
|
||||
}
|
||||
})();
|
||||
const sig = (name, t) => {
|
||||
const x = clamp(t/DT, 0, N - 1.001), i = Math.floor(x), f = x - i, a = SIG[name];
|
||||
return a[i] + (a[i+1] - a[i])*f;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Standing pose: a kinematic chain floor → arch → ball → dome
|
||||
// ------------------------------------------------------------------
|
||||
function standPose(t) {
|
||||
const hA = archDrop.h(t) + hopH(t), hx = hopX(t), phi = sig('phi', t), u = sig('u', t), psi = sig('psi', t);
|
||||
const qA = sig('qA', t) + crouchA(t), qB = sig('qB', t) + crouchB(t), qD = sig('qD', t) + crouchD(t);
|
||||
const hB = ballDrop.h(t), hD = domeDrop.h(t);
|
||||
|
||||
const sxA = 1 + .55*qA, syA = 1 - qA;
|
||||
const side = phi >= 0 ? 1 : -1; // rock on the outer corner of one foot
|
||||
const piv = { x: hx + side*WA*sxA, y: FLOOR - hA };
|
||||
const off = rv(phi, -side*WA*sxA, 0);
|
||||
const A = { x: piv.x + off.x, y: piv.y + off.y };
|
||||
const mA = chain(T(A.x, A.y), R(phi), S(sxA, syA), R(90*deg), T(-ANC.arch.x, -ANC.arch.y));
|
||||
|
||||
const top = rv(phi, u, -HA*syA);
|
||||
const cB = { x: A.x + top.x, y: A.y + top.y - hB };
|
||||
const sxB = 1 + .8*qB, syB = 1 - qB;
|
||||
const mB = chain(T(cB.x, cB.y), R(phi), S(sxB, syB), T(-ANC.ball.x, -ANC.ball.y));
|
||||
const bc = rv(phi, 0, -G.oR*syB), O = { x: cB.x + bc.x, y: cB.y + bc.y };
|
||||
|
||||
// bowl: outer curve resting on the ball, rolling without slipping
|
||||
const ang = phi + psi, dd = rv(ang, 0, -G.oR*syB);
|
||||
const cD = { x: O.x + dd.x, y: O.y + dd.y - hD };
|
||||
const sxD = 1 + .6*qD, syD = 1 - qD;
|
||||
const mD = chain(T(cD.x, cD.y), R(ang), S(sxD, syD), T(0, -G.dR), R(psi*ROLL), R(90*deg), T(-G.dcx, -G.cy));
|
||||
return { arch: mA, ball: mB, dome: mD, O, hA };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Flight: lift-off, unfold around the orb, magnetic clack, hover settle
|
||||
// ------------------------------------------------------------------
|
||||
const FL = { TR: .34, APEX: -108, TC: .44, X: 48, ROT: .40 };
|
||||
const H0 = (() => {
|
||||
const p = standPose(T_L), O = p.O, h = { O };
|
||||
for (const k of ['arch', 'dome']) {
|
||||
const c = ap(p[k], CEN[k]), m = p[k];
|
||||
const fin = { x: CEN[k].x - ORB_C.x, y: 0 };
|
||||
h[k] = { a0: Math.atan2(c.y - O.y, c.x - O.x), r0: Math.hypot(c.x - O.x, c.y - O.y),
|
||||
th0: Math.atan2(m[1], m[0]), aF: k === 'arch' ? Math.PI : 0, rF: Math.abs(fin.x) };
|
||||
}
|
||||
return h;
|
||||
})();
|
||||
const damp = (s, w, z) => { const wd = w*Math.sqrt(1 - z*z); return Math.exp(-z*w*s)*Math.sin(wd*s)/wd; };
|
||||
const fromRest = (x0, s, w, z) => { const wd = w*Math.sqrt(1 - z*z);
|
||||
return Math.exp(-z*w*s)*(x0*Math.cos(wd*s) + (z*w*x0/wd)*Math.sin(wd*s)); };
|
||||
|
||||
function flightPose(t) {
|
||||
const tau = t - T_L, sC = tau - FL.TC;
|
||||
const done = tau > 1.7;
|
||||
let Oy = tau < FL.TR ? H0.O.y + (FL.APEX - H0.O.y)*(1 - (1 - tau/FL.TR)**2)
|
||||
: fromRest(FL.APEX, tau - FL.TR, 9.5, .75);
|
||||
let Ox = H0.O.x*(1 - eio(tau/.4));
|
||||
if (done) { Ox = 0; Oy = 0; }
|
||||
const O = { x: Ox, y: Oy };
|
||||
const st = -Math.sin(Math.PI*clamp(tau/.30))*.085; // stretch on the way up
|
||||
const gs = sC > 0 && !done ? 1 + .05*Math.exp(-6*sC)*Math.sin(20*sC) : 1;
|
||||
const G_ = chain(T(O.x, O.y), S(gs, gs), T(-O.x, -O.y));
|
||||
|
||||
const piece = (k, jsign, kq) => {
|
||||
const h = H0[k];
|
||||
const a = h.a0 + (h.aF - h.a0)*eio(tau/FL.ROT);
|
||||
let r = h.rF + (h.r0 - h.rF)*(1 - smooth(0, .30, tau));
|
||||
r += FL.X*smooth(0, .22, tau)*(1 - eInQ((tau - .30)/(FL.TC - .30)));
|
||||
if (sC > 0 && !done) r += 3.6*Math.exp(-14*sC)*Math.abs(Math.sin(38*sC)); // hard stop, tiny rebound
|
||||
let th = h.th0 + (0 - h.th0)*eio((tau - .02)/FL.ROT);
|
||||
if (done) { r = h.rF; th = 0; }
|
||||
const q = st*kq, c = CEN[k];
|
||||
const C = { x: O.x + r*Math.cos(done ? h.aF : a), y: O.y + r*Math.sin(done ? h.aF : a) };
|
||||
return mul(G_, chain(T(C.x, C.y), S(1 + .6*q, 1 - q), R(th), T(-c.x, -c.y)));
|
||||
};
|
||||
const qb = st*1.1;
|
||||
const ball = mul(G_, chain(T(O.x, O.y), S(1 + .8*qb, 1 - qb), T(-ORB_C.x, -ORB_C.y)));
|
||||
return { arch: piece('arch', 1, .8), dome: piece('dome', -1, .8), ball, O, tau };
|
||||
}
|
||||
|
||||
function pose(t) {
|
||||
t = clamp(t, 0, DUR);
|
||||
const p = t < T_L ? standPose(t) : flightPose(t);
|
||||
// contact shadows
|
||||
const fade = t < T_L ? 1 : 1 - smooth(0, .2, t - T_L);
|
||||
const sh = [];
|
||||
if (fade > 0) {
|
||||
let lowest = Infinity, cx = 0;
|
||||
for (const f of FEET) {
|
||||
const w = ap(p.arch, f), hf = Math.max(0, FLOOR - w.y);
|
||||
lowest = Math.min(lowest, hf); cx += w.x/2;
|
||||
sh.push({ x: w.x, rx: 30 + hf*.35, ry: 5.5 + hf*.05, a: .34*Math.exp(-hf/22)*fade });
|
||||
}
|
||||
sh.unshift({ x: cx, rx: 150 + lowest*.35, ry: 15 + lowest*.03, a: .17*Math.exp(-lowest/210)*fade });
|
||||
}
|
||||
p.shadows = sh;
|
||||
// shock ring when the pieces lock
|
||||
const sC = t - (T_L + FL.TC);
|
||||
p.sC = sC;
|
||||
p.ring = sC > 0 && sC < .8 ? { O: p.O, r: 118 + 210*eOutC(sC/.8), a: .34*(1 - sC/.8)**2, w: 4*(1 - .7*sC/.8) } : null;
|
||||
return p;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Drawing
|
||||
// ------------------------------------------------------------------
|
||||
function makeBG(W, H, noise) {
|
||||
const c = document.createElement('canvas'); c.width = W; c.height = H;
|
||||
const g = c.getContext('2d');
|
||||
const cx = W/2, cy = H*.47, R = Math.hypot(W, H)*.6;
|
||||
const gr = g.createRadialGradient(cx, cy, 0, cx, cy, R);
|
||||
gr.addColorStop(0, TH.bg[0]); gr.addColorStop(.42, TH.bg[1]); gr.addColorStop(1, TH.bg[2]);
|
||||
g.fillStyle = gr; g.fillRect(0, 0, W, H);
|
||||
if (noise) { // static dither: kills banding in the video
|
||||
const id = g.getImageData(0, 0, W, H), d = id.data; let s = 1337;
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
s = (s*1664525 + 1013904223) >>> 0; const n = ((s >>> 24)/255 - .5)*noise;
|
||||
d[i] += n; d[i+1] += n; d[i+2] += n;
|
||||
}
|
||||
g.putImageData(id, 0, 0);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
function draw(ctx, W, H, t, bg) {
|
||||
const px = H/VIEW_H, base = [px, 0, 0, px, W/2, H/2];
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.drawImage(bg, 0, 0, W, H);
|
||||
const p = pose(t);
|
||||
for (const s of p.shadows) {
|
||||
if (s.a < .003) continue;
|
||||
ctx.setTransform(...mul(base, [s.rx, 0, 0, s.ry, s.x, FLOOR]));
|
||||
const g = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
|
||||
const a = Math.min(.9, s.a*TH.shadowK), c = TH.shadow;
|
||||
g.addColorStop(0, `rgba(${c},${a})`); g.addColorStop(.55, `rgba(${c},${a*.45})`); g.addColorStop(1, `rgba(${c},0)`);
|
||||
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(0, 0, 1, 0, Math.PI*2); ctx.fill();
|
||||
}
|
||||
if (p.ring) {
|
||||
ctx.setTransform(...base);
|
||||
ctx.strokeStyle = `rgba(26,159,255,${Math.min(1, p.ring.a*TH.ringA)})`; ctx.lineWidth = p.ring.w;
|
||||
if (TH.ringGlow) { ctx.shadowColor = `rgba(26,159,255,${Math.min(1, p.ring.a*2)})`; ctx.shadowBlur = TH.ringGlow*px; }
|
||||
ctx.beginPath(); ctx.arc(p.ring.O.x, p.ring.O.y, p.ring.r, 0, Math.PI*2); ctx.stroke();
|
||||
ctx.shadowBlur = 0; ctx.shadowColor = 'transparent';
|
||||
}
|
||||
if (TH.glow && p.sC > 0 && p.sC < 1.4) { // dark only: the orb flashes on at lock, light leaks through the halo gap
|
||||
const ga = TH.glow*Math.min(1, p.sC/.03)*Math.exp(-p.sC/.32)*(1 - smooth(1.0, 1.4, p.sC));
|
||||
ctx.setTransform(...base);
|
||||
const g = ctx.createRadialGradient(p.O.x, p.O.y, G.oR*.9, p.O.x, p.O.y, G.oR*2.6);
|
||||
g.addColorStop(0, `rgba(26,159,255,${ga})`); g.addColorStop(.35, `rgba(26,159,255,${ga*.45})`); g.addColorStop(1, 'rgba(26,159,255,0)');
|
||||
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(p.O.x, p.O.y, G.oR*2.6, 0, Math.PI*2); ctx.fill();
|
||||
}
|
||||
ctx.fillStyle = TH.ink;
|
||||
ctx.setTransform(...mul(base, p.arch)); ctx.fill(PATH.arch);
|
||||
ctx.setTransform(...mul(base, p.dome)); ctx.fill(PATH.dome);
|
||||
ctx.fillStyle = ORB;
|
||||
ctx.setTransform(...mul(base, p.ball)); ctx.fill(PATH.orb);
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
}
|
||||
|
||||
// how far (px) things move during an exposure: drives motion-blur sample count
|
||||
const PROBE = { arch: [{x:G.L,y:0},{x:G.L,y:G.B},{x:G.slotL,y:0},{x:G.slotL,y:G.B}],
|
||||
dome: [{x:G.slotR,y:0},{x:G.slotR,y:G.B},{x:176,y:G.cy}],
|
||||
ball: [{x:G.ocx-G.oR,y:G.cy},{x:G.ocx+G.oR,y:G.cy},{x:G.ocx,y:G.cy-G.oR},{x:G.ocx,y:G.cy+G.oR}] };
|
||||
function motionPx(t0, t1, H) {
|
||||
const a = pose(t0), b = pose(t1), px = H/VIEW_H; let m = 0;
|
||||
for (const k of ['arch', 'dome', 'ball']) for (const q of PROBE[k]) {
|
||||
const p0 = ap(a[k], q), p1 = ap(b[k], q); m = Math.max(m, Math.hypot(p1.x - p0.x, p1.y - p0.y));
|
||||
}
|
||||
if (b.ring) m = Math.max(m, Math.abs(b.ring.r - (a.ring ? a.ring.r : 116)));
|
||||
return m*px;
|
||||
}
|
||||
|
||||
// Offline render with real motion blur (180° shutter, adaptive samples)
|
||||
let RC = null;
|
||||
function renderFrame(i, fps = 60, shutter = .5) {
|
||||
const cv = document.getElementById('cv'), W = cv.width, H = cv.height;
|
||||
if (!RC || RC.W !== W || RC.H !== H || RC.theme !== THN) {
|
||||
const ctx = cv.getContext('2d', { willReadFrequently: true });
|
||||
RC = { W, H, theme: THN, ctx, bg: makeBG(W, H, TH.noise), acc: new Uint16Array(W*H*4) };
|
||||
}
|
||||
const t = i/fps, ex = shutter/fps;
|
||||
const t0 = Math.max(0, t - ex/2), t1 = Math.min(DUR, t + ex/2);
|
||||
const n = Math.max(1, Math.min(48, Math.ceil(motionPx(t0, t1, H)/.45)));
|
||||
if (n === 1) { draw(RC.ctx, W, H, t, RC.bg); }
|
||||
else {
|
||||
const acc = RC.acc; acc.fill(0);
|
||||
for (let k = 0; k < n; k++) {
|
||||
draw(RC.ctx, W, H, t0 + (k + .5)/n*(t1 - t0), RC.bg);
|
||||
const d = RC.ctx.getImageData(0, 0, W, H).data;
|
||||
for (let j = 0; j < d.length; j++) acc[j] += d[j];
|
||||
}
|
||||
const out = RC.ctx.createImageData(W, H), o = out.data;
|
||||
for (let j = 0; j < o.length; j++) o[j] = (acc[j] + (n >> 1))/n;
|
||||
RC.ctx.putImageData(out, 0, 0);
|
||||
}
|
||||
return { url: cv.toDataURL('image/png'), samples: n };
|
||||
}
|
||||
|
||||
return { DUR, T_L, HOP, setTheme, get theme() { return THN; }, draw, makeBG, renderFrame, pose, sig, sway, drops: { archDrop, ballDrop, domeDrop },
|
||||
BEATS: [['Drop', .10], ['Wobble', 1.60], ['Jump', 3.56], ['Lock', T_L + FL.TC]],
|
||||
frameCount: fps => Math.round(DUR*fps) + 1, CEN, H0 };
|
||||
})();
|
||||
|
||||
/* =====================================================================
|
||||
Preview player (or bare canvas when ?render=1)
|
||||
===================================================================== */
|
||||
(() => {
|
||||
const qs = new URLSearchParams(location.search);
|
||||
const cv = document.getElementById('cv');
|
||||
if (qs.get('render')) {
|
||||
document.body.classList.add('render');
|
||||
DD.setTheme(qs.get('theme') || 'light');
|
||||
document.body.appendChild(cv);
|
||||
cv.width = +qs.get('w') || 1280; cv.height = +qs.get('h') || 800;
|
||||
cv.style.width = cv.width + 'px'; cv.style.height = cv.height + 'px';
|
||||
return;
|
||||
}
|
||||
const stage = document.getElementById('stage'), ctx = cv.getContext('2d');
|
||||
const scrub = document.getElementById('scrub'), timeEl = document.getElementById('time');
|
||||
const playBtn = document.getElementById('play'), playIcon = document.getElementById('playIcon'), playLabel = document.getElementById('playLabel');
|
||||
const beatsEl = document.getElementById('beats'), fsBtn = document.getElementById('fs');
|
||||
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const sndBtn = document.getElementById('snd'), sndMark = document.getElementById('sndMark'), hint = document.getElementById('hint');
|
||||
let W = 0, H = 0, bg = null, t = reduce ? DD.DUR : 0, playing = !reduce, speed = 1, last = 0, raf = 0;
|
||||
|
||||
// Soundtrack through Web Audio. When it's playing, the audio clock drives the picture.
|
||||
const Sound = (() => {
|
||||
let ctx = null, buf = null, src = null, on = false, pending = null, t0 = 0, c0 = 0, rate = 1;
|
||||
const bytes = () => { const b = atob(DD_SOUND), u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u.buffer; };
|
||||
async function ensure() { // call from a tap: browsers only allow sound after one
|
||||
if (!ctx) { const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return false; ctx = new AC(); }
|
||||
if (ctx.state !== 'running') { try { await ctx.resume(); } catch (e) {} }
|
||||
if (!buf) { pending = pending || new Promise((ok, no) => ctx.decodeAudioData(bytes(), ok, no));
|
||||
try { buf = await pending; } catch (e) { pending = null; return false; } }
|
||||
return ctx.state === 'running';
|
||||
}
|
||||
function stop() { if (src) { try { src.stop(); } catch (e) {} src.disconnect(); src = null; } }
|
||||
function start(at, r) {
|
||||
stop(); if (!on || !buf || !ctx || ctx.state !== 'running' || at >= buf.duration) return;
|
||||
src = ctx.createBufferSource(); src.buffer = buf; src.playbackRate.value = r; src.connect(ctx.destination);
|
||||
c0 = ctx.currentTime; t0 = at; rate = r; src.start(c0, at);
|
||||
}
|
||||
function clock() { return src ? t0 + Math.max(0, ctx.currentTime - c0 - (ctx.outputLatency || 0))*rate : null; }
|
||||
return { ensure, start, stop, clock, get on() { return on; }, set on(v) { on = v; if (!v) stop(); } };
|
||||
})();
|
||||
|
||||
// version: remembered per viewer, otherwise follows the system theme
|
||||
let ver = null; try { ver = localStorage.getItem('dd-version'); } catch (e) {}
|
||||
if (ver !== 'light' && ver !== 'dark') ver = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
function setVersion(v) {
|
||||
ver = v; DD.setTheme(v); stage.classList.toggle('dark', v === 'dark');
|
||||
document.querySelectorAll('.version button').forEach(b => b.setAttribute('aria-pressed', b.dataset.v === v));
|
||||
if (W) bg = DD.makeBG(W, H, 0);
|
||||
try { localStorage.setItem('dd-version', v); } catch (e) {}
|
||||
}
|
||||
document.querySelectorAll('.version button').forEach(b => b.onclick = () => { setVersion(b.dataset.v); render(); });
|
||||
setVersion(ver);
|
||||
function size() {
|
||||
const r = stage.getBoundingClientRect(), dpr = Math.min(window.devicePixelRatio || 1, 2.5);
|
||||
const w = Math.round(r.width*dpr), h = Math.round(r.height*dpr);
|
||||
if (w !== W || h !== H) { W = cv.width = w; H = cv.height = h; bg = DD.makeBG(W, H, 0); }
|
||||
render();
|
||||
}
|
||||
const ICON = { pause: 'M7 5h4v14H7zM13 5h4v14h-4z', play: 'M8 5.5v13l11-6.5z', replay: 'M12 5a7 7 0 1 1-6.6 4.7l1.9.6A5 5 0 1 0 12 7v3L7.5 6 12 2z' };
|
||||
function ui() {
|
||||
const ended = t >= DD.DUR - 1e-6;
|
||||
const mode = playing ? 'pause' : ended ? 'replay' : 'play';
|
||||
playIcon.setAttribute('d', ICON[mode]);
|
||||
playLabel.textContent = mode === 'pause' ? 'Pause' : mode === 'replay' ? 'Replay' : 'Play';
|
||||
playBtn.setAttribute('aria-label', playLabel.textContent);
|
||||
stage.classList.toggle('ended', ended && !playing);
|
||||
hint.textContent = Sound.on ? 'Tap to replay' : 'Turn on Sound to hear it';
|
||||
sndBtn.setAttribute('aria-pressed', Sound.on);
|
||||
sndMark.setAttribute('d', Sound.on ? 'M15.5 9.2a4 4 0 0 1 0 5.6M18.3 6.6a7.6 7.6 0 0 1 0 10.8' : 'M16 9.5l5 5M21 9.5l-5 5');
|
||||
const p = t/DD.DUR; scrub.value = Math.round(p*1000); scrub.style.setProperty('--p', (p*100) + '%');
|
||||
timeEl.textContent = `${t.toFixed(2)} / ${DD.DUR.toFixed(2)}`;
|
||||
let cur = -1; DD.BEATS.forEach((b, i) => { if (t >= b[1]) cur = i; });
|
||||
[...beatsEl.children].forEach((el, i) => el.classList.toggle('on', i === cur));
|
||||
}
|
||||
function render() { if (bg) DD.draw(ctx, W, H, t, bg); ui(); }
|
||||
function loop(now) {
|
||||
raf = 0;
|
||||
if (playing) {
|
||||
const heard = Sound.clock();
|
||||
if (heard !== null) t = Math.min(DD.DUR, heard);
|
||||
else t = Math.min(DD.DUR, t + Math.min(.05, (now - last)/1000)*speed);
|
||||
if (t >= DD.DUR) playing = false;
|
||||
}
|
||||
last = now; render();
|
||||
if (playing) raf = requestAnimationFrame(loop);
|
||||
}
|
||||
function play() {
|
||||
if (t >= DD.DUR - 1e-6) t = 0;
|
||||
playing = true; Sound.start(t, speed); last = performance.now();
|
||||
if (!raf) raf = requestAnimationFrame(loop);
|
||||
}
|
||||
function pause() { playing = false; Sound.stop(); render(); }
|
||||
sndBtn.onclick = async () => {
|
||||
if (Sound.on) { Sound.on = false; ui(); return; }
|
||||
Sound.on = true; ui();
|
||||
if (!(await Sound.ensure())) { Sound.on = false; ui(); return; }
|
||||
t = 0; play(); // replay from the top so it's heard in sync
|
||||
};
|
||||
playBtn.onclick = () => playing ? pause() : play();
|
||||
cv.onclick = () => playing ? pause() : play();
|
||||
scrub.oninput = () => { playing = false; Sound.stop(); t = scrub.value/1000*DD.DUR; render(); };
|
||||
document.querySelectorAll('.speed button').forEach(b => b.onclick = () => {
|
||||
speed = +b.dataset.s; document.querySelectorAll('.speed button').forEach(x => x.setAttribute('aria-pressed', x === b));
|
||||
if (playing) Sound.start(t, speed);
|
||||
});
|
||||
DD.BEATS.forEach(([name, bt]) => {
|
||||
const b = document.createElement('button'); b.className = 'beat'; b.textContent = name;
|
||||
b.style.left = (bt/DD.DUR*100) + '%'; b.onclick = () => { t = bt; play(); };
|
||||
beatsEl.appendChild(b);
|
||||
});
|
||||
addEventListener('keydown', e => {
|
||||
if (e.target.closest('input,button') && e.key !== ' ') return;
|
||||
if (e.key === ' ') { e.preventDefault(); playing ? pause() : play(); }
|
||||
else if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
|
||||
e.preventDefault(); playing = false; Sound.stop(); t = Math.max(0, Math.min(DD.DUR, t + (e.key === 'ArrowRight' ? 1 : -1)/60)); render();
|
||||
}
|
||||
});
|
||||
if (stage.requestFullscreen) {
|
||||
fsBtn.hidden = false;
|
||||
fsBtn.onclick = () => document.fullscreenElement ? document.exitFullscreen() : stage.requestFullscreen().catch(() => {});
|
||||
}
|
||||
new ResizeObserver(size).observe(stage);
|
||||
addEventListener('resize', size);
|
||||
size();
|
||||
if (playing) play();
|
||||
})();
|
||||
</script>
|
||||
<script id="dd-sound">/* soundtrack: MP3, base64. Rebuild with embed_sound.py */
|
||||
const DD_SOUND = /*SOUND*/"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYwLjE2LjEwMAAAAAAAAAAAAAAA//uUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAEJAAGPAAADBggLDhATFhgaHR8iJScqLS8yNDY5Oz5BQ0ZJS01QUlVYWl1gYmVnaWxucXR2eXx+gIOFiIuNkJOVmJqcn6Gkp6msr7Gztri7vsDDxsjLzc/S1Nfa3N/i5Obp6+7x8/b5+/4AAAAATGF2YzYwLjMxAAAAAAAAAAAAAAAAJAXgAAAAAAABjwC+eaeUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//uUZAAP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAETEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xLine truncated
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Embed droiddeck-boot-sound.wav into droiddeck-boot.html (MP3, base64) for the preview page."""
|
||||
import base64, re, subprocess
|
||||
from pathlib import Path
|
||||
here = Path(__file__).parent
|
||||
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(here / "droiddeck-boot-sound.wav"),
|
||||
"-c:a", "libmp3lame", "-b:a", "128k", str(here / "_snd.mp3")], check=True)
|
||||
b64 = base64.b64encode((here / "_snd.mp3").read_bytes()).decode(); (here / "_snd.mp3").unlink()
|
||||
html = (here / "droiddeck-boot.html").read_text()
|
||||
html = re.sub(r'/\*SOUND\*/".*?"/\*END\*/', lambda m: f'/*SOUND*/"{b64}"/*END*/', html, flags=re.S)
|
||||
(here / "droiddeck-boot.html").write_text(html)
|
||||
print(f"embedded {len(b64)/1024:.0f} KB of sound")
|
||||
@@ -0,0 +1,20 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
JS = """(() => {
|
||||
const d = DD.drops, c = (m, q) => ({x: m[0]*q.x + m[2]*q.y + m[4], y: m[1]*q.x + m[3]*q.y + m[5]});
|
||||
const ev = {DUR: DD.DUR, T_L: DD.T_L, LOCK: DD.BEATS[3][1], HOP: DD.HOP,
|
||||
drops: Object.fromEntries(['archDrop','ballDrop','domeDrop'].map(k => [k, {t0: d[k].o.t0, impacts: d[k].impacts}]))};
|
||||
const tr = {t:[], phi:[], u:[], psi:[], ax:[], ay:[], bx:[], by:[], dx:[], dy:[]}, dt = 1/1200;
|
||||
for (let i = 0; i*dt <= DD.DUR + 1e-9; i++) { const t = i*dt, p = DD.pose(t);
|
||||
const a = c(p.arch, DD.CEN.arch), b = c(p.ball, {x: 63.98, y: 111.86}), q = c(p.dome, DD.CEN.dome);
|
||||
tr.t.push(t); tr.phi.push(DD.sig('phi', t)); tr.u.push(DD.sig('u', t)); tr.psi.push(DD.sig('psi', t));
|
||||
tr.ax.push(a.x); tr.ay.push(a.y); tr.bx.push(b.x); tr.by.push(b.y); tr.dx.push(q.x); tr.dy.push(q.y); }
|
||||
ev.tr = tr; return ev; })()"""
|
||||
with sync_playwright() as p:
|
||||
b = p.chromium.launch(); pg = b.new_page()
|
||||
pg.goto(Path(__file__).with_name('droiddeck-boot.html').resolve().as_uri() + '?render=1&w=320&h=200')
|
||||
pg.wait_for_function("typeof DD !== 'undefined'", timeout=15000)
|
||||
ev = pg.evaluate(JS); b.close()
|
||||
json.dump(ev, open('events.json', 'w'))
|
||||
print({k: v for k, v in ev.items() if k != 'tr'})
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render the DroidDeck boot animation to .webm (Steam) or .mp4 (H.264).
|
||||
|
||||
Usage: python3 render.py [WIDTH] [HEIGHT] [FPS] [OUT] [light|dark]
|
||||
python3 render.py 1280 800 60 droiddeck-boot.webm
|
||||
python3 render.py 1920 1080 60 droiddeck-boot.mp4
|
||||
python3 render.py 1280 800 60 droiddeck-boot-dark.webm dark
|
||||
|
||||
Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx-vp9.
|
||||
The animation is drawn by droiddeck-boot.html (same folder); each frame gets real
|
||||
motion blur (180-degree shutter, up to 48 sub-frames when things move fast).
|
||||
"""
|
||||
import base64, os, shutil, subprocess, sys, tempfile, time
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
W = int(sys.argv[1]) if len(sys.argv) > 1 else 1280
|
||||
H = int(sys.argv[2]) if len(sys.argv) > 2 else 800
|
||||
FPS = int(sys.argv[3]) if len(sys.argv) > 3 else 60
|
||||
OUT = sys.argv[4] if len(sys.argv) > 4 else f"droiddeck-boot-{W}x{H}.webm"
|
||||
THEME = sys.argv[5] if len(sys.argv) > 5 else "light" # light | dark
|
||||
ONLY = [int(x) for x in os.environ.get("FRAMES", "").split(",") if x] # debug: render some frames only
|
||||
|
||||
html = Path(__file__).with_name("droiddeck-boot.html").resolve()
|
||||
tmp = Path(os.environ["FRAMEDIR"]) if os.environ.get("FRAMEDIR") else Path(tempfile.mkdtemp(prefix="ddframes_"))
|
||||
tmp.mkdir(parents=True, exist_ok=True) # FRAMEDIR=... makes a long render resumable
|
||||
t0 = time.time()
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch()
|
||||
page = browser.new_page(viewport={"width": W, "height": H})
|
||||
page.goto(f"{html.as_uri()}?render=1&w={W}&h={H}&theme={THEME}")
|
||||
page.wait_for_function("typeof DD !== 'undefined'", timeout=30000)
|
||||
n = page.evaluate(f"DD.frameCount({FPS})")
|
||||
frames = ONLY or range(n)
|
||||
for i in frames:
|
||||
if (tmp / f"f{i:05d}.png").exists() and not ONLY:
|
||||
continue
|
||||
r = page.evaluate(f"DD.renderFrame({i}, {FPS})")
|
||||
(tmp / f"f{i:05d}.png").write_bytes(base64.b64decode(r["url"].split(",", 1)[1]))
|
||||
if i % 30 == 0 or ONLY:
|
||||
print(f"frame {i+1}/{n} blur samples {r['samples']:>2} {time.time()-t0:5.1f}s", flush=True)
|
||||
browser.close()
|
||||
|
||||
if ONLY:
|
||||
print("frames left in", tmp); sys.exit(0)
|
||||
|
||||
COLOR = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv"]
|
||||
SOUND = Path(__file__).with_name("droiddeck-boot-sound.wav") # made by sound.py; muxed in if present
|
||||
cmd = ["ffmpeg", "-y", "-loglevel", "error", "-framerate", str(FPS), "-i", str(tmp / "f%05d.png")]
|
||||
if SOUND.exists():
|
||||
cmd += ["-i", str(SOUND), "-map", "0:v", "-map", "1:a"]
|
||||
cmd += ["-c:a", "aac", "-b:a", "192k"] if OUT.lower().endswith(".mp4") else ["-c:a", "libopus", "-b:a", "160k"]
|
||||
cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int,format=yuv420p"]
|
||||
if OUT.lower().endswith(".mp4"): # H.264 for sharing, previews and anything that won't play webm
|
||||
cmd += ["-c:v", "libx264", "-preset", "slow", "-crf", "15", "-profile:v", "high", "-tune", "animation",
|
||||
"-g", str(FPS * 2), "-movflags", "+faststart"]
|
||||
else: # VP9 webm for Steam's startup movie
|
||||
cmd += ["-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "18", "-deadline", "good", "-cpu-used", "2",
|
||||
"-row-mt", "1", "-g", str(FPS * 2)]
|
||||
cmd += COLOR + ([] if SOUND.exists() else ["-an"]) + [OUT]
|
||||
subprocess.run(cmd, check=True)
|
||||
if not os.environ.get("FRAMEDIR"):
|
||||
shutil.rmtree(tmp)
|
||||
print(f"wrote {OUT} ({os.path.getsize(OUT)/1e6:.2f} MB) in {time.time()-t0:.0f}s")
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env python3
|
||||
"""DroidDeck boot animation: procedural sound design.
|
||||
|
||||
Every sound is synthesized (no samples) and placed on the exact physics events the animation
|
||||
engine reports (events.json, exported by events.py). Key: D major.
|
||||
|
||||
legs (arch) lands on a muted D
|
||||
ball lands on A, the second bounce a quieter echo
|
||||
bowl lands on F#
|
||||
balancing silence
|
||||
jump silence
|
||||
lock a soft landing in the same voice, then all those notes together as the D chord
|
||||
|
||||
Usage: python3 sound.py [events.json] [out.wav]
|
||||
"""
|
||||
import json, sys
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
SR = 48000
|
||||
FPS = 60
|
||||
ev = json.load(open(sys.argv[1] if len(sys.argv) > 1 else 'events.json'))
|
||||
OUT = sys.argv[2] if len(sys.argv) > 2 else 'droiddeck-boot-sound.wav'
|
||||
FRAMES = round(ev['DUR'] * FPS) + 1
|
||||
N = int(np.ceil(FRAMES / FPS * SR)) # exactly the video length
|
||||
rng = np.random.default_rng(20260925)
|
||||
|
||||
# note frequencies
|
||||
def hz(n): return 440.0 * 2 ** ((n - 69) / 12)
|
||||
D2 = 440.0 * 2 ** ((38 - 69) / 12)
|
||||
D3, A3, D4, E4, Fs4, A4, B4, Cs5, D5, E5, Fs5, A5, D6 = [hz(n) for n in (50, 57, 62, 64, 66, 69, 71, 73, 74, 76, 78, 81, 86)]
|
||||
|
||||
# ------------------------------------------------------------------ building blocks
|
||||
def tt(dur): return np.arange(int(dur * SR)) / SR
|
||||
|
||||
def edge(x, a_ms=1.0, r_ms=4.0):
|
||||
"""Click-free start and end."""
|
||||
na, nr = max(1, int(a_ms * SR / 1000)), max(1, int(r_ms * SR / 1000))
|
||||
x[:na] *= np.sin(np.linspace(0, np.pi / 2, na)) ** 2
|
||||
x[-nr:] *= np.cos(np.linspace(0, np.pi / 2, nr)) ** 2
|
||||
return x
|
||||
|
||||
def bp(x, lo, hi, order=2):
|
||||
return signal.sosfilt(signal.butter(order, [lo, min(hi, SR * .45)], 'bandpass', fs=SR, output='sos'), x)
|
||||
|
||||
def lp(x, f, order=2): return signal.sosfilt(signal.butter(order, f, 'lowpass', fs=SR, output='sos'), x)
|
||||
def hp(x, f, order=2): return signal.sosfilt(signal.butter(order, f, 'highpass', fs=SR, output='sos'), x)
|
||||
|
||||
def modal(freqs, decays, amps, dur):
|
||||
t = tt(dur); y = np.zeros_like(t)
|
||||
for f, d, a in zip(freqs, decays, amps):
|
||||
if f < SR * .45: y += a * np.sin(2 * np.pi * f * t) * np.exp(-t / d)
|
||||
return y
|
||||
|
||||
def glide(f0, f1, tau, dur):
|
||||
"""Sine whose pitch moves exponentially from f0 to f1."""
|
||||
t = tt(dur); f = f1 + (f0 - f1) * np.exp(-t / tau)
|
||||
return np.sin(2 * np.pi * np.cumsum(f) / SR)
|
||||
|
||||
def noise_burst(dur, lo, hi, tau):
|
||||
t = tt(dur); return bp(rng.standard_normal(len(t)), lo, hi) * np.exp(-t / tau)
|
||||
|
||||
def pan(x, p):
|
||||
p = np.clip(p, -1, 1); a = (p + 1) * np.pi / 4
|
||||
return np.stack([x * np.cos(a), x * np.sin(a)])
|
||||
|
||||
MIX = np.zeros((2, N))
|
||||
def put(t0, st, gain=1.0):
|
||||
i = int(round(t0 * SR))
|
||||
if i >= N: return
|
||||
j = min(N, i + st.shape[1]); MIX[:, i:j] += gain * st[:, :j - i]
|
||||
|
||||
# ------------------------------------------------------------------ instruments
|
||||
def wood(amp, f0=520, size=1.0, thump=0.0, dur=.35):
|
||||
"""Hard wood / toy-block clack. thump adds body for heavy landings."""
|
||||
r = [1, 1.93, 2.81, 4.13, 5.62]
|
||||
y = modal([f0 * k for k in r], [s * size for s in (.055, .034, .022, .014, .009)], [1, .55, .42, .26, .16], dur)
|
||||
y += .7 * noise_burst(dur, 1400, 7500, .0035)
|
||||
if thump: y += thump * glide(118, 52, .035, dur) * np.exp(-tt(dur) / .075)
|
||||
return edge(y * amp)
|
||||
|
||||
def bonk(amp, f):
|
||||
"""Hollow rubber ball on a board: round pitched body, soft click, tiny board knock."""
|
||||
d = .42; t = tt(d)
|
||||
y = glide(f * 1.28, f, .018, d) * np.exp(-t / (.09 + .05 * amp))
|
||||
y += .22 * glide(f * 2.45, f * 2.3, .02, d) * np.exp(-t / .035)
|
||||
y += .55 * glide(95, 60, .03, d) * np.exp(-t / .045)
|
||||
y += .22 * noise_burst(d, 1800, 5000, .002)
|
||||
y += .25 * wood(1, f0=640, size=.6, dur=d)
|
||||
return edge(y * amp, a_ms=.6)
|
||||
|
||||
def bowl_ring(amp, f=A4, dur=2.4, dscale=1.0):
|
||||
"""Struck metal bowl: inharmonic partials, each split in two for the slow beating shimmer."""
|
||||
t = tt(dur); y = np.zeros_like(t)
|
||||
for k, dec, a, beat in zip((1, 2.71, 5.12, 8.21), tuple(d * dscale for d in (1.25, .62, .3, .15)), (1, .45, .24, .12), (.9, 1.7, 2.6, 3.1)):
|
||||
for s in (-1, 1):
|
||||
y += .5 * a * np.sin(2 * np.pi * (f * k + s * beat / 2) * t + (s > 0) * .8) * np.exp(-t / dec)
|
||||
return edge(y * amp, a_ms=.8, r_ms=30)
|
||||
|
||||
def clonk(amp, ring):
|
||||
d = .5; t = tt(d)
|
||||
y = .8 * glide(160, 92, .03, d) * np.exp(-t / .06) + .45 * wood(1, f0=880, size=.7, dur=d)
|
||||
return edge(y * amp), bowl_ring(ring)
|
||||
|
||||
def marimba(f, amp, damp=1.0):
|
||||
d = 1.2; t = tt(d)
|
||||
tau = .55 * (440 / f) ** .5 * damp
|
||||
y = modal([f, f * 3.93, f * 9.2], [tau, tau * .22, .03], [1, .32, .07], d)
|
||||
y += .05 * lp(rng.standard_normal(len(t)), 2500) * np.exp(-t / .002)
|
||||
return edge(y * amp, a_ms=1.5, r_ms=40)
|
||||
|
||||
def svf_whoosh(env, fc, q=.9):
|
||||
"""Noise through a band-pass whose centre follows fc(t): air moving past a spinning piece."""
|
||||
x = rng.standard_normal(len(env)); y = np.zeros_like(x); ic1 = ic2 = 0.0
|
||||
for i in range(len(x)):
|
||||
g = np.tan(np.pi * min(fc[i], SR * .45) / SR); k = 1 / q
|
||||
a1 = 1 / (1 + g * (g + k)); a2 = g * a1; a3 = g * a2
|
||||
v3 = x[i] - ic2; v1 = a1 * ic1 + a2 * v3; v2 = ic2 + a2 * ic1 + a3 * v3
|
||||
ic1 = 2 * v1 - ic1; ic2 = 2 * v2 - ic2; y[i] = v1
|
||||
return y * env
|
||||
|
||||
def epiano(f, amp, dur=2.8, decay=1.5):
|
||||
"""FM electric piano: bright tine at the strike that mellows as the index falls."""
|
||||
t = tt(dur)
|
||||
idx = 1.7 * np.exp(-t / .22) + .22
|
||||
y = np.sin(2 * np.pi * f * t + idx * np.sin(2 * np.pi * f * t))
|
||||
y += .18 * np.sin(2 * np.pi * f * t + .9 * np.exp(-t / .012) * np.sin(2 * np.pi * 14 * f * t)) * np.exp(-t / .05)
|
||||
return edge(y * np.exp(-t / decay) * amp, a_ms=3, r_ms=60)
|
||||
|
||||
def tock(f, amp, decay=.42, sub=0.0):
|
||||
"""A landing as a muted note in the chord's own FM e-piano voice: felt contact, no pitch bend."""
|
||||
d = 1.5; t = tt(d)
|
||||
idx = 1.3 * np.exp(-t / .07) + .18
|
||||
y = np.sin(2 * np.pi * f * t + idx * np.sin(2 * np.pi * f * t)) * np.exp(-t / decay)
|
||||
y = lp(y, 2600)
|
||||
y += .30 * lp(rng.standard_normal(len(t)), 1600) * np.exp(-t / .0016)
|
||||
if sub: y += sub * np.sin(2 * np.pi * D2 * t) * np.exp(-t / .075)
|
||||
return edge(y * amp, a_ms=1.5, r_ms=80)
|
||||
|
||||
def bell(f, amp, dur=1.6):
|
||||
t = tt(dur)
|
||||
y = np.sin(2 * np.pi * f * t + 1.1 * np.exp(-t / .3) * np.sin(2 * np.pi * 3.5 * f * t)) * np.exp(-t / .7)
|
||||
return edge(y * amp, a_ms=2, r_ms=40)
|
||||
|
||||
# ------------------------------------------------------------------ tracks from the engine
|
||||
tr = {k: np.array(v) for k, v in ev['tr'].items()}
|
||||
TT = tr['t']; dT = TT[1] - TT[0]
|
||||
def at(name, t): return np.interp(t, TT, tr[name])
|
||||
def speed(xk, yk):
|
||||
return np.hypot(np.gradient(tr[xk], dT), np.gradient(tr[yk], dT))
|
||||
X2PAN = 1 / 330 # world units to stereo pan
|
||||
drops = ev['drops']; T_L = ev['T_L']; LOCK = ev['LOCK']; HOP = ev['HOP']
|
||||
events_log = []
|
||||
def log(t, what): events_log.append((round(t, 3), what))
|
||||
|
||||
# ------------------------------------------------------------------ cue sheet
|
||||
# Kept deliberately sparse: one sound per story beat, with silence between them.
|
||||
|
||||
tsamp = np.arange(N) / SR
|
||||
|
||||
# 1. the stack: each piece lands on a muted note of the final chord (D, A, A-echo, F#);
|
||||
# the lock then plays them all together
|
||||
ai = drops['archDrop']['impacts']
|
||||
put(ai[0]['t'], pan(tock(D3, .40, decay=.5, sub=.8), .1)); log(ai[0]['t'], 'legs land: D')
|
||||
|
||||
bi = drops['ballDrop']['impacts']
|
||||
for k, imp in enumerate(bi[:2]):
|
||||
a = .32 * (imp['v'] / bi[0]['v']) ** .9
|
||||
put(imp['t'], pan(tock(A3, a, decay=.36, sub=.3 * a / .32), 0)); log(imp['t'], f'ball: A {a:.2f}')
|
||||
|
||||
di = drops['domeDrop']['impacts']
|
||||
put(di[0]['t'], pan(tock(Fs4, .28, decay=.45, sub=.45), -.05)); log(di[0]['t'], 'bowl lands: F#')
|
||||
|
||||
# 2-3. the balancing act and the jump play in silence: the stack and the lock carry it
|
||||
|
||||
# 4. lock: one snap, then a four-note chord that rings out
|
||||
put(LOCK, pan(tock(D3, .24, decay=.28, sub=.8), 0)); log(LOCK, 'lock: soft landing in the stack voice')
|
||||
for f, a, p, off in ((D3, .24, -.1, 0), (A3, .28, .2, .02), (D4, .30, -.2, .04), (Fs4, .26, .15, .06)):
|
||||
put(LOCK + .018 + off, pan(epiano(f, a, decay=1.3 if f < 300 else 1.1), p))
|
||||
log(LOCK + .018, 'D chord')
|
||||
|
||||
# ------------------------------------------------------------------ room, master
|
||||
def room_ir(dur=1.1, rt60=.75):
|
||||
t = tt(dur); tau = rt60 / 6.9; irs = []
|
||||
for ch in range(2):
|
||||
n = rng.standard_normal(len(t))
|
||||
ir = lp(n, 7000) * np.exp(-t / (tau * .6)) * .5 + lp(n, 2200) * np.exp(-t / tau)
|
||||
ir[:int(.011 * SR)] = 0 # pre-delay
|
||||
for d_ms, g in ((13, .5), (19, .35), (27, .3), (38, .2)):
|
||||
ir[int((d_ms + ch * 1.3) * SR / 1000)] += g
|
||||
irs.append(ir / np.sqrt(np.sum(ir ** 2)))
|
||||
return irs
|
||||
irs = room_ir()
|
||||
wet = np.stack([signal.fftconvolve(MIX[ch], irs[ch])[:N] for ch in range(2)])
|
||||
out = MIX + .14 * wet
|
||||
out = hp(out, 28)
|
||||
fade = np.ones(N); nf = int(.45 * SR); fade[-nf:] = np.cos(np.linspace(0, np.pi / 2, nf)) ** 2
|
||||
out *= fade
|
||||
# gentle peak control: soft-knee compress only the loudest transients, then normalise
|
||||
pk = np.max(np.abs(out)); x = out / pk
|
||||
knee = .5; ax = np.abs(x); over = ax > knee
|
||||
x[over] = np.sign(x[over]) * (knee + (1 - knee) * np.tanh((ax[over] - knee) / (1 - knee)))
|
||||
L0, L1 = int((LOCK + .06) * SR), int((LOCK + .76) * SR)
|
||||
body_rms = np.sqrt(np.mean(x[:, L0:L1].mean(0) ** 2))
|
||||
out = x * (10 ** (-14.9 / 20) / body_rms) # chord body held at the level the team liked (-14.9 dB RMS)
|
||||
assert np.max(np.abs(out)) < 10 ** (-1 / 20), 'would clip'
|
||||
|
||||
import wave
|
||||
pcm = (np.clip(out.T, -1, 1) * 32767).astype('<i2')
|
||||
with wave.open(OUT, 'wb') as w:
|
||||
w.setnchannels(2); w.setsampwidth(2); w.setframerate(SR); w.writeframes(pcm.tobytes())
|
||||
json.dump(sorted(events_log), open('sound_events.json', 'w'), indent=0)
|
||||
print(f'wrote {OUT}: {N / SR:.3f}s, {len(events_log)} cues')
|
||||
for t, w_ in sorted(events_log): print(f' {t:6.3f} {w_}')
|
||||
@@ -0,0 +1,13 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-55.98 0 239.92 223.72" role="img" aria-labelledby="title">
|
||||
<title id="title">DroidDeck split D with a circular orb halo and solid blue orb</title>
|
||||
<defs>
|
||||
<mask id="negative-space" maskUnits="userSpaceOnUse" x="-31.98" y="0" width="207.92" height="223.72">
|
||||
<rect x="-31.98" y="0" width="207.92" height="223.72" fill="#fff"/>
|
||||
<circle cx="63.98" cy="111.86" r="71.81" fill="#000"/>
|
||||
<rect x="56.055" y="0" width="15.83" height="45" fill="#000"/>
|
||||
<rect x="56.055" y="178.72" width="15.83" height="45" fill="#000"/>
|
||||
</mask>
|
||||
</defs>
|
||||
<path fill="#1b1b1b" mask="url(#negative-space)" d="M-31.98 0H63.97c61.84 0 111.96 50.08 111.96 111.86S125.81 223.72 63.97 223.72H-31.98V0Z"/>
|
||||
<circle cx="63.98" cy="111.86" r="55.98" fill="#1A9FFF"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 826 B |
@@ -6,7 +6,7 @@ buildscript {
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:8.8.0'
|
||||
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
|
||||
classpath 'org.jetbrains.kotlin:compose-compiler-gradle-plugin:2.0.21'
|
||||
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.0'
|
||||
classpath 'org.jetbrains.kotlin:compose-compiler-gradle-plugin:2.1.0'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# Agent control
|
||||
|
||||
The debug APK exposes a ContentProvider at `content://com.droiddeck.launcher.agent` and an Activity for starting sessions. Android's shell-only `DUMP` permission protects both. They are absent from release APKs.
|
||||
|
||||
Build and install the debug APK:
|
||||
|
||||
```sh
|
||||
./gradlew assembleDebug --console=plain
|
||||
adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
```
|
||||
|
||||
The provider can also be called directly for state, stop, and resume:
|
||||
|
||||
```sh
|
||||
adb shell content call --uri content://com.droiddeck.launcher.agent --method state
|
||||
adb shell content call --uri content://com.droiddeck.launcher.agent --method stop
|
||||
```
|
||||
|
||||
Start requests go through `tools/droiddeckctl`, which launches the protected debug Activity from the ADB shell. Calling the provider's `start` method directly returns an error because a background provider cannot reliably open the session screen.
|
||||
|
||||
The host CLI resolves one authorized device using `ADB_SERIAL` or `ANDROID_SERIAL` when set. Otherwise it deduplicates transports that report the same device serial and asks for an explicit serial if multiple devices remain.
|
||||
|
||||
```sh
|
||||
tools/droiddeckctl state --json
|
||||
tools/droiddeckctl start steam
|
||||
tools/droiddeckctl wait ready --timeout 90
|
||||
tools/droiddeckctl start desktop
|
||||
tools/droiddeckctl run /usr/bin/foo -- arg1 arg2
|
||||
tools/droiddeckctl stop
|
||||
tools/droiddeckctl resume
|
||||
tools/droiddeckctl logs latest ./session-artifacts
|
||||
tools/droiddeckctl screenshot ./screen.png
|
||||
```
|
||||
|
||||
Every command writes JSON to stdout and reports its resolved ADB serial to stderr. Exit codes are 0 for success, 2 for invalid or rejected commands, 3 for ADB/device errors, 4 for session failures, 5 for timeouts, and 6 for artifact or file errors. Set `ADB` to select an adb executable (or pass `--adb`); pass `--serial` before the command to select a device directly.
|
||||
|
||||
`start` accepts `steam` or `desktop`. Steam starts in Big Picture by default; `--ui desktop` selects the client's desktop UI, and `--url steam://...` passes a client URL. Use `--wait` to wait for `READY` as part of `start`. `run` accepts a program path and optional guest arguments.
|
||||
|
||||
The `state` response uses schema 1 and includes the build label, runtime version, session ID and phase, mode, requested program, suspend and first-frame state, output size, guest PID, failure details, and artifact paths. Phases are `IDLE`, `PREPARING`, `INSTALLING_RUNTIME`, `STARTING_COMPOSITOR`, `STARTING_GUEST`, `STARTING_STEAM`, `READY`, `SUSPENDED`, `STOPPING`, and `FAILED`. Each session also writes `events.jsonl` alongside its existing artifacts.
|
||||
|
||||
`tools/deploy_local.sh` uses the same device resolver. If multiple distinct devices are connected, select one with `ADB_SERIAL` or `ANDROID_SERIAL`.
|
||||
@@ -7,6 +7,115 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d
|
||||
|
||||
---
|
||||
|
||||
## 2026-09-25 - main `8cdedbe`: melonDS out of the box, touch in Big Picture, log privacy, Decky
|
||||
|
||||
State: **main = `8cdedbe`** (PR #22 merge). Device-tested on the AYANEO Pocket FIT (repacked test builds)
|
||||
unless marked. gamescope now staged from release **`gamescope-3.16.29-p3`**.
|
||||
|
||||
- **PR #18 → `9369dc3`** (`feat/melonds-preset`) - melonDS and the session:
|
||||
- **melonDS preset** (`bannerlator-pad-defaults`): the top screen as big as the panel allows with the bottom
|
||||
screen alone beside it, centred (Horizontal + Emphasize top; Hybrid repeats the top screen), sharp pixels;
|
||||
full screen from the front end (`-f`) at the panel's own resolution; the guide button toggles full
|
||||
screen, leaving to a 1x-wide 16:9 window whose menus gamescope stretches to a usable size; DS/DSi BIOS,
|
||||
firmware and NAND found in `ROMs/nds/{bios,firmware}` (BIOS by checksum). Existing installs moved once.
|
||||
- **Desktop**: `QT_QPA_PLATFORM="wayland;xcb"` (the melonDS AppImage ships only xcb and exited at once);
|
||||
a labwc window rule opens melonDS at 800x600, centred.
|
||||
- **HUD** follows the game window, not gamescope's 1x1 cursor or Qt menus (read 0 fps at 60).
|
||||
- **Cursor**: hides on pad / on-screen-control input (Bannerlator's 1.2 s rule), and shows the program's own
|
||||
shape - labwc's resize arrows, I-beams, a hide (Bannerlator's `wl_pointer.set_cursor` port; new here:
|
||||
labwc's GPU cursor is a UBWC dma-buf, read back through `vkp_image_readback`).
|
||||
- **Steam desktop switching**: "Steam Desktop UI" opens the desktop with Steam's desktop client in it (under
|
||||
gamescope the client picks Big Picture regardless); the drawer's **DESKTOP** button does it from Big
|
||||
Picture; relaunches restart the singleTop activity in place (`startActivity` from it was swallowed).
|
||||
Big Picture's own Power → Switch to Desktop still hangs: it waits on SteamOS Manager before its
|
||||
`steamos-session-select` fallback (stub included; a session bus did not help - tried and reverted).
|
||||
- **PR #19 → `ce0da01`** (`fix/log-privacy`) - no credentials or identities in session logs: the device's
|
||||
public addresses (the client's IPv6 check logs "external address" ~20x a session), `network.txt` addresses
|
||||
as their kind and the MAC masked, every Steam AccountName/PersonaName (plain account names leaked in the
|
||||
UI log's login lines), and every text file scrubbed at session end and in the share-logs zip. Verified:
|
||||
0 hits across 83 session folders.
|
||||
- **PR #16 → `5270574`** (Decky Loader, Kurt) - merged with the Steam CEF debugging marker tied to the
|
||||
supervisor toggle (it was created at install; on Android any app can reach 127.0.0.1:8080 - proven from
|
||||
another uid). Decky's own updater still points at the official project (no ARM64 build there).
|
||||
- **PR #20 → `036317f`** (Kurt) - local builds carry the CI payload (NDK proot, patched gamescope).
|
||||
- **PR #22 → `8cdedbe`** (`feat/steam-touch`) - touch in Big Picture: gamescope `0110` binds `wl_touch` in the
|
||||
nested backend and feeds wlserver's touch path (Big Picture sets Passthrough: tap and swipe rows as on a
|
||||
Deck); `0111` makes the nested pointer warp in Passthrough (touchpad mode: hover and tap-to-click work);
|
||||
the compositor's pointer fallback no longer jams on a lost finger-up.
|
||||
- **In design, not built**: the drawer's page dots as QAM-style icons (Display / Controls / Settings), the
|
||||
selected one "stepping forward" in a line; mock `droiddeck-drawer-tabs-preview.html`.
|
||||
|
||||
## 2026-09-24 (afternoon) - main `94f9935`: PS1, controller focus, own signing key, CI hardening
|
||||
|
||||
State: **main = `94f9935`** (PR #41 merge), main build run 36036219740 - the first one signed with
|
||||
DroidDeck's own key (`droiddeck-signed-standard`). No tag, no release since 0.1.6. Device-tested on
|
||||
the AYANEO Pocket FIT unless marked. **main is now protected** (below).
|
||||
|
||||
- **PR #34 → `63d7051`, PR #38 → `c7998a8`** (`feat/duckstation`, `feat/duckstation-play`) - PS1 and the front end:
|
||||
- **DuckStation like ARMSX2**: Player 1 on the controller, BIOS from `ROMs/psx/bios`, `psx` as the game
|
||||
list, Vulkan, guide → pause menu, `-batch -bigpicture -fullscreen` from the rail. Crash Bandicoot and
|
||||
Tekken 3 at 60 fps from the desktop and from the front end.
|
||||
- **One tap to play**: DuckStation's and ARMSX2's first-time setup is answered for the user
|
||||
(`SetupWizardIncomplete = false`); ARMSX2 names its BIOS dump itself (`[Filenames] BIOS`, a US dump
|
||||
first, re-checked before every launch) - PCSX2 needs a named file, DuckStation finds one in its folder.
|
||||
DuckStation no longer warns it cannot inhibit a screensaver (no `org.freedesktop.ScreenSaver` here).
|
||||
- **One tile per disc**: a `.cue`/`.gdi`/`.m3u` hides the files it names (Tekken 3 showed 4×, one per
|
||||
`(Track N).bin`); `bios`/`firmware` folders are skipped (the BIOS showed as a game).
|
||||
- **Controller focus**: the rail item is outlined on open (an app starts in touch mode, where clickables
|
||||
refuse focus - the app now asks for keyboard mode first); Right enters a page on its main button,
|
||||
Left from the page's edge returns to the rail, Right again returns to the tile or button last used
|
||||
(explicit tracking - `FocusRequester.saveFocusedChild` restored into the grid, not the tile); a page
|
||||
opened from a tile takes focus on its main button (focus used to vanish with the tile and the next
|
||||
press landed on Steam); Down from a page's buttons goes to the first tile.
|
||||
- **PR #41 → `94f9935`** (`feat/release-signing`) - signing, file access, hardening before going public:
|
||||
- **Own signing key** (RSA 4096, made on device by `tools/release/make-release-key.sh`, digest
|
||||
`b241ea7d…5d3f0` in `keystore/release-signer.sha256`). Every build before it - 0.1.6 included - was
|
||||
signed with the public AOSP testkey, so anyone could sign an "update" that installs over DroidDeck.
|
||||
- **Hand-over** (APK Signature Scheme v3 rotation): v1/v2 by the testkey, v3 by our key with a lineage
|
||||
testkey → ours, testkey rollback off, `--rotation-min-sdk-version 28`. Proven on the FIT with a throwaway
|
||||
key and package: a 0.1.6-style install updates and keeps its data; an apk signed with the testkey alone
|
||||
is refused; so is one with an attacker's own lineage from the testkey; an apk signed with our key alone
|
||||
(what MT Manager / APK Tool M make) installs over a hand-over install and fresh, not over a testkey one.
|
||||
- **CI**: `sign.yml` (reusable, a matrix job per package) runs after every non-pull-request build
|
||||
(environment `signing-main` on main, `signing-branch` elsewhere; the key is an environment secret).
|
||||
`release.yml` (dispatch, version) signs the exact Build APK artifact of a main commit as four packages:
|
||||
`com.droiddeck.launcher`, `com.tencent.ig`, `com.antutu.benchmark.full`, `com.ludashi.benchmark`
|
||||
(`tools/release/variants.txt`; the manifest rename also covers `.documents` and the `.home` task affinity).
|
||||
- **Documents provider** (`files/AppFilesProvider.kt`): the app's data folder in Android's file picker
|
||||
("Open from" → DroidDeck, per-package title), confined to the data folder (a `../` id is refused, links
|
||||
out of it are hidden), and deleting never follows a link.
|
||||
- **Hardening**: pull requests build with `pull_request`, not `pull_request_target` (a pull request could
|
||||
write the caches main's signed builds restore); a build fails if a private key file is committed;
|
||||
`.gitignore` covers key files; **main is protected** - pull request + passing `build` + one approval,
|
||||
no force-push or deletion, the owner can override for his own pull requests. History scanned before
|
||||
going public: no secrets.
|
||||
- Max and Kurt get the key (jks, p12, pk8 + x509.pem, lineage) with a password and three plain guides
|
||||
(MT Manager / APK Tool M signing, the hand-over, how pull requests / test builds / releases work).
|
||||
- **Also merged today** (Kurt): #20 Back shortcuts (session menu, Steam QAM), #24 build identity on the
|
||||
launcher, #33 per-launch Android display choice, #35 CI build-cleanliness snapshot, #37 the split-D logo,
|
||||
#40 faster held-stick navigation in the session drawer; (The412Banner) #32 stretch games to fill the
|
||||
screen, Quake-engine titles windowed at the session's size.
|
||||
|
||||
## 2026-09-24 - main `08a6769`: GPU desktop, emulators like PS3, ARMSX2, game art
|
||||
|
||||
State: **main = `08a6769`** (PR #29 merge), main build run 35983098806, staged as `Download/DroidDeck-main-08a6769(-Genshin).apk`. No tag, no release since 0.1.6. **Device-tested on the AYANEO Pocket FIT** (Adreno 750) unless marked.
|
||||
|
||||
- **PR #25 → `f6f7470`** (`feat/desktop-gpu`) - the desktop on the GPU:
|
||||
- **Patched wlroots** (`tools/wlroots`, release `wlroots-0.20.2-p1`, staged at `/usr/local/lib/droiddeck-wlroots`): a Vulkan DMA-BUF allocator for the KGSL stand-in node, which is not a DRM device - stock wlroots failed at `drmModeCreateLease` → "unable to create allocator"; linux-dmabuf skips its GEM import check on such a node. labwc's **vulkan** and **gles2** renderers start; **vulkan is the default**.
|
||||
- Compositor: a toplevel's **initial commit is answered with a configure** (labwc on vulkan waited for ever - wlroots moves its toplevel to a private queue after that commit); **`xdg_positioner` / `xdg_popup` / `wl_output` requests no longer abort** the app (NULL implementations; a gamescope beside labwc took the app down); without a Wine desktop a new window takes the keys.
|
||||
- Fallback: labwc that exits or does not answer its socket within 20 s → pixman, remembered per renderer + wlroots md5 + driver (`~/.droiddeck-renderer-failed`, cleared by choosing a renderer). On pixman, Game/Emulator menu entries run through `droiddeck-gpu` (their own gamescope on wayland-0).
|
||||
- Emulators: the pad is a plain Xbox 360 controller outside Steam (SDL ignores Steam's virtual gamepad outside Steam); `bannerlator-pad-defaults` seeds Player 1 per emulator (source-verified formats) and never overwrites a user's profile; big-core pinning (`program_cores`, game cores when chosen); rail programs use the desktop's Linux driver (one shader cache); RPCS3 moved once to `Async Recompiler (multi-threaded)` (no 6650-variant interpreter precompile each boot).
|
||||
- **PC keyboard** (drawer: Keyboard [Hardware] [Android]): Esc, F1-F12, editing block, modifiers (sticky), arrows; real evdev key presses; 47% of the screen.
|
||||
- Proven: Vulkan and gles2 desktops, Firefox on Vulkan, RPCS3 God of War II HD in a window and from the rail (pad bound, no precompile, cores 2-7), pixman fallback path, Steam session.
|
||||
- **PR #26 → `6980428`** (`feat/armsx2`) - **PS2 is ARMSX2** (PCSX2 fork with ARM64 recompilers, GPL-3.0). Upstream PCSX2 only has `pcsx2/arm64/RecStubs.cpp`: NFS Underground 2 ran at 17 fps with one core at 100%; ARMSX2 runs it at **59.9 fps / 100%**, all recompilers + fastmem on under proot. PCSX2 left the front end and the catalog.
|
||||
- **PR #29 → `08a6769`** (`feat/armsx2-polish`):
|
||||
- ARMSX2 from the rail: `-batch -bigpicture -fullscreen`; guide → pause menu → Close Game returns to the app. First run: PCSX2 settings + memory cards copied once; a new player gets ARMSX2's setup with the BIOS folder in `ROMs/ps2/bios` (or `ps2/firmware`), `ps2` as game list, Vulkan, controller on Player 1. Users bring their own BIOS and games.
|
||||
- Catalog `pages` - a file per memory page size; ARMSX2 4K + 16K.
|
||||
- On-screen controls: Auto for rail games and Steam when no controller, off on the desktop; setting in the drawer everywhere; drawer headed by the emulator for rail games.
|
||||
- Front end: Back/B steps back a level (emulator → Desktop, game → emulator) instead of leaving the app; games found up to 3 folders deep (`ps2/games/<game>/`); **box art** (libretro-thumbnails by name exact/loose, xlenore/ps2-covers by PS2 serial, GameTDB by GC/Wii ID, PS3 discs' own `ICON0.PNG`), kept in `files/covers`; wide art shown whole over a blurred copy; titles without dump tags.
|
||||
- **winlator-contents** (the catalog): ARMSX2 `nightly-20260923-92aa2174da` mirrored (`armsx2.AppImage` 4K, `armsx2-16k.AppImage`), PCSX2 dropped from `desktop.json` (PRs #12, #13); the mirror workflow lists only the file being added (a re-run re-fetches and clobbers every listed file, and DuckStation's upstream link moves).
|
||||
- **Not yet device-played**: DuckStation, Dolphin, Cemu, melonDS, PPSSPP, RetroArch (profiles + covers written from their sources). Known gap: a keyboard's Esc does not open ARMSX2's pause menu in a rail game (guide does).
|
||||
|
||||
## 2026-09-23 (evening) - renamed SteamDeck → DroidDeck
|
||||
|
||||
- **App name, app ID and code package**: DroidDeck, `com.droiddeck.launcher` (was `com.steamdeck.launcher`), sources under `app/src/main/java/com/droiddeck/launcher`, the 68 JNI functions renamed with them. A new app ID means DroidDeck installs **beside** SteamDeck, not over it: the runtime, the Steam sign-in and the settings start fresh.
|
||||
@@ -191,13 +300,43 @@ State: **main = `90c7574`** (PR #14 merge), main build run 35895701784. No tag,
|
||||
- Bannerlator's File Manager ports mechanically (`port_fm.py` anchors) once the container hooks
|
||||
are cut; do not hand-edit 2,500 lines.
|
||||
- Deleting a release asset on GitHub can drop a sibling asset - re-list and restore.
|
||||
- A resource without an implementation makes libwayland abort on its first request - every
|
||||
interface the compositor hands out needs one, even as no-ops (positioner, popup, output).
|
||||
- The KGSL stand-in answers no DRM ioctl: `drmIsMaster()` reads that as "master"; check
|
||||
`drmGetVersion()` before treating a GPU fd as DRM.
|
||||
- Verify an emulator's config values from its source: RPCS3's GUI says "Async Shader Recompiler",
|
||||
the config value is "Async Recompiler (multi-threaded)".
|
||||
- Upstream PCSX2 has no ARM64 recompiler; a correct ARM64 build of it is still interpreter-slow.
|
||||
- An Android app starts in touch mode, where Compose clickables refuse focus: `requestFocus()` on open
|
||||
does nothing until the app asks for keyboard input mode.
|
||||
- `grep -q` (or `head`) at the end of a pipe exits early; under `pipefail` that fails the whole line at
|
||||
random. Capture the output first, then search it.
|
||||
- A reusable workflow gets no more permission than its caller gives, and sees environment secrets only
|
||||
with `secrets: inherit`. A workflow naming an environment that does not exist creates it unprotected.
|
||||
- `pull_request_target` shares main's caches with the pull request's code - never with signed builds.
|
||||
- apksigner prints signers as "Signer #1", "Signer (minSdkVersion=…)" or "V3.0 Signer:" by version.
|
||||
|
||||
## Backlog / next
|
||||
- Play-test the other emulators one by one on the FIT: Dolphin, Cemu, melonDS, PPSSPP, RetroArch
|
||||
(pad profiles and covers exist; nothing played yet). DuckStation done 2026-09-24.
|
||||
- **Kurt's PR #39 (Non-Launcher flavor) breaks signing as written**: it replaces the `droiddeck-apk`
|
||||
artifact with `droiddeck-home-apk` / `droiddeck-non-launcher-apk`, which `sign.yml` and `release.yml`
|
||||
read, and it conflicts with today's `build.yml`. Adapt before merging: sign both editions (a release
|
||||
would then be editions × packages).
|
||||
- After the repo is public: add a required reviewer to the `release` environment (not allowed on a
|
||||
private repo on the Pro plan).
|
||||
- First release with the new key (0.1.7): run `release.yml`, publish; 0.1.6 users move over by the
|
||||
hand-over.
|
||||
- Keyboard Esc in a rail game does not reach ARMSX2's pause menu (guide does).
|
||||
- 0.1.7 pre-release when ready (everything above is on main only).
|
||||
- Pin a newer ARMSX2 nightly only after testing it (it changes daily).
|
||||
- Device-prove 0.1.4 on the FIT (list above).
|
||||
- Thor Pro: trackpad tap; the 1–2 min in-game crash once a `crash.log` arrives.
|
||||
- Xfce as a second desktop shell (Max's branch runs XFCE 4.20 on labwc) - a catalog package + a
|
||||
shell choice in the Desktop cog; comfort, not performance.
|
||||
- Quick Access Menu for non-Deck pads - no confirmed chord; needs research, not a guess.
|
||||
- Quick Access Menu for non-Deck pads - Back double-press (500 ms) now routes to the existing Guide+A
|
||||
chord; the in-session menu, Steam settings, and Setup › Session can swap the single- and double-Back
|
||||
actions. Device confirmation is still needed.
|
||||
- FlatOut shrink: try `vk_wsi_force_swapchain_to_current_extent=false` via `steamdeck-env`.
|
||||
- Max's stricter `winnative-directaudio` guards; `winnative-epic-launch` (a feature).
|
||||
- Rename before anything truly public: "SteamDeck" is Valve's mark.
|
||||
- Rename before anything truly public: "SteamDeck" is Valve's mark. (Done 2026-09-23: DroidDeck.)
|
||||
@@ -1,8 +1,5 @@
|
||||
org.gradle.jvmargs=-Xmx4096m -Dfile.encoding=UTF-8
|
||||
# CI is the only thing that builds this repo and its minutes are billed, so every cache Gradle
|
||||
# offers is on: task outputs are reused across runs from the cache the CI action restores, the
|
||||
# configuration phase is skipped when nothing about the build scripts changed, and independent
|
||||
# tasks run together.
|
||||
# Reuse task outputs, skip unchanged configuration, and run independent tasks in parallel.
|
||||
org.gradle.caching=true
|
||||
org.gradle.configuration-cache=true
|
||||
org.gradle.parallel=true
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
b241ea7d77822d39b89d3227e06f3ecf62adec6cbfd38ad06196787991b5d3f0
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resolve one authorized Android device, collapsing transports for the same device."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
class DeviceResolutionError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _run(adb: str, *args: str, timeout: int = 15) -> subprocess.CompletedProcess[str]:
|
||||
try:
|
||||
return subprocess.run(
|
||||
[adb, *args], capture_output=True, text=True, check=False, timeout=timeout
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise DeviceResolutionError(str(exc)) from exc
|
||||
|
||||
|
||||
def _device_list(adb: str) -> list[str]:
|
||||
result = _run(adb, "devices", "-l")
|
||||
if result.returncode != 0:
|
||||
raise DeviceResolutionError(result.stderr.strip() or "adb devices failed")
|
||||
devices = []
|
||||
for line in result.stdout.splitlines()[1:]:
|
||||
fields = line.split()
|
||||
if len(fields) >= 2 and fields[1] == "device":
|
||||
devices.append(fields[0])
|
||||
return devices
|
||||
|
||||
|
||||
def _identity(adb: str, serial: str) -> str | None:
|
||||
for prop in ("ro.serialno", "ro.boot.serialno"):
|
||||
result = _run(adb, "-s", serial, "shell", "getprop", prop)
|
||||
value = result.stdout.strip()
|
||||
if result.returncode == 0 and value and value.lower() not in {"unknown", "null", "0"}:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _rank(serial: str) -> tuple[int, str]:
|
||||
# Prefer a stable mDNS transport over a network address with an ephemeral port.
|
||||
if "_adb-tls-connect._tcp" in serial:
|
||||
return (0, serial)
|
||||
if not re.search(r":\d+$", serial):
|
||||
return (1, serial)
|
||||
return (2, serial)
|
||||
|
||||
|
||||
def resolve_serial(adb: str, explicit: str | None = None, *, log: bool = False) -> str:
|
||||
selected = explicit or os.environ.get("ADB_SERIAL") or os.environ.get("ANDROID_SERIAL")
|
||||
if selected:
|
||||
result = _run(adb, "-s", selected, "get-state")
|
||||
if result.returncode != 0 or result.stdout.strip() != "device":
|
||||
raise DeviceResolutionError(f"ADB serial '{selected}' is not an authorized device")
|
||||
serial = selected
|
||||
else:
|
||||
devices = _device_list(adb)
|
||||
if not devices:
|
||||
raise DeviceResolutionError("No authorized Android device found; set ADB_SERIAL or ANDROID_SERIAL")
|
||||
identities = {device: _identity(adb, device) for device in devices}
|
||||
groups: dict[str, list[str]] = {}
|
||||
for device in devices:
|
||||
identity = identities[device]
|
||||
key = f"device:{identity}" if identity else f"transport:{device}"
|
||||
groups.setdefault(key, []).append(device)
|
||||
if len(groups) != 1:
|
||||
detail = ", ".join(
|
||||
f"{device}" + (f" (serial {identities[device]})" if identities[device] else "")
|
||||
for device in devices
|
||||
)
|
||||
raise DeviceResolutionError(
|
||||
f"Multiple Android devices found ({detail}); set ADB_SERIAL or ANDROID_SERIAL"
|
||||
)
|
||||
aliases = next(iter(groups.values()))
|
||||
serial = min(aliases, key=_rank)
|
||||
if log and len(aliases) > 1:
|
||||
print(f"Collapsed {len(aliases)} ADB transports for one device.", file=sys.stderr)
|
||||
|
||||
if log:
|
||||
print(f"Resolved ADB serial: {serial}", file=sys.stderr)
|
||||
return serial
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--adb", default=os.environ.get("ADB", "adb"))
|
||||
parser.add_argument("--serial", help="Explicit ADB serial; defaults to ADB_SERIAL or ANDROID_SERIAL")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
print(resolve_serial(args.adb, args.serial, log=True))
|
||||
return 0
|
||||
except DeviceResolutionError as exc:
|
||||
print(f"adb-device: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -2,6 +2,15 @@
|
||||
set -euo pipefail
|
||||
|
||||
repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
if tree_status=$(git -C "${repo_root}" status --porcelain 2>/dev/null); then
|
||||
if [[ -n "${tree_status}" ]]; then
|
||||
export DROIDDECK_BUILD_TREE_STATE=dirty
|
||||
else
|
||||
export DROIDDECK_BUILD_TREE_STATE=clean
|
||||
fi
|
||||
else
|
||||
export DROIDDECK_BUILD_TREE_STATE=unknown
|
||||
fi
|
||||
sdk_dir=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-"${HOME}/Library/Android/sdk"}}
|
||||
java_dir=${JAVA_HOME:-"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"}
|
||||
image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v2}
|
||||
@@ -18,6 +27,66 @@ if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "Docker is required to cross-compile the glibc ARM64 preload libraries." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in curl tar zstd shasum unzip; do
|
||||
if ! command -v "${tool}" >/dev/null 2>&1; then
|
||||
echo "${tool} is required to build the CI-equivalent APK." >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [[ -f "${repo_root}/tools/gamescope/release.env" || -f "${repo_root}/tools/wlroots/release.env" ]] \
|
||||
&& ! command -v gh >/dev/null 2>&1; then
|
||||
echo "GitHub CLI is required to download the pinned Gamescope and wlroots release assets." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ndk_version=${DROIDDECK_NDK_VERSION:-}
|
||||
if [[ -z "${ndk_version}" ]]; then
|
||||
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
|
||||
ndk_version=${ndk_path##*/}
|
||||
fi
|
||||
if [[ -z "${ndk_version}" || ! -d "${sdk_dir}/ndk/${ndk_version}" ]]; then
|
||||
echo "No Android NDK found under ${sdk_dir}/ndk; set DROIDDECK_NDK_VERSION." >&2
|
||||
exit 1
|
||||
fi
|
||||
export ANDROID_HOME="${sdk_dir}"
|
||||
export ANDROID_SDK_ROOT="${sdk_dir}"
|
||||
export JAVA_HOME="${java_dir}"
|
||||
export NDK="${sdk_dir}/ndk/${ndk_version}"
|
||||
|
||||
staging_dir=$(mktemp -d "${TMPDIR:-/tmp}/droiddeck-build.XXXXXX")
|
||||
bundle_asset="${repo_root}/app/src/main/assets/pulseaudio.tzst"
|
||||
bundle_backup="${staging_dir}/pulseaudio.original.tzst"
|
||||
bundle_replaced=0
|
||||
linuxfs_dir="${repo_root}/app/src/main/assets/linuxfs"
|
||||
linuxfs_backup="${staging_dir}/linuxfs.original"
|
||||
linuxfs_preexisting=0
|
||||
linuxfs_replaced=0
|
||||
cleanup() {
|
||||
local exit_code=$?
|
||||
trap - EXIT
|
||||
if [[ "${bundle_replaced}" == 1 ]]; then
|
||||
cp -p "${bundle_backup}" "${bundle_asset}" || exit_code=1
|
||||
fi
|
||||
if [[ "${linuxfs_replaced}" == 1 ]]; then
|
||||
rm -rf -- "${linuxfs_dir}" || exit_code=1
|
||||
if [[ "${linuxfs_preexisting}" == 1 ]]; then
|
||||
mv "${linuxfs_backup}" "${linuxfs_dir}" || exit_code=1
|
||||
fi
|
||||
fi
|
||||
rm -rf -- "${staging_dir}" || exit_code=1
|
||||
exit "${exit_code}"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
if [[ -d "${linuxfs_dir}" ]]; then
|
||||
cp -a "${linuxfs_dir}" "${linuxfs_backup}"
|
||||
linuxfs_preexisting=1
|
||||
fi
|
||||
linuxfs_replaced=1
|
||||
rm -rf -- "${linuxfs_dir}"
|
||||
mkdir -p "${linuxfs_dir}"
|
||||
|
||||
if ! docker image inspect "${image_name}" >/dev/null 2>&1; then
|
||||
docker build --platform linux/amd64 -t "${image_name}" \
|
||||
@@ -40,7 +109,12 @@ docker run --rm --platform linux/amd64 \
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$d/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
|
||||
[ -f "$f" ] && install -Dm644 "$f" "$d/${f#tools/linuxfs/overlay/}"
|
||||
done
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/autostart "$d/etc/xdg/labwc/autostart"
|
||||
install -Dm644 tools/linuxfs/desktop/rc.xml "$d/etc/xdg/labwc/rc.xml"
|
||||
install -Dm644 tools/linuxfs/desktop/panel.conf "$d/etc/xdg/lxqt/panel.conf"
|
||||
@@ -73,42 +147,56 @@ docker run --rm --platform linux/amd64 \
|
||||
test -f "$d/usr/local/bin/bannerlator-proton-extra"
|
||||
'
|
||||
|
||||
export ANDROID_HOME="${sdk_dir}"
|
||||
export ANDROID_SDK_ROOT="${sdk_dir}"
|
||||
export JAVA_HOME="${java_dir}"
|
||||
ndk_version=${DROIDDECK_NDK_VERSION:-}
|
||||
if [[ -z "${ndk_version}" ]]; then
|
||||
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
|
||||
ndk_version=${ndk_path##*/}
|
||||
fi
|
||||
if [[ -z "${ndk_version}" || ! -d "${sdk_dir}/ndk/${ndk_version}" ]]; then
|
||||
echo "No Android NDK found under ${sdk_dir}/ndk; set DROIDDECK_NDK_VERSION." >&2
|
||||
exit 1
|
||||
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
|
||||
if [[ -z "${github_repo}" ]]; then
|
||||
origin_url=$(git -C "${repo_root}" remote get-url origin)
|
||||
case "${origin_url}" in
|
||||
https://github.com/*) github_repo=${origin_url#https://github.com/} ;;
|
||||
ssh://git@github.com/*) github_repo=${origin_url#ssh://git@github.com/} ;;
|
||||
git@github.com:*) github_repo=${origin_url#git@github.com:} ;;
|
||||
*)
|
||||
echo "Cannot determine the GitHub repository from origin: ${origin_url}" >&2
|
||||
echo "Set DROIDDECK_GITHUB_REPOSITORY=owner/repo." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
github_repo=${github_repo%.git}
|
||||
fi
|
||||
|
||||
for tool in curl tar zstd; do
|
||||
if ! command -v "${tool}" >/dev/null 2>&1; then
|
||||
echo "${tool} is required to build the bundled audio modules." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then
|
||||
. "${repo_root}/tools/gamescope/release.env"
|
||||
gamescope_archive="${staging_dir}/gamescope.tzst"
|
||||
gh release download "${GAMESCOPE_TAG}" -R "${github_repo}" -p gamescope.tzst -O "${gamescope_archive}"
|
||||
printf '%s %s\n' "${GAMESCOPE_SHA256}" "${gamescope_archive}" | shasum -a 256 -c -
|
||||
zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}"
|
||||
test -f "${linuxfs_dir}/usr/local/bin/gamescope"
|
||||
fi
|
||||
|
||||
if [[ -f "${repo_root}/tools/wlroots/release.env" ]]; then
|
||||
. "${repo_root}/tools/wlroots/release.env"
|
||||
wlroots_archive="${staging_dir}/wlroots.tzst"
|
||||
gh release download "${WLROOTS_TAG}" -R "${github_repo}" -p wlroots.tzst -O "${wlroots_archive}"
|
||||
printf '%s %s\n' "${WLROOTS_SHA256}" "${wlroots_archive}" | shasum -a 256 -c -
|
||||
zstd -dc "${wlroots_archive}" | tar -xf - -C "${linuxfs_dir}"
|
||||
test -f "${linuxfs_dir}/usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so"
|
||||
fi
|
||||
|
||||
mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp"
|
||||
mango_pkgs="${staging_dir}/mango-pkgs"
|
||||
mkdir -p "${mango_dir}" "${mango_pkgs}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive="${staging_dir}/$(basename "${package_url}")"
|
||||
curl -fsSL --retry 3 -o "${package_archive}" "${package_url}"
|
||||
printf '%s %s\n' "${package_sha256}" "${package_archive}" | shasum -a 256 -c -
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
|
||||
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
|
||||
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1 libtracefs.so.1; do
|
||||
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
|
||||
done
|
||||
|
||||
staging_dir=$(mktemp -d "${TMPDIR:-/tmp}/droiddeck-build.XXXXXX")
|
||||
bundle_asset="${repo_root}/app/src/main/assets/pulseaudio.tzst"
|
||||
bundle_backup="${staging_dir}/pulseaudio.original.tzst"
|
||||
bundle_replaced=0
|
||||
cleanup() {
|
||||
local exit_code=$?
|
||||
trap - EXIT
|
||||
if [[ "${bundle_replaced}" == 1 ]]; then
|
||||
cp -p "${bundle_backup}" "${bundle_asset}" || exit_code=1
|
||||
fi
|
||||
rm -rf -- "${staging_dir}" || exit_code=1
|
||||
exit "${exit_code}"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
mkdir -p "${linuxfs_dir}/usr/local/bin"
|
||||
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
|
||||
|
||||
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
|
||||
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
|
||||
@@ -123,9 +211,9 @@ if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export NDK="${sdk_dir}/ndk/${ndk_version}"
|
||||
sink_output="${staging_dir}/sink-out"
|
||||
"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}"
|
||||
"${repo_root}/tools/proot/build.sh" "${repo_root}/app/src/main/jniLibs/arm64-v8a"
|
||||
|
||||
cp -p "${bundle_asset}" "${bundle_backup}"
|
||||
bundle_dir="${staging_dir}/pulseaudio-bundle"
|
||||
@@ -145,7 +233,7 @@ bundle_replaced=1
|
||||
mv "${staging_dir}/pulseaudio.tzst" "${bundle_asset}"
|
||||
|
||||
cd "${repo_root}"
|
||||
./gradlew assembleRelease -PndkVersion="${ndk_version}"
|
||||
./gradlew assembleRelease --console=plain -PndkVersion="${ndk_version}"
|
||||
cp -p "${bundle_backup}" "${bundle_asset}"
|
||||
bundle_replaced=0
|
||||
|
||||
@@ -163,33 +251,6 @@ for audio_file in \
|
||||
fi
|
||||
done
|
||||
|
||||
build_tools=$(find "${sdk_dir}/build-tools" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
|
||||
if [[ ! -x "${build_tools}/zipalign" || ! -x "${build_tools}/apksigner" ]]; then
|
||||
echo "Android build-tools with zipalign/apksigner are required under ${sdk_dir}/build-tools." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
"${build_tools}/zipalign" -p -f 4 "${apk}" "${staging_dir}/app-release.aligned.apk"
|
||||
"${build_tools}/apksigner" sign \
|
||||
--ks keystore/testkey.p12 --ks-type PKCS12 --ks-pass pass:android \
|
||||
--ks-key-alias testkey --key-pass pass:android \
|
||||
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \
|
||||
--out "${apk}" "${staging_dir}/app-release.aligned.apk"
|
||||
|
||||
signature_output=$("${build_tools}/apksigner" verify --min-sdk-version 21 --verbose --print-certs "${apk}")
|
||||
printf '%s\n' "${signature_output}"
|
||||
for scheme in \
|
||||
'Verified using v1 scheme (JAR signing): true' \
|
||||
'Verified using v2 scheme (APK Signature Scheme v2): true' \
|
||||
'Verified using v3 scheme (APK Signature Scheme v3): true'; do
|
||||
grep -qF "${scheme}" <<<"${signature_output}" || {
|
||||
echo "APK signature check failed: ${scheme}" >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
grep -qF 'Signer #1 certificate DN: EMAILADDRESS=android@android.com, CN=Android, OU=Android, O=Android' \
|
||||
<<<"${signature_output}"
|
||||
|
||||
docker run --rm --platform linux/amd64 -v "${repo_root}:/src:ro" -w /src "${image_name}" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
@@ -197,7 +258,7 @@ docker run --rm --platform linux/amd64 -v "${repo_root}:/src:ro" -w /src "${imag
|
||||
work=$(mktemp -d)
|
||||
unzip -q "$apk" "lib/arm64-v8a/*" -d "$work"
|
||||
cd "$work/lib/arm64-v8a"
|
||||
system="libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so
|
||||
system="libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so libstdc++.so
|
||||
libGLESv2.so libEGL.so libnativewindow.so libjnigraphics.so libaaudio.so
|
||||
libOpenSLES.so libmediandk.so libcamera2ndk.so libsync.so libneuralnetworks.so"
|
||||
fail=0
|
||||
@@ -213,6 +274,40 @@ docker run --rm --platform linux/amd64 -v "${repo_root}:/src:ro" -w /src "${imag
|
||||
echo "every NEEDED resolves"
|
||||
'
|
||||
|
||||
build_tools=$(find "${sdk_dir}/build-tools" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
|
||||
if [[ ! -x "${build_tools}/zipalign" || ! -x "${build_tools}/apksigner" ]]; then
|
||||
echo "Android build-tools with zipalign/apksigner are required under ${sdk_dir}/build-tools." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
"${build_tools}/zipalign" -p -f 4 "${apk}" "${apk}.aligned"
|
||||
"${build_tools}/apksigner" sign \
|
||||
--ks "${repo_root}/keystore/testkey.p12" --ks-type PKCS12 --ks-pass pass:android \
|
||||
--ks-key-alias testkey --key-pass pass:android \
|
||||
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \
|
||||
--out "${apk}" "${apk}.aligned"
|
||||
rm -f "${apk}.aligned" "${apk}.idsig"
|
||||
|
||||
signature_output=$("${build_tools}/apksigner" verify --min-sdk-version 21 --verbose --print-certs "${apk}")
|
||||
printf '%s\n' "${signature_output}"
|
||||
if ! unzip -l "${apk}" | grep -qE 'META-INF/.*\.(SF|RSA|DSA)$'; then
|
||||
echo "APK signature check failed: JAR signature files are missing." >&2
|
||||
exit 1
|
||||
fi
|
||||
for scheme in \
|
||||
'Verified using v1 scheme (JAR signing): true' \
|
||||
'Verified using v2 scheme (APK Signature Scheme v2): true' \
|
||||
'Verified using v3 scheme (APK Signature Scheme v3): true'; do
|
||||
grep -qF "${scheme}" <<<"${signature_output}" || {
|
||||
echo "APK signature check failed: ${scheme}" >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
grep -qi 'CN=Android, OU=Android, O=Android' <<<"${signature_output}" || {
|
||||
echo "APK signature check failed: the signer is not the AOSP testkey." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
printf 'APK: %s\n' "${apk}"
|
||||
printf 'SHA-256: '
|
||||
shasum -a 256 "${apk}" | awk '{print $1}'
|
||||
@@ -15,22 +15,7 @@ if [[ ! -f "${apk}" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ -n "${ADB_SERIAL:-}" ]]; then
|
||||
serial=${ADB_SERIAL}
|
||||
else
|
||||
devices=$("${adb_bin}" devices | awk '$2 == "device" {print $1}')
|
||||
device_count=$(printf '%s\n' "${devices}" | sed '/^$/d' | wc -l | tr -d ' ')
|
||||
if [[ "${device_count}" == 0 ]]; then
|
||||
echo "No authorized Android device found. Connect one or set ADB_SERIAL." >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ "${device_count}" != 1 ]]; then
|
||||
echo "Multiple Android devices found; set ADB_SERIAL explicitly." >&2
|
||||
printf '%s\n' "${devices}" >&2
|
||||
exit 2
|
||||
fi
|
||||
serial=${devices}
|
||||
fi
|
||||
serial=$(python3 "${repo_root}/tools/adb_device.py" --adb "${adb_bin}")
|
||||
|
||||
"${adb_bin}" -s "${serial}" install -r --no-incremental "${apk}"
|
||||
installed_path=$("${adb_bin}" -s "${serial}" shell pm path com.droiddeck.launcher | tr -d '\r')
|
||||
|
||||