Compare commits

...
Author SHA1 Message Date
xXJsonDeruloXx af2783cb03 research: probe Valve Bionic Steam client IPC 2026-09-28 15:59:04 -04:00
MaxsTechReviewandMaxsTechReview 240f1194c0 Fix/variables (#60)
* Add editable per-game environment settings below FEX presets

* Add typed preset variable pickers and default D3D12 capability levels

---------

Co-authored-by: MaxsTechReview <6025299+maxjivi05@users.noreply.github.com>
2026-09-28 15:17:57 -04:00
Kurt Himebauch 7b74eebce2 Merge pull request #59 from Droid-Deck/ci/discord-build-announce
ci: publish each signed main build to DroidDeck-CI and post it to Discord
2026-09-28 14:54:29 -04:00
xXJSONDeruloXx 7592684b6f ci: publish to DroidDeck-CI with the org's CI app, not a personal token
DROIDDECK_CI_TOKEN never existed, so PR Release Publish skipped its
upload, and a personal token would expire and belong to one person. Both
workflows now mint a token of the org's DroidDeck CI Publisher app,
installed on DroidDeck-CI only with Contents: write (its ID in the
DROIDDECK_CI_APP_ID variable, its key in DROIDDECK_CI_APP_KEY). No
fallback: a main build without them fails its announce job.
2026-09-28 14:51:13 -04:00
xXJSONDeruloXx 7b78e1629b ci: publish each signed main build to DroidDeck-CI for the Discord post
Run artifacts need a GitHub sign-in to download. Each signed main build
is now also a prerelease main-<sha> of the public DroidDeck-CI (all
variants and their SHA-256s; the last 10 kept, PR releases untouched),
and the Discord post links its standard apk and the release. Without
DROIDDECK_CI_TOKEN the post links the run's artifacts as before.
2026-09-28 14:49:43 -04:00
MaxsTechReview 30741302fb Merge pull request #53 from maxjivi05/fix/adaptive-joysticks
Hide idle adaptive sticks and activate them at touch positions
2026-09-28 14:48:26 -04:00
MaxsTechReview 645f7d0bf1 Merge branch 'main' into fix/adaptive-joysticks 2026-09-28 14:48:14 -04:00
xXJSONDeruloXx 124f162ee8 ci: post each signed main build to Discord
A job after the signing of a main build posts to the Discord's builds
channel: the merged PR (or the commit), and a link to the run's signed
apks. The channel's webhook URL is the DISCORD_BUILDS_WEBHOOK secret;
without it the job posts nothing and passes.
2026-09-28 14:46:41 -04:00
Kurt Himebauch 3c577fd9dd Merge pull request #57 from Droid-Deck/fix/desktop-hardware-cursor
Desktop: hand labwc's cursor to the app, so full-screen games scan out
2026-09-28 14:40:02 -04:00
MaxsTechReview 659ff4817f Expand adaptive joystick activation area by fifty percent 2026-09-28 14:39:55 -04:00
Kurt Himebauch 626adb62af Merge branch 'main' into fix/desktop-hardware-cursor 2026-09-28 14:39:52 -04:00
Kurt Himebauch 71cb100a40 Merge pull request #58 from Droid-Deck/tools/local-release-signing
build_local: sign with DroidDeck's key when a local .signing.env has it
2026-09-28 14:39:22 -04:00
xXJSONDeruloXx 68002f3fa7 build_local: sign with DroidDeck's key when a local .signing.env has it
A local build was signed with the testkey alone, which a release refuses
as an update ("signatures do not match"): testing on a device with a CI
build meant uninstalling it and losing its data first.

With an untracked .signing.env (RELEASE_KEYSTORE, RELEASE_STORE_PASSWORD,
RELEASE_KEY_ALIAS) in the checkout, or in the main checkout for a
worktree, build_local.sh finishes with tools/release/sign-apk.sh as CI's
main builds do, and the apk installs over a release. Without the file
nothing changes. DROIDDECK_SIGNING_ENV points at the file explicitly.
2026-09-28 14:33:15 -04:00
xXJSONDeruloXx dae7592788 Desktop: hand labwc's cursor to the app, so full-screen games scan out
The desktop forced a software cursor (WLR_NO_HARDWARE_CURSORS=1) because
labwc's cursor never showed when handed to the app's compositor. With a
software cursor wlroots never scans out: every frame of a full-screen game
was composited by labwc first ("Direct scan-out disabled by software
cursor", 2284 times in one Adreno 825 report).

Why the cursor never showed: wlroots' Wayland backend attaches and commits
its cursor surface before wl_pointer.set_cursor gives it the cursor role,
and sets it again with nothing new committed each time the pointer enters.
The compositor released a role-less surface's buffer on commit, so the
cursor surface had no image by the time it became the cursor.

- A role-less surface's last buffer (cursor-sized only) is held until the
  next commit; set_cursor publishes it, and a repeat set_cursor of the
  surface already shown unhides its last image.
- A dma-buf cursor is read back after the client's implicit render fence,
  as the zero-copy path waits for it.
- The desktop no longer forces a software cursor.

Device-tested on the AYN Thor (Adreno 740, 1920x1080): labwc's own cursor
is drawn, with its shapes (I-beam over a terminal); wlroots logs "Direct
scan-out enabled" for a full-screen glxgears. At the same 60 fps on screen
the GPU is 3.0 % busy against 4.6 % with the software cursor, both at
550 MHz.
2026-09-28 14:33:08 -04:00
MaxsTechReview e10f5b4430 Limit adaptive stick activation near saved positions 2026-09-28 14:21:34 -04:00
MaxsTechReview 3e32b75a63 Merge branch 'main' into fix/adaptive-joysticks 2026-09-28 12:53:44 -04:00
Kurt Himebauch 435f7a1b03 Merge pull request #56 from Droid-Deck/ci/sign-all-variants
ci: sign every package variant on main
2026-09-28 12:46:40 -04:00
xXJSONDeruloXx 1fd8c50225 ci: sign every package variant on main
main's build signed only the standard package, so the pubg, antutu and
ludashi variants existed only after a manual Release APKs run. The build job
now reads the variant list from tools/release/variants.txt, as release.yml
does, and main's signing job signs all of them.
2026-09-28 12:42:56 -04:00
Kurt Himebauch 197fc3f163 Merge pull request #52 from maxjivi05/fix/splash-screen
Reduce Steam startup movie software decoding load
2026-09-28 11:35:25 -04:00
MaxsTechReview 9530e7b394 Hide idle adaptive sticks and activate them at touch positions 2026-09-28 10:54:24 -04:00
MaxsTechReview 0e0f133496 Reduce Steam startup movie software decoding load 2026-09-28 10:49:25 -04:00
Kurt Himebauch d98c211168 Merge pull request #50 from Droid-Deck/fix/release-blockers
Fix/release blockers
2026-09-28 10:32:44 -04:00
xXJsonDeruloXx 614b4d4de4 chore(release): set version 0.2.0 and remove code comments 2026-09-28 10:32:12 -04:00
Kurt Himebauch 43a19a831a docs(release): show every 0.2.0 section open (#48) 2026-09-28 10:24:24 -04:00
Kurt Himebauch 0d308af024 Merge branch 'main' into fix/release-blockers 2026-09-28 10:22:22 -04:00
The412Banner 128f73da8f Merge pull request #51 from Droid-Deck/fix/child-process-check
Child-process check: read the Developer options toggle too
2026-09-28 09:30:58 -04:00
The412Banner e22a55e949 Child-process check: read the Developer options toggle too
Developer options' "Disable child process restrictions" writes only the
feature-flag property persist.sys.fflag.override.settings_enable_monitor_phantom_procs,
never the global setting. Android (FeatureFlagUtils.isEnabled) uses the global
setting when it is set and that property otherwise, but the check read only the
global setting, so a device switched off in Developer options stayed flagged as
unset however often Check again was pressed.

The check now follows Android's order, and the Setup card no longer says "On"
for a setting that is unset or unreadable.
2026-09-28 09:24:19 -04:00
Kurt Himebauch 67cb005e6c fix(session): stop the session script's own loops when steam exits 2026-09-28 11:52:03 +00:00
Kurt Himebauch 73f76f6799 fix(home): open drawer apps in their own task 2026-09-28 11:52:03 +00:00
Kurt Himebauch 961a060461 fix(session): keep a retried session's first-frame and hud listeners 2026-09-28 11:52:03 +00:00
Kurt Himebauch dadbbf841a fix(session): cancel a session start that is still setting up 2026-09-28 11:52:02 +00:00
Kurt Himebauch 1ce8280371 fix(session): don't launch a cancelled session or end a newer one 2026-09-28 11:52:02 +00:00
Kurt Himebauch 78bdc0e3b5 chore(release): bump to 0.2.1 and check the version at release time 2026-09-28 11:52:02 +00:00
Kurt Himebauch ce5f2f5513 fix(runtime): keep the user's home when a runtime update fails mid-swap 2026-09-28 11:52:02 +00:00
Kurt Himebauch 0f2792c7ac docs: home app and dual-screen demos, trimmed 0.2.0 visuals, README hero (#47) 2026-09-27 22:48:33 -04:00
Kurt Himebauch 7185b775d4 0.2.0 release notes with screenshots, plus launch transition and UI fixes (#46)
* docs(release): draft 0.2.0 beta notes

* docs(release): credit prs and authors in 0.2.0 notes

* docs(release): add #39 and #45 to 0.2.0 notes

* chore: update readme

* fix(ui): cover the whole screen with the capsule wall

The wall was shifted right and then tilted around its own centre, which
left the bottom-left of the home and loading screens bare. Centre it and
size it to the tilted page's bounding box so every corner stays covered.

* feat(ui): flood from the play button into the throbber

Starting a session from a blue button no longer slides the session up
over the front end. The button stretches out on staggered springs until
the page is the ball's blue, the session opens on that same blue with no
window animation, and the blue gathers into the throbber's ball before
the throbber starts. Re-joining a running session, tiles and reduced
motion keep the old rise.

* docs(release): cover everything since 0.1 in the 0.2.0 notes

0.2.0 is the first release from the org, so list what DroidDeck does
as a whole, grouped by area: org pull requests as #N, pull requests
from before the move as The412Banner/DroidDeck#N, and the early work
that predates pull requests by author. CI and build work gets one
short section instead of a line each.

* docs(release): add screenshots and animations to the 0.2.0 notes

Lead with a game running and a few visual highlights, fold the full
list into collapsible sections by area, and shorten every line to the
feature and its credit. Pre-move pull requests read as legacy#N.

* fix(session): give the desktop its own loading hints

The loading screen's hints were written for Steam, so starting the
desktop or an emulator said the first run downloads Steam and that
leaving the app pauses Steam. Desktop and program sessions now rotate
through hints about the desktop instead.

* fix(build): skip incomplete NDKs when picking one locally

An interrupted sdkmanager install leaves a directory like
28.2.13676358.failed under ndk/, which sorted last and was picked
without a toolchain in it. Only consider directories that carry
source.properties.

* docs(release): show launching straight into Big Picture

* docs(release): credit the launch transition to #46
2026-09-27 22:14:23 -04:00
Kurt Himebauch cda6e89c12 fix(session): clear transient UI on pause (#45) 2026-09-27 20:37:58 -04:00
Kurt Himebauch 5f80898c27 Add game file and Proton prefix shortcuts (#39) 2026-09-27 20:37:43 -04:00
The412Banner 85560d6471 Merge pull request #43 from Droid-Deck/fix/session-stragglers
Session stop: kill guest processes proot lost, and cap the session log
2026-09-27 17:19:58 -04:00
The412Banner be6c875277 Session stop: kill guest processes proot lost, and cap the session log
Twice today a session's Xwayland aborted from one thread ("The futex
facility returned an unexpected error code"), proot lost the tracee, and
the process lived on reparented to init: proot's seccomp filter, with no
tracer left, answers ENOSYS, so Xwayland's main loop logged
"WaitForSomething(): poll: Function not implemented" until something killed
it - 9 GB after Dolphin, 13 GB after PPSSPP. --kill-on-exit and the tree
sweep only reach what proot still traces, and the straggler sweep ran only
at the next session's start.

Now a session stop also kills every process of ours whose executable lives
in the Linux runtime, and bannerlator-session keeps only the first
BL_LOG_CAP bytes (256 MB) of session.log, draining the rest so a writer
that filled it is not killed by SIGPIPE.
2026-09-27 16:52:51 -04:00
Kurt Himebauch 91beced154 Merge pull request #41 from Droid-Deck/fix/ui-ux-critique
Fix/UI ux critique
2026-09-27 16:41:18 -04:00
The412Banner ebc3da08b4 Merge pull request #42 from Droid-Deck/feat/cemu-wiiu
Cemu (Wii U) from the front end and the desktop, and two session fixes
2026-09-27 16:39:17 -04:00
xXJsonDeruloXx 41eb780495 fix(ui): remove duplicate focus imports 2026-09-27 16:34:34 -04:00
Kurt Himebauch 359d1535ac fix(copy): american spelling, clearer keyboard and package labels 2026-09-27 14:23:19 -04:00
Kurt Himebauch 4c3a9f027c fix(focus): land controller focus by frame instead of fixed delays 2026-09-27 14:22:56 -04:00
Kurt Himebauch 5a6cc3c76e fix(motion): honor the system animation scale everywhere and on resume 2026-09-27 14:22:17 -04:00
Kurt Himebauch 89bd7deceb refactor(ui): share one frame generation menu and drop the unused dialog 2026-09-27 14:21:41 -04:00
Kurt Himebauch 169f2c3e34 fix(rail): keep sections in fixed places with an empty games state 2026-09-27 14:21:01 -04:00
Kurt Himebauch e6a797695a fix(setup): trim child-process fix to one line and three actions 2026-09-27 14:20:35 -04:00
Kurt Himebauch f1a2ecc857 fix(ui): raise buttons, chips and tabs to handheld touch sizes 2026-09-27 14:20:03 -04:00
Kurt Himebauch 36916f6bde fix(ui): show launch and tab hints where a pad does that 2026-09-27 14:19:32 -04:00
Kurt Himebauch 1b96d13a51 fix(ui): enable launches like play and say why they are disabled 2026-09-27 14:19:02 -04:00
Kurt Himebauch cb1d70bb14 fix(ui): flip booleans with a switch instead of on/off menus 2026-09-27 14:18:29 -04:00
Kurt Himebauch 37af590ca2 fix(ui): use one name each for child-process limit, proton and components 2026-09-27 14:17:49 -04:00
Kurt Himebauch 02f356f8c0 fix(session): keep ended screen with retry, share logs and back 2026-09-27 14:17:16 -04:00
82 changed files with 3038 additions and 321 deletions

No files matched your search

+99 -1
View File
@@ -34,12 +34,18 @@ jobs:
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ubuntu-24.04
timeout-minutes: 45
outputs:
variants: ${{ steps.variants.outputs.list }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
- name: The packages a signed build ships as
id: variants
run: echo "list=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .)" >> "$GITHUB_OUTPUT"
- name: No private key in the tree
run: |
set -euo pipefail
@@ -301,6 +307,9 @@ jobs:
set -o pipefail
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
- name: Game environment launch tests
run: python3 -m unittest discover -s tools/tests -p test_game_environment.py
- name: Unit tests
run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION"
@@ -427,5 +436,94 @@ jobs:
uses: ./.github/workflows/sign.yml
with:
environment: signing-main
variants: '["standard"]'
variants: ${{ needs.build.outputs.variants }}
secrets: inherit
# Each signed main build as a prerelease of the public Droid-Deck/DroidDeck-CI (main-<sha>, the
# last KEEP kept), where anyone can download it without a GitHub account, then a post in the
# Discord's builds channel linking to it. The release is made with a token of the org's
# "DroidDeck CI Publisher" app (installed on DroidDeck-CI only, Contents: write): its ID in the
# DROIDDECK_CI_APP_ID variable, its private key in the DROIDDECK_CI_APP_KEY secret.
# DISCORD_BUILDS_WEBHOOK is the channel's webhook URL.
announce:
needs: [build, sign]
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
timeout-minutes: 10
permissions:
contents: read
env:
CI_REPO: Droid-Deck/DroidDeck-CI
KEEP: 10
steps:
- uses: actions/download-artifact@v4
with:
pattern: droiddeck-signed-*
merge-multiple: true
path: signed
- uses: actions/create-github-app-token@v2
id: ci-token
with:
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
owner: Droid-Deck
repositories: DroidDeck-CI
- name: Publish to DroidDeck-CI
id: publish
env:
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
run: |
set -euo pipefail
tag=main-${GITHUB_SHA::7}
cat signed/SHA256SUMS-*.txt > signed/SHA256SUMS.txt
rm signed/SHA256SUMS-*.txt
notes="Signed build of $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA - unreleased, for testing.
Each apk installs over a DroidDeck release and keeps its data. \`standard\` is the normal app; the others are the same app under another package name, installed beside it.
SHA-256:
\`\`\`
$(cat signed/SHA256SUMS.txt)
\`\`\`"
gh release delete "$tag" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null || true
gh release create "$tag" -R "$CI_REPO" --target main --prerelease \
--title "main ${GITHUB_SHA::7}" --notes "$notes" signed/*
# Only the newest KEEP main builds stay; PR releases (pr-N) are left alone.
gh release list -R "$CI_REPO" -L 200 --json tagName,createdAt \
--jq '[.[] | select(.tagName | startswith("main-"))] | sort_by(.createdAt) | reverse | .['"$KEEP"':][] | .tagName' |
while IFS= read -r old; do gh release delete "$old" -R "$CI_REPO" --yes --cleanup-tag; done
url="$GITHUB_SERVER_URL/$CI_REPO/releases/tag/$tag"
apk=$(cd signed && ls DroidDeck-*.apk | awk 'length(a) == 0 || length($0) < length(a) { a = $0 } END { print a }')
echo "release=$url" >> "$GITHUB_OUTPUT"
echo "apk=$GITHUB_SERVER_URL/$CI_REPO/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
echo "Published $url"
- name: Post to Discord
env:
WEBHOOK: ${{ secrets.DISCORD_BUILDS_WEBHOOK }}
GH_TOKEN: ${{ github.token }}
RELEASE: ${{ steps.publish.outputs.release }}
APK: ${{ steps.publish.outputs.apk }}
run: |
set -euo pipefail
if [ -z "$WEBHOOK" ]; then
echo "::notice::No DISCORD_BUILDS_WEBHOOK secret; nothing posted"
exit 0
fi
commit=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA")
subject=$(jq -r '.commit.message | split("\n")[0]' <<<"$commit")
# A merge commit's subject is "Merge pull request #N from ..."; its body's first line is
# the PR's title, which says more.
title=$(jq -r '.commit.message | split("\n") | map(select(length > 0)) | .[1] // ""' <<<"$commit")
pr=$(sed -n 's/^Merge pull request #\([0-9]*\).*/\1/p' <<<"$subject")
if [ -n "$pr" ]; then
what="[#$pr]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$pr): ${title:-$subject}"
else
what="[\`${GITHUB_SHA::7}\`]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA): $subject"
fi
get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE")
content=$(printf '**New signed build** `main-%s`\n%s\n%s' "${GITHUB_SHA::7}" "$what" "$get")
jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
echo "Posted: $content"
+13 -8
View File
@@ -79,8 +79,9 @@ jobs:
}
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;
[[ "$stable" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && "$candidate" =~ ^com\.droiddeck\.launcher\ [0-9]+$ &&
${candidate##* } -ge ${stable##* } ]] || {
echo "::error::PR package/versionCode '$candidate' cannot install over stable '$stable'"; exit 1;
}
current=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
@@ -119,18 +120,22 @@ jobs:
with:
name: droiddeck-pr-signed-standard
path: signed
- name: Publish to DroidDeck-CI when configured
# A token of the org's "DroidDeck CI Publisher" app, as build.yml's announce job uses.
- uses: actions/create-github-app-token@v2
id: ci-token
with:
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
owner: Droid-Deck
repositories: DroidDeck-CI
- name: Publish to DroidDeck-CI
env:
GH_TOKEN: ${{ secrets.DROIDDECK_CI_TOKEN }}
GH_TOKEN: ${{ steps.ci-token.outputs.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"
+4
View File
@@ -35,6 +35,10 @@ jobs:
run: |
set -euo pipefail
[[ $VERSION =~ ^[0-9A-Za-z._-]+$ ]] || { echo "::error::version '$VERSION': letters, digits, . _ - only"; exit 1; }
name=$(sed -n 's/^ *versionName "\(.*\)"$/\1/p' app/build.gradle)
[[ $VERSION == "$name" || $VERSION == "$name"-* ]] || {
echo "::error::version '$VERSION' does not match versionName '$name' in app/build.gradle: bump versionName and versionCode first"; 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" \
+3
View File
@@ -29,3 +29,6 @@ app/src/main/jniLibs/arm64-v8a/libproot-loader.so
droiddeck-release-key/
password.txt
__pycache__/
# Local signing with the release key (tools/build_local.sh); holds a password.
.signing.env
+3 -1
View File
@@ -5,7 +5,9 @@
</picture>
</p>
Run Valve's native ARM64 Steam client on an Adreno Android device. Steam runs in a Linux runtime under proot, with gamescope and an in-app Vulkan compositor. Windows games use Valve's ARM64 Proton and FEX. A desktop with LXQt, Firefox, and emulators is also available.
DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Adreno handheld, with Windows games through Valve's ARM64 Proton.
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
## Requirements and install
+3 -2
View File
@@ -63,8 +63,8 @@ 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 8
versionName "0.1.7"
versionCode 9
versionName "0.2.0"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
ndk {
@@ -176,4 +176,5 @@ dependencies {
implementation 'com.termux.termux-app:terminal-view:0.118.0'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.16.1'
}
+95 -15
View File
@@ -30,6 +30,7 @@
#include <time.h>
#include <stdarg.h>
#include <errno.h>
#include <poll.h>
#include <sys/timerfd.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
@@ -247,6 +248,10 @@ struct surface {
int releases_pending; /* FPS limiter: buffers of this surface still to be released */
enum surface_role role;
/* A role-less surface's last buffer, held unreleased: it may become the pointer's image
* (wl_pointer.set_cursor after the commit, which is wlroots' order). */
struct wl_resource *idle_buffer;
struct wl_listener idle_buffer_destroy;
struct wl_resource *xdg_surface, *xdg_toplevel;
struct wl_resource *viewport;
@@ -475,6 +480,7 @@ static int g_ntouches;
#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 struct surface *g_cursor_shown; /* compositor thread: whose image g_cursor_px holds */
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 */
@@ -482,6 +488,14 @@ 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 */
/* The last image again, after a hide: the same surface set as the pointer once more with nothing
* newly committed to it (wlroots re-sets its cursor surface each time the pointer enters). */
static void cursor_publish_shown(void) {
pthread_mutex_lock(&g_cursor_lock);
if (g_cursor_w > 0) { g_cursor_hidden = 0; g_cursor_serial++; } /* serial: the hotspot may be new */
pthread_mutex_unlock(&g_cursor_lock);
}
static void cursor_publish_hidden(void) {
pthread_mutex_lock(&g_cursor_lock);
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
@@ -931,6 +945,68 @@ static void surface_set_input(struct wl_client *c, struct wl_resource *r,
static void send_toplevel_configure(struct surface *s);
/* The pointer image from a cursor surface's buffer: wl_shm is copied, a dma-buf (labwc on a GPU
* renderer) is read back once the client's render into it is done - its implicit fence, as the
* zero-copy path waits for it (ahb_swapchain_present). */
static void cursor_publish_buffer(struct surface *s, struct wl_resource *buffer) {
struct dmabuf_buffer *db = get_dmabuf(buffer);
struct wl_shm_buffer *shm = db ? NULL : wl_shm_buffer_get(buffer);
if (shm) {
cursor_publish_shm(shm, g_cursor_hx, g_cursor_hy);
} else if (db && db->n_planes >= 1 && db->width > 0 && db->height > 0 &&
(int64_t)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) return;
struct pollfd p = {.fd = db->fd[0], .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
if (vkp_image_readback(db->img, g_cursor_rb, CURSOR_MAX_PX) != 0) return;
cursor_publish_pixels((const uint8_t *)g_cursor_rb, db->width, db->height,
(size_t)db->width * 4, g_cursor_hx, g_cursor_hy);
} else {
return;
}
g_cursor_shown = s;
}
static void on_idle_buffer_destroyed(struct wl_listener *l, void *data) {
struct surface *s = wl_container_of(l, s, idle_buffer_destroy);
wl_list_remove(&s->idle_buffer_destroy.link);
wl_list_init(&s->idle_buffer_destroy.link);
s->idle_buffer = NULL;
}
/* Only what could be a pointer image is held; anything larger goes straight back. */
static void surface_hold_idle(struct surface *s, struct wl_resource *buffer) {
struct dmabuf_buffer *db = get_dmabuf(buffer);
struct wl_shm_buffer *shm = db ? NULL : wl_shm_buffer_get(buffer);
int64_t px = db ? (int64_t)db->width * db->height
: shm ? (int64_t)wl_shm_buffer_get_width(shm) * wl_shm_buffer_get_height(shm) : 0;
if (px <= 0 || px > CURSOR_MAX_PX) { wl_buffer_send_release(buffer); return; }
s->idle_buffer = buffer;
s->idle_buffer_destroy.notify = on_idle_buffer_destroyed;
wl_resource_add_destroy_listener(buffer, &s->idle_buffer_destroy);
}
/* Lets go of the held buffer; release = give it back to the client (not while it is going away). */
static struct wl_resource *surface_take_idle(struct surface *s) {
struct wl_resource *buffer = s->idle_buffer;
if (!buffer) return NULL;
wl_list_remove(&s->idle_buffer_destroy.link);
wl_list_init(&s->idle_buffer_destroy.link);
s->idle_buffer = NULL;
return buffer;
}
static void surface_drop_idle(struct surface *s) {
struct wl_resource *buffer = surface_take_idle(s);
if (buffer) wl_buffer_send_release(buffer);
}
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
struct surface *child;
@@ -970,28 +1046,19 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
s->pending_buffer = NULL;
s->pending_attach = 0;
surface_drop_idle(s); /* replaced, whatever the surface is now */
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 > 0 && db->height > 0 &&
(int64_t)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);
} else {
cursor_publish_buffer(s, buffer);
wl_buffer_send_release(buffer);
}
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);
/* Role-less surface: never drawn, but its buffer is kept for a set_cursor to come. */
if (buffer) surface_hold_idle(s, buffer);
} else if (db) {
take_dmabuf(s, db, buffer);
} else if (shm) {
@@ -1063,6 +1130,8 @@ static void surface_resource_destroy(struct wl_resource *r) {
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_cursor_shown == s) g_cursor_shown = NULL;
surface_take_idle(s);
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;
@@ -1139,6 +1208,7 @@ static void compositor_create_surface(struct wl_client *c, struct wl_resource *r
wl_list_init(&s->child_link);
wl_list_init(&s->toplevel_link);
wl_list_init(&s->pending_buffer_destroy.link);
wl_list_init(&s->idle_buffer_destroy.link);
wl_list_insert(&g_surfaces, &s->link);
wl_resource_set_implementation(s->resource, &surface_impl, s, surface_resource_destroy);
}
@@ -2143,6 +2213,16 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
g_cursor_surface = s;
g_cursor_hx = hx;
g_cursor_hy = hy;
/* Its content may already be committed: wlroots' Wayland backend attaches and commits the
* cursor surface first and sets it as the pointer after, and sets it again with nothing new
* committed each time the pointer re-enters. */
struct wl_resource *buffer = surface_take_idle(s);
if (buffer) {
cursor_publish_buffer(s, buffer);
wl_buffer_send_release(buffer);
} else if (g_cursor_shown == s) {
cursor_publish_shown();
}
}
static void pointer_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static const struct wl_pointer_interface pointer_impl = {
@@ -97,13 +97,11 @@ object HomeApp {
val intent = Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(ComponentName(app.packageName, app.className))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (displayId == null) {
context.startActivity(intent)
return
}
// 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())
}
@@ -24,6 +24,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.toArgb
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.LsfgNative
@@ -83,6 +84,10 @@ class MainActivity : ComponentActivity() {
// The screen's state. Compose redraws whatever reads these when they change.
private var installed by mutableStateOf<String?>(null)
/** A session launch waiting on its button to fill the page (LaunchFlood). */
private var flood by mutableStateOf<PendingFlood?>(null)
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
private var ready by mutableStateOf(false)
private var available by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
private var busy by mutableStateOf(false)
@@ -225,10 +230,28 @@ class MainActivity : ComponentActivity() {
}
}
}
if (intent?.component?.className == SessionActivity::class.java.name) {
if (flood != null) return
// Started by a blue button: it floods the page first. A running session is re-joined
// as before, rising over the front end.
val from = com.droiddeck.launcher.ui.LaunchOrigin.take()
if (from != null && !SessionState.running && com.droiddeck.launcher.ui.Motion.scale != 0f) {
flood = PendingFlood(from, intent)
return
}
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
}
super.startActivity(intent)
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
}
/** The page is all blue: the session opens on the same blue, with no animation of its own. */
private fun launchFlooded(f: PendingFlood) {
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
super.startActivity(f.intent.putExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, signal.toArgb()))
overridePendingTransition(0, 0)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
@@ -248,6 +271,7 @@ class MainActivity : ComponentActivity() {
showMapping -> { { MappingHost() } }
else -> null
}
com.droiddeck.launcher.ui.FloodBehind({ floodProgress }) {
FrontEndScreen(
FrontEndState(
installed = installed, ready = ready, available = available?.version,
@@ -320,6 +344,10 @@ class MainActivity : ComponentActivity() {
onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true },
onRoms = { showRoms = true },
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
onBrowseFiles = { dir ->
startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)
.putExtra(com.droiddeck.launcher.files.FileManagerActivity.EXTRA_START_DIR, dir.absolutePath))
},
onLogs = {
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
logsEnabled = SessionPrefs.logsEnabled(this)
@@ -365,7 +393,7 @@ class MainActivity : ComponentActivity() {
val result = runCatching {
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
}
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB pairing failed" }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging pairing failed" }
ui.post { complete(error) }
}, "wireless-adb-pair").start()
},
@@ -378,7 +406,7 @@ class MainActivity : ComponentActivity() {
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" }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging command failed" }
ui.post {
if (error == null) refreshPhantomStatus()
complete(error)
@@ -388,7 +416,7 @@ class MainActivity : ComponentActivity() {
onSetPhantomProcessLimit = { enabled, complete ->
Thread({
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB is unavailable" }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging is unavailable" }
ui.post {
if (error == null) refreshPhantomStatus()
complete(error)
@@ -417,6 +445,7 @@ class MainActivity : ComponentActivity() {
),
page = page,
)
}
if (showRoms) RomsDialog(
path = romsDir,
onChoose = {
@@ -443,6 +472,7 @@ class MainActivity : ComponentActivity() {
onDismiss = { showRemove = false },
)
if (showCredits) CreditsDialog { showCredits = false }
flood?.let { f -> com.droiddeck.launcher.ui.LaunchFlood(f.from, onProgress = { floodProgress = it }) { launchFlooded(f) } }
}
}
@@ -518,6 +548,7 @@ class MainActivity : ComponentActivity() {
override fun onResume() {
super.onResume()
com.droiddeck.launcher.ui.Motion.refresh(this)
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.
@@ -551,6 +582,10 @@ class MainActivity : ComponentActivity() {
override fun onStop() {
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
// The session covers the page by now; coming back finds it as it was.
flood = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
super.onStop()
}
@@ -951,7 +986,13 @@ class MainActivity : ComponentActivity() {
// The libraries, off the main thread: manifests and a folder scan.
Thread({
val games = if (ready) Library.steamGames(this) + com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art -> Library.SteamGame(g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId, hero = art.hero ?: art.header) }
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art ->
Library.SteamGame(
g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId,
hero = art.hero ?: art.header, gameFiles = g.folder,
protonPrefix = Library.protonPrefix(this, g.appId),
)
}
} else emptyList()
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
ui.post { steamGames = games; emulatorList = emus }
@@ -97,6 +97,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
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)
/** The blue the front end flooded to on the way in; the loading screen opens on it (LaunchFlood). */
private var floodColor by mutableStateOf<Int?>(null)
private val cursorHide = Runnable { cursorVisible = false }
/** When the pad or the on-screen controls were last used (uptimeMillis); see [showCursor]. */
private var lastPadInputMs = 0L
@@ -232,7 +234,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
root.pointerIcon = noCursor
surfaceView.pointerIcon = noCursor
loading = LoadingState(this)
loading = LoadingState(this, steam = loadingMode() == SessionService.MODE_STEAM)
if (!SessionState.running) {
val needRuntime = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(this) == null
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
@@ -252,19 +254,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
readPrefs()
intent.getIntExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, 0).takeIf { it != 0 && loading.visible }?.let {
floodColor = it
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(it))
}
sessionOverlay = createSessionOverlay()
root.addView(sessionOverlay)
setContentView(root)
handleHomeGuideIntent(intent)
updateOnScreenControls()
WaylandCompositor.setFirstFrameListener {
SessionEvents.firstFrame()
runOnUiThread {
loading.visible = false
hud.start()
}
}
WaylandCompositor.setFirstFrameListener(firstFrameListener)
SessionEvents.markReadyIfPossible()
SessionState.endListener = endListener
// A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord.
@@ -273,6 +273,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun handleOnBackPressed() {
// The PC keyboard closes first (B on a controller), then Back is the drawer again.
when {
::loading.isInitialized && loading.ended -> finish()
drawerOpen -> drawerOpen = false
pcKeyboardOpen -> pcKeyboardOpen = false
else -> routeBackAction()
@@ -299,6 +300,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
title = loadingTitle(), steam = loadingMode() == SessionService.MODE_STEAM,
// As the drawer's Stop does: the service stops, and a start still installing is cancelled.
onCancel = { SessionService.stop(this@SessionActivity); finish() },
endedDetail = loading.endedDetail,
onRetry = { retrySession() },
onShareLogs = { shareCurrentSessionLogs() },
onClose = { finish() },
flood = floodColor?.let { androidx.compose.ui.graphics.Color(it) },
onFlooded = {
floodColor = null
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
},
)
// Opening the drawer takes the controller away from the game: release its pad.
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
@@ -599,6 +609,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionEvents.fail(code, problem)
collectStartArtifacts("session start failed")
loading.showEnded(problem)
focusEndedScreen()
return@post
}
loading.percent = -1
@@ -888,19 +899,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun showEnded(status: Int, hint: String?) {
run {
if (status != 0) {
loading.showEnded(
"The session ended ($status)\n${SessionState.logFile?.path ?: "-"}" +
(if (hint != null) "\n\n$hint" else "")
)
// A moment on screen, so a failure is readable rather than a flash of black;
// longer when there is advice to read.
Handler(Looper.getMainLooper()).postDelayed({ finish() }, if (hint != null) 9000 else 4000)
} else {
finish()
}
if (status == 0) {
finish()
return
}
// It stays until the user leaves: a failure read against a timer is a failure not read.
loading.showEnded(
hint ?: "Steam stopped unexpectedly. Share the logs with a bug report, or try again.",
"Exit status $status · ${SessionState.logFile?.path ?: "no log"}",
)
focusEndedScreen()
}
/** The ended screen's buttons take the pad: it is no longer driving a game. */
private fun focusEndedScreen() {
drawerOpen = false
padBridge?.releaseAll()
uiHandler.post { sessionOverlay.requestFocus() }
}
/** The same start again, in a fresh activity: the ended one keeps no session to reuse. */
private fun retrySession() {
val again = Intent(intent)
finish()
startActivity(again)
}
/**
@@ -956,6 +978,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
return true
}
// The ended screen is a page of buttons: the pad drives them, and B leaves.
if (::loading.isInitialized && loading.ended) {
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) finish()
return true
}
return super.dispatchKeyEvent(event)
}
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) {
@@ -1443,6 +1473,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onResume() {
super.onResume()
com.droiddeck.launcher.ui.Motion.refresh(this)
refreshHomeApp()
if (intent?.action == SessionService.ACTION_RESUME) {
intent.action = null
@@ -1457,6 +1488,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onPause() {
// Do not carry transient session UI across an app/display transition. In particular, the
// drawer's dim layer can otherwise remain over Steam when this activity returns.
drawerOpen = false
pcKeyboardOpen = false
(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.
@@ -1496,6 +1531,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
/** Ours, so a finishing activity never unhooks the one that replaced it. */
private val endListener: (Int) -> Unit = { status -> onSessionEnded(status) }
private val firstFrameListener = Runnable {
SessionEvents.firstFrame()
runOnUiThread {
loading.visible = false
hud.start()
}
}
override fun onDestroy() {
// Deliberately does NOT end the session: this activity can be destroyed while the user is
@@ -1508,7 +1550,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (::hud.isInitialized) hud.stop()
padBridge?.stop()
if (SessionState.endListener === endListener) SessionState.endListener = null
WaylandCompositor.setFirstFrameListener(null)
WaylandCompositor.clearFirstFrameListener(firstFrameListener)
super.onDestroy()
}
@@ -1,42 +1,33 @@
package com.droiddeck.launcher.core
/**
* FEXCore presets for the x86 games the Steam client launches, Bannerlator's table carried over
* so a preset means the same thing in both apps. Each is a set of FEX_* variables put into the
* session's environment; the games under FEX inherit them from the client. The default is FEX's
* own defaults - no variables at all - which is what every session has run on so far.
*
* TSO = x86's total store ordering emulated on ARM: safest, slowest. MULTIBLOCK compiles more per
* block. X87REDUCEDPRECISION trades x87 exactness for speed. SMCCHECKS=none is the risky one -
* anything that writes its own code at runtime (JIT, .NET, DRM) can misbehave. DENUVO keeps the
* checks at full and hides the hypervisor bit, which its anti-tamper looks for.
*/
import com.droiddeck.launcher.R
object FexPreset {
class Preset(val id: String, val label: String, val detail: String, val env: List<String>)
class Preset(val id: String, val label: Int, val detail: Int, val env: List<String>)
private fun tso(main: Int, vector: Int, memcpy: Int, halfBarrier: Int) = listOf(
"FEX_TSOENABLED=$main", "FEX_VECTORTSOENABLED=$vector", "FEX_MEMCPYSETTSOENABLED=$memcpy", "FEX_HALFBARRIERTSOENABLED=$halfBarrier",
)
val all: List<Preset> = listOf(
Preset("", "FEX defaults", "Uses FEX defaults.", emptyList()),
Preset("STABILITY", "Stability", "Safest, slowest settings.", tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=0")),
Preset("COMPATIBILITY", "Compatibility", "Full TSO with multiblock.", tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=1")),
Preset("INTERMEDIATE", "Intermediate", "Balanced TSO with reduced x87 precision.", tso(1, 0, 0, 1) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
Preset("PERFORMANCE", "Performance", "All TSO disabled; multiblock.", tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
Preset("PERFORMANCE_TSO", "Performance + TSO", "Performance settings with main TSO enabled.", tso(1, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
Preset("EXTREME", "Extreme", "Disables self-modifying-code checks. JIT games and DRM may break.",
Preset("", R.string.fex_default_label, R.string.fex_default_detail, emptyList()),
Preset("STABILITY", R.string.fex_stability_label, R.string.fex_stability_detail, tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=0")),
Preset("COMPATIBILITY", R.string.fex_compatibility_label, R.string.fex_compatibility_detail, tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=1")),
Preset("INTERMEDIATE", R.string.fex_intermediate_label, R.string.fex_intermediate_detail, tso(1, 0, 0, 1) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
Preset("PERFORMANCE", R.string.fex_performance_label, R.string.fex_performance_detail, tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
Preset("PERFORMANCE_TSO", R.string.fex_performance_tso_label, R.string.fex_performance_tso_detail, tso(1, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
Preset("EXTREME", R.string.fex_extreme_label, R.string.fex_extreme_detail,
tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=none", "FEX_DISABLEL2CACHE=1", "FEX_DYNAMICL1CACHE=1", "FEX_DYNAMICL1CACHEINCREASECOUNTHEURISTIC=250", "FEX_DYNAMICL1CACHEDECREASECOUNTHEURISTIC=50")),
Preset("EXTREME_TSO", "Extreme + TSO", "Extreme settings with main TSO enabled.",
Preset("EXTREME_TSO", R.string.fex_extreme_tso_label, R.string.fex_extreme_tso_detail,
tso(1, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=none", "FEX_DISABLEL2CACHE=1", "FEX_DYNAMICL1CACHE=1", "FEX_DYNAMICL1CACHEINCREASECOUNTHEURISTIC=250", "FEX_DYNAMICL1CACHEDECREASECOUNTHEURISTIC=50")),
Preset("EXTREME_GN", "Extreme-gn", "Performance with TSC and metadata hints. Try before Extreme.",
Preset("EXTREME_GN", R.string.fex_extreme_gn_label, R.string.fex_extreme_gn_detail,
tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMALLTSCSCALE=1", "FEX_VOLATILEMETADATA=1")),
Preset("DENUVO", "Denuvo", "Performance with full code checks and the hypervisor bit hidden.",
Preset("DENUVO", R.string.fex_denuvo_label, R.string.fex_denuvo_detail,
tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=full", "FEX_HIDEHYPERVISORBIT=1")),
)
fun byId(id: String): Preset = all.firstOrNull { it.id == id } ?: all[0]
/** The variables for the session's environment, in KEY=VALUE form; empty for the default. */
/** Game-launch variables in KEY=VALUE form. */
fun env(id: String): List<String> = byId(id).env
}
@@ -0,0 +1,38 @@
package com.droiddeck.launcher.core
object GameEnvironment {
data class Config(
val shared: Map<String, String?> = emptyMap(),
val games: Map<String, Map<String, String?>> = emptyMap(),
) {
fun entries(scope: String) = if (scope.isEmpty()) shared else games[scope].orEmpty()
fun withEntries(scope: String, entries: Map<String, String?>): Config =
if (scope.isEmpty()) copy(shared = entries.toMap())
else copy(games = if (entries.isEmpty()) games - scope else games + (scope to entries.toMap()))
}
private val namePattern = Regex("[A-Za-z_][A-Za-z0-9_]*")
private val unused = setOf(
"WINEESYNC", "WINENTSYNC", "WINE_FAST_YIELD", "WINE_DO_NOT_CREATE_DXGI_DEVICE_MANAGER",
"WINE_NEW_MEDIASOURCE", "WRAPPER_MAX_IMAGE_COUNT", "WRAPPER_DMAHEAP_CACHED",
"ALSA_LATENCY_MS", "ALSA_VOLUME", "ALSA_BASS_BOOST", "ALSA_PERFORMANCE_MODE",
"DXVK_ASYNC", "DXVK_GPLASYNCCACHE",
)
fun validName(name: String) = namePattern.matches(name)
fun supported(name: String) = name !in unused && !name.startsWith("BOX64_") && !name.startsWith("BOX86_")
fun validValue(value: String) = '\u0000' !in value && value.length <= 8192
fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true)
fun defaults(preset: String): Map<String, String?> = linkedMapOf<String, String?>(
"MESA_SHADER_CACHE_DISABLE" to "false",
"VKD3D_FEATURE_LEVEL" to "12_2",
"VKD3D_SHADER_MODEL" to "6_9",
).apply {
FexPreset.env(preset).forEach { put(it.substringBefore('='), it.substringAfter('=')) }
}
fun effective(config: Config, preset: String, scope: String): Map<String, String?> =
defaults(preset) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
}
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.core
import com.droiddeck.launcher.R
object GameEnvironmentOptions {
enum class Type { TOGGLE, CHOICE, MULTIPLE, NUMBER, TEXT }
data class Option(val name: String, val value: String, val detail: Int, val type: Type, val choices: List<String> = emptyList())
val all = listOf(
Option("MESA_SHADER_CACHE_DISABLE", "false", R.string.game_env_cache, Type.TOGGLE, listOf("false", "true")),
Option("VKD3D_FEATURE_LEVEL", "12_2", R.string.game_env_feature, Type.CHOICE, listOf("12_2", "12_1", "12_0", "11_1", "11_0")),
Option("VKD3D_SHADER_MODEL", "6_9", R.string.game_env_shader, Type.CHOICE, listOf("6_9", "6_8", "6_7", "6_6", "6_5", "6_4", "6_3", "6_2", "6_1", "6_0", "5_1")),
Option("VKD3D_CONFIG", "nodxr", R.string.game_env_vkd3d_config, Type.MULTIPLE, listOf("nodxr", "single_queue", "no_upload_hvv")),
Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")),
Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")),
Option("DXVK_HUD", "fps", R.string.game_env_hud, Type.MULTIPLE, listOf("scale=0.5", "scale=0.7", "opacity=0.5", "opacity=0.7", "devinfo", "fps", "frametimes", "submissions", "drawcalls", "pipelines", "descriptors", "memory", "gpuload", "version", "api", "cs", "compiler", "samplers")),
Option("DXVK_CONFIG", "dxvk.maxFrameRate = 60", R.string.game_env_dxvk_config, Type.TEXT),
Option("VKD3D_FRAME_RATE", "60", R.string.game_env_vkd3d_limit, Type.NUMBER),
Option("mesa_glthread", "true", R.string.game_env_glthread, Type.TOGGLE, listOf("false", "true")),
Option("ZINK_DESCRIPTORS", "auto", 0, Type.CHOICE, listOf("auto", "lazy", "cached", "notemplates")),
Option("ZINK_DEBUG", "nir", 0, Type.MULTIPLE, listOf("nir", "spirv", "tgsi", "validation", "sync", "compact", "noreorder")),
Option("SteamDeck", "0", 0, Type.TOGGLE, listOf("0", "1")),
Option("FD_DEV_FEATURES", "enable_tp_ubwc_flag_hint=1", 0, Type.MULTIPLE, listOf("enable_tp_ubwc_flag_hint=1", "storage_8bit=1")),
Option("TU_DEBUG", "forcecb", 0, Type.MULTIPLE, listOf("forcecb", "nocb", "startup", "deck_emu", "nir", "nobin", "sysmem", "gmem", "forcebin", "layout", "noubwc", "nomultipos", "nolrz", "nolrzfc", "perf", "perfc", "flushall", "syncdraw", "push_consts_per_stage", "rast_order", "unaligned_store", "log_skip_gmem_ops", "dynamic", "bos", "3d_load", "fdm", "noconform", "rd")),
Option("IR3_SHADER_DEBUG", "nouboopt", 0, Type.MULTIPLE, listOf("nouboopt", "nopreamble", "noearlypreamble")),
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
Option("WINEDLLOVERRIDES", "", 0, Type.TEXT),
Option("GALLIUM_HUD", "simple", 0, Type.MULTIPLE, listOf("simple", "fps", "frametime")),
)
fun find(name: String): Option? = all.firstOrNull { it.name == name }
fun toggle(value: String, choice: String): String {
val selected = value.split(',').filter { it.isNotEmpty() }.toMutableSet()
if (!selected.remove(choice)) selected.add(choice)
return selected.joinToString(",")
}
}
@@ -23,18 +23,40 @@ object PhantomProcessLimit {
fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
val value = try {
val global = try {
Settings.Global.getString(resolver, SETTING)
} catch (_: Exception) {
return PhantomProcessStatus.UNREADABLE
}
return when (value?.trim()?.lowercase()) {
return status(global, systemProperty(OVERRIDE_PROPERTY))
}
/**
* The value Android itself acts on, in FeatureFlagUtils.isEnabled's order: the global setting
* when it is set, otherwise the feature-flag override property. Developer options' "Disable
* child process restrictions" writes only the property, so a device switched off there has no
* global setting at all and must not be reported as unset.
*/
fun status(global: String?, override: String?): PhantomProcessStatus {
val value = global?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
?: override?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
return when (value) {
"false", "0" -> PhantomProcessStatus.DISABLED
null, "" -> PhantomProcessStatus.UNSET
null -> PhantomProcessStatus.UNSET
else -> PhantomProcessStatus.ENABLED
}
}
private const val OVERRIDE_PROPERTY = "persist.sys.fflag.override.$SETTING"
private fun systemProperty(name: String): String? = try {
Class.forName("android.os.SystemProperties")
.getMethod("get", String::class.java)
.invoke(null, name) as? String
} catch (_: Exception) {
null
}
fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
@@ -11,6 +11,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.droiddeck.launcher.ui.DroidDeckTheme
import java.io.File
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
class FileManagerActivity : ComponentActivity() {
@@ -19,10 +20,11 @@ class FileManagerActivity : ComponentActivity() {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
}
val initialDir = intent.getStringExtra(EXTRA_START_DIR)?.let(::File)
setContent {
DroidDeckTheme {
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
FileManagerScreen()
FileManagerScreen(initialDir = initialDir)
}
}
}
@@ -32,4 +34,8 @@ class FileManagerActivity : ComponentActivity() {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 1 && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) recreate()
}
companion object {
const val EXTRA_START_DIR = "com.droiddeck.launcher.files.START_DIR"
}
}
@@ -21,6 +21,7 @@ object Library {
class SteamGame(
val appId: Int, val name: String, val art: File?, val library: String, val gameId: Long = appId.toLong(),
val hero: File? = null, val lastPlayed: Long = 0L,
val gameFiles: File? = null, val protonPrefix: File? = null,
)
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
@@ -66,14 +67,31 @@ object Library {
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
private val LAST_PLAYED = Regex("^\\s*\"LastPlayed\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
private val INSTALL_DIR = Regex("^\\s*\"installdir\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
/** Steam's library roots visible to this launcher: its private default plus the selected library. */
private fun steamLibraries(context: Context): List<Pair<File, String>> {
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
return listOfNotNull(
root to "internal",
GameStorage.effective(context)?.let { File(it.path) to it.label },
)
}
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
fun protonPrefix(context: Context, appId: Long, preferredLibrary: File? = null): File? {
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first })
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
return roots.asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
.firstOrNull { it.isDirectory }
}
fun steamGames(context: Context): List<SteamGame> {
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
val cache = File(root, "appcache/librarycache")
val libraries = listOfNotNull(
root to "internal",
GameStorage.effective(context)?.let { File(it.path) to it.label },
)
val libraries = steamLibraries(context)
val out = LinkedHashMap<Int, SteamGame>()
for ((library, label) in libraries) {
val steamapps = File(library, "steamapps")
@@ -89,7 +107,17 @@ object Library {
val art = steamCacheImage(cache, appId, STEAM_CAPSULES)
val hero = steamCacheImage(cache, appId, STEAM_HEROES)
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
out[appId] = SteamGame(appId, name, art, label, hero = hero, lastPlayed = lastPlayed)
// App manifests are Valve KeyValues (VDF) files. installdir is one folder
// below steamapps/common; only expose it when the directory exists and the
// manifest value cannot escape that directory.
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
out[appId] = SteamGame(
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
gameFiles = gameFiles,
protonPrefix = protonPrefix(context, appId.toLong(), library),
)
}
}
return out.values.toList()
@@ -40,9 +40,11 @@ object FrameGen {
}
/** "Off", "Win-FG 2×", "LSFG 3×" - for the main screen. */
fun label(context: Context): String = when (engine(context)) {
ENGINE_WINFG -> "Win-FG ${multiplier(context)}×"
ENGINE_LSFG -> "LSFG ${multiplier(context)}×"
fun label(context: Context): String = label(engine(context), multiplier(context))
fun label(engine: String, multiplier: Int): String = when (engine) {
ENGINE_WINFG -> "Win-FG $multiplier×"
ENGINE_LSFG -> "LSFG $multiplier×"
else -> "Off"
}
@@ -82,47 +84,5 @@ object FrameGen {
return problem
}
/**
* Off, or an engine at 2x/3x/4x; saved on pick, then [onChanged]. The LSFG rows are greyed
* and unpickable until Lossless Scaling is installed in the Steam client - the engine cannot
* run without its DLL, so offering it would only produce a setting that silently does nothing.
*/
fun showPicker(activity: android.app.Activity, onChanged: () -> Unit) {
val lsfgReady = LsfgNative.isInstalled(activity)
val lsfgNote = if (lsfgReady) "" else " - install Lossless Scaling in Steam"
val choices = listOf("Off",
"Win-FG 2×", "Win-FG 3×", "Win-FG 4×",
"LSFG 2×$lsfgNote", "LSFG 3×$lsfgNote", "LSFG 4×$lsfgNote")
val current = when (engine(activity)) {
ENGINE_WINFG -> multiplier(activity) - 1
ENGINE_LSFG -> if (lsfgReady) multiplier(activity) + 2 else 0
else -> 0
}
val adapter = object : android.widget.ArrayAdapter<String>(
activity, android.R.layout.simple_list_item_single_choice, choices) {
override fun isEnabled(position: Int) = lsfgReady || position < 4
override fun areAllItemsEnabled() = lsfgReady
override fun getView(position: Int, convertView: android.view.View?, parent: android.view.ViewGroup): android.view.View {
val view = super.getView(position, convertView, parent)
view.isEnabled = isEnabled(position)
view.alpha = if (isEnabled(position)) 1f else 0.38f
return view
}
}
android.app.AlertDialog.Builder(activity)
.setTitle(com.droiddeck.launcher.R.string.frame_gen_title)
.setSingleChoiceItems(adapter, current) { dialog, which ->
when (which) {
0 -> set(activity, ENGINE_OFF, 2)
in 1..3 -> set(activity, ENGINE_WINFG, which + 1)
else -> set(activity, ENGINE_LSFG, which - 2)
}
dialog.dismiss()
onChanged()
}
.setNeutralButton(android.R.string.ok, null)
.show()
}
private const val TAG = "FrameGen"
}
@@ -45,11 +45,11 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
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 {
fun contains(x: Float, y: Float, r: Float, padding: Float = 0f): Boolean {
val dx = x - cx
val dy = y - cy
if (wide) return abs(dx) <= halfW + r * 0.25f && abs(dy) <= halfH + r * 0.25f
val hit = r * 1.25f
if (wide) return abs(dx) <= halfW + r * 0.25f + padding && abs(dy) <= halfH + r * 0.25f + padding
val hit = r * 1.25f + padding
return dx * dx + dy * dy <= hit * hit
}
@@ -350,6 +350,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
override fun onDraw(canvas: Canvas) {
for (control in controls) {
if (!isVisible(control)) continue
if (control.stick >= 0 && settings.adaptiveSticks && !editing && control.pressedBy == -1) continue
val held = control.pressedBy != -1
val radius = control.radius
if (control.stick >= 0) {
@@ -426,10 +427,13 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
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
val x = event.getX(index)
val y = event.getY(index)
val control = controlAt(x, y) ?: adaptiveStickAt(x, y) ?: return false
if (control.pressedBy != -1) return true
control.pressedBy = event.getPointerId(index)
if (control.stick >= 0) {
control.clicked = settings.stickClick && event.eventTime - control.lastUp < DOUBLE_TAP_MS
control.clicked = settings.stickClick && control.lastUp > 0L && 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
@@ -468,7 +472,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
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
if (control.stick >= 0 && control.pressedBy != -1) control.lastUp = if (control.clicked || event.actionMasked == MotionEvent.ACTION_CANCEL) 0L else event.eventTime
control.pressedBy = -1
control.clicked = false
if (control.stick >= 0 && (control.kx != 0f || control.ky != 0f)) control.dirty = true
@@ -505,7 +509,25 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
}
private fun controlAt(x: Float, y: Float): Control? =
controls.firstOrNull { isVisible(it) && it.contains(x, y, it.radius) }
controls.firstOrNull {
isVisible(it) && (editing || !settings.adaptiveSticks || it.stick < 0) && it.contains(x, y, it.radius)
}
private fun adaptiveStickAt(x: Float, y: Float): Control? {
if (!settings.adaptiveSticks || editing || buttonsOnly) return null
if (x < safe.left || x >= width - safe.right || y < safe.top || y >= height - safe.bottom) return null
if (controls.any { it.stick < 0 && isVisible(it) && it.contains(x, y, it.radius, 5f) }) return null
return controls.filter {
val dx = x - it.cx
val dy = y - it.cy
val reach = it.radius * 1.4f * sqrt(1.5f)
it.stick >= 0 && isVisible(it) && it.pressedBy == -1 && dx * dx + dy * dy <= reach * reach
}.minByOrNull {
val dx = x - it.cx
val dy = y - it.cy
dx * dx + dy * dy
}
}
private fun isVisible(control: Control): Boolean = when {
buttonsOnly && !editing -> control.id == "guide" || control.id == "qam"
@@ -574,6 +596,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
controls.forEach {
it.pressedBy = -1
it.clicked = false
it.lastUp = 0L
if (it.stick >= 0 && (it.kx != 0f || it.ky != 0f)) it.dirty = true
it.kx = 0f; it.ky = 0f
}
@@ -210,6 +210,8 @@ public final class LinuxRuntimeInstaller {
// runtime that isInstalled() would happily launch.
File root = LinuxRuntime.rootDir(context);
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
recoverInterruptedSwap(root, staging, old);
FileUtils.delete(staging);
if (!staging.mkdirs()) return false;
if (listener != null) listener.onProgress("Extracting", -1);
@@ -219,7 +221,6 @@ public final class LinuxRuntimeInstaller {
}
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
FileUtils.delete(old);
if (root.isDirectory() && !root.renameTo(old)) {
FileUtils.delete(staging);
@@ -244,6 +245,8 @@ public final class LinuxRuntimeInstaller {
}
if (!staging.renameTo(root)) {
File keptTo = new File(staging, USER_DATA);
if (keptTo.isDirectory() && old.isDirectory()) keptTo.renameTo(new File(old, USER_DATA));
if (old.isDirectory()) old.renameTo(root);
return false;
}
@@ -257,6 +260,24 @@ public final class LinuxRuntimeInstaller {
}
}
private static void recoverInterruptedSwap(File root, File staging, File old) {
File target = root.isDirectory() ? root : old;
File stagedHome = new File(staging, USER_DATA);
File home = new File(target, USER_DATA);
if (target.isDirectory() && stagedHome.isDirectory() && (!home.exists() || isEmptyDir(home))) {
FileUtils.delete(home);
if (stagedHome.renameTo(home)) Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update");
}
if (!root.isDirectory() && old.isDirectory() && old.renameTo(root)) {
Log.w(TAG, "restored the previous runtime after an interrupted update");
}
}
private static boolean isEmptyDir(File dir) {
String[] names = dir.list();
return dir.isDirectory() && names != null && names.length == 0;
}
/** Removes the runtime; returns false without touching it while an install is running. */
public static boolean uninstall(Context context) {
synchronized (JOB_LOCK) {
@@ -0,0 +1,75 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.AtomicFile
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import java.io.File
object GameEnvironmentStore {
private const val SETTINGS = "game-environment.json"
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
@Synchronized
fun read(context: Context): GameEnvironment.Config {
val file = AtomicFile(File(context.filesDir, SETTINGS))
val bytes = try { file.readFully() } catch (_: java.io.FileNotFoundException) { return GameEnvironment.Config() }
return decode(JSONObject(bytes.toString(Charsets.UTF_8)))
}
fun decode(json: JSONObject): GameEnvironment.Config {
require(json.getInt("version") == 1)
fun entries(value: JSONObject?): Map<String, String?> = buildMap {
value?.keys()?.forEach { name ->
require(GameEnvironment.validName(name))
val entry = value.get(name)
require(entry == JSONObject.NULL || entry is String && GameEnvironment.validValue(entry))
put(name, if (entry == JSONObject.NULL) null else entry as String)
}
}
val games = json.optJSONObject("games")
return GameEnvironment.Config(entries(json.optJSONObject("shared")), buildMap {
games?.keys()?.forEach { id ->
require(id.isNotEmpty() && GameEnvironment.validScope(id))
put(id, entries(games.getJSONObject(id)))
}
})
}
fun encode(config: GameEnvironment.Config): JSONObject {
fun entries(values: Map<String, String?>) = JSONObject().apply {
values.forEach { (key, value) -> put(key, value ?: JSONObject.NULL) }
}
return JSONObject().put("version", 1).put("shared", entries(config.shared)).put("games", JSONObject().apply {
config.games.forEach { (id, values) -> put(id, entries(values)) }
})
}
@Synchronized
fun save(context: Context, config: GameEnvironment.Config) {
val json = encode(config)
decode(json)
write(File(context.filesDir, SETTINGS), json.toString())
publish(context, config)
}
@Synchronized
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context)) + config.shared)
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), encode(resolved).toString())
}
private fun write(file: File, text: String) {
check(file.parentFile!!.isDirectory || file.parentFile!!.mkdirs())
val atomic = AtomicFile(file)
val output = atomic.startWrite()
try {
output.write(text.toByteArray(Charsets.UTF_8))
atomic.finishWrite(output)
} catch (error: Exception) {
atomic.failWrite(output)
throw error
}
}
}
@@ -17,15 +17,20 @@ import java.nio.charset.StandardCharsets
* progress, and lifting that out is the difference between "starting the Steam client" for three
* minutes and a percentage that moves.
*/
class LoadingState(context: Context) {
class LoadingState(context: Context, steam: Boolean = true) {
var visible by mutableStateOf(true)
var step by mutableStateOf("Starting the session…")
var percent by mutableIntStateOf(-1)
var elapsed by mutableStateOf("")
var hint by mutableStateOf("")
var ended by mutableStateOf(false)
/** The technical side of an ended session (exit status, log path), under the advice in [step]. */
var endedDetail by mutableStateOf<String?>(null)
private val hints = context.resources.getStringArray(com.droiddeck.launcher.R.array.loading_hints)
// The desktop and the emulators get their own: the Steam ones talk about Steam.
private val hints = context.resources.getStringArray(
if (steam) com.droiddeck.launcher.R.array.loading_hints else com.droiddeck.launcher.R.array.loading_hints_desktop,
)
private val startedAt = SystemClock.elapsedRealtime()
/** Once a second: the clock and the hint. */
@@ -35,10 +40,11 @@ class LoadingState(context: Context) {
hint = hints[((seconds / 8) % hints.size).toInt()]
}
fun showEnded(message: String) {
fun showEnded(message: String, detail: String? = null) {
visible = true
ended = true
step = message
endedDetail = detail
}
/** Re-reads the end of the log and updates the line and the bar. */
@@ -81,7 +81,7 @@ class PerfHud(context: Context) {
fun stop() {
running = false
WaylandCompositor.setGameListener(null)
WaylandCompositor.clearGameListener(listener)
text = ""
}
@@ -24,7 +24,9 @@ object SessionFiles {
* rename, so a session that still has one mapped keeps the file it opened.
*/
fun stage(context: Context, root: File) {
GameEnvironmentStore.publish(context)
val files = arrayOf(
"usr/local/bin/bannerlator-game-env" to "usr/local/bin/bannerlator-game-env",
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
@@ -298,6 +298,8 @@ object SessionPrefs {
fun setFexPreset(context: Context, id: String) {
prefs(context).edit().putString("fexPreset", id).apply()
runCatching { GameEnvironmentStore.publish(context) }
.onFailure { android.util.Log.e("GameEnvironment", "Could not update game environment", it) }
}
/** The Steam client branch forced on the command line: "publicbeta" (every session so far) or "steamdeck_publicbeta" (Armada's). */
@@ -57,6 +57,7 @@ import java.util.Locale
*/
class SessionService : Service() {
private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>()
private val stopLock = Any()
private var wakeLock: PowerManager.WakeLock? = null
private var wifiLock: WifiManager.WifiLock? = null
private var sessionPid = -1
@@ -84,7 +85,7 @@ class SessionService : Service() {
}
}
/** Counts sessions this service has started; a process exit from an earlier one is ignored. */
private var sessionGen = 0
@Volatile private var sessionGen = 0
override fun onCreate() {
super.onCreate()
@@ -392,6 +393,11 @@ class SessionService : Service() {
networkLink.attach(this)
networkLink.publish()
components.add(networkLink)
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while it was starting; not launching it")
if (gen == sessionGen) components.clear()
return
}
components.forEach { it.start() }
val line = command.joinToString(" ") {
@@ -402,7 +408,7 @@ class SessionService : Service() {
// by the teardown a second after the new one has started, and its exit used to arrive
// here as "session ended: 137" and end the NEW session. An exit belongs to the session
// that started it.
sessionPid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
val pid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
@@ -410,12 +416,24 @@ class SessionService : Service() {
Log.i(TAG, "session ended: $status")
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)
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while its guest was starting; taking it down")
if (gen == sessionGen) {
launchWatcher?.stopWatching()
launchWatcher = null
components.reversed().forEach { runCatching { it.stop() } }
components.clear()
}
if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start()
return
}
sessionPid = pid
if (pid > 1) {
SessionEvents.guestStarted(pid)
} else {
SessionEvents.record("guest.start_failed", mapOf("pid" to pid))
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", pid)
stopSession(-1)
return
}
@@ -510,15 +528,6 @@ class SessionService : Service() {
// 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.
if (SessionPrefs.noXalia(this)) guest.add("PROTON_USE_XALIA=0")
// 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 (steamHere) {
val preset = SessionPrefs.fexPreset(this)
val vars = com.droiddeck.launcher.core.FexPreset.env(preset)
vars.forEach { guest.add(it) }
if (vars.isNotEmpty()) Log.i(TAG, "fex preset $preset: ${vars.joinToString(" ")}")
}
// Anything else, for a device that cannot be reached with a debugger: Downloads/droiddeck-env
// holds KEY=VALUE lines that go into the session's environment as written, after ours, so a
// line here wins. Zink and Turnip tunables (ZINK_DESCRIPTORS=lazy, MESA_*), gamescope's,
@@ -741,6 +750,30 @@ class SessionService : Service() {
* behind, still holding the Wayland socket and the audio server the next session needs. They
* are our uid, so they are ours to kill.
*/
/**
* Every process of ours still running a program out of the Linux runtime once proot is gone.
* proot's --kill-on-exit and the tree sweep only reach what proot still traces; a tracee it
* lost - an Xwayland that aborted from one thread and then looped on a syscall proot's own
* seccomp filter, with no tracer left, answers ENOSYS - survives both, reparented to init,
* and wrote 9 GB of one line into the session log before anything killed it.
*/
private fun killGuestLeftovers() {
val me = android.os.Process.myPid()
val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/"
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
var killed = 0
for (proc in procs) {
val pid = proc.name.toIntOrNull() ?: continue
if (pid == me) continue
// Another uid's exe is not ours to read; a process already gone has none.
val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue }
if (!exe.startsWith(rootfs)) continue
android.os.Process.killProcess(pid)
killed++
}
if (killed > 0) Log.w(TAG, "killed $killed guest process(es) proot no longer tracked")
}
private fun killStragglers() {
val me = android.os.Process.myPid()
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
@@ -853,8 +886,12 @@ class SessionService : Service() {
}
}
private fun finishSessionStop(status: Int) {
private fun finishSessionStop(status: Int, stoppedGen: Int) {
mainHandler.post {
if (stoppedGen != sessionGen || SessionState.running) {
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
return@post
}
SessionState.suspended = false
SessionState.guestPid = -1
releaseLocks()
@@ -873,8 +910,11 @@ class SessionService : Service() {
}
private fun stopSession(status: Int) {
if (!SessionState.running) return
SessionState.running = false
synchronized(stopLock) {
if (!SessionState.running) return
SessionState.running = false
}
val stoppedGen = sessionGen
SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
@@ -917,10 +957,11 @@ class SessionService : Service() {
Thread({
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
finishSessionStop(status)
killGuestLeftovers()
finishSessionStop(status, stoppedGen)
}, "session-teardown").start()
} else {
finishSessionStop(status)
finishSessionStop(status, stoppedGen)
}
}
if (prootPid > 1) acquireLocks()
@@ -1102,6 +1143,10 @@ class SessionService : Service() {
}
fun stop(context: Context) {
if (!SessionState.running) {
SessionState.stopRequested = true
return
}
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
}
@@ -325,7 +325,7 @@ private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean =
val hot = (src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value) && enabled
Box(
contentAlignment = Alignment.Center,
modifier = modifier.heightIn(min = 40.dp).clip(RoundedCornerShape(10.dp))
modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp))
.background(if (hot) pal.signal else colors.surfaceVariant)
.border(2.dp, if (hot) colors.onBackground else pal.line2, RoundedCornerShape(10.dp))
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
@@ -41,12 +41,12 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
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) {
SettingsRow("Color", "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 ->
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = "Color") { 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)
@@ -59,7 +59,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
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)
ToggleRow(host, "controller-adaptive", "Adaptive sticks", "Sticks appear when touched near their saved positions and hide when released", 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() }
@@ -68,7 +68,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
}
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)
ActionRow("Reset controller", "Restore the default color, opacity, size, stick behavior, mapping and layout", "Reset", a.onResetAll)
}
@Composable
@@ -0,0 +1,22 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.Composable
import com.droiddeck.launcher.gpu.FrameGen
/**
* The frame generation picker, anchored to whatever opened it (host key "fg"). One copy for Setup,
* a game's launch settings and the session drawer, so they say the same thing.
*/
@Composable
internal fun FrameGenMenu(
host: MenuHost, engine: String, multiplier: Int, lsfgReady: Boolean,
onPick: (engine: String, multiplier: Int) -> Unit,
) {
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
val need = if (lsfgReady) null else "Needs Lossless Scaling installed in Steam"
fun pick(e: String, m: Int) { onPick(e, m); host.open = null }
MenuItem("Off", checked = engine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { pick(FrameGen.ENGINE_OFF, 2) }
for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_WINFG, m), checked = engine == FrameGen.ENGINE_WINFG && multiplier == m) { pick(FrameGen.ENGINE_WINFG, m) }
for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_LSFG, m), checked = engine == FrameGen.ENGINE_LSFG && multiplier == m, enabled = lsfgReady, detail = need) { pick(FrameGen.ENGINE_LSFG, m) }
}
}
@@ -223,10 +223,11 @@ private fun Content(
if (e.installed) {
Rise(3) {
Actions {
PrimaryButton("Open ${e.name}", enabled = s.ready && !s.busy, main = true) { a.onEmulator(e) }
PrimaryButton("Open ${e.name}", enabled = !s.busy, main = true) { a.onEmulator(e) }
BusyChip(s)
SecondaryButton("ROMs folder", onClick = a.onRoms)
if (pkg != null) SecondaryButton(
if (pkg.kind == "appimage") "Remove" else "Forget",
if (pkg.kind == "appimage") "Remove" else "Hide",
enabled = s.packageBusyId == null && !s.sessionRunning,
) { a.onRemovePackage(pkg.id) }
}
@@ -274,7 +275,7 @@ private fun Content(
if (s.packagePercent >= 0) LinearProgressIndicator(progress = { s.packagePercent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
}
if (pkg?.kind == "tar") Rise(5) { Note("Forgetting this package hides it from Desktop; its files remain in the Linux runtime.") }
if (pkg?.kind == "tar") Rise(5) { Note("Hiding this package takes it off Desktop; its files stay in the Linux runtime.") }
}
}
}
@@ -296,8 +297,8 @@ private fun Content(
Spacer(Modifier.height(14.dp))
Actions {
Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp))
PrimaryButton("Launch in ${e.name}", enabled = s.ready && !s.busy, main = true) { a.onRom(g) }
ActionChip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false)
PrimaryButton("Launch in ${e.name}", enabled = !s.busy, main = true) { a.onRom(g) }
if (s.busy) BusyChip(s) else ActionChip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false)
}
}
if (g.art != null && !narrow) Poster(g.art, g.name, Modifier.width(detailPosterWidth))
@@ -315,7 +316,7 @@ private fun Content(
}
}
}
else -> Note("Select an item.")
else -> Note("That page is gone. Pick a section on the left.")
}
}
}
@@ -331,6 +332,7 @@ private fun DesktopCard(s: FrontEndState, a: FrontEndActions) {
// Enabled without a runtime or the desktop: the session's loading screen installs them first.
PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, main = true, onClick = a.onDesktop)
Cog(onClick = a.onDesktopSettings)
BusyChip(s)
}
}
Column(
@@ -62,16 +62,26 @@ import com.droiddeck.launcher.frontend.Library
@Composable
internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, onSelect: (String) -> Unit, modifier: Modifier) {
val games = remember(s.steamGames) { s.steamGames.sortedByDescending { it.lastPlayed } }
val current = games.firstOrNull { "app:${it.appId}" == selected } ?: games.firstOrNull() ?: return
val host = rememberMenuHost()
val narrow = LocalNarrowPane.current
val current = games.firstOrNull { "app:${it.appId}" == selected } ?: games.firstOrNull()
if (current == null) {
Column(modifier = modifier.padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
Rise(0) { PageHeader("Games") }
Rise(1) { Note("Games you install in Steam show up here. Open Steam, install one, and it appears after the session.") }
Rise(2) {
Actions { PrimaryButton("Play Steam", enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp), onClick = a.onPlay) }
}
}
return
}
val host = rememberMenuHost()
if (games.size == 1) {
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
Rise(0) {
Row(verticalAlignment = Alignment.Bottom) {
GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp)) {
GameHeroCopy(current, if (narrow) 28.sp else 38.sp)
PrimaryButton("Launch", enabled = s.ready && !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(current) }
GameActions(current, s, a)
}
if (!narrow) Poster(current.art, current.name, Modifier.width(168.dp))
}
@@ -92,7 +102,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
) {
GameHero(current, Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 200.dp)) {
GameHeroCopy(current, if (narrow) 24.sp else 32.sp)
PrimaryButton("Launch", enabled = s.ready && !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(current) }
GameActions(current, s, a)
}
SectionTitle("Launch settings", null)
LaunchSettings(s, a, host)
@@ -100,6 +110,21 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
}
}
@Composable
private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions) {
Actions {
PrimaryButton("Launch", enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(g) }
g.gameFiles?.takeIf { it.isDirectory }?.let { dir ->
SecondaryButton("Game files", compact = true) { a.onBrowseFiles(dir) }
}
g.protonPrefix?.takeIf { it.isDirectory }?.let { dir ->
SecondaryButton("Proton prefix", compact = true) { a.onBrowseFiles(dir) }
}
BusyChip(s)
}
}
/** When it was last played (or where it is, if never) over its name, then room for Launch. */
@Composable
private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
@@ -183,6 +208,12 @@ internal fun PageHeader(title: String, trailing: @Composable RowScope.() -> Unit
}
}
/** Why a launch button is greyed out: the runtime is being worked on. Nothing when it is not. */
@Composable
internal fun BusyChip(s: FrontEndState) {
if (s.busy) ActionChip(if (s.percent >= 0) "Runtime busy · ${s.percent}%" else "Runtime busy", ok = false)
}
/** Whether Steam can start, said where Play is rather than only in Setup. */
@Composable
internal fun RuntimeChip(s: FrontEndState) = when {
@@ -53,6 +53,8 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.layout.widthIn
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
@@ -78,7 +80,7 @@ import com.droiddeck.launcher.core.PhantomProcessLimit
/** What the pad's face buttons do here, along the bottom edge as on a console. */
@Composable
internal fun ControllerHints() {
internal fun ControllerHints(select: String = "Select", tabs: Boolean = false) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(modifier = Modifier.fillMaxWidth()) {
@@ -88,7 +90,8 @@ internal fun ControllerHints() {
horizontalArrangement = Arrangement.spacedBy(18.dp, Alignment.End),
modifier = Modifier.fillMaxWidth().height(34.dp).background(colors.surface).padding(horizontal = 20.dp),
) {
HintGlyph("A", "Select")
if (tabs) HintGlyph("LB RB", "Tabs")
HintGlyph("A", select)
HintGlyph("B", "Back")
}
}
@@ -98,7 +101,12 @@ internal fun ControllerHints() {
private fun HintGlyph(button: String, action: String) {
val colors = MaterialTheme.colorScheme
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).clip(CircleShape).background(colors.onBackground)) {
// Face buttons are round; bumpers are a wider keycap.
val shape = if (button.length == 1) CircleShape else RoundedCornerShape(6.dp)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.height(20.dp).widthIn(min = 20.dp).clip(shape).background(colors.onBackground).padding(horizontal = if (button.length == 1) 0.dp else 6.dp),
) {
Text(button, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.background)
}
Text(action, fontSize = 13.sp, color = colors.onSurfaceVariant)
@@ -133,12 +141,13 @@ internal fun SideRail(
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()),
) {
if (s.isHomeApp) RailItem("Apps", Icons.Outlined.Apps, "android-apps", selected == "android-apps", compact, iconOnly, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
RailItem("Steam", Icons.Outlined.SportsEsports, "steam", selected == "steam", compact, iconOnly, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
// Games appears once there is one: an empty list is no place to land.
if (s.steamGames.isNotEmpty()) RailItem("Games", Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, onFocus = { onFocusSelect("games") }) { onSelect("games") }
// Always there, so the items below it never move; an empty library says how to fill it.
RailItem("Games", Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, onFocus = { onFocusSelect("games") }) { onSelect("games") }
RailItem("Desktop", Icons.Outlined.DesktopWindows, "desktop", selected == "desktop", compact, iconOnly, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
RailItem("Components", Icons.Outlined.Layers, "components", selected == "components", compact, iconOnly, onFocus = { onFocusSelect("components") }) { onSelect("components") }
// Home mode's extra section goes last, so it shifts nothing above it.
if (s.isHomeApp) RailItem("Apps", Icons.Outlined.Apps, "android-apps", selected == "android-apps", compact, iconOnly, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
RailItem("Setup", Icons.Outlined.Tune, "setup", selected == "setup", compact, iconOnly, badge = setupNeedsAttention, onFocus = { onFocusSelect("setup") }) { onSelect("setup") }
}
AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
@@ -222,7 +231,9 @@ private fun ResumeRailItem(name: String, compact: Boolean, iconOnly: Boolean, on
val focused by src.collectIsFocusedAsState()
val hovered by src.collectIsHoveredAsState()
val pulse = rememberInfiniteTransition(label = "pulse")
val ringScale by pulse.animateFloat(0.4f, 1.6f, infiniteRepeatable(tween(1600, easing = Motion.Ease), RepeatMode.Restart), label = "ring")
val ringScale by pulse.animateFloat(0.4f, 1.6f, infiniteRepeatable(tween(Motion.ms(1600).coerceAtLeast(1), easing = Motion.Ease), RepeatMode.Restart), label = "ring")
// Animations off: the live dot alone, no pulsing ring.
val still = Motion.scale == 0f
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(3.dp),
@@ -238,7 +249,7 @@ private fun ResumeRailItem(name: String, compact: Boolean, iconOnly: Boolean, on
.padding(vertical = if (iconOnly) 15.dp else if (compact) 6.dp else 9.dp, horizontal = 4.dp),
) {
Box(modifier = Modifier.size(14.dp), contentAlignment = Alignment.Center) {
Box(modifier = Modifier.size(14.dp).graphicsLayer { scaleX = ringScale; scaleY = ringScale; alpha = (1.6f - ringScale) / 1.2f }.border(1.5.dp, pal.good, CircleShape))
if (!still) Box(modifier = Modifier.size(14.dp).graphicsLayer { scaleX = ringScale; scaleY = ringScale; alpha = (1.6f - ringScale) / 1.2f }.border(1.5.dp, pal.good, CircleShape))
Box(modifier = Modifier.size(7.dp).clip(CircleShape).background(pal.good))
}
// Icons only: the live dot alone says something is running; its description says what.
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.ui
import java.io.File
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.ExperimentalComposeUiApi
@@ -71,6 +73,7 @@ import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.roundToInt
import kotlinx.coroutines.withTimeoutOrNull
class FrontEndState(
val installed: String?,
@@ -133,6 +136,7 @@ class FrontEndActions(
val onPerformance: () -> Unit,
val onRoms: () -> Unit,
val onFiles: () -> Unit,
val onBrowseFiles: (File) -> Unit = {},
val onLogs: () -> Unit,
val onShareLogs: () -> Unit = {},
val onOffline: () -> Unit,
@@ -147,10 +151,10 @@ class FrontEndActions(
val onCheckLatestBuild: () -> Unit = {},
val onRefreshPhantomStatus: () -> Unit = {},
val onOpenDeveloperOptions: (Int?) -> Unit = {},
val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless ADB is unavailable") },
val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless debugging is unavailable") },
val onFindWirelessAdbPort: (String, (Int?) -> Unit) -> Unit = { _, done -> done(null) },
val onWirelessAdbApply: (String, Int, Boolean, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless ADB is unavailable") },
val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit = { _, done -> done("Wireless ADB is unavailable") },
val onWirelessAdbApply: (String, Int, Boolean, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless debugging is unavailable") },
val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit = { _, done -> done("Wireless debugging is unavailable") },
val onCopyPhantomCommand: (Boolean) -> Unit = {},
val onDismissPhantomGate: () -> Unit = {},
val controller: ControllerActions? = null,
@@ -158,6 +162,10 @@ class FrontEndActions(
internal object Motion {
var scale = 1f
/** The system's animator scale, re-read on each resume so "Remove animations" applies without a restart. */
fun refresh(context: android.content.Context) {
scale = Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f)
}
val Ease = CubicBezierEasing(0.2f, 0.8f, 0.2f, 1f)
fun ms(base: Int) = (base * scale).roundToInt()
fun <T> tw(base: Int, delay: Int = 0): FiniteAnimationSpec<T> = if (scale == 0f) snap() else tween(ms(base), ms(delay), Ease)
@@ -229,7 +237,8 @@ internal class FrontFocus {
// and the last one focused.
val items = HashMap<String, FocusRequester>()
val attached = HashMap<String, Int>()
var last: String? = null
// State, so the controller hints follow it: A launches from a game row but selects elsewhere.
var last by mutableStateOf<String?>(null)
// The first tile of the page's grid: Down from the page's buttons goes to it, not to whichever
// tile happens to sit under the button.
val firstTile = FocusRequester()
@@ -278,6 +287,22 @@ internal fun Modifier.paneItem(id: String): Modifier {
internal val LocalFrontFocus = staticCompositionLocalOf<FrontFocus?> { null }
/** The pane's exit animation (170ms) and a frame's margin: a new page is in after this. */
private const val PAGE_EXIT_MS = 200
/**
* Asks [target] for focus once a frame until [done] (or a focus request lands), for at most half a
* second: a control can take focus only once it is laid out, and that is a frame or two, not a
* fixed number of milliseconds.
*/
internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusRequester) {
repeat(30) {
androidx.compose.runtime.withFrameNanos { }
if (done()) return
if (runCatching { target().requestFocus() }.isSuccess && done()) return
}
}
@Composable
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
val frontFocus = remember { FrontFocus() }
@@ -323,11 +348,11 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
selected = if (selected.startsWith("emu:")) "desktop" else "emu:" + selected.removePrefix("rom:").substringBefore(':')
}
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
// The last game uninstalled takes the Games tab with it.
// The last game uninstalled leaves the Games tab on its empty state.
LaunchedEffect(s.steamGames.isEmpty()) {
if (s.steamGames.isEmpty() && (selected == "games" || selected.startsWith("app:"))) selected = "steam"
if (s.steamGames.isEmpty() && selected.startsWith("app:")) selected = "games"
}
remember { Motion.scale = Settings.Global.getFloat(ctx.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f); true }
remember { Motion.refresh(ctx); true }
val railSelection = when {
s.pageKey == "performance" || s.pageKey == "protons" || s.pageKey == "controller-mapping" -> "setup"
@@ -367,32 +392,27 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
LaunchedEffect(processSettingsPageVisible) {
if (processSettingsPageVisible) return@LaunchedEffect
snapshotFlow { window.isWindowFocused }.first { it }
repeat(20) {
if (anyFocused) return@LaunchedEffect
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
val target = if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection)
runCatching { target.requestFocus() }
kotlinx.coroutines.delay(100)
}
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
}
// A tile or button that opens a page goes away with the page it was on, and focus with it;
// the pad then had nothing to move from (a press landed back on the rail's first item). So
// once the new page is in, a controller lands on its main button.
LaunchedEffect(selected, s.pageKey, processSettingsPageVisible) {
if (processSettingsPageVisible) return@LaunchedEffect
kotlinx.coroutines.delay(450)
if (!anyFocused && inputModeManager.inputMode == InputMode.Keyboard) runCatching {
if (frontFocus.primaryAttached > 0) frontFocus.primary.requestFocus()
else frontFocus.railFor(railSelection).requestFocus()
}
// Past the old page's exit (170ms), then the first frame the new page takes focus.
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
if (anyFocused || inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
}
// A rail item picked with a controller moves on into its page, once the page is in.
LaunchedEffect(railPicks) {
if (railPicks == 0 || processSettingsPageVisible) return@LaunchedEffect
kotlinx.coroutines.delay(450)
if (inputModeManager.inputMode == InputMode.Keyboard && frontFocus.primaryAttached > 0) runCatching {
frontFocus.paneEntry().requestFocus()
}
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
// Waits for the new page's main button rather than a fixed guess at how long it takes.
withTimeoutOrNull(1_000) { snapshotFlow { frontFocus.primaryAttached > 0 }.first { it } } ?: return@LaunchedEffect
focusWithinFrames({ frontFocus.focusedRail == null && anyFocused }) { frontFocus.paneEntry() }
}
val paneFocus = Modifier
.focusProperties { enter = { frontFocus.paneEntry() } }
@@ -417,7 +437,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
AnimatedVisibility(
inputModeManager.inputMode == InputMode.Keyboard,
enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut(),
) { ControllerHints() }
) {
val onGame = frontFocus.focusedRail == null && frontFocus.last?.startsWith("game:") == true
ControllerHints(
select = if (onGame) "Launch" else "Select",
tabs = railSelection == "setup" && s.pageKey == null && frontFocus.focusedRail == null,
)
}
}
}
@@ -65,12 +65,10 @@ import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
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.sp
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
@@ -209,8 +207,13 @@ internal fun SetupPanel(
) { SecondaryButton(runtime, enabled = !s.busy, compact = true, onClick = a.onRuntime) }
CheckRow(
if (limitBlocks) CheckState.WARN else CheckState.OK,
if (limitBlocks) "Android may close Steam" else "Android process limit",
if (limitBlocks) "“Restrict child processes” is on - it takes a minute to turn off" else PhantomProcessLimit.title(s.phantomProcessStatus),
"Child-process limit",
when (s.phantomProcessStatus) {
PhantomProcessStatus.ENABLED -> "On · Android may close Steam. Turning it off takes a minute"
PhantomProcessStatus.UNSET -> "Not set · the ROM default may close Steam. Turning it off takes a minute"
PhantomProcessStatus.UNREADABLE -> "Could not be checked · turning it off takes a minute"
else -> PhantomProcessLimit.title(s.phantomProcessStatus)
},
) {
if (limitBlocks) PrimaryButton(if (showLimitDetails) "Hide" else "Fix it", compact = true) { showLimitDetails = !showLimitDetails }
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
@@ -218,32 +221,25 @@ internal fun SetupPanel(
}
}
AnimatedVisibility(showLimitDetails, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
// One sentence and at most three buttons. The computer route and its
// raw command live on the full page Wireless debugging opens.
Column(modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, top = 4.dp, bottom = 10.dp)) {
Text(
PhantomProcessLimit.instructions(s.phantomProcessStatus),
if (limitBlocks) PhantomProcessLimit.gateInstructions(s.phantomProcessStatus)
else PhantomProcessLimit.instructions(s.phantomProcessStatus),
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(vertical = 6.dp)) {
SecondaryButton("Developer options", compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton("Check again", compact = true, onClick = a.onRefreshPhantomStatus)
SecondaryButton("Copy ADB command", compact = true, onClick = { a.onCopyPhantomCommand(false) })
}
Text(
PhantomProcessLimit.ADB_COMMAND, fontSize = 12.sp, fontFamily = FontFamily.Monospace,
color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
)
if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
Text(
"With wireless debugging paired, DroidDeck can switch the limit itself. Turning it off is recommended for Steam sessions.",
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp),
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(vertical = 6.dp)) {
SecondaryButton("Turn limit off", compact = true, enabled = !processLimitBusy && s.phantomProcessStatus != PhantomProcessStatus.DISABLED) { setProcessLimit(false) }
SecondaryButton("Turn limit on", compact = true, enabled = !processLimitBusy && s.phantomProcessStatus != PhantomProcessStatus.ENABLED) { setProcessLimit(true) }
Actions {
if (limitBlocks) {
PrimaryButton("Developer options", compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton("Use Wireless debugging", compact = true, enabled = !processLimitBusy) { setProcessLimit(false) }
SecondaryButton("Check again", compact = true, onClick = a.onRefreshPhantomStatus)
} else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
SecondaryButton("Turn limit on", compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
}
if (processLimitBusy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp))
processLimitMessage?.let { Text(it, fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp)) }
}
if (processLimitBusy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp))
processLimitMessage?.let { Text(it, fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp)) }
}
}
CheckRow(
@@ -278,15 +274,13 @@ internal fun SetupPanel(
FrameGenMenu(s, a, host)
}
}
SettingsRow("Session logs", "${if (s.logsEnabled) "Enabled" else "Disabled"} · logs are saved after each session") {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SecondaryButton(if (s.logsEnabled) "Turn off" else "Turn on") { a.onLogs() }
SecondaryButton("Share latest") { a.onShareLogs() }
}
}
SettingsRow("Offline mode", s.offlineAccount?.let { if (s.offline) "Enabled for $it" else "Signed in as $it" } ?: "Sign in to Steam first") {
SecondaryButton(if (s.offline) "Turn off" else "Turn on", enabled = s.offlineAccount != null) { a.onOffline() }
}
ToggleRow(host, "logs", "Session logs", "Saved after each session", s.logsEnabled) { a.onLogs() }
ActionRow("Latest session logs", "Send them with a bug report", "Share logs", a.onShareLogs)
ToggleRow(
host, "offline", "Offline mode",
s.offlineAccount?.let { "Signed in as $it" } ?: "Sign in to Steam first",
s.offline, enabled = s.offlineAccount != null,
) { a.onOffline() }
}
}
3 -> {
@@ -337,7 +331,7 @@ private fun ToolGrid(s: FrontEndState, a: FrontEndActions) {
val columns = if (LocalNarrowPane.current) 2 else 4
val tools = listOf(
ToolSpec(Icons.Outlined.Folder, "Files", "Browse and manage files", a.onFiles),
ToolSpec(Icons.Outlined.Extension, "Compatibility tools", "Install ARM64 Proton builds", a.onProtons),
ToolSpec(Icons.Outlined.Extension, "Proton versions", "Install ARM64 Proton builds", a.onProtons),
ToolSpec(Icons.Outlined.Speed, "Performance", "CPU core assignment", a.onPerformance),
ToolSpec(Icons.Outlined.VideogameAsset, "ROMs folder", s.romsDir ?: "Choose where emulator games are stored", a.onRoms),
)
@@ -380,12 +374,7 @@ private fun ToolCard(t: ToolSpec, modifier: Modifier) {
@Composable
private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
val need = if (s.lsfgReady) null else "Install Lossless Scaling in Steam"
MenuItem("Off", checked = s.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 = s.frameGenEngine == FrameGen.ENGINE_WINFG && s.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
for (m in 2..4) MenuItem("LSFG ${m}×", checked = s.frameGenEngine == FrameGen.ENGINE_LSFG && s.frameGenMultiplier == m, enabled = s.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
}
FrameGenMenu(host, s.frameGenEngine, s.frameGenMultiplier, s.lsfgReady, a.onFrameGenPick)
}
/**
@@ -398,7 +387,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val columns = if (LocalNarrowPane.current) 2 else 3
val controller = a.controller
val cards = buildList<@Composable (Modifier) -> Unit> {
add { m -> SettingCard("Compatibility", "Proton & components", "card:components", m) { a.onComponents(true) } }
add { m -> SettingCard("Components", "FEX, DXVK, VKD3D", "card:components", m) { a.onComponents(true) } }
add { m ->
Box(m) {
SettingCard("Frame generation", s.frameGenLabel, "card:fg", Modifier.fillMaxSize()) {
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import android.provider.Settings
@@ -111,7 +113,7 @@ internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Un
val shape = RoundedCornerShape(22.dp)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.paneItem("back:$label").heightIn(min = if (compact) 36.dp else 44.dp)
modifier = Modifier.paneItem("back:$label").heightIn(min = if (compact) 44.dp else 48.dp)
.clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.04f))
.border(2.dp, if (hot) pal.signal else Color.Transparent, shape)
@@ -163,18 +165,26 @@ internal fun PrimaryButton(
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "btnScale")
val lift by animateFloatAsState(if (hot) 14f else 6f, Motion.tw(300), label = "btnLift")
// Where it sits, so a session it starts can grow out of it (LaunchFlood).
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier.then(track)
.onGloballyPositioned { placed[0] = it }
// 48dp to touch on a handheld; compact rows keep 44.
.heightIn(min = if (compact) 44.dp else 48.dp)
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.primary).onFocusChanged { if (it.isFocused) frontFocus.last = FrontFocus.PRIMARY } else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
.graphicsLayer { alpha = if (LaunchOrigin.flooding === placed) 0f else 1f; scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
.clip(Shape12)
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
.shine(hot, 0.45f)
// The grow and shine alone barely show on the light fill: outline it when a
// controller is on it, as the other controls are.
.border(2.dp, if (hot) pal.signal else Color.Transparent, Shape12)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled) {
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
onClick()
}
.padding(
start = if (large) 20.dp else if (compact) 10.dp else if (icon != null) 14.dp else 18.dp,
end = if (large) 26.dp else if (compact) 10.dp else 18.dp,
@@ -202,7 +212,8 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "secEdge")
val fill by animateColorAsState(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f), Motion.tw(250), label = "secFill")
Box(
modifier = modifier.paneItem("btn:$text").downToFirstTile().graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12)
contentAlignment = Alignment.Center,
modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
@@ -211,7 +222,7 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo
}
@Composable
internal fun Cog(size: androidx.compose.ui.unit.Dp = 42.dp, onClick: () -> Unit) {
internal fun Cog(size: androidx.compose.ui.unit.Dp = 48.dp, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
@@ -0,0 +1,234 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.GameEnvironmentOptions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.input.KeyboardType
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.GameEnvironmentStore
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
fun GameEnvironmentRow(modifier: Modifier = Modifier) {
var open by remember { mutableStateOf(false) }
SettingsRow(stringResource(R.string.game_env_title), stringResource(R.string.game_env_hint)) {
TextButton(onClick = { open = true }, modifier = modifier.controllerConfirm { open = true }) {
Text(stringResource(R.string.game_env_edit))
}
}
if (open) GameEnvironmentEditor { open = false }
}
@Composable
private fun GameEnvironmentEditor(onClose: () -> Unit) {
val context = LocalContext.current
val coroutine = rememberCoroutineScope()
var config by remember { mutableStateOf<GameEnvironment.Config?>(null) }
var games by remember { mutableStateOf(emptyList<Pair<String, String>>()) }
var scope by remember { mutableStateOf("") }
var appId by remember { mutableStateOf("") }
var scopeMenu by remember { mutableStateOf(false) }
var addMenu by remember { mutableStateOf(false) }
var busy by remember { mutableStateOf(false) }
var error by remember { mutableStateOf(false) }
var editing by remember { mutableStateOf<Pair<String, String>?>(null) }
val preset = SessionPrefs.fexPreset(context)
LaunchedEffect(Unit) {
runCatching {
withContext(Dispatchers.IO) {
GameEnvironmentStore.read(context) to Library.steamGames(context).map { it.appId.toString() to it.name }
}
}.onSuccess { (settings, installed) -> config = settings; games = installed }
.onFailure { error = true }
}
fun save(next: GameEnvironment.Config) {
busy = true
coroutine.launch {
val result = runCatching { withContext(Dispatchers.IO) { GameEnvironmentStore.save(context, next) } }
result.onSuccess { config = next; error = false }.onFailure { error = true }
busy = false
}
}
AlertDialog(
onDismissRequest = { if (!busy) onClose() },
title = { Text(stringResource(R.string.game_env_title)) },
confirmButton = { TextButton(onClick = onClose, enabled = !busy) { Text(stringResource(R.string.game_env_close)) } },
text = {
Column(Modifier.heightIn(max = 460.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(stringResource(R.string.game_env_hint))
Text(stringResource(R.string.game_env_defaults), style = MaterialTheme.typography.bodySmall)
if (error) Text(stringResource(R.string.game_env_error), color = MaterialTheme.colorScheme.error)
if (config == null && !error) Text(stringResource(R.string.game_env_loading))
val current = config
if (current != null) {
val profileName = if (scope.isEmpty()) stringResource(R.string.game_env_shared)
else games.firstOrNull { it.first == scope }?.second ?: stringResource(R.string.game_env_profile, scope)
Text(stringResource(R.string.game_env_scope), style = MaterialTheme.typography.labelMedium)
Box {
TextButton(onClick = { scopeMenu = true }, enabled = !busy) { Text(profileName) }
DropdownMenu(expanded = scopeMenu, onDismissRequest = { scopeMenu = false }, modifier = Modifier.heightIn(max = 280.dp)) {
DropdownMenuItem(text = { Text(stringResource(R.string.game_env_shared)) }, onClick = { scope = ""; scopeMenu = false })
val profiles = (games + current.games.keys.filter { id -> games.none { it.first == id } }.map { it to it }).distinctBy { it.first }
for ((id, name) in profiles) DropdownMenuItem(text = { Text(name) }, onClick = { scope = id; scopeMenu = false })
}
}
OutlinedTextField(value = appId, onValueChange = { appId = it }, singleLine = true, enabled = !busy,
label = { Text(stringResource(R.string.game_env_app_id)) }, modifier = Modifier.fillMaxWidth())
TextButton(onClick = { scope = appId.toLong().toString(); appId = "" }, enabled = !busy && appId.isNotEmpty() && GameEnvironment.validScope(appId)) {
Text(stringResource(R.string.game_env_open))
}
Text(stringResource(R.string.game_env_overrides), style = MaterialTheme.typography.bodySmall)
val entries = GameEnvironment.effective(current, preset, scope).toSortedMap()
if (entries.isEmpty()) Text(stringResource(R.string.game_env_empty))
for ((name, value) in entries) {
HorizontalDivider()
Text(name, style = MaterialTheme.typography.titleSmall)
Text(value ?: stringResource(R.string.game_env_unset))
if (!current.entries(scope).containsKey(name)) Text(stringResource(R.string.game_env_inherited), style = MaterialTheme.typography.labelSmall)
Row {
TextButton(onClick = { editing = name to (value ?: "") }, enabled = !busy) { Text(stringResource(R.string.game_env_edit)) }
if (value != null) TextButton(onClick = { save(current.withEntries(scope, current.entries(scope) + (name to null))) }, enabled = !busy) {
Text(stringResource(R.string.game_env_remove))
}
}
if (current.entries(scope).containsKey(name)) TextButton(onClick = { save(current.withEntries(scope, current.entries(scope) - name)) }, enabled = !busy) {
Text(stringResource(R.string.game_env_restore))
}
}
Box {
TextButton(onClick = { addMenu = true }, enabled = !busy) { Text(stringResource(R.string.game_env_add)) }
DropdownMenu(expanded = addMenu, onDismissRequest = { addMenu = false }, modifier = Modifier.heightIn(max = 280.dp)) {
DropdownMenuItem(text = { Text(stringResource(R.string.game_env_custom)) }, onClick = { editing = "" to ""; addMenu = false })
for (option in GameEnvironmentOptions.all) DropdownMenuItem(text = { Text(option.name) }, onClick = { editing = option.name to option.value; addMenu = false })
}
}
TextButton(onClick = { save(current.withEntries(scope, emptyMap())) }, enabled = !busy && current.entries(scope).isNotEmpty()) {
Text(stringResource(R.string.game_env_reset))
}
}
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
}
},
)
editing?.let { (name, value) ->
VariableDialog(name, value, onDismiss = { editing = null }) { key, content ->
config?.let {
val entries = it.entries(scope).toMutableMap()
if (name.isNotEmpty() && name != key) entries[name] = null
entries[key] = content
save(it.withEntries(scope, entries))
}
editing = null
}
}
}
@Composable
private fun VariableDialog(initialName: String, initialValue: String, onDismiss: () -> Unit, onSave: (String, String) -> Unit) {
var name by remember { mutableStateOf(initialName) }
var value by remember { mutableStateOf(initialValue) }
val valid = GameEnvironment.validName(name) && GameEnvironment.validValue(value)
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.game_env_edit)) },
confirmButton = { TextButton(onClick = { onSave(name, value) }, enabled = valid) { Text(stringResource(R.string.game_env_save)) } },
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.game_env_cancel)) } },
text = {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
VariableNamePicker(name) { selected ->
name = selected
value = GameEnvironmentOptions.find(selected)?.value.orEmpty()
}
VariableValueEditor(name, value) { value = it }
GameEnvironmentOptions.find(name)?.takeIf { it.detail != 0 }?.let {
Text(stringResource(it.detail), style = MaterialTheme.typography.bodySmall)
}
if (!GameEnvironment.supported(name)) Text(stringResource(R.string.game_env_unused))
if (!valid && name.isNotEmpty()) Text(stringResource(R.string.game_env_invalid), color = MaterialTheme.colorScheme.error)
}
},
)
}
@Composable
private fun VariableNamePicker(name: String, onChange: (String) -> Unit) {
var expanded by remember { mutableStateOf(false) }
var custom by remember { mutableStateOf(name.isEmpty() || GameEnvironmentOptions.find(name) == null) }
Text(stringResource(R.string.game_env_name), style = MaterialTheme.typography.labelMedium)
Box {
OutlinedButton(onClick = { expanded = true }, modifier = Modifier.fillMaxWidth()) {
Text(if (custom) stringResource(R.string.game_env_custom) else name)
}
DropdownMenu(expanded, onDismissRequest = { expanded = false }, modifier = Modifier.heightIn(max = 280.dp)) {
DropdownMenuItem(text = { Text(stringResource(R.string.game_env_custom)) }, onClick = {
custom = true; onChange(""); expanded = false
})
for (option in GameEnvironmentOptions.all.sortedBy { it.name.uppercase(java.util.Locale.ROOT) }) {
DropdownMenuItem(text = { Text(option.name) }, onClick = {
custom = false; onChange(option.name); expanded = false
})
}
}
}
if (custom) OutlinedTextField(value = name, onValueChange = onChange, singleLine = true,
label = { Text(stringResource(R.string.game_env_name)) }, modifier = Modifier.fillMaxWidth())
}
@Composable
private fun VariableValueEditor(name: String, value: String, onChange: (String) -> Unit) {
val option = GameEnvironmentOptions.find(name)
var expanded by remember(name) { mutableStateOf(false) }
var custom by remember(name) { mutableStateOf(option == null || value !in option.choices && option.type != GameEnvironmentOptions.Type.MULTIPLE) }
when {
option?.type == GameEnvironmentOptions.Type.TOGGLE -> Row(
Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
) {
Text(stringResource(R.string.game_env_value))
Switch(checked = value == option.choices.last(), onCheckedChange = {
onChange(if (it) option.choices.last() else option.choices.first())
})
}
option != null && option.choices.isNotEmpty() -> {
Box {
OutlinedButton(onClick = { expanded = true }, modifier = Modifier.fillMaxWidth()) {
Text(if (custom) stringResource(R.string.game_env_custom_value) else value.ifEmpty { stringResource(R.string.game_env_select_value) })
}
DropdownMenu(expanded, onDismissRequest = { expanded = false }, modifier = Modifier.heightIn(max = 280.dp)) {
DropdownMenuItem(text = { Text(stringResource(R.string.game_env_custom_value)) }, onClick = { custom = true; expanded = false })
for (choice in option.choices) {
val selected = choice in value.split(',')
DropdownMenuItem(text = { Text(choice) }, leadingIcon = {
if (option.type == GameEnvironmentOptions.Type.MULTIPLE) Checkbox(checked = selected, onCheckedChange = null)
}, onClick = {
custom = false
if (option.type == GameEnvironmentOptions.Type.MULTIPLE) {
onChange(GameEnvironmentOptions.toggle(value, choice))
} else {
onChange(choice); expanded = false
}
})
}
}
}
if (custom) OutlinedTextField(value = value, onValueChange = onChange, singleLine = true,
label = { Text(stringResource(R.string.game_env_value)) }, modifier = Modifier.fillMaxWidth())
}
else -> OutlinedTextField(value = value, onValueChange = onChange, singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = if (option?.type == GameEnvironmentOptions.Type.NUMBER) KeyboardType.Number else KeyboardType.Text),
label = { Text(stringResource(R.string.game_env_value)) }, modifier = Modifier.fillMaxWidth())
}
}
@@ -0,0 +1,174 @@
package com.droiddeck.launcher.ui
import android.os.SystemClock
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
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.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import kotlin.math.hypot
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.delay
import kotlinx.coroutines.coroutineScope
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.runtime.snapshotFlow
import androidx.compose.animation.core.spring
// Starting a session from a blue button: the button grows until the page is its blue, and the
// loading screen opens on that blue and gathers it into the ball of the throbber.
/** Carries the flood's colour to the session, which opens on it. */
const val EXTRA_FLOOD = "com.droiddeck.launcher.FLOOD"
/** Where the last pressed blue button sat, so a session started by it can grow out of it. */
internal object LaunchOrigin {
private var bounds: Rect? = null
private var button: Any? = null
private var at = 0L
/** The button a flood is growing out of: it steps aside so only the flood shows. */
var flooding by mutableStateOf<Any?>(null)
fun mark(r: Rect, key: Any) {
bounds = r
button = key
at = SystemClock.uptimeMillis()
}
/** The button behind a launch starting now, if one was pressed just before; it hides for the flood. */
fun take(): Rect? {
val b = bounds?.takeIf { SystemClock.uptimeMillis() - at < 1_500 }
if (b != null) flooding = button
bounds = null
button = null
return b
}
}
/** The page a flood grows over, sinking back a touch as it is covered; [progress] is the flood's. */
@Composable
internal fun FloodBehind(progress: () -> Float, content: @Composable () -> Unit) {
Box(Modifier.fillMaxSize().graphicsLayer { val k = sinkScale(progress()); scaleX = k; scaleY = k }) { content() }
}
private fun sinkScale(progress: Float) = 1f - 0.04f * progress
private val Gather = CubicBezierEasing(0.6f, 0f, 0.15f, 1f)
/**
* The pressed button, [from] in root px, stretching out to cover the page. Each edge rides its own
* loose spring: the ones with furthest to go set off first and quickest, the ones near the page's
* edge lag and then snap after them, so it pulls like something elastic rather than zooming. It
* goes blobby in flight, its gradient settles into the flat blue of the ball, and [onProgress]
* (0 to 1) lets the page behind sink a little. Calls [onCovered] once nothing but blue shows.
* Swallows touches while it runs.
*/
@Composable
internal fun LaunchFlood(from: Rect, onProgress: (Float) -> Unit, onCovered: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
// Left, top, right, bottom: 0 on the button, 1 on the page's edge. Springs overshoot past the
// edge, off the page, so the wobble is felt in the pull and never seen as a shrink.
val edges = remember { List(4) { Animatable(0f) } }
val covered by rememberUpdatedState(onCovered)
val progress by rememberUpdatedState(onProgress)
var page by remember { mutableStateOf(Size.Zero) }
LaunchedEffect(page != Size.Zero) {
if (page == Size.Zero) return@LaunchedEffect
val travel = listOf(from.left, from.top, page.width - from.right, page.height - from.bottom).map { it.coerceAtLeast(0f) }
val far = travel.max().coerceAtLeast(1f)
coroutineScope {
val runs = edges.mapIndexed { i, edge ->
val lead = travel[i] / far
launch {
delay(Motion.ms((180 * (1f - lead)).toInt()).toLong())
edge.animateTo(1f, spring(dampingRatio = 0.48f, stiffness = lerp(110f, 190f, lead))) {
progress(edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f)
}
}
}
// Covered once every edge has reached the page's, the first time round.
snapshotFlow { edges.all { it.value >= 0.995f } }.first { it }
covered()
runs.forEach { it.join() }
}
}
Canvas(Modifier.fillMaxSize().onSizeChanged { page = Size(it.width.toFloat(), it.height.toFloat()) }.pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) {
val (l, t, r, b) = edges.map { it.value }
val mean = edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f
// The button sinks with the page behind (FloodBehind), so the flood leaves from where it is now.
val k = sinkScale(mean)
val cx = size.width / 2f
val cy = size.height / 2f
val left = lerp(cx + (from.left - cx) * k, 0f, l)
val top = lerp(cy + (from.top - cy) * k, 0f, t)
val right = lerp(cx + (from.right - cx) * k, size.width, r)
val bottom = lerp(cy + (from.bottom - cy) * k, size.height, b)
val w = (right - left).coerceAtLeast(0f)
val h = (bottom - top).coerceAtLeast(0f)
// A button's corners at rest, a blob in flight, square once it fills the page.
val blob = kotlin.math.sin(Math.PI * mean).toFloat().coerceAtLeast(0f)
val corner = lerp(12.dp.toPx() * (1f - mean), minOf(w, h) * 0.42f, blob)
// The button's gradient gives way to the ball's flat blue in the first half.
val mix = (mean * 2f).coerceAtMost(1f)
drawRoundRect(
Brush.linearGradient(
listOf(lerp(colors.primary, pal.signal, mix), lerp(pal.primary2, pal.signal, mix)),
start = Offset(left, top), end = Offset(right, bottom),
),
topLeft = Offset(left, top), size = Size(w, h), cornerRadius = CornerRadius(corner),
)
}
}
/**
* The session's first frames: the page in [flood], drawing in to a circle over [ball] (centre and
* radius in root px, once the throbber is laid out) that lands the size of it. Calls [onLanded] then.
*/
@Composable
internal fun FloodGather(flood: Color, ball: Pair<Offset, Float>?, onLanded: () -> Unit) {
val gather = remember { Animatable(0f) }
var started by remember { mutableStateOf(false) }
val landed by rememberUpdatedState(onLanded)
LaunchedEffect(ball != null) {
if (ball == null || started) return@LaunchedEffect
started = true
// A beat of plain blue first, so the change of screen does not read as a cut.
delay(Motion.ms(90).toLong())
gather.animateTo(1f, tween(Motion.ms(640).coerceAtLeast(1), easing = Gather))
landed()
}
Canvas(Modifier.fillMaxSize().pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) {
val b = ball
if (b == null) {
drawRect(flood)
return@Canvas
}
val (c, r) = b
val far = maxOf(hypot(c.x, c.y), hypot(size.width - c.x, c.y), hypot(c.x, size.height - c.y), hypot(size.width - c.x, size.height - c.y))
drawCircle(flood, radius = lerp(far, r, gather.value), center = c)
}
}
@@ -20,6 +20,8 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.session.SessionPrefs
@@ -368,12 +370,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) },
)
}
if (steam && s.fexPreset != null) SettingsGroup("Games") {
if (steam && s.fexPreset != null) SettingsGroup(stringResource(R.string.game_settings_title)) {
ChoiceRow(
host, "fex", "FEX preset", "Applies on next game launch.",
FexPreset.all.map { it.id to it.label }, s.fexPreset,
note = FexPreset.byId(s.fexPreset).detail, onPick = a.onFexPreset,
host, "fex", stringResource(R.string.fex_preset_title), stringResource(R.string.fex_next_launch),
FexPreset.all.map { it.id to stringResource(it.label) }, s.fexPreset,
note = stringResource(FexPreset.byId(s.fexPreset).detail), onPick = a.onFexPreset,
)
GameEnvironmentRow()
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.",
@@ -94,7 +94,7 @@ private fun CompactGateInstructions(
)
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton("Use on-device ADB", compact = true, onClick = onSetUpWirelessAdb)
SecondaryButton("Use Wireless debugging", compact = true, onClick = onSetUpWirelessAdb)
}
}
}
@@ -133,7 +133,7 @@ private fun GateInstructions(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions)
SecondaryButton("Use on-device ADB", onClick = onSetUpWirelessAdb)
SecondaryButton("Use Wireless debugging", onClick = onSetUpWirelessAdb)
}
}
}
@@ -33,7 +33,7 @@ fun ProtonPage(
val colors = MaterialTheme.colorScheme
SettingsPage(
host,
title = "Compatibility tools",
title = "Proton versions",
eyebrow = "Setup",
lede = "Download and install an ARM64 Proton build now, then select it per game in Steam > Properties > Compatibility.",
onBack = onBack,
@@ -4,6 +4,10 @@ import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.runtime.produceState
import androidx.compose.runtime.key
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.runtime.remember
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
@@ -125,8 +129,17 @@ private fun readableStep(step: String): Boolean {
fun LoadingOverlay(
step: String, percent: Int, elapsed: String, hint: String, ended: Boolean,
title: String = "Starting Steam", steam: Boolean = true, onCancel: (() -> Unit)? = null,
/** An ended session's exit status and log path, shown small under the advice. */
endedDetail: String? = null,
onRetry: (() -> Unit)? = null,
onShareLogs: (() -> Unit)? = null,
onClose: (() -> Unit)? = null,
/** The blue the page opens on when a button flooded to it, gathered into the throbber's ball. */
flood: Color? = null,
onFlooded: () -> Unit = {},
) {
val colors = MaterialTheme.colorScheme
var ball by remember { mutableStateOf<Pair<Offset, Float>?>(null) }
val stages = remember(steam) { loadStages(steam) }
var reached by remember { mutableStateOf(0) }
LaunchedEffect(step, steam) {
@@ -164,7 +177,13 @@ fun LoadingOverlay(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.align(Alignment.Center).verticalScroll(rememberScrollState()).padding(horizontal = 32.dp, vertical = 24.dp),
) {
LogoThrobber(Modifier.width(if (ended) 88.dp else 110.dp), running = !ended)
// Held on the plain D while the flood gathers, and started fresh when it lands.
key(flood == null) {
LogoThrobber(
Modifier.width(if (ended) 88.dp else 110.dp).onGloballyPositioned { ball = throbberBall(it.boundsInRoot()) },
running = !ended && flood == null,
)
}
Spacer(Modifier.height(30.dp))
Text(
if (ended) "The session ended" else title, fontSize = 20.sp, fontWeight = FontWeight.SemiBold,
@@ -176,6 +195,12 @@ fun LoadingOverlay(
modifier = Modifier.padding(top = 6.dp).widthIn(max = 520.dp),
)
if (!ended) LoadSegments(stages.size, active, percent, Modifier.padding(top = 18.dp))
if (ended && endedDetail != null) Text(
endedDetail, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant.copy(alpha = 0.8f),
textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 12.dp).widthIn(max = 520.dp),
)
if (ended) EndedActions(onRetry, onShareLogs, onClose)
}
if (!ended && hint.isNotEmpty()) Text(
hint, fontSize = 13.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant.copy(alpha = 0.8f), textAlign = TextAlign.Center,
@@ -183,6 +208,24 @@ fun LoadingOverlay(
modifier = Modifier.align(Alignment.BottomCenter).padding(start = 120.dp, end = 120.dp, bottom = 28.dp),
)
if (!ended && onCancel != null) CancelHint(onCancel, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 16.dp))
if (flood != null) FloodGather(flood, ball, onFlooded)
}
}
/** What to do about an ended session: nothing leaves on a timer, and the pad starts on Try again. */
@Composable
private fun EndedActions(onRetry: (() -> Unit)?, onShareLogs: (() -> Unit)?, onClose: (() -> Unit)?) {
val first = remember { FocusRequester() }
LaunchedEffect(Unit) {
androidx.compose.runtime.withFrameNanos { }
runCatching { first.requestFocus() }
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(top = 22.dp)) {
var firstUsed = false
fun claim(): Modifier = if (firstUsed) Modifier else { firstUsed = true; Modifier.focusRequester(first) }
if (onRetry != null) PrimaryButton("Try again", modifier = claim(), onClick = onRetry)
if (onShareLogs != null) SecondaryButton("Share logs", modifier = claim(), onClick = onShareLogs)
if (onClose != null) SecondaryButton("Back", modifier = claim(), onClick = onClose)
}
}
@@ -192,7 +235,8 @@ private fun LoadSegments(count: Int, active: Int, percent: Int, modifier: Modifi
val pal = LocalPalette.current
val track = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.12f)
val run = rememberInfiniteTransition(label = "segment")
.animateFloat(-0.4f, 1f, infiniteRepeatable(tween(1300, easing = FastOutSlowInEasing)), label = "run")
.animateFloat(-0.4f, 1f, infiniteRepeatable(tween(Motion.ms(1300).coerceAtLeast(1), easing = FastOutSlowInEasing)), label = "run")
val still = Motion.scale == 0f
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = modifier.semantics { contentDescription = "Step ${active + 1} of $count" },
@@ -204,6 +248,7 @@ private fun LoadSegments(count: Int, active: Int, percent: Int, modifier: Modifi
.drawBehind {
if (i != active) return@drawBehind
if (percent >= 0) drawRect(pal.signal, size = Size(size.width * percent.coerceIn(0, 100) / 100f, size.height))
else if (still) drawRect(pal.signal.copy(alpha = 0.5f))
else drawRect(pal.signal, topLeft = Offset(size.width * run.value, 0f), size = Size(size.width * 0.4f, size.height))
},
)
@@ -89,6 +89,8 @@ import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.session.SessionPrefs
@@ -316,20 +318,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
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"
}
val fgLabel = FrameGen.label(a.frameGenEngine, a.frameGenMultiplier)
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 }
}
FrameGenMenu(host, a.frameGenEngine, a.frameGenMultiplier, a.lsfgReady, a.onFrameGenPick)
}
}
}
@@ -349,16 +342,16 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
}
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"))) {
DrawerOutlineButton("PC keyboard", modifier = Modifier.weight(1f).height(48.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"))) {
DrawerOutlineButton("Android", modifier = Modifier.weight(1f).height(48.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,
ChoiceRow(host, "second-screen-mode", "Shows", 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,
@@ -414,13 +407,16 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
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,
}
if (a.steam) SettingsGroup(stringResource(R.string.game_settings_title)) {
ChoiceRow(host, "fex", stringResource(R.string.fex_preset_title), stringResource(R.string.fex_next_launch),
FexPreset.all.map { it.id to stringResource(it.label) }, a.fexPreset,
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
GameEnvironmentRow(modifier = focus.track(page, "game-env"))
}
SettingsGroup("Support") {
SettingsRow("Session logs", "Send this session's logs with a bug report") {
DrawerOutlineButton("Send logs", modifier = focus.track(page, "share-logs")) {
DrawerOutlineButton("Share logs", modifier = focus.track(page, "share-logs")) {
host.open = null
a.onShareLogs()
}
@@ -509,7 +505,7 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
val shape = RoundedCornerShape(20.dp)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = modifier.heightIn(min = 40.dp).semantics { contentDescription = "Stop session" }
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = "Stop session" }
.clip(shape).background(fill).border(if (hot) 2.dp else 1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.55f), shape)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -19,6 +19,8 @@ import androidx.compose.foundation.layout.size
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.semantics.semantics
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -149,7 +151,7 @@ internal fun TabStrip(
.border(2.dp, if (!hot) Color.Transparent else if (on) colors.onBackground else pal.signal, tabShape)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 16.dp, vertical = 9.dp),
.padding(horizontal = 16.dp, vertical = 12.dp),
)
}
}
@@ -301,6 +303,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween,
modifier = modifier
.widthIn(min = LocalChipMinWidth.current)
.heightIn(min = 44.dp)
.clip(RoundedCornerShape(10.dp))
.background(colors.surfaceVariant)
.border(1.dp, edge, RoundedCornerShape(10.dp))
@@ -385,7 +388,46 @@ fun <T> ChoiceRow(
@Composable
fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked: Boolean, enabled: Boolean = true, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) =
ChoiceRow(host, key, label, hint, listOf(true to "On", false to "Off"), checked, enabled, chipModifier = chipModifier, onPick = onChange)
SettingsRow(label, hint) {
ToggleSwitch(checked, enabled, label, chipModifier) { host.open = null; onChange(it) }
}
/** An on/off switch: one tap or one A press flips it, where a menu of On and Off took three. */
@Composable
fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = null, modifier: Modifier = Modifier, onChange: (Boolean) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val track by animateColorAsState(if (checked) pal.signal else colors.surfaceVariant, Motion.tw(180), label = "switchTrack")
val edge by animateColorAsState(if (hot) pal.signal else if (checked) pal.signal else pal.line2, Motion.tw(180), label = "switchEdge")
val knob by animateFloatAsState(if (checked) 1f else 0f, Motion.sp(0.7f), label = "switchKnob")
val flip = { onChange(!checked) }
val shape = RoundedCornerShape(99.dp)
// 48dp tall to touch; the visible track sits inside it.
Box(
contentAlignment = Alignment.Center,
modifier = modifier
.heightIn(min = 48.dp).widthIn(min = 64.dp)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src)
.clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.Switch, onClick = flip)
.controllerConfirm(enabled = enabled, onClick = flip)
.semantics { stateDescription = if (checked) "On" else "Off"; if (label != null) contentDescription = label },
) {
Box(
Modifier.size(width = 52.dp, height = 30.dp).clip(shape).background(track)
.border(if (hot) 2.dp else 1.dp, if (hot && checked) colors.onBackground else edge, shape),
) {
Box(
Modifier.padding(4.dp).size(22.dp)
.graphicsLayer { translationX = knob * 22.dp.toPx() }
.clip(CircleShape)
.background(if (checked) pal.onSignal else colors.onSurfaceVariant),
)
}
}
}
@Composable
fun MultiRow(
@@ -133,8 +133,12 @@ internal fun CapsuleWall(
// Animations off in the system settings: a still wall.
val still = Motion.scale == 0f
BoxWithConstraints(modifier.fillMaxSize()) {
val wallW = maxWidth * 1.3f
val wallH = maxHeight * 2.4f
// Centred on the page and big enough that, once tilted, it still covers every corner.
val tilt = Math.toRadians(13.0)
val cos = kotlin.math.cos(tilt).toFloat()
val sin = kotlin.math.sin(tilt).toFloat()
val wallW = (maxWidth * cos + maxHeight * sin) * 1.1f
val wallH = maxOf(maxHeight * 2.4f, (maxWidth * sin + maxHeight * cos) * 1.1f)
val columns = ((wallW + gap) / (capW + gap)).toInt() + 1
val perRun = ((wallH + gap) / (capH + gap)).toInt() + 1
val run = (capH + gap) * perRun
@@ -142,7 +146,7 @@ internal fun CapsuleWall(
horizontalArrangement = Arrangement.spacedBy(gap),
modifier = Modifier
.wrapContentSize(Alignment.TopStart, unbounded = true)
.offset(x = maxWidth * 0.16f, y = -(wallH - maxHeight) / 2)
.offset(x = -(wallW - maxWidth) / 2, y = -(wallH - maxHeight) / 2)
.requiredSize(wallW, wallH)
.graphicsLayer { rotationZ = -13f },
) {
@@ -64,6 +64,12 @@ internal fun LogoThrobber(modifier: Modifier = Modifier, running: Boolean = true
}
}
/** The ball of a throbber laid out in [bounds]: its centre and its radius, at rest. */
internal fun throbberBall(bounds: androidx.compose.ui.geometry.Rect): Pair<Offset, Float> {
val s = bounds.width / LogoShape.WIDTH
return Offset(bounds.left + (LogoShape.CX - LogoShape.LEFT) * s, bounds.top + LogoShape.CY * s) to LogoShape.BALL * s
}
private const val LOOP_MS = 1900
private val Settle = CubicBezierEasing(0.5f, 0f, 0.3f, 1f)
private val Turn = CubicBezierEasing(0.65f, 0f, 0.35f, 1f)
@@ -172,9 +172,9 @@ fun WirelessAdbFixPage(
SettingsPage(
host = rememberMenuHost(),
title = when {
compactSplit && step < 2 -> "Wireless ADB"
step == 2 -> "Wireless ADB ready"
else -> "Set up on-device ADB"
compactSplit && step < 2 -> "Wireless debugging"
step == 2 -> "Child-process limit updated"
else -> "Change the child-process limit"
},
eyebrow = "Setup",
lede = when {
@@ -201,7 +201,7 @@ fun WirelessAdbFixPage(
) {
SettingsGroup("Child-process limit", compact = compactSplit) {
Text(
"Android confirmed the limit is ${if (desiredEnabled) "enabled" else "disabled"}.",
"Android confirmed the limit is ${if (desiredEnabled) "on" else "off"}.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(14.dp),
)
@@ -332,7 +332,7 @@ private fun WirelessStepForm(
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",
if (desiredEnabled) "Turn limit on" else "Turn limit off",
compact = compact,
enabled = !busy && parseAdbAddress(connectionAddress) != null,
onClick = onApply,
@@ -24,7 +24,7 @@ class HdrProbe(
) {
/** Why HDR cannot be offered, or null when it can. */
val reason: String? = when {
Build.VERSION.SDK_INT < 29 -> "needs Android 10 or newer (display layers with a colour space)"
Build.VERSION.SDK_INT < 29 -> "needs Android 10 or newer (display layers with a color space)"
!hdr10 -> if (formats.isEmpty()) "this display reports no HDR support" else "this display supports $formats, not HDR10"
else -> null
}
@@ -26,6 +26,10 @@ public final class WaylandCompositor {
* listener must marshal to the UI thread itself. */
public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; }
public static synchronized void clearFirstFrameListener(Runnable r) {
if (firstFrameListener == r) firstFrameListener = null;
}
/** Invoked from native (banner_on_first_frame) on the first present. */
@SuppressWarnings("unused")
static void onFirstFramePresented() {
@@ -52,6 +56,10 @@ public final class WaylandCompositor {
public static void setGameListener(GameListener l) { gameListener = l; }
public static synchronized void clearGameListener(GameListener l) {
if (gameListener == l) gameListener = null;
}
/** Invoked from native (banner_on_game_surface). */
@SuppressWarnings("unused")
static void onGameSurface(String window, String gpuName) {
+70
View File
@@ -6,6 +6,12 @@
<item>By default, leaving the app pauses Steam; it picks up where it left off when you come back.</item>
<item>Your controller appears as an Xbox 360 pad. Otherwise, use the on-screen controls.</item>
</string-array>
<string-array name="loading_hints_desktop">
<item>First run sets up the desktop. This may take a few minutes.</item>
<item>By default, leaving the app pauses the session; it picks up where it left off when you come back.</item>
<item>Touch works as a touchpad: drag to move the pointer, tap to click.</item>
<item>Your controller appears as an Xbox 360 pad. Otherwise, use the on-screen controls.</item>
</string-array>
<string name="session_channel">Session</string>
<string name="session_channel_description">Shows while a Steam or desktop session is open</string>
<string name="session_notification">Steam is running</string>
@@ -13,4 +19,68 @@
<string name="resume_session">Resume</string>
<string name="stop_session">Stop session</string>
<string name="frame_gen_title">Frame generation</string>
<string name="game_env_title">Game environment</string>
<string name="game_env_hint">Shared defaults and per-game overrides for games using Proton. Applies on the next game launch.</string>
<string name="game_env_edit">Edit variables</string>
<string name="game_env_shared">All Proton games</string>
<string name="game_env_scope">Game profile</string>
<string name="game_env_app_id">Steam app ID or non-Steam compatibility ID</string>
<string name="game_env_open">Open profile</string>
<string name="game_env_profile">Game %1$s</string>
<string name="game_env_add">Add variable</string>
<string name="game_env_name">Variable name</string>
<string name="game_env_value">Value</string>
<string name="game_env_save">Save</string>
<string name="game_env_cancel">Cancel</string>
<string name="game_env_close">Close</string>
<string name="game_env_remove">Remove</string>
<string name="game_env_restore">Restore inherited settings</string>
<string name="game_env_reset">Reset this profile</string>
<string name="game_env_unset">Unset for this profile</string>
<string name="game_env_empty">No variables set. Driver and Proton defaults apply.</string>
<string name="game_env_inherited">Inherited</string>
<string name="game_env_custom">Custom variable</string>
<string name="game_env_defaults">D3D12 feature level defaults to 12_2 and shader model to 6_9. Both can be changed or removed for each game.</string>
<string name="game_env_error">Could not load or apply the settings. Check available storage and try again.</string>
<string name="game_env_invalid">Use a valid variable name and a value without NUL characters (up to 8192 characters).</string>
<string name="game_env_unused">The standard Linux Proton runtime does not use this variable; it may require a custom component.</string>
<string name="game_env_loading">Loading…</string>
<string name="game_env_overrides">Settings in this profile override shared settings and matching Steam launch-option variables. Remove unsets a variable; restore uses its inherited value.</string>
<string name="game_env_feature">D3D12 feature-level override. 12_2 reports DirectX 12 Ultimate capabilities; unsupported features can fail. Leave unset for automatic detection.</string>
<string name="game_env_shader">D3D12 shader-model override. 6_9 requires a sufficiently recent VKD3D and matching GPU features. Leave unset for automatic detection.</string>
<string name="game_env_cache">Keep Mesa shader caching enabled to reduce repeated compilation. false enables caching.</string>
<string name="game_env_cache_size">Maximum Mesa shader-cache size, such as 1G. Larger caches use more storage.</string>
<string name="game_env_vkd3d_config">VKD3D options for D3D12. nodxr disables ray tracing; use only for a game that needs it.</string>
<string name="game_env_proton_log">Set to 1 for a Proton diagnostic log. Logging can reduce performance and use storage.</string>
<string name="game_env_wined3d">Set to 1 to use OpenGL-based WineD3D instead of DXVK for D3D9–11 compatibility testing.</string>
<string name="game_env_xalia">Set to 0 to disable Proton’s gamepad-navigation helper for this game.</string>
<string name="game_env_hud">DXVK overlay for D3D9–11. fps displays frame rate; unset hides it.</string>
<string name="game_env_dxvk_config">DXVK settings separated by semicolons. Recent builds use dxvk.maxFrameRate for frame limiting; prefer the session frame limiter for ordinary play.</string>
<string name="game_env_vkd3d_limit">D3D12 frame-rate limit. 0 disables the limit.</string>
<string name="game_env_glthread">Mesa OpenGL threading. true can help CPU-limited OpenGL games; test per game.</string>
<string name="fex_preset_title">FEX preset</string>
<string name="fex_next_launch">Applies on the next game launch.</string>
<string name="game_settings_title">Games</string>
<string name="fex_default_label">FEX defaults</string>
<string name="fex_default_detail">Uses FEX defaults.</string>
<string name="fex_stability_label">Stability</string>
<string name="fex_stability_detail">Safest, slowest settings.</string>
<string name="fex_compatibility_label">Compatibility</string>
<string name="fex_compatibility_detail">Full TSO with multiblock.</string>
<string name="fex_intermediate_label">Intermediate</string>
<string name="fex_intermediate_detail">Balanced TSO with reduced x87 precision.</string>
<string name="fex_performance_label">Performance</string>
<string name="fex_performance_detail">All TSO disabled; multiblock.</string>
<string name="fex_performance_tso_label">Performance + TSO</string>
<string name="fex_performance_tso_detail">Performance settings with main TSO enabled.</string>
<string name="fex_extreme_label">Extreme</string>
<string name="fex_extreme_detail">Disables self-modifying-code checks. JIT games and DRM may break.</string>
<string name="fex_extreme_tso_label">Extreme + TSO</string>
<string name="fex_extreme_tso_detail">Extreme settings with main TSO enabled.</string>
<string name="fex_extreme_gn_label">Extreme-gn</string>
<string name="fex_extreme_gn_detail">Performance with TSC and metadata hints. Try before Extreme.</string>
<string name="fex_denuvo_label">Denuvo</string>
<string name="fex_denuvo_detail">Performance with full code checks and the hypervisor bit hidden.</string>
<string name="game_env_custom_value">Custom value</string>
<string name="game_env_select_value">Select value</string>
</resources>
@@ -0,0 +1,75 @@
package com.droiddeck.launcher.core
import org.junit.Assert.*
import org.junit.Test
class GameEnvironmentTest {
@Test fun defaultsIncludeRequestedGraphicsLevelsAndKeepCaching() {
val values = GameEnvironment.defaults("")
assertEquals("false", values["MESA_SHADER_CACHE_DISABLE"])
assertEquals("12_2", values["VKD3D_FEATURE_LEVEL"])
assertEquals("6_9", values["VKD3D_SHADER_MODEL"])
}
@Test fun gameOverridesSharedAndPresetWithoutLeakingToOtherGames() {
val config = GameEnvironment.Config(
shared = mapOf("FEX_MULTIBLOCK" to "0", "VKD3D_FEATURE_LEVEL" to "12_2"),
games = mapOf("42" to mapOf("FEX_MULTIBLOCK" to "1", "VKD3D_FEATURE_LEVEL" to null)),
)
val game = GameEnvironment.effective(config, "COMPATIBILITY", "42")
assertEquals("1", game["FEX_MULTIBLOCK"])
assertTrue(game.containsKey("VKD3D_FEATURE_LEVEL"))
assertNull(game["VKD3D_FEATURE_LEVEL"])
val other = GameEnvironment.effective(config, "COMPATIBILITY", "43")
assertEquals("0", other["FEX_MULTIBLOCK"])
assertEquals("12_2", other["VKD3D_FEATURE_LEVEL"])
}
@Test fun graphicsDefaultsRespectExistingEditsAndRemovals() {
val config = GameEnvironment.Config(shared = mapOf("VKD3D_FEATURE_LEVEL" to "12_0"))
.withEntries("42", mapOf("VKD3D_SHADER_MODEL" to null))
val game = GameEnvironment.effective(config, "", "42")
assertEquals("12_0", game["VKD3D_FEATURE_LEVEL"])
assertTrue(game.containsKey("VKD3D_SHADER_MODEL"))
assertNull(game["VKD3D_SHADER_MODEL"])
val restored = GameEnvironment.effective(config.withEntries("42", emptyMap()), "", "42")
assertEquals("6_9", restored["VKD3D_SHADER_MODEL"])
}
@Test fun multiSelectionPreservesCustomTokensAndRemovesToggledValues() {
assertEquals("fps,custom_token,frametimes", GameEnvironmentOptions.toggle("fps,custom_token", "frametimes"))
assertEquals("custom_token", GameEnvironmentOptions.toggle("fps,custom_token", "fps"))
assertEquals("", GameEnvironmentOptions.toggle("fps", "fps"))
assertEquals("fps", GameEnvironmentOptions.toggle("", "fps"))
}
@Test fun switchingPresetDropsOldPresetOnlyVariables() {
val config = GameEnvironment.Config()
assertEquals("none", GameEnvironment.effective(config, "EXTREME", "")["FEX_SMCCHECKS"])
assertFalse(GameEnvironment.effective(config, "COMPATIBILITY", "").containsKey("FEX_SMCCHECKS"))
assertFalse(GameEnvironment.effective(config, "", "").containsKey("FEX_MULTIBLOCK"))
}
@Test fun resettingOneProfilePreservesOtherProfiles() {
val config = GameEnvironment.Config(shared = mapOf("CUSTOM" to "shared"))
.withEntries("42", mapOf("CUSTOM" to "game"))
.withEntries("43", mapOf("CUSTOM" to "other"))
.withEntries("42", emptyMap())
assertEquals("shared", GameEnvironment.effective(config, "", "42")["CUSTOM"])
assertEquals("other", GameEnvironment.effective(config, "", "43")["CUSTOM"])
assertFalse(config.games.containsKey("42"))
}
@Test fun validationPreservesLiteralValuesAndRejectsInvalidKeys() {
assertTrue(GameEnvironment.validName("mesa_glthread"))
assertFalse(GameEnvironment.validName("X=Y"))
assertFalse(GameEnvironment.validName("1VAR"))
assertFalse(GameEnvironment.validName("VAR\n"))
assertTrue(GameEnvironment.validValue("a=b 'quote' $(touch file) ; $"))
assertTrue(GameEnvironment.validValue(""))
assertFalse(GameEnvironment.validValue("bad\u0000value"))
assertFalse(GameEnvironment.validValue("x".repeat(8193)))
assertTrue(GameEnvironment.validScope("4294967295"))
for (scope in listOf("0", "-1", "01", "+1", "4294967296", "../42")) assertFalse(GameEnvironment.validScope(scope))
}
}
@@ -0,0 +1,29 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Test
class PhantomProcessLimitTest {
@Test
fun developerOptionsToggleAloneCountsAsOff() {
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.status(null, "false"))
}
@Test
fun globalSettingWinsOverTheProperty() {
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.status("false", "true"))
assertEquals(PhantomProcessStatus.ENABLED, PhantomProcessLimit.status("true", "false"))
}
@Test
fun emptyGlobalFallsThroughToTheProperty() {
assertEquals(PhantomProcessStatus.ENABLED, PhantomProcessLimit.status("", "true"))
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.status(" ", "0"))
}
@Test
fun neitherSetIsUnset() {
assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status(null, null))
assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status("", ""))
}
}
@@ -0,0 +1,191 @@
package com.droiddeck.launcher.input
import kotlin.math.sqrt
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE, qualifiers = "mdpi")
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class OnScreenControlsTest {
private lateinit var context: Context
private lateinit var view: OnScreenControls
private var time = 1000L
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("controller", Context.MODE_PRIVATE).edit().clear().commit()
ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (0.45f to 0.5f), "rs" to (0.55f to 0.5f)))
view = OnScreenControls(context, null)
view.layout(0, 0, 1200, 800)
}
@Test fun adaptiveStickHidesUntilTouchedAndReturnsToNeutralOnRelease() {
val left = control("ls")
assertEquals(0, pixel(value(left, "cx"), value(left, "cy")))
assertTrue(touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f)))
assertEquals(7, field(left, "pressedBy"))
assertEquals(540f, value(left, "ax"), 0f)
assertEquals(400f, value(left, "ay"), 0f)
assertNotEquals(0, pixel(540f, 400f))
touch(MotionEvent.ACTION_MOVE, 7 to (580f to 420f))
assertTrue(value(left, "kx") > 0f)
assertTrue(value(left, "ky") > 0f)
touch(MotionEvent.ACTION_UP, 7 to (580f to 420f))
assertEquals(-1, field(left, "pressedBy"))
assertEquals(0f, value(left, "kx"), 0f)
assertEquals(0f, value(left, "ky"), 0f)
assertEquals(0, pixel(540f, 400f))
}
@Test fun simultaneousSticksKeepTheirPointersAndReleaseIndependently() {
val left = control("ls")
val right = control("rs")
touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (540f to 400f), 9 to (660f to 400f))
assertEquals(7, field(left, "pressedBy"))
assertEquals(9, field(right, "pressedBy"))
touch(MotionEvent.ACTION_POINTER_DOWN or (2 shl 8), 7 to (540f to 400f), 9 to (660f to 400f), 11 to (500f to 400f))
assertEquals(7, field(left, "pressedBy"))
touch(MotionEvent.ACTION_POINTER_UP or (2 shl 8), 7 to (540f to 400f), 9 to (660f to 400f), 11 to (500f to 400f))
touch(MotionEvent.ACTION_MOVE, 7 to (700f to 400f), 9 to (500f to 400f))
assertTrue(value(left, "kx") > 0f)
assertTrue(value(right, "kx") < 0f)
touch(MotionEvent.ACTION_POINTER_UP, 7 to (700f to 400f), 9 to (500f to 400f))
assertEquals(-1, field(left, "pressedBy"))
assertEquals(9, field(right, "pressedBy"))
touch(MotionEvent.ACTION_CANCEL, 9 to (500f to 400f))
for (stick in listOf(left, right)) {
assertEquals(-1, field(stick, "pressedBy"))
assertEquals(0f, value(stick, "kx"), 0f)
}
}
@Test fun cancelledTouchDoesNotBecomeAStickClick() {
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
touch(MotionEvent.ACTION_CANCEL, 1 to (540f to 400f))
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
assertEquals(false, field(control("ls"), "clicked"))
touch(MotionEvent.ACTION_UP, 1 to (540f to 400f))
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
assertEquals(true, field(control("ls"), "clicked"))
}
@Test fun buttonsTakePriorityOverAdaptiveRegions() {
val button = control("a")
touch(MotionEvent.ACTION_DOWN, 3 to (value(button, "cx") to value(button, "cy")))
assertEquals(3, field(button, "pressedBy"))
assertEquals(-1, field(control("rs"), "pressedBy"))
}
@Test fun fixedSticksAndEditorRemainVisibleAtSavedPositions() {
ControllerPrefs.setAdaptiveSticks(context, false)
view.reload()
val left = control("ls")
val x = value(left, "cx")
val y = value(left, "cy")
assertNotEquals(0, pixel(x, y))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f)))
touch(MotionEvent.ACTION_DOWN, 1 to (x + 10f to y))
assertEquals(x, value(left, "ax"), 0f)
assertEquals(10f, value(left, "kx"), 0f)
ControllerPrefs.setAdaptiveSticks(context, true)
view = OnScreenControls(context, null, editing = true)
view.layout(0, 0, 1200, 800)
assertNotEquals(0, pixel(value(control("ls"), "cx"), value(control("ls"), "cy")))
}
@Test fun buttonsOnlyAndReloadReleaseAdaptiveSticks() {
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
touch(MotionEvent.ACTION_MOVE, 1 to (570f to 400f))
view.reload()
assertEquals(-1, field(control("ls"), "pressedBy"))
assertEquals(0f, value(control("ls"), "kx"), 0f)
view.setButtonsOnly(true)
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f)))
}
@Test fun adaptiveActivationIsLimitedToExpandedSavedCircle() {
val left = control("ls")
val x = value(left, "cx")
val y = value(left, "cy")
val reach = value(left, "radius") * 1.4f * sqrt(1.5f)
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to y - reach - 1f)))
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to y - reach + 1f)))
assertEquals(y - reach + 1f, value(left, "ay"), 0.001f)
touch(MotionEvent.ACTION_UP, 1 to (x to y - reach + 1f))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x - reach to y - reach)))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f)))
}
@Test fun touchesOutsideActivationAreasStayWithTrackpad() {
val received = mutableListOf<Int>()
val trackpad = View(context).apply {
setOnTouchListener { _, event -> received.add(event.actionMasked); true }
}
val root = FrameLayout(context).apply {
addView(trackpad, FrameLayout.LayoutParams(1200, 800))
addView(view, FrameLayout.LayoutParams(1200, 800))
measure(View.MeasureSpec.makeMeasureSpec(1200, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY))
layout(0, 0, 1200, 800)
}
for ((action, position) in listOf(
MotionEvent.ACTION_DOWN to (600f to 200f),
MotionEvent.ACTION_MOVE to (540f to 400f),
MotionEvent.ACTION_UP to (540f to 400f),
)) {
val event = MotionEvent.obtain(1000L, time++, action, position.first, position.second, 0)
try { assertTrue(root.dispatchTouchEvent(event)) } finally { event.recycle() }
}
assertEquals(listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP), received)
assertEquals(-1, field(control("ls"), "pressedBy"))
}
@Test fun adaptiveActivationLeavesFivePixelsAroundButtonHitTargets() {
for (id in listOf("a", "rb")) {
val button = control(id)
val radius = value(button, "radius")
val edge = value(button, "cy") - radius * if (id == "rb") 1.05f else 1.25f
val x = value(button, "cx")
val left = control("ls")
left.javaClass.getDeclaredField("cx").apply { isAccessible = true }.setFloat(left, x)
left.javaClass.getDeclaredField("cy").apply { isAccessible = true }.setFloat(left, edge - 10f)
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 4f)))
assertEquals(-1, field(left, "pressedBy"))
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 6f)))
assertEquals(1, field(left, "pressedBy"))
touch(MotionEvent.ACTION_UP, 1 to (x to edge - 6f))
}
}
private fun control(id: String): Any = (field(view, "controls") as List<*>).first { field(it!!, "id") == id }!!
private fun field(owner: Any, name: String): Any = owner.javaClass.getDeclaredField(name).apply { isAccessible = true }.get(owner)!!
private fun value(owner: Any, name: String) = field(owner, name) as Float
private fun pixel(x: Float, y: Float): Int {
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
view.draw(Canvas(bitmap))
val color = bitmap.getPixel(x.toInt(), y.toInt())
bitmap.recycle()
return color
}
private fun touch(action: Int, vararg pointers: Pair<Int, Pair<Float, Float>>): Boolean {
val properties = pointers.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray()
val coords = pointers.map { (_, position) -> MotionEvent.PointerCoords().apply { x = position.first; y = position.second; pressure = 1f; size = 1f } }.toTypedArray()
val event = MotionEvent.obtain(1000L, time++, action, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0)
return try { view.onTouchEvent(event) } finally { event.recycle() }
}
}
@@ -0,0 +1,64 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class GameEnvironmentStoreTest {
private lateinit var context: Context
private lateinit var guest: File
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
guest = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json")
File(context.filesDir, "game-environment.json").delete()
}
@Test fun savedSettingsAndPublishedSettingsPreserveUnsetsAndLiteralValues() {
val config = GameEnvironment.Config(
shared = mapOf("LITERAL" to "a=b 'quoted' $(echo test)", "EMPTY" to ""),
games = mapOf("42" to mapOf("LITERAL" to null, "VKD3D_SHADER_MODEL" to "6_9")),
)
GameEnvironmentStore.save(context, config)
assertEquals(config, GameEnvironmentStore.read(context))
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertEquals("false", published.shared["MESA_SHADER_CACHE_DISABLE"])
assertEquals("12_2", published.shared["VKD3D_FEATURE_LEVEL"])
assertEquals("6_9", published.shared["VKD3D_SHADER_MODEL"])
assertEquals(config.games, published.games)
assertEquals(config.shared["LITERAL"], published.shared["LITERAL"])
assertEquals("", published.shared["EMPTY"])
}
@Test fun changingFexPresetPublishesForNextGameLaunch() {
GameEnvironmentStore.save(context, GameEnvironment.Config())
SessionPrefs.setFexPreset(context, "EXTREME")
assertEquals("none", JSONObject(guest.readText()).getJSONObject("shared").getString("FEX_SMCCHECKS"))
SessionPrefs.setFexPreset(context, "")
assertFalse(JSONObject(guest.readText()).getJSONObject("shared").has("FEX_SMCCHECKS"))
}
@Test fun invalidDataCannotReplaceSavedConfiguration() {
val original = GameEnvironment.Config(shared = mapOf("CUSTOM" to "ok"))
GameEnvironmentStore.save(context, original)
assertTrue(runCatching { GameEnvironmentStore.save(context, GameEnvironment.Config(shared = mapOf("BAD=NAME" to "x"))) }.isFailure)
assertEquals(original, GameEnvironmentStore.read(context))
}
@Test fun customComponentVariablesRemainEditable() {
val config = GameEnvironment.Config(shared = mapOf("DXVK_ASYNC" to "1"))
GameEnvironmentStore.save(context, config)
assertEquals(config, GameEnvironmentStore.read(context))
}
}
+11 -8
View File
@@ -1,13 +1,17 @@
# 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
`app/src/main/assets/steam-startup/droiddeck-startup.webm` (1280×720 at 30 fps, pitch black background, VP8 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.
render the animation at the bundled playback profile. 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
python3 artwork/boot-animation-source/render.py 1280 720 30 app/src/main/assets/steam-startup/droiddeck-startup.webm dark
The bundled profile reduces decoded pixels per second by 78% compared with 1080p/60.
VP8 also lowers software decode cost while Steam is starting. Keep the bundled movie at
720p/30; higher-resolution exports are intended for sharing.
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
@@ -27,13 +31,12 @@ 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
pip install playwright && playwright install chromium # ffmpeg with libvpx also required
python3 render.py 1280 720 30 droiddeck-boot-1280x720.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
python3 render.py 1280 720 30 droiddeck-boot-dark-1280x720.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,
Each frame gets real motion blur (180° shutter, adaptive sub-frames). Output is VP8 for .webm or H.264 for .mp4, both BT.709,
so the orb stays #1A9FFF after compression.
## Sound
+8 -8
View File
@@ -2,11 +2,11 @@
"""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 1280 720 30 droiddeck-boot.webm
python3 render.py 1920 1080 60 droiddeck-boot.mp4
python3 render.py 1280 800 60 droiddeck-boot-dark.webm dark
python3 render.py 1280 720 30 droiddeck-boot-dark.webm dark
Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx-vp9.
Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx.
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).
"""
@@ -15,8 +15,8 @@ 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
H = int(sys.argv[2]) if len(sys.argv) > 2 else 720
FPS = int(sys.argv[3]) if len(sys.argv) > 3 else 30
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
@@ -54,9 +54,9 @@ cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+ful
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)]
else: # VP8 keeps software decoding inexpensive during Steam startup
cmd += ["-c:v", "libvpx", "-b:v", "2M", "-crf", "10", "-deadline", "good", "-cpu-used", "2",
"-g", str(FPS * 2)]
cmd += COLOR + ([] if SOUND.exists() else ["-an"]) + [OUT]
subprocess.run(cmd, check=True)
if not os.environ.get("FRAMEDIR"):
+81
View File
@@ -0,0 +1,81 @@
# Steam game environment
Open **Games → Game environment**, directly below **FEX preset**, in Steam
settings or the in-session drawer. Choose all Proton games, an installed game, or enter a Steam app ID. For a
non-Steam shortcut, use its numeric `compatdata` directory ID (unsigned 32-bit).
Changes apply on the next game launch, including when Steam is already running.
A running game must be restarted. Native Linux games and Steam itself are outside
this editor's scope.
The order is inherited process environment, selected FEX preset and built-in
settings, shared edits, then game-specific edits. Editor entries therefore win
over matching Steam launch-option variables. **Remove** explicitly unsets a
variable. **Restore inherited settings** removes the override. **Reset this
profile** clears only that profile's overrides. Values are literal strings, with
no shell expansion; quotes are only needed when the consuming program expects them.
## Defaults and available suggestions
The initial configuration enables Mesa shader caching with
`MESA_SHADER_CACHE_DISABLE=false`, sets `VKD3D_FEATURE_LEVEL=12_2` and
`VKD3D_SHADER_MODEL=6_9`, and preserves the selected FEX preset. Existing edits
and explicit removals take precedence over these defaults. FEX's own default
remains the default preset. Shader caching in VKD3D/DXVK, synchronization, ray
tracing and diagnostic logging otherwise retain the runtime's defaults.
The variable-name picker offers 24 predefined variables and a Custom entry. Like
WinNative, known variables use toggles, value dropdowns, multi-select lists, or
numeric/text fields. Feature-level and shader-model dropdowns also accept custom
values. Custom variables have editable names and literal values.
| Variable | Use |
| --- | --- |
| `VKD3D_FEATURE_LEVEL` | D3D12 capability override; defaults to `12_2`. |
| `VKD3D_SHADER_MODEL` | Shader-model override; defaults to `6_9`. |
| `VKD3D_CONFIG` | Per-game workarounds such as `nodxr`; not a universal performance preset. |
| `MESA_SHADER_CACHE_MAX_SIZE` | Storage budget for Mesa's shader cache, for example `1G`. |
| `mesa_glthread` | OpenGL threading; test with the affected game. |
| `DXVK_CONFIG` | DXVK configuration options; recent builds accept `dxvk.maxFrameRate = 60`. |
| `VKD3D_FRAME_RATE` | D3D12 frame-rate limit. |
| `DXVK_HUD`, `PROTON_LOG` | Optional diagnostics; leave unset for ordinary play. |
| `PROTON_USE_WINED3D` | D3D9–11 OpenGL fallback for compatibility testing. |
| `PROTON_USE_XALIA` | Proton's gamepad-navigation helper toggle. |
Forcing `12_2` or `6_9` changes reported capabilities; it cannot implement a missing
Vulkan feature. Remove either entry to use automatic detection for that capability.
Other picker suggestions are editable starting values and are enabled only when
added and saved. Older or
custom components can support a different set of options. Android Wine wrapper,
ALSA-server, Box64 and patched async-DXVK options are identified in the editor as
requiring a different/custom component; custom entries remain allowed. The old
`DXVK_FRAME_RATE` environment variable was removed from current DXVK, so it is
not offered as a suggestion. Prefer the session frame limiter for ordinary play.
## Launch path and references
WinNative's Linux session filters Android-only options, merges user variables
over the FEX preset, and passes the result to `env -i` before starting Steam. Its
Windows/Wine graphics helper also maps the selected feature level to
`VKD3D_FEATURE_LEVEL`. Reviewed source: [WinNative Linux session](https://github.com/maxjivi05/WinNative/blob/c9fbbb342f2689c852046804f4f5c9afa45b5dcb/app/src/main/runtime/display/XServerDisplayActivity.java),
[variable editor](https://github.com/maxjivi05/WinNative/blob/c9fbbb342f2689c852046804f4f5c9afa45b5dcb/app/src/main/shared/ui/widget/EnvVarsView.java),
[graphics configuration](https://github.com/maxjivi05/WinNative/blob/c9fbbb342f2689c852046804f4f5c9afa45b5dcb/app/src/main/feature/settings/drivers/DXVKConfigUtils.java).
DroidDeck instead publishes an atomic JSON snapshot at
`/root/.config/droiddeck/game-environment.json`. Both its Valve ARM64 Proton
wrapper and adopted third-party Proton wrappers execute `bannerlator-game-env`,
which reads that snapshot for each real game launch and uses `execvpe` to start
Proton. Probe prefix `compatdata/0` and non-launch verbs are unchanged. Malformed
configuration falls back to the inherited environment without evaluating its
contents. Signed non-Steam prefix IDs are normalized to unsigned IDs.
Upstream references: [VKD3D capability parsing](https://github.com/HansKristian-Work/vkd3d-proton/blob/master/libs/vkd3d/device.c),
[VKD3D options](https://github.com/HansKristian-Work/vkd3d-proton#environment-variables),
[Proton runtime options](https://github.com/ValveSoftware/Proton/tree/proton_11.0#runtime-config-options),
[Mesa variables](https://docs.mesa3d.org/envvars.html),
[DXVK variables](https://github.com/doitsujin/dxvk#environment-variables),
[DXVK frame-limiter changes](https://github.com/doitsujin/dxvk/releases).
Validation: `./gradlew testDebugUnitTest` and
`python3 -m unittest discover -s tools/tests -p test_game_environment.py`.
Actual game compatibility depends on the installed Proton, VKD3D and Vulkan driver;
these checks do not establish that every device supports feature level 12_2 or SM 6_9.
+172
View File
@@ -0,0 +1,172 @@
# DroidDeck 0.2.0 (beta)
**Valve's native ARM64 Steam client on your Android handheld.** Windows games run through Valve's ARM64 Proton and FEX, and an optional Linux desktop brings emulators along.
![Tapping DroidDeck on the Android home screen and landing in Steam Big Picture](https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/launch-into-steam.gif)
**Needs:** Android 9+, Adreno 730 or newer (or 8xx), ~3 GB free for the runtime (+1.1 GB for Desktop & apps).
This is the first release from the [Droid-Deck](https://github.com/Droid-Deck) org, so it covers everything DroidDeck does, not just what changed since 0.1.7. `legacy#N` links go to pull requests in [The412Banner/DroidDeck](https://github.com/The412Banner/DroidDeck), from before the move.
---
## Highlights
### Steam, running natively
The real Steam client in Big Picture, fetched from Valve on your device. Turn on **Run Steam when DroidDeck starts** and the app icon takes you straight in, as above.
### A launcher made for handhelds
Your Steam library as a capsule wall, and a Games tab with per-game settings.
<p>
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/launcher-steam.jpg" width="49%" alt="Steam tab with the capsule wall">
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/launcher-games.jpg" width="49%" alt="Games tab with a game's launch settings">
</p>
### Your Android home screen
Set DroidDeck as the Home app and your Android apps live in the launcher too, and in the session menu, so you can open one without leaving your game.
![Android apps listed in the session menu over Steam](https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/drawer-android-apps.jpg)
### Made for two screens
On a dual-screen handheld, launch an Android app on the second screen while Steam keeps the first, or turn the second screen into a keyboard and trackpad, or a Linux terminal.
<p>
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/dual-screen-app.gif" width="32%" alt="Launching Geometry Wars 3 on the second screen from the session menu">
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/second-screen-trackpad.gif" width="32%" alt="Second screen as a trackpad and keyboard">
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/second-screen-terminal.jpg" width="32%" alt="Second screen as a Linux terminal under Big Picture">
</p>
### A session menu over any game
Press Back mid-game for display, controls, components and session settings, paged with LB/RB.
![Paging through the session menu's tabs](https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/session-drawer.gif)
### Swap FEX, DXVK and VKD3D-Proton per Proton build
Download from the nightlies or import a `.wcp`, and see what the running game is using.
![Components manager](https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/components.jpg)
### A Linux desktop, with emulators one tap away
LXQt on the GPU, plus RPCS3, ARMSX2, Dolphin, DuckStation, melonDS, Cemu, PPSSPP and RetroArch.
<p>
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/linux-desktop.jpg" width="49%" alt="LXQt desktop with a file manager and terminal">
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/desktop-apps.jpg" width="49%" alt="Desktop tab with emulators to install">
</p>
### On-screen controls you can lay out yourself
Drag every button where your thumbs want it, with adaptive sticks and phone-sized layouts.
![On-screen controller layout editor](https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/controller-editor.jpg)
---
## Everything in 0.2.0
### Steam
- Native ARM64 Steam client under gamescope, on DroidDeck's own Vulkan compositor (@The412Banner)
- Valve's ARM64 Proton and FEX, ready at first sign-in (@The412Banner, [legacy#22](https://github.com/The412Banner/DroidDeck/pull/22), #33)
- Start offline after one sign-in (@The412Banner)
- Steam Deck mode: battery and NIS in Quick Access, MangoHud overlay (@The412Banner, [legacy#9](https://github.com/The412Banner/DroidDeck/pull/9), [legacy#16](https://github.com/The412Banner/DroidDeck/pull/16))
- Games from your own folders appear in Steam, with store art (@The412Banner, [legacy#9](https://github.com/The412Banner/DroidDeck/pull/9))
- Components manager for FEX, DXVK and VKD3D-Proton, applied on every launch (@The412Banner, #29)
- GE-Proton and proton-cachyos as extra compatibility tools (@The412Banner, @xXJSONDeruloXx, [legacy#18](https://github.com/The412Banner/DroidDeck/pull/18))
- FEX presets per session, Stability to Extreme + TSO (@The412Banner)
- Decky Loader, with plugins in Big Picture (@xXJSONDeruloXx, #16)
- Steam's Internet settings and connection indicator work (@maxjivi05)
- Steam sees the device as "DroidDeck" (@xXJSONDeruloXx, #15)
- Steam launchers on the Linux desktop (@The412Banner, #10)
- DroidDeck startup movie, and optionally straight into Steam when the app opens (@xXJSONDeruloXx, #25, #27, #36, #38)
### Launcher
- Side rail, Games tab, capsule wall, graphite theme, controller hints, phone layouts (@xXJSONDeruloXx, #13, #35, #41)
- Launch buttons flood into the loading screen (@xXJSONDeruloXx, #46)
- Game files and Proton prefix shortcuts on each game's page (@xXJSONDeruloXx, #39)
- Controller navigation everywhere, remembered across the rail (@The412Banner, [legacy#29](https://github.com/The412Banner/DroidDeck/pull/29), [legacy#34](https://github.com/The412Banner/DroidDeck/pull/34), [legacy#38](https://github.com/The412Banner/DroidDeck/pull/38))
- Built-in file manager, a ROMs folder anywhere (SD cards too), app files in Android's picker (@The412Banner, [legacy#41](https://github.com/The412Banner/DroidDeck/pull/41))
- Themes and the split-D logo (@The412Banner, @xXJSONDeruloXx, [legacy#4](https://github.com/The412Banner/DroidDeck/pull/4), [legacy#37](https://github.com/The412Banner/DroidDeck/pull/37), #34)
- Use DroidDeck as your Android home app, with Android apps in the front end (@xXJSONDeruloXx, @The412Banner, [legacy#17](https://github.com/The412Banner/DroidDeck/pull/17), [legacy#44](https://github.com/The412Banner/DroidDeck/pull/44))
- Build identity and latest-build link in the top bar (@xXJSONDeruloXx, [legacy#24](https://github.com/The412Banner/DroidDeck/pull/24), #26)
### Sessions
- Sessions keep running when you leave the app (@The412Banner)
- Pause policy (Auto, Manual, Never), changeable mid-session, audio recovers after a pause (@xXJSONDeruloXx, [legacy#7](https://github.com/The412Banner/DroidDeck/pull/7), #14)
- Paged session menu with Display, Controls and Settings tabs (@xXJSONDeruloXx, @The412Banner, [legacy#40](https://github.com/The412Banner/DroidDeck/pull/40), #6, #24)
- Back opens the menu; a double press opens Steam's Quick Access (@xXJSONDeruloXx, [legacy#3](https://github.com/The412Banner/DroidDeck/pull/3), [legacy#20](https://github.com/The412Banner/DroidDeck/pull/20))
- First run sets itself up from the loading screen (@The412Banner, [legacy#12](https://github.com/The412Banner/DroidDeck/pull/12), [legacy#15](https://github.com/The412Banner/DroidDeck/pull/15))
- Launch on any connected display; a second screen can be a keyboard, trackpad or terminal (@xXJSONDeruloXx, [legacy#13](https://github.com/The412Banner/DroidDeck/pull/13), [legacy#33](https://github.com/The412Banner/DroidDeck/pull/33))
- Share session logs from the app or the ended-session screen (@xXJSONDeruloXx, @The412Banner, [legacy#11](https://github.com/The412Banner/DroidDeck/pull/11), #17, #41)
### Controls
- Any controller shows up as an Xbox 360 pad; an on-screen pad fills in when none is connected (@The412Banner)
- On-screen controller editor with adaptive sticks (@maxjivi05, #9)
- On-screen sticks that use the letterbox bars, plus Steam and QAM touch buttons (@The412Banner, @xXJSONDeruloXx, [legacy#6](https://github.com/The412Banner/DroidDeck/pull/6))
- Real touch in Big Picture; a desktop touchpad that hovers, clicks, scrolls and two-finger drags (@The412Banner, #10, #22)
- Cursor shapes, hidden while you play on a pad (@The412Banner, #18)
- Soft keyboard and a full PC keyboard (@The412Banner, [legacy#25](https://github.com/The412Banner/DroidDeck/pull/25))
### Display and performance
- Frame generation: built-in Win-FG, or LSFG from your own Lossless Scaling, 2×–4× (@The412Banner)
- Import or download Turnip drivers per mode, from Banners-Turnip and WinNative (@The412Banner)
- Resolution and shape per mode, including "Exactly this panel" for 4:3 and 3:2 screens (@The412Banner, [legacy#14](https://github.com/The412Banner/DroidDeck/pull/14))
- Stretch games to fill; Quake-engine games windowed to fit (@The412Banner, [legacy#32](https://github.com/The412Banner/DroidDeck/pull/32))
- HDR10 on supported panels (experimental) (@The412Banner)
- Runs as a game on Android: sustained performance, fastest panel mode, ADPF hints (@The412Banner)
- Steam's interface stays on the GPU (@maxjivi05)
- Pin Steam and games to chosen CPU cores (@The412Banner)
- Faster proot with WinNative's seccomp and tracing fixes (@maxjivi05, #4, #37)
### Desktop and emulators
- LXQt on labwc, on the GPU with Vulkan by default (@The412Banner, [legacy#25](https://github.com/The412Banner/DroidDeck/pull/25))
- Emulators downloaded on request: RetroArch, PPSSPP, RPCS3, DuckStation, ARMSX2, Dolphin, melonDS, Cemu and more (@The412Banner)
- Emulator games launch full screen from the front end, one tile per disc, with box art (@The412Banner, [legacy#29](https://github.com/The412Banner/DroidDeck/pull/29), [legacy#34](https://github.com/The412Banner/DroidDeck/pull/34), [legacy#38](https://github.com/The412Banner/DroidDeck/pull/38))
- ARMSX2 replaces PCSX2 for PS2: 60 fps where PCSX2 managed 17 (@The412Banner, [legacy#26](https://github.com/The412Banner/DroidDeck/pull/26))
- Dolphin, melonDS and Cemu set up out of the box (@The412Banner, #10, #18, #42)
- Emulator controllers preconfigured, and RPCS3 shader fixes (@The412Banner, [legacy#25](https://github.com/The412Banner/DroidDeck/pull/25))
### Audio
- DirectAudio for games, straight to Android (@The412Banner, [legacy#9](https://github.com/The412Banner/DroidDeck/pull/9), [legacy#11](https://github.com/The412Banner/DroidDeck/pull/11))
- Microphone for voice chat, on by default (@The412Banner, [legacy#11](https://github.com/The412Banner/DroidDeck/pull/11))
### Fixed
- Steam updates failing on read-only files (@The412Banner, #33)
- A dropped finger-up blocking later touches (@The412Banner, #22)
- Stopped sessions leaving stray processes and log spam (@The412Banner, #43)
- Cemu and shadPS4 crashing on the input shim; no cursor on the GPU desktop (@The412Banner, #42)
- Leftovers from crashed or killed sessions cleaned up at the next start (@The412Banner, [legacy#16](https://github.com/The412Banner/DroidDeck/pull/16))
- The menu's dim layer staying over Steam after switching apps (@xXJSONDeruloXx, #45)
- Steam library capsule art (@xXJSONDeruloXx, #12)
- The menu's Desktop button wrapping (@xXJSONDeruloXx, #28)
- Launcher restarting when a controller connects (@xXJSONDeruloXx, #40)
- Runtime installs racing, or stopping when you leave the app (@xXJSONDeruloXx, #40)
- Steam blocked by Android's child-process limit; Setup lifts it over wireless ADB (@xXJSONDeruloXx, #21)
### Security
- SHA-256 checked on every catalog, release and Proton download (@xXJSONDeruloXx, #40)
- Runtime archives can't link outside the rootfs (@xXJSONDeruloXx, #40)
- Logs scrub account and persona names, public IPs and device IDs (@The412Banner, #19)
- Signed with DroidDeck's own release key (@The412Banner, [legacy#41](https://github.com/The412Banner/DroidDeck/pull/41))
### Behind the scenes
- Every PR's APK published to DroidDeck-CI (@maxjivi05, #3), with signed builds gated on review (@xXJSONDeruloXx, #5)
- Local builds matching CI, and a debug-only ADB agent bridge (@xXJSONDeruloXx, [legacy#5](https://github.com/The412Banner/DroidDeck/pull/5), [legacy#35](https://github.com/The412Banner/DroidDeck/pull/35), #7, #20)
- CI hardening, branch protection and copy clean-ups (@The412Banner, @xXJSONDeruloXx, [legacy#8](https://github.com/The412Banner/DroidDeck/pull/8), [legacy#10](https://github.com/The412Banner/DroidDeck/pull/10), [legacy#41](https://github.com/The412Banner/DroidDeck/pull/41), #8)
---
**Built on** WinNative by @maxjivi05 (the gamescope runtime, proot session and input interposer), Winlator by brunodev85 (audio and gamepad model), Bannerlator by @The412Banner (file manager, first sign-in flow), lsfg-vk by PancakeTAS, MangoHud by flightlessmango, and Vauzi's Adreno 710/720/722 device entries.
Not affiliated with Valve. Steam, Proton and Steam Deck are Valve's; the client and Proton are fetched from Valve's servers on your device.
**Contributors:** @The412Banner, @xXJSONDeruloXx, @maxjivi05
Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 481 KiB

+25 -1
View File
@@ -41,7 +41,8 @@ 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)
# Only complete NDKs: an interrupted sdkmanager install leaves a directory without source.properties.
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 2 -maxdepth 2 -name source.properties -print | xargs -n1 dirname | sort -V | tail -1)
ndk_version=${ndk_path##*/}
fi
if [[ -z "${ndk_version}" || ! -d "${sdk_dir}/ndk/${ndk_version}" ]]; then
@@ -308,6 +309,29 @@ grep -qi 'CN=Android, OU=Android, O=Android' <<<"${signature_output}" || {
exit 1
}
# With DroidDeck's own key at hand, sign as CI's main builds are (tools/release/sign-apk.sh), so
# the apk installs over a release instead of being refused as a different signer. The key's
# location and password live in an untracked .signing.env (RELEASE_KEYSTORE, RELEASE_STORE_PASSWORD,
# RELEASE_KEY_ALIAS), looked for in this checkout and then in the main one, which worktrees share.
signing_env=${DROIDDECK_SIGNING_ENV:-}
if [[ -z "${signing_env}" ]]; then
for candidate in "${repo_root}/.signing.env" \
"$(dirname "$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir 2>/dev/null || echo .)")/.signing.env"; do
[[ -f "${candidate}" ]] && { signing_env=${candidate}; break; }
done
fi
if [[ -n "${signing_env}" ]]; then
echo "Signing with DroidDeck's key (${signing_env})"
(
set -a
# shellcheck disable=SC1090
. "${signing_env}"
set +a
BUILD_TOOLS="${build_tools}" "${repo_root}/tools/release/sign-apk.sh" "${apk}" standard "${apk}.release"
)
mv "${apk}.release" "${apk}"
fi
printf 'APK: %s\n' "${apk}"
printf 'SHA-256: '
shasum -a 256 "${apk}" | awk '{print $1}'
+4 -4
View File
@@ -55,10 +55,10 @@ if [ -n "${BL_DEBUG_DIR:-}" ]; then
echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') renderer=$WLR_RENDERER"
fi
export WLR_BACKENDS=wayland
# The app's compositor draws no wl_pointer cursor surfaces, so a cursor wlroots hands to its
# parent ("hardware" cursor on the wayland backend) never shows - on the GPU renderers the whole
# cursor was missing. Draw it into the desktop's own frames instead.
export WLR_NO_HARDWARE_CURSORS=${WLR_NO_HARDWARE_CURSORS:-1}
# The cursor goes to the app's compositor as a wl_pointer cursor surface ("hardware" cursor on the
# wayland backend), which the app draws as its pointer. Drawn into the desktop's own frames instead
# (WLR_NO_HARDWARE_CURSORS=1), it cost every frame a full-screen composite: a software cursor
# rules out direct scan-out, so a full-screen game was never handed to the app as it is.
mkdir -p "$HOME/.config/labwc" "$HOME/.config/lxqt"
# Our defaults for labwc and the panel, refreshed every session. What a user changes in the
# panel's own settings lands in panel.conf and is kept; only rc.xml and autostart are ours.
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/python3
import json
import os
import re
import sys
from pathlib import Path
def game_id(env):
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if not prefix:
return None
value = prefix.rsplit("/", 1)[-1]
if not re.fullmatch(r"-?[0-9]+", value):
return None
number = int(value)
if not -(2**31) <= number < 2**32 or number == 0:
return None
return str(number % 2**32)
def apply_config(env, config, app_id):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
result = env.copy()
entries = dict(config.get("shared", {}))
entries.update(config.get("games", {}).get(app_id, {}))
for name, value in entries.items():
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
raise ValueError("invalid environment name")
if value is None:
result.pop(name, None)
elif isinstance(value, str) and "\0" not in value and len(value) <= 8192:
result[name] = value
else:
raise ValueError("invalid environment value")
return result
def main():
command = sys.argv[1:]
if not command:
return 2
env = os.environ.copy()
app_id = game_id(env)
if len(command) > 1 and command[1] == "waitforexitandrun" and app_id:
path = Path.home() / ".config/droiddeck/game-environment.json"
try:
with path.open(encoding="utf-8") as source:
env = apply_config(env, json.load(source), app_id)
except FileNotFoundError:
pass
except (OSError, ValueError, TypeError, AttributeError):
print("bannerlator-game-env: invalid configuration; using inherited environment", file=sys.stderr)
os.execvpe(command[0], command, env)
if __name__ == "__main__":
sys.exit(main())
@@ -19,7 +19,10 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
mv -f "$BL_LOG" "$BL_LOG.1"
fi
exec >>"$BL_LOG" 2>&1
# A guest looping on an error writes gigabytes in minutes (an Xwayland proot had lost track of
# managed 9 GB of one line in 19 min): the log keeps its first BL_LOG_CAP bytes and the rest is
# drained, not refused - a writer that filled it must not die of SIGPIPE.
exec > >({ head -c "${BL_LOG_CAP:-268435456}" >>"$BL_LOG"; cat >/dev/null; }) 2>&1
echo "== bannerlator-session $(date) mode=$mode $*"
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} fps=${BL_FPS:-0} icd=${VK_ICD_FILENAMES:-none}"
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
@@ -588,6 +591,8 @@ BUSCONF
wait "$decky_supervisor" 2>/dev/null || true
echo "== Decky: session supervisor stopped"
fi
_bl_jobs=$(jobs -p)
[ -n "$_bl_jobs" ] && kill $_bl_jobs 2>/dev/null
reap_orphans
fi
exit "$rc"
@@ -233,7 +233,7 @@ for name in %s; do
bl_directaudio "$depot"
bl_game_cpus
bl_idtech3 "$@"
exec ${BL_TASKSET:-} "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
fi
done
echo "bannerlator-proton: no ARM64 Proton depot yet - the client downloads one as this tool's dependency; retry the launch once it has" >&2
@@ -282,7 +282,7 @@ bl_game_cpus
bl_idtech3 "$@"
# Proton takes its base directory from dirname(sys.argv[0]) without resolving it, so it has to be
# started from its own tree.
exec ${BL_TASKSET:-} "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
"""
EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools"
{
+153
View File
@@ -0,0 +1,153 @@
# Bionic Steam client probe
This is a research harness for Valve's Android/Bionic ARM64 Steam client
libraries. It does **not** vendor or redistribute Valve binaries. The build
script fetches the current package from Valve's public Steam client-update
endpoint into a temporary working directory.
The question under test is narrow:
> Can Valve's `androidarm64/libsteamclient.so` run directly under Android's
> Bionic linker, and if so, what does it need in order to become a usable
> Steam client?
## Result
Yes, the library itself works directly on stock Android. It is not a complete
Steam desktop client, however. It is a Steamworks IPC client for a separate
full Steam process.
On 2026-09-28, the public-beta ARM64 client manifest contained
`bins_androidarm64_linuxarm64.zip.35688b00e791987ab70b1b6c6ddd006d4c864470`
with SHA-256:
`811859a83c7c5ff220ac9731235e76fd0d5da603a5cdb56fe5f08e145a417cbd`
The archive contains Android ARM64 builds of `libsteamclient.so`,
`libsteamnetworkingsockets.so`, `libtier0_s.so`, `libvstdlib_s.so`, and
`steamservice.so`.
## ABI evidence
`libsteamclient.so` is a genuine Android/NDK build, not a glibc ARM64 binary
with an Android-flavored directory name:
- ELF64 AArch64 shared object.
- Depends on `libandroid.so`, `liblog.so`, `libm.so`, `libdl.so`, and Bionic
`libc.so`.
- Uses the NDK C++ namespace (`std::__ndk1`).
- Carries `.note.android.ident` and Android LLVM/Clang build strings.
- Contains no `GLIBC_*` symbol-version requirements.
Android's stock linker on an AYN Thor loaded both Valve libraries with no
compatibility shim. `CreateInterface("SteamClient023")` also succeeded.
## What `steamservice.so` proved
`steamservice.so` exports `SteamService_StartThread`,
`SteamService_GetIPCServer`, `SteamService_Stop`, and
`SteamService_Shutdown`. A non-null service name starts its worker thread
successfully on Android and shuts down normally.
That service is **not** the Steamworks host expected by `libsteamclient.so`.
Starting it does not create the TCP IPC listener used by `CreateSteamPipe`.
The service probe is retained because it establishes that the Bionic service
code itself is runnable and documents the calling convention.
## The actual dependency: Steam IPC on TCP 57343
With no Steam host available, both the legacy exported C entry point and the
`SteamClient023` virtual `CreateSteamPipe` method return `0`.
An `LD_PRELOAD` trace of `socket()` and `connect()` showed why:
```text
socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) -> fd
connect(fd, 127.0.0.1:57343) -> ECONNREFUSED
connect(fd, 127.0.0.1:57343) -> ECONNREFUSED
```
A dummy listener captured the client's first 17 bytes:
```text
0d 00 00 00 09 01 00 00 00 00 00 00 00 00 00 00 00
```
Port 57343 is Steam's long-standing local IPC listener. Valve's Lepton
Android compatibility environment uses the same Steam gateway for its
Android `libsteamclient.so`.
## End-to-end proof
Desktop Steam on a Mac was listening on host `127.0.0.1:57343`. We mapped
Android's loopback port to it temporarily with:
```sh
adb reverse tcp:57343 tcp:57343
```
With no local `steamservice.so` involved, the unmodified Bionic client on the
Thor then returned:
```text
SteamClient023=<non-null> rc=0
Steam_CreateSteamPipe=1
Steam_ConnectToGlobalUser=1
Steam_BConnected=1
Steam_BLoggedOn=1
Steam_BReleaseSteamPipe=1
```
This proves the Bionic client is operational on normal Android and can speak
the real cross-process Steam IPC protocol to an ordinary desktop Steam
process.
## Implication for DroidDeck / PRoot
This discovery does **not** by itself remove PRoot. The Android archive does
not contain the full Steam executable or `steamwebhelper`; the Bionic client
expects that full Steam process to exist elsewhere and own port 57343.
The useful architectural split is now proven rather than hypothetical:
```text
Android/Bionic workload
-> Valve Bionic libsteamclient.so
-> TCP Steam IPC :57343
-> full Steam host process
```
For a PRoot-free DroidDeck, the remaining problem is therefore the **host
Steam process**, not Steamworks ABI compatibility. Plausible future backends
are a real Linux environment (rooted chroot/namespaces), a VM/AVF guest with
a host bridge, or a future Valve Bionic build of the full client. Reimplementing
Steam's private IPC server should be treated as a last resort.
## Reproducing
Build and fetch Valve's current Android package into `/tmp`:
```sh
tools/research/bionic-steam-probe/fetch_build.sh
```
Run without a Steam host. This should resolve the Bionic interfaces but
return pipe/user handle `0`:
```sh
tools/research/bionic-steam-probe/run_probe.sh
```
If desktop Steam is running on the ADB host and listening on loopback, test
the real bridge:
```sh
tools/research/bionic-steam-probe/run_probe.sh --reverse-host-steam
```
The runner removes the ADB reverse mapping on exit. No Valve binary is copied
into this repository.
## Security note
Steam binds 57343 to loopback on desktop systems. Keep any DroidDeck bridge
equally constrained; do not expose this private Steam IPC endpoint to the LAN.
On Android all regular applications share the device network namespace, so a
future local host design should also consider how to prevent unrelated apps
from reaching a loopback-only Steam IPC listener.
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env bash
set -euo pipefail
MANIFEST_URL="${MANIFEST_URL:-https://client-update.steamstatic.com/steam_client_publicbeta_linuxarm64}"
WORKDIR="${WORKDIR:-${TMPDIR:-/tmp}/droiddeck-bionic-steam-probe}"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
mkdir -p "$WORKDIR/android" "$WORKDIR/bin"
find_ndk() {
if [[ -n "${ANDROID_NDK_HOME:-}" ]]; then
printf '%s\n' "$ANDROID_NDK_HOME"
return
fi
if [[ -n "${ANDROID_NDK_ROOT:-}" ]]; then
printf '%s\n' "$ANDROID_NDK_ROOT"
return
fi
local sdk="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}}"
local ndk
ndk="$(find "$sdk/ndk" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | sort -V | tail -1)"
[[ -n "$ndk" ]] || return 1
printf '%s\n' "$ndk"
}
NDK="$(find_ndk)" || {
echo "Android NDK not found; set ANDROID_NDK_HOME" >&2
exit 1
}
HOST_TAG="linux-x86_64"
[[ "$(uname -s)" == Darwin ]] && HOST_TAG="darwin-x86_64"
CC="$NDK/toolchains/llvm/prebuilt/$HOST_TAG/bin/aarch64-linux-android26-clang"
curl -fsSL "$MANIFEST_URL" -o "$WORKDIR/manifest.vdf"
PACKAGE="$(python3 - "$WORKDIR/manifest.vdf" <<'PY'
import re
import sys
text = open(sys.argv[1], encoding="utf-8").read()
m = re.search(
r'"bins_androidarm64_linuxarm64"\s*\{.*?"file"\s*"([^"]+)"',
text,
re.S,
)
if not m:
raise SystemExit("bins_androidarm64_linuxarm64 not found")
print(m.group(1))
PY
)"
PACKAGE_SHA="$(python3 - "$WORKDIR/manifest.vdf" <<'PY'
import re
import sys
text = open(sys.argv[1], encoding="utf-8").read()
block = re.search(r'"bins_androidarm64_linuxarm64"\s*\{(.*?)\n\s*\}', text, re.S)
if not block:
raise SystemExit("bins_androidarm64_linuxarm64 block not found")
m = re.search(r'"sha2"\s*"([0-9a-fA-F]{64})"', block.group(1))
if not m:
raise SystemExit("sha2 missing from Android ARM64 package")
print(m.group(1).lower())
PY
)"
echo "Valve package: $PACKAGE"
curl -fsSL "https://client-update.steamstatic.com/$PACKAGE" -o "$WORKDIR/android.zip"
ACTUAL_SHA="$(python3 - "$WORKDIR/android.zip" <<'PY'
import hashlib
import sys
print(hashlib.sha256(open(sys.argv[1], "rb").read()).hexdigest())
PY
)"
[[ "$ACTUAL_SHA" == "$PACKAGE_SHA" ]] || {
echo "SHA-256 mismatch: manifest=$PACKAGE_SHA download=$ACTUAL_SHA" >&2
exit 1
}
python3 - "$WORKDIR/android.zip" "$WORKDIR/android" <<'PY'
import os
import sys
import zipfile
archive, out = sys.argv[1:]
wanted = {
"libsteamclient.so",
"steamservice.so",
"libtier0_s.so",
"libvstdlib_s.so",
}
with zipfile.ZipFile(archive) as zf:
for name in zf.namelist():
base = os.path.basename(name)
if base in wanted:
target = os.path.join(out, base)
with open(target, "wb") as f:
f.write(zf.read(name))
print(f"extracted {name} -> {target}")
PY
"$CC" -O0 -g -Wall -Wextra "$SCRIPT_DIR/steamclient_probe.c" -ldl -o "$WORKDIR/bin/steamclient-probe"
"$CC" -O0 -g -Wall -Wextra "$SCRIPT_DIR/steamservice_probe.c" -ldl -o "$WORKDIR/bin/steamservice-probe"
"$CC" -O0 -g -Wall -Wextra "$SCRIPT_DIR/steamclient_service_probe.c" -ldl -o "$WORKDIR/bin/steamclient-service-probe"
"$CC" -shared -fPIC -O0 -g -Wall -Wextra "$SCRIPT_DIR/trace_hooks.c" -o "$WORKDIR/bin/trace-hooks.so"
echo "Built probes in $WORKDIR/bin"
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
set -euo pipefail
WORKDIR="${WORKDIR:-${TMPDIR:-/tmp}/droiddeck-bionic-steam-probe}"
ADB="${ADB:-adb}"
REMOTE="/data/local/tmp/droiddeck-bionic"
REVERSE=0
if [[ "${1:-}" == "--reverse-host-steam" ]]; then
REVERSE=1
elif [[ -n "${1:-}" ]]; then
echo "usage: $0 [--reverse-host-steam]" >&2
exit 2
fi
[[ -f "$WORKDIR/bin/steamclient-probe" ]] || {
echo "Run fetch_build.sh first" >&2
exit 1
}
[[ -f "$WORKDIR/android/libsteamclient.so" ]] || {
echo "Valve libsteamclient.so is missing from $WORKDIR" >&2
exit 1
}
"$ADB" shell "mkdir -p $REMOTE"
"$ADB" push "$WORKDIR/bin/steamclient-probe" "$REMOTE/steamclient-probe" >/dev/null
"$ADB" push "$WORKDIR/android/libsteamclient.so" "$REMOTE/libsteamclient.so" >/dev/null
"$ADB" shell "chmod 755 $REMOTE/steamclient-probe"
cleanup() {
if (( REVERSE )); then
"$ADB" reverse --remove tcp:57343 >/dev/null 2>&1 || true
fi
}
trap cleanup EXIT
if (( REVERSE )); then
"$ADB" reverse --remove tcp:57343 >/dev/null 2>&1 || true
"$ADB" reverse tcp:57343 tcp:57343 >/dev/null
echo "Mapped Android 127.0.0.1:57343 to host 127.0.0.1:57343."
echo "A desktop Steam process must already be listening on the host."
else
echo "No bridge configured; CreateSteamPipe should be 0 unless Steam already"
echo "exists in the Android network namespace."
fi
set +e
"$ADB" shell "$REMOTE/steamclient-probe $REMOTE/libsteamclient.so"
rc=$?
set -e
if (( REVERSE )); then
if (( rc == 0 )); then
echo "PASS: Bionic libsteamclient connected to host Steam."
else
echo "FAIL: Bionic libsteamclient did not obtain a Steam pipe." >&2
fi
fi
exit "$rc"
@@ -0,0 +1,73 @@
#include <dlfcn.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
typedef void *(*create_interface_fn)(const char *, int *);
typedef int32_t (*create_pipe_fn)(void);
typedef int32_t (*connect_user_fn)(int32_t);
typedef bool (*status_fn)(int32_t, int32_t);
typedef bool (*release_pipe_fn)(int32_t);
static void *lookup(void *handle, const char *name) {
dlerror();
void *ptr = dlsym(handle, name);
const char *error = dlerror();
printf("dlsym %-28s = %p", name, ptr);
if (error != NULL) printf(" error=%s", error);
putchar('\n');
return ptr;
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s LIBSTEAMCLIENT.SO\n", argv[0]);
return 2;
}
printf("pid=%d uid=%d\n", getpid(), getuid());
void *client = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL);
if (client == NULL) {
fprintf(stderr, "dlopen failed: %s\n", dlerror());
return 3;
}
create_interface_fn create_interface =
(create_interface_fn)lookup(client, "CreateInterface");
create_pipe_fn create_pipe =
(create_pipe_fn)lookup(client, "Steam_CreateSteamPipe");
connect_user_fn connect_user =
(connect_user_fn)lookup(client, "Steam_ConnectToGlobalUser");
status_fn connected =
(status_fn)lookup(client, "Steam_BConnected");
status_fn logged_on =
(status_fn)lookup(client, "Steam_BLoggedOn");
release_pipe_fn release_pipe =
(release_pipe_fn)lookup(client, "Steam_BReleaseSteamPipe");
int rc = -1;
void *iface = create_interface != NULL
? create_interface("SteamClient023", &rc) : NULL;
printf("SteamClient023=%p rc=%d\n", iface, rc);
int32_t pipe = create_pipe != NULL ? create_pipe() : 0;
printf("Steam_CreateSteamPipe=%d\n", pipe);
int32_t user = (pipe != 0 && connect_user != NULL)
? connect_user(pipe) : 0;
printf("Steam_ConnectToGlobalUser=%d\n", user);
if (pipe != 0 && user != 0 && connected != NULL) {
printf("Steam_BConnected=%d\n", connected(user, pipe));
}
if (pipe != 0 && user != 0 && logged_on != NULL) {
printf("Steam_BLoggedOn=%d\n", logged_on(user, pipe));
}
if (pipe != 0 && release_pipe != NULL) {
printf("Steam_BReleaseSteamPipe=%d\n", release_pipe(pipe));
}
dlclose(client);
return pipe != 0 && user != 0 ? 0 : 4;
}
@@ -0,0 +1,146 @@
#include <dlfcn.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
typedef void *(*create_interface_fn)(const char *, int *);
typedef void *(*service_start_fn)(const char *);
typedef void *(*service_get_ipc_fn)(void);
typedef void (*service_void_fn)(void);
typedef int32_t (*create_pipe_fn)(void);
typedef int32_t (*connect_user_fn)(int32_t);
typedef bool (*connected_fn)(int32_t, int32_t);
typedef bool (*release_pipe_fn)(int32_t);
static void *must_sym(void *handle, const char *name) {
dlerror();
void *ptr = dlsym(handle, name);
const char *error = dlerror();
printf("dlsym %-28s = %p", name, ptr);
if (error != NULL) printf(" error=%s", error);
putchar('\n');
fflush(stdout);
return ptr;
}
static void dump_unix_sockets(const char *label) {
FILE *file = fopen("/proc/self/net/unix", "r");
if (file == NULL) return;
printf("--- UNIX sockets: %s ---\n", label);
char line[1024];
while (fgets(line, sizeof(line), file) != NULL) {
if (strstr(line, "steam") != NULL ||
strstr(line, "Steam") != NULL ||
strstr(line, "@") != NULL) {
fputs(line, stdout);
}
}
fclose(file);
fflush(stdout);
}
static void *open_library(const char *path) {
printf("dlopen(%s)\n", path);
fflush(stdout);
void *handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (handle == NULL) {
fprintf(stderr, "dlopen failed: %s\n", dlerror());
} else {
printf("dlopen ok handle=%p\n", handle);
}
return handle;
}
int main(int argc, char **argv) {
if (argc < 3) {
fprintf(stderr, "usage: %s STEAMSERVICE.SO LIBSTEAMCLIENT.SO [service_arg]\n",
argv[0]);
return 2;
}
const char *service_arg = argc >= 4 ? argv[3] : ".";
printf("pid=%d uid=%d service_arg=%s\n",
getpid(), getuid(), service_arg);
void *service = open_library(argv[1]);
if (service == NULL) return 3;
service_start_fn service_start =
(service_start_fn)must_sym(service, "SteamService_StartThread");
service_get_ipc_fn get_ipc =
(service_get_ipc_fn)must_sym(service, "SteamService_GetIPCServer");
service_void_fn stop =
(service_void_fn)must_sym(service, "SteamService_Stop");
service_void_fn shutdown =
(service_void_fn)must_sym(service, "SteamService_Shutdown");
printf("IPC before start=%p\n", get_ipc != NULL ? get_ipc() : NULL);
void *started = service_start != NULL ? service_start(service_arg) : NULL;
printf("StartThread=%p IPC after start=%p\n",
started, get_ipc != NULL ? get_ipc() : NULL);
fflush(stdout);
usleep(200000);
dump_unix_sockets("after service start");
void *client = open_library(argv[2]);
if (client == NULL) return 4;
create_interface_fn create_interface =
(create_interface_fn)must_sym(client, "CreateInterface");
create_pipe_fn create_pipe =
(create_pipe_fn)must_sym(client, "Steam_CreateSteamPipe");
connect_user_fn connect_user =
(connect_user_fn)must_sym(client, "Steam_ConnectToGlobalUser");
connected_fn connected =
(connected_fn)must_sym(client, "Steam_BConnected");
connected_fn logged_on =
(connected_fn)must_sym(client, "Steam_BLoggedOn");
release_pipe_fn release_pipe =
(release_pipe_fn)must_sym(client, "Steam_BReleaseSteamPipe");
int rc = -999;
void *steam_client = create_interface != NULL
? create_interface("SteamClient023", &rc) : NULL;
printf("CreateInterface SteamClient023 -> %p rc=%d\n",
steam_client, rc);
int32_t adapter_pipe = 0;
if (steam_client != NULL) {
void **vtable = *(void ***)steam_client;
int32_t (*adapter_create_pipe)(void *) =
(int32_t (*)(void *))vtable[0];
printf("SteamClient023 vtable=%p CreateSteamPipe=%p\n",
vtable, (void *)adapter_create_pipe);
adapter_pipe = adapter_create_pipe(steam_client);
printf("SteamClient023::CreateSteamPipe -> %d\n", adapter_pipe);
}
int32_t pipe = create_pipe != NULL ? create_pipe() : 0;
printf("Steam_CreateSteamPipe -> %d\n", pipe);
dump_unix_sockets("after client CreateSteamPipe");
int32_t user = (connect_user != NULL && pipe != 0)
? connect_user(pipe) : 0;
printf("Steam_ConnectToGlobalUser(%d) -> %d\n", pipe, user);
if (connected != NULL && user != 0 && pipe != 0) {
printf("Steam_BConnected -> %d\n", connected(user, pipe));
}
if (logged_on != NULL && user != 0 && pipe != 0) {
printf("Steam_BLoggedOn -> %d\n", logged_on(user, pipe));
}
fflush(stdout);
sleep(2);
if (release_pipe != NULL && pipe != 0) {
printf("Steam_BReleaseSteamPipe -> %d\n", release_pipe(pipe));
}
if (stop != NULL) stop();
if (shutdown != NULL) shutdown();
dlclose(client);
dlclose(service);
puts("done");
return 0;
}
@@ -0,0 +1,83 @@
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef void *(*get_ipc_fn)(void);
typedef void *(*start_thread_fn)(const char *);
typedef void (*void_fn)(void);
static void *lookup(void *handle, const char *name) {
dlerror();
void *ptr = dlsym(handle, name);
const char *error = dlerror();
printf("dlsym %-28s = %p", name, ptr);
if (error != NULL) {
printf(" error=%s", error);
}
putchar('\n');
fflush(stdout);
return ptr;
}
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr,
"usage: %s STEAMSERVICE.SO [symbols|getipc|start [arg]]\n",
argv[0]);
return 2;
}
printf("pid=%d uid=%d euid=%d\n", getpid(), getuid(), geteuid());
printf("dlopen(%s)\n", argv[1]);
fflush(stdout);
void *handle = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL);
if (handle == NULL) {
fprintf(stderr, "dlopen failed: %s\n", dlerror());
return 3;
}
printf("dlopen ok handle=%p\n", handle);
get_ipc_fn get_ipc =
(get_ipc_fn)lookup(handle, "SteamService_GetIPCServer");
start_thread_fn start =
(start_thread_fn)lookup(handle, "SteamService_StartThread");
void_fn stop = (void_fn)lookup(handle, "SteamService_Stop");
void_fn shutdown = (void_fn)lookup(handle, "SteamService_Shutdown");
lookup(handle, "SteamService_RunMainLoop");
lookup(handle, "CreateInterface");
const char *mode = argc >= 3 ? argv[2] : "symbols";
if (!strcmp(mode, "getipc") || !strcmp(mode, "start")) {
printf("GetIPCServer before start -> %p\n",
get_ipc != NULL ? get_ipc() : NULL);
fflush(stdout);
}
if (!strcmp(mode, "start")) {
const char *arg = argc >= 4 ? argv[3] : NULL;
printf("StartThread arg=%s\n", arg != NULL ? arg : "<NULL>");
fflush(stdout);
void *result = start != NULL ? start(arg) : NULL;
printf("StartThread -> %p; GetIPCServer -> %p\n",
result, get_ipc != NULL ? get_ipc() : NULL);
fflush(stdout);
sleep(2);
if (stop != NULL) {
puts("Stop()");
fflush(stdout);
stop();
}
if (shutdown != NULL) {
puts("Shutdown()");
fflush(stdout);
shutdown();
}
}
dlclose(handle);
puts("done");
return 0;
}
@@ -0,0 +1,101 @@
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/un.h>
#include <unistd.h>
static void trace_line(const char *kind, int fd,
const struct sockaddr *addr, socklen_t len) {
char buffer[768];
const char *detail = "";
char endpoint[512] = {0};
if (addr != NULL && addr->sa_family == AF_UNIX &&
len > offsetof(struct sockaddr_un, sun_path)) {
const struct sockaddr_un *un = (const struct sockaddr_un *)addr;
size_t path_len = len - offsetof(struct sockaddr_un, sun_path);
if (path_len > sizeof(un->sun_path)) path_len = sizeof(un->sun_path);
if (path_len > 0 && un->sun_path[0] == '\0') {
snprintf(endpoint, sizeof(endpoint), "@%.*s",
(int)(path_len - 1), un->sun_path + 1);
} else {
snprintf(endpoint, sizeof(endpoint), "%.*s",
(int)path_len, un->sun_path);
}
detail = endpoint;
} else if (addr != NULL && addr->sa_family == AF_INET &&
len >= sizeof(struct sockaddr_in)) {
const struct sockaddr_in *in = (const struct sockaddr_in *)addr;
unsigned long ip = ntohl(in->sin_addr.s_addr);
snprintf(endpoint, sizeof(endpoint), "%lu.%lu.%lu.%lu:%u",
(ip >> 24) & 0xff, (ip >> 16) & 0xff,
(ip >> 8) & 0xff, ip & 0xff, ntohs(in->sin_port));
detail = endpoint;
}
int n = snprintf(buffer, sizeof(buffer),
"[probe-trace] %s fd=%d family=%d endpoint=%s\n",
kind, fd, addr != NULL ? addr->sa_family : -1, detail);
if (n > 0) write(STDERR_FILENO, buffer, (size_t)n);
}
int socket(int domain, int type, int protocol) {
int fd = (int)syscall(SYS_socket, domain, type, protocol);
char buffer[160];
int n = snprintf(buffer, sizeof(buffer),
"[probe-trace] socket domain=%d type=%d protocol=%d -> %d errno=%d\n",
domain, type, protocol, fd, fd < 0 ? errno : 0);
if (n > 0) write(STDERR_FILENO, buffer, (size_t)n);
return fd;
}
int socketpair(int domain, int type, int protocol, int sv[2]) {
int rc = (int)syscall(SYS_socketpair, domain, type, protocol, sv);
char buffer[180];
int n = snprintf(buffer, sizeof(buffer),
"[probe-trace] socketpair domain=%d type=%d -> %d [%d,%d] errno=%d\n",
domain, type, rc, rc == 0 ? sv[0] : -1,
rc == 0 ? sv[1] : -1, rc < 0 ? errno : 0);
if (n > 0) write(STDERR_FILENO, buffer, (size_t)n);
return rc;
}
int connect(int fd, const struct sockaddr *addr, socklen_t len) {
trace_line("connect", fd, addr, len);
int rc = (int)syscall(SYS_connect, fd, addr, len);
if (rc < 0) {
char buffer[120];
int n = snprintf(buffer, sizeof(buffer),
"[probe-trace] connect rc=%d errno=%d\n", rc, errno);
if (n > 0) write(STDERR_FILENO, buffer, (size_t)n);
}
return rc;
}
int bind(int fd, const struct sockaddr *addr, socklen_t len) {
trace_line("bind", fd, addr, len);
int rc = (int)syscall(SYS_bind, fd, addr, len);
if (rc < 0) {
char buffer[120];
int n = snprintf(buffer, sizeof(buffer),
"[probe-trace] bind rc=%d errno=%d\n", rc, errno);
if (n > 0) write(STDERR_FILENO, buffer, (size_t)n);
}
return rc;
}
int listen(int fd, int backlog) {
int rc = (int)syscall(SYS_listen, fd, backlog);
char buffer[120];
int n = snprintf(buffer, sizeof(buffer),
"[probe-trace] listen fd=%d backlog=%d -> %d errno=%d\n",
fd, backlog, rc, rc < 0 ? errno : 0);
if (n > 0) write(STDERR_FILENO, buffer, (size_t)n);
return rc;
}
+92
View File
@@ -0,0 +1,92 @@
import json
import os
from pathlib import Path
import runpy
import subprocess
import sys
import tempfile
import unittest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
MODULE = runpy.run_path(str(BIN / "bannerlator-game-env"))
COMPAT = runpy.run_path(str(BIN / "bannerlator-steam-compat"))
class GameEnvironmentTest(unittest.TestCase):
def test_profile_precedence_and_unset(self):
env = {"KEEP": "inherited", "REMOVE": "inherited", "CUSTOM": "launch option"}
config = {"version": 1, "shared": {"CUSTOM": "shared"}, "games": {"42": {"REMOVE": None, "CUSTOM": "game", "EMPTY": ""}}}
self.assertEqual(MODULE["apply_config"](env, config, "42"), {"KEEP": "inherited", "CUSTOM": "game", "EMPTY": ""})
self.assertEqual(env["REMOVE"], "inherited")
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
def test_invalid_configuration_is_atomic(self):
env = {"ORIGINAL": "unchanged"}
for entries in ({"A": "ok", "BAD=KEY": "x"}, {"A": "bad\0value"}, {"A": 1}):
with self.assertRaises(ValueError):
MODULE["apply_config"](env, {"version": 1, "shared": entries}, "42")
self.assertEqual(env, {"ORIGINAL": "unchanged"})
def test_game_ids_and_probes(self):
for prefix in ("", "/compatdata/0", "/compatdata/0-123", "/compatdata/nope", "/compatdata/4294967296"):
self.assertIsNone(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": prefix}))
self.assertEqual(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": "/a/compatdata/42/"}), "42")
self.assertEqual(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": "/a/compatdata/-1"}), "4294967295")
def test_launch_reads_updates_preserves_argv_and_does_not_execute_values(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
probe = home / "fake-proton"
probe.write_text("#!/usr/bin/python3\nimport json, os, sys\nprint(json.dumps([os.environ.get('CUSTOM'), sys.argv[1:]]))\n")
probe.chmod(0o755)
env = {**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": "/compatdata/42"}
for value in ("first value", "$(touch " + str(home / "injected") + "); 'literal'=value"):
config.write_text(json.dumps({"version": 1, "shared": {"CUSTOM": value}}))
result = subprocess.check_output([sys.executable, str(BIN / "bannerlator-game-env"), str(probe), "waitforexitandrun", "path with spaces", "a=b"], env=env, text=True)
self.assertEqual(json.loads(result), [value, ["waitforexitandrun", "path with spaces", "a=b"]])
self.assertFalse((home / "injected").exists())
for verb, prefix in (("run", "/compatdata/42"), ("waitforexitandrun", "/compatdata/0")):
output = subprocess.check_output([sys.executable, str(BIN / "bannerlator-game-env"), str(probe), verb], env={**env, "STEAM_COMPAT_DATA_PATH": prefix, "CUSTOM": "original"}, text=True)
self.assertEqual(json.loads(output)[0], "original")
config.write_text("{broken")
result = subprocess.run([sys.executable, str(BIN / "bannerlator-game-env"), str(probe), "waitforexitandrun"], env={**env, "CUSTOM": "original"}, text=True, capture_output=True, check=True)
self.assertEqual(json.loads(result.stdout)[0], "original")
def test_generated_valve_and_third_party_launchers_apply_configuration(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
steam = home / "Steam"
tools = steam / "compatibilitytools.d"
depot = steam / "steamapps/common" / COMPAT["SOURCES"][0]
(depot / "files/bin-arm64").mkdir(parents=True)
extra = tools / "custom-proton"
extra.mkdir(parents=True)
for base in (depot, extra):
proton = base / "proton"
proton.write_text("#!/usr/bin/python3\nimport json, os, sys\nprint(json.dumps([os.environ['CUSTOM'], sys.argv[1:]]))\nsys.exit(7)\n")
proton.chmod(0o755)
(extra / "toolmanifest.vdf").write_text('"manifest" { "commandline" "/proton %verb%" }')
COMPAT["build_tool"](str(tools / COMPAT["TOOL"]))
COMPAT["adopt_extras"](str(tools))
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
config.write_text(json.dumps({"version": 1, "shared": {"CUSTOM": "shared"}, "games": {"42": {"CUSTOM": "specific"}}}))
wrappers = (tools / COMPAT["TOOL"] / COMPAT["LAUNCHER"], extra / COMPAT["EXTRA_WRAPPER"])
for wrapper in wrappers:
wrapper.write_text(wrapper.read_text().replace("/usr/local/bin/bannerlator-game-env", str(BIN / "bannerlator-game-env")))
result = subprocess.run([str(wrapper), "waitforexitandrun", "game with spaces.exe"],
env={"PATH": os.defpath, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": "/compatdata/42", "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(steam)},
text=True, capture_output=True)
self.assertEqual(result.returncode, 7, result.stderr)
self.assertEqual(json.loads(result.stdout), ["specific", ["waitforexitandrun", "game with spaces.exe"]])
def test_both_proton_wrappers_call_environment_launcher(self):
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertIn('exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env', script)
if __name__ == "__main__":
unittest.main()