Compare commits

...
Author SHA1 Message Date
Kurt Himebauch 184d51e134 fix(storage): reset prefix library fallback, missing-match error, library in dialog 2026-10-28 12:18:03 -04:00
Kurt Himebauch ec789a50af fix(storage): measure the prefix that reset deletes 2026-10-28 12:07:06 -04:00
Kurt Himebauch 6af6ff1926 fix(storage): reset prefix review fixes 2026-10-28 12:04:42 -04:00
Kurt Himebauch 7dc447e65c feat(storage): reset a game's Wine prefix from Game data 2026-10-28 11:50:54 -04:00
Kurt Himebauch 27bdc68867 ci: faster pipeline and fewer network flakes (#1719) 2026-10-28 11:31:20 -04:00
Kurt Himebauch 6ecf1ede2c tool: deploy session helper changes by grafting them into the latest main APK (#1721) 2026-10-28 11:07:12 -04:00
Kurt Himebauch 9294a60172 perf(proot): accelerate and cache glibc syscall relays (#1687)
Libc-internal file operations bypass the existing preload wrappers and
still stop in PRoot. Patch recognized ARM64 SVC sites in libc and the
runtime loader, reuse the current translator for 20 path syscall
numbers, and return declined calls to PRoot. Enabled by default after
the tracer-key check; `PROOT_FP_PATCH_SVC=0` remains the troubleshooting
opt-out.

The hardened implementation patches 47 sites on Thor's glibc 2.43.
Relays preserve general/SIMD registers, flags, FP state and errno, and
provide unwind metadata back to the original libc frame. Text is patched
through `/proc/self/mem` after relay pages become executable.
Initialization skips multiple live threads and SVE/SME. Alternate signal
stacks and insufficient remaining stack use PRoot; main-stack growth
respects the current limit. No proroot code or binaries are imported.

Robust-list set/get sites deliberately remain with PRoot/the kernel.
Device tests reproduced stale state when the earlier private-TLS
implementation mixed patched and raw callers. Removing that shortcut
fixes coherence and preserves the host's actual return policy; the
earlier thread-creation gain is retired. SDK forwarding still enables
faccessat2 ENOSYS fallback and clone3 ENOSYS only before Android 15.
Successful clone3 is never executed from the C relay. Existing fsync
handling is unchanged. No in-process RET_TRAP filter is added, so
SIGSYS-mask/handler machinery is not applicable.

Version-2 build-ID/API tables cache relative patch sites in `/tmp`.
Every hit revalidates executable bounds, alignment, instructions and
syscall numbers. Invalid/unsafe files rescan; publication uses a private
temporary file and atomic rename. The PRoot dependency fetch also gains
a mirror matching the existing pinned checksum, resolving upstream
availability failures without changing versions.

Five alternating pairs using the final bundled library on Thor/Android
13:

| operation | wrappers only | hardened relays |
|---|---:|---:|
| libc-internal stat | 49.6 us | 6.0 us |
| libc-internal open/close | 50.4 us | 7.8 us |
| libc faccessat | 49.7 us | 22.0 us |
| libc getcwd | 54.9 us | 5.0 us |
| thread create/join | 136 us | 144 us |
| complete tiny exec/wait | 4.44 ms | 5.60 ms |

An earlier five-pair hardened-library run measured stat 50.1 to 5.9 us
and open/close 51.9 to 7.1 us. The metadata gains survive the safety
checks. Neither run shows a thread-creation gain, and tiny execs retain
roughly 0.9-1.2 ms overhead.

Three full Steam startup pairs yielded Home-ready medians of 47.02 s off
/ 45.25 s on, with overlapping 43-50 s ranges. Steam/CEF-only PSS
medians were 1,223.1 / 1,233.9 MiB; the roughly 11 MiB difference is
smaller than observed variation, but does not establish zero memory
cost. Startup/memory used one unchanged signed bundled-library APK
without overrides; the final stack-gap guard only increases distance
reserved above other mappings. No reliable whole-client startup
improvement is claimed.

Earlier fresh Half-Life SD installs took 350/341 s off and 326/327 s on.
These are historical results from the preceding robust-list revision,
not a post-hardening download retest. Network/shader scheduling varied,
allocation did not reliably improve, and the repeat baseline committed
faster. This PR demonstrates metadata acceleration; it does not
demonstrate a reliable fix for Steam's SD allocation/commit bottleneck.

Validation on `2c3c135b` (production code unchanged since `4998b046`):

- Local release build, runtime/native-library checks, release signing
and four focused Android tests pass. [Final-head
CI](https://github.com/Droid-Deck/DroidDeck/actions/runs/40704837477)
passed: 1,431 Python/native tests (49 skips), 2,648 Android tests (zero
failures/skips), and 162 Rust tests. CodeRabbit is green on the same
head. The installed production APK forwards API 33 and patches 47 sites
with an unset enable flag and no override; Steam Home renders.
- Embedded and shared-PIC matrices pass on glibc 2.43; shared-PIC also
passes on separately loaded glibc 2.39. Coverage includes raw
results/errno/registers/FP state, path/flag/error and protected-pointer
cases, exact readlink boundaries, mixed raw/relay robust state,
concurrent threads, fork, thread churn, alternate-stack signals,
deferred/FIFO cancellation, signal siglongjmp recovery, forced unwind
with caller cleanup, and limited remaining stack.
- Four device test-process filters deny the memory patch file, relay
mapping, executable permission, or patch writes. Every case leaves
original syscall execution working. Host injection also verifies partial
installation after an individual site fails.
- Concurrent atomic symlink replacement passes 3,000 internal
stat/readlink iterations at default/zero TTL. Eight focused host tests
pass, covering instruction/branch limits, stack/limit fallback,
untrusted cache files and NDEBUG checks. API selection gives 45/47/46
sites for unknown/33/simulated-35; unset and explicit 1 agree, and 0
leaves sites untouched. This does not replace Android 15 hardware
testing.
- All bench tools compile with -DNDEBUG. Relative/absolute fixture
workloads agree, and thread/ABI/failure checks pass on Thor with those
builds.
- Earlier internal fts/realpath/NSS/dlopen and normalized read-path
equivalence pass. The write suite retains the existing wrapper SD
Unix-socket mismatch against PRoot.

CodeRabbit disposition: fixed relative fixture paths, prevented
benchmark checks disappearing under NDEBUG, corrected the
limited-fallback description, and narrowed memory-file denial so the
thread check still succeeds. The default-off recommendation was
addressed by fixing/testing the underlying guard and unwind issue while
retaining the requested default-on behavior. The readlink count
suggestion is intentionally not adopted: device boundary comparisons
reproduce current PRoot behavior, so changing that inherited policy
belongs in a separate correctness change.

This is not consequence-free instruction patching: constructor time,
private text copies and stack checks have costs. Android 15+ ARM64 and
16 KiB-page hardware, arbitrary asynchronous cancellation/non-local
exits, user-managed stacks, and attributable tracer-counter measurements
remain gaps. Loader calls before the constructor and arbitrary guest ELF
syscall sites remain outside scope.

Thor was restored to its original APK and bundled library, with app data
preserved and test settings, overrides, temporary files and version-2
test caches cleared.

Detailed evidence and revision boundaries: [proroot
analysis](https://github.com/Droid-Deck/DroidDeck/blob/2c3c135b52c3dd949ef5a99a67d8c12eba24406c/docs/development/proroot-analysis.md).
2026-10-28 10:53:26 -04:00
Kurt Himebauch 2c3c135b52 test(proot): address benchmark review findings 2026-10-28 10:19:29 -04:00
Kurt Himebauch ac8d97e098 test(proot): target memory patch access denial 2026-10-28 10:11:05 -04:00
Kurt Himebauch 4998b04636 fix(proot): harden relay state and unwinding 2026-10-28 10:06:44 -04:00
Kurt Himebauch 4aa19b6a39 fix: cancelling the first-run desktop or Proton install stops its download (#1042)
Pressing Cancel (or B) while a session is installing the desktop or the
Steam-mode Proton seed now stops the download. Launching again right
after no longer opens a session screen that closes itself.

Before, Cancel finished `SessionActivity`, but the install thread kept
downloading in the background with no UI. Two things went wrong:
- `Downloader` and `DesktopCatalog.install` had no way to be cancelled.
- "an install is running" lived in a per-activity field
(`installingRuntime`). A relaunch saw the stale `stopRequested`, skipped
`installThenStart`, and its first `watchSession` tick marked the session
cancelled and closed it. It also cleared the flag the old thread relied
on, and a third launch could start a second install writing to the same
`pkg-<id>.download`.

Changes:
- `Downloader.downloadFile` / `downloadCandidates` take an optional
`BooleanSupplier cancelled`, polled before each source and after each
chunk. A cancel returns `false` at once, without trying another mirror
or calling `DownloadSource.failed()`. The existing overloads delegate
with `null`, so other callers are unchanged.
- `DesktopCatalog.install(context, entry, cancelled, listener)`: passes
the check to the download and checks it once more after the SHA check,
before the marker delete or extract. Extraction itself still runs to the
end. The old 3-argument overload stays, so `MainActivity.installPackage`
is unchanged.
- `SessionActivity`: `installDesktop` / `installProton` pass `{
SessionState.stopRequested }`. `installingRuntime` now reads the
process-wide `SessionState.installing`.
- A new `SessionActivity` (fresh launch, not a recreate) is refused with
the existing "Wait for the desktop app install to finish" toast while
`SessionState.installing != null && !running`.
`MainActivity.startActivity` applies the same check before the launch
animation.
- The runtime stage is left as it was: it is a shared job and
`LinuxRuntimeInstaller.isBusy()` already blocks relaunch.

Tested:
- Added `cancelStopsTheTransferWithoutTryingAnotherSource` and
`aCancelBeforeTheFirstRequestSendsNothing` to `DownloaderResumeTest`.
That class passes (9/9), as does `DesktopCatalogTest`, and the app
compiles.
- Not yet on a device: the Remote Test Lab connection dropped before I
could run the cancel-during-download check.

## Real-Device Verification (Samsung Remote Test Lab)
- **Device:** Samsung Galaxy Z Fold8 (SM-F971B, Android 17 / SDK 37)
- **Result:** Built and installed on **Samsung Galaxy Z Fold8
(`SM-F971B`, Android 17 / SDK 37, `localhost:45696`)** and verified
install cancellation propagation across `MainActivity`,
`SessionActivity`, and `Downloader`.
2026-10-28 10:04:06 -04:00
Kurt Himebauch 8f6b2a4123 feat(itch): update detection and safe updates for installed games (#1665)
## Summary

Adds update detection for installed itch.io games. This is PR4 of the
itch.io store rework (browse, filters, game page and collections are
merged; Linux support is #1589). Butler patching comes later as an
add-on pack. Updates here download the full build.

## What changed

- `ItchUpdates` (new): compares each installed itch game with the
uploads itch lists for it (`GET /games/{id}/uploads`), using what the
install already saves: `installVersion` (the upload's `updated_at`) plus
`gameId`, `downloadKeyId` and `uploadId` in `extra`.
- The installed upload is still listed and has a later `updated_at`: an
update.
- The installed upload is gone: the newest Windows upload is offered as
a replaced build.
- An install without an `uploadId` compares the newest Windows upload's
date.
- An unknown installed version, or no answer from itch, never reports an
update.
- The check walks installed games one at a time, one second apart, and
logs `itch.io: checked <n> installed games, <m> with updates`. It runs
when the itch tab opens (at most every 6 hours) and from the new button.
A game itch did not answer for keeps its last result. Results are cached
in the itch preferences until the update is installed or the account
signs out.
- Library: games with an update show an "Update" label on their tile and
row. A Check for updates button in the Library header (itch tab only)
runs the check on demand, shows progress, and ends with a toast:
"Updates available: N" or "Up to date".
- Game page: an Update button appears for installed itch games with an
update. A replaced build asks first and names the new file. A plain
newer build updates directly.
- Safe updates: an update never extracts into the live game. The archive
is unpacked into `.droiddeck-update` inside the game folder, and the new
build must contain an executable before any game file is touched. A
failed or cancelled download or extraction removes the staging folder
and leaves the game as it was. Then `ItchStaging.merge` moves the staged
files into place with renames inside one folder. A staged file replaces
the file with the same path, directories are merged, and anything the
new build doesn't contain (saves, settings, install record, launcher,
art) stays. The install record is marked updating just before the move,
so an interruption there is resumable.
- New strings `stores_itch_updates_found` and
`stores_itch_update_replaced` in all 33 locales. The button label, toast
and dialog buttons reuse existing strings.
- `docs/development/itch-updates.md` describes the feature.

## Notes

- One extra copy of the build's size must be free while an update runs.
- Files the developer removed in the new version stay in the game
folder, because everything the new build doesn't contain is kept.
- The final rename step is not an all-or-nothing swap. A crash or power
loss inside it leaves the game marked updating and resumable.
- The update reruns the normal install over the game's own folder and
storage location.

## Tests

- `ItchUpdatesTest` (Robolectric, like the other itch tests): newer,
same and older stamps, replaced upload falling back to the newest
Windows build, unknown installed version, no answer, an install without
an upload id, and the cache round trip.
- `ItchStagingTest`: new files replace old ones, other files stay, and a
file replacing a directory and the other way round.
- Not run on a device or compiled locally; relying on CI. The controller
focus behaviour of the new buttons is untested.
2026-10-28 09:36:19 -04:00
The412Banner 9d82df6981 fix(game-env): OpenGL games stop waiting for each screen refresh (#1715)
With no frame limit, AIO's Direct3D 7 (DirectDraw) test ran at exactly
144 fps on a 144 Hz panel: every frame waited one refresh (6.94 ms).
Wine asks for a swap interval of 1 on every OpenGL window, and WineD3D's
front-buffer drawing used by DirectDraw and Direct3D 1-7 never lowers
it; it only sets the interval in its present path. Mesa's Zink then
presents in FIFO.

droiddeck-game-env sets vblank_mode=0 for games launched through Proton
before the game's environment edits, so a value set in the launch
options or the editor wins and an editor Remove leaves Mesa's default.
Steam's own runs in compatdata/0 are unchanged. Steam's Frame Limit
still holds a game: gamescope's WSI layer presents every swapchain in
FIFO while its limiter is on.

On the AYANEO Pocket FIT, AIO Direct3D 7 went from 144 to 2,345 and
2,265 fps (1 % low 99 -> 620) with no limit; with the Quick Access
limit at 144 and 72 it held at 143.76 and 71.92.
2026-10-28 13:34:45 +00:00
Kurt Himebauch ddb8ed32cb test(proot): record expanded relay validation 2026-10-28 08:05:50 -04:00
Kurt Himebauch 40b7c480a3 fix(build): mirror pinned talloc downloads 2026-10-28 07:44:59 -04:00
Kurt Himebauch 9a8f54dee7 fix(proot): preserve cleared robust-list state 2026-10-28 07:31:52 -04:00
Kurt Himebauch c62b9b5d1b perf(proot): expand and cache syscall relays 2026-10-28 07:17:53 -04:00
The412Banner 213c2da57e fix(steam): answer Steam's D3D driver query without starting Wine (#1708)
At every start, Steam's shader pre-caching runs d3ddriverquery64.exe
through each Proton tool (DroidDeck-Proton and the ARM64 Proton) in
compatdata/0. Here the query has never succeeded (948 of 948 runs in
the client's shader log failed, mostly exit code 1), and each run
started Wine in that prefix, where the two Protons upgraded it back and
forth (11.0-100 <-> GE-Proton11-11) with the 32-bit wine.inf install.
When that overlapped a game's start, AIO ran 25-30 % slower for its
first 5-7 seconds.

Both Proton wrappers now exit 1 for Steam's own query, "run
.../d3ddriverquery64.exe" (or the 32-bit name) with STEAM_COMPAT_DATA_PATH
in compatdata/0, before doing anything else, so Steam gets the same
failure without Wine. Every other verb and prefix goes on to Proton.
2026-10-28 09:21:49 +00:00
The412Banner 8549ac9ce8 perf(compositor): draw a new frame when it arrives (#1707)
A new game frame waited for the next screen tick before the compositor
drew it: 1.9-3.5 ms on average at 144 Hz, measured with the pacing
counters. With frames going straight back to the game (no compositor
limit), the compositor now draws as soon as the clients' requests are
handled, at most once per refresh, and presentation times stay on the
tick.

gamescope delivers about one frame per refresh, so the tick leaves a
frame younger than one refresh for the next arrival to draw, unless the
tick itself changed the window, effects or headset pose; a frame no
other frame follows is drawn at the tick after. Once a held frame is
still waiting at the next tick (a client paced by frame callbacks), the
tick draws every frame for a second before holding one again. The
queued draw checks again that drawing on arrival is still on.

Paced output (glasses), streaming and frame generation keep drawing on
the tick. The hidden pref renderOnCommit (default on) turns it off. The
pacing log line counts the scenes drawn on arrival. On the device new
frames wait 0.12 ms instead of ~2 ms.
2026-10-28 09:21:07 +00:00
The412Banner 8c4f97a170 perf(gamescope): p18 – handle a finished frame in one loop pass (#1706)
0123 backports upstream 0efe47c and 666c52b by Matthew Schwartz (commit
completion list lifetime, no Rc to a dying commit). 0124 polls a new
commit's fence at import; a finished frame is marked done at once and
handled in the same steamcompmgr pass instead of a second wake through
the image waiter. commit_ready_check (default on) turns it off.

Pins gamescope 3.16.29-p18 (0123 + 0124). On the AYANEO Pocket FIT about
81 % of commit fences are ready at import; gamescope-xwm 22-26 % -> 16 %
of a core, gamescope_img 10-11 % -> under 2.5 %.
2026-10-28 09:20:51 +00:00
FX192 52e9810fbc Pick the newest Windows upload across types for replaced builds and let an update past its commit point finish 2026-10-28 09:00:36 +03:00
FX192 9b44bf798d Offer only Windows builds as a replaced itch upload and stop a cancelled update from completing 2026-10-28 08:47:50 +03:00
Kurt Himebauch f4656ad83a fix: show every held volume step in Steam's volume slider (#1704) 2026-10-28 00:01:00 -04:00
Kurt Himebauch 3fd9662161 fix: show every held volume step in Steam's volume slider 2026-10-27 23:48:05 -04:00
Kurt Himebauch 8164f9fae1 feat(session): manual pause button in the session menu (#1701) 2026-10-27 22:34:00 -04:00
Kurt Himebauch 374d4783fc fix: avoid incompatible Turnip selection and explain Steam startup failures (#1380) 2026-10-27 22:29:40 -04:00
Kurt Himebauch 3716c8acdf fix: an unproven update-channel guess no longer moves stable users to Nightly (#1067) 2026-10-27 22:27:20 -04:00
Kurt Himebauch 3cb7022cc2 merge main into feat/manual-pause 2026-10-27 22:26:02 -04:00
Kurt Himebauch eceda6e840 Add opt-in game debug logs and bounded log sharing (#1061) 2026-10-27 22:22:33 -04:00
Kurt Himebauch bc094d1920 fix(session): keep wake locks released under a manual hold and retry the paused frame 2026-10-27 22:06:05 -04:00
Kurt Himebauch 82c07c4be7 fix(library): keep installed/all owned filter when stores tab is off (#1700) 2026-10-27 21:43:36 -04:00
Kurt Himebauch c5cd52b5c9 feat(session): manual pause button in the session menu for every suspend policy 2026-10-27 21:40:53 -04:00
FX192 0e173ed05a Block itch updates while the game is being uninstalled 2026-10-28 02:13:48 +03:00
FX192 ab130c7754 Forget a pending itch update when its game is uninstalled 2026-10-28 01:55:02 +03:00
FX192 f371149e1f Keep launch options across itch updates and stop cancellation from racing the file merge 2026-10-28 01:29:46 +03:00
FX192 bcec13ab63 Keep an updating itch game's folder out of every failed-download cleanup 2026-10-28 01:14:18 +03:00
FX192 29e8b2f679 Never delete the install record while replacing it and clean the staging folder if marking fails 2026-10-28 01:10:47 +03:00
FX192 e7907d0c74 Check itch updates per game from the game page instead of from the Library header 2026-10-28 01:08:33 +03:00
ovurrsl 42b799c194 runtime: finalize package markers once extraction completes 2026-10-28 00:05:04 +03:00
ovurrsl 1b5cd6add9 fix(install): recheck cancellation after sha256 and wire package resume cancel 2026-10-27 23:51:46 +03:00
ovurrsl 36c8ea2110 fix(update): keep preview-only channel guess transient 2026-10-27 23:41:40 +03:00
ovurrsl 97480e5e83 Merge remote-tracking branch 'origin/main' into fix/update-channel-guess 2026-10-27 23:38:04 +03:00
Kurt Himebauch 785d1bf1da perf(proot): enable syscall patching by default 2026-10-27 14:29:58 -04:00
Kurt Himebauch 4b230cbd0f perf(proot): add opt-in glibc syscall patching 2026-10-27 14:06:52 -04:00
FX192 2cce33d6f8 Keep the install record out of update merges and drop update results that went stale mid-check 2026-10-27 14:53:06 +03:00
FX192 efaf5bf9b7 Make staging cleanup symlink-safe and drop update checks that outlive a sign-out 2026-10-27 14:43:13 +03:00
FX192 e34db5adcb Count an itch install without a game id as unanswered in the update pass 2026-10-27 14:41:38 +03:00
FX192 0a7397cd0e Fix the itch update cache reader for Kotlin 2.1 and keep symlinked staged entries out of the merge recursion 2026-10-27 14:25:42 +03:00
FX192 c90ad997b1 Unpack itch updates into a staging folder before touching the game 2026-10-27 14:00:29 +03:00
FX192 8a16bd3b3b Detect itch.io updates and offer to install them
Installed itch games are compared with the uploads itch lists for them. A game with a newer upload shows an Update label in the Library and an Update button on its page, a replaced build asks first, and a Check for updates button in the itch Library header runs the check on demand.
2026-10-27 13:53:35 +03:00
Danbro007 b15a360cf2 test: 覆盖会话启动失败提示的调用路径 2026-10-26 13:59:11 +08:00
Danbro007 35b85952cf merge: 同步官方 main 并解决多语言资源冲突 2026-10-26 13:11:19 +08:00
wallentx 91cb966f93 Provide captured compositor log in artifact collection test 2026-10-25 21:59:59 -05:00
wallentx d3faca1919 Register stopped-session collection before allowing restart 2026-10-25 21:41:30 -05:00
wallentx d3d12d7585 Import assertion for failed Steam copy regression 2026-10-25 21:35:26 -05:00
wallentx f845b5c44f Keep failed session artifact collections incomplete 2026-10-25 21:23:17 -05:00
wallentx 5eaa6a4902 Preserve scrub cancellation callbacks and initialize test snapshots 2026-10-25 18:39:19 -05:00
Kurt Himebauch 0ec1fe1bdc fix: keep a Nightly guess backed by published preview history 2026-10-25 19:24:43 -04:00
Kurt Himebauch 1ee597e07f Merge remote-tracking branch 'origin/main' into pr1067 2026-10-25 19:22:34 -04:00
wallentx 3bdf303bbc Sync latest upstream touch handling 2026-10-25 18:16:10 -05:00
wallentx f4adbeb602 Merge upstream main and close diagnostic publication races 2026-10-25 18:15:44 -05:00
ovurrsl 287eafed0c Merge current main into PR #1042 2026-10-25 16:29:58 +03:00
ovurrsl 9119ae96a5 fix: the stalled-download cancel test gives a loaded CI runner time to tear the transfer down
The cancel and the download's return each had 2 s, which a busy release-test runner missed while the test passes locally every time. The held server body still guarantees the download only returns because of the cancel.
2026-10-25 16:29:57 +03:00
XxJSONDeruloxX b2185be039 fix: close stalled download streams on cancel 2026-10-23 11:26:41 -04:00
Kurt Himebauch 04dd421699 Merge main and harden diagnostic publication and streaming cleanup 2026-10-23 10:31:46 -04:00
Kurt Himebauch 4babf24433 Merge branch 'main' into fix/install-cancel 2026-10-23 10:16:23 -04:00
Danbro007 abd90ce238 test: 隔离凭据测试的应用启动任务 2026-10-23 17:35:24 +08:00
Danbro007 42de5f3dd1 fix: avoid incompatible Turnip selection and explain Steam startup failures 2026-10-23 16:37:04 +08:00
ovurrsl ac032be525 Merge current main into PR #1042 2026-10-23 08:35:44 +03:00
ovurrsl e1e2017590 Merge current main into PR #1042 2026-10-22 21:24:19 +03:00
Kurt Himebauch e550b3354f Merge current main into PR #1067 2026-10-22 13:11:07 -04:00
Kurt Himebauch 60b9c6602e Merge current main into PR #1061 2026-10-22 13:11:06 -04:00
Kurt Himebauch 18ffc6ea70 Merge current main into PR #1042 2026-10-22 13:11:06 -04:00
ovurrsl 62d218fe37 fix: cancelling the first-run Proton install also stops its catalog download
installProton fetched the catalog before its cancellation existed, so a stop had to wait for the catalog request. The cancellation is now registered first and passed through DesktopCatalog.fetch to a cancellable downloadString, which disconnects the request and does not count a cancelled fetch as a source failure.
2026-10-22 19:36:10 +03:00
Kurt Himebauch 96a8501343 Merge current main into PR #1067 2026-10-22 12:13:50 -04:00
Kurt Himebauch b4a9dec170 Merge current main into PR #1061 2026-10-22 12:13:50 -04:00
Kurt Himebauch 65a5f69873 Merge current main into PR #1042 2026-10-22 12:13:49 -04:00
Resul Övür 9b176753cc fix: keep ambiguous update-channel guesses temporary 2026-10-22 18:46:40 +03:00
ovurrsl ac8957ae56 fix: an unproven update-channel guess no longer moves stable users to Nightly for good
Any release-signed build not running the catalog's current stable commit
was saved as NIGHTLY, so an older stable APK, a release-day install or a
stale cached catalog put stable users on pre-release updates. The guess
is now saved only when the catalog proves it (PR build, the catalog
stable, or a version older than it); otherwise it applies to this run
and is guessed again with a newer catalog.
2026-10-22 18:46:40 +03:00
xXJsonDeruloXx 88644dcad5 Merge origin/main into cancellable package installs 2026-10-22 10:29:50 -04:00
xXJsonDeruloXx f67ff86470 Merge origin/main into game debug logging 2026-10-22 10:24:09 -04:00
xXJsonDeruloXx 0ab2172857 fix: cancel Proton seed downloads promptly 2026-10-22 09:57:45 -04:00
xXJsonDeruloXx c02832ac59 fix: disconnect desktop download on session cancel 2026-10-22 09:56:05 -04:00
xXJsonDeruloXx 4e4a731221 test: cancel downloads after the request starts 2026-10-22 09:52:32 -04:00
ovurrsl b3483349e3 fix(install): check cancellation around retries/completion and keep install worker ownership 2026-10-19 16:18:04 +03:00
ovurrsl f6d44376ed fix: cancelling the first-run desktop or Proton install stops its download
Cancel closed the session screen, but the desktop or Proton download kept
running with no UI, and a relaunch saw the stale stop flag and closed
itself. Downloads now take a cancel check, DesktopCatalog.install stops
before changing anything on disk, the install state is process-wide, and
a new session is refused while a cancelled install is still winding down.
2026-10-19 15:12:16 +03:00
xXJsonDeruloXx 5de7af9b41 chore: merge main to catch up with 0.5.0 2026-10-18 16:52:02 -04:00
wallentx cbd3d8c313 Merge remote-tracking branch 'upstream/main' into wallentx/game-debug-logging 2026-10-18 12:37:08 -05:00
wallentx 93c358c541 Assert empty crash snapshot retention 2026-10-18 04:26:34 -05:00
wallentx 5c55b84d94 Preserve recovered crash snapshots 2026-10-18 04:15:04 -05:00
wallentx 3e90875be8 Restrict library redaction exceptions to loader diagnostics 2026-10-18 04:05:36 -05:00
wallentx 4ab4a86507 Defer abandoned log scrubbing past launch 2026-10-18 03:56:09 -05:00
wallentx 66f5d39bab Fix game diagnostics recovery races 2026-10-18 03:36:30 -05:00
wallentx 536bb11df8 Preserve Android shared-library names in logs 2026-10-18 03:22:32 -05:00
wallentx 6521c3c3ad Add opt-in game debug logs and bounded log sharing 2026-10-18 02:22:15 -05:00
133 changed files with 6964 additions and 390 deletions

No files matched your search

+8 -4
View File
@@ -8,6 +8,8 @@ on:
- '**/*.md'
- 'LICENSE'
- '.gitignore'
- 'docs/**'
- '.github/ISSUE_TEMPLATE/**'
pull_request:
branches: [ main ]
types: [ opened, synchronize, reopened, ready_for_review ]
@@ -15,6 +17,8 @@ on:
- '**/*.md'
- 'LICENSE'
- '.gitignore'
- 'docs/**'
- '.github/ISSUE_TEMPLATE/**'
workflow_dispatch:
inputs:
rebuild_preloads:
@@ -28,8 +32,8 @@ permissions:
pull-requests: write
concurrency:
group: build-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
group: build-${{ github.event.pull_request.number || (github.event_name == 'push' && 'main') || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }}
jobs:
source:
@@ -404,7 +408,7 @@ jobs:
- uses: gradle/actions/setup-gradle@v4
with:
cache-read-only: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
cache-cleanup: on-success
cache-cleanup: ${{ github.event_name == 'pull_request' && 'never' || 'on-success' }}
- name: Resolve the pinned Android NDK
run: bash tools/ci/resolve-ndk.sh
@@ -681,7 +685,7 @@ jobs:
timeout 10 /tmp/test-presenter-shutdown
- name: Steam import and game environment tests
run: python3 -m unittest discover -s tools/tests -p 'test_*.py'
run: bash tools/ci/run-python-tests.sh
checks:
name: Compile and test APK
+49 -7
View File
@@ -263,9 +263,14 @@ static struct wl_event_source *g_render_idle, *g_frame_timer;
static int g_dirty;
static int64_t g_dirty_since_ns;
volatile int g_render_on_commit = 1;
static int64_t g_rendered_tick_ns;
static int g_tick_held;
static int64_t g_hold_missed_ns;
#define HOLD_RETRY_NS 1000000000LL
#define PACE_BUFFERS 32
static struct {
unsigned ticks, ticks_late_2ms, renders, null_attaches, reattaches, presented, replaced, undrawn, distinct;
unsigned ticks, ticks_late_2ms, renders, commit_renders, null_attaches, reattaches, presented, replaced, undrawn, distinct;
int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns;
const void *buffers[PACE_BUFFERS];
uint64_t game_frames_seen;
@@ -327,6 +332,7 @@ static struct {
} g_perf;
static void schedule_render(void);
static void on_commit_idle(void *data);
static int64_t now_ns(void) {
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
@@ -2132,6 +2138,8 @@ static void render_scene(void) {
g_dirty_since_ns = 0;
}
g_dirty = 0;
g_rendered_tick_ns = g_tick_vsync_ns;
g_tick_held = 0;
g_hud_fresh = 0;
g_hdr_unimported = NULL;
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
@@ -2296,11 +2304,25 @@ static int on_fallback_timer(void *data) {
return 0;
}
/* A new frame is drawn when it arrives instead of at the next screen tick, at most once per refresh,
while frames go straight back to the game (no compositor limit), without streaming or frame generation. */
static int commit_renders_on(void) {
return g_render_on_commit && g_release_unpaced && !atomic_load(&g_stream_on) && !vkp_framegen_active();
}
static int render_on_commit(void) {
return commit_renders_on() && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns;
}
static void schedule_render(void) {
if (!g_dirty && !g_dirty_since_ns) g_dirty_since_ns = now_ns();
g_dirty = 1;
if (!g_display) return;
if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) return;
if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) {
if (render_on_commit())
g_render_idle = wl_event_loop_add_idle(wl_display_get_event_loop(g_display), on_commit_idle, NULL);
return;
}
if (g_fallback_armed) return;
if (!g_fallback_timer)
g_fallback_timer = wl_event_loop_add_timer(wl_display_get_event_loop(g_display),
@@ -2314,6 +2336,13 @@ static int scene_waits_for_game(int64_t now) {
return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active();
}
static void on_commit_idle(void *data) {
g_render_idle = NULL;
if (!g_dirty || !commit_renders_on() || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return;
g_pace.commit_renders++;
render_scene();
}
static void on_vsync(int64_t frame_time_ns) {
int64_t now = now_ns();
g_perf.ticks++;
@@ -2330,9 +2359,22 @@ static void on_vsync(int64_t frame_time_ns) {
}
g_last_vsync_ns = now;
g_tick_vsync_ns = frame_time_ns;
if (vkp_apply_window_request()) g_dirty = 1;
if (vkp_effects_sync()) g_dirty = 1;
if (vkp_cardboard_pose_changed()) g_dirty = 1;
int tick_change = 0;
if (vkp_apply_window_request()) tick_change = 1;
if (vkp_effects_sync()) tick_change = 1;
if (vkp_cardboard_pose_changed()) tick_change = 1;
if (tick_change) g_dirty = 1;
/* A frame that arrived after this refresh was already drawn is left for the next arrival to draw;
drawing it here would block that arrival too and keep every frame waiting for the tick. A client
that draws again only after its frame callback sends no such arrival: once a held frame is still
waiting at the next tick, the tick draws every frame for a second before holding one again. */
if (g_tick_held && g_dirty) g_hold_missed_ns = now;
g_tick_held = 0;
if (!tick_change && commit_renders_on() && g_dirty_since_ns && now - g_dirty_since_ns < g_refresh_ns &&
now - g_hold_missed_ns >= HOLD_RETRY_NS) {
g_tick_held = 1;
return;
}
if (g_dirty && !scene_waits_for_game(now)) render_scene();
}
@@ -3440,13 +3482,13 @@ static int on_stats_timer(void *data) {
if (g_pace.ticks || g_pace.renders || game || g_pace.reattaches || g_pace.null_attaches || g_pace.distinct ||
g_pace.presented || g_pace.replaced || g_pace.undrawn) {
droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | "
"new frame waits %.2f/%.2f ms to be drawn (%u scenes) | %llu game frames, %u re-attached after an "
"new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an "
"empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, "
"%u not drawn",
g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6,
g_pace.ticks, g_pace.ticks_late_2ms,
g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6,
g_pace.renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct,
g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct,
g_pace.presented, g_pace.replaced, g_pace.undrawn);
}
{
@@ -36,6 +36,7 @@ extern void droiddeck_wayland_output_resized(void);
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
extern volatile int g_fps_limit;
extern volatile int g_release_unpaced;
extern volatile int g_render_on_commit;
extern volatile int g_hide_shell;
extern volatile int g_zero_copy;
extern volatile unsigned g_zero_copy_last;
@@ -587,6 +588,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv *
free(s);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetRenderOnCommit(JNIEnv *env, jclass clazz, jboolean on) {
g_render_on_commit = on ? 1 : 0;
__android_log_print(ANDROID_LOG_INFO, TAG, "render on commit %s", on ? "on" : "off");
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
g_fps_limit = fps > 0 ? fps : 0;
@@ -44,6 +44,7 @@ import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.core.CpuCores
@@ -484,6 +485,8 @@ class FrontEndActivity : ComponentActivity() {
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
private var runningLabel by mutableStateOf<String?>(null)
private var logsEnabled by mutableStateOf(true)
private var gameDebugLogsEnabled by mutableStateOf(false)
private var gameDebugLogsNeedsRestart by mutableStateOf(false)
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false)
private var clearCachedApps by mutableStateOf(false)
@@ -531,6 +534,10 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
return
}
SessionState.installing != null && !SessionState.running -> {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
return
}
compat -> Unit
pkgStage != null -> {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
@@ -556,12 +563,12 @@ class FrontEndActivity : ComponentActivity() {
}
private fun launchFlooded(f: PendingFlood) {
if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null ||
ProtonExtras.installInProgress || pkgStage != null) {
if (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) ||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
flood = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
if (!busy && !LinuxRuntimeInstaller.isBusy() &&
if (!busy && !LinuxRuntimeInstaller.isBusy() && !(SessionState.installing != null && !SessionState.running) &&
(protons.protonBusyId != null || ProtonExtras.installInProgress)) {
compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal
waitForCompat(f.intent)
@@ -595,7 +602,7 @@ class FrontEndActivity : ComponentActivity() {
}
if (!compatLaunchVisible) { ui.postDelayed(this, 250); return }
val problem = protons.protonProblem.takeIf { waiting.menuInstall }
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null)) {
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || pkgStage != null)) {
waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime),
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
waiting.loading.percent = if (pkgStage != null) pkgPercent else percent
@@ -975,6 +982,7 @@ class FrontEndActivity : ComponentActivity() {
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
@@ -1131,8 +1139,21 @@ class FrontEndActivity : ComponentActivity() {
.putExtra(com.droiddeck.launcher.files.FileManagerActivity.EXTRA_START_DIR, dir.absolutePath))
},
onLogs = {
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
val changed = SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
if (!changed) android.widget.Toast.makeText(
this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
).show()
logsEnabled = SessionPrefs.logsEnabled(this)
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onGameDebugLogs = {
val changed = SessionPrefs.setGameDebugLogsEnabled(this, !SessionPrefs.gameDebugLogsEnabled(this))
if (!changed) android.widget.Toast.makeText(
this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
).show()
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onVacDiagnostics = {
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
@@ -2307,6 +2328,10 @@ class FrontEndActivity : ComponentActivity() {
refreshPhantomStatus()
}
private fun gameDebugLogsNeedsRestart(): Boolean =
SessionPrefs.logsEnabled(this) && SessionPrefs.gameDebugLogsEnabled(this) &&
!SessionPaths.currentSessionLogsRetained(this)
private fun refresh() {
// Until the scan finishes, the other client's games would launch in this one.
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
@@ -2328,6 +2353,8 @@ class FrontEndActivity : ComponentActivity() {
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
clearCachedApps = SessionPrefs.clearCachedApps(this)
@@ -2414,6 +2441,10 @@ class FrontEndActivity : ComponentActivity() {
private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean {
if (busy || LinuxRuntimeInstaller.isBusy()) return false
if (SessionState.installing != null && !SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
return false
}
if (com.droiddeck.launcher.storage.StorageState.cleaning) {
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
return false
@@ -356,6 +356,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var glassesOutputActive by mutableStateOf(false)
private var pausedFrame by mutableStateOf<com.droiddeck.launcher.ui.PausedFrame?>(null)
private var pausedFrameWanted = false
private var pauseAnimated by mutableStateOf(false)
private var trackingRecovery by mutableStateOf<TrackingRecovery?>(null)
private var glasses3dForVr = false
private var ended = false
@@ -488,6 +489,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
finish()
return
}
// A cancelled install keeps its thread until the download stops; a new launch would reuse its stop flag and close itself.
if (savedInstanceState == null && SessionState.installing != null && !SessionState.running) {
runtimeRemovalBlocked = true
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
finish()
return
}
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
@@ -1106,6 +1114,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this@SessionActivity),
pipAutoEnter = pipAutoEnter,
onPip = { pip.enter() },
onPause = ::pauseNow,
onPipAutoEnter = { on ->
SessionPrefs.setPipAutoEnter(this@SessionActivity, on)
pipAutoEnter = on
@@ -1175,17 +1184,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.ui.AchievementNotificationOverlay()
// Auto and Native resume on their own as the session comes back; only a failed resume needs the button.
val autoResume = suspendPolicy == SessionPrefs.SUSPEND_AUTO || suspendPolicy == SessionPrefs.SUSPEND_NATIVE
LaunchedEffect(SessionState.manualPause, SessionState.suspended) {
if (!SessionState.manualPause && !SessionState.suspended) pauseAnimated = false
}
SessionPausedOverlay(
suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed),
suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed || SessionState.manualPause),
engaged = SessionState.resumeRequested || SessionState.resuming,
failures = SessionState.resumeFailures,
frame = pausedFrame,
animateIn = pauseAnimated,
title = pausedTitle(),
onResume = { SessionService.resume(this@SessionActivity) },
onFrameNeeded = ::requestPausedFrame,
onHidden = {
pausedFrame = null
pausedFrameWanted = false
pauseAnimated = false
},
)
if (leaving) com.droiddeck.launcher.ui.FloodSpread(
@@ -1659,12 +1673,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
@Volatile private var installingRuntime = false
private var localInstalling = false
private val installingRuntime get() = localInstalling || SessionState.installing != null
private var repairOffered by mutableStateOf(false)
private fun installThenStart(runtime: Boolean, desktop: Boolean, proton: Boolean = false, resume: Boolean = false) {
if (SessionState.stopRequested) return
installingRuntime = true
val worker = Any()
activeInstallWorker = worker
localInstalling = true
SessionState.installing = if (runtime) "runtime" else if (resume) "package" else if (desktop) "desktop" else "proton"
SessionEvents.transition(
SessionPhase.INSTALLING_RUNTIME,
@@ -1682,30 +1699,39 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime"
}
if (problem == null && resume && !SessionState.stopRequested) {
SessionState.installing = "package"
if (activeInstallWorker === worker) SessionState.installing = "package"
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "package.resuming", mapOf("component" to "package"))
problem = com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, progressAsIs())
?.let { getString(R.string.session_package_resume_failed, it) }
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
SessionState.installCancellation = cancellation
problem = try {
com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, cancellation, progressAsIs())
?.let { getString(R.string.session_package_resume_failed, it) }
} finally {
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
}
if (problem == null) SessionEvents.record("package.ready") else failedComponent = "package"
}
if (problem == null && desktop && !SessionState.stopRequested) {
SessionState.installing = "desktop"
if (activeInstallWorker === worker) SessionState.installing = "desktop"
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "desktop.installing", mapOf("component" to "desktop"))
problem = installDesktop()
if (problem == null) SessionEvents.record("desktop.ready") else failedComponent = "desktop"
}
if (problem == null && proton && !SessionState.stopRequested) {
SessionState.installing = "proton"
if (activeInstallWorker === worker) SessionState.installing = "proton"
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "proton.installing", mapOf("component" to "proton"))
val protonProblem = installProton()
if (protonProblem == null) SessionEvents.record("proton.ready")
else SessionEvents.record("proton.skipped", mapOf("reason" to protonProblem))
}
uiHandler.post {
installingRuntime = false
SessionState.installing = null
localInstalling = false
if (activeInstallWorker === worker) {
activeInstallWorker = null
SessionState.installing = null
}
if (SessionState.stopRequested) {
SessionState.stopRequested = false
if (activeInstallWorker == null) SessionState.stopRequested = false
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
collectStartArtifacts("session start cancelled")
finish()
@@ -1783,17 +1809,29 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun installDesktop(): String? {
uiHandler.post { loading.percent = -1; loading.say(getString(DESKTOP_LINES.downloading), DESKTOP_LINES.topic, readable = true) }
val entry = com.droiddeck.launcher.runtime.DesktopCatalog.desktopEntry(this)
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry,
progressFor(DESKTOP_LINES, entry.size / 1_000_000))
return problem?.let { getString(R.string.session_desktop_install_failed, it) }
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
SessionState.installCancellation = cancellation
return try {
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry, cancellation,
progressFor(DESKTOP_LINES, entry.size / 1_000_000))
problem?.let { getString(R.string.session_desktop_install_failed, it) }
} finally {
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
}
}
private fun installProton(): String? {
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
val entry = catalog.fetch(catalog.STEAM_SEED_URL)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
?: return "catalog unreachable"
return catalog.install(this, entry, progressFor(PROTON_LINES, entry.size / 1_000_000))
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
SessionState.installCancellation = cancellation
return try {
val entry = catalog.fetch(catalog.STEAM_SEED_URL, cancellation)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
?: return if (cancellation.asBoolean) "cancelled" else "catalog unreachable"
catalog.install(this, entry, cancellation, progressFor(PROTON_LINES, entry.size / 1_000_000))
} finally {
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
}
}
override fun surfaceCreated(holder: SurfaceHolder) {
@@ -2192,9 +2230,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (line.contains(FEX_MISSING)) fexMissing = true
}
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
val launchFailure = com.droiddeck.launcher.session.SessionLaunchFailure.find(text.lineSequence())
if (steamSetup != null) {
val message = getString(if (steamSetup.download) R.string.session_end_steam_download else R.string.session_end_steam_setup)
EndHint(listOfNotNull(message, steamSetup.curlError).joinToString("\n"))
} else if (launchFailure == com.droiddeck.launcher.session.SessionLaunchFailure.STEAM_ILLEGAL_INSTRUCTION) {
val message = getString(R.string.session_end_steam_sigill)
val fallback = if (SessionState.steamClientArch == "arm64") getString(R.string.session_end_steam_try_x64) else null
EndHint(listOfNotNull(message, fallback).joinToString("\n"))
} else if (launchFailure == com.droiddeck.launcher.session.SessionLaunchFailure.VULKAN_DEVICE_MISSING) {
val adreno = com.droiddeck.launcher.gpu.GpuInfo.detect().family != com.droiddeck.launcher.gpu.GpuInfo.Family.NOT_ADRENO
EndHint(getString(if (adreno) R.string.session_end_vulkan_device else R.string.session_end_gpu_unsupported))
} else if (fexMissing) {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
@@ -3106,10 +3152,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
// The frozen game cannot draw again, so the paused overlay shows a copy taken while the surface still holds its frame.
private fun capturePausedFrame() {
private fun capturePausedFrame(manual: Boolean = false) {
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive) return
if (SessionState.suspended && pausedFrame != null) return
if (suspendPolicy == SessionPrefs.SUSPEND_NEVER || !::surfaceView.isInitialized) return
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return
if (surfaceView.holder.surface?.isValid != true) return
val width = surfaceView.width
val height = surfaceView.height
@@ -3141,6 +3187,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private fun pauseNow() {
if (!SessionState.running || SessionState.suspended) return
pauseAnimated = true
drawerOpen = false
pausedFrame = null
capturePausedFrame(manual = true)
SessionService.pause(this)
}
// Sessions that froze from picture-in-picture, or before onPause could copy a frame, have none; the
// compositor shows the frozen frame again once its output is back, so copy it from there.
private fun requestPausedFrame() {
@@ -3852,6 +3907,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private const val PAUSED_FRAME_REDRAW_MS = 150L
private const val TAG = "SessionActivity"
private var startedScreens = 0
@Volatile private var activeInstallWorker: Any? = null
private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need"
private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION
private const val CURSOR_PAD_HOLD_MS = 1200L
@@ -29,6 +29,11 @@ import java.util.Locale
object DeviceReport {
private const val TAG = "DeviceReport"
internal fun cpuFeaturesSummary(cpuInfo: String): String = cpuInfo.lineSequence()
.filter { it.substringBefore(':').trim() == "Features" }
.map { it.substringAfter(':').trim().split(Regex("\\s+")).filter(String::isNotEmpty).joinToString(" ") }
.filter(String::isNotEmpty).distinct().joinToString(" | ").ifEmpty { "not reported" }
fun write(context: Context, target: File, mode: String) {
try {
target.writeText(build(context, mode))
@@ -141,6 +146,7 @@ object DeviceReport {
h("CPU and memory")
k("Cores", CpuCores.all.size)
k("CPU features", cpuFeaturesSummary(FileUtils.readString(File("/proc/cpuinfo")).orEmpty()))
b.append("Core ceilings ")
b.append(CpuCores.all.joinToString(", ") { c ->
"cpu$c " + (CpuCores.maxGhz(c)?.let { String.format(Locale.US, "%.2f GHz", it) } ?: "?")
@@ -16,20 +16,83 @@ import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public final class Downloader {
private static final String TAG = "Downloader";
private static final int CONNECT_TIMEOUT_MS = 10_000;
private static final int STALL_TIMEOUT_MS = 15_000;
private static final int HTTP_RANGE_NOT_SATISFIABLE = 416;
private static final java.util.concurrent.ExecutorService CANCEL_EXECUTOR =
java.util.concurrent.Executors.newCachedThreadPool(r -> {
Thread thread = new Thread(r, "download-cancel");
thread.setDaemon(true);
return thread;
});
private Downloader() {}
public static final class Cancellation implements java.util.function.BooleanSupplier {
private final AtomicBoolean cancelled = new AtomicBoolean();
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
private final AtomicReference<InputStream> input = new AtomicReference<>();
private final java.util.function.BooleanSupplier external;
public Cancellation() { this(null); }
public Cancellation(java.util.function.BooleanSupplier external) { this.external = external; }
public void cancel() {
cancelled.set(true);
HttpURLConnection active = connection.get();
if (active != null) disconnectAsync(active);
InputStream activeInput = input.get();
if (activeInput != null) closeAsync(activeInput);
}
private static void disconnectAsync(HttpURLConnection active) {
CANCEL_EXECUTOR.execute(() -> {
try { active.disconnect(); } catch (RuntimeException ignored) { }
});
}
private static void closeAsync(InputStream active) {
CANCEL_EXECUTOR.execute(() -> {
try { active.close(); } catch (IOException ignored) { }
});
}
@Override public boolean getAsBoolean() {
return cancelled.get() || (external != null && external.getAsBoolean());
}
private void attach(HttpURLConnection active) {
connection.set(active);
if (getAsBoolean()) disconnectAsync(active);
}
private void detach(HttpURLConnection active) { connection.compareAndSet(active, null); }
private void attach(InputStream active) {
input.set(active);
if (getAsBoolean()) closeAsync(active);
}
private void detach(InputStream active) { input.compareAndSet(active, null); }
}
public static String downloadString(String url) {
return downloadString(url, null);
}
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
List<String> sources = DownloadSource.INSTANCE.candidates(url);
for (int i = 0; i < sources.size(); i++) {
if (isCancelled(cancelled)) return null;
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
Fetch fetch = fetch(sources.get(i));
Fetch fetch = fetch(sources.get(i), cancelled);
// A cancelled fetch says nothing about the source, so it must not count as a failure.
if (isCancelled(cancelled)) return null;
if (fetch.body != null) {
DownloadSource.INSTANCE.succeeded(sources.get(i));
return fetch.body;
@@ -53,30 +116,52 @@ public final class Downloader {
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
java.util.function.Consumer<Float> progress) {
return downloadFile(url, destination, resume, expectedSha256, null, progress);
}
/** {@code cancelled} is polled while bytes arrive; a cancel stops at once and leaves the partial file for the caller. */
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}"))
throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters");
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, progress);
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress);
}
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
static List<String> sources(String url, String expectedSha256) {
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
}
// Package-private for the local multi-source HTTP test.
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
String expectedSha256, java.util.function.Consumer<Float> progress) {
return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress);
}
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
String expectedSha256, java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
Identity identity = loadIdentity(destination, resume, expectedSha256);
for (int i = 0; i < sources.size(); i++) {
String source = sources.get(i);
if (isCancelled(cancelled)) return false;
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, progress);
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress);
// A cancel is not a source failure: no other mirror, and no DownloadSource.failed().
if (outcome == Outcome.CANCELLED) return false;
if (outcome == Outcome.DONE) {
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) {
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
if (!discardPartial(destination, identity)) return false;
continue;
if (expectedSha256 != null) {
String actualSha256 = Hashes.sha256(destination);
if (isCancelled(cancelled)) return false;
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
if (!discardPartial(destination, identity)) return false;
continue;
}
}
if (isCancelled(cancelled)) return false;
resumeFile(destination).delete();
DownloadSource.INSTANCE.succeeded(source);
if (progress != null) progress.accept(1f);
@@ -88,7 +173,11 @@ public final class Downloader {
return false;
}
private enum Outcome { DONE, RETRY, FATAL }
private enum Outcome { DONE, RETRY, FATAL, CANCELLED }
private static boolean isCancelled(java.util.function.BooleanSupplier cancelled) {
return cancelled != null && cancelled.getAsBoolean();
}
private static final class Identity {
private String source;
@@ -156,7 +245,9 @@ public final class Downloader {
}
private static Outcome attempt(String url, File destination, boolean resume, Identity identity,
String expectedSha256, java.util.function.Consumer<Float> progress) {
String expectedSha256, java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
if (isCancelled(cancelled)) return Outcome.CANCELLED;
HttpURLConnection connection = null;
long have = resume && destination.isFile() ? destination.length() : 0;
try {
@@ -166,6 +257,7 @@ public final class Downloader {
have = 0;
}
connection = open(url, STALL_TIMEOUT_MS);
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(connection);
if (have > 0) {
connection.setRequestProperty("Range", "bytes=" + have + "-");
connection.setRequestProperty("If-Range", identity.etag);
@@ -174,7 +266,7 @@ public final class Downloader {
if (have > 0 && code == HTTP_RANGE_NOT_SATISFIABLE) {
connection.disconnect();
if (!discardPartial(destination, identity)) return Outcome.RETRY;
return attempt(url, destination, false, identity, expectedSha256, progress);
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
@@ -185,13 +277,13 @@ public final class Downloader {
if (appending && !rangeStartsAt(connection.getHeaderField("Content-Range"), have)) {
connection.disconnect();
if (!discardPartial(destination, identity)) return Outcome.RETRY;
return attempt(url, destination, false, identity, expectedSha256, progress);
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
String etag = connection.getHeaderField("ETag");
if (have > 0 && appending && (!strongETag(etag) || !etag.equals(identity.etag))) {
connection.disconnect();
if (!discardPartial(destination, identity)) return Outcome.RETRY;
return attempt(url, destination, false, identity, expectedSha256, progress);
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
if (!appending && have > 0) {
// If-Range may legitimately return full 200 when representation changed.
@@ -208,26 +300,36 @@ public final class Downloader {
identity.etag = strongETag(etag) ? etag : null;
saveIdentity(destination, identity, expectedSha256);
long written = have;
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
InputStream input = connection.getInputStream();
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(input);
try (InputStream in = new BufferedInputStream(input, 1 << 16);
OutputStream out = new FileOutputStream(destination, appending)) {
byte[] buffer = new byte[1 << 16];
long lastReport = 0;
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
out.write(buffer, 0, read);
written += read;
if (isCancelled(cancelled)) return Outcome.CANCELLED;
if (progress != null && written - lastReport > (1 << 20)) {
lastReport = written;
progress.accept(total > 0 ? written / (float) total : -1f);
}
}
} finally {
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
}
if (isCancelled(cancelled)) return Outcome.CANCELLED;
if (total > 0 && written < total) return Outcome.RETRY;
return Outcome.DONE;
} catch (Exception e) {
if (isCancelled(cancelled)) return Outcome.CANCELLED;
Log.w(TAG, "download " + url, e);
return Outcome.RETRY;
} finally {
if (connection != null) connection.disconnect();
if (connection != null) {
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(connection);
connection.disconnect();
}
}
}
@@ -256,9 +358,15 @@ public final class Downloader {
}
private static Fetch fetch(String url) {
return fetch(url, null);
}
private static Fetch fetch(String url, java.util.function.BooleanSupplier cancelled) {
HttpURLConnection connection = null;
Cancellation token = cancelled instanceof Cancellation ? (Cancellation) cancelled : null;
try {
connection = open(url, STALL_TIMEOUT_MS);
if (token != null) token.attach(connection);
int code = connection.getResponseCode();
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
@@ -270,10 +378,14 @@ public final class Downloader {
return new Fetch(new String(out.toByteArray(), StandardCharsets.UTF_8), false);
}
} catch (Exception e) {
if (isCancelled(cancelled)) return new Fetch(null, false);
Log.w(TAG, "GET " + url, e);
return new Fetch(null, false);
} finally {
if (connection != null) connection.disconnect();
if (connection != null) {
if (token != null) token.detach(connection);
connection.disconnect();
}
}
}
@@ -1,21 +1,59 @@
package com.droiddeck.launcher.core
object LogRedactor {
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
private val HIDL_SHARED_LIBRARY = Regex(
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
)
private val hidlMatcher = object : ThreadLocal<java.util.regex.Matcher>() {
override fun initialValue(): java.util.regex.Matcher = HIDL_SHARED_LIBRARY.toPattern().matcher("")
internal const val MAX_LINE_LENGTH = 64 * 1024
internal const val OVERSIZED_LINE = "<oversized log line withheld>"
private data class MatcherKey(val pattern: String, val options: Set<RegexOption>)
private class MatcherCache : LinkedHashMap<MatcherKey, java.util.regex.Matcher>(32, 0.75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<MatcherKey, java.util.regex.Matcher>?): Boolean =
size > 32
}
private fun isHidlLoaderDiagnostic(input: String, match: MatchResult): Boolean {
val matcher = hidlMatcher.get()!!
val isLibrary = try { matcher.reset(match.value).matches() } finally { matcher.reset("") }
if (!isLibrary) return false
val start = match.range.first
val end = match.range.last + 1
// Android matchers own native state, so reuse them instead of creating one for every log line.
private val matchers = object : ThreadLocal<MatcherCache>() {
override fun initialValue(): MatcherCache = MatcherCache()
}
private fun <T> withMatcher(
regex: Regex,
input: CharSequence,
action: (java.util.regex.Matcher) -> T,
): T {
val key = MatcherKey(regex.pattern, regex.options)
val matcher = matchers.get()!!.getOrPut(key) { regex.toPattern().matcher("") }
return try {
action(matcher.reset(input))
} finally {
matcher.reset("")
}
}
private fun replaceMatches(input: String, regex: Regex, replacement: String): String =
replaceMatches(input, regex) { replacement }
private fun replaceMatches(
input: String,
regex: Regex,
replacement: (java.util.regex.Matcher) -> String,
): String = withMatcher(regex, input) { matcher ->
if (!matcher.find()) return@withMatcher input
val out = StringBuffer(input.length)
do {
matcher.appendReplacement(out, java.util.regex.Matcher.quoteReplacement(replacement(matcher)))
} while (matcher.find())
matcher.appendTail(out)
out.toString()
}
private fun matchesEntire(input: String, regex: Regex): Boolean =
withMatcher(regex, input) { it.matches() }
private fun isHidlLoaderDiagnostic(input: String, match: java.util.regex.Matcher): Boolean {
if (!matchesEntire(match.group(), HIDL_SHARED_LIBRARY)) return false
val start = match.start()
val end = match.end()
val prefix = "library \""
val suffix = "\" not found"
val earliestQuote = (start - 4096).coerceAtLeast(0)
@@ -39,6 +77,12 @@ object LogRedactor {
(suffixEnd == input.length || !(input[suffixEnd].isLetterOrDigit() || input[suffixEnd] == '_'))
}
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
private val HIDL_SHARED_LIBRARY = Regex(
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
)
private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})")
private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}")
private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b")
@@ -111,6 +155,7 @@ object LogRedactor {
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
)
matchers.remove()
}
@Volatile
@@ -178,8 +223,8 @@ object LogRedactor {
}
fun describeAddresses(text: String): String {
var out = IPV6.replace(text) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
out = IPV4.replace(out) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
var out = replaceMatches(text, IPV6) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
out = replaceMatches(out, IPV4) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
return out
}
@@ -204,23 +249,28 @@ object LogRedactor {
"(?<![\\d.])(?:10\\.\\d{1,3}|192\\.168|172\\.(?:1[6-9]|2\\d|3[01])|169\\.254)\\.\\d{1,3}\\.\\d{1,3}(?!\\.?\\d)"
)
fun scrubTo(src: java.io.File, out: java.io.Writer) {
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
}
fun scrubTo(
src: java.io.File,
out: java.io.Writer,
shouldStop: () -> Boolean = { false },
): Boolean = scrubLines(src, out, ::redact, shouldStop)
fun redactForShare(line: String): String {
if (line.isEmpty()) return line
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
return try {
val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
LAN_IPV4.replace(out, "<lan-address>")
replaceMatches(out, LAN_IPV4, "<lan-address>")
} catch (t: Throwable) {
"<redaction failed; line withheld>"
}
}
private const val SHARE_LINE_MAX = 64 * 1024
fun scrubForShare(src: java.io.File, out: java.io.Writer) {
fun scrubForShare(
src: java.io.File,
out: java.io.Writer,
shouldStop: () -> Boolean = { false },
): Boolean {
src.inputStream().buffered().use { input ->
input.mark(2)
val first = input.read()
@@ -228,27 +278,30 @@ object LogRedactor {
input.reset()
if ((first == 0xff && second == 0xfe) || (first == 0xfe && second == 0xff)) {
out.write("<unsupported encoding; file withheld>\n")
return
return true
}
val decoder = Charsets.UTF_8.newDecoder()
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
java.io.InputStreamReader(input, decoder).use { reader ->
val buffer = CharArray(8192)
val line = StringBuilder()
var withheld = false
val line = StringBuilder(4096)
var withheld: String? = null
var afterCr = false
fun emit() {
out.write(if (withheld) "<unsupported or oversized line withheld>" else redactForShare(line.toString()))
out.write(withheld ?: redactForShare(line.toString()))
out.write("\n")
line.setLength(0)
withheld = false
withheld = null
}
try {
while (true) {
if (shouldStop()) return false
val size = reader.read(buffer)
if (size < 0) break
if (shouldStop()) return false
for (i in 0 until size) {
if (shouldStop()) return false
val ch = buffer[i]
if (afterCr) {
afterCr = false
@@ -257,23 +310,79 @@ object LogRedactor {
if (ch == '\r' || ch == '\n') {
emit()
afterCr = ch == '\r'
} else if (!withheld) {
// Splitting a line can separate a credential from its label.
if (ch == '\u0000' || line.length == SHARE_LINE_MAX) {
withheld = true
} else if (withheld == null) {
if (ch == '\u0000' || line.length == MAX_LINE_LENGTH) {
withheld = if (ch == '\u0000') "<unsupported or oversized line withheld>" else OVERSIZED_LINE
line.setLength(0)
} else {
line.append(ch)
}
} else line.append(ch)
}
}
}
if (withheld || line.isNotEmpty()) emit()
if (withheld != null || line.isNotEmpty()) emit()
} catch (_: java.nio.charset.CharacterCodingException) {
out.write("<unsupported encoding; file withheld>\n")
}
}
}
return true
}
private fun scrubLines(
src: java.io.File,
out: java.io.Writer,
scrub: (String) -> String,
shouldStop: () -> Boolean,
): Boolean {
src.bufferedReader().use { input ->
val chunk = CharArray(8192)
val line = StringBuilder(4096)
var oversized = false
var pendingContent = false
var pendingCarriageReturn = false
fun emit() {
out.write(if (oversized) OVERSIZED_LINE else scrub(line.toString()))
out.write("\n")
line.setLength(0)
oversized = false
pendingContent = false
}
while (true) {
if (shouldStop()) return false
val count = input.read(chunk)
if (count < 0) break
if (shouldStop()) return false
for (i in 0 until count) {
val char = chunk[i]
if (pendingCarriageReturn) {
emit()
pendingCarriageReturn = false
if (char == '\n') continue
}
when (char) {
'\r' -> pendingCarriageReturn = true
'\n' -> emit()
else -> {
pendingContent = true
if (!oversized) {
if (line.length < MAX_LINE_LENGTH) line.append(char)
else {
line.setLength(0)
oversized = true
}
}
}
}
}
}
if (pendingCarriageReturn || pendingContent) {
if (shouldStop()) return false
emit()
}
}
return true
}
private fun quoted(value: String): String {
@@ -315,45 +424,51 @@ object LogRedactor {
fun redact(line: String): String {
if (line.isEmpty()) return line
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
return try {
val out = Line(line)
if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}<redacted:mac>" })
if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, "<redacted:mac>"))
if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) {
val value = it.groupValues[2]
if (out.has("mac")) out.set(replaceMatches(out.text, MAC_FIELD) { "${it.group(1)}<redacted:mac>" })
if (out.holds(':', 5) || out.holds('-', 5)) out.set(replaceMatches(out.text, MAC, "<redacted:mac>"))
if (out.has("serial", "android")) out.set(replaceMatches(out.text, DEVICE_IDENTIFIER) {
val value = it.group(2)
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
"${it.groupValues[1]}${quote}<redacted:serial>${quote}"
"${it.group(1)}${quote}<redacted:serial>${quote}"
})
if (out.holds('-', 4)) out.set(GUID.replace(out.text, "<redacted:guid>"))
if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}<redacted:jwt>" })
if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "<redacted:jwt>"))
if (out.holds('-', 4)) out.set(replaceMatches(out.text, GUID, "<redacted:guid>"))
if (out.has("jwt")) out.set(replaceMatches(out.text, JWT_LABELLED) { "${it.group(1)}<redacted:jwt>" })
if ("ey" in out.text) out.set(replaceMatches(out.text, JWT_BASE64, "<redacted:jwt>"))
if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) {
out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>${it.groupValues[2]}" })
out.set(replaceMatches(out.text, SECRET_KV) {
val quote = it.group(2).orEmpty()
"${it.group(1)}${quote}<redacted:token>${quote}"
})
}
if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}<redacted:code>" })
if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "<redacted:key>"))
if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" })
if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m ->
val id = m.groupValues[1]
if (out.has("guard", "factor", "2fa")) out.set(replaceMatches(out.text, GUARD_CODE) { "${it.group(1)}<redacted:code>" })
if (out.hasRun(32, ::isHex)) out.set(replaceMatches(out.text, WEBAPI_KEY, "<redacted:key>"))
if ("76561" in out.text) out.set(replaceMatches(out.text, STEAMID64) { "${it.group(1)}********${it.group(3)}" })
if ("[U:1:" in out.text) out.set(replaceMatches(out.text, STEAMID3) { m ->
val id = m.group(1)
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
})
if (out.has("external")) out.set(EXTERNAL_ADDR.replace(out.text) { "${it.groupValues[1]}<redacted:ip>" })
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:ip>"))
if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
if (out.has("external")) out.set(replaceMatches(out.text, EXTERNAL_ADDR) { "${it.group(1)}<redacted:ip>" })
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:ip>"))
if (out.has("onloginstatechange")) out.set(replaceMatches(out.text, LOGIN_STATE) { "${it.group(1)}<redacted:account>" })
if ("OnLoginUsersChanged " in out.text) out.set(replaceMatches(out.text, LOGIN_USERS) { "${it.group(1)}<redacted:account>" })
if (out.has("account", "user")) {
out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
out.set(replaceMatches(out.text, ACCOUNT_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
}
if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:account>"))
if ('@' in out.text) out.set(EMAIL.replace(out.text) { m ->
m.value.takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
if (out.has("login")) out.set(replaceMatches(out.text, LOGIN_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:account>"))
if ('@' in out.text) out.set(replaceMatches(out.text, EMAIL) { m ->
m.group().takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
})
if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) {
out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=<redacted:token>" })
out.set(replaceMatches(out.text, RESIDUAL) { "${it.group(1)}=<redacted:token>" })
}
if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) {
out.set(LONG_TOKEN.replace(out.text, "<redacted:token>"))
out.set(replaceMatches(out.text, LONG_TOKEN, "<redacted:token>"))
}
out.text
} catch (t: Throwable) {
@@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@@ -47,10 +48,16 @@ public final class TurnipDriver {
private final Context context;
private final File contentDir;
private final Supplier<GpuInfo> gpuDetector;
public TurnipDriver(Context context) {
this(context, GpuInfo.Companion::detect);
}
TurnipDriver(Context context, Supplier<GpuInfo> gpuDetector) {
this.context = context;
this.contentDir = new File(context.getFilesDir(), "graphics_driver");
this.gpuDetector = gpuDetector;
}
public String driverPath(String driverId) {
@@ -284,7 +291,12 @@ public final class TurnipDriver {
}
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
if (quest != null) return quest;
int model = GpuInfo.Companion.detect().getModel();
GpuInfo gpu = gpuDetector.get();
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO) {
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
return null;
}
int model = gpu.getModel();
Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model));
return chooseByModel(model, android.os.Build.VERSION.SDK_INT);
}
@@ -22,8 +22,8 @@ object DesktopCatalog {
val icon: String, val category: String,
)
fun fetch(url: String = CATALOG_URL): List<Entry>? {
val body = Downloader.downloadString(url) ?: return null
fun fetch(url: String = CATALOG_URL, cancelled: java.util.function.BooleanSupplier? = null): List<Entry>? {
val body = Downloader.downloadString(url, cancelled) ?: return null
return try {
val json = JSONObject(body)
val arr = json.getJSONArray("packages")
@@ -71,9 +71,22 @@ object DesktopCatalog {
}
fun resumeInterrupted(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
resumeInterrupted(context, null, listener)
}
fun resumeInterrupted(
context: Context,
cancelled: Downloader.Cancellation?,
listener: LinuxRuntimeInstaller.ProgressListener?,
): String? = synchronized(installLock) {
for (entry in interrupted(context)) {
Log.w(TAG, "finishing the interrupted install of ${entry.id} ${entry.version}")
install(context, entry, listener)?.let { return it }
val problem = if (cancelled == null) {
install(context, entry, listener)
} else {
install(context, entry, cancelled, listener)
}
if (problem != null) return problem
}
null
}
@@ -144,10 +157,16 @@ object DesktopCatalog {
}
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
installLocked(context, entry, listener)
installLocked(context, entry, null, listener)
}
private fun installLocked(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
fun install(context: Context, entry: Entry, cancelled: Downloader.Cancellation,
listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
installLocked(context, entry, cancelled, listener)
}
private fun installLocked(context: Context, entry: Entry, cancelled: Downloader.Cancellation?,
listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val root = LinuxRuntime.rootDir(context)
if (!root.isDirectory) return context.getString(R.string.deskpkg_runtime_missing)
if (entry.sha256.isEmpty()) return context.getString(R.string.deskpkg_no_checksum, entry.name)
@@ -166,14 +185,20 @@ object DesktopCatalog {
if (!downloaded(download, entry)) {
val downloading = context.getString(R.string.user_apps_downloading, entry.name)
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, 0)
val ok = Downloader.downloadFile(entry.url, download, true, entry.sha256) { f ->
val progress = java.util.function.Consumer<Float> { f ->
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, if (f < 0) -1 else Math.round(f * 100f))
}
if (!ok) return context.getString(R.string.user_apps_download_failed)
val ok = if (cancelled == null) {
Downloader.downloadFile(entry.url, download, true, entry.sha256, progress)
} else {
Downloader.downloadFile(entry.url, download, true, entry.sha256, cancelled, progress)
}
if (!ok || cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
report.onProgress(LinuxRuntimeInstaller.Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1)
val actual = Hashes.sha256(download)
if (!entry.sha256.equals(actual, ignoreCase = true)) return context.getString(R.string.deskpkg_checksum_mismatch)
}
if (cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
report.onProgress(context.getString(R.string.deskpkg_installing, entry.name), -1)
when (entry.kind) {
"appimage" -> {
@@ -1,7 +1,9 @@
package com.droiddeck.launcher.runtime
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
@@ -34,6 +36,9 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
private val observer = object : ContentObserver(handler) {
override fun onChange(selfChange: Boolean) { if (running) publish() }
}
private val volumeSteps = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { if (running) publishVolume() }
}
private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) {
override fun onEvent(event: Int, path: String?) {
if (path in REQUESTS) handler.post { if (running) consume() }
@@ -50,13 +55,22 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
}
}
fun publish(force: Boolean = false) {
private fun publishVolume() {
try {
directory.mkdirs()
val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1)
val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC)
write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n")
} catch (e: Exception) {
Log.w(TAG, "Could not publish Android volume", e)
}
}
fun publish(force: Boolean = false) {
publishVolume()
try {
directory.mkdirs()
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
write("backlight/droiddeck/brightness", "$value\n")
write("backlight/droiddeck/actual_brightness", "$value\n")
@@ -81,6 +95,10 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
permissionNotified = false
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
requests.startWatching()
context.registerReceiver(volumeSteps, IntentFilter().apply {
addAction(VOLUME_CHANGED_ACTION)
addAction(STREAM_MUTE_CHANGED_ACTION)
}, null, handler)
refresh.run()
}
}
@@ -90,6 +108,7 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
running = false
handler.removeCallbacks(refresh)
requests.stopWatching()
try { context.unregisterReceiver(volumeSteps) } catch (e: IllegalArgumentException) { }
context.contentResolver.unregisterContentObserver(observer)
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
}
@@ -170,6 +189,9 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
companion object {
private const val TAG = "DeviceControls"
// AudioService sends these on every stream step; the Settings observer and 250 ms poll lag a held volume key.
private const val VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION"
private const val STREAM_MUTE_CHANGED_ACTION = "android.media.STREAM_MUTE_CHANGED_ACTION"
private const val PERMISSION_CHANNEL = "brightness_permission"
private const val PERMISSION_NOTIFICATION = 0x4442
private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request")
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.Build
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
@@ -37,9 +38,10 @@ object ProotFastPath {
fun hostEnv(key: String): Pair<String, String> = "PROOT_FASTPATH" to key
fun guestEnv(root: File, binds: List<String>, key: String): List<String> = listOf(
fun guestEnv(root: File, binds: List<String>, key: String, sdk: Int = Build.VERSION.SDK_INT): List<String> = listOf(
"PROOT_FP_ROOT=" + root.path,
"PROOT_FP_BINDS=" + binds.joinToString("|"),
"PROOT_FP_KEY=$key",
"PROOT_FP_ANDROID_API=$sdk",
)
}
@@ -13,6 +13,7 @@ object GameEnvironmentStore {
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
const val DXVK_CONFIG = "dxvkConfig"
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
const val GAME_DEBUG_LOGS = "gameDebugLogs"
@Synchronized
fun read(context: Context): GameEnvironment.Config {
@@ -87,7 +88,11 @@ object GameEnvironmentStore {
}
@Synchronized
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
fun publish(
context: Context,
config: GameEnvironment.Config = read(context),
gameDebugLogsOverride: Boolean? = null,
) {
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
val json = encode(resolved)
val dxvk = TextureFiltering.dxvkOptions(
@@ -110,6 +115,11 @@ object GameEnvironmentStore {
)
}
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
json.put(
GAME_DEBUG_LOGS,
gameDebugLogsOverride ?: (SessionPrefs.logsEnabled(context) &&
SessionPrefs.gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context)),
)
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
}
@@ -7,6 +7,9 @@ import com.droiddeck.launcher.core.SessionLogCapture
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.io.Writer
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -16,6 +19,9 @@ object SessionArtifacts {
const val COMPLETE_MARKER = ".complete"
private const val RECOVERY_RUNTIME_CAPTURED_MARKER = ".recovery-runtime-captured"
private const val RECOVERY_RUNTIME_EXPIRED_MARKER = ".recovery-runtime-expired"
private val SCRUBBED_MARKER = ".scrubbed-r${LogRedactor.RULES_VERSION}"
private val OLD_SCRUBBED_MARKER = Regex("""\.scrubbed-(r?\d+)""")
@@ -72,9 +78,9 @@ object SessionArtifacts {
copySteamLogs(context, dir, record, steamArch)
VacDiagnostics.collect(context, dir)
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
markScrubbed(scrubTree(record))
val scrubbed = markScrubbed(scrubTree(record))
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
if (scrubbed) File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
} catch (e: Exception) {
Log.w(TAG, "collecting session artifacts", e)
}
@@ -88,15 +94,10 @@ object SessionArtifacts {
}?.toList() ?: return
if (dirs.isEmpty()) return
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val workers = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4)
val pool = java.util.concurrent.Executors.newFixedThreadPool(workers) { r ->
Thread({ android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); r.run() }, "scrub-logs")
}
val done = try {
pool.invokeAll(dirs.map { dir -> java.util.concurrent.Callable { scrubAndMark(dir) } })
.count { f -> try { f.get() } catch (e: Exception) { false } }
} finally {
pool.shutdown()
var done = 0
for (dir in dirs) {
if (SessionState.running) break
if (scrubAndMark(dir, stopWhenSessionStarts = true)) done++
}
val failed = dirs.size - done
Log.i(TAG, "logs: scrubbed $done folders under r${LogRedactor.RULES_VERSION}" +
@@ -114,35 +115,121 @@ object SessionArtifacts {
private class Record(val dir: File) {
val files = HashMap<File, Scrubbed>()
var failed = false
var deferred = false
}
private fun scrubFolder(dir: File, record: Record) {
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f ->
if (LogRedactor.isBinary(f)) return@forEach
// Too large to rewrite in memory: the folder must not be recorded as scrubbed.
if (!LogRedactor.isText(f)) { record.failed = true; return@forEach }
val done = scrubFile(dir, f)
if (done == null) record.failed = true else record.files[f] = done
private sealed class ScrubResult {
class Done(val scrubbed: Scrubbed) : ScrubResult()
object Failed : ScrubResult()
object Deferred : ScrubResult()
}
private fun scrubFolder(
dir: File,
record: Record,
shouldStop: () -> Boolean,
beforeReplace: (File) -> Unit,
listFiles: (File) -> Array<File>?,
): Boolean {
val files = listFiles(dir)?.filter { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }
if (files == null) {
record.failed = true
return true
}
for (f in files) {
if (shouldStop()) return false
if (LogRedactor.isBinary(f)) continue
when (val result = scrubFile(dir, f, shouldStop, beforeReplace)) {
is ScrubResult.Done -> record.files[f] = result.scrubbed
ScrubResult.Failed -> record.failed = true
ScrubResult.Deferred -> {
record.failed = true
record.deferred = true
return false
}
}
}
return true
}
private fun scrubFile(dir: File, f: File): Scrubbed? {
private fun scrubFile(
dir: File,
f: File,
shouldStop: () -> Boolean,
beforeReplace: (File) -> Unit,
): ScrubResult {
val tmp = File(dir, ".${f.name}.scrub")
return try {
val before = Scrubbed(f.length(), f.lastModified())
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
val scrubbed = tmp.readBytes()
if (scrubbed.contentEquals(f.readBytes())) {
val scrubbed = tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w, shouldStop) }
if (!scrubbed) {
tmp.delete()
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
} else {
if (!tmp.renameTo(f)) { f.writeBytes(scrubbed); tmp.delete() }
Scrubbed(scrubbed.size.toLong(), f.lastModified()).takeIf { f.length() == it.length }
return ScrubResult.Deferred
}
val scrubbedLength = tmp.length()
when (sameContents(tmp, f, shouldStop)) {
null -> {
tmp.delete()
ScrubResult.Deferred
}
true -> {
tmp.delete()
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed
}
false -> {
if (shouldStop()) {
tmp.delete()
return ScrubResult.Deferred
}
beforeReplace(f)
if (f.length() != before.length || f.lastModified() != before.modified) {
tmp.delete()
return ScrubResult.Failed
}
if (!tmp.renameTo(f)) {
tmp.delete()
return ScrubResult.Failed
}
Scrubbed(scrubbedLength, f.lastModified()).takeIf { f.length() == it.length }
?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed
}
}
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${f.name}", e)
tmp.delete()
null
ScrubResult.Failed
}
}
internal fun sameContents(a: File, b: File, shouldStop: () -> Boolean = { false }): Boolean? {
if (shouldStop()) return null
if (a.length() != b.length()) return false
fun readChunk(input: java.io.InputStream, buffer: ByteArray): Int? {
var count = 0
while (count < buffer.size) {
if (shouldStop()) return null
val read = input.read(buffer, count, buffer.size - count)
if (shouldStop()) return null
if (read < 0) break
if (read == 0) continue
count += read
}
return count
}
return a.inputStream().buffered().use { left ->
b.inputStream().buffered().use { right ->
val leftBuffer = ByteArray(64 * 1024)
val rightBuffer = ByteArray(64 * 1024)
while (true) {
val leftCount = readChunk(left, leftBuffer) ?: return null
val rightCount = readChunk(right, rightBuffer) ?: return null
if (leftCount != rightCount) return false
if (leftCount == 0) break
if (shouldStop()) return null
for (i in 0 until leftCount) if (leftBuffer[i] != rightBuffer[i]) return false
}
true
}
}
}
@@ -183,10 +270,44 @@ object SessionArtifacts {
}.toSet()
}
internal fun scrubAndMark(dir: File): Boolean = markScrubbed(scrubTree(Record(dir)))
internal fun scrubAndMark(
dir: File,
stopWhenSessionStarts: Boolean = false,
beforeReplace: (File) -> Unit = {},
listFiles: (File) -> Array<File>? = { it.listFiles() },
sessionStarted: () -> Boolean = { SessionState.running },
): Boolean {
val shouldStop = { stopWhenSessionStarts && sessionStarted() }
val record = scrubTree(
Record(dir),
listFiles = listFiles,
beforeReplace = beforeReplace,
shouldStop = shouldStop,
)
if (shouldStop()) {
record.failed = true
record.deferred = true
}
return markScrubbed(record)
}
private fun scrubTree(record: Record): Record {
record.dir.walkTopDown().filter { it.isDirectory }.forEach { scrubFolder(it, record) }
private fun scrubTree(
record: Record,
listFiles: (File) -> Array<File>? = { it.listFiles() },
beforeReplace: (File) -> Unit = {},
shouldStop: () -> Boolean = { false },
): Record {
for (dir in record.dir.walkTopDown().filter { it.isDirectory }) {
if (shouldStop() || !scrubFolder(dir, record, shouldStop, beforeReplace, listFiles)) {
record.failed = true
record.deferred = true
break
}
}
if (shouldStop()) {
record.failed = true
record.deferred = true
}
return record
}
@@ -205,6 +326,7 @@ object SessionArtifacts {
private const val HEAD = 4096L
private class Mark(val size: Long, val head: String)
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
fun markSteamLogs(dir: File, logs: File) {
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
@@ -240,23 +362,54 @@ object SessionArtifacts {
.firstOrNull { m -> heads.getOrPut(minOf(m.size, HEAD)) { head(src, m.size) } == m.head }?.size ?: 0L
}
private fun copySteamLogs(context: Context, dir: File, record: Record, steamArch: String? = null) {
private fun copySteamLogs(
context: Context,
dir: File,
record: Record,
steamArch: String? = null,
stopWhenSessionStarts: Boolean = false,
) {
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
if (!logs.isDirectory) return
val out = File(dir, "steam").apply { mkdirs() }
copySessionLogs(logs, dir, out).forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
record.failed = record.failed || result.failed
record.deferred = record.deferred || result.deferred
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
internal fun copySessionLogs(logs: File, dir: File, out: File): List<File> {
internal fun copySessionLogs(
logs: File,
dir: File,
out: File,
openWriter: (File) -> Writer = { it.bufferedWriter() },
): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files
private fun copySessionLogsResult(
logs: File,
dir: File,
out: File,
openWriter: (File) -> Writer = { it.bufferedWriter() },
shouldStop: () -> Boolean,
): CopyResult {
val marks = steamLogMarks(dir)
val copied = ArrayList<File>()
logs.listFiles { f -> f.isFile }?.forEach { src ->
var failed = false
var deferred = false
val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false)
for (src in sources) {
if (shouldStop()) {
failed = true
deferred = true
break
}
val size = src.length()
val from = marks?.let { startOf(src, size, it) } ?: 0L
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) return@forEach
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) continue
val dst = File(out, src.name)
val staging = File(out, ".${src.name}.copy")
try {
val dst = File(out, src.name)
src.inputStream().buffered().use { input ->
var left = if (from > 0) from - 1 else 0L
while (left > 0) {
@@ -270,49 +423,183 @@ object SessionArtifacts {
if (c < 0 || c == '\n'.code) break
}
}
dst.bufferedWriter().use { w ->
input.bufferedReader().forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
val complete = openWriter(staging).use { w -> scrubSteamLog(input, w, shouldStop) }
if (!complete) {
staging.delete()
failed = true
deferred = true
}
}
copied.add(dst)
if (deferred) break
Files.move(
staging.toPath(),
dst.toPath(),
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING,
)
copied += dst
} catch (e: Exception) {
staging.delete()
Log.w(TAG, "could not scrub ${src.name}", e)
failed = true
}
}
return copied
return CopyResult(copied, failed, deferred)
}
private fun scrubSteamLog(
input: java.io.InputStream,
out: java.io.Writer,
shouldStop: () -> Boolean,
): Boolean {
input.reader().use { reader ->
val chunk = CharArray(8192)
val line = StringBuilder(4096)
var oversized = false
var pendingContent = false
var pendingCarriageReturn = false
fun emit() {
out.write(if (oversized) LogRedactor.OVERSIZED_LINE else LogRedactor.redact(line.toString()))
out.write("\n")
line.setLength(0)
oversized = false
pendingContent = false
}
while (true) {
if (shouldStop()) return false
val count = reader.read(chunk)
if (count < 0) break
if (shouldStop()) return false
for (i in 0 until count) {
if (shouldStop()) return false
val char = chunk[i]
if (pendingCarriageReturn) {
emit()
pendingCarriageReturn = false
if (char == '\n') continue
}
when (char) {
'\r' -> pendingCarriageReturn = true
'\n' -> emit()
else -> {
pendingContent = true
if (!oversized) {
if (line.length < LogRedactor.MAX_LINE_LENGTH) line.append(char)
else {
line.setLength(0)
oversized = true
}
}
}
}
}
}
if (pendingCarriageReturn || pendingContent) {
if (shouldStop()) return false
emit()
}
}
return true
}
@Synchronized
fun finishAbandoned(context: Context) {
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false) {
val stopWhenSessionStarts = !beforeGuestStart
val parent = LinuxRuntime.logDir(context)
val abandoned = parent.listFiles { f ->
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists() && !inFlight(f)
}?.sortedWith(SessionPaths.chronological) ?: return
if (abandoned.isEmpty()) return
val current = SessionPaths.current()
val latestPreviousSession = SessionPaths.sessionFolders(context).lastOrNull { it != current }
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
abandoned.forEachIndexed { i, dir ->
if (dir == current) return@forEachIndexed
val newest = i == abandoned.lastIndex
for (dir in abandoned) {
if (stopWhenSessionStarts && SessionState.running) break
if (dir == current) continue
if (beforeGuestStart && dir != latestPreviousSession) continue
val newest = dir == latestPreviousSession
try {
File(dir, "ended-without-teardown.txt").writeText(
"This session's process ended without running its own teardown - killed by\n" +
"Android, a native crash, or the device going down - so the files below were\n" +
"gathered when the app next started, at ${now()}.\n" +
"The logs written during the session (session.log, app.log, wayland.log,\n" +
"audio.log, device.txt) were on disk already and are as they were left.\n" +
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
)
val recoveryNote = File(dir, "ended-without-teardown.txt")
val runtimeCaptured = File(dir, RECOVERY_RUNTIME_CAPTURED_MARKER)
val runtimeExpired = File(dir, RECOVERY_RUNTIME_EXPIRED_MARKER)
val recoveryPreviouslyAttempted = recoveryNote.exists()
val recoveryAttempted = recoveryPreviouslyAttempted &&
(runtimeCaptured.exists() || runtimeExpired.exists() || !beforeGuestStart)
if (!recoveryAttempted) {
recoveryNote.writeText(
"This session's process ended without running its own teardown - killed by\n" +
"Android, a native crash, or the device going down - so the files below were\n" +
"gathered when the app next started, at ${now()}.\n" +
"The logs written during the session (session.log, app.log, wayland.log,\n" +
"audio.log, device.txt) were on disk already and are as they were left.\n" +
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
)
}
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() &&
(runtimeExpired.exists() || !beforeGuestStart) &&
!recoveryNote.readText().contains("runtime capture did not finish")) {
recoveryNote.appendText(
"Steam's logs and VAC evidence are not included: runtime capture did not finish " +
"before its evidence expired.\n"
)
}
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() && !beforeGuestStart) {
runtimeExpired.writeText("runtime evidence no longer belongs to this session, at ${now()}\n")
}
val record = Record(dir)
if (newest) {
copySteamLogs(context, dir, record, recordedClient(dir))
VacDiagnostics.collect(context, dir)
if (newest && !recoveryAttempted) {
copySteamLogs(
context,
dir,
record,
steamArch = recordedClient(dir),
stopWhenSessionStarts = stopWhenSessionStarts,
)
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
if (!record.failed && VacDiagnostics.collect(context, dir)) {
try {
runtimeCaptured.writeText("collected at ${now()}\n")
} catch (e: Exception) {
record.failed = true
if (beforeGuestStart) {
runtimeExpired.writeText("runtime capture marker failed, at ${now()}\n")
}
Log.w(TAG, "could not mark runtime capture for $dir", e)
}
} else {
record.failed = true
if (beforeGuestStart) {
runtimeExpired.writeText("runtime capture failed, at ${now()}\n")
}
}
}
}
if (record.deferred || stopWhenSessionStarts && SessionState.running) {
record.failed = true
record.deferred = true
markScrubbed(record)
break
}
val crashLog = File(dir, "crash.log")
if (!crashLog.exists()) {
SessionLogCapture.dumpCrashBuffer(crashLog)
}
if (stopWhenSessionStarts && SessionState.running) {
record.failed = true
record.deferred = true
markScrubbed(record)
break
}
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
markScrubbed(scrubTree(record))
if (beforeGuestStart) return
val scrubbed = scrubTree(record) { stopWhenSessionStarts && SessionState.running }
val marked = markScrubbed(scrubbed)
if (scrubbed.deferred) break
if (!marked) continue
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
Log.i(TAG, "finished the abandoned session folder $dir")
} catch (e: Exception) {
@@ -0,0 +1,42 @@
package com.droiddeck.launcher.session
enum class SessionLaunchFailure {
STEAM_ILLEGAL_INSTRUCTION,
VULKAN_DEVICE_MISSING;
companion object {
private val ANSI = Regex("\u001b\\[[0-?]*[ -/]*[@-~]")
private val STEAM_EXIT = Regex("== steam exited rc=(\\d+)")
fun find(lines: Sequence<String>): SessionLaunchFailure? {
var steamStarted = false
var illegalInstruction = false
var missingDevice = false
lines.forEach { raw ->
val line = ANSI.replace(raw, "").trim()
when {
line.startsWith("== droiddeck-session ") -> {
steamStarted = false
illegalInstruction = false
missingDevice = false
}
line.startsWith("== STEP ") && line.contains("starting the Steam client") -> {
steamStarted = true
illegalInstruction = false
}
STEAM_EXIT.matches(line) && steamStarted ->
illegalInstruction = STEAM_EXIT.matchEntire(line)?.groupValues?.get(1) == "132"
line.startsWith("[gamescope]") && line.contains("vulkan:") -> when {
line.contains("failed to find physical device") -> missingDevice = true
line.contains("selecting physical device") -> missingDevice = false
}
}
}
return when {
illegalInstruction -> STEAM_ILLEGAL_INSTRUCTION
missingDevice -> VULKAN_DEVICE_MISSING
else -> null
}
}
}
}
@@ -44,6 +44,10 @@ object SessionPaths {
fun current(): File? = dir
/** Whether the current session folder will survive teardown. No session means the next one can retain logs. */
fun currentSessionLogsRetained(context: Context): Boolean =
dir?.let { it.parentFile == SessionFiles.logDirectory(context) } ?: true
fun lastEnded(): File? = ended?.takeIf { it.isDirectory }
@Synchronized
@@ -603,6 +603,7 @@ object SessionPrefs {
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true)
fun renderOnCommit(context: Context): Boolean = prefs(context).getBoolean("renderOnCommit", true)
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
@@ -630,8 +631,74 @@ object SessionPrefs {
fun logsEnabled(context: Context): Boolean =
prefs(context).getBoolean("logs", true)
fun setLogsEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("logs", on).apply()
fun setLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
setLogPreference(
context,
key = "logs",
oldValue = logsEnabled(context),
newValue = on,
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
)
}
/** Extra Proton, Wine and graphics diagnostics for the next game launch; off unless chosen. */
fun gameDebugLogsEnabled(context: Context): Boolean =
prefs(context).getBoolean("gameDebugLogsEnabled", false)
fun setGameDebugLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
setLogPreference(
context,
key = "gameDebugLogsEnabled",
oldValue = gameDebugLogsEnabled(context),
newValue = on,
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
)
}
private fun setLogPreference(
context: Context,
key: String,
oldValue: Boolean,
newValue: Boolean,
newEffective: Boolean,
): Boolean {
if (oldValue == newValue) return true
val saved = prefs(context)
val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) &&
SessionPaths.currentSessionLogsRetained(context)
fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value)
if (oldEffective == newEffective) {
if (saved.edit().putBoolean(key, newValue).commit()) return true
saved.edit().putBoolean(key, oldValue).commit()
return false
}
if (oldEffective && !newEffective) {
try {
publish(false)
} catch (e: Exception) {
android.util.Log.e("GameEnvironment", "Could not disable game diagnostics", e)
return false
}
if (saved.edit().putBoolean(key, newValue).commit()) return true
saved.edit().putBoolean(key, oldValue).commit()
runCatching { publish(oldEffective) }
.onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) }
return false
}
if (!saved.edit().putBoolean(key, newValue).commit()) {
saved.edit().putBoolean(key, oldValue).commit()
return false
}
return try {
publish(newEffective)
true
} catch (e: Exception) {
saved.edit().putBoolean(key, oldValue).commit()
runCatching { publish(oldEffective) }
.onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) }
android.util.Log.e("GameEnvironment", "Could not update game diagnostics", e)
false
}
}
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
@@ -91,6 +91,7 @@ class SessionService : Service() {
private var screenOn = true
private var sessionDisplayId = Display.DEFAULT_DISPLAY
private var manualPauseRequested = false
private var manualHold = false
private var steamSleepToken: String? = null
private var nativeSleepToken: String? = null
private var nativeSleepReady = false
@@ -274,7 +275,11 @@ class SessionService : Service() {
val hold = intent?.getBooleanExtra(EXTRA_HOLD, false) == true
if (hold == signInHold) return START_NOT_STICKY
signInHold = hold
if (hold) manualPauseRequested = false
if (hold) {
manualPauseRequested = false
manualHold = false
SessionState.manualPause = false
}
suspendAttemptFailed = false
updateSuspendPolicy()
return START_NOT_STICKY
@@ -304,6 +309,14 @@ class SessionService : Service() {
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_PAUSE_NOW -> {
if (!SessionState.running || SessionState.suspended || signInHold) return START_NOT_STICKY
manualHold = true
SessionState.manualPause = true
suspendAttemptFailed = false
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_RESUME -> {
resumeSession()
return START_NOT_STICKY
@@ -346,6 +359,8 @@ class SessionService : Service() {
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
manualHold = false
SessionState.manualPause = false
SessionState.pipActive = false
pipTask = false
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
@@ -385,10 +400,10 @@ class SessionService : Service() {
}
private fun collectSessionArtifacts(dir: File, steamArch: String?) {
SessionLogCapture.stopFor(dir)
try {
SessionArtifacts.collect(this, dir, "session stopped", steamArch)
} finally {
SessionLogCapture.stopFor(dir)
SessionPaths.release(this, dir)
}
}
@@ -461,13 +476,20 @@ class SessionService : Service() {
SessionFiles.stage(this, root, startsSession = true)
// Earlier sessions' reports still read the Steam logs and VAC marker this session replaces.
SessionArtifacts.awaitCollections()
SessionArtifacts.finishAbandoned(this)
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
VacDiagnostics.arm(this)
com.droiddeck.launcher.agent.AgentGuest.reset(this)
com.droiddeck.launcher.stores.gog.GogComet.begin()
com.droiddeck.launcher.stores.StoreLaunchRequests.start(this)
val sessionDir = openSessionFolder()
try {
GameEnvironmentStore.publish(this)
} catch (e: Exception) {
Log.e(TAG, "could not publish the game environment", e)
stopSession(-1)
return
}
val sessionLog = File(sessionDir, "session.log")
val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})"
Log.i(TAG, prootLine)
@@ -1332,6 +1354,8 @@ class SessionService : Service() {
if (panelVisible) activityVisible = true
screenOn = readScreenOn()
manualPauseRequested = false
manualHold = false
SessionState.manualPause = false
suspendDownloadNow = false
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
completeNativeSleep()
@@ -1539,12 +1563,12 @@ class SessionService : Service() {
manualPauseRequested = false
}
val controller = suspendController ?: return
if (downloadsBlockingSuspend) acquireLocks()
val steamPause = SessionState.mode == MODE_STEAM && !downloadsBlockingSuspend && when (suspendPolicy) {
if (downloadsBlockingSuspend && !manualHold) acquireLocks()
val steamPause = SessionState.mode == MODE_STEAM && (manualHold || !downloadsBlockingSuspend && when (suspendPolicy) {
SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE -> hidden
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested
else -> false
}
})
if (!steamPause) {
completeNativeSleep()
} else if (nativeSleepToken == null && steamSleepToken == null &&
@@ -1552,7 +1576,7 @@ class SessionService : Service() {
prepareNativeSleep()
}
val prepared = SessionState.mode != MODE_STEAM || nativeSleepReady
val shouldSuspend = steamSleepToken != null || when (suspendPolicy) {
val shouldSuspend = steamSleepToken != null || (manualHold && prepared) || when (suspendPolicy) {
SessionPrefs.SUSPEND_AUTO -> hidden && prepared && !downloadsBlockingSuspend
SessionPrefs.SUSPEND_NATIVE -> hidden && nativeSleepReady && !downloadsBlockingSuspend
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && prepared && !downloadsBlockingSuspend
@@ -1600,6 +1624,8 @@ class SessionService : Service() {
SessionEvents.record("session.suspend_cancelled")
} else {
suspendAttemptFailed = true
manualHold = false
SessionState.manualPause = false
Log.w(TAG, "could not confirm that the session stopped")
}
}
@@ -1648,7 +1674,7 @@ class SessionService : Service() {
}
private fun resumeSteamSleepOnReturn() {
if (suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) {
if (!manualHold && suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) {
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
completeNativeSleep()
completeSteamSleep()
@@ -1706,42 +1732,48 @@ class SessionService : Service() {
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
}
private fun finishSessionStop(status: Int, stoppedGen: Int) {
private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) {
mainHandler.post {
if (stoppedGen != sessionGen || SessionState.running) {
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
return@post
try {
if (stoppedGen != sessionGen || SessionState.running) {
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
return@post
}
SessionState.suspended = false
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
manualHold = false
SessionState.manualPause = false
SessionState.pipActive = false
pipTask = false
SessionState.guestPid = -1
com.droiddeck.launcher.agent.AgentGuest.stop()
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
releaseLocks()
MemoryLog.stop()
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
} else {
val code = SessionState.failureCode ?: "GUEST_EXIT"
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
val failureStatus = SessionState.failureStatus ?: status
SessionEvents.fail(code, message, failureStatus)
}
SessionState.steamVr = false
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
SessionState.notifyEnded(status)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
} finally {
afterStopped()
}
SessionState.suspended = false
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
SessionState.pipActive = false
pipTask = false
SessionState.guestPid = -1
com.droiddeck.launcher.agent.AgentGuest.stop()
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
releaseLocks()
MemoryLog.stop()
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
} else {
val code = SessionState.failureCode ?: "GUEST_EXIT"
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
val failureStatus = SessionState.failureStatus ?: status
SessionEvents.fail(code, message, failureStatus)
}
SessionState.steamVr = false
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
SessionState.notifyEnded(status)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
@@ -1772,7 +1804,9 @@ class SessionService : Service() {
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
SessionState.running = false
SessionPaths.take() to SessionState.steamClientArch
val ended = SessionPaths.take()
if (ended != null) SessionArtifacts.collectionStarted(ended)
ended to SessionState.steamClientArch
}
SessionState.micAvailable = false
SessionState.micEnabled = false
@@ -1801,8 +1835,6 @@ class SessionService : Service() {
suspendController = null
if (ended != null) {
VacDiagnostics.snapshot(this, ended)
SessionArtifacts.collectionStarted(ended)
Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
}
components.reversed().forEach {
try {
@@ -1812,6 +1844,9 @@ class SessionService : Service() {
}
}
components.clear()
val collectEnded = {
if (ended != null) Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
}
FakeInputWriter.releaseAllRingSlots()
com.droiddeck.launcher.input.SteamTouchDevice.release()
val steamClientMayRun = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
@@ -1823,13 +1858,13 @@ class SessionService : Service() {
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
finishSessionStop(status, stoppedGen)
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
}, "session-teardown").start()
} else {
Thread({
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen)
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
}, "gog-session-stop").start()
}
@@ -2068,6 +2103,7 @@ class SessionService : Service() {
const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION"
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
const val ACTION_SUSPEND_NOW = "com.droiddeck.launcher.SUSPEND_NOW"
private const val ACTION_PAUSE_NOW = "com.droiddeck.launcher.PAUSE_NOW"
private const val ACTION_PIP_BEGIN = "com.droiddeck.launcher.PIP_BEGIN"
const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME"
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
@@ -2142,6 +2178,7 @@ class SessionService : Service() {
fun stop(context: Context) {
if (!SessionState.running) {
SessionState.stopRequested = true
SessionState.installCancellation?.cancel()
return
}
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
@@ -2187,6 +2224,10 @@ class SessionService : Service() {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SIGN_IN_HOLD).putExtra(EXTRA_HOLD, hold))
}
fun pause(context: Context) {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PAUSE_NOW))
}
fun resume(context: Context) {
if (!SessionState.running) return
if (SessionState.suspended) SessionState.resumeRequested = true
@@ -37,6 +37,9 @@ object SessionState {
@Volatile
var installing: String? = null
@Volatile
var installCancellation: com.droiddeck.launcher.core.Downloader.Cancellation? = null
@Volatile
var stopRequested = false
@@ -53,6 +56,7 @@ object SessionState {
var resuming by mutableStateOf(false)
var resumeFailures by mutableIntStateOf(0)
var resumeFailed by mutableStateOf(false)
var manualPause by mutableStateOf(false)
@Volatile var pipActive = false
@Volatile
var program: String? = null
@@ -21,7 +21,7 @@ object SettingsReset {
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
@@ -37,6 +37,7 @@ object SettingsReset {
internal fun isSessionSetting(key: String) = key in SESSION_KEYS || SESSION_PREFIXES.any { key.startsWith(it) }
fun resetAll(context: Context, gameProfiles: Boolean, gameScopes: Collection<String> = emptyList()): Boolean {
if (!SessionPrefs.setGameDebugLogsEnabled(context, false)) return false
var ok = true
val session = context.getSharedPreferences("session", Context.MODE_PRIVATE)
session.edit().apply { session.all.keys.filter { isSessionSetting(it) }.forEach { remove(it) } }.commit()
@@ -68,13 +68,13 @@ object VacDiagnostics {
}
}
fun collect(context: Context, dir: File) {
fun collect(context: Context, dir: File): Boolean {
val root = LinuxRuntime.rootDir(context)
val kept = File(dir, SNAPSHOT_MARKER).takeIf { it.isFile }
val marker = kept ?: File(root, MARKER)
val launchList = if (kept != null) File(dir, SNAPSHOT_LAUNCHES) else File(root, LAUNCHES)
if (!marker.isFile) return
try {
if (!marker.isFile) return true
return try {
val armed = marker.readLines().map { it.trim() }
val since = (armed.getOrNull(0)?.toLongOrNull() ?: 0L) * 1000 - 5_000
val arch = armed.getOrNull(1)?.takeIf { it.isNotEmpty() } ?: SessionPrefs.steamClientArch(context)
@@ -125,8 +125,10 @@ object VacDiagnostics {
File(dir, SNAPSHOT_MARKER).delete()
File(dir, SNAPSHOT_LAUNCHES).delete()
Log.i(TAG, "VAC diagnostics: ${consoles.size} console log(s), ${steamHits.size} client VAC line(s), into $dir")
true
} catch (e: Exception) {
Log.w(TAG, "collecting VAC diagnostics", e)
false
}
}
@@ -19,7 +19,7 @@ enum class Bucket { GAMES, GAME_DATA, TOOLS, COMPONENTS, STORES, DESKTOP, SYSTEM
class GameUsage(
val appId: Int, val name: String, val art: File?, val library: String, val internal: Boolean, val lastPlayed: Long,
val game: Long, val prefix: Long, val shaders: Long, val workshop: Long, val shaderDir: File?,
val x64: Boolean = false,
val x64: Boolean = false, val prefixDir: File? = null,
) {
val data: Long get() = prefix + shaders + workshop
val total: Long get() = game + data
@@ -175,14 +175,16 @@ object StorageScan {
}
if (!m.installed) continue
val gameBytes = dir?.let { File(lib.root, "steamapps/common/$it") }?.takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val prefix = File(lib.data, "steamapps/compatdata/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val compatRoot = File(lib.data, "steamapps/compatdata").takeIf { it.isDirectory } ?: File(lib.root, "steamapps/compatdata")
val prefixDir = File(compatRoot, m.appId.toString()).takeIf { it.isDirectory }
val prefix = prefixDir?.let { walker.measure(it) } ?: 0
val shaderDir = File(lib.data, "steamapps/shadercache/${m.appId}").takeIf { it.isDirectory }
val shaders = shaderDir?.let { walker.measure(it) } ?: 0
val workshop = File(lib.root, "steamapps/workshop/content/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val known = art[lib.x64]?.get(m.appId)
games.add(GameUsage(
m.appId, known?.name ?: m.name, known?.art, lib.label, lib.internal, m.lastPlayed,
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64,
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64, prefixDir,
))
}
}
@@ -140,6 +140,13 @@ object StorageState {
FileOps.delete(dir)
})
fun resetPrefix(context: Context, game: GameUsage) = act(context, "prefix-${game.appId}", { _, fresh ->
val dir = fresh.games.firstOrNull { it.appId == game.appId && it.x64 == game.x64 && it.prefixDir?.path == game.prefixDir?.path }
?.prefixDir ?: error("prefix not found")
check(FileOps.delete(dir)) { "cannot delete $dir" }
true
})
fun removeLeftover(context: Context, l: Leftover) = act(context, "leftover-${l.appId}", { _, fresh ->
val leftover = fresh.leftovers.firstOrNull { it.appId == l.appId && it.prefix?.path == l.prefix?.path && it.shaders?.path == l.shaders?.path }
?: return@act false
@@ -63,7 +63,7 @@ class StoreGameSidecar(
val file = File(folder, FILE_NAME)
val tmp = File(folder, "$FILE_NAME.tmp")
tmp.writeText(toJson().toString(2))
if (!tmp.renameTo(file)) { file.delete(); tmp.renameTo(file) }
if (!tmp.renameTo(file)) java.nio.file.Files.move(tmp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
companion object {
@@ -30,7 +30,12 @@ object StoreInstalls {
it.write(before.copy(state = StoreGameSidecar.STATE_UPDATING, installVersion = "").toJson().toString(2).toByteArray(Charsets.UTF_8))
it.fd.sync()
}
Files.move(stage.toPath(), StoreGameSidecar.file(folder).toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
val record = StoreGameSidecar.file(folder).toPath()
try {
Files.move(stage.toPath(), record, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} catch (e: java.nio.file.AtomicMoveNotSupportedException) {
Files.move(stage.toPath(), record, StandardCopyOption.REPLACE_EXISTING)
}
} finally {
stage.delete()
}
@@ -191,7 +191,10 @@ object StoresState {
backend?.signOut(app)
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchCollections.clear()
if (store == Store.ITCH) {
com.droiddeck.launcher.stores.itch.ItchCollections.clear()
com.droiddeck.launcher.stores.itch.ItchUpdates.clear(app)
}
main.post {
if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store)
@@ -282,6 +285,7 @@ object StoresState {
main.post {
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
uninstalling.remove(key)
if (game.sidecar.store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchUpdates.applied(app, key)
}
})
main.post(onDone)
@@ -33,6 +33,10 @@ internal class ItchInstaller(
private val folder: File,
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private var work: File = folder
private var updating = false
private var previous: StoreGameSidecar? = null
private val commit = Any()
override fun run(handle: DownloadQueue.JobHandle): String? {
val key = ItchAuth.key(app)
@@ -40,7 +44,10 @@ internal class ItchInstaller(
val downloadKeyId = item.extra["downloadKeyId"].orEmpty()
if (downloadKeyId.isBlank() && !item.isFree) throw IllegalStateException(app.getString(R.string.stores_itch_not_owned))
val gameId = ItchGame.resolveId(item) ?: throw IllegalStateException(app.getString(R.string.stores_itch_no_game))
val resuming = StoreGameSidecar.read(folder)?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
val before = StoreGameSidecar.read(folder)
previous = before
updating = before != null && (before.isInstalled || before.state == StoreGameSidecar.STATE_UPDATING)
val resuming = before?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
StoreInstalls.begin(folder, Store.ITCH, item.id, item.title, item.imageUrl, item.imageUrl)
handle.stage(DownloadStage.MANIFEST)
val uploads = ItchApi.uploads(key, gameId, downloadKeyId)
@@ -60,12 +67,12 @@ internal class ItchInstaller(
handle.stage(DownloadStage.INSTALL)
install(archive, filename, handle, resuming)
} catch (t: Throwable) {
if (!cancelled.get()) StoreInstalls.discard(app, folder, listOf(scratch))
if (!cancelled.get()) dropCaches(scratch)
throw t
}
if (exe == null) {
if (cancelled.get()) return null
StoreInstalls.discard(app, folder, listOf(scratch))
dropCaches(scratch)
throw IllegalStateException(app.getString(R.string.stores_itch_no_exe))
}
archive.delete()
@@ -75,6 +82,8 @@ internal class ItchInstaller(
id = item.id,
title = item.title,
exe = exe,
args = previous?.args.orEmpty(),
env = previous?.env.orEmpty(),
installVersion = upload.optString("updated_at", upload.optString("updatedAt")),
installedAt = System.currentTimeMillis(),
cover = item.imageUrl,
@@ -83,12 +92,24 @@ internal class ItchInstaller(
cloud = false,
)
StoreInstalls.complete(app, folder, sidecar) { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }
ItchUpdates.applied(app, item.key)
return folder.path
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (deleteFiles) StoreInstalls.discard(app, folder, listOf(StoreInstallRoot.scratchDir(app, Store.ITCH, item.id)))
if (deleteFiles) dropCaches(StoreInstallRoot.scratchDir(app, Store.ITCH, item.id))
}
private fun dropCaches(scratch: File) {
if (!updating) {
StoreInstalls.discard(app, folder, listOf(scratch))
return
}
synchronized(commit) {
StoreInstalls.deleteTree(scratch)
ItchStaging.delete(File(folder, ItchStaging.DIR))
}
}
private fun download(key: String, downloadKeyId: String, uploadId: String, version: String, target: File, expected: Long,
@@ -158,23 +179,45 @@ internal class ItchInstaller(
}
private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean): String? {
folder.mkdirs()
work = if (updating) File(folder, ItchStaging.DIR) else folder
if (updating) ItchStaging.delete(work)
work.mkdirs()
if (resuming) clearPartialInstall()
when (val kind = sniff(archive, filename)) {
"zip" -> unzip(archive, handle)
"7z" -> sevenZip(archive, handle)
"rar" -> unrar(archive, handle)
"exe" -> copy(archive, File(folder, filename.ifBlank { "game.exe" }))
"tar" -> untar(archive, null, handle)
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
else -> copy(archive, File(folder, filename.ifBlank { "game" }))
val exe = try {
when (val kind = sniff(archive, filename)) {
"zip" -> unzip(archive, handle)
"7z" -> sevenZip(archive, handle)
"rar" -> unrar(archive, handle)
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
"tar" -> untar(archive, null, handle)
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
else -> copy(archive, File(work, filename.ifBlank { "game" }))
}
val hint = filename.substringBeforeLast('.')
StoreExe.pick(work, hint.ifBlank { null }, item.title)
} catch (t: Throwable) {
if (updating) ItchStaging.delete(work)
throw t
}
val hint = filename.substringBeforeLast('.')
val exe = StoreExe.pick(folder, hint.ifBlank { null }, item.title)
if (exe.isBlank()) {
handle.log("itch.io: no exe found in ${folder.name}")
if (updating) ItchStaging.delete(work)
return null
}
if (updating) synchronized(commit) {
if (cancelled.get()) {
ItchStaging.delete(work)
return null
}
try {
StoreInstalls.markUpdating(folder)
} catch (t: Throwable) {
ItchStaging.delete(work)
throw t
}
ItchStaging.merge(work, folder)
ItchStaging.delete(work)
}
return exe
}
@@ -197,8 +240,8 @@ internal class ItchInstaller(
}
private fun target(name: String): File? {
val file = File(folder, name.replace('\\', '/'))
val root = folder.canonicalPath
val file = File(work, name.replace('\\', '/'))
val root = work.canonicalPath
val path = file.canonicalPath
return if (path == root || path.startsWith(root + File.separator)) file else null
}
@@ -206,8 +249,8 @@ internal class ItchInstaller(
// No JVM library reads RAR5; the runtime's bsdtar (libarchive) does.
private fun unrar(archive: File, handle: DownloadQueue.JobHandle) {
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.stores_itch_archive, "rar"))
val binds = if (listOf(app.filesDir, app.cacheDir).any { folder.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(folder.absolutePath)
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(work.absolutePath)
fun bsdtar(args: List<String>, onLine: (String) -> Unit) =
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = "itch-unrar", extraBinds = binds, fastPath = true) { line ->
if (!line.startsWith("proot ")) onLine(line)
@@ -216,7 +259,7 @@ internal class ItchInstaller(
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
var done = 0L
val tail = ArrayDeque<String>()
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", folder.absolutePath)) { line ->
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
if (tail.size == 5) tail.removeFirst()
tail.addLast(line)
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.stores.itch
import java.io.File
import java.nio.file.Files
internal object ItchStaging {
const val DIR = ".droiddeck-update"
const val RECORD = ".droiddeck-store.json"
fun merge(from: File, to: File, top: Boolean = true) {
for (child in from.listFiles().orEmpty()) {
if (top && child.name == RECORD) continue
val dest = File(to, child.name)
val destPath = dest.toPath()
if (child.isDirectory && !Files.isSymbolicLink(child.toPath()) && dest.isDirectory && !Files.isSymbolicLink(destPath)) {
merge(child, dest, false)
continue
}
if (Files.isSymbolicLink(destPath) || dest.exists()) {
delete(dest)
}
Files.move(child.toPath(), destPath)
}
}
fun delete(file: File) {
if (!Files.isSymbolicLink(file.toPath()) && file.isDirectory) file.listFiles().orEmpty().forEach { delete(it) }
file.delete()
}
}
@@ -0,0 +1,187 @@
package com.droiddeck.launcher.stores.itch
import android.content.Context
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.atomic.AtomicBoolean
internal class ItchUpdate(val uploadId: String, val updatedAt: String, val filename: String, val replaced: Boolean)
internal object ItchUpdates {
private const val KEY_AT = "updates_checked_at"
private const val KEY_FOUND = "updates_found"
private const val THROTTLE_MS = 6 * 60 * 60 * 1000L
private const val GAP_MS = 1_000L
val available = mutableStateMapOf<String, ItchUpdate>()
var checkingKey by mutableStateOf<String?>(null)
private set
private val running = AtomicBoolean(false)
private val restored = AtomicBoolean(false)
@Volatile private var generation = 0
internal fun evaluate(uploads: JSONArray?, uploadId: String, version: String): ItchUpdate? {
if (uploads == null || version.isBlank()) return null
val current = ItchUploads.byId(uploads, uploadId)
if (current != null) {
val stamp = ItchUploads.updatedAt(current)
return if (stamp > version) ItchUpdate(uploadId, stamp, ItchUploads.filename(current), false) else null
}
val next = ItchUploads.newestWindows(uploads) ?: return null
val stamp = ItchUploads.updatedAt(next)
if (uploadId.isBlank() && stamp <= version) return null
return ItchUpdate(next.optString("id"), stamp, ItchUploads.filename(next), uploadId.isNotBlank())
}
internal fun encode(found: Map<String, ItchUpdate>): String = JSONObject().also { out ->
for ((key, u) in found) out.put(key, JSONObject().put("uploadId", u.uploadId).put("updatedAt", u.updatedAt).put("filename", u.filename).put("replaced", u.replaced))
}.toString()
internal fun decode(raw: String?): Map<String, ItchUpdate> {
val json = runCatching { JSONObject(raw.orEmpty()) }.getOrNull() ?: return emptyMap()
val out = LinkedHashMap<String, ItchUpdate>()
for (key in json.keys()) {
val u = json.optJSONObject(key) ?: continue
val id = u.optString("uploadId")
if (id.isBlank()) continue
out[key] = ItchUpdate(id, u.optString("updatedAt"), u.optString("filename"), u.optBoolean("replaced"))
}
return out
}
private fun restore(app: Context) {
if (!restored.compareAndSet(false, true)) return
val started = generation
val saved = decode(ItchPrefs.get(app).getString(KEY_FOUND, null))
StoresState.post {
if (started != generation) return@post
for ((k, v) in saved) if (k !in available) available[k] = v
}
}
private fun save(app: Context) {
ItchPrefs.get(app).edit().putString(KEY_FOUND, encode(available.toMap())).apply()
}
fun check(context: Context) {
val app = context.applicationContext
if (!running.compareAndSet(false, true)) return
val started = generation
Thread({
try {
restore(app)
val prefs = ItchPrefs.get(app)
if (System.currentTimeMillis() - prefs.getLong(KEY_AT, 0L) < THROTTLE_MS) return@Thread
val key = ItchAuth.key(app)
if (key.isBlank()) return@Thread
val games = StoresState.installed.toList().filter { it.sidecar.store == Store.ITCH && it.sidecar.isInstalled }
val found = LinkedHashMap<String, ItchUpdate>()
val answered = HashSet<String>()
val snapshot = HashMap<String, Pair<String, String>>()
var failed = false
games.forEachIndexed { i, game ->
if (i > 0) Thread.sleep(GAP_MS)
val extra = game.sidecar.extra
snapshot[game.key] = game.sidecar.installVersion to extra["uploadId"].orEmpty()
val gameId = extra["gameId"].orEmpty()
if (gameId.isNotEmpty()) {
val uploads = ItchApi.uploads(key, gameId, extra["downloadKeyId"].orEmpty())
if (uploads == null) failed = true
else {
answered += game.key
evaluate(uploads, extra["uploadId"].orEmpty(), game.sidecar.installVersion)?.let { found[game.key] = it }
}
} else failed = true
}
if (started != generation) return@Thread
StoresState.post {
if (started != generation) return@post
for (k in answered) {
val now = StoresState.installed.firstOrNull { it.key == k } ?: continue
if (snapshot[k] != now.sidecar.installVersion to now.sidecar.extra["uploadId"].orEmpty()) continue
val u = found[k]
if (u != null) available[k] = u else available.remove(k)
}
save(app)
}
if (!failed && started == generation) prefs.edit().putLong(KEY_AT, System.currentTimeMillis()).apply()
StoresState.logLine("itch.io: checked ${games.size} installed games, ${found.size} with updates")
} finally {
running.set(false)
}
}, "itch-updates").start()
}
fun checkGame(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
if (checkingKey != null) return
checkingKey = game.key
val started = generation
val version = game.sidecar.installVersion
val uploadId = game.sidecar.extra["uploadId"].orEmpty()
Thread({
try {
val key = ItchAuth.key(app)
val extra = game.sidecar.extra
val gameId = extra["gameId"].orEmpty()
val uploads = if (key.isBlank() || gameId.isEmpty()) null else ItchApi.uploads(key, gameId, extra["downloadKeyId"].orEmpty())
val found = evaluate(uploads, uploadId, version)
StoresState.post {
if (started != generation) return@post
val now = StoresState.installed.firstOrNull { it.key == game.key }
if (uploads != null && now != null && now.sidecar.installVersion == version && now.sidecar.extra["uploadId"].orEmpty() == uploadId) {
if (found != null) available[game.key] = found else available.remove(game.key)
save(app)
}
val text = when {
uploads == null -> app.getString(R.string.stores_sync_failed)
found != null -> app.getString(R.string.stores_itch_updates_found, 1)
else -> app.getString(R.string.upd_current_status)
}
Toast.makeText(app, text, Toast.LENGTH_SHORT).show()
}
StoresState.logLine("itch.io: checked ${game.sidecar.title}, ${if (found != null) "update available" else "up to date"}")
} finally {
StoresState.post { checkingKey = null }
}
}, "itch-update-check").start()
}
fun start(context: Context, game: InstalledStoreGame, update: ItchUpdate) {
val app = context.applicationContext
if (StoresState.uninstalling.containsKey(game.key)) return
val root = game.folder.parentFile?.parentFile ?: return
val extra = game.sidecar.extra + ("uploadId" to update.uploadId)
val item = CatalogItem(
Store.ITCH, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
isFree = extra["downloadKeyId"].isNullOrBlank(), owned = true, extra = extra,
)
StoresState.install(app, item, root)
}
fun applied(context: Context, key: String) {
val app = context.applicationContext
StoresState.post {
available.remove(key)
save(app)
}
}
fun clear(context: Context) {
val app = context.applicationContext
generation++
ItchPrefs.get(app).edit().remove(KEY_AT).remove(KEY_FOUND).apply()
StoresState.post { available.clear() }
}
}
@@ -18,6 +18,14 @@ internal object ItchUploads {
return candidates.maxWithOrNull(compareBy({ it.optString("updated_at", it.optString("updatedAt")) }, { it.optLong("id") }))
}
fun newestWindows(uploads: JSONArray?): JSONObject? {
if (uploads == null) return null
val windows = (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }
.filter { it.optString("storage") != "external" && !it.optBoolean("demo") && windows(it) }
val games = windows.filter { it.optString("type") in GAME_TYPES }
return games.ifEmpty { windows }.maxWithOrNull(compareBy({ updatedAt(it) }, { it.optLong("id") }))
}
fun windows(upload: JSONObject): Boolean {
val platforms = upload.optJSONObject("platforms")
if (platforms != null) {
@@ -52,6 +60,8 @@ internal object ItchUploads {
return (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }.firstOrNull { it.optString("id") == id }
}
fun updatedAt(upload: JSONObject): String = upload.optString("updated_at", upload.optString("updatedAt"))
fun size(upload: JSONObject): Long = upload.optLong("size", upload.optLong("size_bytes"))
fun filename(upload: JSONObject): String = upload.optString("filename").substringAfterLast('/')
@@ -99,6 +99,8 @@ class FrontEndState(
val frameGenLabel: String,
val romsDir: String?,
val logsEnabled: Boolean,
val gameDebugLogsEnabled: Boolean = false,
val gameDebugLogsNeedsRestart: Boolean = false,
val vacDiagnostics: Boolean = false,
val agentCommands: Boolean = false,
val clearCachedApps: Boolean = false,
@@ -208,6 +210,7 @@ class FrontEndActions(
val onFiles: () -> Unit,
val onBrowseFiles: (File) -> Unit = {},
val onLogs: () -> Unit,
val onGameDebugLogs: () -> Unit = {},
val onVacDiagnostics: () -> Unit = {},
val onAgentCommands: () -> Unit = {},
val onClearCachedApps: (Boolean) -> Unit = {},
@@ -475,6 +475,12 @@ internal fun SetupPanel(
4 -> {
SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) {
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
ToggleRow(
host, "game-debug-logs", stringResource(R.string.setup_game_debug_logs),
stringResource(if (s.gameDebugLogsNeedsRestart) R.string.setup_game_debug_logs_restart else R.string.setup_game_debug_logs_hint),
s.gameDebugLogsEnabled,
enabled = s.logsEnabled,
) { a.onGameDebugLogs() }
ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
@@ -205,7 +205,12 @@ internal fun GameDetail(
GameHero(
title, item, installed, game,
Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 210.dp).onGloballyPositioned { StoresMotion.heroAt = it.boundsInRoot() },
corner = { if (!s.shortcutPicker) RemoveButton(title, game, installed, a) },
corner = {
if (!s.shortcutPicker) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (installed != null && installed.sidecar.store == Store.ITCH) ItchCheckButton(installed)
RemoveButton(title, game, installed, a)
}
},
scores = scores.takeIf { !stacked },
) {
HeroEyebrow(source, game, item, installed, download?.location ?: failed?.location)
@@ -357,6 +362,7 @@ internal fun GameActions(
GameShortcutMenu(game, a)
EditArtButton(game)
}
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
if (store == Store.XBOX && installed != null && id != null) {
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
@@ -529,7 +535,7 @@ private fun EditArtButton(g: Library.SteamGame) {
}
@Composable
private fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.itch.ItchUpdate
import com.droiddeck.launcher.stores.itch.ItchUpdates
@Composable
internal fun ItchCheckButton(installed: InstalledStoreGame) {
val ctx = LocalContext.current
IconAction(Icons.Filled.Refresh, stringResource(R.string.store_check_updates), "game:check-updates", enabled = ItchUpdates.checkingKey == null) {
ItchUpdates.checkGame(ctx, installed)
}
}
@Composable
internal fun ItchUpdateButton(installed: InstalledStoreGame, enabled: Boolean) {
val ctx = LocalContext.current
val update = ItchUpdates.available[installed.key] ?: return
var asking by remember { mutableStateOf(false) }
SecondaryButton(stringResource(R.string.common_update), enabled = enabled) {
if (update.replaced) asking = true else ItchUpdates.start(ctx, installed, update)
}
if (asking) ReplacedDialog(installed, update) { asking = false }
}
@Composable
private fun ReplacedDialog(installed: InstalledStoreGame, update: ItchUpdate, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
AppDialog(shown, close, "itchUpdate", wide = false, maxWidth = 460.dp) {
DialogTitleRow(installed.sidecar.title, close)
Text(
stringResource(R.string.stores_itch_update_replaced, update.filename.ifBlank { update.uploadId }),
fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
PrimaryButton(stringResource(R.string.common_update)) {
close()
ItchUpdates.start(ctx, installed, update)
}
SecondaryButton(stringResource(R.string.common_cancel)) { close() }
}
}
}
@@ -91,6 +91,7 @@ import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.itch.ItchCollection
import com.droiddeck.launcher.stores.itch.ItchCollections
import com.droiddeck.launcher.stores.itch.ItchUpdates
import com.droiddeck.launcher.stores.retainOrder
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
import com.droiddeck.launcher.stores.sortGames
@@ -194,7 +195,10 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
val q = LibraryView.query.trim().lowercase()
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) ItchCollections.load(ctx) }
LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) {
ItchCollections.load(ctx)
ItchUpdates.check(ctx)
} }
val collection = if (source == Store.ITCH.id) ItchCollections.chosen() else null
val pool = if (collection == null) all else collectionEntries(all, ItchCollections.gamesOf(collection.id).orEmpty())
val matching = pool.filter {
@@ -309,7 +313,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
grid = {
LibraryGrid(
s, a, grid, visible, split, visible.size, sources, source, sizesPending, syncing,
showUninstalled = listUninstalled.takeIf { stores }, onShowUninstalled = setShowUninstalled,
showUninstalled = listUninstalled.takeIf { !s.shortcutPicker },onShowUninstalled = setShowUninstalled,
hiddenUninstalled = hiddenUninstalled,
onSource = { LibraryView.source = it },
onCycle = { step ->
@@ -582,6 +586,7 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
download != null -> Text("${download.percent}%", fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
e.item != null && StoresState.isUnfinished(e.item) -> Text(stringResource(R.string.stores_resume), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
if (e.installed && e.storeKey?.let { it in ItchUpdates.available } == true) Text(stringResource(R.string.common_update), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
if (size != null && size > 0) Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
if (!e.installed) Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
}
@@ -38,6 +38,7 @@ import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.ScreenShare
import androidx.compose.material.icons.outlined.Pause
import androidx.compose.material.icons.outlined.PictureInPictureAlt
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
import androidx.compose.material.icons.outlined.Settings
@@ -285,6 +286,7 @@ class DrawerActions(
val pipSupported: Boolean = false,
val pipAutoEnter: Boolean = false,
val onPip: () -> Unit = {},
val onPause: () -> Unit = {},
val onPipAutoEnter: (Boolean) -> Unit = {},
val unfoldedControls: Boolean? = null,
val onUnfoldedControls: (Boolean) -> Unit = {},
@@ -427,17 +429,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
.padding(12.dp),
) {
val title = a.title ?: if (a.steam) stringResource(R.string.drawer_steam) else stringResource(R.string.drawer_desktop)
if (narrow) Text(title, fontSize = 18.sp, fontWeight = FontWeight.Bold,
color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp))
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp),
) {
if (narrow) Spacer(Modifier.weight(1f)) else Text(title, fontSize = 18.sp, fontWeight = FontWeight.Bold,
color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Spacer(Modifier.weight(1f))
SteamActionPill(
stringResource(R.string.stores_dl_pause), Icons.Outlined.Pause, focus.track(page, "pause"),
) { host.open = null; a.onPause() }
if (a.pipSupported) SteamActionPill(
stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"),
) { host.open = null; a.onPip() }
@@ -77,6 +77,7 @@ class PausedFrame(val image: ImageBitmap, val bounds: android.graphics.Rect)
private const val CARD_SCALE = 0.82f
private const val FRAME_WAIT_MS = 600L
private val PopEasing = CubicBezierEasing(0.3f, 1.5f, 0.4f, 1f)
private fun tone(saturation: Float, brightness: Float): ColorMatrix =
ColorMatrix().apply {
@@ -90,6 +91,7 @@ fun SessionPausedOverlay(
engaged: Boolean,
failures: Int,
frame: PausedFrame?,
animateIn: Boolean,
title: String,
onResume: () -> Unit,
onFrameNeeded: () -> Unit,
@@ -106,6 +108,18 @@ fun SessionPausedOverlay(
LaunchedEffect(suspended, engaged) {
when {
suspended && !engaged -> {
if (!shown && animateIn) {
if (currentFrame == null) {
onFrameNeeded()
withTimeoutOrNull(FRAME_WAIT_MS) { snapshotFlow { currentFrame }.first { it != null } }
}
shown = true
launch { press.animateTo(1f, Motion.sp(0.5f, Spring.StiffnessMedium)) }
launch { ring.animateTo(0f, Motion.tw(200)) }
launch { lift.animateTo(1f, Motion.tw(520)) }
orb.animateTo(1f, Motion.tw(380, delay = if (orb.value < 0.5f) 260 else 0, easing = PopEasing))
return@LaunchedEffect
}
if (!shown) {
if (currentFrame == null) {
onFrameNeeded()
@@ -846,17 +846,23 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
val ctx = LocalContext.current
val busy = sessionRunning || StorageState.cleaning
var confirm by remember { mutableStateOf<com.droiddeck.launcher.storage.Leftover?>(null) }
var confirmPrefix by remember { mutableStateOf<com.droiddeck.launcher.storage.GameUsage?>(null) }
SubHeader(stringResource(R.string.storage_game_data), stringResource(R.string.storage_game_data_hint, gb(report.prefixes), gb(report.workshop), gb(report.shaders)), onBack)
ActionStatus()
if (sessionRunning) { Note(stringResource(R.string.storage_session_running)); Spacer(Modifier.height(4.dp)) }
val games = report.games.filter { it.data >= ONE_MB }.sortedByDescending { it.data }
val games = report.games.filter { it.data >= ONE_MB || it.prefixDir != null }.sortedByDescending { it.data }
SectionTitle(stringResource(R.string.storage_data_installed), gb(games.sumOf { it.data }))
ListCard {
if (games.isEmpty()) Text(stringResource(R.string.storage_no_games), fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(16.dp))
games.forEachIndexed { i, g ->
ItemRow(
gameName(g), stringResource(R.string.storage_data_parts, gb(g.prefix), gb(g.shaders), gb(g.workshop)), g.data, i == games.lastIndex,
action = { SecondaryButton(stringResource(R.string.storage_clear_shaders), compact = true, enabled = !busy && g.shaders >= ONE_MB) { StorageState.clearShaders(ctx, g.appId, g.x64) } },
action = {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(stringResource(R.string.storage_clear_shaders), compact = true, enabled = !busy && g.shaders >= ONE_MB) { StorageState.clearShaders(ctx, g.appId, g.x64) }
SecondaryButton(stringResource(R.string.storage_reset_prefix), compact = true, enabled = !busy && g.prefixDir != null) { confirmPrefix = g }
}
},
)
}
}
@@ -888,6 +894,13 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
SectionTitle(stringResource(R.string.storage_data_other), null)
ListCard { ItemRow(stringResource(R.string.storage_data_other_title), stringResource(R.string.storage_data_other_detail), report.otherPrefixes, true) }
}
confirmPrefix?.let { g ->
ConfirmDialog(
stringResource(R.string.storage_reset_prefix_title, gameName(g)),
stringResource(R.string.storage_reset_prefix_confirm, gb(g.prefix), g.library), stringResource(R.string.storage_reset_prefix),
onConfirm = { StorageState.resetPrefix(ctx, g) }, onDismiss = { confirmPrefix = null },
)
}
confirm?.let { l ->
ConfirmDialog(
stringResource(R.string.storage_remove_title, stringResource(R.string.storage_steam_app, l.appId)),
@@ -200,18 +200,31 @@ object AppUpdates {
fun message(context: Context): String = context.getString(text, *args)
}
fun follow(context: Context, catalog: Catalog?): Follow {
fun follow(context: Context, catalog: Catalog?): Follow = follow(context, catalog, installed())
internal fun follow(context: Context, catalog: Catalog?, me: Installed): Follow {
stored(context)?.let { return it }
val me = installed()
val inferred = when {
me.pr != 0 -> Follow(Channel.TEST, me.pr)
catalog == null -> return Follow(Channel.STABLE)
catalog.stable != null && isRunning(catalog.stable, me) -> Follow(Channel.STABLE)
me.updatable -> Follow(Channel.NIGHTLY)
else -> Follow(Channel.STABLE)
}
setFollow(context, inferred)
return inferred
val guess = guessFollow(catalog, me)
if (guess.certain) setFollow(context, guess.follow)
return guess.follow
}
internal class Guess(val follow: Follow, val certain: Boolean)
/**
* Stable and Preview builds of one commit are the same APK. Preview history can include older Stable releases,
* so an overlapping older-build guess keeps the Stable default for this run without persisting it.
*/
internal fun guessFollow(catalog: Catalog?, me: Installed): Guess {
if (me.pr != 0) return Guess(Follow(Channel.TEST, me.pr), true)
val stable = catalog?.stable
if (stable != null && isRunning(stable, me)) return Guess(Follow(Channel.STABLE), true)
val publishedPreview = catalog != null && me.updatable && (
catalog.preview?.let { isRunning(it, me) } == true ||
catalog.recentPreviews.any { matchesInstalledCommit(it.commit, me.commit) }
)
if (stable?.version?.let { compareVersions(me.version, it) < 0 } == true) return Guess(Follow(Channel.STABLE), !publishedPreview)
return Guess(Follow(if (publishedPreview) Channel.NIGHTLY else Channel.STABLE), false)
}
fun setFollow(context: Context, follow: Follow) {
@@ -53,6 +53,7 @@ object CompositorHost {
fpsLimit: Int,
): Boolean {
ownVsyncThread = SessionPrefs.vsyncThread(context)
WaylandCompositor.nativeSetRenderOnCommit(SessionPrefs.renderOnCommit(context))
pace(refreshHz, fpsLimit)
if (!SessionState.running) WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight)
if (started) {
@@ -284,6 +284,8 @@ public final class WaylandCompositor {
public static native void nativeSetFpsLimit(int fps);
public static native void nativeSetRenderOnCommit(boolean on);
public static native void nativeSetGpuTurbo(boolean on);
public static native int nativeRaisePriority(int tid, int nice);
+2
View File
@@ -3219,6 +3219,8 @@
<string name="library_in">في المكتبة</string>
<string name="xbox_filter_show">عرض</string>
<string name="itch_collections">المجموعات</string>
<string name="stores_itch_updates_found">التحديثات المتاحة: %1$d</string>
<string name="stores_itch_update_replaced">استبدل المطوّر هذا الإصدار بـ %1$s. هل تريد التحديث إليه؟</string>
<string name="xbox_filter_cloud">سحابية</string>
<string name="stores_xbox_cloud_settings">إعدادات السحابة</string>
<string name="apps_search_hint">البحث في التطبيقات</string>
@@ -3069,6 +3069,8 @@
<string name="library_in">En Biblioteca</string>
<string name="xbox_filter_show">Mostrar</string>
<string name="itch_collections">Colecciones</string>
<string name="stores_itch_updates_found">Actualizaciones disponibles: %1$d</string>
<string name="stores_itch_update_replaced">El desarrollador reemplazó esta versión por %1$s. ¿Actualizar a ella?</string>
<string name="xbox_filter_cloud">Nube</string>
<string name="stores_xbox_cloud_settings">Configuración de nube</string>
<string name="apps_search_hint">Buscar apps</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">В Библиотека</string>
<string name="xbox_filter_show">Показване</string>
<string name="itch_collections">Колекции</string>
<string name="stores_itch_updates_found">Налични актуализации: %1$d</string>
<string name="stores_itch_update_replaced">Разработчикът замени тази версия с %1$s. Да се актуализира ли до нея?</string>
<string name="xbox_filter_cloud">Облак</string>
<string name="stores_xbox_cloud_settings">Настройки на облака</string>
<string name="apps_search_hint">Търсене на приложения</string>
+2
View File
@@ -3151,6 +3151,8 @@
<string name="library_in">V knihovně</string>
<string name="xbox_filter_show">Zobrazit</string>
<string name="itch_collections">Kolekce</string>
<string name="stores_itch_updates_found">Dostupné aktualizace: %1$d</string>
<string name="stores_itch_update_replaced">Vývojář nahradil tuto verzi souborem %1$s. Aktualizovat na ni?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Nastavení cloudu</string>
<string name="apps_search_hint">Hledat aplikace</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">I Bibliotek</string>
<string name="xbox_filter_show">Vis</string>
<string name="itch_collections">Samlinger</string>
<string name="stores_itch_updates_found">Opdateringer tilgængelige: %1$d</string>
<string name="stores_itch_update_replaced">Udvikleren har erstattet denne version med %1$s. Opdater til den?</string>
<string name="xbox_filter_cloud">Sky</string>
<string name="stores_xbox_cloud_settings">Skyindstillinger</string>
<string name="apps_search_hint">Søg i apps</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">In der Bibliothek</string>
<string name="xbox_filter_show">Anzeigen</string>
<string name="itch_collections">Sammlungen</string>
<string name="stores_itch_updates_found">Verfügbare Updates: %1$d</string>
<string name="stores_itch_update_replaced">Der Entwickler hat diesen Build durch %1$s ersetzt. Darauf aktualisieren?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Cloud-Einstellungen</string>
<string name="apps_search_hint">Apps durchsuchen</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">Στη Βιβλιοθήκη</string>
<string name="xbox_filter_show">Εμφάνιση</string>
<string name="itch_collections">Συλλογές</string>
<string name="stores_itch_updates_found">Διαθέσιμες ενημερώσεις: %1$d</string>
<string name="stores_itch_update_replaced">Ο προγραμματιστής αντικατέστησε αυτήν την έκδοση με %1$s. Να γίνει ενημέρωση σε αυτήν;</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Ρυθμίσεις cloud</string>
<string name="apps_search_hint">Αναζήτηση εφαρμογών</string>
+2
View File
@@ -3119,6 +3119,8 @@
<string name="library_in">En la Biblioteca</string>
<string name="xbox_filter_show">Mostrar</string>
<string name="itch_collections">Colecciones</string>
<string name="stores_itch_updates_found">Actualizaciones disponibles: %1$d</string>
<string name="stores_itch_update_replaced">El desarrollador reemplazó esta versión por %1$s. ¿Actualizar a ella?</string>
<string name="xbox_filter_cloud">Nube</string>
<string name="stores_xbox_cloud_settings">Ajustes de nube</string>
<string name="apps_search_hint">Buscar aplicaciones</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">Kirjastossa</string>
<string name="xbox_filter_show">Näytä</string>
<string name="itch_collections">Kokoelmat</string>
<string name="stores_itch_updates_found">Päivityksiä saatavilla: %1$d</string>
<string name="stores_itch_update_replaced">Kehittäjä korvasi tämän version tiedostolla %1$s. Päivitetäänkö siihen?</string>
<string name="xbox_filter_cloud">Pilvi</string>
<string name="stores_xbox_cloud_settings">Pilviasetukset</string>
<string name="apps_search_hint">Hae sovelluksia</string>
+2
View File
@@ -3119,6 +3119,8 @@
<string name="library_in">Dans la Bibliothèque</string>
<string name="xbox_filter_show">Afficher</string>
<string name="itch_collections">Collections</string>
<string name="stores_itch_updates_found">Mises à jour disponibles : %1$d</string>
<string name="stores_itch_update_replaced">Le développeur a remplacé cette version par %1$s. Mettre à jour vers celle-ci ?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Paramètres cloud</string>
<string name="apps_search_hint">Rechercher des applications</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">लाइब्रेरी में</string>
<string name="xbox_filter_show">दिखाएँ</string>
<string name="itch_collections">संग्रह</string>
<string name="stores_itch_updates_found">उपलब्ध अपडेट: %1$d</string>
<string name="stores_itch_update_replaced">डेवलपर ने इस बिल्ड को %1$s से बदल दिया है। क्या उस पर अपडेट करें?</string>
<string name="xbox_filter_cloud">क्लाउड</string>
<string name="stores_xbox_cloud_settings">क्लाउड सेटिंग्स</string>
<string name="apps_search_hint">ऐप खोजें</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">A könyvtárban</string>
<string name="xbox_filter_show">Megjelenítés</string>
<string name="itch_collections">Gyűjtemények</string>
<string name="stores_itch_updates_found">Elérhető frissítések: %1$d</string>
<string name="stores_itch_update_replaced">A fejlesztő lecserélte ezt a buildet erre: %1$s. Frissít rá?</string>
<string name="xbox_filter_cloud">Felhő</string>
<string name="stores_xbox_cloud_settings">Felhőbeállítások</string>
<string name="apps_search_hint">Alkalmazások keresése</string>
+2
View File
@@ -3073,6 +3073,8 @@
<string name="library_in">Di Pustaka</string>
<string name="xbox_filter_show">Tampilkan</string>
<string name="itch_collections">Koleksi</string>
<string name="stores_itch_updates_found">Pembaruan tersedia: %1$d</string>
<string name="stores_itch_update_replaced">Pengembang mengganti build ini dengan %1$s. Perbarui ke build itu?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Pengaturan cloud</string>
<string name="apps_search_hint">Cari aplikasi</string>
+2
View File
@@ -3117,6 +3117,8 @@
<string name="library_in">Nella Libreria</string>
<string name="xbox_filter_show">Mostra</string>
<string name="itch_collections">Raccolte</string>
<string name="stores_itch_updates_found">Aggiornamenti disponibili: %1$d</string>
<string name="stores_itch_update_replaced">Lo sviluppatore ha sostituito questa build con %1$s. Aggiornare a quella?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Impostazioni cloud</string>
<string name="apps_search_hint">Cerca app</string>
+2
View File
@@ -3060,6 +3060,8 @@
<string name="library_in">ライブラリにあります</string>
<string name="xbox_filter_show">表示</string>
<string name="itch_collections">コレクション</string>
<string name="stores_itch_updates_found">利用可能なアップデート: %1$d</string>
<string name="stores_itch_update_replaced">開発者がこのビルドを %1$s に置き換えました。更新しますか?</string>
<string name="xbox_filter_cloud">クラウド</string>
<string name="stores_xbox_cloud_settings">クラウド設定</string>
<string name="apps_search_hint">アプリを検索</string>
+2
View File
@@ -3060,6 +3060,8 @@
<string name="library_in">라이브러리에 있음</string>
<string name="xbox_filter_show">표시</string>
<string name="itch_collections">컬렉션</string>
<string name="stores_itch_updates_found">사용 가능한 업데이트: %1$d</string>
<string name="stores_itch_update_replaced">개발자가 이 빌드를 %1$s(으)로 교체했습니다. 업데이트할까요?</string>
<string name="xbox_filter_cloud">클라우드</string>
<string name="stores_xbox_cloud_settings">클라우드 설정</string>
<string name="apps_search_hint">앱 검색</string>
+2
View File
@@ -3058,6 +3058,8 @@
<string name="library_in">Dalam Pustaka</string>
<string name="xbox_filter_show">Tunjukkan</string>
<string name="itch_collections">Koleksi</string>
<string name="stores_itch_updates_found">Kemas kini tersedia: %1$d</string>
<string name="stores_itch_update_replaced">Pembangun telah menggantikan binaan ini dengan %1$s. Kemas kini kepadanya?</string>
<string name="xbox_filter_cloud">Awan</string>
<string name="stores_xbox_cloud_settings">Tetapan awan</string>
<string name="apps_search_hint">Cari apl</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">I Bibliotek</string>
<string name="xbox_filter_show">Vis</string>
<string name="itch_collections">Samlinger</string>
<string name="stores_itch_updates_found">Oppdateringer tilgjengelig: %1$d</string>
<string name="stores_itch_update_replaced">Utvikleren har erstattet denne versjonen med %1$s. Oppdatere til den?</string>
<string name="xbox_filter_cloud">Sky</string>
<string name="stores_xbox_cloud_settings">Skyinnstillinger</string>
<string name="apps_search_hint">Søk i apper</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">In Bibliotheek</string>
<string name="xbox_filter_show">Weergeven</string>
<string name="itch_collections">Collecties</string>
<string name="stores_itch_updates_found">Beschikbare updates: %1$d</string>
<string name="stores_itch_update_replaced">De ontwikkelaar heeft deze build vervangen door %1$s. Bijwerken naar die build?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Cloudinstellingen</string>
<string name="apps_search_hint">Apps zoeken</string>
+2
View File
@@ -3154,6 +3154,8 @@
<string name="library_in">W bibliotece</string>
<string name="xbox_filter_show">Pokaż</string>
<string name="itch_collections">Kolekcje</string>
<string name="stores_itch_updates_found">Dostępne aktualizacje: %1$d</string>
<string name="stores_itch_update_replaced">Deweloper zastąpił tę wersję plikiem %1$s. Zaktualizować do niej?</string>
<string name="xbox_filter_cloud">Chmura</string>
<string name="stores_xbox_cloud_settings">Ustawienia chmury</string>
<string name="apps_search_hint">Szukaj aplikacji</string>
@@ -3117,6 +3117,8 @@
<string name="library_in">Na Biblioteca</string>
<string name="xbox_filter_show">Mostrar</string>
<string name="itch_collections">Coleções</string>
<string name="stores_itch_updates_found">Atualizações disponíveis: %1$d</string>
<string name="stores_itch_update_replaced">O programador substituiu esta versão por %1$s. Atualizar para ela?</string>
<string name="xbox_filter_cloud">Nuvem</string>
<string name="stores_xbox_cloud_settings">Definições da nuvem</string>
<string name="apps_search_hint">Pesquisar aplicações</string>
+2
View File
@@ -3117,6 +3117,8 @@
<string name="library_in">Na Biblioteca</string>
<string name="xbox_filter_show">Mostrar</string>
<string name="itch_collections">Coleções</string>
<string name="stores_itch_updates_found">Atualizações disponíveis: %1$d</string>
<string name="stores_itch_update_replaced">O desenvolvedor substituiu esta versão por %1$s. Atualizar para ela?</string>
<string name="xbox_filter_cloud">Nuvem</string>
<string name="stores_xbox_cloud_settings">Configurações da nuvem</string>
<string name="apps_search_hint">Pesquisar apps</string>
+2
View File
@@ -3117,6 +3117,8 @@
<string name="library_in">În Bibliotecă</string>
<string name="xbox_filter_show">Afișează</string>
<string name="itch_collections">Colecții</string>
<string name="stores_itch_updates_found">Actualizări disponibile: %1$d</string>
<string name="stores_itch_update_replaced">Dezvoltatorul a înlocuit această versiune cu %1$s. Actualizezi la ea?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Setări cloud</string>
<string name="apps_search_hint">Caută aplicații</string>
+2
View File
@@ -3153,6 +3153,8 @@
<string name="library_in">В библиотеке</string>
<string name="xbox_filter_show">Показать</string>
<string name="itch_collections">Коллекции</string>
<string name="stores_itch_updates_found">Доступные обновления: %1$d</string>
<string name="stores_itch_update_replaced">Разработчик заменил эту сборку на %1$s. Обновиться до неё?</string>
<string name="xbox_filter_cloud">Облако</string>
<string name="stores_xbox_cloud_settings">Настройки облака</string>
<string name="apps_search_hint">Поиск приложений</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">I Bibliotek</string>
<string name="xbox_filter_show">Visa</string>
<string name="itch_collections">Samlingar</string>
<string name="stores_itch_updates_found">Uppdateringar tillgängliga: %1$d</string>
<string name="stores_itch_update_replaced">Utvecklaren har ersatt den här versionen med %1$s. Uppdatera till den?</string>
<string name="xbox_filter_cloud">Moln</string>
<string name="stores_xbox_cloud_settings">Molninställningar</string>
<string name="apps_search_hint">Sök appar</string>
+2
View File
@@ -3058,6 +3058,8 @@
<string name="library_in">อยู่ในไลบรารี</string>
<string name="xbox_filter_show">แสดง</string>
<string name="itch_collections">คอลเลกชัน</string>
<string name="stores_itch_updates_found">มีอัปเดตพร้อมใช้งาน: %1$d</string>
<string name="stores_itch_update_replaced">ผู้พัฒนาได้แทนที่บิลด์นี้ด้วย %1$s ต้องการอัปเดตเป็นบิลด์นั้นไหม</string>
<string name="xbox_filter_cloud">คลาวด์</string>
<string name="stores_xbox_cloud_settings">การตั้งค่าคลาวด์</string>
<string name="apps_search_hint">ค้นหาแอป</string>
+2
View File
@@ -3085,6 +3085,8 @@
<string name="library_in">Kütüphane içinde</string>
<string name="xbox_filter_show">Göster</string>
<string name="itch_collections">Koleksiyonlar</string>
<string name="stores_itch_updates_found">Mevcut güncellemeler: %1$d</string>
<string name="stores_itch_update_replaced">Geliştirici bu sürümü %1$s ile değiştirdi. Ona güncellensin mi?</string>
<string name="xbox_filter_cloud">Bulut</string>
<string name="stores_xbox_cloud_settings">Bulut ayarları</string>
<string name="apps_search_hint">Uygulama ara</string>
+2
View File
@@ -3151,6 +3151,8 @@
<string name="library_in">У бібліотеці</string>
<string name="xbox_filter_show">Показати</string>
<string name="itch_collections">Колекції</string>
<string name="stores_itch_updates_found">Доступні оновлення: %1$d</string>
<string name="stores_itch_update_replaced">Розробник замінив цю збірку на %1$s. Оновити до неї?</string>
<string name="xbox_filter_cloud">Хмара</string>
<string name="stores_xbox_cloud_settings">Налаштування хмари</string>
<string name="apps_search_hint">Пошук застосунків</string>
+2
View File
@@ -3058,6 +3058,8 @@
<string name="library_in">Trong Thư viện</string>
<string name="xbox_filter_show">Hiển thị</string>
<string name="itch_collections">Bộ sưu tập</string>
<string name="stores_itch_updates_found">Có bản cập nhật: %1$d</string>
<string name="stores_itch_update_replaced">Nhà phát triển đã thay bản dựng này bằng %1$s. Cập nhật lên bản đó?</string>
<string name="xbox_filter_cloud">Đám mây</string>
<string name="stores_xbox_cloud_settings">Cài đặt đám mây</string>
<string name="apps_search_hint">Tìm ứng dụng</string>
@@ -3010,6 +3010,10 @@
<string name="glasses_6dof">6DoF 虚拟屏幕</string>
<string name="tracking_recovery_look">在光线充足的房间内缓慢环顾四周。\n不要遮挡追踪摄像头,并面向家具等有明显细节的物体。</string>
<string name="spatial_print_job">DroidDeck ChArUco 30 mm</string>
<string name="session_end_steam_sigill">Steam 因非法指令(SIGILL)停止。这可能是 CPU 指令兼容问题,也可能是客户端崩溃。请分享日志并附上设备信息。</string>
<string name="session_end_steam_try_x64">可尝试“Steam 设置 → Steam 客户端 → x86-64(实验)”。此选项需要额外下载,运行速度也可能更慢。</string>
<string name="session_end_vulkan_device">Linux 图形驱动未找到可用的 Vulkan 设备。请确认所选 Linux GPU 驱动支持这颗 GPU。</string>
<string name="session_end_gpu_unsupported">当前配置缺少兼容这颗 GPU 的 Linux Vulkan 驱动,会话无法启动。Adreno Turnip 驱动不能为联发科/Mali GPU 增加支持。</string>
<string name="setup_group_memory">内存</string>
<string name="setup_clear_cached">会话前关闭缓存的应用</string>
<string name="setup_clear_cached_hint">会话开始时关闭 Android 留在后台的应用,让游戏有更多内存可用。需要开启无线调试。</string>
@@ -3062,6 +3066,8 @@
<string name="library_in">已在游戏库</string>
<string name="xbox_filter_show">显示</string>
<string name="itch_collections">收藏集</string>
<string name="stores_itch_updates_found">可用更新:%1$d</string>
<string name="stores_itch_update_replaced">开发者已将此版本替换为 %1$s。要更新到该版本吗?</string>
<string name="xbox_filter_cloud">云</string>
<string name="stores_xbox_cloud_settings">云设置</string>
<string name="apps_search_hint">搜索应用</string>
@@ -3009,6 +3009,10 @@
<string name="glasses_6dof">6DoF 虛擬螢幕</string>
<string name="tracking_recovery_look">在光線充足的房間內緩慢環顧四周。\n不要遮擋追蹤攝影機,並面向家具等有明顯細節的物體。</string>
<string name="spatial_print_job">DroidDeck ChArUco 30 mm</string>
<string name="session_end_steam_sigill">Steam 因非法指令(SIGILL)停止。這可能是 CPU 指令兼容問題,也可能是客戶端崩潰。請分享記錄並附上裝置資訊。</string>
<string name="session_end_steam_try_x64">可嘗試「Steam 設定 → Steam 客戶端 → x86-64(實驗)」。此選項需要額外下載,執行速度也可能更慢。</string>
<string name="session_end_vulkan_device">Linux 圖形驅動程式未找到可用的 Vulkan 裝置。請確認所選 Linux GPU 驅動程式支援這顆 GPU。</string>
<string name="session_end_gpu_unsupported">目前設定缺少兼容這顆 GPU 的 Linux Vulkan 驅動程式,工作階段無法啟動。Adreno Turnip 驅動程式無法為聯發科/Mali GPU 增加支援。</string>
<string name="setup_group_memory">記憶體</string>
<string name="setup_clear_cached">工作階段前關閉快取的應用程式</string>
<string name="setup_clear_cached_hint">工作階段開始時關閉 Android 留在背景的應用程式,讓遊戲有更多記憶體可用。需要開啟無線偵錯。</string>
@@ -3061,6 +3065,8 @@
<string name="library_in">已在收藏庫</string>
<string name="xbox_filter_show">顯示</string>
<string name="itch_collections">收藏集</string>
<string name="stores_itch_updates_found">可用更新:%1$d</string>
<string name="stores_itch_update_replaced">開發者已將此版本替換為 %1$s。要更新到該版本嗎?</string>
<string name="xbox_filter_cloud">雲端</string>
<string name="stores_xbox_cloud_settings">雲端設定</string>
<string name="apps_search_hint">搜尋應用程式</string>
@@ -3009,6 +3009,10 @@
<string name="glasses_6dof">6DoF 虛擬螢幕</string>
<string name="tracking_recovery_look">在光線充足的房間內緩慢環顧四周。\n不要遮擋追蹤攝影機,並面向家具等有明顯細節的物體。</string>
<string name="spatial_print_job">DroidDeck ChArUco 30 mm</string>
<string name="session_end_steam_sigill">Steam 因非法指令(SIGILL)停止。這可能是 CPU 指令相容問題,也可能是用戶端當機。請分享記錄並附上裝置資訊。</string>
<string name="session_end_steam_try_x64">可嘗試「Steam 設定 → Steam 用戶端 → x86-64(實驗)」。此選項需要額外下載,執行速度也可能更慢。</string>
<string name="session_end_vulkan_device">Linux 圖形驅動程式未找到可用的 Vulkan 裝置。請確認所選 Linux GPU 驅動程式支援這顆 GPU。</string>
<string name="session_end_gpu_unsupported">目前設定缺少相容這顆 GPU 的 Linux Vulkan 驅動程式,工作階段無法啟動。Adreno Turnip 驅動程式無法為聯發科/Mali GPU 增加支援。</string>
<string name="setup_group_memory">記憶體</string>
<string name="setup_clear_cached">工作階段前關閉快取的應用程式</string>
<string name="setup_clear_cached_hint">工作階段開始時關閉 Android 留在背景的應用程式,讓遊戲有更多記憶體可用。需要開啟無線偵錯。</string>
@@ -3061,6 +3065,8 @@
<string name="library_in">已在收藏庫</string>
<string name="xbox_filter_show">顯示</string>
<string name="itch_collections">收藏集</string>
<string name="stores_itch_updates_found">可用更新:%1$d</string>
<string name="stores_itch_update_replaced">開發者已將此版本替換為 %1$s。要更新到該版本嗎?</string>
<string name="xbox_filter_cloud">雲端</string>
<string name="stores_xbox_cloud_settings">雲端設定</string>
<string name="apps_search_hint">搜尋應用程式</string>
+13
View File
@@ -800,6 +800,10 @@
<string name="setup_session">Session</string>
<string name="setup_logs">Session logs</string>
<string name="setup_logs_hint">Saved after each session</string>
<string name="setup_game_debug_logs">Game debug logs</string>
<string name="setup_game_debug_logs_hint">Include Proton, Wine and graphics diagnostics on the next game launch. Can reduce performance and use more storage.</string>
<string name="setup_game_debug_logs_restart">Restart this session to save game debug logs</string>
<string name="setup_logging_update_failed">Couldn\'t update logging. Check the switch and try again.</string>
<string name="setup_agent_commands">Debugging tools</string>
<string name="setup_latest_logs">Latest session logs</string>
<string name="setup_saved_logs">Saved session logs</string>
@@ -2955,6 +2959,9 @@
<string name="storage_data_installed">Installed games</string>
<string name="storage_data_parts">Prefix %1$s · shaders %2$s · workshop %3$s</string>
<string name="storage_clear_shaders">Clear shaders</string>
<string name="storage_reset_prefix">Reset prefix</string>
<string name="storage_reset_prefix_title">Reset prefix for %1$s?</string>
<string name="storage_reset_prefix_confirm">Deletes its Wine prefix (%1$s) in %2$s and recreates it on the next launch. Saves, settings and installed redistributables inside it are lost; Steam Cloud saves stay in your account.</string>
<string name="storage_data_leftovers">Uninstalled games</string>
<string name="storage_steam_app">Steam app %1$d</string>
<string name="storage_leftover_unsure_detail">Its prefix still holds files, which can include local saves</string>
@@ -3215,6 +3222,10 @@
<string name="spatial_saved_views_hint">Saved views can be recalculated. Start a new calibration to capture in the current tracking frame.</string>
<string name="spatial_model_checksum_error">Hand model checksum mismatch</string>
<string name="spatial_opencv_load_error">OpenCV could not load</string>
<string name="session_end_steam_sigill">Steam stopped with an illegal instruction (SIGILL). This can be a CPU instruction compatibility problem or a client crash. Share the logs with your device details.</string>
<string name="session_end_steam_try_x64">You can try Steam settings → Steam client → x86-64 (experimental). It needs an additional download and may run more slowly.</string>
<string name="session_end_vulkan_device">The Linux graphics driver could not find a usable Vulkan device. Check that the selected Linux GPU driver supports this GPU.</string>
<string name="session_end_gpu_unsupported">This session cannot start because this GPU has no compatible Linux Vulkan driver in the current setup. Adreno Turnip drivers cannot enable support for MediaTek/Mali GPUs.</string>
<string name="setup_group_memory">Memory</string>
<string name="setup_clear_cached">Clear cached apps before a session</string>
<string name="setup_clear_cached_hint">When a session starts, DroidDeck closes the apps Android keeps parked in the background, so the game has more memory. Wireless debugging must be on.</string>
@@ -3283,6 +3294,8 @@
<string name="library_in">In Library</string>
<string name="xbox_filter_show">Show</string>
<string name="itch_collections">Collections</string>
<string name="stores_itch_updates_found">Updates available: %1$d</string>
<string name="stores_itch_update_replaced">The developer replaced this build with %1$s. Update to it?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Cloud settings</string>
<string name="xbox_cloud_gaming" translatable="false">Xbox Cloud Gaming</string>
@@ -0,0 +1,20 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Test
class DeviceReportCpuTest {
@Test fun onlyFeatureListsAreReportedAndDifferentCoreCapabilitiesAreKept() {
val cpuInfo = """
processor : 0
Features : fp asimd aes
Serial : private-device-id
processor : 1
Features : fp asimd aes atomics
processor : 2
Features : fp asimd aes
""".trimIndent()
assertEquals("fp asimd aes | fp asimd aes atomics", DeviceReport.cpuFeaturesSummary(cpuInfo))
assertEquals("not reported", DeviceReport.cpuFeaturesSummary("processor : 0\n"))
}
}
@@ -6,6 +6,9 @@ import java.net.Socket
import java.nio.file.Files
import java.security.MessageDigest
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
@@ -29,6 +32,9 @@ class DownloaderResumeTest {
@Volatile private var misbehave = false
@Volatile private var etag: String? = "\"v1\""
@Volatile private var corrupt = false
@Volatile private var holdAfterFirstChunk = false
private var bodyStarted = CountDownLatch(1)
private var continueBody = CountDownLatch(1)
@Before fun setUp() {
dir = Files.createTempDirectory("downloader-resume").toFile()
@@ -70,8 +76,15 @@ class DownloaderResumeTest {
val start = if (from == null) "200 OK" else "206 Partial Content"
val extra = if (from == null) "" else "Content-Range: bytes 0-${data.size - 1}/${data.size}\r\n"
out.write("HTTP/1.1 $start\r\n${extra}${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
out.write(content)
out.flush()
if (holdAfterFirstChunk) {
out.write(content, 0, 1024)
out.flush()
bodyStarted.countDown()
continueBody.await(5, TimeUnit.SECONDS)
} else {
out.write(content)
out.flush()
}
} else if (from == null) {
out.write("HTTP/1.1 200 OK\r\n${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
out.write(content, 0, cutAt)
@@ -168,6 +181,48 @@ class DownloaderResumeTest {
}
@Test fun cancelStopsTheTransferWithoutTryingAnotherSource() {
val first = "http://127.0.0.1:${server.localPort}/first"
val second = "http://127.0.0.1:${server.localPort}/second"
val target = File(dir, "runtime.tar.zst")
misbehave = true
val polls = java.util.concurrent.atomic.AtomicInteger()
// candidate selection and attempt each check once before the request; later checks follow chunks
val cancelled = java.util.function.BooleanSupplier { polls.incrementAndGet() > 2 }
assertFalse(Downloader.downloadCandidates(first, listOf(first, second), target, true, null, cancelled, null))
assertEquals("a cancel must not fall back to the next source", listOf<String?>(null), requests.toList())
assertTrue("the transfer stopped early (kept=${target.length()})", target.length() in 1 until data.size)
}
@Test fun cancellationDisconnectsAStalledTransfer() {
val url = "http://127.0.0.1:${server.localPort}/first"
val target = File(dir, "runtime.tar.zst")
misbehave = true
holdAfterFirstChunk = true
val cancellation = Downloader.Cancellation()
val executor = Executors.newSingleThreadExecutor()
val cancelExecutor = Executors.newSingleThreadExecutor()
try {
val result = executor.submit<Boolean> { Downloader.downloadFile(url, target, true, null, cancellation, null) }
assertTrue("server sent the first chunk", bodyStarted.await(2, TimeUnit.SECONDS))
val cancelled = cancelExecutor.submit { cancellation.cancel() }
cancelled.get(10, TimeUnit.SECONDS)
assertFalse("cancelled download", result.get(10, TimeUnit.SECONDS))
assertEquals(listOf<String?>(null), requests.toList())
} finally {
continueBody.countDown()
executor.shutdownNow()
cancelExecutor.shutdownNow()
}
}
@Test fun aCancelBeforeTheFirstRequestSendsNothing() {
val url = "http://127.0.0.1:${server.localPort}/runtime.tar.zst"
val target = File(dir, "runtime.tar.zst")
assertFalse(Downloader.downloadFile(url, target, true, null, { true }, null))
assertEquals(emptyList<String?>(), requests.toList())
}
@Test fun withoutADigestOnlyTheOriginalUrlIsTried() {
val url = "https://github.com/owner/repo/releases/download/v1/app.AppImage"
assertEquals(listOf(url), Downloader.sources(url, null))
@@ -3,9 +3,14 @@ package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.StringWriter
class LogRedactorTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun labelledJwtIsRedacted() {
val out = LogRedactor.redact("Using JWT 25484942796017334")
assertFalse(out.contains("25484942796017334"))
@@ -226,6 +231,103 @@ class LogRedactorTest {
assertEquals(once, LogRedactor.redactForShare(once))
}
@Test fun anOversizedDirectInputIsWithheldBeforeRegex() {
val secret = "sessionid=abcdef123456"
val line = "x".repeat(LogRedactor.MAX_LINE_LENGTH) + secret
assertEquals(LogRedactor.OVERSIZED_LINE, LogRedactor.redact(line))
assertEquals(LogRedactor.OVERSIZED_LINE, LogRedactor.redactForShare(line))
}
@Test fun streamWithholdsAnOversizedLogicalLineWholeAndContinues() {
val secret = "sessionid=abcdef123456"
val src = tmp.newFile("oversized.log")
src.writeText(
"before\r" +
"x".repeat(LogRedactor.MAX_LINE_LENGTH - 3) + secret + "\r\n" +
"after $secret"
)
val out = StringWriter()
LogRedactor.scrubTo(src, out)
assertEquals(
"before\n${LogRedactor.OVERSIZED_LINE}\nafter sessionid=<redacted:token>\n",
out.toString(),
)
assertFalse(out.toString().contains("abcdef123456"))
}
@Test fun sharedStreamDistinguishesOversizedAndUnsupportedLines() {
val src = tmp.newFile("shared-lines.log")
src.writeText(
"x".repeat(LogRedactor.MAX_LINE_LENGTH + 1) + "\n" +
"private-prefix\u0000private-suffix\n" +
"after sessionid=abcdef123456\n"
)
val out = StringWriter()
assertTrue(LogRedactor.scrubForShare(src, out))
assertEquals(
"${LogRedactor.OVERSIZED_LINE}\n" +
"<unsupported or oversized line withheld>\n" +
"after sessionid=<redacted:token>\n",
out.toString(),
)
}
@Test fun aMaximumLengthLineBeforeCrLfIsStillScrubbed() {
val src = tmp.newFile("maximum.log")
val line = "x ".repeat(LogRedactor.MAX_LINE_LENGTH / 2)
src.writeText(line + "\r\n")
val out = StringWriter()
LogRedactor.scrubTo(src, out)
assertEquals(line + "\n", out.toString())
assertFalse(out.toString().contains(LogRedactor.OVERSIZED_LINE))
}
@Test fun streamingScrubStopsBetweenInputChunks() {
val src = tmp.newFile("cancelled.log")
src.writeText("first safe line\n" + "x".repeat(20_000) + " sessionid=abcdef123456\n")
val out = StringWriter()
var checks = 0
val complete = LogRedactor.scrubTo(src, out) { ++checks >= 4 }
assertFalse(complete)
assertFalse(out.toString().contains("abcdef123456"))
assertTrue(checks >= 4)
}
@Test fun manyLearnedAccountsKeepBoundariesAndLiteralNames() {
val users = tmp.newFile("loginusers.vdf")
users.writeText((0 until 40).joinToString("\n") {
"\"AccountName\" \"probe_account_$it\""
} + "\n\"PersonaName\" \"Player.+[40]\"\n")
try {
LogRedactor.learnAccounts(users)
assertEquals("owner=<redacted:account> persona=<redacted:account>",
LogRedactor.redact("owner=probe_account_39 persona=Player.+[40]"))
assertEquals("owner=probe_account_390", LogRedactor.redact("owner=probe_account_390"))
} finally {
LogRedactor.learnAccounts(tmp.root.resolve("missing-users"))
}
}
@Test fun manyLearnedAddressesKeepOtherAddresses() {
val link = tmp.newFile("droiddeck-net")
link.writeText((1..40).joinToString("\n") { "addr 203.0.113.$it 24" })
try {
LogRedactor.learnOwnAddresses(link)
assertEquals("local=<redacted:ip> server=203.0.113.200",
LogRedactor.redact("local=203.0.113.40 server=203.0.113.200"))
} finally {
LogRedactor.learnOwnAddresses(tmp.root.resolve("missing-network"))
}
}
@Test fun learnedAccountsComeFromBothClients() {
val root = java.nio.file.Files.createTempDirectory("redactor").toFile()
try {
@@ -1,6 +1,11 @@
package com.droiddeck.launcher.gpu
import android.os.Environment
import android.os.Build
import com.droiddeck.launcher.session.QuestExperimental
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
@@ -9,6 +14,7 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowBuild
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@@ -16,10 +22,23 @@ class TurnipDriverAutoTest {
@Before fun reset() {
ShadowBuild.setModel("Phone")
ShadowBuild.setDevice("phone")
overrideFile().delete()
}
@After fun cleanUp() {
overrideFile().delete()
SessionPrefs.setAndroidDriver(RuntimeEnvironment.getApplication(), TurnipDriver.AUTO)
File(RuntimeEnvironment.getApplication().filesDir, "graphics_driver/test-pinned").deleteRecursively()
}
private fun overrideFile() = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-driver")
private fun gpu(model: Int, adreno: Boolean = true) = GpuInfo(
"test GPU", model, GpuInfo.familyOf(adreno, model), "", false,
)
@Test fun questModelsUseTheirPatchedDriverAsTheFallback() {
val driver = TurnipDriver(RuntimeEnvironment.getApplication())
val driver = TurnipDriver(RuntimeEnvironment.getApplication()) { error("Quest must not use generic GPU detection") }
for (model in listOf("Quest 3", "Quest 3S", "Quest 2")) {
ShadowBuild.setModel(model)
assertEquals(if (model == "Quest 2") QuestExperimental.DRIVER_A6XX else QuestExperimental.DRIVER,
@@ -27,8 +46,54 @@ class TurnipDriverAutoTest {
}
}
@Test fun otherDevicesRetainTheGenericFallback() {
assertEquals("turnip25.1.0", TurnipDriver(RuntimeEnvironment.getApplication()).autoId())
@Test fun aNonAdrenoDeviceDoesNotAutomaticallyLoadTurnip() {
assertEquals(GpuInfo.Family.NOT_ADRENO, GpuInfo.detect().family)
assertEquals("system", TurnipDriver(RuntimeEnvironment.getApplication()).autoId())
}
@Test fun autoSelectionUsesTheDetectedFamilyAndModel() {
val context = RuntimeEnvironment.getApplication()
for ((detected, expected) in listOf(
gpu(0, adreno = false) to "system",
gpu(0) to "turnip25.1.0",
gpu(650) to "turnip26.3.0-a6xx",
gpu(730) to "turnip25.1.0",
gpu(850) to "turnip-sdk36",
)) {
var calls = 0
assertEquals(expected, TurnipDriver(context) { calls++; detected }.autoId())
assertEquals(1, calls)
}
}
@Test fun nonAdrenoDoesNotUseTheAndroid16TurnipFallback() {
val context = RuntimeEnvironment.getApplication()
val sdk = Build.VERSION.SDK_INT
try {
ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 36)
assertEquals("system", TurnipDriver(context) { gpu(0, adreno = false) }.autoId())
assertEquals("turnip-sdk36", TurnipDriver(context) { gpu(0) }.autoId())
} finally {
ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", sdk)
}
}
@Test fun externalOverrideStillTakesPriorityOverDetection() {
val driver = TurnipDriver(RuntimeEnvironment.getApplication()) { error("override must precede detection") }
overrideFile().parentFile!!.mkdirs()
overrideFile().writeText("system")
assertEquals("system", driver.autoId())
overrideFile().writeText("a8")
assertEquals("turnip-sdk36", driver.autoId())
}
@Test fun aManuallySelectedImportedDriverStillTakesPriorityOverDetection() {
val context = RuntimeEnvironment.getApplication()
val dir = File(context.filesDir, "graphics_driver/test-pinned").apply { mkdirs() }
File(dir, "meta.json").writeText("""{"libraryName":"test.so"}""")
File(dir, "test.so").writeText("")
SessionPrefs.setAndroidDriver(context, "test-pinned")
assertEquals("test-pinned", TurnipDriver(context) { error("manual choice must precede detection") }.install())
}
@Test fun normalizedGpuModelsSelectExistingGenerationDrivers() {
@@ -66,6 +66,15 @@ class DeviceControlsComponentTest {
assertEquals(3, audio.getStreamVolume(AudioManager.STREAM_MUSIC))
}
@Test fun everyVolumeStepIsPublishedWithoutWaitingForThePoll() {
for (level in 2..5) {
audio.setStreamVolume(AudioManager.STREAM_MUSIC, level, 0)
context.sendBroadcast(android.content.Intent("android.media.VOLUME_CHANGED_ACTION"))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(level.toString(), File(directory, "volume.state").readText().split(" ").first())
}
}
@Test fun deniedBrightnessDoesNotOpenSettingsOrReplayAnOldSliderValueAfterPermission() {
WriteSettingsShadow.writable = false
request("brightness", "0.75")
@@ -10,6 +10,12 @@ import java.io.File
class ProotFastPathTest {
private val root = File("/data/data/com.droiddeck.launcher/files/linuxfs")
@Test fun guestEnvironmentCarriesTheHostAndroidApi() {
for (sdk in listOf(33, 35, 36)) {
assertTrue(ProotFastPath.guestEnv(root, emptyList(), "test", sdk).contains("PROOT_FP_ANDROID_API=$sdk"))
}
}
@Test fun aSessionsUsualBindsGetAKey() {
val binds = (1..87).map { "/host/$it:/guest/$it" }
assertNotNull(ProotFastPath.key(root, binds))
@@ -4,6 +4,7 @@ import android.content.Context
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
@@ -12,6 +13,8 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@@ -21,10 +24,137 @@ class GameEnvironmentStoreTest {
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.remove("logs")
.remove("gameDebugLogsEnabled")
.commit()
guest = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json")
File(context.filesDir, "game-environment.json").delete()
}
@After fun tearDown() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.remove("logs")
.remove("gameDebugLogsEnabled")
.commit()
}
@Test fun gameDebugLogsAreOffByDefault() {
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
GameEnvironmentStore.save(context, GameEnvironment.Config())
assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun gameDebugLogsRequireSessionLogsAndPreserveCustomDiagnostics() {
val config = GameEnvironment.Config(shared = mapOf("PROTON_LOG" to "0", "WINEDEBUG" to "+warn"))
GameEnvironmentStore.save(context, config)
SessionPrefs.setGameDebugLogsEnabled(context, true)
var published = JSONObject(guest.readText())
assertTrue(published.getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertEquals("0", published.getJSONObject("shared").getString("PROTON_LOG"))
assertEquals("+warn", published.getJSONObject("shared").getString("WINEDEBUG"))
assertEquals(config, GameEnvironmentStore.read(context))
SessionPrefs.setLogsEnabled(context, false)
published = JSONObject(guest.readText())
assertFalse(published.getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
SessionPrefs.setLogsEnabled(context, true)
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun failedGameDebugOptOutLeavesTheEnabledPreferenceVisible() {
assertTrue(SessionPrefs.setGameDebugLogsEnabled(context, true))
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
val guestDirectory = guest.parentFile!!
guestDirectory.deleteRecursively()
guestDirectory.parentFile!!.mkdirs()
guestDirectory.writeText("blocks the guest configuration directory\n")
try {
assertFalse(SessionPrefs.setGameDebugLogsEnabled(context, false))
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
} finally {
guestDirectory.delete()
guestDirectory.mkdirs()
GameEnvironmentStore.publish(context)
}
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun unchangedEffectiveDiagnosticsDoNotRequireGuestPublication() {
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
val guestDirectory = guest.parentFile!!
guestDirectory.deleteRecursively()
guestDirectory.parentFile!!.mkdirs()
guestDirectory.writeText("blocks the guest configuration directory\n")
try {
assertTrue(SessionPrefs.setLogsEnabled(context, false))
assertFalse(SessionPrefs.logsEnabled(context))
} finally {
guestDirectory.delete()
guestDirectory.mkdirs()
SessionPrefs.setLogsEnabled(context, true)
GameEnvironmentStore.publish(context)
}
}
@Test fun logPreferenceUpdatesUseThePublisherLock() {
GameEnvironmentStore.publish(context)
val entered = CountDownLatch(1)
val finished = CountDownLatch(1)
lateinit var thread: Thread
synchronized(GameEnvironmentStore) {
thread = Thread {
entered.countDown()
SessionPrefs.setGameDebugLogsEnabled(context, true)
finished.countDown()
}
thread.start()
assertTrue(entered.await(5, TimeUnit.SECONDS))
assertFalse(finished.await(100, TimeUnit.MILLISECONDS))
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
assertTrue(finished.await(5, TimeUnit.SECONDS))
thread.join()
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun gameDebugLogsWaitForARetainedSessionFolder() {
assertNull(SessionPaths.current())
assertTrue(SessionPaths.currentSessionLogsRetained(context))
GameEnvironmentStore.publish(context)
SessionPrefs.setLogsEnabled(context, false)
val cacheSession = SessionPaths.beginOrCurrent(context, "game-debug-logs")
try {
assertFalse(SessionPaths.currentSessionLogsRetained(context))
SessionPrefs.setLogsEnabled(context, true)
SessionPrefs.setGameDebugLogsEnabled(context, true)
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertEquals(cacheSession, SessionPaths.take())
SessionPaths.release(context, cacheSession)
val retainedSession = SessionPaths.beginOrCurrent(context, "game-debug-logs")
assertTrue(SessionPaths.currentSessionLogsRetained(context))
GameEnvironmentStore.publish(context)
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertEquals(retainedSession, SessionPaths.current())
} finally {
SessionPaths.take()?.let { ended ->
SessionPaths.release(context, ended)
ended.deleteRecursively()
}
}
}
@Test fun savedSettingsAndPublishedSettingsPreserveUnsetsAndLiteralValues() {
val config = GameEnvironment.Config(
shared = mapOf("LITERAL" to "a=b 'quoted' $(echo test)", "EMPTY" to ""),
@@ -0,0 +1,121 @@
package com.droiddeck.launcher.session
import android.app.Application
import com.droiddeck.launcher.R
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.gpu.GpuInfo
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(
sdk = [33], application = Application::class, qualifiers = "en-rUS",
instrumentedPackages = ["com.droiddeck.launcher.gpu.GpuInfo"],
shadows = [SessionEndHintTest.DetectedGpu::class],
)
class SessionEndHintTest {
@get:Rule val temporary = TemporaryFolder()
private lateinit var activity: SessionActivity
private var previousArchitecture: String? = null
@Before
fun setUp() {
previousArchitecture = SessionState.steamClientArch
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
SessionState.steamClientArch = "arm64"
}
@After
fun tearDown() {
SessionState.steamClientArch = previousArchitecture
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
}
@Test
fun sigillOnArm64IncludesTheExperimentalX64Fallback() {
SessionState.steamClientArch = "arm64"
assertEquals(
activity.getString(R.string.session_end_steam_sigill) + "\n" + activity.getString(R.string.session_end_steam_try_x64),
hintText(sigillLog()),
)
}
@Test
fun sigillOnX86_64DoesNotSuggestSwitchingToItself() {
SessionState.steamClientArch = "x86_64"
assertEquals(activity.getString(R.string.session_end_steam_sigill), hintText(sigillLog()))
}
@Test
fun sigillWithUnknownArchitectureDoesNotAssumeArm64() {
SessionState.steamClientArch = null
assertEquals(activity.getString(R.string.session_end_steam_sigill), hintText(sigillLog()))
}
@Test
fun vulkanFailureOnAdrenoSelectsTheDriverHint() {
for (family in listOf(GpuInfo.Family.A6XX, GpuInfo.Family.ADRENO_UNKNOWN)) {
DetectedGpu.family = family
assertEquals(family.name, activity.getString(R.string.session_end_vulkan_device), hintText(vulkanLog()))
}
}
@Test
fun vulkanFailureOnNonAdrenoExplainsTheMissingLinuxDriver() {
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
assertEquals(activity.getString(R.string.session_end_gpu_unsupported), hintText(vulkanLog()))
}
@Test
fun missingEmptyAndUnrelatedLogsHaveNoHint() {
assertNull(hint(null))
assertNull(hint(File(temporary.root, "missing.log")))
assertNull(hint(log("")))
assertNull(hint(log("game: Illegal instruction\n== steam exited rc=132")))
}
private fun sigillLog() = log("== STEP 12:00:00 starting the Steam client\n== steam exited rc=132\n")
private fun vulkanLog() = log("[gamescope] [Error] vulkan: failed to find physical device\n")
private fun log(text: String): File = temporary.newFile().apply { writeText(text) }
private fun hint(log: File?): Any? = SessionActivity::class.java
.getDeclaredMethod("sessionEndHint", File::class.java).apply { isAccessible = true }.invoke(activity, log)
private fun hintText(log: File): String {
val result = hint(log)
assertNotNull(result)
return ReflectionHelpers.getField(result, "text")
}
@Implements(value = GpuInfo.Companion::class, isInAndroidSdk = false)
class DetectedGpu {
@Implementation
fun detect(): GpuInfo = GpuInfo("test GPU", if (family == GpuInfo.Family.A6XX) 610 else 0, family, "", false)
companion object {
var family = GpuInfo.Family.NOT_ADRENO
}
}
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class SessionLaunchFailureTest {
private fun find(vararg lines: String) = SessionLaunchFailure.find(lines.asSequence())
@Test fun installedSteamThatExitsWithSigillHasACpuFailureHint() {
assertEquals(SessionLaunchFailure.STEAM_ILLEGAL_INSTRUCTION, find(
"== STEP 06:35:36.987 Steam client ready",
"== STEP 06:35:41.058 starting the Steam client",
"/usr/local/bin/droiddeck-session: line 309: 1192 Illegal instruction steam",
"== steam exited rc=132",
"(EE) failed to read Wayland events: Broken pipe",
))
}
@Test fun gamescopeWithoutAPhysicalDeviceHasAGraphicsFailureHint() {
assertEquals(SessionLaunchFailure.VULKAN_DEVICE_MISSING, find(
"[gamescope] [\u001b[0;31mError\u001b[0m] \u001b[0;37mvulkan:\u001b[0m failed to find physical device",
"SDL_Vulkan_CreateSurface failed: VK_KHR_wayland_surface extension is not enabled in the Vulkan instance.Failed to create backend.",
))
}
@Test fun unrelatedIllegalInstructionsAndExitCodesAreNotBlamedOnSteam() {
assertNull(find("game: Illegal instruction", "== steam exited rc=132"))
assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=139"))
assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=1320"))
assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=0"))
}
@Test fun onlyTheLatestClientAttemptCounts() {
assertNull(find(
"== STEP 12:00:00 starting the Steam client", "== steam exited rc=132",
"== STEP 12:01:00 starting the Steam client", "== steam exited rc=0",
))
}
@Test fun aLaterSuccessfulDeviceSelectionClearsTheGraphicsFailure() {
assertNull(find(
"[gamescope] [Error] vulkan: failed to find physical device",
"[gamescope] [Info] vulkan: selecting physical device 'Turnip Adreno (TM) 610': queue family 0",
))
}
@Test fun aNewSessionDoesNotReuseAnOldFailure() {
assertNull(find(
"== STEP 12:00:00 starting the Steam client", "== steam exited rc=132",
"== droiddeck-session Fri Oct 23 12:01:00 mode=steam",
))
}
}
@@ -1,8 +1,10 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.LogRedactor
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
@@ -12,6 +14,9 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.zip.ZipFile
@RunWith(RobolectricTestRunner::class)
@@ -147,6 +152,41 @@ class SessionLogShareTest {
assertTrue(zip(folder).values.none { it.contains(leaked) })
}
@Test fun aDirectoryListingFailureLeavesTheTreeUnrecordedButDoesNotStopSiblingScrubbing() {
val folder = tmp.newFolder("2026-10-06-06-listing")
val unavailable = File(folder, "unavailable").apply { mkdirs() }
val unavailableLog = File(unavailable, "session.log").apply { writeText("$secret\n") }
val availableLog = File(folder, "available/session.log").apply {
parentFile!!.mkdirs()
writeText("$secret\n")
}
assertFalse(SessionArtifacts.scrubAndMark(folder, listFiles = {
if (it == unavailable) null else it.listFiles()
}))
assertTrue(unavailableLog.readText().contains(leaked))
assertFalse(availableLog.readText().contains(leaked))
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun aFailedScrubStillRecordsTheCollectionEventWithoutCompletingTheFolder() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val folder = tmp.newFolder("2026-10-06-06-collect")
File(folder, "wayland.log").writeText("test compositor log\n")
File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).apply {
mkdirs()
resolve("blocker").writeText("force marker write failure\n")
}
SessionArtifacts.collect(context, folder, "test")
assertTrue(File(folder, "events.jsonl").readText().contains("session.artifacts_collected"))
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
}
@Test fun steamLogsPastTheSizeLimitStayOut() {
val folder = tmp.newFolder("2026-10-06-07-steam")
File(folder, "session.log").writeText("ok\n")
@@ -160,4 +200,322 @@ class SessionLogShareTest {
assertTrue("steam/console_log.txt" in names)
assertFalse("steam/cef_log.previous.txt" in names)
}
@Test fun streamingComparisonPreservesUnchangedFileAndReplacesChangedFile() {
val folder = tmp.newFolder("2026-10-06-08-steam")
val unchanged = File(folder, "unchanged.log")
unchanged.bufferedWriter().use { out -> repeat(5000) { out.write("safe diagnostic $it\n") } }
val originalModified = 1_600_000_000_000L
assertTrue(unchanged.setLastModified(originalModified))
val changed = File(folder, "changed.log")
changed.bufferedWriter().use { out ->
repeat(5000) { out.write("safe diagnostic $it\n") }
out.write("$secret\n")
}
assertTrue(SessionArtifacts.scrubAndMark(folder))
assertEquals(originalModified, unchanged.lastModified())
assertFalse(changed.readText().contains(leaked))
assertTrue(changed.readText().contains("sessionid=<redacted:token>"))
}
@Test fun historicalScrubDefersWithoutLeavingMarkersAndResumes() {
val folder = tmp.newFolder("2026-10-06-09-steam")
val log = File(folder, "session.log").apply { writeText("$secret\n") }
val rulesMarker = File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").apply { writeText("stale\n") }
val treeMarker = File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).apply { writeText("rules ${LogRedactor.RULES_VERSION}\n") }
SessionState.running = true
try {
assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true))
} finally {
SessionState.running = false
}
assertFalse(rulesMarker.exists())
assertFalse(treeMarker.exists())
assertTrue(log.readText().contains(leaked))
assertTrue(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true))
assertFalse(log.readText().contains(leaked))
assertTrue(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").isFile)
}
@Test fun historicalScrubCancellationDuringStreamingPreservesTheOriginal() {
val folder = tmp.newFolder("2026-10-06-10-steam")
val original = "first safe line\n" + "x".repeat(20_000) + " $secret\n"
val log = File(folder, "session.log").apply { writeText(original) }
var checks = 0
assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true) { ++checks >= 4 })
assertEquals(original, log.readText())
assertFalse(File(folder, ".session.log.scrub").exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun historicalScrubCancellationBeforeComparisonPreservesTheOriginal() {
val folder = tmp.newFolder("2026-10-06-11-steam")
val original = "safe diagnostic\n"
val log = File(folder, "session.log").apply { writeText(original) }
val temporary = File(folder, ".session.log.scrub")
assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true) { temporary.length() > 0 })
assertEquals(original, log.readText())
assertFalse(temporary.exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun historicalScrubDoesNotReplaceALogThatChangedBeforeCommit() {
val folder = tmp.newFolder("2026-10-06-12-steam")
val original = "sessionid=$leaked\n"
val appended = "writer finished after collection started\n"
val log = File(folder, "session.log").apply { writeText(original) }
assertFalse(SessionArtifacts.scrubAndMark(folder, beforeReplace = { it.appendText(appended) }))
assertEquals(original + appended, log.readText())
assertFalse(File(folder, ".session.log.scrub").exists())
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun comparisonCancellationWinsOverAnImmediateLengthMismatch() {
val left = tmp.newFile("left.log").apply { writeText("short\n") }
val right = tmp.newFile("right.log").apply { writeText("a different length\n") }
assertNull(SessionArtifacts.sameContents(left, right) { true })
}
@Test fun recoveryRetryKeepsItsSteamLogsWhenALaterSessionLeftNoFolder() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "2026-10-08-01-steam").apply { mkdirs() }
val saved = File(folder, "steam/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session A\n")
}
File(folder, "ended-without-teardown.txt").writeText("recovery attempted before session B\n")
val runtime = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session B\n")
}
SessionArtifacts.finishAbandoned(context)
assertEquals("session A\n", saved.readText())
assertEquals("session B\n", runtime.readText())
assertTrue(File(folder, "ended-without-teardown.txt").readText().contains("runtime capture did not finish"))
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
}
@Test fun abandonedRecoveryDoesNotCopyLogsFromANewerCompletedSession() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val logs = com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context)
val folder = File(logs, "2026-10-08-02-steam").apply { mkdirs() }
val saved = File(folder, "steam/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session A\n")
}
File(logs, "2026-10-08-03-steam").apply { mkdirs() }
.resolve(SessionArtifacts.COMPLETE_MARKER).writeText("finished session B\n")
File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session B\n")
}
SessionArtifacts.finishAbandoned(context)
assertEquals("session A\n", saved.readText())
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
}
@Test fun startupRecoveryRunsBeforeVacMarkerArmWhileOrdinaryCleanupDefers() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "2999-12-31-99-startup-recovery")
val marker = File(root, "root/.droiddeck-vac-diagnostics")
val launches = File(root, "root/.droiddeck-vac-launches")
val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/startup-recovery-vac.log")
val sessionLog = File(folder, "session.log")
val crashLog = File(folder, "crash.log")
val previousRunning = SessionState.running
val previousPhase = SessionState.phase
try {
folder.deleteRecursively()
folder.mkdirs()
SessionArtifacts.recordClient(folder, "arm64")
sessionLog.writeText("$secret\n")
marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") }
launches.writeText("startup VAC evidence\n")
runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("startup VAC evidence\n") }
SessionState.running = true
SessionState.phase = SessionPhase.STARTING_GUEST
SessionArtifacts.finishAbandoned(context)
assertFalse(File(folder, "ended-without-teardown.txt").exists())
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertEquals("startup VAC evidence\n", File(folder, "steam/startup-recovery-vac.log").readText())
assertTrue(File(folder, "vac.txt").readText().contains("startup VAC evidence"))
assertTrue(File(folder, ".recovery-runtime-captured").isFile)
assertTrue(crashLog.isFile && crashLog.length() > 0L)
assertTrue(sessionLog.readText().contains(leaked))
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertFalse(sessionLog.readText().contains(leaked))
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
} finally {
SessionState.running = previousRunning
SessionState.phase = previousPhase
folder.deleteRecursively()
runtimeSteamLog.delete()
marker.delete()
launches.delete()
}
}
@Test fun startupRecoveryExcludesCurrentFolderAndCapturesDeferredRuntime() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
val logs = com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context)
val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
val olderFolder = File(logs, "$day-8999-older-recovery")
val folder = File(logs, "$day-9000-deferred-recovery")
val marker = File(root, "root/.droiddeck-vac-diagnostics")
val launches = File(root, "root/.droiddeck-vac-launches")
val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/deferred-recovery-vac.log")
val previousRunning = SessionState.running
val previousPhase = SessionState.phase
val previousLogsEnabled = SessionPrefs.logsEnabled(context)
var currentFolder: File? = null
try {
olderFolder.deleteRecursively()
olderFolder.mkdirs()
folder.deleteRecursively()
folder.mkdirs()
SessionArtifacts.recordClient(folder, "arm64")
File(folder, "ended-without-teardown.txt").writeText("recovery began before session start\n")
marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") }
launches.writeText("deferred VAC evidence\n")
runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("deferred VAC evidence\n") }
SessionState.running = true
SessionState.phase = SessionPhase.STARTING_GUEST
SessionPrefs.setLogsEnabled(context, true)
currentFolder = SessionPaths.beginOrCurrent(context, "current-session")
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertEquals("deferred VAC evidence\n", File(folder, "steam/deferred-recovery-vac.log").readText())
assertTrue(File(folder, "vac.txt").readText().contains("deferred VAC evidence"))
assertTrue(File(folder, ".recovery-runtime-captured").isFile)
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
assertFalse(File(olderFolder, "ended-without-teardown.txt").exists())
assertFalse(File(olderFolder, SessionArtifacts.COMPLETE_MARKER).exists())
assertFalse(File(currentFolder, "ended-without-teardown.txt").exists())
assertFalse(File(currentFolder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
assertTrue(File(olderFolder, SessionArtifacts.COMPLETE_MARKER).isFile)
assertFalse(File(currentFolder, SessionArtifacts.COMPLETE_MARKER).exists())
} finally {
SessionState.running = previousRunning
SessionState.phase = previousPhase
SessionPaths.take()?.let { SessionPaths.release(context, it) }
currentFolder?.deleteRecursively()
SessionPrefs.setLogsEnabled(context, previousLogsEnabled)
olderFolder.deleteRecursively()
folder.deleteRecursively()
runtimeSteamLog.delete()
marker.delete()
launches.delete()
}
}
@Test fun failedPreGuestRuntimeCaptureWritesNeitherCaptureNorCompleteMarker() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "9999-12-31-01-vac-failure")
val marker = File(root, "root/.droiddeck-vac-diagnostics")
val launches = File(root, "root/.droiddeck-vac-launches")
val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/expired-recovery.log")
val crashLog = File(folder, "crash.log")
val previousRunning = SessionState.running
try {
folder.deleteRecursively()
folder.mkdirs()
SessionArtifacts.recordClient(folder, "arm64")
File(folder, "ended-without-teardown.txt").writeText("recovery began before session start\n")
val firstCrashSnapshot = "first crash snapshot\n".toByteArray()
crashLog.writeBytes(firstCrashSnapshot)
File(folder, "vac.txt").mkdirs()
marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") }
launches.writeText("VAC evidence that cannot be reported\n")
runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("session A\n") }
SessionState.running = true
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertFalse(File(folder, ".recovery-runtime-captured").exists())
assertTrue(File(folder, ".recovery-runtime-expired").isFile)
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
assertArrayEquals(firstCrashSnapshot, crashLog.readBytes())
File(folder, "vac.txt").deleteRecursively()
runtimeSteamLog.writeText("session B\n")
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertEquals("session A\n", File(folder, "steam/expired-recovery.log").readText())
assertArrayEquals(firstCrashSnapshot, crashLog.readBytes())
assertTrue(File(folder, "ended-without-teardown.txt").readText().contains("runtime capture did not finish"))
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertArrayEquals(firstCrashSnapshot, crashLog.readBytes())
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
} finally {
SessionState.running = previousRunning
folder.deleteRecursively()
runtimeSteamLog.delete()
marker.delete()
launches.delete()
}
}
@Test fun emptyCrashSnapshotIsPreservedAcrossRecovery() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "9999-12-31-02-empty-crash")
val crashLog = File(folder, "crash.log")
val previousRunning = SessionState.running
try {
folder.deleteRecursively()
folder.mkdirs()
crashLog.writeBytes(ByteArray(0))
SessionState.running = true
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertTrue(crashLog.isFile)
assertEquals(0L, crashLog.length())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertTrue(crashLog.isFile)
assertEquals(0L, crashLog.length())
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
} finally {
SessionState.running = previousRunning
folder.deleteRecursively()
}
}
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -20,6 +21,49 @@ import org.robolectric.annotation.Config
class SessionLogShareZipTest {
private val app get() = RuntimeEnvironment.getApplication()
@Test fun aLargeSteamLogIsRedactedInTheSharedArchive() {
val session = File(LinuxRuntime.logDir(app), "2026-10-08-02-steam").apply { mkdirs() }
val raw = File(session, "steam-42.log")
val earlySecret = "early-sessionid-abcdef123456"
val trailingSecret = "late-refresh-token-abcdef123456"
try {
// One long line exercises the streaming limit; the final ordinary line must still be redacted.
raw.bufferedWriter().use { out ->
out.write("sessionid=$earlySecret")
val chunk = "x".repeat(8192)
repeat(8192) { out.write(chunk) }
out.write("\nrefresh_token=$trailingSecret\n")
}
assertTrue(raw.length() > 64L * 1024 * 1024)
val zip = SessionLogShare.zipFolder(app, session)!!
ZipFile(zip).use { archive ->
val entry = archive.getEntry("${session.name}/steam-42.log")!!
archive.getInputStream(entry).use { input ->
// Only inspect the bounded scrubbed prefix: the pre-fix raw archive is over 64 MiB.
val expected = "${com.droiddeck.launcher.core.LogRedactor.OVERSIZED_LINE}\n"
val prefix = ByteArray(expected.toByteArray(StandardCharsets.UTF_8).size)
var offset = 0
while (offset < prefix.size) {
val count = input.read(prefix, offset, prefix.size - offset)
assertTrue("zip entry ended before its scrubbed prefix", count > 0)
offset += count
}
assertEquals(expected, String(prefix, StandardCharsets.UTF_8))
input.bufferedReader().use { reader ->
val trailing = requireNotNull(reader.readLine())
assertFalse("trailing secret survived", trailing.contains(trailingSecret))
assertEquals("refresh_token=<redacted:token>", trailing)
assertEquals(null, reader.readLine())
}
}
}
} finally {
SessionLogShare.clear(app)
session.deleteRecursively()
}
}
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
val logs = LinuxRuntime.logDir(app)
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
@@ -2,10 +2,13 @@ package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.IOException
import java.io.Writer
class SessionSteamLogsTest {
@get:Rule val tmp = TemporaryFolder()
@@ -59,4 +62,37 @@ class SessionSteamLogsTest {
assertEquals(listOf("web.txt"), names(copied))
assertFalse(File(out, "web.txt").readText().contains("abcdef123456"))
}
@Test fun aCopyFailurePreservesThePreviousSnapshotAndRemovesPartialStaging() {
val logs = tmp.newFolder("logs")
val session = tmp.newFolder("session")
val out = tmp.newFolder("out")
File(logs, "console_log.txt").writeText("new complete line\n")
val snapshot = File(out, "console_log.txt").apply { writeText("previous valid snapshot\n") }
lateinit var staging: File
val copied = SessionArtifacts.copySessionLogs(logs, session, out) { target ->
staging = target
val delegate = target.bufferedWriter()
object : Writer() {
private var failed = false
override fun write(buffer: CharArray, offset: Int, length: Int) {
if (!failed) {
delegate.write(buffer, offset, minOf(length, 4))
delegate.flush()
failed = true
}
throw IOException("injected writer failure")
}
override fun flush() = delegate.flush()
override fun close() = delegate.close()
}
}
assertTrue(copied.isEmpty())
assertEquals("previous valid snapshot\n", snapshot.readText())
assertFalse(staging.exists())
}
}
@@ -34,6 +34,7 @@ class SettingsResetTest {
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
SessionPrefs.setGuestHostname(app, "MyDeck")
assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true))
SessionPrefs.setHudShowFps(app, false)
SessionPrefs.setHudShowBattery(app, false)
SessionPrefs.setHudShowGraph(app, false)
@@ -54,6 +55,10 @@ class SettingsResetTest {
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app))
assertFalse(SessionPrefs.gameDebugLogsEnabled(app))
val guest = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app),
"root/.config/droiddeck/game-environment.json")
assertFalse(org.json.JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertTrue(SessionPrefs.hudShowFps(app))
assertTrue(SessionPrefs.hudShowBattery(app))
assertTrue(SessionPrefs.hudShowGraph(app))
@@ -67,6 +72,22 @@ class SettingsResetTest {
assertFalse(prefs("steam_touch").contains("gyro"))
}
@Test fun aFailedDebugOptOutDoesNotHideTheEnabledPreference() {
assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true))
val directory = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app),
"root/.config/droiddeck")
directory.deleteRecursively()
directory.writeText("blocks configuration publication")
try {
assertFalse(SettingsReset.resetAll(app, gameProfiles = false))
assertTrue(SessionPrefs.gameDebugLogsEnabled(app))
} finally {
directory.delete()
directory.mkdirs()
GameEnvironmentStore.publish(app)
}
}
@Test fun libraryAndRecordsAreKept() {
val folder = "/storage/emulated/0/Games/Foo"
SessionPrefs.setAddedGameName(app, folder, "Foo")
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.stores
import android.app.Application
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.assertEquals
@@ -18,7 +19,7 @@ import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
@Config(sdk = [33], application = Application::class)
class StoreAccountsCipherTest {
private val app get() = RuntimeEnvironment.getApplication()
private fun newKey(): SecretKey = SecretKeySpec(ByteArray(32).also { SecureRandom().nextBytes(it) }, "AES")
@@ -0,0 +1,85 @@
package com.droiddeck.launcher.stores.itch
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class ItchStagingTest {
@get:Rule val tmp = TemporaryFolder()
private fun file(root: File, path: String, text: String) = File(root, path).also { it.parentFile?.mkdirs(); it.writeText(text) }
@Test fun newFilesReplaceOldOnesAndEverythingElseStays() {
val game = tmp.newFolder("game")
val staged = tmp.newFolder("staged")
file(game, "game.exe", "old")
file(game, "data/level.dat", "old")
file(game, "saves/slot1.sav", "mine")
file(game, ".droiddeck-store.json", "record")
file(staged, "game.exe", "new")
file(staged, "data/level.dat", "new")
file(staged, "data/extra.dat", "new")
file(staged, "saves/default.sav", "new")
ItchStaging.merge(staged, game)
assertEquals("new", File(game, "game.exe").readText())
assertEquals("new", File(game, "data/level.dat").readText())
assertEquals("new", File(game, "data/extra.dat").readText())
assertEquals("mine", File(game, "saves/slot1.sav").readText())
assertEquals("new", File(game, "saves/default.sav").readText())
assertEquals("record", File(game, ".droiddeck-store.json").readText())
assertTrue(staged.listFiles().orEmpty().all { it.isDirectory && it.listFiles().orEmpty().isEmpty() })
}
@Test fun aFileReplacingADirectoryAndTheOtherWayRound() {
val game = tmp.newFolder("game")
val staged = tmp.newFolder("staged")
file(game, "a/inner.txt", "old")
file(game, "b", "old")
file(staged, "a", "new")
file(staged, "b/inner.txt", "new")
ItchStaging.merge(staged, game)
assertTrue(File(game, "a").isFile)
assertEquals("new", File(game, "a").readText())
assertEquals("new", File(game, "b/inner.txt").readText())
assertFalse(File(game, "a/inner.txt").exists())
}
@Test fun deletingFollowsNoLinkOutOfTheTree() {
val outside = tmp.newFolder("outside")
file(outside, "keep.txt", "keep")
val staged = tmp.newFolder("staged")
file(staged, "own.txt", "x")
java.nio.file.Files.createSymbolicLink(File(staged, "link").toPath(), outside.toPath())
ItchStaging.delete(staged)
assertFalse(staged.exists())
assertEquals("keep", File(outside, "keep.txt").readText())
}
@Test fun aLinkInTheGameIsReplacedNotFollowed() {
val outside = tmp.newFolder("outside")
file(outside, "keep.txt", "keep")
val game = tmp.newFolder("game")
java.nio.file.Files.createSymbolicLink(File(game, "data").toPath(), outside.toPath())
val staged = tmp.newFolder("staged")
file(staged, "data/level.dat", "new")
ItchStaging.merge(staged, game)
assertEquals("keep", File(outside, "keep.txt").readText())
assertFalse(File(outside, "level.dat").exists())
assertEquals("new", File(game, "data/level.dat").readText())
}
@Test fun theInstallRecordIsNeverReplacedByTheArchive() {
val game = tmp.newFolder("game")
val staged = tmp.newFolder("staged")
file(game, ".droiddeck-store.json", "record")
file(staged, ".droiddeck-store.json", "forged")
file(staged, "sub/.droiddeck-store.json", "nested")
ItchStaging.merge(staged, game)
assertEquals("record", File(game, ".droiddeck-store.json").readText())
assertEquals("nested", File(game, "sub/.droiddeck-store.json").readText())
}
}
@@ -0,0 +1,84 @@
package com.droiddeck.launcher.stores.itch
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
class ItchUpdatesTest {
private fun upload(id: String, updated: String, filename: String = "game-$id.zip", windows: Boolean = true, type: String = "default") =
JSONObject().put("id", id).put("filename", filename).put("updated_at", updated).put("type", type).put("storage", "hosted")
.put("platforms", JSONObject().put("windows", windows).put("linux", !windows))
private fun list(vararg uploads: JSONObject) = JSONArray().also { a -> uploads.forEach { a.put(it) } }
@Test fun aNewerStampOnTheSameUploadIsAnUpdate() {
val update = ItchUpdates.evaluate(list(upload("7", "2026-10-20T10:00:00Z")), "7", "2026-09-01T10:00:00Z")!!
assertEquals("7", update.uploadId)
assertEquals("2026-10-20T10:00:00Z", update.updatedAt)
assertFalse(update.replaced)
}
@Test fun theSameStampIsNotAnUpdate() {
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-09-01T10:00:00Z")), "7", "2026-09-01T10:00:00Z"))
}
@Test fun anOlderStampIsNotAnUpdate() {
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-08-01T10:00:00Z")), "7", "2026-09-01T10:00:00Z"))
}
@Test fun aMissingUploadFallsBackToTheNewestWindowsOneAndAsksFirst() {
val update = ItchUpdates.evaluate(
list(upload("8", "2026-10-01T10:00:00Z"), upload("9", "2026-10-05T10:00:00Z"), upload("10", "2026-10-09T10:00:00Z", windows = false)),
"7", "2026-09-01T10:00:00Z",
)!!
assertEquals("9", update.uploadId)
assertTrue(update.replaced)
}
@Test fun aReplacedUploadWithNoWindowsBuildLeftIsNotOffered() {
val linux = list(upload("8", "2026-10-01T10:00:00Z", windows = false))
assertNull(ItchUpdates.evaluate(linux, "7", "2026-09-01T10:00:00Z"))
assertNull(ItchUpdates.evaluate(linux, "", "2026-09-01T10:00:00Z"))
}
@Test fun aWindowsBuildOfAnotherTypeBeatsALinuxDefaultOne() {
val update = ItchUpdates.evaluate(
list(upload("8", "2026-10-09T10:00:00Z", windows = false), upload("9", "2026-10-01T10:00:00Z", type = "other")),
"7", "2026-09-01T10:00:00Z",
)!!
assertEquals("9", update.uploadId)
assertTrue(update.replaced)
}
@Test fun anUnknownInstalledVersionNeverReportsAnUpdate() {
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-10-20T10:00:00Z")), "7", ""))
}
@Test fun noAnswerOrNoWindowsBuildMeansNoUpdate() {
assertNull(ItchUpdates.evaluate(null, "7", "2026-09-01T10:00:00Z"))
assertNull(ItchUpdates.evaluate(JSONArray(), "7", "2026-09-01T10:00:00Z"))
}
@Test fun anInstallWithoutAnUploadIdComparesTheNewestWindowsBuild() {
val update = ItchUpdates.evaluate(list(upload("8", "2026-10-01T10:00:00Z")), "", "2026-09-01T10:00:00Z")!!
assertEquals("8", update.uploadId)
assertFalse(update.replaced)
assertNull(ItchUpdates.evaluate(list(upload("8", "2026-08-01T10:00:00Z")), "", "2026-09-01T10:00:00Z"))
}
@Test fun foundUpdatesSurviveTheCache() {
val found = mapOf("itch:a/b" to ItchUpdate("9", "2026-10-05T10:00:00Z", "b.zip", true))
val back = ItchUpdates.decode(ItchUpdates.encode(found))
assertEquals(setOf("itch:a/b"), back.keys)
assertEquals("9", back.getValue("itch:a/b").uploadId)
assertTrue(back.getValue("itch:a/b").replaced)
assertEquals(emptyMap<String, ItchUpdate>(), ItchUpdates.decode(null))
assertEquals(emptyMap<String, ItchUpdate>(), ItchUpdates.decode("not json"))
}
}
@@ -8,6 +8,7 @@ import com.droiddeck.launcher.update.AppUpdates.Offer
import com.droiddeck.launcher.update.AppUpdates.PreviewChange
import com.droiddeck.launcher.update.AppUpdates.PreviewHistoryKind
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.json.JSONArray
@@ -285,4 +286,69 @@ class AppUpdatesTest {
} catch (_: IOException) {
}
}
@Test fun anOlderStableIsGuessedStableAndSaved() {
val g = AppUpdates.guessFollow(catalog, me("eeeeeee999", version = "0.1.9"))
assertEquals(AppUpdates.Channel.STABLE, g.follow.channel)
assertTrue(g.certain)
}
@Test fun anOlderBuildInPreviewHistoryKeepsStableAsAnUncertainGuess() {
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
val g = AppUpdates.guessFollow(withHistory, me("2".repeat(40), version = "0.1.0"))
assertEquals(Channel.STABLE, g.follow.channel)
assertFalse(g.certain)
}
@Test fun anOlderCataloguedBuildDoesNotPersistAGuessAndExplicitChoicesStillWin() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val preferences = context.getSharedPreferences("app_updates", android.content.Context.MODE_PRIVATE)
preferences.edit().clear().commit()
try {
val installed = me("2".repeat(40), version = "0.1.0")
val newerStable = release("0".repeat(40), version = "9999.0.0")
val currentPreview = release(installed.commit)
val newerCatalog = AppUpdates.Catalog(newerStable, currentPreview, emptyList(), 0L)
assertEquals(Channel.STABLE, AppUpdates.follow(context, newerCatalog, installed).channel)
assertNull(preferences.getString("channel", null))
assertEquals(Channel.STABLE, AppUpdates.follow(context, null, installed).channel)
assertNull(preferences.getString("channel", null))
for (choice in listOf(Follow(Channel.STABLE), Follow(Channel.NIGHTLY), Follow(Channel.TEST, 93))) {
AppUpdates.setFollow(context, choice)
val actual = AppUpdates.follow(context, newerCatalog, installed)
assertEquals(choice.channel, actual.channel)
assertEquals(choice.pr, actual.pr)
}
} finally {
preferences.edit().clear().commit()
}
}
@Test fun runningTheCatalogStableIsCertainStable() {
val g = AppUpdates.guessFollow(catalog, me(stable.commit))
assertEquals(AppUpdates.Channel.STABLE, g.follow.channel)
assertTrue(g.certain)
}
@Test fun aPublishedPreviewPastStableIsGuessedNightlyWithoutSaving() {
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
val g = AppUpdates.guessFollow(withHistory, me("2".repeat(40), version = "0.3.0"))
assertEquals(AppUpdates.Channel.NIGHTLY, g.follow.channel)
assertFalse(g.certain)
}
@Test fun anUncataloguedNewerBuildStaysStableForNow() {
val g = AppUpdates.guessFollow(catalog, me("9".repeat(40), version = "0.3.0"))
assertEquals(AppUpdates.Channel.STABLE, g.follow.channel)
assertFalse(g.certain)
val offline = AppUpdates.guessFollow(null, me("9".repeat(40), version = "0.3.0"))
assertEquals(AppUpdates.Channel.STABLE, offline.follow.channel)
assertFalse(offline.certain)
}
@Test fun aPullRequestBuildIsCertainTest() {
val g = AppUpdates.guessFollow(catalog, me("ccccccc2222222222222222222222222222222", pr = 93))
assertEquals(AppUpdates.Channel.TEST, g.follow.channel)
assertTrue(g.certain)
}
}
+47
View File
@@ -52,12 +52,59 @@ environment entries and is intentionally narrower than **Reset game profile**.
Values are literal strings, with no shell expansion; quotes are only needed when
the consuming program expects them.
## Game debug logs
Under **Setup > Diagnostics**, enable **Session logs** and **Game debug logs**
before reproducing a Windows game problem. Game debug logs is off by default and
is available when Session logs is enabled. It applies to the next game launch through DroidDeck's
Valve or third-party Proton wrapper, including added games and store shortcuts.
A running game must be restarted. If the current session began with Session logs
disabled, restart that session first: its existing log folder is disposable, and
the UI shows a restart reminder instead of enabling logs that would be discarded.
| Generated setting | Effective value while enabled |
| --- | --- |
| `PROTON_LOG` | `1` |
| `PROTON_LOG_DIR`, `PROTON_CRASH_REPORT_DIR`, `DXVK_LOG_PATH` | The actual session log directory |
| `DXVK_LOG_LEVEL` | `debug` |
| `VKD3D_DEBUG` | `info` |
| `WINEDEBUG` | Valid custom channels plus Proton's standard diagnostic channels |
Diagnostics take precedence over conflicting inherited, shared, or per-game log
settings while the switch is on. Wine channel selectors are normalized and
deduplicated with the last selector winning; required exception, module, and
timestamp channels are applied last, including when a profile contains `-all`.
Custom channels from `PROTON_LOG` are retained when valid. Malformed channel tokens
are omitted; an oversized list falls back to the standard diagnostic channels.
Saved profiles and Steam launch options are unchanged. The launcher merges a
process-environment map, so every variable has one value and paths containing
spaces, quotes, or shell characters stay literal. Existing arguments and
`%command%` are not reconstructed. Disabling the switch restores the user's normal
settings on the next launch. It does not change Steam probes or native Linux
programs, whose ordinary output remains in the session log.
After reproducing once, stop the session and use **Latest session logs > Share
logs**. The archive includes the generated Wine/Proton and graphics logs. Debug
logging can reduce performance and consume storage; disable it after collecting
the report. If the session log directory is unavailable, the launcher reports
that diagnostics were skipped instead of writing uncollected files elsewhere.
A Unity game under FEX (`UnityPlayer.dll` for Windows builds under Proton,
`UnityPlayer.so` or `GameAssembly.so` for native Linux builds started by
**Linux x86 (FEX)**) keeps FEX's TSO on when the Default profile's FEX preset
turns it off: without TSO such games can deadlock or crash (seen with Megabonk
and Crab Game). A FEX preset chosen for the game itself still applies.
Games launched through Proton get `vblank_mode=0`, so OpenGL does not wait for
each screen refresh. Wine asks for a swap interval of 1 on every OpenGL window, and WineD3D's front-buffer
drawing (DirectDraw, Direct3D 1–7) never lowers it, so those games ran at the
refresh rate even with no frame limit (AIO Direct3D 7: 144 fps at 144 Hz, about
2,260 with the wait off). Steam's Frame Limit still holds a game: while it is on,
gamescope's WSI layer presents every swapchain in FIFO at the limit. A
`vblank_mode` from the launch options or the environment editor is kept, and
**Remove** in the editor leaves Mesa's own default.
## Defaults and available suggestions
The initial configuration enables Mesa shader caching with
+44
View File
@@ -0,0 +1,44 @@
# itch.io updates
An installed itch game is checked against the uploads itch lists for it. A game with an update shows an
Update label on its Library tile and an Update button on its game page. A Check for updates button sits
in the top right of an installed itch game's page, next to the delete button, and checks that game only.
## Detection
The install record (`.droiddeck-store.json`) keeps three things from the install: the upload's
`updated_at` as `installVersion`, and `gameId`, `downloadKeyId` and `uploadId` in `extra`.
`ItchUpdates.evaluate` compares them with `GET /games/<id>/uploads`:
- the installed upload is still listed and its `updated_at` is later: an update to the same upload;
- the installed upload is gone: the newest Windows upload is offered as a replaced build;
- an install without an `uploadId` compares the newest Windows upload's stamp;
- an unknown installed version or no answer from itch never reports an update.
The automatic check walks the installed itch games one at a time, one second apart, and logs
`itch.io: checked <n> installed games, <m> with updates`. It runs when the itch tab opens, at most every
six hours. The button on a game page checks only that game, at any time, answers with a toast ("Update
available", "Up to date" or "Sync failed") and logs `itch.io: checked <title>, ...`. A game itch did not answer for keeps its last
result, and the six-hour clock only advances after a fully answered pass. Results are kept in the itch
preferences until the update is installed or the account signs out.
## Installing
The Update button reruns the normal install over the game's own folder, keeping its storage location.
For a replaced build the game page asks first and names the new file.
An update never extracts into the live game. The download goes to the scratch folder, as for any
install, and the archive is unpacked into `.droiddeck-update` inside the game folder. The new build is
checked there (an executable must be found) before a single game file is touched. A failed or cancelled
download or extraction removes the staging folder and leaves the game as it was.
Only then does `ItchStaging.merge` move the staged files into place, which are renames inside one
folder: a staged file replaces the file with the same path, directories are merged, and anything the new
build does not contain (saves, settings, the install record, launcher and art) stays. The install record
is marked updating just before the move, so an interruption in that short step is resumable, and the
finished record carries the new `installVersion` and `uploadId`. Free space for one extra copy of the
build is needed while the update runs.
A cancel that arrives before the files are moved in stops the update and removes the staging folder. Once
the move has started the update is past the point of no return: it finishes and writes the new record, so
a cancel during that short step cannot leave new files under an old record.
+547
View File
@@ -0,0 +1,547 @@
# proroot: what it does and what DroidDeck can take from it
Static analysis of [coderredlab/proroot](https://github.com/coderredlab/proroot) v1.2.8
(`c01039ab`, 2026-06-17). The repository holds only five arm64 binaries and a README. The licence is
proprietary, and redistributing modified binaries is not allowed, so only the ideas below are
usable, not the code. The binaries were read with the NDK's `llvm-readelf`, `llvm-nm`,
`llvm-objdump` and `llvm-strings`. `libproroot-stub-loader.so` and `libproroot-bridge.so` still carry
`.symtab`, and `libproroot-runtime.so` exports about 260 names, so the function names below are
proroot's own.
## Architecture
proroot does not use ptrace. Everything runs inside the guest process.
| file | kind | role |
|---|---|---|
| `libproroot.so` | bionic PIE executable | Launcher. Parses `-r/-b/-w/-0/--link2symlink`, writes a config file (`.proroot-config-<pid>`, passed down as `PROROOT_CFG_FD`), and execs the guest through `libproroot-linker.so` or the stub loader. |
| `libproroot-linker.so` | freestanding PIE, run as an executable | A from-scratch glibc dynamic linker ("cleanroom linker") that replaces `ld-linux-aarch64.so.1`. It maps the program and its `DT_NEEDED` libraries, relocates them, sets up static TLS, and stubs `_dl_*` and `__tunable_get_val`. It finds `_rtld_global_ro` through a table of offsets per glibc version ("no offset table for glibc X, patches skipped"). It also installs a SIGSYS handler with an allow-list. |
| `libproroot-stub-loader.so` | freestanding static PIE | Userland `exec`. It maps the target and its `PT_INTERP` itself and builds the stack and auxv. It then **rewrites the `svc #0` sites** in the loaded images (`proroot_svc_scan`, `proroot_svc_patch_apply`, `select_trampoline_for_site`) to branch into per-syscall trampolines (`proroot_tramp_openat`, `_statx`, `_faccessat2`, `_clone3`, `_rt_sigaction`, `_shmget`, ...). Sites it cannot patch fall back to an in-process seccomp `RET_TRAP` filter with a SIGSYS handler ("trampoline fallback, activating trap-mode fallback"). |
| `libproroot-runtime.so` | glibc `LD_PRELOAD` | Hooks about 200 libc entry points: path translation, fake root (`fake_id0_*`), link2symlink, exec routing, SysV shm, netlink, `/proc` and `/sys` views, `brk`, a fake DRM/KMS and GBM device plus libseat for compositors, X11 and Unix-socket fixups. After load it **patches the svc sites in glibc itself** (`patch_libc_syscalls`). |
| `libproroot-bridge.so` | static `ET_EXEC` at `0x7000000000` | The "trampoline" for static guest binaries. It installs a path-trap seccomp filter plus a SIGSYS handler, maps the target, and serves a virtual `/proc` (`status`, `stat`, `cmdline`, `environ`, `mounts`, `mountinfo`, `fdinfo`, `auxv`). |
The executable files all live in `nativeLibraryDir`, which is the only place an app may exec from.
That is why the dynamic linker and the static loader each have their own userland loader. proot
handles the same constraint with `libproot-loader.so`.
## How the in-process syscall interception works
1. **Patching svc sites in glibc** (`patch_phdr_callback`, called through `dl_iterate_phdr`):
- It scans only an allow-list of objects: `libc.so.6`/`libc-`, `ld-linux`, `libpthread`,
`librt`, `libdl`. Main executables get patched early only for listed programs (apt, dpkg,
curl, openssl, node, chromium/electron/playwright, passwd/useradd/...). Other programs are
patched later (`log_deferred_libc_patch`, `PROROOT_FORCE_EARLY_PATCH`).
- In each executable `PT_LOAD` it finds `svc #0` (`0xd4000001`). It checks the instructions
before it for a `mov x8, #nr` it recognises. One fixed glibc `openat` call sequence gets
special treatment: its `bl` is redirected to a relay (`emit_openat_call_relay_entry`).
- The site is replaced with a `b`/`bl` to a relay stub on a page allocated within ±128 MiB
(`alloc_relay_page`). Sites out of range are logged as `bl-out-of-range`; `large-image
multi-cover tramp` places extra relay pages for big images.
- **Write path:** it first tries `mprotect(PROT_READ|PROT_WRITE|PROT_EXEC)` on the segment.
If that is refused, it `pwrite`s the 4-byte instruction through `/proc/self/mem`. Either way
it then calls `__clear_cache`. The log line counts sites by kind: `patched %d seccomp + %d
path (%d relay) + %d brk`.
2. **In-process SIGSYS fallback**:
- A BPF filter allows syscalls whose instruction pointer is inside proroot's own code and
returns `SECCOMP_RET_TRAP` for the path, exec, clone and wait syscalls from anywhere else.
The IP check is the same idea as our patch 0014, with TRAP instead of TRACE.
- The handler emulates the call and writes the result into the signal frame. Guest SIGSYS
handlers are kept and chained (`proroot_record_user_sigsys`, `invoke_user_sigsys`).
3. **Keeping SIGSYS deliverable**, the objection in option 4 of
[proot-performance](proot-performance.md):
- The `sigprocmask` and `pthread_sigmask` hooks call `sigtrap_unblocked_mask`, which
`sigdelset`s `SIGSYS` (and `SIGTRAP` for some guests) from any `SIG_BLOCK`/`SIG_SETMASK` set.
- `rt_sigaction` is guarded so the guest cannot replace the handler (`proroot_tramp_rt_sigaction`,
the `sigaction_guard` trace points).
- The raw `rt_sigprocmask` that glibc makes internally, for example `pthread_create` blocking
every signal, goes through a patched svc site. The stub loader and the runtime both compare
against syscall 135.
4. **Android-blocked syscalls are answered in-process.** The stub loader dispatches
`set_robust_list`, `rseq`, `faccessat2`, `clone3`, `futex_waitv` and `seccomp`. The runtime
emulates SysV shm (`emu_shm*`), `set*id`/`get*id` under `-0`, and `brk`
(`emulate_guest_brk`, over a reserved mapping).
## Compared with DroidDeck
| | DroidDeck (proot + 0001–0018 + `libblfastpath.so`) | proroot |
|---|---|---|
| exec, `PT_INTERP`, `/proc/self/exe` | proot's loader under ptrace, 0.4–0.8 ms per exec | Its own loaders, with no tracer; also needs its own ld.so with a glibc offset table |
| path calls through libc wrappers | fast path, about 0.6–1.9 µs | runtime hooks |
| path calls from glibc internals (ld.so, fts, realpath, nss, `__open_nocancel`) and raw `svc` | **still go to proot (15–60 µs)** | **patched svc sites** |
| Android-blocked syscalls (`set_robust_list`, `faccessat2`, `clone3`, ...) | SIGSYS stop answered by proot (0016 etc.), one ptrace round trip and one signal round trip each | in-process |
| `brk` | proot emulation, a trap per call (mitigated by `top_pad`) | in-process emulation |
| correctness fallback | proot is always there | limited in-process seccomp/SIGSYS handling; no general tracer fallback, so calls outside the filter can run unconfined or be emulated incorrectly |
| long Unix socket paths | fast path `/proc/self/fd/N/name` aliases | short socket aliases (`proroot_create_short_unix_socket_alias`) |
| rseq | `GLIBC_TUNABLES=glibc.pthread.rseq=0` | trampoline |
proroot is not a model for replacing proot. It has no tracer to fall back on, so a missed call
site or an unexpected glibc build silently breaks isolation or correctness. Its own linker depends
on glibc internals for each version. Proton, Wine, FEX and Steam's self-updating ELFs are a much
wider surface than the Node, Python and Chromium workloads proroot was tested on. Its value for
DroidDeck is as a fast path *in front of* proot.
## What is worth taking
1. **Patch glibc's svc sites from `libblfastpath.so`'s constructor.** This is the largest gain
and the cheapest way to do option 6 in [proot-performance](proot-performance.md) ("a proot-aware
glibc") without rebuilding glibc.
- For `libc.so.6` (and `ld-linux-aarch64.so.1` for runtime `dlopen`), rewrite each `svc #0`
that follows a recognised `mov x8, #nr` for the path syscalls the fast path already handles.
The rewrite is a `b` to a relay that calls the existing translator.
- The relay issues the syscall from the `0xffff00000` trampoline page, which 0014 already lets
through. Anything the translator declines is re-issued from an svc in the relay page, outside
the trampoline, so proot traps it exactly as it does today. Correctness still rests on proot.
- This covers fts (`find` over 2.7k files, unchanged today), realpath, nss, `__open_nocancel`,
and `dlopen` after start-up.
- Library loading at start-up, before the constructor runs, still traps.
2. **Answer the Android-blocked syscalls through those relays.**
- `set_robust_list` and `get_robust_list`: keep the head in TLS, as 0016 already does in
proot.
- `faccessat2`: answer `ENOSYS`, or translate it when flags are 0, as the wrapper does.
- `clone3`: answer `ENOSYS` before Android 15, so glibc falls back to `clone`.
- `futex_waitv`: droiddeck-fsync already handles this.
- Each one removes a SIGSYS stop plus a ptrace round trip, about 30–50 µs. `set_robust_list`
alone is one per thread, which matters for Steam/CEF and Wine thread churn.
3. **The `/proc/self/mem` write as a fallback for patching.** If the app domain refuses
`mprotect(PROT_WRITE|PROT_EXEC)` on rootfs (`app_data_file`) text, i.e. an `execmod` denial,
a write through `/proc/self/mem` makes the page copy-on-write without an `mprotect`. That page
is never writable and executable at once. Check this on the Thor before relying on it. The
same question is still open for the trampoline page (`execmem`).
4. **Keep SIGSYS unblocked if in-process `SECCOMP_RET_TRAP` is ever used.** Strip `SIGSYS` in the
`sigprocmask`/`pthread_sigmask`/`rt_sigprocmask` paths, and keep the handler installed while
chaining the guest's. This only becomes safe once item 1 covers glibc's internal
`rt_sigprocmask`. It is a prerequisite, not a recommendation to switch.
5. **Cache patch sites by build-id.** proroot rescans each image on every exec and defers patching
for most programs to keep exec cheap. A scan of libc's roughly 1.5 MiB of text is cheap, but a
per-build-id site table, written once in `/tmp` by the fast path, would make it free.
Not worth taking: the cleanroom ld.so and its glibc offset table; the userland exec loader (proot
already does this); the fake DRM/GBM/libseat device (DroidDeck has its own compositor path);
netlink and SysV shm (`netif.c` and `sysv.c` already cover these); and the long-socket aliasing
(the fast path covers it).
## Open questions before prototyping item 1
- Does the app domain allow `mprotect(RWX)` on a private mapping of an `app_data_file`? Does a
`/proc/self/mem` write work under the app's SELinux context and proot's own `ptrace` attach?
`/proc/self/mem` writes need `PTRACE_MODE_ATTACH` on self, which is always allowed.
- How many `libc.so.6` path syscall sites fall outside a recognisable `mov x8, #nr` window? For
example, `syscall()` takes the number in a register, which needs the existing `syscall()` hook.
- Patched pages become private copies, about 4 KiB per patched page per process. Measure RSS
across the Steam/CEF tree.
- Equivalence: run `bench/equiv.py` plus a `find`/`realpath`/nss workload with `PROOT_FP_STATS`.
Compare the trap counts from patch 0018 before and after.
## First implementation and Thor validation (2026-10-27)
`tools/proot/fastpath/svc-patch.h`, included by `fastpath.c`, implements the first
slice of item 1. It runs automatically in fresh processes using the replacement
`libblfastpath.so` when the ordinary fast-path configuration and tracer-key check
succeed. Set `PROOT_FP_PATCH_SVC=0` to disable it for troubleshooting or comparisons;
`PROOT_FP_PATCH_SVC=1` also explicitly enables it. It skips processes that already have multiple threads,
and declines SVE/SME hardware because the relay preserves the base ARM64 register state.
The scanner visits executable segments of the loaded `libc.so.6` and
`ld-linux-aarch64.so.1`. It only patches `openat` and `newfstatat` sites with an
unshifted `movz x8/w8, #nr` within the preceding eight instructions. Intervening
instructions must belong to a small allow-list of argument moves/sign-extension,
immediate moves, stack loads/stores and NOPs that leave x8 unchanged. Branches,
calls, x8 writes and unknown instructions stop recognition. This includes libc's
non-adjacent O_CREAT sequences. Register-number dispatchers and other syscall
numbers remain under PRoot. No glibc version offsets, proroot code, or modified
proroot binaries are used.
Each replacement is a four-byte `b` into a nearby relay. Relay pages are filled while
writable, then changed to RX before publishing any branch. Text writes use
`/proc/self/mem`; failure leaves the site unpatched. The relay preserves x1–x30, all
32 SIMD registers, NZCV, FPCR/FPSR and the caller's `errno`, returning a raw kernel-style
result in x0. It calls the existing path translator, using the existing allowed
trampoline for translated calls. Declined and recursive calls execute an ordinary
`svc` in this library, where PRoot still intercepts them. No SIGSYS handler or new
seccomp filter is installed. `PROOT_FP_STATS=1` adds `fastpath-svc` exit counters.
The connected AYN Thor was running runtime r9, glibc 2.43, with a 4 KiB page size in
`u:r:untrusted_app_27:s0`. `bench/svc-probe.c`, run through the app's guest bridge,
confirmed all of the following while PRoot was attached:
- An RX private mapping of the rootfs libc accepted `mprotect(RWX)`.
- `/proc/self/mem` accepted a changed byte in that RX mapping; readback and restoration
succeeded, and the backing file stayed unchanged.
- An anonymous RW mapping could be changed to RX.
- libc contained 415 `svc #0` sites: 327 with an adjacent number load, 76 with a
number load only within the preceding eight instructions, and 12 with neither.
The linker contained 56 sites, 45 adjacent and 11 nearby-only. Nearby counts are
scan statistics, not proof that the number remains live at the syscall.
The initial adjacent-only scanner patched nine sites; the final scanner patched
14, including file-creation paths, across libc and the linker. It used two relay
pages in standalone validation processes. `bench/svc-check.c` exercises the
actual emitted relay and checks raw success/error results, errno, x1–x30, q0–q31,
NZCV, FPCR/FPSR, four simultaneous threads, the multi-thread patching guard, and fork.
Null arguments and unsupported flags fall back to PRoot. The instruction decoder
and exact ±128 MiB branch limits also have a host regression test.
Default-policy validation on the Thor confirmed that an unset `PROOT_FP_PATCH_SVC`
and explicit `1` both patched 14 sites; explicit `0` left all 415 libc and 56 linker
syscall sites unchanged. The register/thread/fork check also passed with the
environment flag unset.
Five alternating pairs of `bench/svc-workload.c` runs compared the same replacement
library with patching off/on, with fast-path stats enabled in both. The workload
gets `fstatat` and `__open64_nocancel` directly from libc, bypassing the preload's
public wrappers, and makes 5,000 of each call against a prepared regular file:
| median | wrappers only | svc patching |
|---|---:|---:|
| internal `fstatat` | 38.6 µs | 3.0 µs |
| internal open + close | 39.3 µs | 5.8 µs |
| voluntary context switches over both loops | 10,000 | 0 |
### SD allocation and writes
`bench/svc-storage.c` separates the operations relevant to Steam downloads. Three
alternating pairs ran on internal `/tmp` and the selected `/mnt/droiddeck-sd` library,
with Steam idle and no simultaneous local Steam download. Each fresh directory held 64 long-named files
extended to 256 KiB, followed by 1,000 libc-internal stats and a 64 MiB sequential
write followed by `fdatasync`. Both modes used the same replacement library; only
`PROOT_FP_PATCH_SVC` changed. Medians on SD were:
| phase | wrappers only | svc patching |
|---|---:|---:|
| create/extend/close 64 files | 1.500 s | 1.486 s |
| 1,000 internal stats | 61.2 ms | 5.4 ms |
| 64 MiB write calls | 43.9 ms | 40.9 ms |
| final `fdatasync` | 2.514 s | 2.539 s |
Internal allocation fell from 7.1 ms to 1.9 ms; internal stats fell from 39.5 ms
to 2.5 ms. Internal `fdatasync` varied from 36 to 164 ms across individual runs.
The patched SD workload recorded 1,065 internal calls handled in-process, covering
64 file creations, 1,000 stats and the streaming-file creation. Per-phase medians
are independent and should not be added as a median whole-run duration.
The SD metadata gain does not establish faster Steam downloads. File creation
improved by only a few percent, and write/flush speed did not improve in this probe.
The remaining SD cost is much larger than the saved syscall-interception time.
The earlier [Thor SD investigation](thor-sd-storage-investigation.md) likewise
identified native exFAT metadata waits; the current benchmark does not independently
attribute those waits to a particular mount flag. A real Steam install comparison
must separate preallocation, transfer/staging and final commit before claiming an
end-to-end improvement.
### Real Steam downloads to SD
Four fresh installs of owned, initially uninstalled **7 Billion Humans** (792100)
used library folder 1, `/mnt/droiddeck-sd`, and were uninstalled between trials.
Each downloaded 228,935,584 bytes and staged 237,717,350 bytes in 19 files, ending
at BuildID 8016557, depots 792101/5052600457178655633 and
792104/8245917369753676198. Every trial logged zero reused/stored/delta bytes at
the start and completed with `No Error`. Existing installed games were retained.
The repeat off/on pair used the exact same replacement library, SHA-256
`ab605c021aee271cd49fa1cb337d7ff0c762dbac198b711e9818639c0cd4b17d`.
The first off run used the earlier adjacent-only build, with patching disabled.
Only the patching environment flag changed for the final pair. Times below come
from Steam's one-second-resolution `content_log.txt`; total starts at Reconfiguring
and ends at scheduler completion, excluding session startup:
| trial | patching | preallocate | download/stage | commit to completion | total |
|---|---|---:|---:|---:|---:|
| first baseline | off | 1 s | 123 s | 1 s | 135 s |
| first patched | on | <1 s | 47 s | 1 s | 50 s |
| repeat baseline | off | <1 s | 30 s | 1 s | 33 s |
| repeat patched | on | <1 s | 29 s | 2 s | 32 s |
Reconfiguration accounts for the remaining total time. The first baseline
overlapped another Steam client's network download; that client's telemetry must
not be mistaken for the Thor's. Later samples were filtered to local client `0`.
The repeat pair reached similar network rates, roughly 7–8 MB/s while transferring.
All four attempts logged the same unsupported large-file preallocation retry.
**This does not demonstrate a useful SD-download speedup.** The apparent initial
135→50 second gain disappeared when baseline was repeated. The final 33 versus
32 seconds is within this small experiment's timing/network variability. This
19-file title also does not settle performance for games with thousands of loose
files. Metadata calls clearly improve, while SD creation/writeback remain the
stronger next targets. No network settings, SD mount flags or root privileges
were changed for these tests.
The internal-call equivalence workload, including fts, realpath, reentrant NSS,
runtime dlopen, missing paths and fallback errors, matched `PROOT_FP_OFF=1` at both
the default parent-cache TTL and TTL 0. The existing `equiv.py` also matched after
normalizing random/thermal read payloads to their lengths, volatile PID values in
the `/proc` directory listing, and tolerating Android's
denied `/dev` directory read. Its root fixtures were relocated into a temporary tree.
`equiv2.py` used temporary root/SD fixtures, normalized `/proc/<self-pid>` output,
and tolerated the SD filesystem's unsupported symlink creation. Its patched output
matched the wrapper-only output at both TTLs. **It did not fully match PRoot:**
binding a Unix socket in the selected SD bind returned EPERM with the existing
wrappers, whereas PRoot succeeded. This mismatch reproduced with svc patching off;
it is a separate existing fast-path socket issue. The suite is not a clean full
equivalence pass. `equiv3.py` was not run because it rewrites live NSS configuration.
A fresh Steam session using the override and `PROOT_FP_PATCH_SVC=1` rendered its
library UI. Sonic Mania (584400) gained focus and rendered its title screen. This
is startup smoke coverage, not gameplay or a Steam startup-speed measurement.
The installed PRoot pack emitted no profiling start/counter records despite the
queued profiling setting; the profiler report had `hasCounters: false`. That is a
measurement gap, not evidence of zero remaining traps.
### Expanded relay coverage (before the safety follow-up)
The subsequent revision keeps patching enabled by default and shares the existing
wrapper translators with 20 path syscall numbers: openat, newfstatat, statx,
readlinkat, faccessat, mkdirat, unlinkat, renameat, renameat2, symlinkat, fchmodat,
utimensat, truncate, statfs, getxattr, lgetxattr, listxattr, llistxattr,
inotify_add_watch and getcwd. This is an allowlist of safely recognized sites, not
a claim that every glibc implementation contains every site. Unsupported paths,
flags, instructions and inaccessible pointers still use the original PRoot route.
Input/output copies use process_vm_readv/writev rather than dereferencing arbitrary
guest pointers. The device matrix checks error priority, protected buffers and a
NUL-terminated path ending at a page boundary.
The app forwards its Android SDK as `PROOT_FP_ANDROID_API`. With a known SDK,
set_robust_list retains the head in TLS and returns ENOSYS, matching patch 0016;
self get_robust_list uses that head. Uncaptured heads and other TIDs fall back to
PRoot. This does not implement kernel robust-mutex owner-death recovery. faccessat2
returns ENOSYS for glibc's fallback. clone3 returns ENOSYS only before API 35;
it is never executed from the C relay, since successful clone3 would change the
child's stack. The [Android 14 allowlist](https://android.googlesource.com/platform/bionic/+/refs/heads/android14-release/libc/SECCOMP_ALLOWLIST_COMMON.TXT)
omits clone3 and the [Android 15 allowlist](https://android.googlesource.com/platform/bionic/+/refs/heads/android15-release/libc/SECCOMP_ALLOWLIST_COMMON.TXT)
includes it. Unknown platforms leave these sites untouched. Existing droiddeck-fsync
handling of futex_waitv is unchanged.
Build-ID tables in `/tmp/.droiddeck-svc-v1-<api>-<build-id>` cache relative site
offsets. Every hit revalidates executable-segment bounds, alignment, the current
SVC opcode and the recognized syscall number. Missing, malformed, truncated,
overly permissive or symlinked tables trigger a rescan; writes use a private
temporary file and atomic rename. Images without a readable GNU build-ID still
scan normally. `PROOT_FP_SVC_CACHE=0` disables caching for comparison. Changes to
the accepted instruction/syscall set must bump the cache version.
On the Thor's glibc 2.43 / Android 13, 49 sites patch across libc and the loader.
Warm cached discovery took 60–63 microseconds in two samples versus roughly
0.6–0.7 milliseconds for the earlier uncached scan; patch publication took about
0.28 milliseconds. These are constructor phases, not whole Steam startup times.
Five alternating expanded-library pairs measured median internal stat at 39.5→4.9
microseconds and open/close at 41.2→6.4 microseconds, with 10,000→0 voluntary
context switches over both loops. The earlier SD/download tables above describe
the initial 14-site revision and must not be attributed to this expanded build.
Five alternating pairs of `svc-threads` additionally measured thread create/join
at 138→113 microseconds, libc faccessat at 51.6→14.7 microseconds, and libc getcwd
at 46.8→4.1 microseconds. Each run creates 128 threads and executes 2,000 calls
to each libc entry point, bypassing the exported preload wrappers with dlsym.
The access call includes glibc's faccessat2 fallback.
Repeated `/usr/bin/true` launches expose the startup tradeoff. Five batches of
40 children per mode measured medians of 3.834 ms with wrappers only, 4.882 ms
with uncached patching and 4.731 ms with cached patching, including subprocess
launch/wait and enabled exit statistics. Discovery across the 200 launches per
patched mode fell from a median 496 to 59 microseconds; publishing patches took
261/267 microseconds. The cache removes scanning work, but constructor setup and
patching still cost time for very short programs. No overall exec speedup is claimed.
Three alternating storage pairs with the expanded library measured:
| SD phase | wrappers only | expanded relays |
|---|---:|---:|
| create/extend/close 64 files | 1.556 s | 1.514 s |
| 1,000 internal stats | 73.2 ms | 12.5 ms |
| 64 MiB write calls | 54.2 ms | 55.1 ms |
| final fdatasync | 2.799 s | 2.730 s |
These phase medians do not establish a general write-speed improvement. Internal
allocation was 7.1→3.6 ms and internal stats 49.8→7.7 ms; the SD filesystem's
allocation and flush waits remain much larger than the interception savings.
### Expanded-build Steam SD comparison
Owned, initially uninstalled Half-Life (70) supplies a larger file tree: 4,525
installed files / 589,603,955 bytes, BuildID 15961492. Each fresh trial initially
scheduled 294,238,640 download bytes, 589,603,955 staged bytes and 4,488 preallocated
files on `/mnt/droiddeck-sd`. Steam reported successful installation in every run.
Local client `0` telemetry was selected. Times use one-second content-log timestamps;
total runs from the first main-app Reconfiguring event to scheduler completion.
| trial | patching | initial preallocate | transfer/stage window | final commit | total |
|---|---|---:|---:|---:|---:|
| first baseline | off | 90 s | 52 s | 204 s | 350 s |
| expanded, default setting | on | 94 s | 48 s | 184 s | 326 s |
| repeat baseline | off | 97 s | 69 s | 175 s | 341 s |
The patched and repeat-baseline trials use the same final library SHA-256
`af4f66680dcfbd5002f641ffe206cdc7bd89400be169d3ef21c4e0ee7f979589`.
The first baseline used the preceding build with patching disabled; the only
subsequent production change corrected explicitly cleared robust-list TLS state.
All initial download records showed zero stored/reused/delta bytes. Shader updates
interrupted the main download in each trial; the transfer window includes those
pauses. On the repeat baseline, reconfiguration retained two small files already
downloaded during that same trial, so the final resumed job scheduled 294,236,672
download / 589,599,865 stage bytes and committed 4,572 entries rather than 4,574.
This is not pre-existing payload reuse; the earlier fresh schedule is retained
in the measurement records.
The observed whole-install difference does not establish a reliable SD speedup:
the repeat baseline committed faster than the patched run, while its transfer
window was slower. Allocation also did not improve. The 326 versus 341–350 second
totals combine network, shader scheduling and SD variability. The syscall gains
are demonstrated independently; these samples do not show that they fix Steam's
SD allocation/commit bottleneck. The test title was removed between trials; an
interrupted first uninstall left a repair queue, which was cleared by removing
only that task-created title while Steam was stopped before the subsequent fresh
trial. Existing installed games were retained.
The expanded ABI matrix passes raw return values, errno, all x1–x30 and q0–q31,
NZCV and non-default FPCR/FPSR, four concurrent threads with distinct robust heads, fork, 100
signals on an alternate stack, deferred cancellation, cancellation/cleanup of a
blocked libc FIFO open, clearing/restoring a robust head, and 32 thread create/join
cycles. Constructor patching still refuses a process with multiple live threads.
Host tests exercise corrupted cache entries, invalid offsets/opcodes, mismatched
API/version, unsafe file modes, symlinks and truncation. The Android unit test
checks API forwarding. The existing preload/agent selection passed 79 tests with
two skips before the cache regression test was added.
API-selection probes patch 45 sites with an unknown SDK, 49 with API 33 and 48
with simulated API 35; unset and explicit 1 agree, and explicit 0 leaves the
original sites intact. This does not substitute for testing on Android 15 hardware.
CI at 40b7c480 passed 1,427 Python/native tests (49 skips), 2,630 Android tests and
162 Rust host tests, plus APK compilation. A local release APK built successfully,
passed runtime-payload/native-library checks and was signed with the installed
release certificate. The full local Windows JVM run reported 150 failures / 2,568
tests (eight skips), including Unix-path, symlink and permission assumptions;
the four ProotFastPath tests passed in both local variants. The passing full
suite evidence is the Linux CI run, not a clean Windows full-suite result.
Internal fts/realpath/NSS/dlopen and the normalized first equivalence suite still
match PRoot at both cache TTLs. The write suite still matches wrapper-only output
and reproduces the same existing SD Unix-socket mismatch described above.
No in-process RET_TRAP filter is installed, so the proposed SIGSYS mask/handler
machinery is not applicable. Startup loader traps before the constructor and
raw calls in arbitrary guest ELFs remain outside the patch scope. Additional
glibc builds, Android versions, unwind behavior, Steam/CEF tree RSS and matching
patch-0018 tracer measurements remain coverage gaps.
Build the tools with the same ARM64 glibc toolchain as the fast path:
```sh
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -pthread \
-o svc-check tools/proot/bench/svc-check.c -ldl
aarch64-linux-gnu-gcc -O2 -Wall -Wextra \
-o svc-probe tools/proot/bench/svc-probe.c -ldl
aarch64-linux-gnu-gcc -O2 -Wall -Wextra \
-o svc-workload tools/proot/bench/svc-workload.c -ldl
aarch64-linux-gnu-gcc -O2 -Wall -Wextra \
-o svc-storage tools/proot/bench/svc-storage.c -ldl
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -pthread \
-o svc-threads tools/proot/bench/svc-threads.c -ldl
```
Run `svc-probe` inside the app's guest environment, not from `adb shell`.
`svc-check` embeds the fast path and requires its normal enabled tracer environment.
For that embedded-library check, start with PROOT_FP_PATCH_SVC=0 when the session
also preloads a fast-path library (including through /etc/ld.so.preload). The check
then enables its own copy at main before creating threads, keeping another copy
from owning the glibc patch sites. The other tools use the normal preload.
For `svc-workload`, pass a prepared directory containing `file` and a `link` symlink
to it; add any second argument to enable timing. Use the documented library override
workflow in [proot-performance](proot-performance.md) for a fresh session. No extra
environment setting is needed; use `PROOT_FP_PATCH_SVC=0` for the unpatched comparison.
`svc-storage` takes a new, unused directory name; it creates and removes its own test
files and directory. It writes 64 MiB plus 16 MiB of file extensions per run.
### Safety follow-up (2026-10-28)
Path patching remains enabled by default. Robust-list registration/query sites are
now deliberately excluded: a device regression test reproduced disagreement
between the relay's private TLS head and an unpatched raw get_robust_list call in
the preceding implementation. Both directions now use the existing PRoot/kernel
route, including cleared heads. This preserves the host's actual return policy:
the installed Thor runtime accepts set_robust_list with zero, whereas the removed
emulation returned ENOSYS. PRoot patch 0016 can instead return ENOSYS when Android
blocks registration; neither policy is replaced by private relay state.
The build-ID cache is version 2 because the accepted syscall set changed. The
current glibc 2.43/API-33 build patches 47 sites rather than 49. faccessat2 and
pre-Android-15 clone3 fallback acceleration remain; droiddeck-fsync is unchanged.
The earlier 138-to-113-microsecond thread result belongs to the retired robust-list
implementation and must not be claimed for the current code.
Relays now save the original post-SVC program counter and supply unwind metadata
for the saved caller registers. Device tests force an unwind from inside the
translator through a patched libc frame and verify caller cleanup. A signal handler
also exits with siglongjmp; a later call recovers the abandoned recursion guard
and resumes acceleration. These tests supplement deferred and blocked-FIFO
cancellation; they are not a claim of arbitrary asynchronous-cancellation safety.
Compiler stack-usage output identified multiple nested PATH_MAX-sized frames.
Before entering them, a small dispatcher checks the active alternate signal stack
and cached writable stack mapping. Alternate-stack calls and calls with less than
96 KiB remaining use PRoot. Main-stack growth respects the current RLIMIT_STACK
and leaves space above the preceding mapping. The implementation adds only a few
TLS words, not a large private translation stack. Tests cover a restricted thread
stack, normal/alternate-stack signals, main-stack growth and a reduced/unavailable
stack limit. User-managed stacks and arbitrary mid-helper non-local exits remain
broader compatibility risks, not proven consequence-free cases.
On Thor/Android 13, the embedded and shared-PIC matrices pass on glibc 2.43;
the shared-PIC matrix also passes with a separately loaded glibc 2.39. They cover register/FP/errno preservation, mixed raw
and relay robust calls, pointer and page boundaries, readlink buffers of target
length minus one through plus two, thread churn, fork, signal/non-local exits,
forced unwinding and limited stack space. Readlink preserves PRoot's existing
translated-link length behavior; bytes beyond the reported payload are unspecified.
Test-process seccomp filters separately deny opening /proc/self/mem, nearby relay
mappings, executable mprotect and patch writes. All four device cases leave zero
patched sites and a working original libc syscall. Host injection additionally
checks that one failed site write permits other sites to install. Concurrent
atomic symlink replacement passes 3,000 internal stat/readlink iterations at both
zero and default cache TTLs. These are bounded tests; they do not prove every
possible filesystem race or reproduce a real SELinux execmod denial.
Five new alternating pairs measured:
| operation | wrappers only | hardened relays |
|---|---:|---:|
| libc-internal stat | 50.1 us | 5.9 us |
| libc-internal open/close | 51.9 us | 7.1 us |
| libc faccessat | 52.0 us | 20.2 us |
| libc getcwd | 51.7 us | 4.6 us |
| thread create/join | 129 us | 144 us |
| complete tiny exec/wait | 5.04 ms | 5.96 ms |
The metadata gains survive the safety checks. This run shows no thread-creation
gain, and the roughly 0.9 ms tiny-exec cost remains. The earlier SD download and
flush results are historical measurements of the preceding build; no new claim
that SD media writes or whole Steam installs become reliably faster follows from
these syscall results. Android 15+ ARM64 and 16 KiB-page hardware remain untested.
Three alternating pairs also measured session start through the Steam Big Picture
Home page becoming ready, using its DOM/Recent Games content rather than merely
the compositor's first frame. Off runs took 48.76/43.47/47.02 seconds; on runs took
43.43/45.25/50.40 seconds. The 47.02-to-45.25-second medians sit within overlapping
run-to-run variation and do not establish a reliable whole-client startup win.
These use the signed bundled-library build without overrides; the final stack-gap
guard only increases the reserved distance above other mappings.
At Home-ready plus 20 seconds, three one-second-spaced process-memory samples per
run gave Steam/CEF-only median PSS of 1,223.1 MiB off and 1,233.9 MiB on. Including
their active Python/Wine descendants gave 1,243.7/1,254.6 MiB. The five Steam/CEF
processes were selected by executable name; descendants were included by parent
PID. Per-run Steam/CEF medians ranged 1,217.9–1,240.9 MiB off and
1,194.8–1,244.9 MiB on. The roughly 11 MiB median increase is smaller than this
variation, but it is not evidence of zero memory cost. PSS avoids counting shared
pages in full for each process. Startup and memory comparisons used one unchanged
APK; no downloads or games were initiated during them.
CodeRabbit follow-up: the workload now compares canonical paths, so relative and
absolute fixture arguments agree. All SVC bench tools keep their checks active
under NDEBUG; their clock, syscall and thread operations cannot silently disappear.
Both cases were rebuilt with -DNDEBUG and checked on Thor. The memory-file-denial
test now blocks only O_RDWR opens and asserts the single-thread check still works,
so it reaches the intended /proc/self/mem failure. The initial proroot comparison
also distinguishes its limited in-process fallback from a general tracer.
The request to return to default-off was addressed through the interruption/unwind
fixes and tests while retaining the requested default. The proposed readlink count
change was not applied because exact boundary tests reproduce the current PRoot
behavior; changing that inherited policy belongs in a separate correctness change.
+61
View File
@@ -0,0 +1,61 @@
# Steam startup failures on older CPUs and non-Adreno GPUs
These are different failures, even when neither reaches the Steam interface.
## Steam exits with SIGILL (#1376)
The [Redmi Note 8 report](https://github.com/Droid-Deck/DroidDeck/issues/1376)
shows gamescope selecting Adreno 610 successfully, all 17 client parts being
downloaded, and the native Steam executable immediately exiting with status
132 (`Illegal instruction`). The failure occurs after installation, not during
the runtime download. The supplied logs do not identify the faulting program
counter or CPU feature flags, so they cannot establish the exact instruction.
The official ARM64 Steam client and web helper inspected during this
investigation contain LSE atomic instructions. This is a compatibility concern
for CPUs without LSE, not proof that LSE caused this particular crash. Device
reports now include only the kernel's CPU `Features` lists, without unrelated
`/proc/cpuinfo` fields such as serial numbers.
After SIGILL, the failure screen explains the signal and, for an ARM64 client,
points to **Steam settings → Steam client → x86-64 (experimental)**. This is an
explicit user choice with an additional download and emulation overhead. It
does not establish that the device can run every component or game.
The x86-64 client normally reuses a matching-build native ARM web helper.
When CPU feature flags explicitly lack `atomics`, it now retains the existing
x86 web helper instead. Otherwise the fallback could re-enter native code
containing the same instruction class. All reported core feature lists must
include that exact flag; absent or unreadable feature data retains the prior
behavior. Explicit x86-helper selection and the client-build matching rule
remain unchanged.
## gamescope cannot find a Vulkan device (#1368)
The [MT6993 report](https://github.com/Droid-Deck/DroidDeck/issues/1368) shows a
non-Adreno device starting with an Adreno Turnip display driver, followed by
gamescope failing to find a physical device through the Linux freedreno ICD.
Steam has not been started in that trace.
Automatic Android display-driver selection now leaves non-Adreno GPUs on the
system driver rather than choosing Turnip from the Android SDK version. An
Adreno GPU with an unknown model still uses the existing SDK fallback; Quest,
external overrides and manual selections retain their priority. The failure
screen distinguishes an unavailable Linux Vulkan device from a failed Steam
download.
This does not implement MT6993/Mali graphics support. The Linux session needs
a driver for that GPU and kernel, and the Android compositor also has Vulkan
requirements. The system Android driver alone does not provide the Linux
driver; the desktop's software rendering does not replace the outer
compositor. Removing the unsupported-device notice or importing Adreno
Turnip cannot supply these missing components.
## Verification boundary
Regression tests cover actual automatic driver selection, log classification
and the x86 client's web-helper selection. The supplied session logs can be
replayed through the classifier. No target phone was available, and the
specific ARM64 instruction fault has not been reproduced under a debugger.
Neither report should be treated as verified fixed on hardware based on these
tests alone.
+33 -11
View File
@@ -3,10 +3,15 @@
#include <pulsecore/core-rtclock.h>
#include <pulsecore/core-subscribe.h>
#define ANDROID_VOLUME_IDLE_MS 100
#define ANDROID_VOLUME_ACTIVE_MS 16
#define ANDROID_VOLUME_ACTIVE_TICKS 40
struct android_volume {
pa_sink *sink;
char *directory;
pa_time_event *timer;
unsigned active_ticks;
};
static bool android_volume_read(const char *directory, unsigned *level, unsigned *maximum, unsigned *muted) {
@@ -57,22 +62,39 @@ static void android_volume_refresh(pa_mainloop_api *api, pa_time_event *event, c
char *processing = pa_sprintf_malloc("%s.processing", request);
char *mute_processing = pa_sprintf_malloc("%s.processing", mute_request);
if (access(request, F_OK) != 0 && access(mute_request, F_OK) != 0 &&
access(processing, F_OK) != 0 && access(mute_processing, F_OK) != 0 &&
android_volume_read(bridge->directory, &level, &maximum, &muted)) {
pa_cvolume volume;
if (bridge->sink->n_volume_steps != maximum + 1) {
bridge->sink->n_volume_steps = maximum + 1;
pa_subscription_post(bridge->sink->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, bridge->sink->index);
access(processing, F_OK) != 0 && access(mute_processing, F_OK) != 0) {
if (android_volume_read(bridge->directory, &level, &maximum, &muted)) {
pa_cvolume volume;
bool changed = false;
if (bridge->sink->n_volume_steps != maximum + 1) {
bridge->sink->n_volume_steps = maximum + 1;
pa_subscription_post(bridge->sink->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, bridge->sink->index);
}
pa_cvolume_set(&volume, bridge->sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum);
if (!pa_cvolume_equal(&volume, &bridge->sink->real_volume)) {
pa_sink_volume_changed(bridge->sink, &volume);
changed = true;
}
if (bridge->sink->muted != !!muted) {
pa_sink_mute_changed(bridge->sink, !!muted);
changed = true;
}
if (changed) bridge->active_ticks = ANDROID_VOLUME_ACTIVE_TICKS;
}
pa_cvolume_set(&volume, bridge->sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum);
if (!pa_cvolume_equal(&volume, &bridge->sink->real_volume)) pa_sink_volume_changed(bridge->sink, &volume);
if (bridge->sink->muted != !!muted) pa_sink_mute_changed(bridge->sink, !!muted);
} else {
bridge->active_ticks = ANDROID_VOLUME_ACTIVE_TICKS;
}
pa_xfree(request);
pa_xfree(mute_request);
pa_xfree(processing);
pa_xfree(mute_processing);
pa_core_rttime_restart(bridge->sink->core, event, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC);
/* A held volume key steps Android every ~50 ms; sampling at 100 ms hands Steam uneven multi-step jumps. */
unsigned delay_ms = ANDROID_VOLUME_IDLE_MS;
if (bridge->active_ticks) {
bridge->active_ticks--;
delay_ms = ANDROID_VOLUME_ACTIVE_MS;
}
pa_core_rttime_restart(bridge->sink->core, event, pa_rtclock_now() + delay_ms * PA_USEC_PER_MSEC);
}
static struct android_volume *android_volume_new(pa_sink *sink, const char *directory) {
@@ -90,7 +112,7 @@ static struct android_volume *android_volume_new(pa_sink *sink, const char *dire
pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels);
pa_sink_set_set_volume_callback(sink, android_volume_set);
pa_sink_set_set_mute_callback(sink, android_volume_mute);
bridge->timer = pa_core_rttime_new(sink->core, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC,
bridge->timer = pa_core_rttime_new(sink->core, pa_rtclock_now() + ANDROID_VOLUME_IDLE_MS * PA_USEC_PER_MSEC,
android_volume_refresh, bridge);
return bridge;
}
+5 -5
View File
@@ -221,7 +221,7 @@ fi
. "${repo_root}/tools/linuxfs/uruntime.env"
uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime"
install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime"
install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE"
@@ -256,7 +256,7 @@ mkdir -p "${msi_pkgs}" "${msi_dir}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "${package_url}")
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
tar -xJf "${package_archive}" -C "${msi_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt")
for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done
@@ -276,7 +276,7 @@ mkdir -p "${mango_dir}" "${mango_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "${package_url}")
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
@@ -294,7 +294,7 @@ mkdir -p "${pw_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "${package_url}")
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
@@ -303,7 +303,7 @@ pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then
curl -fsSL -o "${pa_tarball}.part" \
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \
https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
mv "${pa_tarball}.part" "${pa_tarball}"
fi
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
set -uo pipefail
cd "$(dirname "$0")/../.."
groups=${PYTHON_TEST_GROUPS:-3}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
index=0
while read -r file; do
module=$(basename "$file" .py)
echo "$module" >> "$work/group-$((index % groups)).list"
index=$((index + 1))
done < <(ls -S tools/tests/test_*.py)
pids=()
for list in "$work"/group-*.list; do
(
PYTHONPATH=tools/tests python3 -m unittest $(cat "$list") > "${list%.list}.log" 2>&1
echo $? > "${list%.list}.status"
) &
pids+=($!)
done
wait "${pids[@]}"
failed=0
for list in "$work"/group-*.list; do
echo "::group::$(basename "$list"): $(tr '\n' ' ' < "$list" | cut -c1-120)"
cat "${list%.list}.log"
echo "::endgroup::"
if [ "$(cat "${list%.list}.status")" != 0 ]; then
failed=1
echo "::error::$(basename "$list") failed"
fi
done
exit "$failed"
+1 -1
View File
@@ -16,7 +16,7 @@ cargo build --locked --release --target aarch64-unknown-linux-gnu
install -m644 target/aarch64-unknown-linux-gnu/release/comet "$out/comet"
zip="$cache/dummy-service.zip"
if ! echo "7fc5facd1fce4d516cd3ce527e7e4dbe0bfd17649cea805e8ea7c37d4ba58d9a $zip" | sha256sum -c - >/dev/null 2>&1; then
curl -fsSL --retry 3 -o "$zip" https://github.com/imLinguin/comet/releases/download/v0.3.2/dummy-service.zip
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$zip" https://github.com/imLinguin/comet/releases/download/v0.3.2/dummy-service.zip
fi
echo "7fc5facd1fce4d516cd3ce527e7e4dbe0bfd17649cea805e8ea7c37d4ba58d9a $zip" | sha256sum -c -
unzip -o "$zip" GalaxyCommunication.exe update-permissions.exe -d "$out"
+2 -2
View File
@@ -3,12 +3,12 @@ set -euo pipefail
if [ -f tools/droiddeck-esync/release.env ]; then
. tools/droiddeck-esync/release.env
release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}"
curl -fsSL --retry 3 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"
echo "$SYNC_BUNDLE_SHA256 sync-bundle.tzst" | sha256sum -c -
mkdir -p app/src/main/assets/droiddeck-esync
tar --use-compress-program=unzstd -xf sync-bundle.tzst -C app/src/main/assets/droiddeck-esync
rm sync-bundle.tzst
curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json"
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o sync-index.json "$release_url/index.json"
revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' sync-index.json)
for id in $revoked; do
if [ -e "app/src/main/assets/droiddeck-esync/packs/$id.tzst" ]; then
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff. Show more