Compare commits

...
Author SHA1 Message Date
Kurt Himebauch ef1221cf05 fix: serialize maintenance and uninstall 2026-10-28 19:21:05 -04:00
Kurt Himebauch 090b87c37c fix: harden native store handoffs 2026-10-28 19:04:31 -04:00
Kurt Himebauch ab7390e844 fix: wait for Steam navigation readiness 2026-10-28 18:37:19 -04:00
Kurt Himebauch ea8feebea7 fix: keep verified Steam navigation 2026-10-28 18:24:46 -04:00
Kurt Himebauch 3ccf8ca01a fix: guard maintenance queue admission 2026-10-28 18:12:58 -04:00
Kurt Himebauch be51429fa4 fix: append itch recovery progress 2026-10-28 18:12:58 -04:00
Kurt Himebauch 3df06f48b7 fix: gate native cleanup before deletion 2026-10-28 18:12:57 -04:00
Kurt Himebauch 48ad5506b6 fix: forward Steam maintenance navigation 2026-10-28 17:50:58 -04:00
Kurt Himebauch 2229dbc0a8 fix: report archive storage accurately 2026-10-28 17:37:20 -04:00
Kurt Himebauch 8858285d13 fix: show store update indicators 2026-10-28 17:32:24 -04:00
Kurt Himebauch 67034e5f3d fix: preserve legacy store maintenance 2026-10-28 17:30:58 -04:00
Kurt Himebauch cd09deddba feat: add store maintenance 2026-10-28 17:30:58 -04:00
Kurt Himebauch aef1f85aa9 ci: run store engine host tests in a parallel job (#1735)
* ci: run store engine host tests in a parallel non-gating job

* ci: harden the store tests job permissions, timeout and exit status
2026-10-28 16:47:42 -04:00
Kurt Himebauch 198f667bf0 feat: add GOG maintenance 2026-10-28 16:10:17 -04:00
Kurt Himebauch 52fa41767c fix: stop stale Android readbacks snapping Steam's brightness slider back (#1731)
* fix: stop stale Android readbacks snapping Steam's brightness slider back during a held stick

* fix: let deploy_fast sign with the release env on macOS and Linux

* fix: honor DROIDDECK_SIGNING_ENV first and cover the env signer in tests

* fix: honor DROIDDECK_SIGNING_ENV first and cover the env signer in tests

* fix: retry held brightness readbacks, use a monotonic hold clock and resolve the signing env path

* fix: resolve the build-tools path before signing changes directory

* fix: pick the newest build-tools numerically and keep the env file from replacing them

* fix: only pick build-tools that have aapt, zipalign and apksigner
2026-10-28 15:25:48 -04:00
Kurt Himebauch 6469a7693c ci: check out without history blobs or the release-note GIFs (#1725) 2026-10-28 13:11:14 -04:00
Kurt Himebauch cd1caf523d Default to Native background behavior and automatic PiP (#1727) 2026-10-28 13:10:08 -04:00
Kurt Himebauch 37e0f30cc6 Reset a game's Wine prefix from Game data (#1724) 2026-10-28 13:09:47 -04:00
Kurt Himebauch 23811147aa Guide the child-process toggle when developer options are off (#1726)
* feat(setup): guide build number and the child-process toggle when developer options are off

* fix(setup): only guide the child-process toggle on devices that have it
2026-10-28 13:01:44 -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
The412Banner 4ef6b53eb0 fix(proton): Windows CPU 0 is the fastest core (#1697)
Wine numbers the Windows CPUs like the host, so Windows CPU 0 was host
core 0, a small core on most Android chips. Games that pin their main
thread to CPU 0 ran it there: GTA IV 32 fps on the AYANEO Pocket FIT,
61 fps once CPU 0 is the fastest core.

droiddeck-game-env hands Wine the game's cores fastest first, from each
core's cpu_capacity (or its top clock). Equal cores keep their order.
Cores picked globally or in a game profile stay the only cores the game
sees, now fastest first; a pick only counts when it narrows the cores.
Games on Proton's own default_cpu_limit list keep their count on the
fastest cores (quoted and unquoted counts); other values such as "P"
are left to Proton. A typed WINE_CPU_TOPOLOGY / PROTON_CPU_TOPOLOGY
still wins, an empty one turns it off for a game, and
DROIDDECK_FASTEST_CORES=0 turns it off. Steam's own Proton runs in
compatdata/0 are left as before.

Builds on maxjivi05's "Windows games see only the cores they are pinned
to" (9d85af75).
2026-10-27 19:07:59 -04: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
kingokksa 4f58230a20 fix(session): look up the launched game without rescanning the library (#1595) 2026-10-27 15:53:31 -04:00
maxjivi05 2d19c31872 fix(release): rename the pin task affinity for variant APKs 2026-10-27 15:50:51 -04:00
Kurt Himebauch c9044a27e3 fix(release): rename pairing guide affinity for variant APKs 2026-10-27 15:16:58 -04:00
maxjivi05 10174c1bd5 fix(manifest): name the pairing guide's task from the application id 2026-10-27 15:16:58 -04:00
Kurt Himebauch da3b8017cb fix(steam): hide duplicate Android volume indicator in Steam sessions (#1689) 2026-10-27 15:00:13 -04:00
Kurt Himebauch e906d2f077 feat(launcher): full launcher Apps page (#1686)
* feat(launcher): apps page with search, sort, filter, folders, widgets and page swipes

* feat(launcher): app shortcuts, pinned shortcuts, hidden apps and LauncherApps listing

* fix(ui): let page content scroll to the bottom edge

* feat(launcher): accept widgets other apps ask to pin

* i18n(launcher): translate apps page strings

* fix(launcher): keep disabled pins, serialize widget adds, add many plurals

* fix(launcher): drop in-flight pin refreshes after unpinning

* fix(launcher): skip unpin when pinned shortcuts can't be read

* fix(launcher): drop in-flight app lists when home role is lost

* fix(launcher): only migrate folder entries with one launcher activity
2026-10-27 14:50:11 -04: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
Kurt Himebauch ef9866e423 fix(input): stop controller rumble when the device sleeps (#1668) 2026-10-27 13:14:23 -04:00
Kurt Himebauch f07dd5eb97 feat(setup): guided Wireless debugging onboarding for the child-process limit (#1682)
* feat(setup): guide wireless pairing from a picture-in-picture window

* feat(setup): share one child-process fix flow between Setup and Play Steam

* fix(setup): read the child-process limit from the settings provider

* fix(setup): re-check the child-process limit while Setup is open

* fix(setup): skip a dead saved pairing and quiet the pairing guide

* fix(setup): handle repeat guide launches and start pairing after the display choice
2026-10-27 12:33:10 -04:00
The412Banner 067dabe81c perf(compositor): screen tick on its own thread, pacing counters (#1678)
The Choreographer frame callback that drives the compositor ran on the
app's main thread, so main-thread work delayed the tick before it
reached the compositor thread. It now runs on a display-priority
HandlerThread with its own Choreographer; the session pref vsyncThread
(default true) switches back to the main thread. Each resume posts a new
callback with its own generation, so one left queued from an earlier
resume, on either thread, stops itself instead of ticking twice.

A new 10 s "pacing" log line reports how late the tick reaches the
compositor, how long a new frame waits to be drawn, game frames against
buffers re-attached after an empty attach, empty attaches and distinct
buffers, and presentation feedback shown, replaced before drawing and
not drawn.
2026-10-27 12:32:15 -04:00
Kurt Himebauch 378beacfac fix(ui): portrait nav highlight drift and blurry Android app icons (#1677)
* fix(ui): keep nav highlight on its tab while the bar scrolls

* fix(ui): render Android app icons at display density
2026-10-27 10:15:05 -04:00
Kurt Himebauch e8bfe0c4e4 fix: hold Home as Steam on Retroid Nova pads (#1674)
* fix: hold Home as Steam on Retroid Nova pads

* fix(input): track Home Guide apart from controller Guide

* fix(input): keep held controls on Home cancel and resume on Home
2026-10-27 10:14:43 -04:00
The412Banner b5cc6dd185 perf(gamescope): skip the repeated window lookup and wake on host events (#1672)
The WSI layer sends override_window_content on every present, and
gamescope walked the X tree to the top-level window (a blocking
XQueryTree round trip per level, under the wlserver lock) before
noticing the same swapchain already overrides it. A swapchain repeating
the same window now skips the walk for 100 ms (0121).

Backport of upstream gamescope 2962992 by Matthew Schwartz: the nested
Wayland backend's input thread reads the host display, but steamcompmgr
does not watch that fd, so buffer releases and presentation feedback
could wait up to one refresh for its next poll; the input thread now
wakes it after each read (0122).

Pins gamescope-3.16.29-p17, the archive that was A/B-tested on the
device. PATCHES.md also describes the p16 change to 0120.
2026-10-27 09:10:53 -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
264 changed files with 28285 additions and 797 deletions

No files matched your search

+85 -11
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:
@@ -45,6 +49,10 @@ jobs:
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
sparse-checkout: |
/*
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Pin and merge the APK source
id: merge
@@ -78,6 +86,10 @@ jobs:
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
sparse-checkout: |
/*
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Merge the pinned APK base
if: github.event_name == 'pull_request'
@@ -132,6 +144,10 @@ jobs:
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
sparse-checkout: |
/*
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Merge the pinned APK base
if: github.event_name == 'pull_request'
@@ -283,6 +299,10 @@ jobs:
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
sparse-checkout: |
/*
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Check human authorship
@@ -404,7 +424,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
@@ -526,13 +546,6 @@ jobs:
git diff --exit-code -- app/src/main/rust/stores/Cargo.lock \
|| { echo "::error::Cargo.lock changed during the build; commit the regenerated lockfile (uploaded as stores-cargo-lock)"; exit 1; }
- name: Store engines host unit tests
timeout-minutes: 10
continue-on-error: true
run: |
cd app/src/main/rust/stores
cargo test --locked 2>&1 | tail -60
- name: Upload the regenerated Cargo.lock
if: failure()
uses: actions/upload-artifact@v4
@@ -622,6 +635,63 @@ jobs:
APK_OUTCOME: ${{ steps.apk-upload.outcome }}
run: bash tools/release/report-build.sh
store-tests:
name: Store engines host tests
needs: source
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ubuntu-24.04
timeout-minutes: 15
continue-on-error: true
permissions:
contents: read
actions: read
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
sparse-checkout: |
/*
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Merge the pinned APK base
if: github.event_name == 'pull_request'
env:
BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
run: |
set -euo pipefail
git fetch --no-tags origin "$BUILD_BASE_SHA"
git config user.name "ci"
git config user.email "ci@users.noreply.github.com"
git merge --no-ff --no-edit FETCH_HEAD
- name: Verify backend and test source match
env:
XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
- name: Rust toolchain
id: rust
run: echo "rustc=$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
- name: Cache cargo registry and the host test target
uses: actions/cache@v4
with:
path: |
~/.cargo/registry/index
~/.cargo/registry/cache
~/.cargo/git/db
app/src/main/rust/stores/target
key: stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-${{ hashFiles('app/src/main/rust/stores/src/**', 'app/src/main/rust/stores/Cargo.toml', 'app/src/main/rust/stores/build.rs') }}
restore-keys: |
stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-
stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-
- name: Store engines host unit tests
timeout-minutes: 10
continue-on-error: true
run: |
set -o pipefail
cd app/src/main/rust/stores
cargo test --locked 2>&1 | tail -60
python-tests:
name: Python and native regression tests
needs: source
@@ -633,6 +703,10 @@ jobs:
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
sparse-checkout: |
/*
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Merge the pinned APK base
if: github.event_name == 'pull_request'
@@ -681,7 +755,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
+9
View File
@@ -286,6 +286,13 @@ if (uvcDir) {
}
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
def stageGogNotices = tasks.register('stageGogNotices', Copy) {
from(layout.projectDirectory.dir('src/main/rust/stores/vendor/xdelta3')) { include 'LICENSE', 'README.droiddeck.md' }
into(layout.buildDirectory.dir('gogNotices/licenses/xdelta3'))
}
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('gogNotices'))
tasks.named('preBuild').configure { dependsOn(stageGogNotices) }
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
mustRunAfter(stageSessionScripts, stageRuntimeAssets)
workingDir rootProject.projectDir
@@ -303,6 +310,8 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
description = 'Cross-compiles the store download engines (libdroiddeckstores.so) with cargo-ndk.'
onlyIf { !skipRust }
inputs.dir(rustCrateDir.dir('src'))
inputs.dir(rustCrateDir.dir('vendor'))
inputs.file(rustCrateDir.file('build.rs'))
inputs.files(rustCrateDir.file('Cargo.toml'), rustCrateDir.file('Cargo.lock'))
inputs.property('ndkVersion', android.ndkVersion)
if (!skipRust) inputs.property('rustToolchain', providers.exec {
+24
View File
@@ -30,6 +30,7 @@
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.CAMERA" />
@@ -81,6 +82,17 @@
</intent-filter>
</activity>
<activity
android:name=".PairingGuideActivity"
android:exported="false"
android:launchMode="singleTask"
android:taskAffinity="${applicationId}.pairingguide"
android:excludeFromRecents="true"
android:supportsPictureInPicture="true"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"
android:theme="@style/AppTheme" />
<activity
android:name=".FrontEndActivity"
android:exported="true"
@@ -146,6 +158,18 @@
</activity>
<activity
android:name=".PinRequestActivity"
android:exported="true"
android:excludeFromRecents="true"
android:taskAffinity="${applicationId}.pin"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.content.pm.action.CONFIRM_PIN_SHORTCUT" />
<action android:name="android.content.pm.action.CONFIRM_PIN_APPWIDGET" />
</intent-filter>
</activity>
<activity
android:name=".input.ControllerEditorActivity"
android:exported="false"
+108 -8
View File
@@ -207,6 +207,7 @@ struct surface {
struct wl_resource *dmabuf;
struct dmabuf_buffer *dmabuf_buf;
struct wl_listener dmabuf_destroy;
const void *last_dmabuf;
int buf_w, buf_h, has_content;
int buf_alpha;
int opaque[4], pending_opaque[4], pending_opaque_set;
@@ -261,6 +262,26 @@ 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, 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;
} g_pace;
static void pace_note_buffer(const void *buffer) {
for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++)
if (g_pace.buffers[i] == buffer) return;
if (g_pace.distinct < PACE_BUFFERS) g_pace.buffers[g_pace.distinct] = buffer;
g_pace.distinct++;
}
static int64_t g_last_vsync_ns;
static int64_t g_tick_vsync_ns;
static int64_t g_refresh_ns = 16666667;
@@ -311,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);
@@ -758,6 +780,9 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
if (!repeat) {
if (!s->dmabuf && s->last_dmabuf == buffer) g_pace.reattaches++;
s->last_dmabuf = buffer;
pace_note_buffer(buffer);
drop_dmabuf(s, 1);
s->dmabuf = buffer;
s->dmabuf_buf = b;
@@ -919,12 +944,15 @@ static void feedback_resource_destroy(struct wl_resource *r) {
wl_list_remove(wl_resource_get_link(r));
}
static void feedback_discard_all(struct wl_list *list) {
static unsigned feedback_discard_all(struct wl_list *list) {
struct wl_resource *fb, *tmp;
unsigned n = 0;
wl_resource_for_each_safe(fb, tmp, list) {
wp_presentation_feedback_send_discarded(fb);
wl_resource_destroy(fb);
n++;
}
return n;
}
static uint32_t nominal_refresh_ns(void) {
@@ -953,6 +981,7 @@ static void feedback_present_all(struct wl_list *list, int64_t t) {
nominal_refresh_ns(), 0, 0,
WP_PRESENTATION_FEEDBACK_KIND_VSYNC);
wl_resource_destroy(fb);
g_pace.presented++;
}
}
@@ -1119,7 +1148,9 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
uint8_t pixel[4];
feedback_discard_all(&s->feedback);
g_pace.replaced += feedback_discard_all(&s->feedback);
if (!buffer) g_pace.null_attaches++;
else if (!db) s->last_dmabuf = NULL;
if (buffer) {
wl_list_remove(&s->pending_buffer_destroy.link);
@@ -2092,14 +2123,23 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) {
unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
static void render_scene(void) {
if (atomic_load(&g_stream_on)) { render_stream(); return; }
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
struct draw_list dl = {0};
struct surface *s;
int w, h;
const int64_t t_scene = now_ns();
int copy = 0;
if (g_dirty_since_ns) {
const int64_t wait = t_scene - g_dirty_since_ns;
g_pace.wait_ns += wait;
if (wait > g_pace.wait_max_ns) g_pace.wait_max_ns = wait;
g_pace.renders++;
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;
@@ -2239,7 +2279,7 @@ static void render_scene(void) {
}
wl_list_for_each(s, &g_surfaces, link) {
if (s->drawn) feedback_present_all(&s->feedback, t);
else feedback_discard_all(&s->feedback);
else g_pace.undrawn += feedback_discard_all(&s->feedback);
}
fire_all_frames();
} else {
@@ -2264,10 +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),
@@ -2281,18 +2336,45 @@ 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++;
if (frame_time_ns > 0 && now >= frame_time_ns) {
const int64_t late = now - frame_time_ns;
g_pace.ticks++;
g_pace.tick_late_ns += late;
if (late > g_pace.tick_late_max_ns) g_pace.tick_late_max_ns = late;
if (late > 2000000LL) g_pace.ticks_late_2ms++;
}
if (g_last_vsync_ns) {
int64_t d = now - g_last_vsync_ns;
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
}
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();
}
@@ -3396,6 +3478,24 @@ static int on_stats_timer(void *data) {
#undef PERF_MS
memset(&g_perf, 0, sizeof(g_perf));
}
const uint64_t game = g_game_frames - g_pace.game_frames_seen;
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, %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, 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);
}
{
const uint64_t seen = g_game_frames;
memset(&g_pace, 0, sizeof(g_pace));
g_pace.game_frames_seen = seen;
}
g_stat_frames = g_stat_dmabuf = g_stat_shm = 0;
droiddeck_color_stats_tick();
@@ -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)
@@ -495,6 +498,21 @@ class FrontEndActivity : ComponentActivity() {
private var homeScreenEnabled by mutableStateOf(false)
private var defaultHomeLabel by mutableStateOf<String?>(null)
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
private var androidAppsListing = 0
private val packageCallback = object : android.content.pm.LauncherApps.Callback() {
private fun changed() {
refreshAndroidApps()
if (HomeWidgets.providers != null) HomeWidgets.refreshProviders(this@FrontEndActivity)
}
override fun onPackageRemoved(packageName: String, user: android.os.UserHandle) = changed()
override fun onPackageAdded(packageName: String, user: android.os.UserHandle) = changed()
override fun onPackageChanged(packageName: String, user: android.os.UserHandle) = changed()
override fun onPackagesAvailable(packageNames: Array<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
override fun onPackagesUnavailable(packageNames: Array<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
override fun onShortcutsChanged(packageName: String, shortcuts: MutableList<android.content.pm.ShortcutInfo>, user: android.os.UserHandle) {
if (homeAppSelected) HomePins.refresh(this@FrontEndActivity)
}
}
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
private lateinit var displayManager: DisplayManager
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
@@ -516,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()
@@ -541,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)
@@ -580,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
@@ -960,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,
@@ -1013,9 +1036,35 @@ class FrontEndActivity : ComponentActivity() {
onPlay = { playSteam() },
onPlaySteamVr = { playSteamVr() },
onSteamUrl = { url ->
if (!SessionState.running) startSession(
Intent(this, SessionActivity::class.java).putExtra(SessionService.EXTRA_STEAM_URL, url), steamSession = true,
)
if (!com.droiddeck.launcher.session.SteamSessionUrl.isSupported(url)) {
android.widget.Toast.makeText(this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG).show()
} else if (!SessionState.running) {
android.widget.Toast.makeText(this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG).show()
} else if (SessionState.mode != SessionService.MODE_STEAM) {
android.widget.Toast.makeText(this, R.string.steam_navigation_switch_mode, android.widget.Toast.LENGTH_LONG).show()
} else if (SessionState.stopRequested) {
android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
} else {
if (SessionState.suspended) SessionService.resume(this)
val context = applicationContext
val sessionId = SessionState.sessionId
Thread({
val opened = runCatching {
com.droiddeck.launcher.agent.AgentGuest.openSteamUrl(context, url)
}.isSuccess
ui.post {
val canResume = com.droiddeck.launcher.session.SteamSessionUrl.canResume(
sessionId, SessionState.sessionId, SessionState.running,
SessionState.stopRequested, isDestroyed,
)
if (opened && canResume) startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
else if (!opened && !isDestroyed) android.widget.Toast.makeText(
this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG,
).show()
}
}, "steam-navigation").start()
}
},
onPlayDesktopUi = {
startSession(Intent(this, SessionActivity::class.java)
@@ -1026,7 +1075,11 @@ class FrontEndActivity : ComponentActivity() {
if (shortcutPicker) chooseGameShortcut(g)
else {
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g, onBlocked = {
android.widget.Toast.makeText(
this, R.string.store_maintenance_launch_blocked, android.widget.Toast.LENGTH_LONG,
).show()
}) { launchGame(g) }
}
},
onEpicLauncher = { openEpicLauncher() },
@@ -1116,8 +1169,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))
@@ -1274,7 +1340,12 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
},
onDismissPhantomGate = { showPhantomGate = false },
onShowPhantomGate = {
refreshPhantomStatus()
showPhantomGate = true
},
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) },
onOpenNotificationSettings = {
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
@@ -1563,6 +1634,15 @@ class FrontEndActivity : ComponentActivity() {
})
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
refreshSecondScreenDisplays()
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
HomeWidgets.startListening(this)
}
@Suppress("OVERRIDE_DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) return
@Suppress("DEPRECATION")
super.onActivityResult(requestCode, resultCode, data)
}
override fun onSaveInstanceState(outState: Bundle) {
@@ -1588,6 +1668,8 @@ class FrontEndActivity : ComponentActivity() {
override fun onStop() {
unregisterReceiver(wifiLocationReceiver)
unregisterReceiver(mediaReceiver)
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
HomeWidgets.stopListening(this)
ui.removeCallbacks(mediaRefresh)
com.droiddeck.launcher.stores.StoresState.libraryListener = null
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
@@ -1603,10 +1685,24 @@ class FrontEndActivity : ComponentActivity() {
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
defaultHomeLabel = HomeApp.defaultLabel(this)
androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList()
refreshAndroidApps()
integrationState = readIntegration()
}
private fun refreshAndroidApps() {
if (!homeAppSelected) {
++androidAppsListing
androidApps = emptyList()
return
}
val seq = ++androidAppsListing
HomePins.refresh(this)
Thread({
val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList())
ui.post { if (seq == androidAppsListing) androidApps = apps }
}, "home-apps").start()
}
private fun refreshSecondScreenDisplays() {
if (!::displayManager.isInitialized) return
// The launcher can itself be shown on a non-default display (DeX, an external monitor); that one is not a "second screen".
@@ -2262,6 +2358,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"
@@ -2283,6 +2383,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)
@@ -2369,6 +2471,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
@@ -6,20 +6,41 @@ import android.graphics.Bitmap
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.LauncherApps
import android.content.pm.ShortcutInfo
import android.graphics.Rect
import android.os.Process
import android.os.UserHandle
import android.os.UserManager
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.graphics.drawable.toBitmap
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlin.math.roundToInt
object HomeApp {
private const val ICON_DP = 72
data class LaunchableApp(
val label: String,
val packageName: String,
val className: String,
val icon: Bitmap?,
)
val system: Boolean = false,
val game: Boolean = false,
val installedAt: Long = 0L,
val updatedAt: Long = 0L,
val user: UserHandle? = null,
val userSerial: Long = 0L,
) {
val component get() = ComponentName(packageName, className)
val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
val work get() = userSerial != 0L
}
fun isHomeScreenEnabled(context: Context): Boolean =
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
@@ -69,33 +90,79 @@ object HomeApp {
fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS)
fun launchableApps(context: Context): List<LaunchableApp> {
val launcher = context.getSystemService(LauncherApps::class.java)
val users = context.getSystemService(UserManager::class.java)
val pm = context.packageManager
val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
val apps = pm.queryIntentActivities(launch, 0)
.asSequence()
.mapNotNull { result ->
val activity = result.activityInfo ?: return@mapNotNull null
if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null
val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName }
val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull()
LaunchableApp(label, activity.packageName, activity.name, icon)
val own = Process.myUserHandle()
val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
val apps = users.userProfiles.flatMap { user ->
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
val component = info.componentName
if (component.packageName == context.packageName && user == own) return@mapNotNull null
val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
val app = info.applicationInfo
val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
@Suppress("DEPRECATION")
val game = app.category == ApplicationInfo.CATEGORY_GAME || app.flags and ApplicationInfo.FLAG_IS_GAME != 0
LaunchableApp(
label, component.packageName, component.className, icon,
system = app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0,
game = game,
installedAt = info.firstInstallTime,
updatedAt = updated ?: info.firstInstallTime,
user = user,
userSerial = serial,
)
}
.distinctBy { it.packageName }
.toList()
return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
}
return apps.distinctBy { it.key }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
}
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) {
val intent = Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(ComponentName(app.packageName, app.className))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (displayId == null) {
context.startActivity(intent)
return
}
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
context.startActivity(intent, options.toBundle())
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null, bounds: Rect? = null) {
val options = displayId?.let { ActivityOptions.makeBasic().setLaunchDisplayId(it).toBundle() }
val launcher = context.getSystemService(LauncherApps::class.java)
launcher.startMainActivity(app.component, app.user ?: Process.myUserHandle(), bounds, options)
}
fun canUseShortcuts(context: Context): Boolean =
runCatching { context.getSystemService(LauncherApps::class.java).hasShortcutHostPermission() }.getOrDefault(false)
fun shortcuts(context: Context, app: LaunchableApp): List<ShortcutInfo> {
if (!canUseShortcuts(context)) return emptyList()
val query = LauncherApps.ShortcutQuery()
.setPackage(app.packageName)
.setActivity(app.component)
.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST)
return runCatching { context.getSystemService(LauncherApps::class.java).getShortcuts(query, app.user ?: Process.myUserHandle()) }
.getOrNull().orEmpty()
.filter { it.isEnabled }
.sortedWith(compareBy<ShortcutInfo> { if (it.isDeclaredInManifest) 0 else 1 }.thenBy { it.rank })
.take(5)
}
fun shortcutIcon(context: Context, info: ShortcutInfo, px: Int = (ICON_DP * context.resources.displayMetrics.density).roundToInt()): Bitmap? = runCatching {
context.getSystemService(LauncherApps::class.java)
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
}.getOrNull()
fun startShortcut(context: Context, info: ShortcutInfo) {
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
}
fun openAppInfo(context: Context, app: LaunchableApp) {
context.getSystemService(LauncherApps::class.java)
.startAppDetailsActivity(app.component, app.user ?: Process.myUserHandle(), null, null)
}
fun canUninstall(app: LaunchableApp): Boolean = !app.system && !app.work
fun uninstall(context: Context, app: LaunchableApp) {
context.startActivity(
Intent(Intent.ACTION_DELETE, Uri.fromParts("package", app.packageName, null))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
fun isActiveSteamSession(): Boolean =
@@ -0,0 +1,65 @@
package com.droiddeck.launcher
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import org.json.JSONArray
import org.json.JSONObject
import java.util.UUID
object HomeFolders {
data class Folder(val id: String, val name: String, val apps: List<String>)
private const val PREFS = "home_launcher"
private const val KEY = "folders"
var folders by mutableStateOf<List<Folder>>(emptyList())
private set
private var loaded = false
fun load(context: Context) {
if (loaded) return
loaded = true
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
folders = runCatching {
val array = JSONArray(raw)
(0 until array.length()).map { i ->
val o = array.getJSONObject(i)
val apps = o.getJSONArray("apps")
Folder(o.getString("id"), o.getString("name"), (0 until apps.length()).map { apps.getString(it) })
}
}.getOrDefault(emptyList())
}
fun create(context: Context, name: String, appKey: String): Folder {
val folder = Folder(UUID.randomUUID().toString(), name, listOf(appKey))
update(context, without(appKey) + folder)
return folder
}
fun add(context: Context, folderId: String, appKey: String) =
update(context, without(appKey).map { if (it.id == folderId) it.copy(apps = it.apps + appKey) else it })
fun remove(context: Context, appKey: String) = update(context, without(appKey))
fun rename(context: Context, folderId: String, name: String) =
update(context, folders.map { if (it.id == folderId) it.copy(name = name) else it })
fun delete(context: Context, folderId: String) = update(context, folders.filterNot { it.id == folderId })
fun migrateMembers(context: Context, keyFor: (String) -> String?) {
if (folders.none { f -> f.apps.any { '/' !in it } }) return
update(context, folders.map { f -> f.copy(apps = f.apps.map { if ('/' in it) it else keyFor(it) ?: it }.distinct()) })
}
private fun without(appKey: String): List<Folder> =
folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() }
private fun update(context: Context, next: List<Folder>) {
folders = next
val array = JSONArray()
for (f in next) array.put(JSONObject().put("id", f.id).put("name", f.name).put("apps", JSONArray(f.apps)))
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
}
}
@@ -0,0 +1,26 @@
package com.droiddeck.launcher
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
object HomeHidden {
private const val PREFS = "home_launcher"
private const val KEY = "hidden"
var keys by mutableStateOf<Set<String>>(emptySet())
private set
private var loaded = false
fun load(context: Context) {
if (loaded) return
loaded = true
keys = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, emptySet()).orEmpty().toSet()
}
fun set(context: Context, key: String, hidden: Boolean) {
keys = if (hidden) keys + key else keys - key
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, keys).apply()
}
}
@@ -0,0 +1,75 @@
package com.droiddeck.launcher
import android.content.Context
import android.content.pm.LauncherApps
import android.content.pm.ShortcutInfo
import android.graphics.Bitmap
import android.os.Handler
import android.os.Looper
import android.os.Process
import android.os.UserManager
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
/** Shortcuts other apps asked to put on the home screen. The system keeps the pinned set per launcher. */
object HomePins {
class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) {
val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else ""
val label get() = info.shortLabel?.toString()?.trim().orEmpty().ifEmpty { appLabel }
val work get() = userSerial != 0L
}
var pinned by mutableStateOf<List<Pinned>>(emptyList())
private set
private val main = Handler(Looper.getMainLooper())
private var listing = 0
fun refresh(context: Context) {
val app = context.applicationContext
val seq = ++listing
Thread({
val list = runCatching { load(app) }.getOrDefault(emptyList())
main.post { if (seq == listing) pinned = list }
}, "home-pins").start()
}
private fun load(context: Context): List<Pinned> {
if (!HomeApp.canUseShortcuts(context)) return emptyList()
val launcher = context.getSystemService(LauncherApps::class.java)
val users = context.getSystemService(UserManager::class.java)
val pm = context.packageManager
val own = Process.myUserHandle()
val query = LauncherApps.ShortcutQuery().setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
return users.userProfiles.flatMap { user ->
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
runCatching { launcher.getShortcuts(query, user) }.getOrNull().orEmpty()
.filter { it.isEnabled && it.isPinned }
.map { info ->
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.`package`, 0)).toString() }
.getOrDefault(info.`package`)
Pinned(info, HomeApp.shortcutIcon(context, info), appLabel, serial)
}
}
}
fun accept(context: Context, request: LauncherApps.PinItemRequest): Boolean {
val ok = runCatching { request.isValid && request.accept() }.getOrDefault(false)
if (ok) refresh(context)
return ok
}
fun unpin(context: Context, pinned: Pinned) {
val info = pinned.info
val launcher = context.getSystemService(LauncherApps::class.java)
val query = LauncherApps.ShortcutQuery().setPackage(info.`package`).setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
val unpinned = runCatching {
val current = checkNotNull(launcher.getShortcuts(query, info.userHandle))
val keep = current.map { it.id } - info.id
launcher.pinShortcuts(info.`package`, keep, info.userHandle)
}.isSuccess
if (!unpinned) return
listing++
this.pinned = this.pinned.filterNot { it.key == pinned.key }
}
}
@@ -0,0 +1,317 @@
package com.droiddeck.launcher
import android.app.Activity
import android.appwidget.AppWidgetHost
import android.appwidget.AppWidgetHostView
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProviderInfo
import android.content.Context
import android.content.Intent
import android.content.pm.LauncherApps
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.SizeF
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.graphics.drawable.toBitmap
import org.json.JSONArray
import org.json.JSONObject
import kotlin.math.hypot
import kotlin.math.roundToInt
object HomeWidgets {
data class Placed(val id: Int, val widthDp: Int, val heightDp: Int)
data class Provider(
val info: AppWidgetProviderInfo,
val label: String,
val appLabel: String,
val preview: Bitmap?,
val widthDp: Int,
val heightDp: Int,
)
private const val HOST_ID = 0x0DDE
private const val PREFS = "home_launcher"
private const val KEY = "widgets"
private const val REQUEST_BIND = 0x0DD1
private const val REQUEST_CONFIGURE = 0x0DD2
private const val REQUEST_RECONFIGURE = 0x0DD3
const val MIN_WIDTH_DP = 96
const val MIN_HEIGHT_DP = 56
var widgets by mutableStateOf<List<Placed>>(emptyList())
private set
var providers by mutableStateOf<List<Provider>?>(null)
private set
private var loaded = false
private var host: Host? = null
private var pending: AppWidgetProviderInfo? = null
private var pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
private var pinRequest: LauncherApps.PinItemRequest? = null
private val main = Handler(Looper.getMainLooper())
private class Host(context: Context) : AppWidgetHost(context, HOST_ID) {
override fun onCreateView(context: Context, appWidgetId: Int, appWidget: AppWidgetProviderInfo?): AppWidgetHostView =
HomeWidgetView(context)
}
class HomeWidgetView(context: Context) : AppWidgetHostView(context) {
var onLongPress: (() -> Unit)? = null
private var fired = false
private var downX = 0f
private var downY = 0f
private val slop = ViewConfiguration.get(context).scaledTouchSlop
private val longPress = Runnable {
fired = true
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
onLongPress?.invoke()
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
fired = false
downX = ev.x
downY = ev.y
postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong())
}
MotionEvent.ACTION_MOVE -> if (hypot(ev.x - downX, ev.y - downY) > slop) removeCallbacks(longPress)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> removeCallbacks(longPress)
}
return fired
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (fired) {
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) fired = false
return true
}
return super.onTouchEvent(event)
}
}
private fun host(context: Context): Host = host ?: Host(context.applicationContext).also { host = it }
fun load(context: Context) {
if (loaded) return
loaded = true
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
val manager = AppWidgetManager.getInstance(context)
val parsed = runCatching {
val array = JSONArray(raw)
(0 until array.length()).map { i ->
val o = array.getJSONObject(i)
Placed(o.getInt("id"), o.getInt("w"), o.getInt("h"))
}
}.getOrDefault(emptyList())
val live = parsed.filter { manager.getAppWidgetInfo(it.id) != null }
parsed.filterNot { it in live }.forEach { host(context).deleteAppWidgetId(it.id) }
widgets = live
if (live.size != parsed.size) save(context)
}
fun startListening(context: Context) {
load(context)
runCatching { host(context).startListening() }
}
fun stopListening(context: Context) {
runCatching { host(context).stopListening() }
}
fun info(context: Context, id: Int): AppWidgetProviderInfo? = AppWidgetManager.getInstance(context).getAppWidgetInfo(id)
fun createView(context: Context, id: Int): HomeWidgetView? {
val info = info(context, id) ?: return null
return host(context).createView(context, id, info) as? HomeWidgetView
}
fun applySize(view: AppWidgetHostView, widthDp: Int, heightDp: Int) {
if (Build.VERSION.SDK_INT >= 31) {
view.updateAppWidgetSize(Bundle(), listOf(SizeF(widthDp.toFloat(), heightDp.toFloat())))
} else {
@Suppress("DEPRECATION")
view.updateAppWidgetSize(null, widthDp, heightDp, widthDp, heightDp)
}
}
fun loadProviders(context: Context) {
if (providers != null) return
val app = context.applicationContext
Thread({
val pm = app.packageManager
val manager = AppWidgetManager.getInstance(app)
val dpi = app.resources.displayMetrics.densityDpi
val list = manager.installedProviders.mapNotNull { info ->
runCatching {
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.provider.packageName, 0)).toString() }
.getOrDefault(info.provider.packageName)
val drawable = info.loadPreviewImage(app, dpi) ?: info.loadIcon(app, dpi)
val preview = drawable?.let { d ->
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
val scale = minOf(1f, 360f / maxOf(w, h))
d.toBitmap((w * scale).roundToInt().coerceAtLeast(1), (h * scale).roundToInt().coerceAtLeast(1))
}
val (w, h) = defaultSize(app, info)
Provider(info, info.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { appLabel }, appLabel, preview, w, h)
}.getOrNull()
}.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, Provider::appLabel).thenBy(String.CASE_INSENSITIVE_ORDER, Provider::label))
main.post { providers = list }
}, "widget-providers").start()
}
fun refreshProviders(context: Context) {
providers = null
loadProviders(context)
}
private fun defaultSize(context: Context, info: AppWidgetProviderInfo): Pair<Int, Int> {
val density = context.resources.displayMetrics.density
var w = (info.minWidth / density).roundToInt()
var h = (info.minHeight / density).roundToInt()
if (Build.VERSION.SDK_INT >= 31) {
if (info.targetCellWidth > 0) w = maxOf(w, info.targetCellWidth * 80)
if (info.targetCellHeight > 0) h = maxOf(h, info.targetCellHeight * 80)
}
return w.coerceIn(160, 560) to h.coerceIn(MIN_HEIGHT_DP, 360)
}
fun minSize(context: Context, id: Int): Pair<Int, Int> {
val info = info(context, id) ?: return MIN_WIDTH_DP to MIN_HEIGHT_DP
val density = context.resources.displayMetrics.density
val w = (if (info.minResizeWidth > 0) info.minResizeWidth else info.minWidth) / density
val h = (if (info.minResizeHeight > 0) info.minResizeHeight else info.minHeight) / density
return w.roundToInt().coerceAtLeast(MIN_WIDTH_DP) to h.roundToInt().coerceAtLeast(MIN_HEIGHT_DP)
}
fun add(activity: Activity, provider: Provider) {
if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null)
}
/** Places a widget another app asked for; its own app has already configured it. */
fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean {
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false
val info = request.getAppWidgetProviderInfo(activity) ?: return false
load(activity)
add(activity, info, request)
return pending != null
}
private fun add(activity: Activity, info: AppWidgetProviderInfo, request: LauncherApps.PinItemRequest?) {
val h = host(activity)
val id = h.allocateAppWidgetId()
pending = info
pendingId = id
pinRequest = request
val manager = AppWidgetManager.getInstance(activity)
val bound = runCatching { manager.bindAppWidgetIdIfAllowed(id, info.profile, info.provider, null) }.getOrDefault(false)
if (bound) {
bound(activity, id, info)
return
}
val bind = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile)
@Suppress("DEPRECATION")
runCatching { activity.startActivityForResult(bind, REQUEST_BIND) }.onFailure { abandon(activity) }
}
private fun bound(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
val request = pinRequest
if (request == null) {
configure(activity, id, info)
return
}
val accepted = runCatching { request.isValid && request.accept(Bundle().apply { putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, id) }) }
.getOrDefault(false)
if (accepted) place(activity, id, info) else abandon(activity)
}
private fun configure(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
val optional = Build.VERSION.SDK_INT >= 31 &&
info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0
if (info.configure == null || optional) {
place(activity, id, info)
return
}
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_CONFIGURE, null) }
.onFailure { place(activity, id, info) }
}
fun canReconfigure(context: Context, id: Int): Boolean {
val info = info(context, id) ?: return false
if (info.configure == null) return false
return Build.VERSION.SDK_INT < 28 || info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE != 0
}
fun reconfigure(activity: Activity, id: Int) {
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_RECONFIGURE, null) }
}
fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int): Boolean {
when (requestCode) {
REQUEST_BIND -> {
val info = pending
if (resultCode == Activity.RESULT_OK && info != null) bound(activity, pendingId, info) else abandon(activity)
}
REQUEST_CONFIGURE -> {
val info = pending
if (resultCode == Activity.RESULT_OK && info != null) place(activity, pendingId, info) else abandon(activity)
}
REQUEST_RECONFIGURE -> Unit
else -> return false
}
return true
}
private fun abandon(context: Context) {
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) host(context).deleteAppWidgetId(pendingId)
pending = null
pinRequest = null
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
}
private fun place(context: Context, id: Int, info: AppWidgetProviderInfo) {
val (w, h) = defaultSize(context, info)
pending = null
pinRequest = null
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
widgets = widgets + Placed(id, w, h)
save(context)
}
fun resize(context: Context, id: Int, widthDp: Int, heightDp: Int) {
widgets = widgets.map { if (it.id == id) it.copy(widthDp = widthDp, heightDp = heightDp) else it }
save(context)
}
fun move(context: Context, id: Int, by: Int) {
val i = widgets.indexOfFirst { it.id == id }
val j = i + by
if (i < 0 || j !in widgets.indices) return
widgets = widgets.toMutableList().apply { add(j, removeAt(i)) }
save(context)
}
fun remove(context: Context, id: Int) {
host(context).deleteAppWidgetId(id)
widgets = widgets.filterNot { it.id == id }
save(context)
}
private fun save(context: Context) {
val array = JSONArray()
for (w in widgets) array.put(JSONObject().put("id", w.id).put("w", w.widthDp).put("h", w.heightDp))
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
}
}
@@ -0,0 +1,346 @@
package com.droiddeck.launcher
import android.app.ActivityOptions
import android.app.AppOpsManager
import android.app.PictureInPictureParams
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.provider.Settings
import android.util.Rational
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.core.AppLanguage
import com.droiddeck.launcher.core.GlobalSettings
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.WirelessAdbPairingService
import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.LocalPalette
import com.droiddeck.launcher.ui.PrimaryButton
import com.droiddeck.launcher.ui.SecondaryButton
import kotlinx.coroutines.delay
class PairingGuideActivity : ComponentActivity() {
enum class Step { BUILD_NUMBER, CHILD_PROCESS, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
private var settingsDisplay: Int? = null
private var toggleOnly = false
private var inPip by mutableStateOf(false)
private var launchPending = false
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
setContent { DroidDeckTheme { Guide() } }
launchPending = savedInstanceState == null
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
launchPending = true
}
override fun onResume() {
super.onResume()
if (!launchPending) return
if (inPip || settingsDisplay != null) {
launchSettings()
return
}
enterPip()
if (!inPip) launchSettings()
}
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
inPip = isInPictureInPictureMode
if (isInPictureInPictureMode && launchPending) launchSettings()
}
private fun launchSettings() {
launchPending = false
openSettings(stepFor(SettingsState.read(this), WirelessAdbPairingService.stage.value, toggleOnly))
}
private fun enterPip() {
inPip = runCatching {
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(4, 3)).build())
}.getOrDefault(false)
}
private fun openSettings(step: Step) {
val intent = if (step == Step.BUILD_NUMBER) {
Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
} else {
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).apply {
if (step != Step.CHILD_PROCESS) putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
}
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val display = settingsDisplay
runCatching {
if (display == null) startActivity(intent)
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
}.onFailure {
runCatching { startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
}
private fun returnToApp() {
startActivity(Intent(this, FrontEndActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
finish()
}
@Composable
private fun Guide() {
val stage by WirelessAdbPairingService.stage.collectAsState()
val settingsState by produceState(SettingsState.read(this)) {
while (true) {
value = SettingsState.read(this@PairingGuideActivity)
delay(500)
}
}
val step = stepFor(settingsState, stage, toggleOnly)
var previous by remember { mutableStateOf(step) }
LaunchedEffect(step) {
if (previous == Step.BUILD_NUMBER && (step == Step.WIRELESS_DEBUGGING || step == Step.CHILD_PROCESS)) openSettings(step)
previous = step
when (step) {
Step.DONE -> { delay(1_500); returnToApp() }
Step.FAILED -> { delay(3_000); returnToApp() }
else -> Unit
}
}
LaunchedEffect(stage) { if (stage == Stage.Idle && !toggleOnly) finish() }
BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
if (inPip) CompactStep(step, stage)
else FullGuide(step, stage)
}
}
@Composable
private fun CompactStep(step: Step, stage: Stage) {
Column(Modifier.fillMaxSize().padding(10.dp), verticalArrangement = Arrangement.SpaceBetween) {
Text(
instruction(step, stage), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onBackground, maxLines = 3, overflow = TextOverflow.Ellipsis,
)
StepVisual(step, compact = true)
StepDots(step)
}
}
@Composable
private fun FullGuide(step: Step, stage: Stage) {
Column(
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(stringResource(R.string.gate_title), style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
Text(instruction(step, stage), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground)
StepVisual(step, compact = false)
StepDots(step)
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
if (step == Step.DONE || step == Step.FAILED) {
PrimaryButton(stringResource(R.string.common_back), onClick = ::returnToApp)
} else {
PrimaryButton(stringResource(R.string.gate_open_dev), onClick = {
if (settingsDisplay == null) enterPip()
openSettings(step)
})
SecondaryButton(stringResource(R.string.common_cancel), onClick = {
if (!toggleOnly) WirelessAdbPairingService.cancel(this@PairingGuideActivity)
returnToApp()
})
}
}
}
}
@Composable
private fun instruction(step: Step, stage: Stage): String = when (step) {
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number)
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_child_process)
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless)
Step.PAIR -> stringResource(R.string.pairguide_pair)
Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3)
Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_working)
Step.DONE -> stringResource(R.string.adbpair_title_done)
Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed)
}
@Composable
private fun StepVisual(step: Step, compact: Boolean) {
val colors = MaterialTheme.colorScheme
val accent = LocalPalette.current.signal
val pulse = rememberInfiniteTransition(label = "guidePulse")
val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat")
val label = when (step) {
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number)
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_row_child_process)
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless)
Step.PAIR -> stringResource(R.string.pairguide_row_pair)
Step.CODE -> stringResource(R.string.adbpair_enter_code)
Step.WORKING, Step.DONE, Step.FAILED -> return
}
val rowHeight = if (compact) 34.dp else 56.dp
Row(
Modifier.fillMaxWidth().height(rowHeight).background(colors.surfaceVariant, RoundedCornerShape(10.dp))
.border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(10.dp)).padding(horizontal = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge,
color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
when (step) {
Step.WIRELESS_DEBUGGING, Step.CHILD_PROCESS -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent)
Box(contentAlignment = Alignment.Center) {
Box(Modifier.size(if (compact) 18.dp else 26.dp).scale(0.6f + beat * 0.8f).alpha(1f - beat)
.background(accent, CircleShape))
Box(Modifier.size(if (compact) 8.dp else 12.dp).background(accent, CircleShape))
}
}
}
}
}
@Composable
private fun Toggle(on: Boolean, accent: Color, compact: Boolean) {
val width = if (compact) 26.dp else 40.dp
val knob = if (compact) 12.dp else 18.dp
Box(
Modifier.width(width).height(knob + 4.dp)
.background(if (on) accent.copy(alpha = 0.6f) else MaterialTheme.colorScheme.outline, CircleShape).padding(2.dp),
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
) { Box(Modifier.size(knob).background(Color.White, CircleShape)) }
}
@Composable
private fun StepDots(step: Step) {
val accent = LocalPalette.current.signal
val shown = if (toggleOnly) listOf(Step.BUILD_NUMBER, Step.CHILD_PROCESS)
else listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size
Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
shown.forEachIndexed { index, _ ->
Box(Modifier.size(if (index == at) 8.dp else 6.dp)
.background(if (index <= at) accent else MaterialTheme.colorScheme.outline, CircleShape))
}
Spacer(Modifier.width(2.dp))
}
}
private data class SettingsState(
val developerOptions: Boolean,
val wirelessDebugging: Boolean,
val childProcessBlocked: Boolean,
) {
companion object {
fun read(context: Context) = SettingsState(
GlobalSettings.developerOptionsOn(context),
GlobalSettings.wirelessDebuggingOn(context),
PhantomProcessLimit.blocksSteam(PhantomProcessLimit.read(context)),
)
}
}
companion object {
private const val EXTRA_DISPLAY = "settingsDisplay"
private const val EXTRA_TOGGLE_ONLY = "toggleOnly"
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
private fun stepFor(settings: SettingsState, stage: Stage, toggleOnly: Boolean): Step = if (toggleOnly) when {
!settings.developerOptions -> Step.BUILD_NUMBER
settings.childProcessBlocked -> Step.CHILD_PROCESS
else -> Step.DONE
} else when (stage) {
is Stage.Working -> Step.WORKING
Stage.Done -> Step.DONE
is Stage.Failed -> Step.FAILED
is Stage.CodeNeeded -> Step.CODE
else -> when {
!settings.developerOptions -> Step.BUILD_NUMBER
!settings.wirelessDebugging -> Step.WIRELESS_DEBUGGING
else -> Step.PAIR
}
}
fun canFloat(context: Context): Boolean {
if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false
val ops = context.getSystemService(AppOpsManager::class.java) ?: return true
val mode = if (Build.VERSION.SDK_INT >= 29) {
ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
} else {
@Suppress("DEPRECATION")
ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
}
return mode == AppOpsManager.MODE_ALLOWED
}
fun start(context: Context, settingsDisplay: Int?, toggleOnly: Boolean = false): Boolean {
if (settingsDisplay == null && !canFloat(context)) return false
context.startActivity(Intent(context, PairingGuideActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(EXTRA_TOGGLE_ONLY, toggleOnly)
.apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) })
return true
}
}
}
@@ -0,0 +1,82 @@
package com.droiddeck.launcher
import android.content.Intent
import android.content.pm.LauncherApps
import android.graphics.Bitmap
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.core.graphics.drawable.toBitmap
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.PinRequestPrompt
class PinRequestActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val request = runCatching { getSystemService(LauncherApps::class.java).getPinItemRequest(intent) }.getOrNull()
if (request == null || !request.isValid) {
finish()
return
}
val prompt = when (request.requestType) {
LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT -> request.shortcutInfo?.let { info ->
val appLabel = appLabel(info.`package`)
Triple(info.shortLabel?.toString().orEmpty().ifEmpty { appLabel }, appLabel, HomeApp.shortcutIcon(this, info))
}
LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET -> request.getAppWidgetProviderInfo(this)?.let { info ->
val appLabel = appLabel(info.provider.packageName)
val dpi = resources.displayMetrics.densityDpi
val icon = runCatching { (info.loadPreviewImage(this, dpi) ?: info.loadIcon(this, dpi))?.let(::scaled) }.getOrNull()
Triple(info.loadLabel(packageManager)?.toString().orEmpty().ifEmpty { appLabel }, appLabel, icon)
}
else -> null
}
if (prompt == null) {
finish()
return
}
val (label, appLabel, icon) = prompt
val widget = request.requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET
setContent {
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
PinRequestPrompt(
label = label, appLabel = appLabel, icon = icon, wide = widget,
onAdd = {
if (!widget) {
HomePins.accept(this, request)
finish()
} else if (!HomeWidgets.addPinned(this, request)) finish()
},
onCancel = { finish() },
)
}
}
}
@Suppress("OVERRIDE_DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) {
finish()
return
}
@Suppress("DEPRECATION")
super.onActivityResult(requestCode, resultCode, data)
}
private fun appLabel(packageName: String): String =
runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() }
.getOrDefault(packageName)
private fun scaled(d: android.graphics.drawable.Drawable): Bitmap {
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
val k = minOf(1f, 480f / maxOf(w, h))
return d.toBitmap((w * k).toInt().coerceAtLeast(1), (h * k).toInt().coerceAtLeast(1))
}
}
@@ -68,6 +68,7 @@ import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.input.EvdevKeys
import com.droiddeck.launcher.input.HomeGuideInput
import com.droiddeck.launcher.input.InputSpace
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.ControllerPrefs
@@ -355,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
@@ -487,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()
@@ -1105,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
@@ -1174,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(
@@ -1330,7 +1345,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return
incoming.action = null
setIntent(incoming)
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
if (SessionState.suspended) SessionService.resume(this)
else if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
}
@@ -1657,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,
@@ -1680,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()
@@ -1781,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) {
@@ -2190,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)
@@ -2208,8 +2256,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
val steamVolume =
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!gestureSettingsOpen && !screenKeyTextFocus && window.decorView.hasWindowFocus()
if (steamVolume) {
val audio = getSystemService(android.media.AudioManager::class.java)
if (com.droiddeck.launcher.input.SteamVolumeKeys.dispatch(event, !audio.isVolumeFixed) { direction ->
audio.adjustStreamVolume(android.media.AudioManager.STREAM_MUSIC, direction, 0)
}) return true
}
return super.dispatchKeyEvent(event)
}
}
val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
@@ -2276,7 +2336,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true
}
val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START ||
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || event.keyCode == KeyEvent.KEYCODE_HOME
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || HomeGuideInput.isHome(event.keyCode)
val resumeKeyId = event.deviceId to event.keyCode
if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) {
if (event.action == KeyEvent.ACTION_DOWN) {
@@ -3092,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
@@ -3127,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() {
@@ -3290,7 +3359,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
enabled = {
resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen &&
!achievementsOpen && !gestureSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended &&
SessionState.mode == SessionService.MODE_STEAM && padBridge?.canHoldGuide() == true
SessionState.mode == SessionService.MODE_STEAM && padBridge != null
},
setPressed = { padBridge?.setHomeGuidePressed(it) },
onCancel = { padBridge?.cancelHomeGuide() },
@@ -3838,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
@@ -11,7 +11,9 @@ import android.os.FileObserver
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SteamSessionUrl
import org.json.JSONObject
import java.io.File
import java.util.UUID
@@ -96,6 +98,16 @@ object AgentGuest {
fun focus(context: Context): JSONObject? =
if (SessionState.running) readJson(File(dir(context), "focus.json")) else null
fun openSteamUrl(context: Context, url: String, timeoutMs: Long = STEAM_URL_TIMEOUT_MS): JSONObject {
require(SteamSessionUrl.isSupported(url)) { "Unsupported Steam navigation URL" }
val result = call(context, JSONObject().put("kind", "steam-url").put("url", url)
.put("timeout", (timeoutMs - 1_000).coerceAtLeast(1_000) / 1_000.0), timeoutMs, trusted = true)
check(SteamSessionUrl.wasOpened(result.optBoolean("ok"), result.optBoolean("launched"))) {
"Steam did not accept the navigation request"
}
return result
}
fun selectedSteamAppId(context: Context): Long? {
val result = call(context, JSONObject().put("kind", "steam-selection"), 6_000)
if (!result.optBoolean("ok") || result.isNull("appId")) return null
@@ -194,4 +206,6 @@ object AgentGuest {
} catch (e: Exception) {
null
}
private const val STEAM_URL_TIMEOUT_MS = 125_000L
}
@@ -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();
}
}
}
@@ -0,0 +1,24 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.net.Uri
import android.provider.Settings
object GlobalSettings {
// Settings.Global caches values in-process and misses deletions made over adb; ask the provider directly.
fun read(context: Context, name: String): String? {
val uri = Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
context.contentResolver.query(uri, arrayOf(Settings.NameValueTable.VALUE), null, null, null)?.use { cursor ->
return if (cursor.moveToFirst()) cursor.getString(0) else null
}
return Settings.Global.getString(context.contentResolver, name)
}
fun isOn(context: Context, name: String): Boolean =
runCatching { read(context, name)?.trim() == "1" }.getOrDefault(false)
fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED)
// Settings.Global.ADB_WIFI_ENABLED is hidden; the key is stable since Android 11.
fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled")
}
@@ -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) {
@@ -60,14 +60,14 @@ object PhantomProcessLimit {
if (usesDeviceConfig(sdk)) {
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
val global = try {
Settings.Global.getString(context.contentResolver, SETTING)
GlobalSettings.read(context, SETTING)
} catch (_: Exception) {
null
}
return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY))
}
val global = try {
Settings.Global.getString(context.contentResolver, SETTING)
GlobalSettings.read(context, SETTING)
} catch (_: Exception) {
return PhantomProcessStatus.UNREADABLE
}
@@ -184,12 +184,15 @@ class WirelessAdbPairingService : Service() {
setSound(null, null)
enableVibration(false)
})
manager?.createNotificationChannel(NotificationChannel(PROGRESS_CHANNEL_ID, getString(R.string.adbpair_progress_channel_name),
NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })
val open = PendingIntent.getActivity(this, 0,
Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE)
val cancel = PendingIntent.getService(this, 1,
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
val builder = Notification.Builder(this, CHANNEL_ID)
val quiet = stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working
val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentIntent(open)
.setShowWhen(false)
@@ -239,6 +242,7 @@ class WirelessAdbPairingService : Service() {
companion object {
private const val CHANNEL_ID = "wireless-adb-pairing"
private const val PROGRESS_CHANNEL_ID = "wireless-adb-pairing-progress"
private const val NOTIFICATION_ID = 3
private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
@@ -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);
}
@@ -38,7 +38,7 @@ object HomeButtonShortcuts {
fun onKeyEvent(context: Context, event: KeyEvent): Boolean {
// AYN maps its system-assistant key (gpio-keys KEY_F24) to HOME too; only the pad's Home is Guide.
if (event.keyCode != KeyEvent.KEYCODE_HOME || !PadBridge.isControllerKeyEvent(event)) return false
if (!HomeGuideInput.isHome(event.keyCode) || !PadBridge.isControllerKeyEvent(event)) return false
return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context))
}
@@ -7,7 +7,7 @@ class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCa
private val cancelled = mutableSetOf<Int>()
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
if (event.keyCode != KeyEvent.KEYCODE_HOME) return false
if (!isHome(event.keyCode)) return false
if (!enabled) cancel()
val device = event.deviceId
return when (event.action) {
@@ -39,4 +39,9 @@ class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCa
cancelled.remove(device)
if (presses.remove(device) && presses.isEmpty()) { onCancel(); setPressed(false) }
}
companion object {
// The Retroid Nova pad falls back to Generic.kl, which maps its Home scan code to MOVE_HOME.
fun isHome(keyCode: Int) = keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_HOME
}
}
@@ -53,6 +53,7 @@ public final class PadBridge {
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS];
private final PadState effectiveState = new PadState();
private final PadState homeGuideReport = new PadState();
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private boolean open;
private volatile boolean selectSteam;
@@ -63,6 +64,7 @@ public final class PadBridge {
private boolean systemQamPressed;
private boolean backQamPressed;
private boolean homeGuidePressed;
private int homeGuideSlot = -1;
private final PadState lastBackQamReport = new PadState();
private final PadState lastWrittenReport = new PadState();
private boolean backQamAxesBlocked;
@@ -162,6 +164,7 @@ public final class PadBridge {
public synchronized void stop() {
homeGuidePressed = false;
homeGuideSlot = -1;
clearBackQamWrites();
releaseBackPaddles();
activeControllerId = NO_CONTROLLER;
@@ -229,6 +232,7 @@ public final class PadBridge {
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_MOVE_HOME:
if (!isFromController(device)) return false;
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|| device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC
@@ -329,7 +333,8 @@ public final class PadBridge {
case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.press(9, pressed); break;
case KeyEvent.KEYCODE_BUTTON_MODE:
case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_MOVE_HOME: pad.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Z:
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed);
break;
@@ -485,6 +490,7 @@ public final class PadBridge {
public synchronized void releaseAll() {
homeGuidePressed = false;
homeGuideSlot = -1;
clearBackQamWrites();
routedTouch.clear();
backQamPressed = false;
@@ -512,18 +518,24 @@ public final class PadBridge {
return builtinPad && nativeQam();
}
public boolean canHoldGuide() {
return builtinPad;
}
public synchronized void setHomeGuidePressed(boolean pressed) {
if (pressed && !canHoldGuide()) return;
int slot = pressed ? firstPlayerSlot() : homeGuideSlot;
if (slot > 0) {
homeGuideSlot = pressed ? slot : -1;
publish(slot);
return;
}
if (homeGuidePressed == pressed) return;
homeGuidePressed = pressed;
updateHeldModifier(PadState.GUIDE, pressed);
}
public synchronized void cancelHomeGuide() {
int slot = homeGuideSlot;
if (slot > 0) {
homeGuideSlot = -1;
publish(slot);
}
if (!homeGuidePressed) return;
clearBackQamWrites();
homeGuidePressed = false;
@@ -784,6 +796,7 @@ public final class PadBridge {
partners[slot] = NO_CONTROLLER;
clearJoyCons(slot);
slotControllers.set(slot, NO_CONTROLLER);
if (slot == homeGuideSlot) homeGuideSlot = -1;
if (slot == firstPlayerSlot()) releaseBackPaddles();
if (slot == 0) {
state.clear();
@@ -840,7 +853,13 @@ public final class PadBridge {
}
playerWriters[slot] = player;
}
player.writePad(playerStates[slot]);
PadState report = playerStates[slot];
if (slot == homeGuideSlot) {
homeGuideReport.copyFrom(report);
homeGuideReport.press(PadState.GUIDE, true);
report = homeGuideReport;
}
player.writePad(report);
}
private void publish() {
@@ -0,0 +1,22 @@
package com.droiddeck.launcher.input
import android.media.AudioManager
import android.view.KeyEvent
/** Use Steam's PulseAudio bridge for feedback instead of requesting Android's volume UI. */
internal object SteamVolumeKeys {
fun dispatch(event: KeyEvent, enabled: Boolean, adjust: (Int) -> Unit): Boolean {
val direction = when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP -> AudioManager.ADJUST_RAISE
KeyEvent.KEYCODE_VOLUME_DOWN -> AudioManager.ADJUST_LOWER
KeyEvent.KEYCODE_VOLUME_MUTE -> AudioManager.ADJUST_TOGGLE_MUTE
else -> return false
}
if (!enabled) return false
if (event.action == KeyEvent.ACTION_DOWN &&
(event.keyCode != KeyEvent.KEYCODE_VOLUME_MUTE || event.repeatCount == 0)) {
adjust(direction)
}
return event.action == KeyEvent.ACTION_DOWN || event.action == KeyEvent.ACTION_UP
}
}
@@ -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())
}
@@ -51,7 +51,8 @@ object NoSteamLaunch {
fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? {
val id = game.appId.toLong() and 0xFFFFFFFFL
return AddedGames.scan(context).firstOrNull { settingsId(it) == id }
val one = game.gameFiles?.let { AddedGames.single(context, it.path) }
return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id }
}
fun nameFor(program: String?, args: List<String>): String? = when (program) {
@@ -30,6 +30,7 @@ class RumbleComponent : SessionPart() {
private val joyConPairs = HashMap<Long, Motors>()
private var preferences: SharedPreferences? = null
private var enabled = false
private var quiet = false
private var motorThread: HandlerThread? = null
private var handler: Handler? = null
private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
@@ -44,6 +45,11 @@ class RumbleComponent : SessionPart() {
if (!enabled) cancelAll()
}
@Synchronized fun quiet(on: Boolean) {
quiet = on
if (on) cancelAll()
}
override fun start() {
val ctx = app() ?: return
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
@@ -89,7 +95,7 @@ class RumbleComponent : SessionPart() {
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
if (!enabled) return
if (!enabled || quiet) return
val target = target(slot)
val previous = playing[slot]
if (target !== previous) {
@@ -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) {
@@ -74,6 +74,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
"usr/local/bin/droiddeck-gog-maintenance" to "usr/local/bin/droiddeck-gog-maintenance",
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
@@ -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
@@ -602,6 +602,8 @@ 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)
@@ -629,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)
@@ -1127,7 +1195,7 @@ object SessionPrefs {
resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP
else prefMode(mode)
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", false)
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true)
fun setPipAutoEnter(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
@@ -1170,7 +1238,8 @@ object SessionPrefs {
}
fun suspendPolicy(context: Context, mode: String): String =
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
prefs(context).getString("suspendPolicy.${prefMode(mode)}",
if (mode == SessionService.MODE_STEAM) SUSPEND_NATIVE else SUSPEND_MANUAL)
?.let { if (it == LEGACY_SUSPEND_DOWNLOADS) SUSPEND_AUTO else it }
?.takeIf { it in setOf(SUSPEND_AUTO, SUSPEND_NATIVE, SUSPEND_MANUAL, SUSPEND_NEVER) }
?.let { if (mode != SessionService.MODE_STEAM && it == SUSPEND_NATIVE) SUSPEND_AUTO else it }
@@ -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,12 +1576,15 @@ 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
else -> false
}
// A frozen game never sends the stop for a held rumble, so the keepalive would run on.
val quietRumble = !screenOn || shouldSuspend || SessionState.suspended
components.forEach { (it as? RumbleComponent)?.quiet(quietRumble) }
if (freezePending && !shouldSuspend && !freezeCancelled) {
freezeCancelled = true
controller.cancelFreeze()
@@ -1597,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")
}
}
@@ -1645,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()
@@ -1703,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()
}
}
@@ -1769,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
@@ -1798,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 {
@@ -1809,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
@@ -1820,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()
}
@@ -2065,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"
@@ -2139,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))
@@ -2184,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()
@@ -0,0 +1,23 @@
package com.droiddeck.launcher.session
object SteamSessionUrl {
private val allowed = Regex("steam://(?:open/downloads|uninstall/[1-9][0-9]{0,9})")
private const val MAX_STEAM_APP_ID = 4_294_967_295L
fun isSupported(url: String): Boolean {
if (!allowed.matches(url)) return false
val appId = url.removePrefix("steam://uninstall/").takeIf { it != url }?.toLongOrNull()
return appId == null || appId <= MAX_STEAM_APP_ID
}
internal fun wasOpened(ok: Boolean, launched: Boolean): Boolean = ok && launched
internal fun canResume(
expectedSessionId: String?,
currentSessionId: String?,
running: Boolean,
stopping: Boolean,
activityDestroyed: Boolean,
): Boolean = expectedSessionId != null && expectedSessionId == currentSessionId &&
running && !stopping && !activityDestroyed
}
@@ -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 {
@@ -254,6 +254,7 @@ object StoreInstallRoot {
val sidecar = StoreGameSidecar.read(folder)
when {
sidecar == null -> Unfinished(store, null, folder)
store == Store.GOG && sidecar.state == StoreGameSidecar.STATE_UPDATING -> null
!sidecar.isInstalled -> Unfinished(store, sidecar.id, folder)
else -> null
}
@@ -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()
}
@@ -64,10 +64,21 @@ object StoreLaunch {
private const val CODE_VAR = "DD_X"
private const val CLIENT_VAR = "DD_A"
internal fun matchingInstalls(context: Context, store: Store, id: String): List<Pair<File, StoreGameSidecar>> =
StoreInstallRoot.gameFolders(context.applicationContext).mapNotNull { folder ->
StoreGameSidecar.read(folder)?.takeIf { it.store == store && it.id == id }?.let { folder to it }
}
internal fun findInstalled(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? =
matchingInstalls(context, store, id).firstOrNull { it.second.isInstalled }
private fun preferredInstall(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? {
val matches = matchingInstalls(context, store, id)
return matches.firstOrNull { it.second.isInstalled } ?: matches.firstOrNull()
}
fun installedGame(context: Context, store: Store, id: String): Library.SteamGame? {
val folder = StoreInstallRoot.gameFolders(context).firstOrNull { folder ->
StoreGameSidecar.read(folder)?.let { it.store == store && it.id == id && it.isInstalled } == true
} ?: return null
val folder = findInstalled(context, store, id)?.first ?: return null
val game = AddedGames.single(context, folder.path) ?: return null
return Library.addedGame(context, game)
}
@@ -82,11 +93,22 @@ object StoreLaunch {
}
}
fun prepare(context: Context, store: Store, id: String, onReady: () -> Unit) {
if (store != Store.EPIC) { onReady(); return }
fun prepare(context: Context, store: Store, id: String, onBlocked: () -> Unit = {}, onReady: () -> Unit) {
val app = context.applicationContext
Thread({
epicCode(app, id)
val selected = try {
preferredInstall(app, store, id)
} catch (e: Exception) {
Log.w(TAG, "could not inspect installed ${store.label} launch records for $id", e)
return@Thread
}
if (selected != null && com.droiddeck.launcher.stores.maintenance.StoreMaintenance.launchExcluded(
InstalledStoreGame(selected.second, selected.first))) {
Log.i(TAG, "launch blocked while ${store.label} maintenance is active: $id")
StoresState.post(onBlocked)
return@Thread
}
if (store == Store.EPIC) epicCode(app, id)
StoresState.post(onReady)
}, "stores-launch-prep").start()
}
@@ -96,9 +118,10 @@ object StoreLaunch {
fun epicCode(context: Context, id: String): CodeResult {
val app = context.applicationContext
val result = try {
val folder = StoreInstallRoot.gameFolders(app).firstOrNull { f -> StoreGameSidecar.read(f)?.let { it.store == Store.EPIC && it.id == id } == true }
val sidecar = folder?.let { StoreGameSidecar.read(it) }
sidecar?.let { refreshLauncher(folder, it) }
val selected = preferredInstall(app, Store.EPIC, id)
val folder = selected?.first
val sidecar = selected?.second
selected?.let { (installedFolder, installedSidecar) -> refreshLauncher(installedFolder, installedSidecar) }
val options = sidecar?.epic
if (folder == null) CodeResult(false, "not-installed")
else if (options != null && !options.wantsCode) {
@@ -124,11 +147,11 @@ object StoreLaunch {
return result
}
fun prepare(context: Context, game: Library.SteamGame, onReady: () -> Unit) {
fun prepare(context: Context, game: Library.SteamGame, onBlocked: () -> Unit = {}, onReady: () -> Unit) {
val store = Store.byId(game.source)
val id = game.storeId
if (store == null || id == null) { onReady(); return }
prepare(context, store, id, onReady)
if (store == null || id == null) { StoresState.post(onReady); return }
prepare(context, store, id, onBlocked = onBlocked, onReady = onReady)
}
}
@@ -11,6 +11,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
object StoresState {
private const val TAG = "Stores"
@@ -72,7 +73,10 @@ object StoresState {
fun backend(store: Store): StoreBackend? = backends[store]
fun register(backend: StoreBackend) { backends[backend.store] = backend }
fun register(backend: StoreBackend) {
backends[backend.store] = backend
backend.maintenanceAdapter()?.let(StoreMaintenance::register)
}
fun refresh(context: Context) {
val app = context.applicationContext
@@ -81,7 +85,7 @@ object StoresState {
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled }?.let { InstalledStoreGame(it, folder) }
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList())
val partial = StoreInstallRoot.unfinished(app)
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
@@ -95,6 +99,8 @@ object StoresState {
engine = version
accountsLoaded = true
}
StoreMaintenance.checkInstalled(app, onDisk)
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
}
}
}
@@ -179,6 +185,7 @@ object StoresState {
}
fun signIn(context: Context, store: Store) {
StoreMaintenance.invalidate(store)
expired.remove(store)
libraryAsked.remove(store)
backends[store]?.signIn(context) ?: logLine("${store.label}: this build has no sign-in for it yet")
@@ -189,9 +196,13 @@ object StoresState {
background("stores-signout") {
val backend = backends[store]
backend?.signOut(app)
StoreMaintenance.invalidate(store)
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)
@@ -271,7 +282,11 @@ object StoresState {
fun uninstall(context: Context, game: InstalledStoreGame, onDone: () -> Unit = {}) {
val app = context.applicationContext
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
uninstalling[key] = 0f
if (!com.droiddeck.launcher.stores.maintenance.StoreMaintenance.beginUninstall(game)) {
android.widget.Toast.makeText(app, "Close, finish, or recover maintenance before uninstalling.", android.widget.Toast.LENGTH_LONG).show()
onDone()
return
}
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
@@ -282,6 +297,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)
@@ -343,4 +359,5 @@ interface StoreBackend {
fun search(context: Context, query: String): List<CatalogItem> = emptyList()
fun install(context: Context, item: CatalogItem, root: java.io.File)
fun uninstall(context: Context, game: InstalledStoreGame)
fun maintenanceAdapter(): com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter? = null
}
@@ -12,10 +12,12 @@ import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import org.json.JSONObject
object AmazonBackend : StoreBackend {
override val store: Store = Store.AMAZON
override fun maintenanceAdapter(): StoreMaintenanceAdapter = AmazonMaintenanceAdapter
init {
LoginFlows.amazonFlow = { AmazonLogin.create() }
@@ -11,6 +11,8 @@ import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.StoreDownloadTier
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import org.json.JSONObject
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
@@ -20,6 +22,8 @@ internal class AmazonInstaller(
private val app: Context,
private val item: CatalogItem,
private val folder: File,
private val maintenance: JSONObject? = null,
private val maintenanceGame: InstalledStoreGame? = null,
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
@@ -29,7 +33,7 @@ internal class AmazonInstaller(
val entitlementId = item.extra["entitlementId"].orEmpty()
val sku = item.extra["sku"].orEmpty()
val cover = item.tallImageUrl ?: item.imageUrl
StoreInstalls.begin(folder, Store.AMAZON, item.id, item.title, cover, item.imageUrl)
if (maintenance == null) StoreInstalls.begin(folder, Store.AMAZON, item.id, item.title, cover, item.imageUrl)
if (cancelled.get()) return null
val tier = StoreDownloadTier.current(app)
@@ -41,9 +45,14 @@ internal class AmazonInstaller(
.put("maxWorkers", tier.networkWindow.coerceIn(1, 128))
.put("processWorkers", tier.processWorkers)
.put("caBundle", "")
maintenance?.let {
request.put("targetManifestPath", it.getString("manifestPath"))
request.put("targetVersionId", it.getString("versionId"))
}
val shown = AtomicLong(-1)
val downloading = AtomicBoolean(false)
var applyLease: AutoCloseable? = null
val prefs = AmazonPrefs.get(app)
val listener = object : AmazonNative.InstallListener {
override fun onStatus(text: String) { handle.stage(DownloadStage.MANIFEST, text) }
@@ -70,7 +79,8 @@ internal class AmazonInstaller(
override fun onLog(line: String) { handle.log("amazon: $line") }
override fun beforeReplace(): Boolean = try {
StoreInstalls.markUpdating(folder)
if (maintenance == null) StoreInstalls.markUpdating(folder)
else if (applyLease == null) applyLease = StoreMaintenance.beginApplyLease(maintenanceGame!!)
true
} catch (e: Exception) {
handle.log("amazon: the install record could not be switched to updating (${e.javaClass.simpleName})")
@@ -80,12 +90,11 @@ internal class AmazonInstaller(
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) = Unit
}
val outcome = AmazonNative.install(request, listener, cancelled)
val outcome = try { AmazonNative.install(request, listener, cancelled) }
finally { runCatching { applyLease?.close() } }
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "The Amazon install failed" })
val result = outcome.result ?: JSONObject()
handle.stage(DownloadStage.INSTALL, "Finishing…")
val versionId = result.optString("versionId")
val total = result.optLong("totalBytes", 0L)
prefs.edit().apply {
@@ -93,6 +102,14 @@ internal class AmazonInstaller(
putString("version_${item.id}", versionId)
}.apply()
if (maintenance != null && maintenanceGame != null) {
if (applyLease == null) StoreMaintenance.beginApplyLease(maintenanceGame).close()
StoreMaintenance.complete(app, maintenanceGame, versionId.ifEmpty { maintenance.optString("versionId") })
return folder.path
}
handle.stage(DownloadStage.INSTALL, "Finishing…")
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
val spec = AmazonNative.call("launch.spec", JSONObject().put("gameDir", folder.absolutePath).put("title", item.title))
?: throw IllegalStateException(AmazonNative.ENGINE_MISSING)
@@ -0,0 +1,143 @@
package com.droiddeck.launcher.stores.amazon
import android.content.Context
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.SavedQueue
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
import com.droiddeck.launcher.stores.maintenance.RecoveryState
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import org.json.JSONObject
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
internal object AmazonMaintenanceAdapter : StoreMaintenanceAdapter {
override val store: Store = Store.AMAZON
private const val TARGET_SCHEMA = 1
private const val INSTALLED_MANIFEST = ".droiddeck-maintenance/amazon/installed.manifest"
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> = buildSet {
if (game.sidecar.extra["entitlementId"].orEmpty().isNotBlank()) add(MaintenanceAction.UPDATE)
if (game.sidecar.installVersion.isNotBlank() && File(game.folder, INSTALLED_MANIFEST).isFile) add(MaintenanceAction.REPAIR)
}
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck {
val token = AmazonCredentialStore.getValidAccessToken(context)
?: return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "Not signed in to Amazon Games")
val entitlement = game.sidecar.extra["entitlementId"].orEmpty()
require(entitlement.isNotBlank()) { "The installed Amazon record has no entitlement ID" }
val latest = AmazonApiClient.getGameDownload(token, entitlement)
?: error("Amazon's current game version could not be checked")
if (latest.versionId.isBlank()) return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Amazon did not provide a version ID")
val installed = game.sidecar.installVersion
if (installed.isBlank()) return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, latest.versionId, "The installed Amazon version is unknown")
return MaintenanceCheck(
if (latest.versionId == installed) MaintenanceCheckState.CURRENT else MaintenanceCheckState.AVAILABLE,
latest.versionId,
)
}
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
require(action == MaintenanceAction.UPDATE || action == MaintenanceAction.REPAIR) { "Amazon supports Update and Repair" }
require(action in capabilities(game)) { "The installed Amazon record is missing the data required for ${action.name.lowercase()}" }
require(StoreMaintenance.readOperation(game.folder) == null) { "Resume or recover the existing Amazon operation first" }
val token = AmazonCredentialStore.getValidAccessToken(context) ?: error("Not signed in to Amazon Games")
val entitlement = game.sidecar.extra["entitlementId"].orEmpty()
val current = AmazonApiClient.getGameDownload(token, entitlement) ?: error("Amazon's current download is unavailable")
require(current.versionId.isNotBlank()) { "Amazon did not provide a version ID" }
val dir = File(game.folder, ".droiddeck-maintenance/amazon")
require(!Files.isSymbolicLink(File(game.folder, ".droiddeck-maintenance").toPath())) { "Amazon maintenance metadata is a symbolic link" }
require(!Files.isSymbolicLink(dir.toPath())) { "Amazon maintenance metadata is a symbolic link" }
dir.mkdirs()
val (version, path, bytes) = if (action == MaintenanceAction.REPAIR) {
require(game.sidecar.installVersion.isNotBlank()) { "The installed Amazon version is unknown; repair cannot safely choose a target" }
val installed = File(game.folder, INSTALLED_MANIFEST)
require(installed.isFile && !Files.isSymbolicLink(installed.toPath())) { "The installed Amazon manifest is unavailable; repair cannot safely choose a target" }
val raw = installed.readBytes()
val info = AmazonNative.inspect(raw) ?: error("The installed Amazon manifest could not be verified")
require(!info.has("error")) { info.optString("error", "The installed Amazon manifest could not be verified") }
require(info.optInt("unverifiableFiles", 0) == 0) { "Amazon's installed manifest has file hashes DroidDeck cannot verify; Repair cannot safely replace those files" }
Triple(game.sidecar.installVersion, installed, info.optLong("totalBytes", 0L))
} else {
val raw = AmazonApiClient.getBytes(AmazonApiClient.appendPath(current.downloadUrl, "manifest.proto"), token)
?: error("Amazon's update manifest could not be downloaded")
val info = AmazonNative.inspect(raw) ?: error("Amazon's update manifest could not be read")
require(!info.has("error")) { info.optString("error", "Amazon's update manifest could not be read") }
require(info.optInt("unverifiableFiles", 0) == 0) { "Amazon's update manifest has file hashes DroidDeck cannot verify; it cannot safely replace those files" }
val target = File(dir, "target.manifest")
val temp = File(dir, "target.manifest.tmp")
require(!Files.isSymbolicLink(temp.toPath())) { "Amazon maintenance metadata is a symbolic link" }
temp.writeBytes(raw)
try { Files.move(temp.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING) }
Triple(current.versionId, target, info.optLong("totalBytes", 0L))
}
val target = JSONObject().put("schema", TARGET_SCHEMA).put("versionId", version)
.put("manifestPath", path.absolutePath)
return MaintenanceProposal(
game.folder.canonicalFile, game.sidecar, "Version $version", action,
downloadBytes = bytes, diskBytes = bytes, description = "Up to ${com.droiddeck.launcher.stores.formatBytes(bytes)} of whole-file data; existing files are verified against Amazon's manifest.",
target = target,
)
}
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
check(proposal.operation == MaintenanceAction.UPDATE || proposal.operation == MaintenanceAction.REPAIR)
val target = validateTarget(game, proposal.target)
return enqueueJob(context, game, target, proposal.downloadBytes, proposal.operation)
}
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) {
require(operation.optString("phase") in setOf("queued", "download", "applying")) { "The Amazon operation needs attention before it can resume" }
val target = validateTarget(game, operation.getJSONObject("target"))
val bytes = operation.optLong("downloadBytes", 0L).coerceAtLeast(0L)
check(enqueueJob(context, game, target, bytes, MaintenanceAction.valueOf(operation.getString("operation")))) {
"Amazon maintenance is already queued"
}
}
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
val phase = runCatching { StoreMaintenance.readOperation(game.folder)?.optString("phase").orEmpty() }.getOrDefault("")
return if (phase in setOf("queued", "download", "applying")) MaintenanceRecovery(RecoveryState.RESUMABLE, phase)
else if (phase.isNotEmpty()) MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, phase) else MaintenanceRecovery()
}
private fun validateTarget(game: InstalledStoreGame, target: JSONObject): JSONObject {
require(target.optInt("schema") == TARGET_SCHEMA) { "The saved Amazon maintenance target is unsupported" }
require(target.optString("versionId").isNotBlank()) { "The saved Amazon target has no version ID" }
val rawPath = File(target.optString("manifestPath"))
require(!Files.isSymbolicLink(rawPath.toPath())) { "The saved Amazon manifest is a symbolic link" }
val path = rawPath.canonicalFile
require(path.path.startsWith(game.folder.canonicalPath + File.separator) && path.isFile) {
"The saved Amazon manifest is unavailable or outside the install folder"
}
val checked = AmazonNative.inspect(path.readBytes()) ?: error("The saved Amazon manifest could not be verified")
require(!checked.has("error")) { checked.optString("error", "The saved Amazon manifest could not be verified") }
require(checked.optInt("unverifiableFiles", 0) == 0) { "Amazon's saved manifest has file hashes DroidDeck cannot verify; it cannot safely replace those files" }
return JSONObject(target.toString()).put("manifestPath", path.absolutePath)
}
private fun enqueueJob(context: Context, game: InstalledStoreGame, target: JSONObject, bytes: Long, action: MaintenanceAction): Boolean {
val app = context.applicationContext
val sidecar = game.sidecar
val item = CatalogItem(Store.AMAZON, sidecar.id, sidecar.title, sidecar.hero, tallImageUrl = sidecar.cover,
extra = mapOf("entitlementId" to sidecar.extra["entitlementId"].orEmpty(), "sku" to sidecar.extra["sku"].orEmpty(),
StoreMaintenance.OPERATION_KEY to action.name, StoreMaintenance.FOLDER_KEY to game.folder.absolutePath))
return DownloadQueue.enqueueIfIdle(app, DownloadEntry(Store.AMAZON, item.id, item.title, cover = item.tallImageUrl,
bytesTotal = bytes, location = StoreInstallRoot.labelFor(app, game.folder)), onAccepted = {
SavedQueue.remember(app, item, null)
}) {
AmazonInstaller(app, item, game.folder, target, game)
}
}
}
@@ -19,6 +19,8 @@ import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
@@ -176,6 +178,18 @@ object BattleNetInstall {
fun checkUpdate(context: Context, game: InstalledStoreGame, force: Boolean = false) = check(game.sidecar.id, game.folder, force)
fun maintenanceCheck(context: Context, game: InstalledStoreGame): MaintenanceCheck {
val product = product(game.sidecar.id)
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Battle.net does not support this installed product")
val local = runCatching { buildKey(File(game.folder, BUILD_INFO).readText()) }.getOrNull()
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "The installed Battle.net build is unknown")
val latest = runCatching { latestBuild(fetch(VERSIONS.format(Locale.ROOT, local.first, product)), local.first) }
.getOrElse { return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = it.message ?: "Battle.net update check failed") }
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Battle.net did not provide a build for region ${local.first}")
return if (latest == local.second) MaintenanceCheck(MaintenanceCheckState.CURRENT, latest)
else MaintenanceCheck(MaintenanceCheckState.AVAILABLE, latest)
}
internal fun check(id: String, folder: File, force: Boolean) {
val product = product(id) ?: return
val now = System.currentTimeMillis()
@@ -271,8 +285,9 @@ internal class BattleNetInstaller(
var reason: String? = null
val code = BattleNetInstall.run(app, args, cancelled) { line ->
when {
line.startsWith(BattleNetInstall.PROGRESS) ->
runCatching { JSONObject(line.removePrefix(BattleNetInstall.PROGRESS)) }.getOrNull()?.let { progress(handle, it) }
line.startsWith(BattleNetInstall.PROGRESS) -> runCatching { JSONObject(line.removePrefix(BattleNetInstall.PROGRESS)) }.getOrNull()?.let {
progress(handle, it)
}
line == BattleNetInstall.STATE + "waiting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_waiting))
line == BattleNetInstall.STATE + "queued" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_queued))
line == BattleNetInstall.STATE + "starting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting))
@@ -0,0 +1,40 @@
package com.droiddeck.launcher.stores.battlenet
import android.content.Context
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
import com.droiddeck.launcher.stores.maintenance.RecoveryState
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import org.json.JSONObject
internal object BattleNetMaintenanceAdapter : StoreMaintenanceAdapter {
override val store = Store.BATTLENET
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> = setOf(MaintenanceAction.OPEN_CLIENT)
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck =
BattleNetInstall.maintenanceCheck(context, game)
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal =
error("Battle.net updates must use its Agent/client workflow")
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean =
error("Battle.net updates must use its Agent/client workflow")
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject): Unit =
error("Resume this Battle.net operation through its Agent/client workflow")
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
if (StoreMaintenance.readOperation(game.folder) == null) return MaintenanceRecovery()
return MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, "Inspect this update in Battle.net before launching the game")
}
override fun openClient(context: Context, game: InstalledStoreGame) = BattleNetClient.open(emptyList())
override fun openClientLabel(game: InstalledStoreGame) = "Open Battle.net for Scan and Repair"
}
@@ -19,6 +19,7 @@ import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
@@ -153,6 +154,7 @@ object BattleNetClient {
object BattleNetBackend : StoreBackend {
override val store: Store = Store.BATTLENET
override fun maintenanceAdapter(): StoreMaintenanceAdapter = BattleNetMaintenanceAdapter
override fun signIn(context: Context) = BattleNetClient.signIn(context)
@@ -31,6 +31,9 @@ data class DownloadEntry(
val stageItemsTotal: Int = 0,
val diskBytes: Long = 0L,
val stagesPassed: Int = 0,
val interruptible: Boolean = true,
val reusedBytes: Long = 0L,
val appliedBytes: Long = 0L,
) {
fun passed(s: DownloadStage): Boolean = state == DownloadState.INSTALLED || (stagesPassed and (1 shl s.ordinal)) != 0
@@ -21,6 +21,11 @@ object DownloadQueue {
fun diskSize(bytes: Long) = update(key) { if (bytes > 0) it.copy(diskBytes = bytes) else it }
fun progress(bytesDone: Long, bytesTotal: Long, detail: String? = null, @Suppress("UNUSED_PARAMETER") speedBps: Long = -1L) = measure(key, bytesDone, bytesTotal, detail?.let(::stripSpeed))
fun log(line: String) = StoresState.logLine(line)
fun interruptible(value: Boolean) = update(key) {
check(value || !cancelled.get()) { "The operation was paused before installer application" }
it.copy(interruptible = value)
}
fun maintenance(reusedBytes: Long, appliedBytes: Long) = update(key) { it.copy(reusedBytes = reusedBytes, appliedBytes = appliedBytes) }
}
private fun stripSpeed(s: String): String = s.replace(Regex("\\s+\\S+ [KMG]B/s\\s*$"), "").trimEnd()
@@ -124,9 +129,32 @@ object DownloadQueue {
fun isActive(key: String): Boolean = entry(key)?.isActive == true
fun enqueue(context: Context, entry: DownloadEntry, factory: () -> DownloadJob) {
enqueueInternal(context, entry, onAccepted = {}, factory = factory)
}
/** Enqueues only if the key is idle, running [onAccepted] atomically before the accepted row is saved. */
fun enqueueIfIdle(
context: Context,
entry: DownloadEntry,
onAccepted: () -> Unit,
factory: () -> DownloadJob,
): Boolean = enqueueInternal(context, entry, onAccepted = onAccepted, factory = factory)
private fun enqueueInternal(
context: Context,
entry: DownloadEntry,
onAccepted: () -> Unit,
factory: () -> DownloadJob,
): Boolean {
val app = context.applicationContext
synchronized(lock) {
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return } }
items[entry.key]?.let {
if (it.entry.isActive) {
Log.i(TAG, "${entry.key}: already queued")
return false
}
}
onAccepted()
items.remove(entry.key)
val state = if (heldPaused.remove(entry.key)) DownloadState.PAUSED else DownloadState.QUEUED
items[entry.key] = Item(entry.copy(state = state, stage = DownloadStage.MANIFEST, startedAt = System.currentTimeMillis()), factory)
@@ -135,6 +163,7 @@ object DownloadQueue {
StoresState.logLine("${entry.store.label}: queued \"${entry.name}\"" + if (entry.bytesTotal > 0) " (${com.droiddeck.launcher.stores.formatBytes(entry.bytesTotal)})" else "")
publish(app)
advance(app)
return true
}
/** Immediately records a failed download (e.g. from pre-flight storage check). */
@@ -166,12 +195,13 @@ object DownloadQueue {
fun pause(key: String) {
val item = synchronized(lock) { items[key] } ?: return
synchronized(lock) {
if (!item.entry.interruptible) return
if (item.entry.state == DownloadState.QUEUED) { item.entry = item.entry.copy(state = DownloadState.PAUSED, queuePosition = 0); renumber(); publishLocked(); return }
if (item.entry.state != DownloadState.RUNNING) return
item.pauseRequested = true
item.cancelled.set(true)
item.job?.cancel(deleteFiles = false)
}
item.cancelled.set(true)
item.job?.cancel(deleteFiles = false)
StoresState.logLine("paused \"${item.entry.name}\"")
}
@@ -204,17 +234,19 @@ object DownloadQueue {
val wasRunning: Boolean
synchronized(lock) {
item = items[key] ?: return
if (!item.entry.interruptible) return
wasRunning = item.entry.state == DownloadState.RUNNING
if (wasRunning) {
item.cancelled.set(true)
item.job?.cancel(deleteFiles = true)
}
if (!wasRunning) {
item.entry = item.entry.copy(state = DownloadState.CANCELLED, queuePosition = 0, finishedAt = System.currentTimeMillis())
renumber()
publishLocked()
}
}
if (wasRunning) {
item.cancelled.set(true)
item.job?.cancel(deleteFiles = true)
} else {
if (!wasRunning) {
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-cancel").start()
}
StoresState.logLine("cancelled \"${item.entry.name}\"")
@@ -45,7 +45,7 @@ object SavedQueue {
val f = File(context.filesDir, FILE)
val tmp = File(context.filesDir, "$FILE.tmp")
tmp.writeText(out.toString())
tmp.renameTo(f)
java.nio.file.Files.move(tmp.toPath(), f.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}.onFailure { Log.w(TAG, "could not save the queue", it) }
}
}
@@ -68,7 +68,13 @@ object SavedQueue {
for ((item, root, paused) in back) {
if (DownloadQueue.entry(key(item)) != null) continue
if (paused) DownloadQueue.holdPaused(key(item))
StoresState.install(app, item, root)
if (item.extra.containsKey(com.droiddeck.launcher.stores.maintenance.StoreMaintenance.OPERATION_KEY) ||
item.store == Store.GOG && item.extra.containsKey(com.droiddeck.launcher.stores.gog.GogMaintenance.OPERATION)) {
Thread({
runCatching { com.droiddeck.launcher.stores.maintenance.StoreMaintenance.restore(app, item) }
.onFailure { DownloadQueue.recordFailed(app, DownloadEntry(item.store, item.id, item.title), it.message ?: "${item.store.label} recovery failed") }
}, "store-maintenance-restore").start()
} else StoresState.install(app, item, root)
}
}
}, "store-queue-restore").start()
@@ -14,10 +14,12 @@ import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import com.droiddeck.launcher.stores.mergeItems
object EpicBackend : StoreBackend, EpicLaunchSupport {
override val store: Store = Store.EPIC
override fun maintenanceAdapter(): StoreMaintenanceAdapter = EpicMaintenanceAdapter
init {
LoginFlows.epicFlow = { EpicLogin.create() }
@@ -13,6 +13,8 @@ import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.StoreDownloadTier
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
@@ -23,6 +25,8 @@ internal class EpicInstaller(
private val app: Context,
private val item: CatalogItem,
private val folder: File,
private val maintenance: JSONObject? = null,
private val maintenanceGame: InstalledStoreGame? = null,
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val namespace = item.extra["namespace"].orEmpty()
@@ -36,7 +40,14 @@ internal class EpicInstaller(
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_sync_sign_in))
val token = EpicCredentialStore.getValidAccessToken(app) ?: throw IllegalStateException("Not signed in to Epic Games")
val cover = item.tallImageUrl ?: item.imageUrl
StoreInstalls.begin(folder, Store.EPIC, item.id, item.title, cover, item.imageUrl)
val tags = maintenance?.optJSONArray("tags")?.let { a -> List(a.length()) { a.optString(it) } }
?: EpicInstallTags.tagsFor(installLocale())
val priorTagsRaw = maintenanceGame?.sidecar?.extra?.get("installTags")
?: StoreGameSidecar.read(folder)?.extra?.get("installTags").orEmpty()
val previousTags = runCatching {
if (priorTagsRaw.isBlank()) tags else JSONArray(priorTagsRaw).let { a -> List(a.length()) { a.optString(it) } }
}.getOrDefault(tags)
if (maintenance == null) StoreInstalls.begin(folder, Store.EPIC, item.id, item.title, cover, item.imageUrl)
if (cancelled.get()) return null
handle.stage(DownloadStage.MANIFEST, "Reading the build list…")
@@ -50,13 +61,16 @@ internal class EpicInstaller(
.put("gameDir", folder.absolutePath)
.put("scratchDir", if (StoreInstallRoot.isRemovable(app, folder)) scratch().absolutePath else "")
.put("storageLabel", StoreInstallRoot.labelFor(app, folder))
.put("tags", JSONArray(EpicInstallTags.tagsFor(installLocale())))
.put("tags", JSONArray(tags))
.put("previousTags", JSONArray(previousTags))
.put("maxWorkers", tier.networkWindow.coerceIn(1, 128))
.put("processWorkers", tier.processWorkers)
.put("caBundle", "")
maintenance?.let { request.put("targetManifestPath", it.getString("manifestPath")) }
val shown = AtomicLong(-1)
val installing = AtomicBoolean(false)
var applyLease: AutoCloseable? = null
val prefs = EpicPrefs.get(app)
val listener = object : EpicNative.InstallListener {
override fun onStatus(text: String) { handle.stage(DownloadStage.MANIFEST, text) }
@@ -90,7 +104,8 @@ internal class EpicInstaller(
override fun onLog(line: String) { handle.log("epic: $line") }
override fun beforeReplace(): Boolean = try {
StoreInstalls.markUpdating(folder)
if (maintenance == null) StoreInstalls.markUpdating(folder)
else if (applyLease == null) applyLease = StoreMaintenance.beginApplyLease(maintenanceGame!!)
true
} catch (e: Exception) {
handle.log("epic: the install record could not be switched to updating (${e.javaClass.simpleName})")
@@ -100,11 +115,21 @@ internal class EpicInstaller(
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) = Unit
}
val outcome = EpicNative.install(request, listener, cancelled)
val outcome = try { EpicNative.install(request, listener, cancelled) }
finally { runCatching { applyLease?.close() } }
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "Native Epic install failed" })
val result = outcome.result ?: JSONObject()
if (maintenance != null && maintenanceGame != null) {
if (applyLease == null) StoreMaintenance.beginApplyLease(maintenanceGame).close()
val extra = LinkedHashMap(maintenanceGame.sidecar.extra)
maintenance.optString("deploymentId").takeIf { it.isNotBlank() }?.let { extra["deploymentId"] = it }
maintenance.optString("buildInfoVersion").takeIf { it.isNotBlank() }?.let { extra["buildInfoVersion"] = it }
StoreMaintenance.complete(app, maintenanceGame, result.optString("buildVersion"), extra)
return folder.path
}
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
val picked = StoreExe.pick(folder, result.optString("launchExe"), item.title)
if (picked.isEmpty()) handle.log("epic: no exe found in ${folder.name}; pick one in Steam settings › Added games")
@@ -125,7 +150,9 @@ internal class EpicInstaller(
extra["namespace"] = namespace
extra["catalogItemId"] = catalogItemId
if (deployment.isNotEmpty()) extra["deploymentId"] = deployment
extra["buildInfoVersion"] = JSONObject(info).optString("buildVersion")
extra[StoreLanguage.EXTRA] = item.extra[StoreLanguage.EXTRA] ?: StoreLanguage.preferredCode(app)
extra["installTags"] = JSONArray(EpicInstallTags.tagsFor(installLocale())).toString()
extra[WinCompSources.EPIC_PREREQ_PATH] = result.optString("prereqPath")
extra[WinCompSources.EPIC_PREREQ_NAME] = result.optString("prereqName")
if (result.optBoolean("prereqRead", false)) extra[WinCompSources.LIST_READ] = "1"
@@ -0,0 +1,170 @@
package com.droiddeck.launcher.stores.epic
import android.content.Context
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.SavedQueue
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
import com.droiddeck.launcher.stores.maintenance.RecoveryState
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
internal object EpicMaintenanceAdapter : StoreMaintenanceAdapter {
override val store: Store = Store.EPIC
private const val TARGET_SCHEMA = 1
private const val INSTALLED_MANIFEST = ".droiddeck-maintenance/epic/installed.manifest"
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> = buildSet {
val extra = game.sidecar.extra
if (extra["namespace"].orEmpty().isNotBlank() && extra["catalogItemId"].orEmpty().isNotBlank()) add(MaintenanceAction.UPDATE)
if (game.sidecar.installVersion.isNotBlank() && File(game.folder, INSTALLED_MANIFEST).isFile) add(MaintenanceAction.REPAIR)
}
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck {
val token = EpicCredentialStore.getValidAccessToken(context)
?: return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "Not signed in to Epic Games")
val info = currentInfo(token, game.sidecar.id, game.sidecar.extra)
val latest = info.optString("buildVersion")
if (latest.isBlank()) return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Epic did not provide a build version")
val installed = game.sidecar.extra["buildInfoVersion"].orEmpty().ifBlank { game.sidecar.installVersion }
if (installed.isBlank()) return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, latest, "The installed Epic build is unknown")
return MaintenanceCheck(if (latest == installed) MaintenanceCheckState.CURRENT else MaintenanceCheckState.AVAILABLE, latest)
}
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
require(action == MaintenanceAction.UPDATE || action == MaintenanceAction.REPAIR) { "Epic supports Update and Repair" }
require(action in capabilities(game)) { "The installed Epic record is missing the data required for ${action.name.lowercase()}" }
require(StoreMaintenance.readOperation(game.folder) == null) { "Resume or recover the existing Epic operation first" }
val token = EpicCredentialStore.getValidAccessToken(context) ?: error("Not signed in to Epic Games")
val info = currentInfo(token, game.sidecar.id, game.sidecar.extra)
val tags = installedTags(context, game)
val buildInfoVersion = info.optString("buildVersion").ifBlank { error("Epic did not provide a build version") }
val dir = File(game.folder, ".droiddeck-maintenance/epic")
require(!Files.isSymbolicLink(File(game.folder, ".droiddeck-maintenance").toPath()) && !Files.isSymbolicLink(dir.toPath())) {
"Epic maintenance metadata is a symbolic link"
}
dir.mkdirs()
val targetPath: File
val manifestBytes: ByteArray
val targetBuild: String
val deploymentId: String
if (action == MaintenanceAction.REPAIR) {
targetPath = File(game.folder, INSTALLED_MANIFEST)
require(targetPath.isFile && !Files.isSymbolicLink(targetPath.toPath())) { "The installed Epic manifest is unavailable; repair cannot safely choose a target" }
manifestBytes = targetPath.readBytes()
val parsed = EpicNative.inspect(manifestBytes, JSONObject()) ?: error("The installed Epic manifest could not be read")
require(!parsed.has("error")) { parsed.optString("error", "The installed Epic manifest could not be read") }
targetBuild = parsed.optString("buildVersion").ifBlank { error("The installed Epic manifest has no build version") }
deploymentId = game.sidecar.extra["deploymentId"].orEmpty()
} else {
manifestBytes = EpicNative.fetch("manifest.download", JSONObject().put("info", info))
?: error("Epic's update manifest could not be downloaded")
val parsed = EpicNative.inspect(manifestBytes, JSONObject()) ?: error("Epic's update manifest could not be read")
require(!parsed.has("error")) { parsed.optString("error", "Epic's update manifest could not be read") }
targetBuild = parsed.optString("buildVersion").ifBlank { buildInfoVersion }
deploymentId = info.optString("deploymentId")
targetPath = File(dir, "target.manifest")
val temp = File(dir, "target.manifest.tmp")
require(!Files.isSymbolicLink(temp.toPath())) { "Epic maintenance metadata is a symbolic link" }
temp.writeBytes(manifestBytes)
try { Files.move(temp.toPath(), targetPath.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(temp.toPath(), targetPath.toPath(), StandardCopyOption.REPLACE_EXISTING) }
}
val estimate = EpicNative.inspect(manifestBytes, JSONObject().put("op", "estimate").put("tags", JSONArray(tags)))
?: error("Epic's target manifest could not be checked")
require(!estimate.has("error")) { estimate.optString("error", "Epic's target manifest could not be checked") }
val downloadBytes = estimate.optLong("downloadBytes", -1L)
val diskBytes = estimate.optLong("diskBytes", -1L)
require(downloadBytes >= 0 && diskBytes >= 0) { "Epic's target manifest has an invalid size estimate" }
val target = JSONObject().put("schema", TARGET_SCHEMA).put("buildVersion", targetBuild)
.put("buildInfoVersion", if (action == MaintenanceAction.REPAIR) game.sidecar.extra["buildInfoVersion"].orEmpty() else buildInfoVersion)
.put("deploymentId", deploymentId)
.put("manifestPath", targetPath.absolutePath).put("tags", JSONArray(tags))
return MaintenanceProposal(
game.folder.canonicalFile, game.sidecar,
if (action == MaintenanceAction.REPAIR) "Installed build $targetBuild" else "Build $targetBuild", action,
downloadBytes = downloadBytes, diskBytes = diskBytes,
description = "Up to ${com.droiddeck.launcher.stores.formatBytes(downloadBytes)} of unique Epic chunks; files are SHA-1 verified against the pinned manifest.",
target = target,
)
}
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
check(proposal.operation == MaintenanceAction.UPDATE || proposal.operation == MaintenanceAction.REPAIR)
val target = validateTarget(game, proposal.target)
return enqueueJob(context, game, target, proposal.downloadBytes, proposal.operation)
}
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) {
require(operation.optString("phase") in setOf("queued", "download", "applying")) { "The Epic operation needs attention before it can resume" }
val target = validateTarget(game, operation.getJSONObject("target"))
check(enqueueJob(context, game, target, operation.optLong("downloadBytes", 0L).coerceAtLeast(0L),
MaintenanceAction.valueOf(operation.getString("operation")))) { "Epic maintenance is already queued" }
}
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
val phase = runCatching { StoreMaintenance.readOperation(game.folder)?.optString("phase").orEmpty() }.getOrDefault("")
return if (phase in setOf("queued", "download", "applying")) MaintenanceRecovery(RecoveryState.RESUMABLE, phase)
else if (phase.isNotEmpty()) MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, phase) else MaintenanceRecovery()
}
private fun validateTarget(game: InstalledStoreGame, target: JSONObject): JSONObject {
require(target.optInt("schema") == TARGET_SCHEMA) { "The saved Epic maintenance target is unsupported" }
require(target.optString("buildVersion").isNotBlank()) { "The saved Epic target has no build version" }
val rawPath = File(target.optString("manifestPath"))
require(!Files.isSymbolicLink(rawPath.toPath())) { "The saved Epic manifest is a symbolic link" }
val path = rawPath.canonicalFile
require(path.path.startsWith(game.folder.canonicalPath + File.separator) && path.isFile) {
"The saved Epic manifest is unavailable or outside the install folder"
}
val parsed = EpicNative.inspect(path.readBytes(), JSONObject()) ?: error("The saved Epic manifest could not be verified")
require(!parsed.has("error") && parsed.optString("buildVersion") == target.optString("buildVersion")) {
"The saved Epic manifest does not match the pinned build"
}
return JSONObject(target.toString()).put("manifestPath", path.absolutePath)
}
private fun currentInfo(token: String, id: String, extra: Map<String, String>): JSONObject {
val namespace = extra["namespace"].orEmpty().ifBlank { error("The Epic namespace is missing from the install record") }
val catalog = extra["catalogItemId"].orEmpty().ifBlank { error("The Epic catalog item ID is missing from the install record") }
val raw = EpicApiClient.getManifestApiJson(token, namespace, catalog, extra["appName"] ?: id)
?: error("Epic's current build information could not be fetched")
return JSONObject(raw)
}
private fun installedTags(context: Context, game: InstalledStoreGame): List<String> = runCatching {
val raw = game.sidecar.extra["installTags"].orEmpty()
val array = JSONArray(raw)
List(array.length()) { array.getString(it) }.filter { it.isNotBlank() }
}.getOrElse {
EpicInstallTags.tagsFor(StoreLanguage.localeFor(game.sidecar.extra[StoreLanguage.EXTRA], context))
}
private fun enqueueJob(context: Context, game: InstalledStoreGame, target: JSONObject, bytes: Long, action: MaintenanceAction): Boolean {
val app = context.applicationContext
val sidecar = game.sidecar
val extra = LinkedHashMap(sidecar.extra)
val item = CatalogItem(Store.EPIC, sidecar.id, sidecar.title, sidecar.hero, tallImageUrl = sidecar.cover,
extra = extra + mapOf(StoreMaintenance.OPERATION_KEY to action.name, StoreMaintenance.FOLDER_KEY to game.folder.absolutePath))
return DownloadQueue.enqueueIfIdle(app, DownloadEntry(Store.EPIC, item.id, item.title, cover = item.tallImageUrl,
bytesTotal = bytes, location = StoreInstallRoot.labelFor(app, game.folder)), onAccepted = {
SavedQueue.remember(app, item, null)
}) {
EpicInstaller(app, item, game.folder, target, game)
}
}
}
@@ -33,6 +33,7 @@ object GogAuth {
@Synchronized
private fun saveAccount(context: Context, accessToken: String, refreshToken: String?, userId: String?) {
GogMaintenance.reset()
var username = ""
runCatching {
val body = StoreNet.get("https://embed.gog.com/userData.json", bearer = accessToken, userAgent = GALAXY_UA)
@@ -28,6 +28,7 @@ object GogBackend : StoreBackend {
}
override fun signOut(context: Context) {
GogMaintenance.reset()
GogPrefs.get(context).edit().remove("library_cache").remove("library_cache_v2").remove("library_synced_at").apply()
}
@@ -53,7 +54,11 @@ object GogBackend : StoreBackend {
StoresState.post {
StoresState.status.remove(store)
when (result) {
is GogLibrary.SyncResult.Ok -> { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store) }
is GogLibrary.SyncResult.Ok -> {
StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) })
StoresState.problems.remove(store)
GogMaintenance.checkInstalled(app, StoresState.installed)
}
is GogLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
GogLibrary.SyncResult.Busy -> {}
@@ -0,0 +1,187 @@
package com.droiddeck.launcher.stores.gog
import android.content.Context
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoreNet
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.util.zip.GZIPInputStream
import java.util.zip.InflaterInputStream
internal object GogContent {
const val SYSTEM = "https://content-system.gog.com"
const val CDN = "https://gog-cdn-fastly.gog.com/content-system"
fun token(context: Context) = GogAuth.validToken(context) ?: error("Sign in to GOG and retry")
fun builds(id: String, token: String): JSONObject {
val result = json("$SYSTEM/products/$id/os/windows/builds?generation=2", token)
if (result.optJSONArray("items")?.length() != 0) return result
return json("$SYSTEM/products/$id/os/windows/builds?generation=1", token)
}
fun product(id: String, token: String): JSONObject = json("https://api.gog.com/products/$id?expand=downloads", token)
fun downloadFilename(url: String): String = java.net.URLDecoder.decode(URL(url).path.substringAfterLast('/').replace("+", "%2B"), "UTF-8")
fun resolveDownload(download: GogOfflineDownload, token: String): GogOfflineDownload = download.copy(parts = download.parts.map { part ->
val resolved = GogDownloadManager.resolveRedirect(part.url, token) ?: error("The GOG download link is unavailable")
val connection = URL(resolved).openConnection() as HttpURLConnection
try {
connection.requestMethod = "HEAD"
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
check(connection.responseCode in 200..299) { "GOG download metadata failed (HTTP ${connection.responseCode})" }
val disposition = connection.getHeaderField("Content-Disposition").orEmpty()
val supplied = Regex("filename=\"?([^\";]+)", RegexOption.IGNORE_CASE).find(disposition)?.groupValues?.get(1).orEmpty()
val remote = downloadFilename(resolved).takeIf { it.endsWith(".exe", true) || it.endsWith(".bin", true) }.orEmpty()
val name = part.name.ifBlank { supplied.ifBlank { remote } }
check(name.isNotBlank()) { "GOG did not provide the installer part filename" }
part.copy(name = name, size = connection.contentLengthLong.coerceAtLeast(0))
} finally { connection.disconnect() }
})
fun json(url: String, token: String? = null): JSONObject {
require(URL(url).protocol == "https") { "GOG metadata requires HTTPS" }
val connection = URL(url).openConnection() as HttpURLConnection
try {
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
connection.setRequestProperty("User-Agent", GogAuth.GALAXY_UA)
if (token != null && URL(url).host.let { it == "gog.com" || it.endsWith(".gog.com") }) connection.setRequestProperty("Authorization", "Bearer $token")
check(connection.responseCode in 200..299) { "GOG metadata request failed (HTTP ${connection.responseCode})" }
val raw = connection.inputStream.readBytes()
val text = when {
raw.size > 1 && raw[0] == 0x78.toByte() -> InflaterInputStream(raw.inputStream()).bufferedReader().use { it.readText() }
raw.size > 1 && raw[0] == 0x1f.toByte() && raw[1] == 0x8b.toByte() -> GZIPInputStream(raw.inputStream()).bufferedReader().use { it.readText() }
else -> raw.toString(Charsets.UTF_8)
}
return JSONObject(text)
} finally { connection.disconnect() }
}
fun snapshot(old: GogInstallRecord, build: GogBuild, token: String,
metadata: (String, String?) -> JSONObject = ::json): GogInstallRecord {
check(build.link.isNotBlank()) { "GOG build manifest is unavailable" }
val manifest = metadata(build.link, token)
val files = JSONArray()
val depots = if (build.generation == 1) manifest.optJSONObject("product")?.optJSONArray("depots") ?: manifest.optJSONArray("depot") else manifest.optJSONArray("depots")
check(depots != null) { "GOG build has no depot list" }
val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language)
val selectedBitness = if (depots.objects().any { it.optJSONArray("osBitness")?.strings()?.contains("64") == true }) "64" else "32"
val owned = if (old.products.any { it != old.id }) StoreNet.get("https://embed.gog.com/user/data/games", bearer = token)?.let { JSONObject(it).optJSONArray("owned")?.strings()?.toSet() } else emptySet()
val products = old.products.filter { it == old.id || owned?.contains(it) == true }
check(old.products.all { it == old.id || owned?.contains(it) == true }) { "Could not confirm ownership of installed GOG DLC" }
for (depot in depots.objects()) {
if (depot.has("redist")) continue
val ids = depot.optJSONArray("gameIDs")?.strings() ?: listOf(depot.optString("productId", old.id))
val product = ids.firstOrNull { it in products } ?: continue
val languages = depot.optJSONArray("languages")?.strings().orEmpty()
if (!languageSelected(languages, resolvedLanguage)) continue
val bitness = depot.optJSONArray("osBitness")?.strings().orEmpty()
if (bitness.isNotEmpty() && selectedBitness !in bitness) continue
val hash = depot.optString("manifest")
val content = when {
hash.isNotEmpty() && build.generation == 2 -> metadata("$CDN/v2/meta/${cdnPath(hash)}", null)
hash.isNotEmpty() -> {
val timestamp = manifest.getJSONObject("product").getString("timestamp")
metadata("$CDN/v1/manifests/$product/windows/$timestamp/$hash", token)
}
depot.has("files") -> JSONObject().put("depot", depot)
else -> error("GOG depot manifest is missing")
}
val entries = content.getJSONObject("depot").optJSONArray(if (build.generation == 2) "items" else "files") ?: error("GOG depot files are missing")
for (entry in entries.objects()) {
val type = entry.optString("type")
check(type != "DepotLink") { "This GOG build contains unsupported file links" }
val support = depot.optBoolean("support") || entry.optBoolean("support") || entry.optJSONArray("flags")?.strings()?.contains("support") == true
val relative = entry.getString("path").replace('\\', '/').trimEnd('/').let { if (build.generation == 1) it.trimStart('/') else it }
val path = if (support) (if (build.generation == 1) "support/$relative" else "support/$product/$relative") else relative
val directory = type == "DepotDirectory" || entry.has("directory")
val chunks = entry.optJSONArray("chunks") ?: JSONArray()
val size = if (build.generation == 2) chunks.objects().sumOf { it.optLong("size") } else entry.optLong("size")
files.put(JSONObject().put("path", path).put("size", size).put("directory", directory)
.put("md5", entry.optString("md5").ifBlank { entry.optString("hash") }.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) }.orEmpty())
.put("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product)
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?')))
}
}
check(files.length() > 0) { "GOG build contains no matching files" }
return old.copy(source = "depot", generation = build.generation, build = build.id, version = build.version,
branch = build.branch, language = resolvedLanguage, manifest = sanitize(manifest), files = files, products = products, verified = true)
}
fun languageSelected(list: List<String>, selected: String): Boolean = list.any { it.equals("Neutral", true) } || StoreLanguage.depotMatchesResolved(list.toTypedArray(), selected)
fun cdnPath(hash: String): String {
require(hash.matches(Regex("[a-fA-F0-9]{32,64}"))) { "Invalid GOG content hash" }
return "${hash.take(2)}/${hash.substring(2, 4)}/$hash"
}
fun links(record: GogInstallRecord, token: String, patches: Boolean = false): JSONObject {
val out = JSONObject()
for (id in record.products) {
val path = if (record.generation == 1) "/windows/${record.manifest.optJSONObject("product")?.optString("timestamp")}/" else "/"
val query = "_version=2&" + (if (record.generation == 1) "type=depot" else "generation=2") + "&path=${java.net.URLEncoder.encode(path, "UTF-8")}" + if (patches) "&root=%2Fpatches%2Fstore" else ""
val response = json("$SYSTEM/products/$id/secure_link?$query", token)
val bases = response.optJSONArray("urls")?.objects().orEmpty().mapNotNull { item ->
val params = item.optJSONObject("parameters")
var url = item.optString("url_format")
params?.keys()?.forEach { key -> url = url.replace("{$key}", params.getString(key)) }
url.takeIf { it.startsWith("https://") }
}
check(bases.isNotEmpty()) { "GOG refused a download link" }
out.put(id, JSONArray(bases))
}
return out
}
fun patches(old: GogInstallRecord, target: GogInstallRecord, token: String): JSONArray {
if (old.generation != 2 || target.generation != 2 || old.build.isBlank() || old.build == target.build) return JSONArray()
return runCatching {
val index = json("$SYSTEM/products/${old.id}/patches?_version=4&from_build_id=${old.build}&to_build_id=${target.build}", token)
val meta = json(index.getString("link"), token)
if (meta.optString("algorithm") != "xdelta3") return@runCatching JSONArray()
val result = JSONArray()
for (depot in meta.getJSONArray("depots").objects()) {
if (depot.optString("productId") !in target.products || !languageSelected(depot.optJSONArray("languages")?.strings().orEmpty(), target.language)) continue
val data = json("$CDN/v2/patches/meta/${cdnPath(depot.getString("manifest"))}")
for (item in data.getJSONObject("depot").getJSONArray("items").objects()) if (item.optString("type") == "DepotDiff")
result.put(JSONObject(item.toString()).put("product", depot.getString("productId")))
}
result
}.getOrElse { JSONArray() }
}
fun setupFiles(record: GogInstallRecord, token: String): Pair<JSONArray, JSONObject>? {
if (!record.manifest.optBoolean("scriptInterpreter")) return null
if (record.files.objects().none { file -> record.products.any { file.optString("path").substringAfterLast('/') == "goggame-$it.script" } }) return null
val index = json("$SYSTEM/dependencies/repository?generation=2")
val repository = json(index.getString("repository_manifest"))
val depot = repository.getJSONArray("depots").objects().firstOrNull { it.optString("dependencyId") == "ISI" }
?: error("GOG setup interpreter is unavailable")
val content = json("$CDN/v2/dependencies/meta/${cdnPath(depot.getString("manifest"))}")
val files = JSONArray()
for (entry in content.getJSONObject("depot").getJSONArray("items").objects()) {
if (entry.optString("type") != "DepotFile") continue
val chunks = entry.getJSONArray("chunks")
files.put(JSONObject().put("path", "support/" + entry.getString("path").replace('\\', '/'))
.put("size", chunks.objects().sumOf { it.getLong("size") }).put("md5", entry.optString("md5"))
.put("chunks", chunks).put("product", "redist"))
}
val response = json("$SYSTEM/open_link?generation=2&_version=2&path=%2Fdependencies%2Fstore%2F", token)
val bases = GogDownloadManager.parseCdnUrls(response.toString())
check(bases.isNotEmpty()) { "GOG setup download links are unavailable" }
return files to JSONObject().put("redist", JSONArray(bases))
}
fun sanitize(value: JSONObject): JSONObject {
val result = JSONObject()
for (key in value.keys()) {
if (key.lowercase() in setOf("clientsecret", "access_token", "refresh_token", "link", "urls", "url")) continue
val v = value.get(key)
result.put(key, when (v) { is JSONObject -> sanitize(v); is JSONArray -> JSONArray((0 until v.length()).map { i -> v.get(i).let { if (it is JSONObject) sanitize(it) else it } }); else -> v })
}
return result
}
}
@@ -106,7 +106,7 @@ public final class GogDownloadManager {
String builds1Json = httpGet(builds1Url, null);
if (builds1Json == null) builds1Json = httpGet(builds1Url, token);
if (builds1Json == null) throw new InstallException("No builds available for this game");
Gen1Outcome one = runGen1(ctx, game, token, builds1Json, installPath, cb, cancelled);
Gen1Outcome one = runGen1(ctx, game, token, builds1Json, installPath, cb, cancelled, lang);
if (one.result != null || cancelled.get()) return one.result;
if (!"NO_CS_BUILDS".equals(one.error)) throw new InstallException("Download failed: " + one.error);
cb.onProgress("No Galaxy builds; fetching the installer…", 12);
@@ -250,6 +250,11 @@ public final class GogDownloadManager {
if (anyFailed.get()) { out.error = "one or more chunks failed to download"; return out; }
cb.onProgress("Finishing…", 96);
try {
GogMaintenance.captureDepot(game.gameId, installPath, gm.buildId, buildsJson, manifest, new JSONArray(depotJsons), resolved);
} catch (Exception e) {
cb.onLog("gog: maintenance inventory not recorded: " + e.getMessage());
}
writeFile(new File(installPath, MARKER), ("{\"gameId\":\"" + game.gameId + "\",\"buildId\":\"" + gm.buildId + "\"}").getBytes("UTF-8"));
deleteCounted(new File(installPath, ".gog_chunks"), cb);
String clientId = manifest.optString("clientId", null);
@@ -279,7 +284,7 @@ public final class GogDownloadManager {
String buildId = null, manifestUrl = null;
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
if ("windows".equals(item.optString("os"))) {
if ("windows".equals(item.optString("os")) && (item.isNull("branch") || item.optString("branch").isEmpty())) {
buildId = item.optString("build_id");
manifestUrl = item.optString("link");
if (manifestUrl == null || manifestUrl.isEmpty()) manifestUrl = item.optString("meta_url");
@@ -328,7 +333,7 @@ public final class GogDownloadManager {
private static final class Gen1Outcome { Result result; String error; }
private static Gen1Outcome runGen1(Context ctx, GogGame game, String token, String buildsJson, File installPath, Callback cb, AtomicBoolean cancelled) {
private static Gen1Outcome runGen1(Context ctx, GogGame game, String token, String buildsJson, File installPath, Callback cb, AtomicBoolean cancelled, String language) {
Gen1Outcome out = new Gen1Outcome();
try {
JSONObject builds = new JSONObject(buildsJson);
@@ -346,6 +351,15 @@ public final class GogDownloadManager {
String manifestStr = decompressBytes(raw);
if (manifestStr == null) { out.error = "manifest decompress failed"; return out; }
JSONObject manifest = new JSONObject(manifestStr);
if (manifest.has("product")) {
try {
out.result = GogMaintenance.installContent(ctx, game, installPath, builds, language, cb, cancelled);
if (out.result == null && !cancelled.get()) out.error = "no usable public Windows build";
} catch (Exception e) {
out.error = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
}
return out;
}
JSONArray depots = manifest.optJSONArray("depot");
if (depots == null) { out.error = "no depot array"; return out; }
List<Gen1File> files = new ArrayList<>();
@@ -472,6 +486,7 @@ public final class GogDownloadManager {
String exe = pickExe(installPath, null, game.title);
if (exe.isEmpty()) throw new InstallException("The installer was extracted but no game executable was found");
cb.onLog("gog: installer extracted natively; game exe " + exe);
GogMaintenance.captureOffline(game.gameId, installPath, downloads);
return new Result(exe, "", total);
} catch (InstallerException e) {
throw e;
@@ -576,13 +591,13 @@ public final class GogDownloadManager {
return cleaned.isEmpty() ? "game" : cleaned;
}
private static String resolveRedirect(String url, String token) {
static String resolveRedirect(String url, String token) {
try {
if (url.startsWith("/")) url = "https://www.gog.com" + url;
for (int hop = 0; hop < 5; hop++) {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setInstanceFollowRedirects(false);
if (token != null) conn.setRequestProperty("Authorization", "Bearer " + token);
if (token != null && (new URL(url).getHost().equals("gog.com") || new URL(url).getHost().endsWith(".gog.com"))) conn.setRequestProperty("Authorization", "Bearer " + token);
int code = conn.getResponseCode();
String location = conn.getHeaderField("Location");
if (code == 301 || code == 302 || code == 303 || code == 307 || code == 308) {
@@ -686,6 +701,7 @@ public final class GogDownloadManager {
cb.onBytes(shown, planned, speedBps.get());
}
@Override public void onLog(String line) { cb.onLog(line); }
@Override public void onMaintenance(long networkBytes, long reusedBytes, long appliedBytes) {}
@Override public void onComplete(boolean success, boolean wasCancelled, boolean linkExpiry, String error, long bytesWritten, int filesDone) {
okRef.set(success); linkExpiryRef.set(linkExpiry); errRef.set(error == null ? "" : error); latch.countDown();
}
@@ -0,0 +1,58 @@
package com.droiddeck.launcher.stores.gog
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.RandomAccessFile
import java.security.MessageDigest
internal object GogEstimate {
data class Size(val download: Long, val required: Long)
private data class Chunk(val file: File, val offset: Long)
fun range(file: File, offset: Long, size: Long, md5: String): Boolean {
if (!file.isFile || offset < 0 || size < 0 || file.length() < offset + size || !md5.matches(Regex("[a-fA-F0-9]{32}"))) return false
return runCatching {
RandomAccessFile(file, "r").use { input ->
input.seek(offset)
val digest = MessageDigest.getInstance("MD5"); val buffer = ByteArray(64 * 1024); var left = size
while (left > 0) { val n = input.read(buffer, 0, minOf(left, buffer.size.toLong()).toInt()); check(n > 0); digest.update(buffer, 0, n); left -= n }
digest.digest().joinToString("") { "%02x".format(it) }.equals(md5, true)
}
}.getOrDefault(false)
}
fun calculate(folder: File, old: GogInstallRecord, target: GogInstallRecord, patches: JSONArray, reuseChunks: Boolean = true): Size {
val reusable = HashMap<Pair<String, Long>, MutableList<Chunk>>()
for (file in old.files.objects()) {
val source = GogFiles.inside(folder, file.getString("path")); var offset = 0L
for (chunk in file.optJSONArray("chunks")?.objects().orEmpty()) {
reusable.getOrPut(chunk.optString("md5").lowercase() to chunk.optLong("size")) { ArrayList() }.add(Chunk(source, offset))
offset += chunk.optLong("size")
}
}
var download = 0L; var required = 0L
for (file in target.files.objects()) {
if (file.optBoolean("directory") || GogFiles.matches(folder, file)) continue
val chunks = file.optJSONArray("chunks")?.objects().orEmpty()
val stamp = MessageDigest.getInstance("MD5").digest(file.getString("path").toByteArray()).joinToString("") { "%02x".format(it) }
val stage = File(GogFiles.dir(folder), "stage/$stamp")
var offset = 0L
var cost = if (chunks.isEmpty()) file.getLong("size") else chunks.sumOf { chunk ->
val size = chunk.getLong("size"); val hash = chunk.getString("md5")
val exists = reuseChunks && (range(stage, offset, size, hash) || reusable[hash.lowercase() to size].orEmpty().any { range(it.file, it.offset, size, hash) })
offset += size
if (exists) 0L else chunk.optLong("compressedSize")
}
val patch = patches.objects().firstOrNull { it.optString("path_target").replace('\\', '/') == file.getString("path") }
if (reuseChunks && patch != null) {
val source = GogFiles.inside(folder, patch.getString("path_source").replace('\\', '/'))
val delta = patch.getJSONArray("chunks").objects().sumOf { it.optLong("compressedSize") }
if (delta < cost && source.isFile && GogFiles.hash(source).equals(patch.getString("md5_source"), true)) cost = delta
}
download = Math.addExact(download, cost)
required = Math.addExact(required, maxOf(0, file.getLong("size") - stage.length()) + cost)
}
return Size(download, required)
}
}
@@ -0,0 +1,115 @@
package com.droiddeck.launcher.stores.gog
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.atomic.AtomicBoolean
import java.util.zip.InflaterInputStream
internal object GogFallback {
fun transfer(folder: File, plan: JSONObject, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean,
callback: GogDownloadManager.Callback? = null) {
val stageRoot = File(GogFiles.dir(folder), "stage").apply { mkdirs() }
val files = plan.getJSONArray("files")
GogFiles.validate(files, folder)
var wire = 0L
fun progress(n: Int) { wire += n; handle?.progress(wire, plan.optLong("downloadBytes").coerceAtLeast(wire)); callback?.onBytes(wire, plan.optLong("downloadBytes").coerceAtLeast(wire), 0) }
for ((index, item) in files.objects().withIndex()) {
if (stop.get()) return
val destination = GogFiles.inside(folder, item.getString("path"))
if (item.optBoolean("directory")) { java.nio.file.Files.createDirectories(destination.toPath()); continue }
if (GogFiles.matches(folder, item)) continue
val stage = File(stageRoot, java.security.MessageDigest.getInstance("MD5").digest(item.getString("path").toByteArray()).joinToString("") { "%02x".format(it) })
val chunks = item.optJSONArray("chunks")?.objects().orEmpty()
FileOutputStream(stage).use { output ->
if (chunks.isNotEmpty()) {
for (chunk in chunks) {
if (stop.get()) return
val packed = File(stageRoot, "${stage.name}.packed")
val urls = endpoints(plan.getJSONObject("links"), item.getString("product"), GogContent.cdnPath(chunk.getString("compressedMd5")))
download(urls, packed, chunk.getLong("compressedSize"), stop, ::progress)
check(GogFiles.hash(packed).equals(chunk.getString("compressedMd5"), true)) { "GOG compressed chunk checksum mismatch" }
val digest = java.security.MessageDigest.getInstance("MD5")
var count = 0L
packed.inputStream().buffered().use { raw ->
raw.mark(2); val first = raw.read(); raw.reset()
val stored = chunk.getLong("size") == chunk.getLong("compressedSize") && chunk.getString("md5").equals(chunk.getString("compressedMd5"), true)
val input = if (!stored && first == 0x78) InflaterInputStream(raw) else raw
val buffer = ByteArray(64 * 1024)
while (true) {
if (stop.get()) return
val n = input.read(buffer); if (n < 0) break
count += n; check(count <= chunk.getLong("size")) { "GOG chunk exceeds expected size" }
digest.update(buffer, 0, n); output.write(buffer, 0, n)
}
}
check(count == chunk.getLong("size") && digest.digest().joinToString("") { "%02x".format(it) }.equals(chunk.getString("md5"), true)) { "GOG chunk checksum mismatch" }
packed.delete()
}
} else if (item.getLong("size") > 0) {
val remote = item.getString("remotePath")
val urls = if (remote.startsWith("https://")) listOf(remote) else endpoints(plan.getJSONObject("links"), item.getString("product"), remote.trimStart('/'))
val range = item.getLong("offset")
val raw = File(stageRoot, "${stage.name}.range")
download(urls, raw, item.getLong("size"), stop, ::progress, range)
raw.inputStream().use { it.copyTo(output) }; raw.delete()
}
output.fd.sync()
}
if (stop.get()) return
check(stage.length() == item.getLong("size")) { "GOG file size mismatch" }
if (item.optString("md5").isNotBlank()) check(GogFiles.hash(stage).equals(item.getString("md5"), true)) { "GOG file checksum mismatch" }
if (item.optString("sha256").isNotBlank()) check(GogFiles.hash(stage, "SHA-256").equals(item.getString("sha256"), true)) { "GOG file checksum mismatch" }
destination.parentFile!!.mkdirs()
GogFiles.inside(folder, item.getString("path"))
GogFiles.replace(stage, destination)
handle?.stage(DownloadStage.INSTALL); handle?.stageProgress((index + 1).toLong(), files.length().toLong())
callback?.onProgress("Downloading: ${destination.name}", ((index + 1) * 100 / files.length()))
}
val targetPaths = files.objects().mapTo(HashSet()) { it.getString("path").lowercase(java.util.Locale.ROOT) }
for (old in plan.optJSONArray("oldFiles")?.objects().orEmpty()) {
if (stop.get()) return
if (old.getString("path").lowercase(java.util.Locale.ROOT) !in targetPaths && GogFiles.matches(folder, old))
check(GogFiles.inside(folder, old.getString("path")).delete()) { "Could not remove obsolete GOG file" }
}
}
fun endpoints(links: JSONObject, product: String, path: String): List<String> = links.getJSONArray(product).strings().map { base ->
if (base.contains("{GALAXY_PATH}")) base.replace("{GALAXY_PATH}", path)
else base.substringBefore('?').trimEnd('/') + "/" + path + if ('?' in base) "?" + base.substringAfter('?') else ""
}
fun download(urls: List<String>, destination: File, size: Long, stop: AtomicBoolean, progress: (Int) -> Unit, range: Long? = null) {
var failure: Throwable? = null
for (attempt in 0..2) for (url in urls) {
if (stop.get()) return
val connection = URL(url).openConnection() as HttpURLConnection
try {
check(URL(url).protocol == "https" || URL(url).host in setOf("127.0.0.1", "localhost"))
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
if (range != null) connection.setRequestProperty("Range", "bytes=$range-${range + size - 1}")
check(connection.responseCode == if (range == null) 200 else 206) { "GOG download failed (HTTP ${connection.responseCode})" }
FileOutputStream(destination).use { output ->
connection.inputStream.use { input ->
val buffer = ByteArray(64 * 1024); var count = 0L
while (true) {
if (stop.get()) return
val n = input.read(buffer); if (n < 0) break
count += n; check(size <= 0 || count <= size) { "GOG response exceeds expected size" }
output.write(buffer, 0, n); progress(n)
}
check(size <= 0 || count == size) { "Incomplete GOG download" }
}
output.fd.sync()
}
return
} catch (e: Exception) { failure = e }
finally { connection.disconnect() }
}
throw failure ?: IllegalStateException("No GOG download URL")
}
}
@@ -0,0 +1,176 @@
package com.droiddeck.launcher.stores.gog
import com.droiddeck.launcher.stores.StoreGameSidecar
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import java.util.Locale
internal enum class GogOperation { UPDATE, REPAIR, PATCH, REFRESH }
internal data class GogInstallRecord(
val id: String,
val source: String,
val generation: Int = 0,
val build: String = "",
val version: String = "",
val branch: String = "",
val language: String = "en-US",
val products: List<String> = listOf(id),
val manifest: JSONObject = JSONObject(),
val files: JSONArray = JSONArray(),
val verified: Boolean = true,
) {
fun json() = JSONObject().put("schema", 1).put("id", id).put("source", source)
.put("generation", generation).put("build", build).put("version", version).put("branch", branch)
.put("language", language).put("products", JSONArray(products)).put("manifest", manifest)
.put("files", files).put("verified", verified)
fun write(folder: File) = GogFiles.write(File(GogFiles.dir(folder), "installed.json"), json())
companion object {
fun parse(o: JSONObject): GogInstallRecord {
require(o.optInt("schema") == 1) { "Unsupported GOG installation record" }
return GogInstallRecord(o.getString("id"), o.getString("source"), o.optInt("generation"),
o.optString("build"), o.optString("version"), o.optString("branch"), o.optString("language", "en-US"),
o.optJSONArray("products")?.strings().orEmpty().ifEmpty { listOf(o.getString("id")) },
o.optJSONObject("manifest") ?: JSONObject(), o.optJSONArray("files") ?: JSONArray(), o.optBoolean("verified", true))
}
fun read(folder: File): GogInstallRecord? = GogFiles.read(File(GogFiles.dir(folder), "installed.json"))?.let(::parse)
fun authenticBuild(folder: File, id: String): String = GogFiles.read(File(folder, "goggame-$id.id"))?.optString("buildId").orEmpty()
.ifBlank { GogFiles.read(File(folder, "goggame-$id.info"))?.optString("buildId").orEmpty() }
fun migrate(folder: File, sidecar: StoreGameSidecar): GogInstallRecord {
read(folder)?.let { require(it.id == sidecar.id); return it }
val legacy = GogFiles.read(File(folder, "_gog_manifest.json"))
val info = GogFiles.read(File(folder, "goggame-${sidecar.id}.info"))
val build = authenticBuild(folder, sidecar.id).ifBlank { legacy?.optString("buildId").orEmpty().ifBlank { sidecar.installVersion } }
val ids = folder.listFiles().orEmpty().mapNotNull { Regex("goggame-([0-9]+)\\.info").matchEntire(it.name)?.groupValues?.get(1) }
return GogInstallRecord(sidecar.id, if (legacy != null || sidecar.installVersion.isNotBlank()) "depot" else "offline",
legacy?.optInt("generation", if (build.isNotBlank()) 2 else 0) ?: if (build.isNotBlank()) 2 else 0,
build, info?.optString("versionName").orEmpty(), language = sidecar.extra[com.droiddeck.launcher.stores.StoreLanguage.EXTRA] ?: "en-US",
products = (listOf(sidecar.id) + ids).distinct()).also { it.write(folder) }
}
}
}
internal object GogFiles {
fun dir(folder: File): File = inside(folder, ".droiddeck-gog").apply { mkdirs() }
fun journal(folder: File): File = File(dir(folder), "operation.json")
fun inside(root: File, raw: String): File {
val path = raw.replace('\\', '/')
require(path.isNotBlank() && !path.startsWith('/') && ':' !in path && '\u0000' !in path &&
path.split('/').none { it.isEmpty() || it == "." || it == ".." }) { "Invalid GOG path: $raw" }
val base = root.canonicalFile
var out = base
for (part in path.split('/')) {
out = File(out, part)
require(!Files.isSymbolicLink(out.toPath())) { "GOG path is a symbolic link: $raw" }
}
require(out.canonicalFile.toPath().startsWith(base.toPath())) { "GOG path leaves installation" }
return out
}
fun read(file: File): JSONObject? {
require(!Files.isSymbolicLink(file.toPath())) { "GOG metadata is a symbolic link" }
return if (!file.exists()) null else JSONObject(file.readText())
}
fun write(file: File, value: JSONObject) {
require(!Files.isSymbolicLink(file.toPath()))
file.parentFile!!.mkdirs()
val tmp = File.createTempFile(".gog-", ".stage", file.parentFile)
try {
FileOutputStream(tmp).use { it.write(value.toString().toByteArray(Charsets.UTF_8)); it.fd.sync() }
replace(tmp, file)
} finally { tmp.delete() }
}
fun replace(from: File, to: File) {
require(!Files.isSymbolicLink(to.toPath()))
try { Files.move(from.toPath(), to.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING) }
}
fun hash(file: File, algorithm: String = "MD5"): String {
val digest = MessageDigest.getInstance(algorithm)
file.inputStream().use { input -> val buffer = ByteArray(128 * 1024); while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) } }
return digest.digest().joinToString("") { "%02x".format(it) }
}
fun matches(folder: File, file: JSONObject): Boolean {
val f = inside(folder, file.getString("path"))
if (!Files.isRegularFile(f.toPath(), LinkOption.NOFOLLOW_LINKS) || f.length() != file.getLong("size")) return false
val md5 = file.optString("md5")
if (md5.matches(Regex("[a-fA-F0-9]{32}"))) return hash(f).equals(md5, true)
val sha = file.optString("sha256")
if (sha.isNotBlank()) return hash(f, "SHA-256").equals(sha, true)
val chunks = file.optJSONArray("chunks")?.objects().orEmpty()
var offset = 0L
return chunks.isNotEmpty() && chunks.all { chunk ->
val result = GogEstimate.range(f, offset, chunk.getLong("size"), chunk.getString("md5"))
offset += chunk.getLong("size"); result
} || f.length() == 0L
}
fun validate(files: JSONArray, folder: File) {
val paths = HashSet<String>()
val components = HashMap<String, String>()
for (file in files.objects()) {
val path = file.getString("path").replace('\\', '/')
inside(folder, path)
require(!path.startsWith(".droiddeck-", true) && path != StoreGameSidecar.FILE_NAME) { "GOG content overlaps launcher metadata" }
require(paths.add(path.lowercase(Locale.ROOT))) { "GOG paths differ only by case: $path" }
var parent = folder
var relative = ""
for (part in path.split('/')) {
relative = if (relative.isEmpty()) part else "$relative/$part"
val previous = components.putIfAbsent(relative.lowercase(Locale.ROOT), relative)
require(previous == null || previous == relative) { "GOG directory paths differ only by case: $path" }
require(parent.list()?.none { it != part && it.equals(part, true) } != false) { "An existing path differs only by case: $path" }
parent = File(parent, part)
}
}
}
}
internal fun JSONArray.objects(): List<JSONObject> = (0 until length()).map { getJSONObject(it) }
internal fun JSONArray.strings(): List<String> = (0 until length()).map { optString(it) }
internal data class GogBuild(val id: String, val version: String, val generation: Int, val branch: String, val link: String) {
companion object {
fun select(builds: JSONObject, pinned: String = "", branch: String = ""): GogBuild? {
val items = builds.optJSONArray("items")?.objects().orEmpty().filter { it.optString("os", "windows") == "windows" }
val item = if (pinned.isNotBlank()) items.firstOrNull { it.optString("build_id") == pinned || it.optString("legacy_build_id") == pinned }
else items.firstOrNull { it.optString("branch").let { b -> (if (b == "null") "" else b) == branch } }
return item?.let { GogBuild(it.optString("build_id"), it.optString("version_name"), it.optInt("generation", 2),
it.optString("branch").let { b -> if (b == "null") "" else b },
it.optString("link").ifBlank { it.optString("meta_url").ifBlank { it.optJSONArray("urls")?.optJSONObject(0)?.optString("url").orEmpty() } }) }
}
}
}
internal data class GogOfflinePart(val id: String, val name: String, val url: String, val size: Long, val md5: String)
internal data class GogOfflineDownload(val id: String, val name: String, val version: String, val language: String, val parts: List<GogOfflinePart>) {
val size: Long get() = parts.sumOf { it.size }
companion object {
fun parse(downloads: JSONObject, kind: String): List<GogOfflineDownload> = downloads.optJSONArray(kind)?.objects().orEmpty()
.filter { it.optString("os") == "windows" }.mapNotNull { entry ->
val files = entry.optJSONArray("files")?.objects().orEmpty()
val parts = files.mapNotNull { f ->
val url = f.optString("downlink").ifBlank { f.optString("manualUrl") }
if (url.isBlank()) null else GogOfflinePart(f.optString("id"), f.optString("filename"), url, f.optLong("size"), f.optString("md5"))
}
if (parts.isEmpty()) null else GogOfflineDownload(entry.optString("id").ifBlank { parts.first().id },
entry.optString("name", "GOG download"), entry.optString("version"), entry.optString("language"), parts)
}
}
}
@@ -0,0 +1,415 @@
package com.droiddeck.launcher.stores.gog
import android.content.Context
import androidx.compose.runtime.mutableStateMapOf
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.*
import com.droiddeck.launcher.stores.download.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.RandomAccessFile
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
internal object GogMaintenance {
enum class State { UNKNOWN, CHECKING, CURRENT, AVAILABLE, FAILED }
data class Check(val state: State, val version: String = "", val reason: String = "")
data class Proposal(val folder: File, val before: GogInstallRecord, val target: GogInstallRecord,
val operation: GogOperation, val downloadBytes: Long, val diskBytes: Long, val patch: GogOfflineDownload? = null, val deltas: JSONArray = JSONArray(), val fullFiles: Boolean = false)
val checks = mutableStateMapOf<String, Check>()
private val workers = Executors.newFixedThreadPool(2)
private val checkedAt = java.util.concurrent.ConcurrentHashMap<String, Long>()
private val inFlight = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
@Volatile private var account = ""
private val revision = java.util.concurrent.atomic.AtomicLong()
private const val HELPER = "/usr/local/bin/droiddeck-gog-maintenance"
const val OPERATION = "gogOperation"
const val FOLDER = "gogFolder"
fun reset() {
revision.incrementAndGet()
account = ""; checkedAt.clear()
StoresState.post { checks.clear() }
}
fun checkInstalled(context: Context, games: List<InstalledStoreGame>) {
val user = StoreAccounts.displayName(context, Store.GOG).orEmpty()
if (user != account) { reset(); account = user }
if (user.isBlank()) return
games.filter { it.sidecar.store == Store.GOG && it.sidecar.isInstalled }.forEach { check(context, it) }
}
fun check(context: Context, game: InstalledStoreGame, force: Boolean = false) {
val key = game.folder.absolutePath
if (!force && System.currentTimeMillis() - (checkedAt[key] ?: 0) < 30 * 60_000) return
if (!inFlight.add(key)) return
val owner = revision.get()
StoresState.post { checks[game.sidecar.id] = Check(State.CHECKING) }
workers.execute {
val result = runCatching {
var old = GogInstallRecord.migrate(game.folder, game.sidecar)
if (!old.verified || GogFiles.journal(game.folder).exists()) Check(State.UNKNOWN, reason = "Finish or recover the GOG maintenance operation first")
else {
val token = GogContent.token(context)
if (old.source == "depot") {
val builds = GogContent.builds(old.id, token)
if (old.files.length() == 0 && old.build.isNotBlank()) GogBuild.select(builds, pinned = old.build)?.let { old = old.copy(branch = it.branch, generation = it.generation) }
val latest = GogBuild.select(builds, branch = old.branch)
when { latest == null -> Check(State.UNKNOWN, reason = "No build is available on the installed branch")
old.build.isBlank() -> Check(State.UNKNOWN, latest.version, "The installed build is unknown")
latest.id == old.build -> Check(State.CURRENT, old.version)
else -> Check(State.AVAILABLE, latest.version) }
} else {
val downloads = GogContent.product(old.id, token).getJSONObject("downloads")
val installer = offlineInstaller(downloads, old.language)
if (old.version.isBlank()) Check(State.UNKNOWN, installer.version, "The installed version is unknown")
else Check(if (old.version == installer.version) State.CURRENT else State.AVAILABLE, installer.version)
}
}
}.getOrElse { Check(State.FAILED, reason = it.message ?: "GOG update check failed") }
if (revision.get() == owner && (result.state == State.CURRENT || result.state == State.AVAILABLE)) checkedAt[key] = System.currentTimeMillis()
inFlight.remove(key)
StoresState.post { if (revision.get() == owner) checks[game.sidecar.id] = result }
}
}
fun offlinePatches(context: Context, game: InstalledStoreGame): List<GogOfflineDownload> =
GogOfflineDownload.parse(GogContent.product(game.sidecar.id, GogContent.token(context)).getJSONObject("downloads"), "patches")
internal fun offlineInstaller(downloads: JSONObject, language: String): GogOfflineDownload {
val installers = GogOfflineDownload.parse(downloads, "installers")
return installers.firstOrNull { it.language.equals(language, true) }
?: installers.firstOrNull { !it.language.equals("Neutral", true) && StoreLanguage.depotAccepted(arrayOf(it.language), language) }
?: installers.firstOrNull { it.language.equals("Neutral", true) }
?: error("No Windows offline installer is available for the installed language ($language)")
}
fun prepare(context: Context, game: InstalledStoreGame, operation: GogOperation, patch: GogOfflineDownload? = null, resume: Boolean = false): Proposal {
val folder = game.folder.canonicalFile
var old = GogInstallRecord.migrate(folder, game.sidecar)
val journal = GogFiles.read(GogFiles.journal(folder))
require(journal == null || journal.optString("folder") == folder.path) { "GOG recovery folder does not match" }
if (journal != null && journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain") && operation != GogOperation.REFRESH) error("The patch was interrupted. Inspect the installer result or use a full offline refresh; it will not be rerun automatically.")
require(journal == null || operation == GogOperation.REFRESH || journal.optString("operation") == operation.name) { "Resume the existing GOG operation or select a full offline refresh" }
val token = GogContent.token(context)
if (operation == GogOperation.PATCH) {
if (old.source == "depot" && old.manifest.length() == 0 && old.build.isNotBlank()) {
val exact = GogBuild.select(GogContent.builds(old.id, token), pinned = old.build)
?: error("The installed GOG setup manifest is unavailable; use a full offline refresh")
old = GogContent.snapshot(old, exact, token)
}
check(patch != null) { "Select a GOG patch" }
if (resume) require(journal?.optString("downloadVersion") == patch.version) { "The selected patch changed; select it again in Offline patches" }
val selected = GogContent.resolveDownload(patch, token)
return Proposal(folder, old, old.copy(source = "offline", version = selected.version, verified = false), operation, selected.size,
selected.size + folder.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.name != ".droiddeck-gog" }.filter { it.isFile }.sumOf { it.length() }, selected)
}
if (operation == GogOperation.REFRESH || old.source != "depot") {
require(operation != GogOperation.REPAIR) { "This offline installation has no depot manifest. Use a full offline refresh to restore its files." }
val download = GogContent.resolveDownload(offlineInstaller(GogContent.product(old.id, token).getJSONObject("downloads"), old.language), token)
if (resume) require(journal?.optString("downloadId") == download.id && journal.optString("downloadVersion") == download.version) { "The previous offline installer is no longer available; select a new full offline refresh" }
if (old.products.any { it != old.id }) {
val pinned = journal?.optJSONObject("target")?.optString("build").orEmpty()
val build = GogBuild.select(GogContent.builds(old.id, token), pinned = pinned, branch = old.branch)
?: error("No depot build is available to preserve installed DLC during this refresh. Use Update instead.")
val target = GogContent.snapshot(old, build, token)
GogFiles.validate(target.files, folder)
val native = GogNative.isAvailable()
val remaining = GogEstimate.calculate(folder, old, target, JSONArray(), reuseChunks = native)
return Proposal(folder, old, target, GogOperation.REFRESH, Math.addExact(download.size, remaining.download),
Math.addExact(Math.multiplyExact(download.size, 3), remaining.required), download, fullFiles = !native)
}
val target = old.copy(source = "offline", build = "", generation = 0, version = download.version, manifest = JSONObject(), files = JSONArray(), verified = true)
return Proposal(folder, old, target, GogOperation.REFRESH, download.size, download.size * 3, download)
}
require(old.verified || operation != GogOperation.REPAIR) { "The patched installation must be reconciled before repair" }
val pinned = journal?.optJSONObject("target")?.let(GogInstallRecord::parse)
val builds = GogContent.builds(old.id, token)
if (old.files.length() == 0 && old.build.isNotBlank()) GogBuild.select(builds, pinned = old.build)?.let { old = old.copy(branch = it.branch, generation = it.generation) }
val build = GogBuild.select(builds,
pinned = pinned?.build ?: if (operation == GogOperation.REPAIR) old.build.ifBlank { error("The installed GOG build is unknown; update it first") } else "",
branch = pinned?.branch ?: old.branch) ?: error("The requested GOG build is no longer available")
val target = GogContent.snapshot(old, build, token)
GogFiles.validate(target.files, folder)
var before = journal?.optJSONObject("before")?.let(GogInstallRecord::parse) ?: old
if (before.files.length() == 0 && before.build.isNotBlank()) {
val historical = GogBuild.select(builds, pinned = before.build)
if (historical != null) before = runCatching { GogContent.snapshot(before, historical, token) }.getOrDefault(before)
}
val deltas = GogContent.patches(before, target, token)
val native = GogNative.isAvailable()
val size = GogEstimate.calculate(folder, before, target, deltas, reuseChunks = native)
return Proposal(folder, before, target, operation, size.download, size.required, deltas = deltas, fullFiles = !native)
}
fun resume(context: Context, game: InstalledStoreGame): Proposal {
val journal = GogFiles.read(GogFiles.journal(game.folder)) ?: error("GOG operation journal is missing")
val operation = GogOperation.valueOf(journal.getString("operation"))
val patch = if (operation == GogOperation.PATCH) offlinePatches(context, game)
.firstOrNull { it.id == journal.optString("downloadId") } ?: error("The selected GOG patch is no longer available") else null
return prepare(context, game, operation, patch, resume = true)
}
fun recoverPatch(context: Context, game: InstalledStoreGame) {
val folder = game.folder.canonicalFile
check(!DownloadQueue.isActive(game.key)) { "Wait for the GOG operation to finish" }
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG patch journal is missing")
require(journal.optString("folder") == folder.path && journal.optString("operation") == GogOperation.PATCH.name)
require(journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain"))
RandomAccessFile(GogFiles.inside(folder, ".droiddeck-gog/lease"), "rw").use { lease ->
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: error("Close the patch installer before verifying its result")
lock.use {
ensureIdle(context, folder)
val before = GogInstallRecord.parse(journal.getJSONObject("before"))
val buildId = GogInstallRecord.authenticBuild(folder, before.id).ifBlank { before.build }
check(buildId.isNotBlank()) { "The resulting build is unknown. Use a full offline refresh." }
val token = GogContent.token(context)
val build = GogBuild.select(GogContent.builds(before.id, token), pinned = buildId)
?: error("The resulting build manifest is unavailable. Use a full offline refresh.")
val target = GogContent.snapshot(before, build, token)
GogFiles.validate(target.files, folder)
check(target.files.objects().all { it.optBoolean("directory") || GogFiles.matches(folder, it) }) {
"The files do not match the reported build. Use a full offline refresh to recover."
}
val sidecar = StoreGameSidecar.parse(journal.getJSONObject("sidecar").toString()) ?: error("The original GOG settings are missing")
target.write(folder)
StoreInstalls.complete(context, folder, sidecar.copy(installVersion = target.build, state = StoreGameSidecar.STATE_INSTALLED))
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
}
}
checkedAt.remove(folder.path)
DownloadQueue.dismiss(game.key)
StoresState.notifyLibraryChanged(context)
StoresState.post { checks.remove(game.sidecar.id) }
}
fun enqueue(context: Context, game: InstalledStoreGame, proposal: Proposal) {
val app = context.applicationContext
require(game.folder.canonicalFile == proposal.folder)
check(!DownloadQueue.isActive("gog:${game.sidecar.id}")) { "GOG maintenance is already queued" }
check(!StoreInstallRoot.insufficientSpace(proposal.diskBytes, StoreInstallRoot.availableBytes(proposal.folder))) { "Not enough free space for GOG maintenance" }
val journal = JSONObject().put("schema", 1).put("folder", proposal.folder.path).put("operation", proposal.operation.name)
.put("before", proposal.before.json()).put("target", proposal.target.json()).put("sidecar", game.sidecar.toJson()).put("phase", "download")
proposal.patch?.let { journal.put("downloadId", it.id).put("downloadVersion", it.version) }
GogFiles.write(GogFiles.journal(proposal.folder), journal)
val item = CatalogItem(Store.GOG, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
extra = mapOf(OPERATION to proposal.operation.name, FOLDER to proposal.folder.path))
SavedQueue.remember(app, item, null)
enqueueJob(app, item, proposal)
}
private fun enqueueJob(context: Context, item: CatalogItem, proposal: Proposal) {
DownloadQueue.enqueue(context, DownloadEntry(Store.GOG, item.id, item.title, cover = item.tallImageUrl,
bytesTotal = proposal.downloadBytes, location = StoreInstallRoot.labelFor(context, proposal.folder))) { Job(context, proposal) }
}
fun restore(context: Context, item: CatalogItem) {
val folder = File(item.extra[FOLDER] ?: error("Missing GOG recovery folder")).canonicalFile
require(StoreInstallRoot.gameFolders(context).any { it.canonicalFile == folder }) { "GOG recovery folder is unavailable" }
val sidecar = StoreGameSidecar.read(folder) ?: error("GOG installation record is missing")
require(sidecar.store == Store.GOG && sidecar.id == item.id)
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG operation journal is missing")
val operation = GogOperation.valueOf(journal.getString("operation"))
if (journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain")) {
DownloadQueue.recordFailed(context, DownloadEntry(Store.GOG, item.id, item.title), "The patch result needs recovery; open Offline patches")
return
}
val game = InstalledStoreGame(sidecar, folder)
SavedQueue.remember(context, item, null)
enqueueJob(context, item, resume(context, game))
}
private class Job(val app: Context, val proposal: Proposal) : DownloadQueue.DownloadJob {
val cancelled = AtomicBoolean(false)
@Volatile var applyingPatch = false
@Volatile private var running = false
@Volatile private var deleteCaches = false
override fun cancel(deleteFiles: Boolean) {
if (applyingPatch) return
deleteCaches = deleteCaches || deleteFiles
cancelled.set(true)
if (!running && deleteCaches) cleanCaches()
}
override fun run(handle: DownloadQueue.JobHandle): String? {
running = true
try { return perform(handle) }
finally {
running = false; applyingPatch = false; handle.interruptible(true)
if (deleteCaches) cleanCaches()
}
}
private fun cleanCaches() {
for (name in listOf("stage", "downloads", "extracted")) {
val root = GogFiles.inside(proposal.folder, ".droiddeck-gog/$name")
if (root.exists()) java.nio.file.Files.walk(root.toPath()).use { paths ->
paths.sorted(java.util.Comparator.reverseOrder()).forEach { java.nio.file.Files.deleteIfExists(it) }
}
}
}
private fun perform(handle: DownloadQueue.JobHandle): String? {
val folder = proposal.folder
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG operation journal is missing")
val sidecar = StoreGameSidecar.parse(journal.getJSONObject("sidecar").toString()) ?: error("GOG previous installation is missing")
if (proposal.operation == GogOperation.PATCH) {
val result = GogOffline.apply(app, proposal, handle, cancelled, onApplying = { applyingPatch = true; handle.interruptible(false) })
applyingPatch = false; handle.interruptible(true)
if (!result || cancelled.get()) return null
} else {
RandomAccessFile(GogFiles.inside(folder, ".droiddeck-gog/lease"), "rw").use { lease ->
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: error("Close the GOG game before updating it")
lock.use {
ensureIdle(app, folder)
sidecar.copy(state = StoreGameSidecar.STATE_UPDATING).write(folder)
GogFiles.write(GogFiles.journal(folder), journal.put("phase", "applying"))
if (proposal.operation == GogOperation.REFRESH) {
GogOffline.refresh(app, proposal, handle, cancelled)
if (!cancelled.get() && proposal.target.source == "depot") transfer(app, proposal, handle, cancelled)
} else transfer(app, proposal, handle, cancelled)
if (cancelled.get()) return null
}
}
}
if (cancelled.get()) return null
val target = GogInstallRecord.read(folder)?.takeIf { proposal.operation == GogOperation.PATCH || proposal.operation == GogOperation.REFRESH && proposal.target.source != "depot" } ?: proposal.target
check(target.verified) { "The patch completed, but its resulting version could not be verified. Inspect the game or use a full offline refresh." }
target.write(folder)
StoreInstalls.complete(app, folder, sidecar.copy(installVersion = target.build.ifBlank { target.version }, state = StoreGameSidecar.STATE_INSTALLED))
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
runCatching { cleanCaches() }.onFailure { handle.log("gog: completed; could not remove expendable cache: ${it.message}") }
checkedAt.remove(folder.path)
StoresState.post { checks.remove(sidecar.id) }
return folder.path
}
}
private fun ensureIdle(context: Context, folder: File) {
val game = AddedGames.single(context, folder.path) ?: return
check(SessionState.gameId != (game.appId and 0xffffffffL).toString()) { "Close the GOG game before maintenance" }
if (SessionState.running) {
val id = (game.steamAppId?.toLong() ?: game.appId) and 0xffffffffL
val guest = AddedGames.guestPath(context, folder) ?: error("The GOG folder is unavailable to Linux")
if (SessionState.suspended || AgentGuest.hello(context) == null) {
val root = AddedGames.guestPath(context, SessionPrefs.activeSteamRoot(context)) ?: error("The Steam folder is unavailable to Linux")
val rc = GuestCommand.run(context, listOf("/usr/bin/env", "STEAM_COMPAT_CLIENT_INSTALL_PATH=$root", HELPER, "idle", guest, id.toString(), game.guestExe),
extraBinds = StoreInstallRoot.externalBindSpecs(context), logName = "gog-idle", onLine = StoresState::logLine)
check(rc == 0) { "Close the GOG game before maintenance" }
return
}
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, "idle", guest, id.toString(), game.guestExe))).put("timeout", 15)
val result = AgentGuest.call(context, request, 20_000, trusted = true)
check(result.optBoolean("ok") && result.optInt("exitCode", -1) == 0) { "Close the GOG game before maintenance" }
}
}
private fun transfer(context: Context, proposal: Proposal, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean, callback: GogDownloadManager.Callback? = null) {
val token = GogContent.token(context)
var patches = proposal.deltas
var previousWire = 0L
for (attempt in 0..4) {
if (stop.get()) return
val links = GogContent.links(proposal.target, GogContent.token(context))
val patchLinks = if (patches.length() > 0) runCatching { GogContent.links(proposal.target, token, patches = true) }.getOrElse { patches = JSONArray(); JSONObject() } else JSONObject()
val plan = JSONObject().put("files", proposal.target.files).put("oldFiles", proposal.before.files)
.put("patches", patches).put("links", links).put("patchLinks", patchLinks).put("downloadBytes", proposal.downloadBytes)
val optimized = GogNative.isAvailable()
val remaining = GogEstimate.calculate(proposal.folder, proposal.before, proposal.target, patches, reuseChunks = optimized).required
check(!StoreInstallRoot.insufficientSpace(remaining, StoreInstallRoot.availableBytes(proposal.folder))) { "Not enough free space for remaining GOG maintenance" }
handle?.diskSize(remaining)
if (!optimized) {
try { GogFallback.transfer(proposal.folder, plan, handle, stop, callback); return }
catch (e: Exception) {
if (stop.get()) return
if (attempt == 4 || Regex("HTTP (401|403|404|500)").find(e.message.orEmpty()) == null) throw e
handle?.log("gog: refreshing file-download links; verified replacements are retained")
continue
}
}
val latch = CountDownLatch(1)
var runWire = 0L
var success = false; var expired = false; var failure = "GOG download failed"
val listener = object : GogNative.Listener {
override fun onProgress(bytesDone: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, file: String, fileBytes: Long, verified: Boolean) {
handle?.stage(if (verified) DownloadStage.VERIFY else DownloadStage.INSTALL)
handle?.stageProgress(filesDone.toLong(), filesTotal.toLong(), filesDone, filesTotal)
callback?.onStage(if (verified) "verify" else "install", filesDone.toLong(), filesTotal.toLong(), filesDone, filesTotal)
}
override fun onBytes(bytesDone: Long, bytesTotal: Long) {
runWire = bytesDone
handle?.progress(previousWire + bytesDone, (previousWire + bytesTotal).coerceAtLeast(previousWire + bytesDone))
callback?.onBytes(previousWire + bytesDone, (previousWire + bytesTotal).coerceAtLeast(previousWire + bytesDone), 0)
}
override fun onLog(line: String) { handle?.log(line); callback?.onLog(line) }
override fun onMaintenance(networkBytes: Long, reusedBytes: Long, appliedBytes: Long) { handle?.maintenance(reusedBytes, appliedBytes) }
override fun onComplete(ok: Boolean, cancelled: Boolean, linkExpiry: Boolean, error: String, bytesWritten: Long, filesDone: Int) {
success = ok; expired = linkExpiry; failure = error; latch.countDown()
}
}
val native = GogNative.start(2, arrayOf(plan.toString()), emptyArray(), proposal.folder.path, emptyArray(), "", 1, 1, false, "gog maintenance", listener)
check(native != 0L) { "GOG native engine could not start" }
try { while (!latch.await(200, TimeUnit.MILLISECONDS)) if (stop.get()) GogNative.cancel(native) }
finally { GogNative.release(native) }
if (stop.get()) return
if (success) {
for (file in proposal.target.files.objects()) if (!file.optBoolean("directory") && file.optString("md5").isBlank() && file.optString("sha256").isBlank())
file.put("sha256", GogFiles.hash(GogFiles.inside(proposal.folder, file.getString("path")), "SHA-256"))
return
}
if (!expired || attempt == 4) error(failure)
previousWire += runWire
handle?.log("gog: refreshing expired download links; validated files and chunks are retained")
}
}
@JvmStatic
fun installContent(context: Context, game: GogGame, folder: File, builds: JSONObject, language: String,
callback: GogDownloadManager.Callback, cancelled: AtomicBoolean): GogDownloadManager.Result? {
val build = GogBuild.select(builds) ?: return null
folder.mkdirs()
val old = GogInstallRecord(game.gameId, "depot", language = language)
val target = GogContent.snapshot(old, build, GogContent.token(context))
GogFiles.validate(target.files, folder)
val bytes = target.files.objects().sumOf { it.optJSONArray("chunks")?.objects()?.sumOf { c -> c.optLong("compressedSize") }?.takeIf { n -> n > 0 } ?: it.optLong("size") }
val disk = target.files.objects().sumOf { it.optLong("size") }
check(!StoreInstallRoot.insufficientSpace(disk, StoreInstallRoot.availableBytes(folder))) { "Not enough free space for GOG installation" }
callback.onSizes(bytes, disk)
transfer(context, Proposal(folder, old, target, GogOperation.UPDATE, bytes, disk), null, cancelled, callback)
if (cancelled.get()) return null
target.write(folder)
val result = GogDownloadManager.Result(GogDownloadManager.pickExe(folder, null, game.title), build.id, disk)
result.language = target.language
result.dependencies = target.manifest.optJSONArray("dependencies")?.strings().orEmpty()
result.dependenciesRead = true
return result
}
@JvmStatic
fun captureDepot(id: String, folder: File, build: String, buildsJson: String, manifest: JSONObject, depots: JSONArray, language: String) {
val selected = GogBuild.select(JSONObject(buildsJson), pinned = build)
val files = JSONArray()
for (depot in depots.strings()) for (item in JSONObject(depot).getJSONObject("depot").getJSONArray("items").objects()) {
val chunks = item.optJSONArray("chunks") ?: continue
files.put(JSONObject().put("path", item.getString("path").replace('\\', '/')).put("size", chunks.objects().sumOf { it.optLong("size") })
.put("md5", item.optString("md5")).put("chunks", chunks).put("product", id))
}
GogFiles.validate(files, folder)
GogInstallRecord(id, "depot", 2, build, selected?.version.orEmpty(), selected?.branch.orEmpty(), language,
manifest = GogContent.sanitize(manifest), files = files).write(folder)
}
@JvmStatic
fun captureOffline(id: String, folder: File, downloads: JSONObject) {
val selected = GogOfflineDownload.parse(downloads, "installers").firstOrNull() ?: return
GogInstallRecord(id, "offline", version = selected.version, language = selected.language).write(folder)
}
}
@@ -15,6 +15,8 @@ object GogNative {
fun onBytes(bytesDone: Long, bytesTotal: Long)
fun onMaintenance(networkBytes: Long, reusedBytes: Long, appliedBytes: Long)
fun onLog(line: String)
fun onComplete(success: Boolean, cancelled: Boolean, linkExpiry: Boolean, error: String, bytesWritten: Long, filesDone: Int)
@@ -26,7 +28,7 @@ object GogNative {
fun isAvailable(): Boolean {
available?.let { return it }
val ok = try {
StoresNative.ensureLoaded() && nativeProbe() == 1
StoresNative.ensureLoaded() && nativeProbe() == 2
} catch (t: Throwable) {
Log.w(TAG, "native GOG engine unavailable: ${t.javaClass.simpleName}: ${t.message}")
false
@@ -0,0 +1,200 @@
package com.droiddeck.launcher.stores.gog
import android.content.Context
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
internal object GogOffline {
private const val HELPER = "/usr/local/bin/droiddeck-gog-maintenance"
internal data class Layout(val source: File, val prefix: String)
internal fun layout(extracted: File, installed: File, id: String, executable: String): Layout {
val nested = executable.startsWith("app/", true) && !File(installed, "goggame-$id.info").isFile
return Layout(extracted, if (nested) "app/" else "")
}
internal fun validateDepotInstaller(extracted: File, target: GogInstallRecord) {
if (target.source != "depot") return
val builds = listOf(extracted, File(extracted, "app")).map { GogInstallRecord.authenticBuild(it, target.id) }.filter { it.isNotBlank() }
require(builds.isNotEmpty() && builds.all { it == target.build } && target.build.isNotBlank()) {
"The offline installer does not identify the selected depot build. Use Update to preserve installed DLC."
}
}
private fun download(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean): File {
val patch = proposal.patch ?: error("GOG download selection is missing")
val root = File(GogFiles.dir(proposal.folder), "downloads").apply { mkdirs() }
var first: File? = null; var bytes = 0L
for ((index, part) in patch.parts.withIndex()) {
if (stop.get()) return first ?: File(root, "cancelled")
val resolved = GogDownloadManager.resolveRedirect(part.url, GogContent.token(context)) ?: error("The GOG download link is unavailable")
val serverName = GogContent.downloadFilename(resolved).takeIf { it.endsWith(".exe", true) || it.endsWith(".bin", true) }
val name = part.name.ifBlank { serverName ?: error("GOG did not provide the installer part filename") }
require('/' !in name && '\\' !in name && name !in setOf(".", "..")) { "Invalid GOG installer filename" }
val file = GogFiles.inside(root, name)
val receipt = File(root, "part-$index.json")
val saved = GogFiles.read(receipt)
val complete = file.isFile && (part.size <= 0 || file.length() == part.size) && when {
part.md5.isNotBlank() -> GogFiles.hash(file).equals(part.md5, true)
saved?.optString("id") == part.id && saved.optString("filename") == name -> GogFiles.hash(file, "SHA-256") == saved.optString("sha256")
else -> false
}
if (!complete) {
val staging = GogFiles.inside(root, "$name.partial")
GogFallback.download(listOf(resolved), staging, part.size, stop, { n -> bytes += n; handle.progress(bytes, proposal.downloadBytes.coerceAtLeast(bytes)) })
if (stop.get()) return first ?: file
if (part.md5.isNotBlank()) check(GogFiles.hash(staging).equals(part.md5, true)) { "GOG installer checksum mismatch" }
GogFiles.replace(staging, file)
GogFiles.write(receipt, JSONObject().put("id", part.id).put("filename", name).put("sha256", GogFiles.hash(file, "SHA-256")))
}
if (index == 0) { check(file.extension.equals("exe", true)) { "GOG patch has no setup executable" }; first = file }
}
return first ?: error("GOG download has no files")
}
fun refresh(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean) {
val installer = download(context, proposal, handle, stop)
if (stop.get()) return
val extracted = File(GogFiles.dir(proposal.folder), "extracted").apply { mkdirs() }
val source = AddedGames.guestPath(context, installer) ?: error("The GOG installer is not visible to Linux")
val target = AddedGames.guestPath(context, extracted) ?: error("The GOG staging folder is not visible to Linux")
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
val rc = GuestCommand.run(context, listOf("/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", target, source),
extraBinds = StoreInstallRoot.externalBindSpecs(context), cancelled = stop, logName = "gog-refresh", onLine = handle::log)
if (stop.get()) return
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
applyRefresh(proposal, extracted, handle, stop)
}
internal fun applyRefresh(proposal: GogMaintenance.Proposal, extracted: File, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean) {
validateDepotInstaller(extracted, proposal.target)
val sidecar = StoreGameSidecar.read(proposal.folder) ?: error("The original GOG settings are missing")
val layout = layout(extracted, proposal.folder, proposal.before.id, sidecar.exe)
val files = layout.source.walkTopDown().onEnter { directory ->
check(!java.nio.file.Files.isSymbolicLink(directory.toPath())) { "GOG installer contains a symbolic link" }
directory.parentFile != extracted || directory.name !in setOf("tmp", "commonappdata", "userappdata", "localappdata")
}.filter { it != layout.source && it != File(extracted, "app") }.map { file ->
check(!java.nio.file.Files.isSymbolicLink(file.toPath()))
val relative = file.relativeTo(layout.source).invariantSeparatorsPath.removePrefix("app/")
JSONObject().put("path", layout.prefix + relative)
.put("size", if (file.isDirectory) 0 else file.length()).put("directory", file.isDirectory)
.put("md5", if (file.isDirectory) "" else GogFiles.hash(file)).put("product", proposal.before.id) to file
}.toList().groupBy { it.first.getString("path") }.map { (_, entries) ->
check(entries.size == 1 || entries.all { it.first.getBoolean("directory") }) { "GOG installer has conflicting file locations" }
entries.first()
}
check(files.any { !it.first.getBoolean("directory") }) { "GOG installer contained no game files" }
val inventory = JSONArray(files.map { it.first })
GogFiles.validate(inventory, proposal.folder)
val executable = sidecar.exe.replace('\\', '/')
check(files.any { !it.first.getBoolean("directory") && it.first.getString("path").equals(executable, true) } ||
proposal.before.verified && proposal.before.files.length() > 0 &&
proposal.before.files.objects().none { it.getString("path").equals(executable, true) } && GogFiles.inside(proposal.folder, executable).isFile) {
"The offline installer did not extract the game's executable. No installed files were changed."
}
val installed = proposal.target.copy(files = inventory)
GogFiles.write(File(GogFiles.dir(proposal.folder), "refresh-target.json"), installed.json())
for ((index, entry) in files.withIndex()) {
if (stop.get()) return
val (file, sourceFile) = entry
val destination = GogFiles.inside(proposal.folder, file.getString("path"))
if (file.getBoolean("directory")) java.nio.file.Files.createDirectories(destination.toPath()) else {
destination.parentFile!!.mkdirs()
GogFiles.replace(sourceFile, destination)
}
handle?.stageProgress((index + 1).toLong(), files.size.toLong())
}
if (proposal.target.source != "depot") {
val targetPaths = files.mapTo(HashSet()) { it.first.getString("path").lowercase(java.util.Locale.ROOT) }
for (old in proposal.before.files.objects()) if (old.getString("path").lowercase(java.util.Locale.ROOT) !in targetPaths && GogFiles.matches(proposal.folder, old))
check(GogFiles.inside(proposal.folder, old.getString("path")).delete())
installed.write(proposal.folder)
}
}
fun apply(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean, onApplying: () -> Unit): Boolean {
check(GogFiles.read(GogFiles.journal(proposal.folder))?.optString("phase") in setOf("download", "patch-ready")) {
"The patch result needs recovery. Inspect the installer or use a full offline refresh; the patch will not be run again."
}
val installer = download(context, proposal, handle, stop)
if (stop.get()) return false
val setup = GogContent.setupFiles(proposal.before, GogContent.token(context))
if (setup != null) {
GogFallback.transfer(proposal.folder, JSONObject().put("files", setup.first).put("links", setup.second)
.put("downloadBytes", setup.first.objects().sumOf { it.getJSONArray("chunks").objects().sumOf { chunk -> chunk.getLong("compressedSize") } }), handle, stop)
if (stop.get()) return false
}
val added = AddedGames.single(context, proposal.folder.path) ?: error("The GOG game shortcut is unavailable")
val id = (added.steamAppId?.toLong() ?: added.appId) and 0xffffffffL
val folder = AddedGames.guestPath(context, proposal.folder) ?: error("The GOG folder is unavailable to Linux")
val executable = AddedGames.guestPath(context, installer) ?: error("The GOG patch is unavailable to Linux")
context.startActivity(android.content.Intent(context, com.droiddeck.launcher.SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, if (SessionState.running) SessionState.mode else SessionService.MODE_DESKTOP)
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP))
val deadline = System.currentTimeMillis() + 120_000
while (AgentGuest.hello(context) == null && System.currentTimeMillis() < deadline) { if (stop.get()) return false; Thread.sleep(250) }
check(AgentGuest.hello(context) != null) { "The Linux session did not become ready; open it and retry" }
val journal = GogFiles.read(GogFiles.journal(proposal.folder)) ?: error("GOG patch journal is missing")
journal.put("phase", "patch-ready")
File(GogFiles.dir(proposal.folder), "patch-status.json").delete()
GogFiles.write(GogFiles.journal(proposal.folder), journal)
val request = JSONObject().put("kind", "exec").put("timeout", 15)
.put("env", JSONObject().put("DROIDDECK_GOG_DESKTOP", if (SessionState.mode == SessionService.MODE_DESKTOP) "1" else "0"))
.put("argv", JSONArray(listOf(HELPER, "start", folder, id.toString(), executable, added.guestExe)))
if (stop.get()) return false
onApplying()
val response = AgentGuest.call(context, request, 20_000, trusted = true)
check(response.optBoolean("ok") && response.optInt("exitCode", -1) == 0) { "The GOG patch installer could not start; inspect the GOG log" }
handle.stage(DownloadStage.INSTALL, "Use the Linux session to finish or cancel the patch installer")
var nextStatus = System.currentTimeMillis() + 5_000
while (true) {
val status = GogFiles.read(File(GogFiles.dir(proposal.folder), "patch-status.json"))
if (status?.optString("state") in setOf("done", "failed", "uncertain")) {
check(status?.optString("state") == "done") { status?.optString("reason") ?: "GOG patch failed" }
break
}
check(SessionState.running) { "The patch session ended. Its result needs recovery; the patch will not be rerun automatically." }
check(!SessionState.suspended) { "The patch session was suspended. Resume it and verify recovery before retrying." }
if (System.currentTimeMillis() >= nextStatus) {
val query = JSONObject().put("kind", "exec").put("timeout", 5).put("argv", JSONArray(listOf(HELPER, "status", folder)))
val answer = AgentGuest.call(context, query, 10_000, trusted = true)
check(answer.optBoolean("ok") && answer.optInt("exitCode", -1) == 0) { "The patch helper could not be reached. Resume the Linux session and verify recovery." }
nextStatus = System.currentTimeMillis() + 5_000
}
Thread.sleep(500)
}
val info = GogFiles.read(File(proposal.folder, "goggame-${proposal.before.id}.info"))
val version = info?.optString("versionName").orEmpty()
val build = GogInstallRecord.authenticBuild(proposal.folder, proposal.before.id)
var record = proposal.target.copy(build = build, version = version, files = JSONArray(), manifest = JSONObject(), verified = false)
record.write(proposal.folder)
if (build.isNotBlank()) {
record = runCatching {
val token = GogContent.token(context)
val target = GogBuild.select(GogContent.builds(record.id, token), pinned = build)
val snapshot = target?.let { GogContent.snapshot(record, it, token) }
snapshot?.takeIf { it.files.objects().all { f -> f.optBoolean("directory") || GogFiles.matches(proposal.folder, f) } } ?: record
}.getOrDefault(record)
}
record.write(proposal.folder)
if (!record.verified) {
val before = StoreGameSidecar.read(proposal.folder) ?: error("The GOG installation record is missing")
before.copy(installVersion = "", state = StoreGameSidecar.STATE_UPDATING).write(proposal.folder)
val operation = GogFiles.read(GogFiles.journal(proposal.folder))!!
GogFiles.write(GogFiles.journal(proposal.folder), operation.put("phase", "patch-uncertain"))
}
return true
}
}
@@ -10,6 +10,7 @@ import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreBackend
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
@@ -18,6 +19,8 @@ import java.io.File
object ItchBackend : StoreBackend {
override val store: Store = Store.ITCH
override fun maintenanceAdapter(): StoreMaintenanceAdapter = ItchMaintenanceAdapter
override fun signIn(context: Context) {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ItchApi.KEYS_PAGE)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
@@ -11,14 +11,17 @@ import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreNet
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import org.apache.commons.compress.archivers.sevenz.SevenZFile
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.apache.commons.compress.archivers.zip.ZipFile
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
@@ -31,8 +34,13 @@ internal class ItchInstaller(
private val app: Context,
private val item: CatalogItem,
private val folder: File,
private val maintenanceTarget: JSONObject? = null,
) : 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 +48,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)
@@ -48,47 +59,93 @@ internal class ItchInstaller(
val upload = (if (chosen.isBlank()) ItchUploads.windows(uploads) else ItchUploads.byId(uploads, chosen))
?: throw IllegalStateException(app.getString(R.string.stores_itch_no_upload))
val uploadId = upload.optString("id")
val version = ItchUploads.updatedAt(upload)
val filename = ItchUploads.filename(upload)
val size = ItchUploads.size(upload)
maintenanceTarget?.let {
require(it.optInt("schema") == 1 && it.optString("gameId") == gameId &&
it.optString("downloadKeyId") == downloadKeyId && it.optString("uploadId") == uploadId &&
it.optString("updatedAt") == version && it.optString("filename") == filename && it.optLong("size") == size) {
"The pinned itch.io upload changed; prepare maintenance again"
}
}
val scratch = StoreInstallRoot.scratchDir(app, Store.ITCH, item.id)
scratch.mkdirs()
val archive = File(scratch, filename.ifBlank { "download.bin" })
val exe = try {
handle.stage(DownloadStage.DOWNLOAD)
download(key, downloadKeyId, uploadId, upload.optString("updated_at", upload.optString("updatedAt")), archive, size, handle)
download(key, downloadKeyId, uploadId, version, archive, size, handle)
if (cancelled.get()) return null
handle.stage(DownloadStage.INSTALL)
install(archive, filename, handle, resuming)
} catch (t: Throwable) {
if (!cancelled.get()) StoreInstalls.discard(app, folder, listOf(scratch))
if (maintenanceTarget != null) {
runCatching { handle.interruptible(true) }
val beforeSidecar = previous
val recoverableCommit = runCatching { ItchStaging.recover(folder) }.getOrDefault(true)
if (t is ItchStaging.PreflightConflict && !recoverableCommit && beforeSidecar != null) {
runCatching { StoreMaintenance.complete(app, InstalledStoreGame(beforeSidecar, folder)) }
}
}
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()
StoreInstalls.deleteTree(scratch)
if (maintenanceTarget != null) {
val beforeSidecar = previous ?: throw IllegalStateException("The installed itch.io sidecar disappeared")
try {
StoreMaintenance.complete(app, InstalledStoreGame(beforeSidecar, folder), version,
beforeSidecar.extra + ("uploadId" to maintenanceTarget.optString("uploadId")))
ItchUpdates.applied(app, item.key)
} finally { handle.interruptible(true) }
return folder.path
}
val sidecar = StoreGameSidecar(
store = Store.ITCH,
id = item.id,
title = item.title,
exe = exe,
installVersion = upload.optString("updated_at", upload.optString("updatedAt")),
args = previous?.args.orEmpty(),
env = previous?.env.orEmpty(),
installVersion = version,
installedAt = System.currentTimeMillis(),
cover = item.imageUrl,
hero = item.imageUrl,
extra = mapOf("gameId" to gameId, "downloadKeyId" to downloadKeyId, "uploadId" to uploadId),
cloud = false,
)
if (!updating) ItchStaging.writeInventory(folder, ItchStaging.inventory(folder))
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))
if (maintenanceTarget != null) {
val phase = runCatching { StoreMaintenance.readOperation(folder)?.optString("phase") }.getOrNull()
if (phase in setOf("queued", "download")) runCatching { StoreMaintenance.clearOperation(folder) }
}
}
}
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 +215,84 @@ 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()
val availableBeforeExtraction = if (maintenanceTarget != null) StoreInstallRoot.availableBytes(folder) else StoreInstallRoot.SPACE_UNKNOWN
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" }))
}
if (maintenanceTarget != null) previous?.exe.orEmpty() else {
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 (maintenanceTarget != null) {
val stagedBytes = ItchStaging.regularFileBytes(work)
?: throw IllegalStateException("Could not measure the extracted itch.io archive")
val requiredBytes = ItchStaging.additionalBytesRequired(stagedBytes, backupExtraBytes = 0L)
handle.diskSize(requiredBytes)
if (StoreInstallRoot.insufficientSpace(requiredBytes, availableBeforeExtraction)) {
throw IllegalStateException(app.getString(R.string.stores_storage_insufficient,
com.droiddeck.launcher.stores.formatBytes(requiredBytes),
com.droiddeck.launcher.stores.formatBytes(availableBeforeExtraction)))
}
}
if (updating && maintenanceTarget != null) {
handle.interruptible(false)
synchronized(commit) {
if (cancelled.get()) {
handle.interruptible(true)
ItchStaging.delete(work)
return null
}
val old = previous ?: throw IllegalStateException("The installed itch.io sidecar disappeared")
val game = InstalledStoreGame(old, folder)
StoreMaintenance.withApplyLease(game) {
val targetInventory = ItchStaging.inventory(work)
val savedInventory = ItchStaging.readInventoryIfPresent(folder)
val targetUploadId = maintenanceTarget?.optString("uploadId").orEmpty()
val targetVersion = maintenanceTarget?.optString("updatedAt").orEmpty()
val installedExactUpload = targetUploadId.isNotBlank() && old.extra["uploadId"] == targetUploadId &&
old.installVersion == targetVersion
val managed = ItchStaging.previousInventory(savedInventory, targetInventory, installedExactUpload, old.exe)
ItchStaging.commit(work, folder, managed, onCommitted = { next ->
ItchStaging.writeInventory(folder, next)
})
}
}
return exe
}
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 +315,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 +324,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 +334,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,137 @@
package com.droiddeck.launcher.stores.itch
import android.content.Context
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.SavedQueue
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
import com.droiddeck.launcher.stores.maintenance.RecoveryState
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import org.json.JSONObject
import java.util.concurrent.ConcurrentHashMap
internal object ItchMaintenanceAdapter : StoreMaintenanceAdapter {
override val store = Store.ITCH
private val exactTargets = ConcurrentHashMap<String, JSONObject>()
private val exactCheckedAt = ConcurrentHashMap<String, Long>()
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> {
val result = linkedSetOf(MaintenanceAction.REFRESH)
if (StoreMaintenance.check(game).state == MaintenanceCheckState.AVAILABLE) result.add(MaintenanceAction.UPDATE)
val exact = exactTargets[game.key]
if (System.currentTimeMillis() - (exactCheckedAt[game.key] ?: 0L) < 30 * 60_000L &&
!game.sidecar.installVersion.isBlank() && exact != null && exact.optString("uploadId") == game.sidecar.extra["uploadId"] &&
exact.optString("updatedAt") == game.sidecar.installVersion) result.add(MaintenanceAction.REPAIR)
return result
}
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck {
val key = ItchAuth.key(context)
if (key.isBlank()) { forgetExact(game.key); return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "Sign in to itch.io to check uploads") }
val gameId = game.sidecar.extra["gameId"].orEmpty()
if (gameId.isBlank()) { forgetExact(game.key); return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "The installed itch.io game has no game ID") }
val uploads = ItchApi.uploads(key, gameId, game.sidecar.extra["downloadKeyId"].orEmpty())
?: run { forgetExact(game.key); return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "itch.io upload check failed") }
if (game.sidecar.installVersion.isBlank()) {
forgetExact(game.key)
return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "The installed itch.io upload version is unknown; use Refresh")
}
val uploadId = game.sidecar.extra["uploadId"].orEmpty()
val installed = ItchUploads.byId(uploads, uploadId)
val exact = installed?.takeIf { game.sidecar.installVersion.isNotBlank() && ItchUploads.updatedAt(it) == game.sidecar.installVersion }
if (exact != null) {
exactTargets[game.key] = targetJson(game, exact)
exactCheckedAt[game.key] = System.currentTimeMillis()
} else forgetExact(game.key)
val update = ItchUpdates.evaluate(uploads, uploadId, game.sidecar.installVersion)
return if (update == null) MaintenanceCheck(MaintenanceCheckState.CURRENT, game.sidecar.installVersion)
else MaintenanceCheck(MaintenanceCheckState.AVAILABLE, update.updatedAt, if (update.replaced) "The installed upload was replaced" else "A newer upload is available")
}
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
val token = ItchAuth.key(context)
require(token.isNotBlank()) { "Sign in to itch.io to maintain this game" }
val extra = game.sidecar.extra
val gameId = extra["gameId"].orEmpty()
val keyId = extra["downloadKeyId"].orEmpty()
require(gameId.isNotBlank()) { "The installed itch.io game has no game ID" }
val uploads = ItchApi.uploads(token, gameId, keyId) ?: throw IllegalStateException("itch.io upload check failed")
val currentUpload = ItchUploads.byId(uploads, extra["uploadId"].orEmpty())
val chosenUpload = when (action) {
MaintenanceAction.REPAIR -> currentUpload?.takeIf { game.sidecar.installVersion.isNotBlank() && ItchUploads.updatedAt(it) == game.sidecar.installVersion }
?: throw IllegalStateException("The exact installed upload is no longer available; use Refresh for the current upload")
MaintenanceAction.UPDATE -> {
val next = ItchUpdates.evaluate(uploads, extra["uploadId"].orEmpty(), game.sidecar.installVersion)
?: throw IllegalStateException("No newer itch.io upload is available")
ItchUploads.byId(uploads, next.uploadId) ?: throw IllegalStateException("The selected itch.io upload disappeared")
}
MaintenanceAction.REFRESH -> currentUpload ?: ItchUploads.newestWindows(uploads)
?: throw IllegalStateException("No Windows itch.io upload is available")
else -> throw IllegalArgumentException("Unsupported itch.io maintenance action")
}
val target = targetJson(game, chosenUpload)
val id = target.optString("uploadId")
val stamp = target.optString("updatedAt")
val label = when (action) {
MaintenanceAction.REPAIR -> "installed upload $id ($stamp)"
MaintenanceAction.UPDATE -> "upload $id ($stamp)"
else -> if (id == extra["uploadId"] && stamp == game.sidecar.installVersion) "current upload $id ($stamp)" else "current upload $id ($stamp); the installed upload is no longer available"
}
val size = target.optLong("size")
return MaintenanceProposal(game.folder, game.sidecar, label, action, size, MaintenanceProposal.UNKNOWN_BYTES,
"Downloads one pinned archive. Extracted size and required free space are unknown until download; DroidDeck checks the measured extracted payload before replacing files.", target)
}
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean =
enqueuePinned(context, game, proposal.target)
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) {
val target = operation.optJSONObject("target") ?: throw IllegalStateException("itch.io maintenance target is missing")
check(enqueuePinned(context, game, target)) { "itch.io maintenance is already queued" }
}
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
ItchStaging.readInventoryIfPresent(game.folder)
val operation = StoreMaintenance.readOperation(game.folder)
return if (operation?.optString("phase")?.let { it in setOf("queued", "download", "applying") } == true || ItchStaging.recover(game.folder))
MaintenanceRecovery(RecoveryState.RESUMABLE, "Resume the interrupted itch.io archive replacement")
else MaintenanceRecovery()
}
private fun enqueuePinned(context: Context, game: InstalledStoreGame, target: JSONObject): Boolean {
val item = CatalogItem(
Store.ITCH, game.sidecar.id, game.sidecar.title, game.sidecar.hero,
tallImageUrl = game.sidecar.cover, isFree = game.sidecar.extra["downloadKeyId"].isNullOrBlank(), owned = true,
extra = game.sidecar.extra + mapOf("uploadId" to target.optString("uploadId"),
StoreMaintenance.OPERATION_KEY to (StoreMaintenance.readOperation(game.folder)?.optString("operation") ?: MaintenanceAction.REFRESH.name),
StoreMaintenance.FOLDER_KEY to game.folder.absolutePath),
)
val entry = DownloadEntry(Store.ITCH, game.sidecar.id, game.sidecar.title,
bytesTotal = target.optLong("size"), location = StoreInstallRoot.labelFor(context, game.folder))
return DownloadQueue.enqueueIfIdle(context.applicationContext, entry, onAccepted = {
SavedQueue.remember(context.applicationContext, item, null)
}) { ItchInstaller(context.applicationContext, item, game.folder, target) }
}
private fun targetJson(game: InstalledStoreGame, upload: JSONObject): JSONObject = JSONObject()
.put("schema", 1).put("gameId", game.sidecar.extra["gameId"].orEmpty())
.put("downloadKeyId", game.sidecar.extra["downloadKeyId"].orEmpty())
.put("uploadId", upload.optString("id"))
.put("updatedAt", ItchUploads.updatedAt(upload))
.put("filename", ItchUploads.filename(upload))
.put("size", ItchUploads.size(upload))
private fun forgetExact(gameKey: String) {
exactTargets.remove(gameKey)
exactCheckedAt.remove(gameKey)
}
}
@@ -0,0 +1,434 @@
package com.droiddeck.launcher.stores.itch
import org.json.JSONObject
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.RandomAccessFile
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
internal object ItchStaging {
const val DIR = ".droiddeck-update"
const val RECORD = ".droiddeck-store.json"
private const val JOURNAL = "itch-commit.json"
private const val PROGRESS = "itch-commit-progress.jsonl"
private const val INVENTORY = "itch-inventory.json"
private const val BACKUPS = "itch-backups"
private const val DIRECTORY = "<directory>"
class PreflightConflict(message: String) : IllegalArgumentException(message)
fun inventory(root: File): Map<String, String> = linkedMapOf<String, String>().also { out ->
fun visit(dir: File, prefix: String) {
for (child in dir.listFiles().orEmpty().sortedBy { it.name }) {
if (Files.isSymbolicLink(child.toPath())) continue
val path = if (prefix.isEmpty()) child.name else "$prefix/${child.name}"
if (prefix.isEmpty() && (child.name == RECORD || child.name == DIR || child.name == ".droiddeck-maintenance")) continue
if (child.isDirectory) {
val children = child.listFiles()
if (children != null && children.isEmpty()) out["$path/"] = DIRECTORY
else visit(child, path)
} else if (child.isFile) out[path] = sha256(child)
}
}
visit(root, "")
}
fun regularFileBytes(root: File): Long? {
var total = 0L
var readable = true
fun visit(dir: File) {
if (!readable || Files.isSymbolicLink(dir.toPath())) return
val children = dir.listFiles() ?: run { readable = false; return }
for (child in children) {
if (Files.isSymbolicLink(child.toPath())) continue
if (child.isDirectory) visit(child)
else if (child.isFile) {
val length = runCatching { Files.size(child.toPath()) }.getOrNull()
if (length == null || Long.MAX_VALUE - total < length) {
readable = false
return
}
total += length
}
}
}
if (!root.isDirectory) return null
visit(root)
return total.takeIf { readable }
}
fun additionalBytesRequired(stagedBytes: Long, backupExtraBytes: Long): Long {
require(stagedBytes >= 0L && backupExtraBytes >= 0L)
return if (Long.MAX_VALUE - stagedBytes < backupExtraBytes) Long.MAX_VALUE else stagedBytes + backupExtraBytes
}
private fun protectedUserData(relative: String): Boolean = relative.split('/').any {
it.lowercase() in setOf("save", "saves", "userdata", "user data", "profiles")
} || relative.substringAfterLast('/').substringAfterLast('.', "").lowercase() in setOf("sav", "save")
fun readInventory(root: File): Map<String, String> = readInventoryIfPresent(root).orEmpty()
fun previousInventory(
saved: Map<String, String>?,
target: Map<String, String>,
exactLegacyTarget: Boolean,
selectedExe: String,
): Map<String, String> = (saved ?: if (exactLegacyTarget) target else emptyMap())
.filterKeys { it != selectedExe || it in target }
fun readInventoryIfPresent(root: File): Map<String, String>? {
val metadata = File(root, ".droiddeck-maintenance")
require(!Files.isSymbolicLink(metadata.toPath())) { "Maintenance metadata directory is a symbolic link" }
val file = File(metadata, INVENTORY)
require(!Files.isSymbolicLink(file.toPath())) { "itch.io inventory is a symbolic link" }
if (!file.exists()) return null
require(file.isFile) { "itch.io inventory is not a regular file" }
val value = runCatching { JSONObject(file.readText()) }
.getOrElse { throw IllegalStateException("itch.io inventory is corrupt", it) }
return linkedMapOf<String, String>().apply {
value.keys().forEach { path ->
val hash = value.optString(path)
require(validInventoryEntry(root.canonicalFile, path, hash)) { "itch.io inventory entry is invalid" }
put(path, hash)
}
}
}
fun writeInventory(root: File, inventory: Map<String, String>) {
val metadata = File(root, ".droiddeck-maintenance")
require(!Files.isSymbolicLink(metadata.toPath())) { "Maintenance metadata directory is a symbolic link" }
metadata.mkdirs()
val file = File(metadata, INVENTORY)
require(!Files.isSymbolicLink(file.toPath())) { "itch.io inventory is a symbolic link" }
writeJournal(file, JSONObject().apply { inventory.forEach { (path, hash) -> put(path, hash) } })
}
fun commit(
from: File,
to: File,
previous: Map<String, String>,
afterEntry: ((Int) -> Unit)? = null,
onCommitted: ((Map<String, String>) -> Unit)? = null,
): Map<String, String> {
require(!Files.isSymbolicLink(to.toPath())) { "The itch.io install folder is a symbolic link" }
val root = to.canonicalFile
val metadata = File(root, ".droiddeck-maintenance").apply { mkdirs() }
require(!Files.isSymbolicLink(metadata.toPath())) { "Maintenance metadata directory is a symbolic link" }
val backups = File(metadata, BACKUPS)
val journal = File(metadata, JOURNAL)
val progress = File(metadata, PROGRESS)
val existing = readJournal(journal)
val discovered = inventory(from)
val existingNext = existing?.getJSONObject("next")
val next = existing?.optJSONObject("next")?.let { saved ->
linkedMapOf<String, String>().apply {
saved.keys().forEach { relative ->
val hash = saved.optString(relative)
require(validInventoryEntry(root, relative, hash)) { "The interrupted itch.io inventory is invalid" }
put(relative, hash)
}
for ((relative, hash) in discovered) {
val becameEmptyAfterMove = hash == DIRECTORY && relative.endsWith('/') &&
keys.any { it != relative && it.startsWith(relative) }
require(this[relative] == hash || becameEmptyAfterMove) {
"The staged itch.io archive does not match the interrupted target"
}
}
}
} ?: discovered
val files = JSONObject().apply { next.forEach { (path, hash) -> put(path, hash) } }
val obsolete = previous.keys.filter { it !in next }.sorted()
val stage = from.canonicalFile
val paths = obsolete.sortedWith(compareByDescending<String> { it.count { ch -> ch == '/' } }.thenBy { it }) +
next.keys.sortedWith(compareBy<String> { it.count { ch -> ch == '/' } }.thenBy { it })
val obsoletePlan = JSONObject().apply { obsolete.forEach { put(it, previous[it]) } }
val legacyDone = existing?.optJSONObject("done")
check(existing == null || existing.optInt("schema") == 1 && existingNext != null && existing.optJSONObject("obsolete") != null) {
"An interrupted itch.io replacement has an unsupported journal"
}
check(existing == null || !existing.has("done") || legacyDone != null) {
"An interrupted itch.io progress journal is invalid"
}
require(!Files.isSymbolicLink(progress.toPath())) { "The itch.io progress log is a symbolic link" }
val allowedPaths = next.keys + obsoletePlan.keys().asSequence().toSet()
val completed = if (existing != null) readProgress(progress, root, allowedPaths) else linkedSetOf()
if (existing != null && legacyDone != null) {
validateDone(root, legacyDone, allowedPaths)
for (relative in legacyDone.keys().asSequence().filter { legacyDone.optBoolean(it) }) {
if (completed.add(relative)) appendProgress(progress, relative)
}
}
require(!Files.isSymbolicLink(backups.toPath())) { "The itch.io backup directory is a symbolic link" }
backups.mkdirs()
require(!Files.isSymbolicLink(backups.toPath())) { "The itch.io backup directory is a symbolic link" }
check(backups.isDirectory) { "The itch.io backup path is not a directory" }
for (relative in paths) {
val expected = next[relative]
if (expected == null) continue
val path = relative.removeSuffix("/")
val dest = safe(root, path) ?: throw PreflightConflict("Unsafe itch.io archive path: $relative")
safe(backups, path) ?: throw PreflightConflict("Unsafe itch.io backup path: $relative")
val wasJournaledDone = relative in completed
if (expected == DIRECTORY) {
if (dest.exists() && !dest.isDirectory) {
val oldFileHash = previous[path]
if (oldFileHash == null || !dest.isFile || sha256(dest) != oldFileHash)
throw PreflightConflict("itch.io archive directory collides with an unmanaged file: $path")
}
continue
}
val oldHash = previous[relative]
if (protectedUserData(path) && dest.exists()) {
if (!((oldHash != null && dest.isFile && sha256(dest) == oldHash) || wasJournaledDone))
throw PreflightConflict("itch.io archive collides with untracked or modified user data: $path")
}
val currentHash = if (dest.isFile) sha256(dest) else null
if (currentHash != expected) {
val emptyManagedDirectory = dest.isDirectory && !Files.isSymbolicLink(dest.toPath()) && dest.listFiles().isNullOrEmpty()
if (dest.exists() && !dest.isFile && !emptyManagedDirectory)
throw PreflightConflict("itch.io update collides with an unmanaged directory: $relative")
if (dest.exists() && oldHash == null && !emptyManagedDirectory && !wasJournaledDone)
throw PreflightConflict("itch.io update collides with an unmanaged file: $relative")
require(safe(stage, path)?.isFile == true) { "Staged itch.io file is missing: $relative" }
}
}
val plan = JSONObject().put("schema", 1).put("next", files).put("obsolete", obsoletePlan)
if (existing == null || legacyDone != null) {
if (existing == null && progress.exists()) check(progress.delete()) { "Could not clear stale itch.io progress log" }
writeJournal(journal, plan)
}
var count = 0
for (relative in paths) {
val directory = next[relative] == DIRECTORY
val path = relative.removeSuffix("/")
val expected = next[relative]
val oldHash = previous[relative]
val wasJournaledDone = relative in completed
val dest = safe(root, path)
if (dest == null && expected == null) {
if (completed.add(relative)) appendProgress(progress, relative)
count++
afterEntry?.invoke(count)
continue
}
val actualDest = dest ?: throw IllegalStateException("Unsafe itch.io archive path: $relative")
val staged = safe(stage, path)
val backup = safe(backups, path)
if (backup == null && expected == null) {
if (completed.add(relative)) appendProgress(progress, relative)
count++
afterEntry?.invoke(count)
continue
}
val actualBackup = backup ?: throw IllegalStateException("Unsafe itch.io backup path: $relative")
if (wasJournaledDone) {
val expectedHash = expected.takeUnless { it == DIRECTORY }
if (expectedHash != null && actualDest.isFile && sha256(actualDest) == expectedHash) { count++; continue }
if (expected == DIRECTORY && actualDest.isDirectory && !Files.isSymbolicLink(actualDest.toPath())) { count++; continue }
if (expectedHash == null && expected != DIRECTORY && (!actualDest.isFile || oldHash == null || sha256(actualDest) != oldHash)) { count++; continue }
}
if (expected == null) {
if (oldHash == DIRECTORY) {
if (actualDest.isDirectory && !Files.isSymbolicLink(actualDest.toPath()) && actualDest.listFiles().isNullOrEmpty()) actualDest.delete()
} else if (actualDest.isFile && oldHash != null && sha256(actualDest) == oldHash) {
actualBackup.parentFile?.mkdirs()
move(actualDest, actualBackup)
}
} else if (directory) {
require(!Files.isSymbolicLink(actualDest.toPath())) { "itch.io archive directory collides with a symbolic link: $path" }
if (actualDest.exists() && !actualDest.isDirectory) {
val oldFileHash = previous[path]
require(oldFileHash != null && sha256(actualDest) == oldFileHash) { "itch.io archive directory collides with an unmanaged file: $path" }
actualBackup.parentFile?.mkdirs()
move(actualDest, actualBackup)
}
check(actualDest.isDirectory || actualDest.mkdirs()) { "Could not create itch.io archive directory: $path" }
} else {
if (protectedUserData(path) && actualDest.exists()) {
require((oldHash != null && actualDest.isFile && sha256(actualDest) == oldHash) || wasJournaledDone) {
"itch.io archive collides with untracked or modified user data: $path"
}
}
val currentHash = if (actualDest.isFile) sha256(actualDest) else null
if (currentHash == expected) {
staged?.delete()
} else {
val stagedFile = staged?.takeIf { it.isFile } ?: throw IllegalStateException("Staged itch.io file is missing: $relative")
val emptyManagedDirectory = actualDest.isDirectory && !Files.isSymbolicLink(actualDest.toPath()) && actualDest.listFiles().isNullOrEmpty()
require(!actualDest.exists() || oldHash != null || emptyManagedDirectory || wasJournaledDone) { "itch.io update collides with an unmanaged file: $relative" }
if (actualDest.isDirectory && !Files.isSymbolicLink(actualDest.toPath()) && actualDest.listFiles().isNullOrEmpty()) actualDest.delete()
require(!actualDest.exists() || actualDest.isFile) { "itch.io update collides with an unmanaged directory: $relative" }
require(!Files.isSymbolicLink(actualDest.toPath())) { "itch.io update collides with a symbolic link: $relative" }
if (actualDest.exists() && !actualBackup.exists()) {
actualBackup.parentFile?.mkdirs()
move(actualDest, actualBackup)
}
actualDest.parentFile?.mkdirs()
move(stagedFile, actualDest)
check(sha256(actualDest) == expected) { "itch.io replacement failed verification: $relative" }
}
}
if (completed.add(relative)) appendProgress(progress, relative)
count++
afterEntry?.invoke(count)
}
onCommitted?.invoke(next)
StoreInstallsSafeDelete.delete(from)
StoreInstallsSafeDelete.delete(backups)
if (progress.exists()) check(progress.delete()) { "Could not remove itch.io progress log" }
journal.delete()
return next
}
fun recover(to: File): Boolean {
require(!Files.isSymbolicLink(to.toPath())) { "The itch.io install folder is a symbolic link" }
val root = to.canonicalFile
val file = File(root, ".droiddeck-maintenance/$JOURNAL")
val state = readJournal(file) ?: return false
require(state.optInt("schema") == 1) { "The interrupted itch.io replacement has an unsupported journal" }
val next = state.optJSONObject("next") ?: throw IllegalStateException("The interrupted itch.io inventory is missing")
val obsolete = state.optJSONObject("obsolete") ?: throw IllegalStateException("The interrupted itch.io cleanup list is missing")
for (relative in next.keys()) {
require(validInventoryEntry(root, relative, next.optString(relative))) {
"The interrupted itch.io inventory is invalid"
}
}
for (relative in obsolete.keys()) {
require(validInventoryEntry(root, relative, obsolete.optString(relative))) {
"The interrupted itch.io cleanup list is invalid"
}
}
val metadata = file.parentFile
val progress = File(metadata, PROGRESS)
val allowedPaths = next.keys().asSequence().toSet() + obsolete.keys().asSequence().toSet()
readProgress(progress, root, allowedPaths)
state.optJSONObject("done")?.let { validateDone(root, it, allowedPaths) }
return true
}
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)
if (child.isDirectory && !Files.isSymbolicLink(child.toPath()) && dest.isDirectory && !Files.isSymbolicLink(dest.toPath())) {
merge(child, dest, false)
} else {
if (Files.isSymbolicLink(dest.toPath())) dest.delete()
require(!dest.exists() || child.isDirectory == dest.isDirectory) {
"itch.io archive path collides with an existing path: ${child.name}"
}
require(!dest.exists() || !dest.isDirectory) { "itch.io archive path collides with a directory: ${child.name}" }
dest.parentFile?.mkdirs()
move(child, dest)
}
}
}
fun delete(file: File) = StoreInstallsSafeDelete.delete(file)
private fun safe(root: File, relative: String): File? {
if (relative.isBlank() || relative.startsWith('/') || relative.contains('\\') || relative.split('/').any { it.isBlank() || it == "." || it == ".." }) return null
val file = File(root, relative)
var current = root
for (segment in relative.split('/')) {
current = File(current, segment)
if (Files.isSymbolicLink(current.toPath())) return null
}
val canonical = file.canonicalFile
return canonical.takeIf { it.path.startsWith(root.path + File.separator) }
}
private fun validInventoryEntry(root: File, relative: String, value: String): Boolean =
safe(root, relative.removeSuffix("/")) != null &&
(if (value == DIRECTORY) relative.endsWith('/') else value.matches(HASH) && !relative.endsWith('/'))
private fun validateDone(root: File, done: JSONObject, allowed: Set<String>) {
for (relative in done.keys()) {
require(relative in allowed && safe(root, relative.removeSuffix("/")) != null && done.get(relative) is Boolean) {
"The interrupted itch.io progress is invalid"
}
}
}
private fun readProgress(file: File, root: File, allowed: Set<String>): MutableSet<String> {
require(!Files.isSymbolicLink(file.toPath())) { "The itch.io progress log is a symbolic link" }
if (!file.exists()) return linkedSetOf()
require(file.isFile) { "The itch.io progress log is not a regular file" }
val bytes = file.readBytes()
val text = bytes.toString(Charsets.UTF_8)
val completed = linkedSetOf<String>()
var start = 0
while (true) {
val end = text.indexOf('\n', start)
if (end < 0) break
val line = text.substring(start, end)
require(line.isNotBlank()) { "The itch.io progress log contains an empty record" }
val relative = runCatching { JSONObject(line).getString("path") }
.getOrElse { throw IllegalStateException("The itch.io progress log is corrupt", it) }
require(relative in allowed && safe(root, relative.removeSuffix("/")) != null) {
"The itch.io progress log contains an invalid path"
}
completed += relative
start = end + 1
}
val lastNewline = bytes.indexOfLast { it == '\n'.code.toByte() }
if (lastNewline + 1 < bytes.size) {
RandomAccessFile(file, "rw").use { journal ->
journal.setLength((lastNewline + 1).toLong())
journal.fd.sync()
}
}
return completed
}
private fun appendProgress(file: File, relative: String) {
require(!Files.isSymbolicLink(file.toPath())) { "The itch.io progress log is a symbolic link" }
val record = JSONObject().put("path", relative).toString() + "\n"
FileOutputStream(file, true).use { output ->
output.write(record.toByteArray(Charsets.UTF_8))
output.fd.sync()
}
}
private fun sha256(file: File): String {
val digest = MessageDigest.getInstance("SHA-256")
FileInputStream(file).use { input ->
val bytes = ByteArray(128 * 1024)
while (true) { val n = input.read(bytes); if (n < 0) break; digest.update(bytes, 0, n) }
}
return digest.digest().joinToString("") { "%02x".format(it) }
}
private fun move(from: File, to: File) {
try { Files.move(from.toPath(), to.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING) }
}
private fun readJournal(file: File): JSONObject? {
file.parentFile?.let { require(!Files.isSymbolicLink(it.toPath())) { "Maintenance metadata directory is a symbolic link" } }
if (Files.isSymbolicLink(file.toPath())) throw IllegalStateException("The itch.io replacement journal is a symbolic link")
if (!file.exists()) return null
require(file.isFile) { "The itch.io replacement journal is not a regular file" }
return runCatching { JSONObject(file.readText()) }.getOrElse { throw IllegalStateException("The itch.io replacement journal is corrupt", it) }
}
private fun writeJournal(file: File, value: JSONObject) {
val temp = File.createTempFile(".itch-commit-", ".tmp", file.parentFile)
try {
FileOutputStream(temp).use { it.write(value.toString().toByteArray(Charsets.UTF_8)); it.fd.sync() }
move(temp, file)
} finally { temp.delete() }
}
private val HASH = Regex("[0-9a-f]{64}")
}
private object StoreInstallsSafeDelete {
fun delete(file: File) {
if (!Files.isSymbolicLink(file.toPath()) && file.isDirectory) file.listFiles().orEmpty().forEach(::delete)
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('/')
@@ -0,0 +1,381 @@
package com.droiddeck.launcher.stores.maintenance
import android.content.Context
import androidx.compose.runtime.mutableStateMapOf
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.RandomAccessFile
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
enum class MaintenanceAction { UPDATE, REPAIR, REFRESH, OPEN_CLIENT }
enum class MaintenanceCheckState { UNKNOWN, CHECKING, CURRENT, AVAILABLE, FAILED }
data class MaintenanceCheck(
val state: MaintenanceCheckState = MaintenanceCheckState.UNKNOWN,
val version: String = "",
val reason: String = "",
)
enum class RecoveryState { NONE, RESUMABLE, NEEDS_ATTENTION }
data class MaintenanceRecovery(val state: RecoveryState = RecoveryState.NONE, val message: String = "")
data class MaintenanceProposal(
val folder: File,
val before: StoreGameSidecar,
val targetLabel: String,
val operation: MaintenanceAction,
val downloadBytes: Long = UNKNOWN_BYTES,
val diskBytes: Long = UNKNOWN_BYTES,
val description: String = "",
val target: JSONObject,
) {
companion object {
const val UNKNOWN_BYTES = -1L
}
}
interface StoreMaintenanceAdapter {
val store: Store
fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction>
fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck
fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal
fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean
fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject)
fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery = MaintenanceRecovery()
fun openClient(context: Context, game: InstalledStoreGame) = Unit
fun openClientLabel(game: InstalledStoreGame): String = "Open client"
}
object StoreMaintenance {
const val OPERATION_KEY = "maintenanceOperation"
const val FOLDER_KEY = "maintenanceFolder"
private const val JOURNAL = "operation.json"
private const val CHECK_INTERVAL_MS = 30 * 60_000L
private val adapters = ConcurrentHashMap<Store, StoreMaintenanceAdapter>()
private val workers = Executors.newFixedThreadPool(2)
private val checkedAt = ConcurrentHashMap<String, Long>()
private val inFlight = ConcurrentHashMap<String, Long>()
private val revisions = ConcurrentHashMap<Store, Long>()
private val accounts = ConcurrentHashMap<Store, String>()
private val operationLocks = ConcurrentHashMap<String, Any>()
private val preparing = ConcurrentHashMap.newKeySet<String>()
val checks = mutableStateMapOf<String, MaintenanceCheck>()
fun register(adapter: StoreMaintenanceAdapter) {
adapters[adapter.store] = adapter
}
fun adapter(store: Store): StoreMaintenanceAdapter? = adapters[store]
fun adapter(game: InstalledStoreGame): StoreMaintenanceAdapter? = adapter(game.sidecar.store)
fun check(game: InstalledStoreGame): MaintenanceCheck = checks[game.key] ?: MaintenanceCheck()
fun checkInstalled(context: Context, games: List<InstalledStoreGame>) {
games.forEach { game -> if (game.sidecar.isInstalled && adapters.containsKey(game.sidecar.store)) check(context, game) }
}
fun check(context: Context, game: InstalledStoreGame, force: Boolean = false) {
val adapter = adapters[game.sidecar.store] ?: return
val account = StoreAccounts.displayName(context, game.sidecar.store).orEmpty()
val previous = accounts.put(game.sidecar.store, account)
if (previous != null && previous != account) invalidate(game.sidecar.store)
val key = "${game.sidecar.store.id}:${game.folder.canonicalPath}"
if (!force && System.currentTimeMillis() - (checkedAt[key] ?: 0L) < CHECK_INTERVAL_MS) return
val owner = revisions[game.sidecar.store] ?: 0L
if (inFlight.putIfAbsent(key, owner) != null) return
StoresState.post { if ((revisions[game.sidecar.store] ?: 0L) == owner) checks[game.key] = MaintenanceCheck(MaintenanceCheckState.CHECKING) }
workers.execute {
try {
val result = runCatching { adapter.check(context.applicationContext, game) }
.getOrElse { MaintenanceCheck(MaintenanceCheckState.FAILED, reason = it.message ?: "${game.sidecar.store.label} update check failed") }
if ((revisions[game.sidecar.store] ?: 0L) == owner && (result.state == MaintenanceCheckState.CURRENT || result.state == MaintenanceCheckState.AVAILABLE))
checkedAt[key] = System.currentTimeMillis()
StoresState.post { if ((revisions[game.sidecar.store] ?: 0L) == owner) checks[game.key] = result }
} finally { inFlight.remove(key, owner) }
}
}
fun invalidate(store: Store) {
revisions.compute(store) { _, revision -> (revision ?: 0L) + 1L }
checkedAt.keys.removeIf { it.startsWith("${store.id}:") }
inFlight.keys.removeIf { it.startsWith("${store.id}:") }
StoresState.post { checks.keys.removeIf { it.startsWith("${store.id}:") } }
}
fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
require(action in capabilities(game)) { "${game.sidecar.store.label} does not support ${action.name.lowercase()}" }
require(action != MaintenanceAction.OPEN_CLIENT)
val adapter = adapters[game.sidecar.store] ?: error("${game.sidecar.store.label} maintenance is unavailable")
val folder = game.folder.canonicalFile
synchronized(operationLock(folder)) {
requireCurrentInstalledGame(game)
check(preparing.add(folder.path)) { "${game.sidecar.store.label} maintenance is already being prepared" }
}
return try {
adapter.prepare(context.applicationContext, game, action)
} finally {
synchronized(operationLock(folder)) { preparing.remove(folder.path) }
}
}
fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> =
adapters[game.sidecar.store]?.capabilities(game).orEmpty()
fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal) {
require(game.folder.canonicalFile == proposal.folder.canonicalFile)
require(proposal.operation != MaintenanceAction.OPEN_CLIENT && proposal.operation in capabilities(game))
val adapter = adapters[game.sidecar.store] ?: error("${game.sidecar.store.label} maintenance is unavailable")
val folder = game.folder.canonicalFile
synchronized(operationLock(folder)) {
requireCurrentInstalledGame(game)
check(folder.path !in preparing) { "${game.sidecar.store.label} maintenance is being prepared" }
require(!com.droiddeck.launcher.stores.download.DownloadQueue.isActive(game.key)) {
"${game.sidecar.store.label} already has an active operation"
}
val enqueueId = java.util.UUID.randomUUID().toString()
writeOperation(proposal, game, enqueueId)
val accepted = try {
adapter.enqueue(context.applicationContext, game, proposal)
} catch (error: Throwable) {
runCatching { clearNewQueuedOperation(game, enqueueId, preserveActive = true) }
.onFailure(error::addSuppressed)
throw error
}
if (!accepted) {
clearNewQueuedOperation(game, enqueueId, preserveActive = false)
error("${game.sidecar.store.label} already has an active operation")
}
}
}
fun beginUninstall(game: InstalledStoreGame): Boolean {
val folder = game.folder.canonicalFile
return synchronized(operationLock(folder)) {
if (game.key in StoresState.uninstalling || folder.path in preparing) return@synchronized false
val hasSharedApply = capabilities(game).any { it != MaintenanceAction.OPEN_CLIENT }
val currentInstall = runCatching {
if (hasSharedApply) requireCurrentInstalledGame(game)
else require(folder.isDirectory && !Files.isSymbolicLink(folder.toPath()))
readOperation(folder) == null
}.getOrDefault(false)
if (!currentInstall) return@synchronized false
StoresState.uninstalling[game.key] = 0f
true
}
}
fun resume(context: Context, game: InstalledStoreGame) {
requireInstalledFolder(context, game.folder)
val adapter = adapters[game.sidecar.store] ?: error("${game.sidecar.store.label} maintenance is unavailable")
val operation = readOperation(game.folder) ?: error("${game.sidecar.store.label} operation journal is missing")
require(operation.optString("folder") == game.folder.canonicalPath && operation.optString("store") == game.sidecar.store.id && operation.optString("id") == game.sidecar.id)
adapter.resume(context.applicationContext, game, operation)
}
fun openClient(context: Context, game: InstalledStoreGame) {
require(MaintenanceAction.OPEN_CLIENT in capabilities(game))
adapters[game.sidecar.store]?.openClient(context.applicationContext, game)
}
fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
val adapterRecovery = try { adapters[game.sidecar.store]?.recovery(context.applicationContext, game) }
catch (error: Exception) { return MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, error.message ?: "The maintenance journal could not be read") }
if (adapterRecovery?.state != null && adapterRecovery.state != RecoveryState.NONE) return adapterRecovery
val operation = try { readOperation(game.folder) }
catch (error: Exception) { return MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, error.message ?: "The maintenance journal could not be read") }
if (operation != null) {
val state = if (operation.optString("phase") in setOf("queued", "download")) RecoveryState.RESUMABLE else RecoveryState.NEEDS_ATTENTION
return MaintenanceRecovery(state, operation.optString("phase"))
}
if (!game.sidecar.isInstalled) return MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, "The installation did not finish")
return adapterRecovery ?: MaintenanceRecovery()
}
fun operationFile(folder: File) = File(File(folder, ".droiddeck-maintenance"), JOURNAL)
fun readOperation(folder: File): JSONObject? {
val directory = File(folder, ".droiddeck-maintenance")
val file = File(directory, JOURNAL)
require(!Files.isSymbolicLink(directory.toPath()) && !Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
return file.takeIf { it.isFile }?.let {
JSONObject(it.readText()).also { operation ->
require(operation.optInt("schema") == 1) { "Unsupported store maintenance journal" }
require(operation.optString("folder") == folder.canonicalPath) { "Maintenance journal folder does not match" }
}
}
}
fun clearOperation(folder: File) {
val directory = File(folder, ".droiddeck-maintenance")
val file = File(directory, JOURNAL)
require(!Files.isSymbolicLink(directory.toPath()) && !Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
if (!file.exists()) return
require(file.isFile) { "Maintenance journal is not a regular file" }
val operation = readOperation(folder) ?: return
require(operation.optString("phase") in setOf("queued", "download")) { "An applying maintenance operation must be recovered" }
require(!Files.isSymbolicLink(directory.toPath()) && !Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
check(file.delete()) { "Could not clear the queued maintenance operation" }
}
fun <T> withApplyLease(game: InstalledStoreGame, block: () -> T): T {
return beginApplyLease(game).use { block() }
}
fun beginApplyLease(game: InstalledStoreGame): AutoCloseable {
val folder = game.folder.canonicalFile
synchronized(operationLock(folder)) { return beginApplyLeaseLocked(game, folder) }
}
private fun beginApplyLeaseLocked(game: InstalledStoreGame, folder: File): AutoCloseable {
require(folder == game.folder.absoluteFile.canonicalFile)
val operation = readOperation(folder) ?: error("${game.sidecar.store.label} operation journal is missing")
require(operation.optString("folder") == folder.path && operation.optString("store") == game.sidecar.store.id && operation.optString("id") == game.sidecar.id)
val directory = File(folder, ".droiddeck-maintenance")
require(!Files.isSymbolicLink(directory.toPath())) { "Maintenance metadata directory is a symbolic link" }
directory.mkdirs()
val leaseFile = File(directory, "lease")
require(!Files.isSymbolicLink(leaseFile.toPath())) { "Maintenance lease is a symbolic link" }
val lease = RandomAccessFile(leaseFile, "rw")
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: run {
lease.close()
error("Close the game before maintenance")
}
try {
val before = StoreGameSidecar.parse(operation.getJSONObject("before").toString())
?: error("The original ${game.sidecar.store.label} settings are missing")
require(before.store == game.sidecar.store && before.id == game.sidecar.id)
writeJson(operationFile(folder), operation.put("phase", "applying"))
before.copy(state = StoreGameSidecar.STATE_UPDATING).write(folder)
} catch (error: Throwable) {
lock.close()
lease.close()
throw error
}
return AutoCloseable { lock.close(); lease.close() }
}
private fun operationLock(folder: File): Any = operationLocks.computeIfAbsent(folder.path) { Any() }
private fun requireCurrentInstalledGame(game: InstalledStoreGame) {
val folder = game.folder.canonicalFile
require(game.sidecar.isInstalled && folder.isDirectory && !Files.isSymbolicLink(folder.toPath())) {
"${game.sidecar.store.label} installation is no longer available"
}
val current = StoreGameSidecar.read(folder)
require(current?.store == game.sidecar.store && current.id == game.sidecar.id && current.isInstalled) {
"${game.sidecar.store.label} installation record is no longer available"
}
require(game.key !in StoresState.uninstalling) { "${game.sidecar.store.label} game is being uninstalled" }
}
private fun clearNewQueuedOperation(game: InstalledStoreGame, enqueueId: String, preserveActive: Boolean) {
val folder = game.folder.canonicalFile
if (preserveActive && com.droiddeck.launcher.stores.download.DownloadQueue.isActive(game.key)) return
val operation = readOperation(folder) ?: return
if (operation.optString("enqueueId") != enqueueId || operation.optString("phase") != "queued" ||
operation.optString("folder") != folder.path || operation.optString("store") != game.sidecar.store.id ||
operation.optString("id") != game.sidecar.id) return
val file = operationFile(folder)
require(!Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
if (file.isFile) check(file.delete()) { "Could not clear the failed queued maintenance operation" }
}
fun complete(
context: Context,
game: InstalledStoreGame,
installVersion: String = game.sidecar.installVersion,
updatedExtra: Map<String, String>? = null,
) {
val folder = game.folder.canonicalFile
val operation = readOperation(folder) ?: error("${game.sidecar.store.label} operation journal is missing")
require(operation.optString("folder") == folder.path && operation.optString("store") == game.sidecar.store.id && operation.optString("id") == game.sidecar.id)
require(operation.optString("phase") == "applying") { "The ${game.sidecar.store.label} operation was not applied" }
val before = StoreGameSidecar.parse(operation.getJSONObject("before").toString())
?: error("The original ${game.sidecar.store.label} settings are missing")
StoreInstalls.complete(context.applicationContext, folder,
before.copy(installVersion = installVersion, extra = updatedExtra ?: before.extra, state = StoreGameSidecar.STATE_INSTALLED))
check(operationFile(folder).delete()) { "Could not finish the ${game.sidecar.store.label} recovery record" }
checkedAt.remove("${game.sidecar.store.id}:${folder.path}")
StoresState.post { checks.remove(game.key) }
}
private fun writeOperation(proposal: MaintenanceProposal, game: InstalledStoreGame, enqueueId: String) {
val folder = proposal.folder.canonicalFile
require(proposal.before.store == game.sidecar.store && proposal.before.id == game.sidecar.id)
val directory = File(folder, ".droiddeck-maintenance")
require(!Files.isSymbolicLink(directory.toPath())) { "Maintenance metadata directory is a symbolic link" }
directory.mkdirs()
val file = File(directory, JOURNAL)
require(!Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
require(!file.exists()) { "Resume or recover the existing ${game.sidecar.store.label} operation first" }
val value = JSONObject().put("schema", 1).put("store", game.sidecar.store.id).put("id", game.sidecar.id)
.put("folder", folder.path).put("enqueueId", enqueueId).put("operation", proposal.operation.name).put("phase", "queued")
.put("before", proposal.before.toJson()).put("targetLabel", proposal.targetLabel)
.put("downloadBytes", proposal.downloadBytes).put("diskBytes", proposal.diskBytes)
.put("description", proposal.description).put("target", proposal.target)
writeJson(file, value)
}
private fun writeJson(file: File, value: JSONObject) {
require(!Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
file.parentFile?.mkdirs()
val temp = File.createTempFile(".maintenance-", ".tmp", file.parentFile)
try {
FileOutputStream(temp).use { it.write(value.toString().toByteArray(Charsets.UTF_8)); it.fd.sync() }
try { Files.move(temp.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING) }
} finally { temp.delete() }
}
fun restore(context: Context, item: CatalogItem) {
if (item.store == Store.GOG && item.extra.containsKey("gogOperation")) {
com.droiddeck.launcher.stores.gog.GogMaintenance.restore(context, item)
return
}
if (adapters[item.store] == null) error("${item.store.label} maintenance is unavailable")
val folder = item.extra["maintenanceFolder"] ?: item.extra["gogFolder"]
?: error("Missing ${item.store.label} recovery folder")
requireInstalledFolder(context, File(folder))
val installed = InstalledStoreGame(
StoreGameSidecar.read(File(folder)) ?: error("${item.store.label} installation record is missing"),
File(folder),
)
require(installed.sidecar.store == item.store && installed.sidecar.id == item.id)
resume(context, installed)
}
private fun requireInstalledFolder(context: Context, folder: File) {
val canonical = folder.canonicalFile
require(StoreInstallRoot.gameFolders(context.applicationContext).any { it.canonicalFile == canonical }) {
"Maintenance folder is outside the installed game roots"
}
}
fun launchExcluded(game: InstalledStoreGame): Boolean {
if (!game.sidecar.isInstalled) return true
val gogJournal = if (game.sidecar.store == Store.GOG) File(game.folder, ".droiddeck-gog/operation.json") else null
if (gogJournal?.isFile == true) {
val phase = runCatching { JSONObject(gogJournal.readText()).optString("phase") }.getOrDefault("")
if (phase != "download") return true
}
val queued = com.droiddeck.launcher.stores.download.DownloadQueue.isActive(game.key)
val file = operationFile(game.folder)
val journal = file.exists() && !runCatching { readOperation(game.folder)?.optString("phase") in setOf("queued", "download") }.getOrDefault(false)
return queued || journal
}
}
@@ -7,10 +7,18 @@ import androidx.compose.runtime.setValue
import com.droiddeck.launcher.stores.*
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import org.json.JSONObject
import java.io.File
object XboxBackend : StoreBackend {
override val store = Store.XBOX
override fun maintenanceAdapter(): StoreMaintenanceAdapter = XboxMaintenanceAdapter
@Volatile private var access: Map<String, String> = emptyMap()
@Volatile private var generation = 0
private var syncing: Int? = null
@@ -148,6 +156,55 @@ object XboxBackend : StoreBackend {
enqueue(context, item, root)
}
internal fun maintenanceCheck(context: Context, game: InstalledStoreGame): MaintenanceCheck {
return try {
if (StoreAccounts.signedInAs(context, store) == null)
return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "Sign in to Xbox before checking package updates")
val contentId = game.sidecar.extra["contentId"].orEmpty()
if (!contentId.matches(Regex("[a-fA-F0-9-]{36}")))
return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "The installed Xbox package identity is unknown")
val market = game.sidecar.extra["market"]?.takeIf { it.matches(Regex("[A-Z]{2}")) } ?: Xodus.market()
val plan = Xodus.run(context.applicationContext, listOf("resolve-package", game.sidecar.id, "--json", "--market", market))
if (plan.optString("status") != "ready")
return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Xodus did not resolve a current Xbox package")
val choice = XboxCatalog.objects(plan.optJSONArray("choices")).firstOrNull { it.optString("contentId").equals(contentId, true) }
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "The installed Xbox package is not in the current package choices")
val version = listOf("version", "packageVersion", "package_version").firstNotNullOfOrNull { key -> choice.optString(key).takeIf { it.isNotBlank() } }
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Xodus did not expose a current package version")
val installed = runCatching { XboxManifest.read(game.folder).version }.getOrDefault(game.sidecar.installVersion)
if (installed.isBlank()) MaintenanceCheck(MaintenanceCheckState.UNKNOWN, version, "The installed Xbox package version is unknown")
else MaintenanceCheck(if (installed == version) MaintenanceCheckState.CURRENT else MaintenanceCheckState.AVAILABLE, version)
} catch (error: Exception) {
MaintenanceCheck(MaintenanceCheckState.FAILED, reason = error.message ?: "Xbox package check failed")
}
}
internal fun prepareMaintenance(context: Context, game: InstalledStoreGame): MaintenanceProposal {
check(!XboxRuntime.isActive(game.sidecar.id)) { "Close this Xbox game before updating it." }
val contentId = game.sidecar.extra["contentId"].orEmpty()
require(contentId.matches(Regex("[a-fA-F0-9-]{36}"))) { "The installed Xbox package identity is unknown." }
val market = game.sidecar.extra["market"]?.takeIf { it.matches(Regex("[A-Z]{2}")) } ?: Xodus.market()
val version = maintenanceCheck(context, game).takeIf { it.state == MaintenanceCheckState.AVAILABLE }?.version.orEmpty()
val size = MaintenanceProposal.UNKNOWN_BYTES
val target = JSONObject().put("schema", 1).put("contentId", contentId).put("market", market).put("version", version)
return MaintenanceProposal(game.folder.canonicalFile, game.sidecar, version.ifBlank { "latest licensed Xbox package" }, MaintenanceAction.UPDATE,
downloadBytes = size, diskBytes = size, description = "Xodus refreshes the installed package through its licensed streaming path.", target = target)
}
internal fun enqueueMaintenance(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
val sidecar = game.sidecar
val item = CatalogItem(store, sidecar.id, sidecar.title, sidecar.hero, tallImageUrl = sidecar.cover,
owned = sidecar.extra["access"] == "owned", subscription = sidecar.extra["access"] == "gamepass",
extra = sidecar.extra + mapOf("contentId" to proposal.target.getString("contentId"), "market" to proposal.target.getString("market"),
StoreMaintenance.OPERATION_KEY to MaintenanceAction.UPDATE.name, StoreMaintenance.FOLDER_KEY to game.folder.canonicalPath))
val root = game.folder.parentFile?.parentFile ?: error("Xbox install root is missing")
val entry = DownloadEntry(store, sidecar.id, sidecar.title, cover = sidecar.cover,
bytesTotal = proposal.downloadBytes, location = StoreInstallRoot.labelFor(context, game.folder))
return DownloadQueue.enqueueIfIdle(context.applicationContext, entry, onAccepted = {
com.droiddeck.launcher.stores.download.SavedQueue.remember(context, item, root)
}) { XboxInstaller(context.applicationContext, item, game.folder, game) }
}
private fun enqueue(context: Context, item: CatalogItem, root: File) {
val app = context.applicationContext
val folder = StoreInstallRoot.folderFor(app, store, item.id, item.title, root)
@@ -4,13 +4,15 @@ import android.content.Context
import com.droiddeck.launcher.stores.*
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import org.json.JSONObject
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
internal class XboxInstaller(private val app: Context, private val item: CatalogItem, private val folder: File) : DownloadQueue.DownloadJob {
internal class XboxInstaller(private val app: Context, private val item: CatalogItem, private val folder: File,
private val maintenanceGame: InstalledStoreGame? = null) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val paused = CountDownLatch(1)
@Volatile private var child: Xodus.Child? = null
@@ -32,8 +34,10 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
folder.mkdirs()
} else {
check(!XboxRuntime.isActive(item.id)) { "Close this Xbox game before updating it." }
StoreInstalls.markUpdating(folder)
StoreInstalls.begin(folder, Store.XBOX, item.id, item.title, item.tallImageUrl, item.imageUrl)
if (maintenanceGame == null) {
StoreInstalls.markUpdating(folder)
StoreInstalls.begin(folder, Store.XBOX, item.id, item.title, item.tallImageUrl, item.imageUrl)
}
}
var complete = false
var sequence = -1L
@@ -41,8 +45,9 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
val source = if (content) selected else item.id
val guestFolder = StoreInstallRoot.guestPathForXodus(app, folder)
val selection = if (content) emptyList() else listOf("--selected-content-id", selected)
Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market,
"--progress-json", "--control-stdin") + selection).use { process ->
val stream = stream@ {
Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market,
"--progress-json", "--control-stdin") + selection).use { process ->
child = process
val rejected = AtomicBoolean(false)
val rejectedLine = Regex(Xodus.SIGN_IN_REJECTED)
@@ -67,18 +72,25 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
} }
check(process.process.waitFor(15, TimeUnit.SECONDS)) { "Xbox installer did not exit." }
diagnostics.join(2000)
if (cancelled.get()) return null
if (cancelled.get()) return@stream
check(!rejected.get()) { app.getString(com.droiddeck.launcher.R.string.stores_xbox_sign_in_again) }
check(process.process.exitValue() == 0 && complete) { "Xbox download did not complete. Resume to retry with fresh licenses." }
}
}
if (maintenanceGame != null) StoreMaintenance.withApplyLease(maintenanceGame, stream) else stream()
if (cancelled.get()) return null
if (content) {
XboxContent.complete(app, item, folder)
return folder.path
}
val exe = executable(folder)
StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
extra = item.extra + mapOf("contentId" to selected, "market" to market)))
val version = XboxManifest.read(folder).version
if (maintenanceGame != null) {
StoreMaintenance.complete(app, maintenanceGame, version,
maintenanceSidecarExtra(maintenanceGame.sidecar.extra, selected, market))
} else StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
installVersion = version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
extra = maintenanceSidecarExtra(item.extra, selected, market)))
return folder.path
} finally {
child = null
@@ -89,11 +101,11 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
delete = deleteFiles
delete = deleteFiles && maintenanceGame == null
val process = child
if (process == null) {
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
else if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
if (delete && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
else if (delete) StoreInstalls.discard(app, folder, emptyList())
return
}
Thread({
@@ -107,5 +119,13 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
companion object {
internal fun executable(folder: File): String = XboxManifest.executable(folder)
internal fun maintenanceSidecarExtra(before: Map<String, String>, contentId: String, market: String): Map<String, String> =
LinkedHashMap(before).apply {
remove(StoreMaintenance.OPERATION_KEY)
remove(StoreMaintenance.FOLDER_KEY)
put("contentId", contentId)
put("market", market)
}
}
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.stores.xbox
import android.content.Context
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
import com.droiddeck.launcher.stores.maintenance.RecoveryState
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
import org.json.JSONObject
import java.io.File
internal object XboxMaintenanceAdapter : StoreMaintenanceAdapter {
override val store = Store.XBOX
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> =
if (game.sidecar.extra["contentId"].orEmpty().matches(Regex("[a-fA-F0-9-]{36}"))) setOf(MaintenanceAction.UPDATE) else emptySet()
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck = XboxBackend.maintenanceCheck(context, game)
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
require(action == MaintenanceAction.UPDATE) { "Xbox Repair is not exposed by Xodus" }
return XboxBackend.prepareMaintenance(context, game)
}
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
require(proposal.operation == MaintenanceAction.UPDATE && proposal.target.optInt("schema") == 1)
return XboxBackend.enqueueMaintenance(context, game, proposal)
}
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) {
require(operation.optString("phase") in setOf("queued", "download", "applying"))
val target = operation.optJSONObject("target") ?: error("Xbox maintenance target is missing")
require(target.optInt("schema") == 1 && target.optString("contentId").matches(Regex("[a-fA-F0-9-]{36}")))
val proposal = MaintenanceProposal(game.folder.canonicalFile,
com.droiddeck.launcher.stores.StoreGameSidecar.parse(operation.getJSONObject("before").toString())
?: error("The original Xbox settings are missing"), operation.optString("targetLabel"), MaintenanceAction.UPDATE,
operation.optLong("downloadBytes", MaintenanceProposal.UNKNOWN_BYTES),
operation.optLong("diskBytes", MaintenanceProposal.UNKNOWN_BYTES), operation.optString("description"), JSONObject(target.toString()))
check(XboxBackend.enqueueMaintenance(context, game, proposal)) { "Xbox maintenance is already queued" }
}
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
val journal = StoreMaintenance.readOperation(game.folder) ?: return MaintenanceRecovery()
return when (journal.optString("phase")) {
"queued", "download", "applying" -> MaintenanceRecovery(RecoveryState.RESUMABLE, "Resume the Xodus package update")
else -> MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, "The Xbox package update needs recovery")
}
}
}
@@ -0,0 +1,959 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.FilterAlt
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material.icons.filled.Widgets
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.zIndex
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.HomeFolders
import com.droiddeck.launcher.HomeHidden
import com.droiddeck.launcher.HomePins
import android.content.pm.ShortcutInfo
import android.graphics.Bitmap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import com.droiddeck.launcher.HomeWidgets
import com.droiddeck.launcher.R
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
private sealed interface AppEntry : AppEntryKey {
val key: String
class App(val app: HomeApp.LaunchableApp) : AppEntry {
override val label get() = app.label
override val key get() = "app:" + app.key
override val installedAt get() = app.installedAt
override val updatedAt get() = app.updatedAt
}
class Folder(val folder: HomeFolders.Folder, val apps: List<HomeApp.LaunchableApp>) : AppEntry {
override val label get() = folder.name
override val key get() = "folder:" + folder.id
override val installedAt get() = apps.maxOf { it.installedAt }
override val updatedAt get() = apps.maxOf { it.updatedAt }
}
class Shortcut(val pinned: HomePins.Pinned) : AppEntry {
override val label get() = pinned.label
override val key get() = pinned.key
override val installedAt get() = 0L
override val updatedAt get() = 0L
}
}
private fun indexLetter(label: String): String {
val c = label.trim().firstOrNull()?.uppercaseChar() ?: return "#"
return if (c in 'A'..'Z') c.toString() else if (c.isLetter()) c.toString() else "#"
}
private fun searchRank(label: String, q: String): Int? {
if (label.startsWith(q, ignoreCase = true)) return 0
if (label.split(' ', '-', '_', '.').any { it.startsWith(q, ignoreCase = true) }) return 1
if (label.contains(q, ignoreCase = true)) return 2
return null
}
internal fun Context.findActivity(): Activity? {
var c: Context? = this
while (c is ContextWrapper) {
if (c is Activity) return c
c = c.baseContext
}
return null
}
private fun Modifier.menuKey(onMenu: () -> Unit): Modifier = onPreviewKeyEvent { event ->
val k = event.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y && k.keyCode != KeyEvent.KEYCODE_MENU) false
else {
if (k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) onMenu()
true
}
}
internal object AppsView {
const val ALL = "all"
const val GAMES = "games"
const val DOWNLOADED = "downloaded"
const val SYSTEM = "system"
const val HIDDEN = "hidden"
val FILTERS = listOf(ALL, GAMES, DOWNLOADED, SYSTEM, HIDDEN)
const val NAME_ASC = "nameAsc"
const val NAME_DESC = "nameDesc"
const val INSTALLED = "installed"
const val UPDATED = "updated"
val SORTS = listOf(NAME_ASC, NAME_DESC, INSTALLED, UPDATED)
var filter by mutableStateOf(ALL)
var sort by mutableStateOf(NAME_ASC)
private var loaded = false
private fun prefs(context: Context) = context.getSharedPreferences("home_launcher", Context.MODE_PRIVATE)
fun load(context: Context) {
if (loaded) return
loaded = true
val p = prefs(context)
filter = p.getString("filter", ALL)?.takeIf { it in FILTERS } ?: ALL
sort = p.getString("sort", NAME_ASC)?.takeIf { it in SORTS } ?: NAME_ASC
}
fun setFilter(context: Context, value: String) {
filter = value
prefs(context).edit().putString("filter", value).apply()
}
fun setSort(context: Context, value: String) {
sort = value
prefs(context).edit().putString("sort", value).apply()
}
fun keeps(app: HomeApp.LaunchableApp): Boolean {
val hidden = app.key in HomeHidden.keys
return when (filter) {
HIDDEN -> hidden
GAMES -> !hidden && app.game
DOWNLOADED -> !hidden && !app.system
SYSTEM -> !hidden && app.system
else -> !hidden
}
}
fun comparator(): Comparator<AppEntryKey> = when (sort) {
NAME_DESC -> compareBy<AppEntryKey, String>(String.CASE_INSENSITIVE_ORDER) { it.label }.reversed()
INSTALLED -> compareByDescending<AppEntryKey> { it.installedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label }
UPDATED -> compareByDescending<AppEntryKey> { it.updatedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label }
else -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }
}
}
internal interface AppEntryKey {
val label: String
val installedAt: Long
val updatedAt: Long
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) {
val ctx = LocalContext.current
remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); true }
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
val padH = if (narrow) 16.dp else 22.dp
var query by rememberSaveable { mutableStateOf("") }
var openFolder by rememberSaveable { mutableStateOf<String?>(null) }
var renameOnOpen by rememberSaveable { mutableStateOf(false) }
var picking by rememberSaveable { mutableStateOf(false) }
val folders = HomeFolders.folders
val byKey = remember(s.androidApps) { s.androidApps.associateBy { it.key } }
val byPkg = remember(s.androidApps) { s.androidApps.filterNot { it.work }.groupBy { it.packageName }.mapNotNull { (pkg, apps) -> apps.singleOrNull()?.let { pkg to it } }.toMap() }
LaunchedEffect(byPkg) { if (byPkg.isNotEmpty()) HomeFolders.migrateMembers(ctx) { byPkg[it]?.key } }
val member: (String) -> HomeApp.LaunchableApp? = { byKey[it] ?: byPkg[it] }
val pins = HomePins.pinned
val hidden = HomeHidden.keys
val q = query.trim()
val filter = AppsView.filter
val sort = AppsView.sort
val entries: List<AppEntry> = remember(s.androidApps, folders, q, filter, sort, pins, hidden) {
val kept = s.androidApps.filter { AppsView.keeps(it) }
val shortcuts = if (filter == AppsView.ALL) pins.map { AppEntry.Shortcut(it) } else emptyList()
if (q.isNotEmpty()) {
(kept.map { AppEntry.App(it) } + shortcuts).mapNotNull { e -> searchRank(e.label, q)?.let { it to e } }
.sortedWith(compareBy<Pair<Int, AppEntry>> { it.first }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.second.label })
.map { it.second }
} else if (filter != AppsView.ALL) {
kept.map { AppEntry.App(it) }.sortedWith(AppsView.comparator())
} else {
val folderEntries = folders.mapNotNull { f ->
val apps = f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
if (apps.isEmpty()) null else AppEntry.Folder(f, apps)
}
val grouped = folderEntries.flatMap { f -> f.apps.map { it.key } }.toSet()
(folderEntries + kept.filter { it.key !in grouped }.map { AppEntry.App(it) } + shortcuts).sortedWith(AppsView.comparator())
}
}
val grid = rememberLazyGridState()
LaunchedEffect(q, filter, sort) { grid.scrollToItem(0) }
val widgetsShown = q.isEmpty() && filter == AppsView.ALL && HomeWidgets.widgets.isNotEmpty()
val leadItems = if (widgetsShown) 1 else 0
val byName = sort == AppsView.NAME_ASC || sort == AppsView.NAME_DESC
val newFolder: (HomeApp.LaunchableApp) -> Unit = { app ->
val f = HomeFolders.create(ctx, ctx.getString(R.string.apps_folder_default), app.key)
renameOnOpen = true
openFolder = f.id
}
Box(modifier) {
Column(Modifier.fillMaxSize().imePadding()) {
Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = if (narrow) 8.dp else 12.dp)) {
ModeHeader(
stringResource(R.string.content_android_apps), query, { query = it },
placeholder = stringResource(R.string.apps_search_hint),
clearSearchFocus = openFolder != null || picking,
lead = {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
Text(stringResource(R.string.content_android_apps), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
val shownCount = s.androidApps.count { AppsView.keeps(it) } + if (filter == AppsView.ALL) pins.size else 0
Text(androidx.compose.ui.res.pluralStringResource(R.plurals.apps_count, shownCount, shownCount), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
},
) {
AppsFilterButton()
AppsSortButton()
HeaderIconButton(stringResource(R.string.apps_add_widget), Icons.Filled.Widgets, "add-widget") {
HomeWidgets.loadProviders(ctx)
picking = true
}
}
}
Box(Modifier.weight(1f).fillMaxWidth()) {
val scroller = q.isEmpty() && byName && entries.size > 16
LazyVerticalGrid(
columns = GridCells.Adaptive(if (narrow) 84.dp else 96.dp),
state = grid,
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(start = padH, end = if (scroller) padH + 22.dp else padH, top = 12.dp, bottom = 16.dp),
modifier = Modifier.fillMaxSize(),
) {
if (widgetsShown) item(key = "widgets", span = { GridItemSpan(maxLineSpan) }) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val maxW = maxWidth
FlowRow(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp),
) {
for (w in HomeWidgets.widgets) key(w.id) { WidgetCard(w, maxW.value.toInt()) }
}
}
}
if (entries.isEmpty()) item(key = "empty", span = { GridItemSpan(maxLineSpan) }) {
Note(
when {
q.isNotEmpty() -> stringResource(R.string.apps_no_match, q)
filter == AppsView.HIDDEN -> stringResource(R.string.apps_hidden_none)
else -> stringResource(R.string.content_no_android_apps)
},
)
}
items(entries, key = { it.key }) { entry ->
when (entry) {
is AppEntry.App -> AppTile(
entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder,
first = entry === entries.first(),
)
is AppEntry.Shortcut -> PinnedTile(entry.pinned, first = entry === entries.first())
is AppEntry.Folder -> FolderTile(entry, first = entry === entries.first(), onOpen = { renameOnOpen = false; openFolder = entry.folder.id }) {
renameOnOpen = true
openFolder = entry.folder.id
}
}
}
}
if (scroller) AlphabetScroller(entries, grid, leadItems, Modifier.align(Alignment.CenterEnd).fillMaxHeight().padding(end = 4.dp, top = 8.dp, bottom = 8.dp))
}
}
val folder = folders.firstOrNull { it.id == openFolder }
LaunchedEffect(folder == null, openFolder) { if (folder == null && openFolder != null) openFolder = null }
AnimatedVisibility(
folder != null, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
modifier = Modifier.fillMaxSize().zIndex(2f),
) {
var last by remember { mutableStateOf(folder) }
if (folder != null) last = folder
last?.let { f ->
FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder) {
openFolder = null
renameOnOpen = false
}
}
}
AnimatedVisibility(
picking, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
modifier = Modifier.fillMaxSize().zIndex(3f),
) { WidgetPicker(padH) { picking = false } }
}
}
@Composable
private fun SwipeLock() {
DisposableEffect(Unit) {
PageSwipe.locks++
onDispose { PageSwipe.locks-- }
}
}
@Composable
private fun appsFilterLabel(filter: String): String = stringResource(
when (filter) {
AppsView.GAMES -> R.string.apps_filter_games
AppsView.DOWNLOADED -> R.string.apps_filter_downloaded
AppsView.SYSTEM -> R.string.apps_filter_system
AppsView.HIDDEN -> R.string.apps_filter_hidden
else -> R.string.apps_filter_all
},
)
@Composable
private fun appsSortLabel(sort: String): String = stringResource(
when (sort) {
AppsView.NAME_DESC -> R.string.apps_sort_name_desc
AppsView.INSTALLED -> R.string.apps_sort_installed
AppsView.UPDATED -> R.string.apps_sort_updated
else -> R.string.apps_sort_name_asc
},
)
@Composable
private fun AppsFilterButton() = HeaderChoiceButton(
stringResource(R.string.apps_filter), Icons.Filled.FilterAlt, "apps-filter",
AppsView.FILTERS, AppsView.filter, { appsFilterLabel(it) }, AppsView::setFilter,
)
@Composable
private fun AppsSortButton() = HeaderChoiceButton(
stringResource(R.string.stores_sort), Icons.Filled.Sort, "apps-sort",
AppsView.SORTS, AppsView.sort, { appsSortLabel(it) }, AppsView::setSort,
)
@Composable
private fun HeaderChoiceButton(
title: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String,
options: List<String>, current: String, label: @Composable (String) -> String, onPick: (Context, String) -> Unit,
) {
val pal = LocalPalette.current
val ctx = LocalContext.current
var at by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
HeaderIconButton("$title · ${label(current)}", icon, key) {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = options.size,
handle = { Icon(icon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
) {
StepTitle(title)
StepList {
options.forEachIndexed { i, option ->
StepChoice(
label(option), selected = option == current, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (option == current) Modifier.focusRequester(first) else Modifier),
) {
onPick(ctx, option)
Steps.fold()
}
}
}
})
}
}
}
@Composable
private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scope = rememberCoroutineScope()
val firstAt = remember(entries) {
val map = LinkedHashMap<String, Int>()
entries.forEachIndexed { i, e -> map.putIfAbsent(indexLetter(e.label), i) }
map
}
val letters = remember(firstAt) { firstAt.keys.toList() }
var dragging by remember { mutableStateOf<String?>(null) }
val current by remember(entries, leadItems) {
derivedStateOf {
val i = (grid.firstVisibleItemIndex - leadItems).coerceIn(0, (entries.size - 1).coerceAtLeast(0))
entries.getOrNull(i)?.let { indexLetter(it.label) }
}
}
var height by remember { mutableIntStateOf(1) }
val jump: (Float) -> Unit = { y ->
val i = ((y / height) * letters.size).toInt().coerceIn(0, letters.size - 1)
val letter = letters[i]
if (letter != dragging) {
dragging = letter
val at = firstAt[letter] ?: 0
scope.launch { grid.scrollToItem(if (at == 0) 0 else leadItems + at) }
}
}
Box(modifier.width(22.dp)) {
Column(
verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
.clip(RoundedCornerShape(11.dp))
.background(if (dragging != null) colors.surface.copy(alpha = 0.85f) else Color.Transparent)
.onSizeChanged { height = it.height.coerceAtLeast(1) }
.pointerInput(letters) {
awaitEachGesture {
val down = awaitFirstDown()
down.consume()
jump(down.position.y)
while (true) {
val event = awaitPointerEvent()
val c = event.changes.firstOrNull { it.id == down.id } ?: break
if (!c.pressed) break
c.consume()
jump(c.position.y)
}
dragging = null
}
},
) {
for (l in letters) {
val on = l == (dragging ?: current)
Text(
l, fontSize = 10.sp, lineHeight = 11.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Medium,
color = if (on) pal.signal else colors.onSurfaceVariant, textAlign = TextAlign.Center,
)
}
}
dragging?.let { l ->
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.align(Alignment.Center).offset { IntOffset(-64.dp.roundToPx(), 0) }.size(56.dp)
.clip(CircleShape).background(pal.signal),
) { Text(l, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = pal.onPrimary) }
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TileFrame(
id: String, first: Boolean, onClick: () -> Unit, onMenu: () -> Unit,
content: @Composable (hot: Boolean) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.95f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "appScale")
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
.paneItem("tile:$id").then(if (first) Modifier.firstTile().paneEntry() else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(Shape12)
.background(if (hot) colors.surface else colors.surface.copy(alpha = 0.55f))
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
.hoverable(src)
.combinedClickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onLongClick = onMenu, onClick = onClick)
.controllerConfirm(onClick = onClick)
.menuKey(onMenu)
.padding(horizontal = 6.dp, vertical = 10.dp),
) { content(hot) }
}
@Composable
private fun TileLabel(text: String) = Text(
text, fontSize = 12.sp, lineHeight = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
)
@Composable
private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.Dp) {
val icon = app.icon
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(size))
else Box(Modifier.size(size).clip(CircleShape).background(artBrush(hueOf(app.label))))
}
@Composable
private fun AppTile(
app: HomeApp.LaunchableApp, folderId: String?, first: Boolean,
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
) {
var menu by remember { mutableStateOf(false) }
Box {
TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) {
AppIcon(app, 52.dp)
TileLabel(app.label)
}
AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder)
}
}
@Composable
private fun AppMenu(
app: HomeApp.LaunchableApp, folderId: String?, open: Boolean,
onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
) {
val ctx = LocalContext.current
var choosing by remember { mutableStateOf(false) }
var shortcuts by remember { mutableStateOf<List<Pair<ShortcutInfo, Bitmap?>>>(emptyList()) }
LaunchedEffect(open) {
if (!open) {
choosing = false
return@LaunchedEffect
}
shortcuts = withContext(Dispatchers.IO) {
HomeApp.shortcuts(ctx, app).map { it to HomeApp.shortcutIcon(ctx, it, 64) }
}
}
val isHidden = app.key in HomeHidden.keys
AnchoredMenu(open, onDismiss = onDismiss, title = app.label, compact = true, minWidth = 200.dp) { first ->
if (choosing) {
val others = HomeFolders.folders.filter { it.id != folderId }
var firstUsed = false
for (f in others) key(f.id) {
MenuItem(f.name, checked = false, focusRequester = if (!firstUsed) first.also { firstUsed = true } else null) {
HomeFolders.add(ctx, f.id, app.key)
onDismiss()
}
}
MenuItem(stringResource(R.string.apps_new_folder), checked = false, focusRequester = if (others.isEmpty()) first else null) {
onDismiss()
onNewFolder(app)
}
} else {
shortcuts.forEachIndexed { i, (info, icon) ->
key(info.id) {
MenuItem(
info.shortLabel?.toString().orEmpty(), checked = false,
focusRequester = if (i == 0) first else null,
leading = { MenuIcon(icon) },
) {
onDismiss()
runCatching { HomeApp.startShortcut(ctx, info) }
}
}
}
if (shortcuts.isNotEmpty()) Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(LocalPalette.current.line))
if (!isHidden) MenuItem(stringResource(R.string.apps_add_to_folder), checked = false, focusRequester = if (shortcuts.isEmpty()) first else null) { choosing = true }
if (folderId != null) MenuItem(stringResource(R.string.apps_remove_from_folder), checked = false) {
HomeFolders.remove(ctx, app.key)
onDismiss()
}
MenuItem(stringResource(if (isHidden) R.string.apps_unhide else R.string.apps_hide), checked = false,
focusRequester = if (isHidden && shortcuts.isEmpty()) first else null) {
onDismiss()
HomeHidden.set(ctx, app.key, !isHidden)
}
MenuItem(stringResource(R.string.apps_app_info), checked = false) {
onDismiss()
runCatching { HomeApp.openAppInfo(ctx, app) }
}
if (HomeApp.canUninstall(app)) MenuItem(stringResource(R.string.apps_uninstall), checked = false) {
onDismiss()
runCatching { HomeApp.uninstall(ctx, app) }
}
}
}
}
@Composable
private fun MenuIcon(icon: Bitmap?) {
if (icon != null) Image(icon.asImageBitmap(), null, modifier = Modifier.size(20.dp))
else Spacer(Modifier.size(20.dp))
}
@Composable
private fun PinnedTile(pinned: HomePins.Pinned, first: Boolean) {
val ctx = LocalContext.current
var menu by remember { mutableStateOf(false) }
Box {
TileFrame(pinned.key, first, onClick = { runCatching { HomeApp.startShortcut(ctx, pinned.info) } }, onMenu = { menu = true }) {
Box {
val icon = pinned.icon
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp))
else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label))))
}
TileLabel(pinned.label)
}
AnchoredMenu(menu, onDismiss = { menu = false }, title = pinned.label, compact = true, minWidth = 180.dp) { firstItem ->
MenuItem(stringResource(R.string.apps_shortcut_remove), checked = false, detail = pinned.appLabel, focusRequester = firstItem) {
menu = false
HomePins.unpin(ctx, pinned)
}
}
}
}
@Composable
private fun FolderIcon(apps: List<HomeApp.LaunchableApp>, size: androidx.compose.ui.unit.Dp) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val cell = (size - 14.dp) / 2
Box(
Modifier.size(size).clip(RoundedCornerShape(size / 3.5f)).background(colors.surfaceVariant)
.glideBorder(false, RoundedCornerShape(size / 3.5f), pal.signal, pal.line2)
.padding(5.dp),
) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
for (row in apps.take(4).chunked(2)) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
for (a in row) AppIcon(a, cell)
}
}
}
}
@Composable
private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Unit, onRename: () -> Unit) {
val ctx = LocalContext.current
var menu by remember { mutableStateOf(false) }
Box {
TileFrame(entry.key, first, onClick = onOpen, onMenu = { menu = true }) {
FolderIcon(entry.apps, 52.dp)
TileLabel(entry.folder.name)
}
AnchoredMenu(menu, onDismiss = { menu = false }, title = entry.folder.name, compact = true, minWidth = 160.dp) { firstItem ->
MenuItem(stringResource(R.string.apps_folder_rename), checked = false, focusRequester = firstItem) {
menu = false
onRename()
}
MenuItem(stringResource(R.string.apps_folder_ungroup), checked = false) {
menu = false
HomeFolders.delete(ctx, entry.folder.id)
}
}
}
}
@Composable
private fun FolderSheet(
folder: HomeFolders.Folder, apps: List<HomeApp.LaunchableApp>, renameFirst: Boolean,
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit,
) {
SwipeLock()
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var renaming by remember(folder.id) { mutableStateOf(renameFirst) }
var name by remember(folder.id) { mutableStateOf(if (renameFirst) "" else folder.name) }
val commit = {
val n = name.trim()
if (n.isNotEmpty() && n != folder.name) HomeFolders.rename(ctx, folder.id, n)
renaming = false
}
val close = { if (renaming) commit(); onClose() }
BackHandler { close() }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f))
.pointerInput(Unit) { awaitEachGesture { val d = awaitFirstDown(); d.consume(); close() } },
) {
val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true }
AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160)), exit = scaleOut(Motion.tw(140)) + fadeOut(Motion.tw(140))) {
Column(
modifier = Modifier.widthIn(max = 620.dp).fillMaxWidth(0.9f).heightIn(max = 520.dp)
.clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f))
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
.controllerBack(close)
.padding(16.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) {
if (renaming) Box(Modifier.weight(1f)) {
AdbTextField(
value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name),
keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false,
placeholder = folder.name, focusOnShow = true, onDone = { commit() },
)
} else {
Text(folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
SmallIconButton(Icons.Filled.Edit, stringResource(R.string.apps_folder_rename), tint = colors.onSurfaceVariant) { renaming = true }
Spacer(Modifier.weight(1f))
}
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant) { close() }
}
LazyVerticalGrid(
columns = GridCells.Adaptive(92.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(apps, key = { it.key }) { app ->
AppTile(app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder)
}
}
}
}
}
}
@Composable
private fun WidgetCard(w: HomeWidgets.Placed, maxWidthDp: Int) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var menu by remember { mutableStateOf(false) }
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val width = w.widthDp.coerceAtMost(maxWidthDp)
val activity = remember(ctx) { ctx.findActivity() }
Box {
Box(
Modifier.size(width.dp, w.heightDp.dp)
.clip(Shape16)
.background(colors.surface.copy(alpha = 0.35f))
.glideBorder(hot || menu, Shape16, pal.signal)
.hoverable(src).focusable(interactionSource = src)
.controllerConfirm { menu = true }
.menuKey { menu = true },
) {
AndroidView(
factory = { c ->
(HomeWidgets.createView(c, w.id) ?: android.view.View(c)).apply {
val radius = 16 * c.resources.displayMetrics.density
outlineProvider = object : android.view.ViewOutlineProvider() {
override fun getOutline(view: android.view.View, outline: android.graphics.Outline) =
outline.setRoundRect(0, 0, view.width, view.height, radius)
}
clipToOutline = true
}
},
update = { v ->
if (v is HomeWidgets.HomeWidgetView) {
v.onLongPress = { menu = true }
HomeWidgets.applySize(v, width, w.heightDp)
}
},
modifier = Modifier.fillMaxSize(),
)
}
val (minW, minH) = remember(w.id) { HomeWidgets.minSize(ctx, w.id) }
val index = HomeWidgets.widgets.indexOfFirst { it.id == w.id }
val label = remember(w.id) { HomeWidgets.info(ctx, w.id)?.loadLabel(ctx.packageManager) ?: "" }
AnchoredMenu(menu, onDismiss = { menu = false }, title = label, compact = true, minWidth = 180.dp) { first ->
val step = 48
MenuItem(stringResource(R.string.apps_widget_wider), checked = false, enabled = width < maxWidthDp, focusRequester = first) {
HomeWidgets.resize(ctx, w.id, (width + step).coerceAtMost(maxWidthDp), w.heightDp)
}
MenuItem(stringResource(R.string.apps_widget_narrower), checked = false, enabled = width > minW) {
HomeWidgets.resize(ctx, w.id, (width - step).coerceAtLeast(minW), w.heightDp)
}
MenuItem(stringResource(R.string.apps_widget_taller), checked = false, enabled = w.heightDp < 480) {
HomeWidgets.resize(ctx, w.id, width, (w.heightDp + step).coerceAtMost(480))
}
MenuItem(stringResource(R.string.apps_widget_shorter), checked = false, enabled = w.heightDp > minH) {
HomeWidgets.resize(ctx, w.id, width, (w.heightDp - step).coerceAtLeast(minH))
}
if (index > 0) MenuItem(stringResource(R.string.apps_widget_move_earlier), checked = false) { HomeWidgets.move(ctx, w.id, -1) }
if (index in 0 until HomeWidgets.widgets.size - 1) MenuItem(stringResource(R.string.apps_widget_move_later), checked = false) { HomeWidgets.move(ctx, w.id, 1) }
if (activity != null && HomeWidgets.canReconfigure(ctx, w.id)) MenuItem(stringResource(R.string.apps_widget_configure), checked = false) {
menu = false
HomeWidgets.reconfigure(activity, w.id)
}
MenuItem(stringResource(R.string.apps_widget_remove), checked = false) {
menu = false
HomeWidgets.remove(ctx, w.id)
}
}
}
}
@Composable
private fun WidgetPicker(padH: androidx.compose.ui.unit.Dp, onClose: () -> Unit) {
SwipeLock()
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val activity = remember(ctx) { ctx.findActivity() }
BackHandler { onClose() }
val providers = HomeWidgets.providers
Column(Modifier.fillMaxSize().background(colors.background).pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false) } }) {
LazyVerticalGrid(
columns = GridCells.Adaptive(150.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(horizontal = padH, vertical = 14.dp),
modifier = Modifier.fillMaxSize(),
) {
item(key = "back", span = { GridItemSpan(maxLineSpan) }) {
Column {
Box(Modifier.padding(bottom = 10.dp)) { BackLink(stringResource(R.string.rail_apps), compact = true, onClick = onClose) }
PageHeader(stringResource(R.string.apps_add_widget)) {
if (providers != null) Chip(providers.size.toString(), ok = false)
}
}
}
when {
providers == null -> item(key = "loading", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_loading)) }
providers.isEmpty() -> item(key = "none", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_none)) }
else -> items(providers, key = { it.info.provider.flattenToString() }) { p ->
ProviderCard(p, first = p === providers.first()) {
onClose()
if (activity != null) HomeWidgets.add(activity, p)
}
}
}
}
}
}
@Composable
private fun ProviderCard(p: HomeWidgets.Provider, first: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Column(
modifier = Modifier.fillMaxWidth().paneItem("widget:" + p.info.provider.flattenToString()).then(if (first) Modifier.firstTile() else Modifier)
.clip(Shape12).background(colors.surface)
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick),
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxWidth().aspectRatio(1.6f).background(colors.surfaceVariant).padding(10.dp),
) {
val preview = p.preview
if (preview != null) Image(preview.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())
}
Column(Modifier.padding(horizontal = 10.dp, vertical = 8.dp)) {
Text(p.label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val cells = "${(p.widthDp / 80f).roundToInt().coerceAtLeast(1)} × ${(p.heightDp / 80f).roundToInt().coerceAtLeast(1)}"
Text(if (p.appLabel == p.label) cells else "${p.appLabel} · $cells", fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
@Composable
fun PinRequestPrompt(label: String, appLabel: String, icon: Bitmap?, wide: Boolean, onAdd: () -> Unit, onCancel: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
BackHandler { onCancel() }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f))
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); onCancel() } },
) {
val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true }
AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160))) {
Column(
verticalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.widthIn(min = 280.dp, max = 420.dp)
.clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f))
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
.controllerBack(onCancel)
.padding(18.dp),
) {
Text(
stringResource(R.string.apps_pin_title).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
letterSpacing = 1.5.sp, color = colors.onSurfaceVariant,
)
if (wide && icon != null) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxWidth().heightIn(max = 180.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface).padding(10.dp),
) { Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxWidth()) }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
if (!wide) {
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp))
else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(label))))
}
Column(Modifier.weight(1f)) {
Text(label, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(appLabel, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
SecondaryButton(stringResource(R.string.common_cancel), onClick = onCancel)
PrimaryButton(stringResource(R.string.apps_pin_add), onClick = onAdd)
}
}
}
}
}
@@ -699,7 +699,7 @@ fun ComponentsPage(
Box(Modifier.fillMaxSize().onGloballyPositioned { pageAt = it.positionInRoot() }.onFocusChanged { pageFocused = it.hasFocus }) {
Column(
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp).padding(top = if (narrow) 12.dp else 18.dp)
.then(if (selectedGame == null) Modifier.bumpers(
onPrevious = { pick(layerStep(layer, -1)) },
onNext = { pick(layerStep(layer, 1)) },
@@ -972,7 +972,7 @@ private fun Stack(
onFocus = { onFocus(l) }, onClick = { onOpen(l) },
)
}
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
StackHeading(stringResource(R.string.comp_this_device))
card(GPU_TAB)
Spacer(Modifier.height(6.dp))
@@ -10,6 +10,8 @@ import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.snap
import androidx.compose.animation.core.tween
import androidx.compose.animation.scaleIn
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.scaleOut
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.rememberUpdatedState
@@ -105,7 +107,7 @@ import java.io.File
internal fun Pane(
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
) {
BoxWithConstraints(modifier = modifier) {
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
@@ -138,12 +140,19 @@ internal fun Pane(
before[0] = target
val targetNow by rememberUpdatedState(target)
val leave = if (Hops.linking) PageLeave.Link else PageLeave.Ordinary
LaunchedEffect(target) { Hops.linking = false }
LaunchedEffect(target) {
Hops.linking = false
PageSwipe.direction = 0
}
AnimatedContent(
targetState = target,
modifier = Modifier.onGloballyPositioned { paneAt[0] = it.positionInRoot() },
transitionSpec = {
val swipe = PageSwipe.direction
when {
swipe != 0 -> (fadeIn(Motion.tw(260, 40)) + slideInHorizontally(Motion.tw(360)) { it * swipe / 8 })
.togetherWith(fadeOut(Motion.tw(160)) + slideOutHorizontally(Motion.tw(220)) { -it * swipe / 8 })
.apply { targetContentZIndex = 1f }
targetState in origins -> (fadeIn(Motion.tw(120)))
.togetherWith(fadeOut(Motion.tw(320, 80)) + scaleOut(Motion.tw(480), targetScale = 0.95f))
.apply { targetContentZIndex = 1f }
@@ -162,7 +171,7 @@ internal fun Pane(
label = "pane",
) { key ->
val drawn = (if (page != null && key == s.pageKey) page else pages[key])
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb) }
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) }
val hopSink by androidx.compose.animation.core.animateFloatAsState(
if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink",
)
@@ -223,7 +232,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, L
private fun Content(
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
@@ -232,13 +241,13 @@ private fun Content(
val padH = if (narrow) 16.dp else 22.dp
val padV = if (narrow) 12.dp else 18.dp
if (selected == "setup") {
Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) {
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
Column(modifier = modifier.padding(horizontal = padH).padding(top = padV)) {
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging)
}
return
}
if (selected == "updates") {
UpdatesPage(s, a, modifier.padding(horizontal = padH, vertical = padV))
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
return
}
if (selected == "steam") {
@@ -261,24 +270,12 @@ private fun Content(
DesktopPage(s, a, modifier, onSelect)
return
}
if (selected == "android-apps" && s.isHomeApp) {
AndroidAppsPage(s, modifier, onAndroidAppClick)
return
}
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
when {
selected == "android-apps" && s.isHomeApp -> {
Rise(0) { PageHeader(stringResource(R.string.content_android_apps)) { Chip(stringResource(R.string.content_apps_count, s.androidApps.size), ok = false) } }
if (s.androidApps.isEmpty()) Rise(3) { Note(stringResource(R.string.content_no_android_apps)) }
else Rise(3, Modifier.fillMaxWidth()) {
ArtGrid(s.androidApps.map { app ->
Tile(
app.label,
null,
null,
"android:${app.packageName}",
onClick = { onAndroidAppClick(app) },
iconBitmap = app.icon,
)
})
}
}
selected.startsWith("user:") -> {
val app = UserAppsState.items.firstOrNull { "user:${it.key}" == selected }
if (app == null) Note(stringResource(R.string.user_apps_gone)) else UserAppPage(app, s, a, onSelect)
@@ -84,7 +84,9 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.layout.boundsInParent
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onPlaced
import com.droiddeck.launcher.core.PhantomProcessLimit
@@ -99,15 +101,15 @@ internal fun BottomBar(
val keys = navigationKeys(s)
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
var barAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
val content = remember { arrayOfNulls<LayoutCoordinates>(1) }
Row(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface), verticalAlignment = Alignment.CenterVertically) {
BoxWithConstraints(Modifier.weight(1f)) {
val itemWidth = (maxWidth / keys.size).coerceIn(56.dp, 88.dp)
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onGloballyPositioned { barAt = it.boundsInRoot().topLeft }) {
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-barAt), tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f)
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onPlaced { content[0] = it }) {
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f)
Row(Modifier.selectableGroup().padding(vertical = 4.dp), horizontalArrangement = Arrangement.Center) {
NavigationItems(s, shown, compact = true, iconOnly = false, height = 56.dp, width = itemWidth,
place = { key -> Modifier.onGloballyPositioned { bounds[key] = it.boundsInRoot(); Hops.railBounds[key] = it.boundsInRoot() } },
place = { key -> Modifier.onGloballyPositioned { item -> content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }; Hops.railBounds[key] = item.boundsInRoot() } },
onSelect = onSelect, onFocusSelect = onFocusSelect)
}
}
@@ -116,7 +118,7 @@ internal fun BottomBar(
}
}
private fun navigationKeys(s: FrontEndState) = buildList {
internal fun navigationKeys(s: FrontEndState) = buildList {
add("steam"); add("games")
if (s.gameStoresEnabled) add("stores")
add("desktop"); add("components")
@@ -143,18 +145,18 @@ internal fun SideRail(
val keys = navigationKeys(s)
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
var railAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onGloballyPositioned { railAt = it.boundsInRoot().topLeft }) {
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-railAt), tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
val content = remember { arrayOfNulls<LayoutCoordinates>(1) }
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onPlaced { content[0] = it }) {
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.fillMaxWidth().selectableGroup(),
) {
val place: (String) -> Modifier = { key ->
Modifier.onGloballyPositioned {
bounds[key] = it.boundsInRoot()
Hops.railBounds[key] = it.boundsInRoot()
Modifier.onGloballyPositioned { item ->
content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }
Hops.railBounds[key] = item.boundsInRoot()
}
}
NavigationItems(s, shown, compact, iconOnly, fit, if (iconOnly) 52.dp else 80.dp, place, onSelect, onFocusSelect)
@@ -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 = {},
@@ -255,6 +258,8 @@ class FrontEndActions(
val onCopyPhantomCommand: (Boolean) -> Unit = {},
val onDismissPhantomGate: () -> Unit = {},
val onStartWirelessAdbPairing: () -> Unit = {},
val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false },
val onShowPhantomGate: () -> Unit = {},
val onOpenNotificationSettings: () -> Unit = {},
val controller: ControllerActions? = null,
val updates: UpdatesActions = UpdatesActions(),
@@ -425,6 +430,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
var developerChoiceToggle by rememberSaveable { mutableStateOf(false) }
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
val colors = MaterialTheme.colorScheme
@@ -433,9 +440,49 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
val requestDeveloperOptions = {
developerChoiceGuided = false
developerChoiceToggle = false
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
else showDeveloperDisplayChoice = true
}
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
if (developerChoiceGuided) a.onStartWirelessAdbPairing()
val guided = developerChoiceGuided || developerChoiceToggle
if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId)
developerChoiceGuided = false
developerChoiceToggle = false
}
val requestChildProcessToggle = {
if (!PhantomProcessLimit.hasDeveloperToggle() || com.droiddeck.launcher.core.GlobalSettings.developerOptionsOn(ctx)) {
requestDeveloperOptions()
} else {
developerChoiceGuided = false
developerChoiceToggle = true
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
else showDeveloperDisplayChoice = true
}
}
val startGuidedPairing = {
if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) {
wirelessAdbDesiredEnabled = false
showWirelessAdbFix = true
} else {
developerChoiceGuided = true
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
else showDeveloperDisplayChoice = true
}
}
var applyingSavedPairing by remember { mutableStateOf(false) }
val fixPhantomLimit = {
if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing()
else if (!applyingSavedPairing) {
applyingSavedPairing = true
a.onSetPhantomProcessLimit(false) { error ->
applyingSavedPairing = false
if (error != null) startGuidedPairing()
}
}
}
val requestWirelessAdbFix: (Boolean) -> Unit = { enabled ->
wirelessAdbDesiredEnabled = enabled
showWirelessAdbFix = true
@@ -477,6 +524,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop"
else -> s.pageKey ?: selected
}
val railSelectionNow = androidx.compose.runtime.rememberUpdatedState(railSelection)
var railPicks by remember { mutableStateOf(0) }
val showRailPage: (String, Boolean) -> Unit = { key, focusContent ->
if (key == "components") a.onComponents(focusContent)
@@ -579,13 +627,23 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
},
) {
Pane(
s, selected, a, page, Modifier.fillMaxSize().then(paneFocus), { selected = it },
s, selected, a, page,
Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }) { dir ->
val keys = navigationKeys(s)
val at = keys.indexOf(railSelectionNow.value)
if (at >= 0) keys.getOrNull(at + dir)?.let { key ->
PageSwipe.direction = dir
showRailPage(key, false)
}
},
{ selected = it },
onAndroidAppClick = { app ->
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
else appToChooseDisplay = app
},
onOpenDeveloperOptions = requestDeveloperOptions,
onOpenDeveloperOptions = requestChildProcessToggle,
onRequestWirelessAdb = requestWirelessAdbFix,
onPairWirelessDebugging = startGuidedPairing,
)
}
@@ -618,11 +676,9 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
PhantomProcessGatePage(
status = s.phantomProcessStatus,
onDismiss = a.onDismissPhantomGate,
onOpenDeveloperOptions = requestDeveloperOptions,
onFixWithWirelessDebugging = {
a.onStartWirelessAdbPairing()
requestDeveloperOptions()
},
onOpenDeveloperOptions = requestChildProcessToggle,
applyingSavedPairing = applyingSavedPairing,
onFixWithWirelessDebugging = fixPhantomLimit,
onEnterAddressManually = { requestWirelessAdbFix(false) },
onCopyCommand = { a.onCopyPhantomCommand(false) },
onOpenNotificationSettings = a.onOpenNotificationSettings,
@@ -648,13 +704,17 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
},
onMainScreen = {
showDeveloperDisplayChoice = false
a.onOpenDeveloperOptions(null)
openDeveloperOptionsOn(null)
},
onSecondaryScreen = { displayId ->
showDeveloperDisplayChoice = false
a.onOpenDeveloperOptions(displayId)
openDeveloperOptionsOn(displayId)
},
onDismiss = {
showDeveloperDisplayChoice = false
developerChoiceGuided = false
developerChoiceToggle = false
},
onDismiss = { showDeveloperDisplayChoice = false },
)
}
}
@@ -141,6 +141,7 @@ internal fun SetupPanel(
a: FrontEndActions,
onOpenDeveloperOptions: () -> Unit,
onRequestWirelessAdb: (Boolean) -> Unit,
onPairWirelessDebugging: () -> Unit,
) {
val host = rememberMenuHost()
val ctx = LocalContext.current
@@ -203,6 +204,12 @@ internal fun SetupPanel(
tab = STORAGE_TAB
}
}
LaunchedEffect(Unit) {
while (true) {
kotlinx.coroutines.delay(2_000)
a.onRefreshPhantomStatus()
}
}
LaunchedEffect(tab) {
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
androidx.compose.runtime.withFrameNanos { }
@@ -279,7 +286,7 @@ internal fun SetupPanel(
},
divider = divider && !showLimitDetails,
) {
if (limitBlocks) PrimaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_fix_it), compact = true) { showLimitDetails = !showLimitDetails }
if (limitBlocks) PrimaryButton(stringResource(R.string.setup_fix_it), compact = true, onClick = a.onShowPhantomGate)
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
SecondaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_details), compact = true) { showLimitDetails = !showLimitDetails }
}
@@ -292,11 +299,7 @@ internal fun SetupPanel(
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
)
Actions {
if (limitBlocks) {
PrimaryButton(stringResource(R.string.setup_dev_options), compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton(stringResource(R.string.setup_use_wireless), compact = true, enabled = !processLimitBusy) { setProcessLimit(false) }
SecondaryButton(stringResource(R.string.setup_check_again), compact = true, onClick = a.onRefreshPhantomStatus)
} else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
SecondaryButton(stringResource(R.string.setup_limit_turn_on), compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
}
}
@@ -472,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,
@@ -509,7 +518,7 @@ internal fun SetupPanel(
)
if (!s.adbPaired) ActionRow(
stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint),
stringResource(R.string.setup_adb_pair_button), { onRequestWirelessAdb(false) },
stringResource(R.string.setup_adb_pair_button), onPairWirelessDebugging,
)
}
}
@@ -90,6 +90,7 @@ import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.xbox.XboxBackend
import com.droiddeck.launcher.stores.xbox.XboxCloudGames
@@ -205,7 +206,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)
@@ -346,7 +352,7 @@ internal fun GameActions(
val gone = storeKey?.let { StoresState.uninstalling[it] }
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
PrimaryButton(
stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && !xboxBusy,
stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
) {
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(ctx, store, id, s, a)
@@ -357,25 +363,19 @@ internal fun GameActions(
GameShortcutMenu(game, a)
EditArtButton(game)
}
if (store == Store.ITCH && installed != null && StoreMaintenance.adapter(installed) == null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
if (store != Store.GOG && installed != null && installed.key !in StoresState.uninstalling && StoreMaintenance.adapter(installed) != null) StoreMaintenanceActions(installed)
if (store == null && game != null && game.source == Library.SOURCE_STEAM && game.appId > 0) SteamClientMaintenanceActions(a, s.sessionRunning)
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)) {
if (StoreMaintenance.adapter(installed) == null) SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
runCatching { XboxBackend.update(ctx, installed) }
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) }
}
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
}
if (store == Store.BATTLENET) {
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
ActionChip(downloadLabel(download), ok = false)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
}
}
if (store == Store.BATTLENET && installed == null) {
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
}
@@ -529,7 +529,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,188 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.background
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.gog.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
internal fun GogMaintenanceActions(game: InstalledStoreGame) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) }
var patches by remember { mutableStateOf<List<GogOfflineDownload>?>(null) }
var proposal by remember { mutableStateOf<GogMaintenance.Proposal?>(null) }
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
var recoverablePatch by remember { mutableStateOf(false) }
val key = "gog:${game.sidecar.id}"
val download = com.droiddeck.launcher.stores.StoresState.download(key)
val active = download?.isActive == true
val check = GogMaintenance.checks[game.sidecar.id]
LaunchedEffect(game.folder.path) { GogMaintenance.check(ctx, game) }
LaunchedEffect(menu, active) {
if (menu) {
recoverablePatch = false
val result = withContext(Dispatchers.IO) { runCatching {
GogFiles.read(GogFiles.journal(game.folder))?.let {
it.optString("operation") == GogOperation.PATCH.name && it.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain")
} == true
} }
result.onSuccess { recoverablePatch = it }.onFailure { error = it.message }
}
}
fun prepare(operation: GogOperation, patch: GogOfflineDownload? = null) {
menu = false; patches = null; busy = true; error = null
scope.launch {
runCatching { withContext(Dispatchers.IO) { GogMaintenance.prepare(ctx, game, operation, patch) } }
.onSuccess { proposal = it }.onFailure { error = it.message }
busy = false
}
}
if (active) {
ActionChip(downloadLabel(download!!), ok = false)
if (download.interruptible) {
SecondaryButton(stringResource(if (download.state == DownloadState.PAUSED) R.string.stores_dl_resume else R.string.stores_dl_pause)) {
if (download.state == DownloadState.PAUSED) DownloadQueue.resume(ctx, key) else DownloadQueue.pause(key)
}
} else Text(stringResource(R.string.gog_patch_in_session), color = MaterialTheme.colorScheme.onSurfaceVariant)
} else if (!game.sidecar.isInstalled || GogFiles.journal(game.folder).exists()) {
SecondaryButton(stringResource(R.string.gog_resume), modifier = Modifier.testTag("gog-resume")) {
busy = true
scope.launch {
runCatching {
withContext(Dispatchers.IO) {
GogMaintenance.resume(ctx, game)
}
}.onSuccess { proposal = it }.onFailure { error = it.message }
busy = false
}
}
} else if (check?.state == GogMaintenance.State.AVAILABLE) {
SecondaryButton(stringResource(R.string.gog_update, check.version.ifBlank { game.sidecar.title }), enabled = !busy, modifier = Modifier.testTag("gog-update")) { prepare(GogOperation.UPDATE) }
}
androidx.compose.foundation.layout.Box {
SecondaryButton(stringResource(if (busy) R.string.common_checking else R.string.gog_maintenance), enabled = !busy && !active, modifier = Modifier.testTag("gog-maintenance")) { menu = !menu }
AnchoredMenu(menu, { menu = false }, title = stringResource(R.string.gog_maintenance), compact = true) { first ->
MenuItem(stringResource(R.string.common_update), checked = false) { prepare(GogOperation.UPDATE) }
MenuItem(stringResource(R.string.gog_check), checked = false, focusRequester = first) { menu = false; GogMaintenance.check(ctx, game, true) }
MenuItem(stringResource(R.string.gog_repair), checked = false, modifier = Modifier.testTag("gog-repair")) { prepare(GogOperation.REPAIR) }
MenuItem(stringResource(R.string.gog_patches), checked = false, modifier = Modifier.testTag("gog-patches")) {
menu = false; busy = true
scope.launch {
runCatching { withContext(Dispatchers.IO) { GogMaintenance.offlinePatches(ctx, game) } }
.onSuccess { patches = it }.onFailure { error = it.message }
busy = false
}
}
MenuItem(stringResource(R.string.gog_refresh), checked = false) { prepare(GogOperation.REFRESH) }
if (recoverablePatch) MenuItem(stringResource(R.string.gog_recover), checked = false, modifier = Modifier.testTag("gog-recover")) {
menu = false; busy = true
scope.launch {
runCatching { withContext(Dispatchers.IO) { GogMaintenance.recoverPatch(ctx, game) } }.onFailure { error = it.message }
busy = false
}
}
}
}
if (check?.state == GogMaintenance.State.FAILED || check?.state == GogMaintenance.State.UNKNOWN) {
if (check.reason.isNotBlank()) Text(check.reason, fontSize = 12.sp, color = colors.onSurfaceVariant)
}
patches?.let { list ->
val shown = rememberShown { patches = null }
val close = { shown.targetState = false }
AppDialog(shown, close, "gogPatches", wide = false, maxWidth = 460.dp) {
DialogTitleRow(stringResource(R.string.gog_patches), close)
Text(game.sidecar.title, fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(stringResource(R.string.gog_patch_requirements), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
if (list.isEmpty()) Text(stringResource(R.string.gog_no_patches), fontSize = 13.sp, color = colors.onSurfaceVariant)
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
list.forEach { patch ->
ListRow(onClick = { close(); prepare(GogOperation.PATCH, patch) }) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(patch.name, fontSize = 13.sp, lineHeight = 18.sp, fontWeight = FontWeight.Medium, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(listOf(StoreLanguage.displayName(patch.language).ifBlank { patch.language }, patch.version, formatBytes(patch.size)).filter { it.isNotBlank() }.joinToString(" · "),
fontSize = 11.sp, lineHeight = 15.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text(stringResource(R.string.gog_select_patch), fontSize = 12.sp, color = LocalPalette.current.signal)
}
}
}
SecondaryButton(stringResource(R.string.gog_refresh)) { prepare(GogOperation.REFRESH) }
}
}
proposal?.let { selected ->
val shown = rememberShown { proposal = null }
val close = { shown.targetState = false }
val action = when (selected.operation) {
GogOperation.UPDATE -> R.string.common_update
GogOperation.REPAIR -> R.string.gog_repair_action
GogOperation.PATCH -> R.string.gog_open_patch
GogOperation.REFRESH -> R.string.gog_refresh_action
}
AppDialog(shown, close, "gogMaintenance", wide = false, maxWidth = 460.dp) {
DialogTitleRow(stringResource(action), close)
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(listOf(game.sidecar.title, selected.before.version).filter { it.isNotBlank() }.joinToString(" · "), fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (selected.operation != GogOperation.REPAIR) Text(selected.patch?.name ?: selected.target.version.ifBlank { selected.target.build }, fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.SemiBold,
color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
Row(horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface.copy(alpha = 0.65f)).padding(12.dp)) {
GogMetric(stringResource(R.string.gog_download_label), formatBytes(selected.downloadBytes), Modifier.weight(1f))
GogMetric(stringResource(if (selected.operation == GogOperation.PATCH || selected.operation == GogOperation.REFRESH) R.string.gog_space_estimate_label else R.string.gog_space_label),
formatBytes(selected.diskBytes), Modifier.weight(1f))
}
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(stringResource(R.string.gog_managed_files), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
if (selected.fullFiles) Text(stringResource(R.string.gog_full_files), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
if (selected.operation == GogOperation.PATCH) Text(stringResource(R.string.gog_patch_installer_note), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
PrimaryButton(stringResource(action), enabled = !busy, modifier = Modifier.testTag("gog-apply")) {
busy = true
close()
scope.launch {
runCatching { withContext(Dispatchers.IO) { GogMaintenance.enqueue(ctx, game, selected) } }.onFailure { error = it.message }
busy = false
}
}
SecondaryButton(stringResource(R.string.common_cancel), onClick = close)
}
}
}
error?.let { Text(it, fontSize = 12.sp, color = colors.error) }
}
@Composable
private fun GogMetric(label: String, value: String, modifier: Modifier) {
Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(label, fontSize = 11.sp, lineHeight = 15.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(value, fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
}
}
@@ -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,10 @@ 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.gog.GogMaintenance
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import com.droiddeck.launcher.stores.retainOrder
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
import com.droiddeck.launcher.stores.sortGames
@@ -194,7 +198,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 {
@@ -304,12 +311,12 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
open, detailScroll,
gridScrolled = { grid.firstVisibleItemIndex > 0 || grid.firstVisibleItemScrollOffset > 0 },
onDetailFocus = { detailFocused = it },
modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp),
modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp).padding(top = if (narrow) 10.dp else 14.dp),
wrap = { key, content -> StoreTheme(GameRef.parse(key).let { r -> r.store ?: r.game(s.steamGames)?.source?.let { Store.byId(it) } }) { content() } },
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,12 +589,17 @@ 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 && libraryUpdateAvailable(e)) 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))
}
}
}
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available } == true ||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE ||
e.storeKey?.let { StoreMaintenance.checks[it]?.state == MaintenanceCheckState.AVAILABLE } == true
@Composable
private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, choose: (() -> Unit)?, onOpen: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -608,6 +620,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch
val size = if (e.installed && folder != null) diskSize(inst, folder) else e.item?.let { StoreSizes.size(it) }?.takeIf { it > 0 }
val status = when {
download != null -> downloadLabel(download)
e.installed && libraryUpdateAvailable(e) -> stringResource(R.string.common_update)
!e.installed -> stringResource(R.string.stores_section_not_installed)
e.game != null -> playedSpan(e.game.lastPlayed)?.replaceFirstChar { it.uppercase() } ?: stringResource(R.string.games_never_played)
else -> stringResource(R.string.stores_installed_chip)
@@ -638,7 +651,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch
}
@Composable
private fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) {
internal fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
@@ -655,7 +668,7 @@ private fun HeaderIconButton(description: String, icon: androidx.compose.ui.grap
/** Choosing Library in the rail lands on the first game, as Play Steam does on the Steam page. */
@Composable
private fun Modifier.paneEntry(): Modifier {
internal fun Modifier.paneEntry(): Modifier {
val ff = LocalFrontFocus.current ?: return this
androidx.compose.runtime.DisposableEffect(ff) {
ff.primaryAttached++
@@ -0,0 +1,60 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.input.pointer.util.addPointerInputChange
import androidx.compose.ui.unit.dp
import kotlin.math.abs
internal object PageSwipe {
var locks by mutableIntStateOf(0)
var direction by mutableIntStateOf(0)
}
// Runs on the Final pass so carousels, sliders, scrollers and widgets that consumed the drag keep it.
@Composable
internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): Modifier {
val enabledNow by rememberUpdatedState(enabled)
val onSwipeNow by rememberUpdatedState(onSwipe)
return pointerInput(Unit) {
val distance = 72.dp.toPx()
val flingDistance = 32.dp.toPx()
val flingVelocity = 900.dp.toPx()
val slop = viewConfiguration.touchSlop
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Final)
if (!enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture
val tracker = VelocityTracker()
tracker.addPointerInputChange(down)
var total = Offset.Zero
var mine = false
while (true) {
val event = awaitPointerEvent(PointerEventPass.Final)
if (event.changes.size > 1) return@awaitEachGesture
val change = event.changes.firstOrNull { it.id == down.id } ?: return@awaitEachGesture
if (!change.pressed) break
if (!mine && change.isConsumed) return@awaitEachGesture
total += change.position - change.previousPosition
tracker.addPointerInputChange(change)
if (!mine && abs(total.x) > slop && abs(total.x) > abs(total.y) * 2f) mine = true
if (mine) change.consume()
}
if (!mine || PageSwipe.locks > 0) return@awaitEachGesture
val vx = tracker.calculateVelocity().x
val horizontal = abs(total.x) > abs(total.y) * 1.5f
val far = abs(total.x) > distance
val flung = abs(total.x) > flingDistance && abs(vx) > flingVelocity && (vx > 0) == (total.x > 0)
if (horizontal && (far || flung)) onSwipeNow(if (total.x < 0) 1 else -1)
}
}
}
@@ -45,6 +45,7 @@ import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
@Composable
fun PhantomProcessGatePage(
status: PhantomProcessStatus,
applyingSavedPairing: Boolean,
onDismiss: () -> Unit,
onOpenDeveloperOptions: () -> Unit,
onFixWithWirelessDebugging: () -> Unit,
@@ -77,7 +78,7 @@ fun PhantomProcessGatePage(
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 620.dp
val fix: @Composable ColumnScope.() -> Unit = {
FixGroup(hasToggle, stage, environment, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging,
FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging,
onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) })
}
val side: @Composable ColumnScope.() -> Unit = {
@@ -119,6 +120,7 @@ private fun FixGroup(
stage: Stage,
environment: GateEnvironment,
compact: Boolean,
applyingSavedPairing: Boolean,
onOpenDeveloperOptions: () -> Unit,
onFixWithWirelessDebugging: () -> Unit,
onOpenNotificationSettings: () -> Unit,
@@ -131,6 +133,10 @@ private fun FixGroup(
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
when {
applyingSavedPairing -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
Body(stringResource(R.string.adbpair_applying))
}
pairing -> PairingProgress(stage, onCancel)
hasToggle -> {
Body(stringResource(R.string.gate_toggle_steps))
@@ -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)),
@@ -0,0 +1,221 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
import com.droiddeck.launcher.stores.maintenance.RecoveryState
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
internal fun SteamClientMaintenanceActions(actions: FrontEndActions, sessionRunning: Boolean) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (sessionRunning) SecondaryButton("Open Steam downloads", modifier = Modifier.testTag("steam-downloads")) {
actions.onSteamUrl("steam://open/downloads")
} else SecondaryButton("Start Steam", modifier = Modifier.testTag("steam-start")) { actions.onPlay() }
}
Text("In Steam, open this game’s Properties → Installed Files → Verify integrity.",
fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@Composable
internal fun StoreMaintenanceActions(game: InstalledStoreGame) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val adapter = StoreMaintenance.adapter(game) ?: return
val capabilities = adapter.capabilities(game)
val check = StoreMaintenance.checks[game.key]
val key = game.key
val download = StoresState.download(key)
val active = download?.isActive == true
var busy by remember(key) { mutableStateOf(false) }
var error by remember(key) { mutableStateOf<String?>(null) }
var proposal by remember(key) { mutableStateOf<MaintenanceProposal?>(null) }
var recovery by remember(key) { mutableStateOf(MaintenanceRecovery()) }
var menu by remember(key) { mutableStateOf(false) }
LaunchedEffect(game.folder.path) { StoreMaintenance.check(context, game) }
LaunchedEffect(game.folder.path, active, download?.state) {
recovery = withContext(Dispatchers.IO) { StoreMaintenance.recovery(context, game) }
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
if (active) {
ActionChip(downloadLabel(download!!), ok = false)
if (download.interruptible) SecondaryButton(
stringResource(if (download.state == com.droiddeck.launcher.stores.download.DownloadState.PAUSED) com.droiddeck.launcher.R.string.stores_dl_resume else com.droiddeck.launcher.R.string.stores_dl_pause),
) {
if (download.state == com.droiddeck.launcher.stores.download.DownloadState.PAUSED) DownloadQueue.resume(context, key) else DownloadQueue.pause(key)
}
} else if (recovery.state == RecoveryState.RESUMABLE) {
SecondaryButton("Resume", enabled = !busy, modifier = Modifier.testTag("store-resume")) {
busy = true
scope.launch {
try {
runCatchingCancellable { withContext(Dispatchers.IO) { StoreMaintenance.resume(context, game) } }
.onFailure { error = it.message }
} finally { busy = false }
}
}
} else if (MaintenanceAction.UPDATE in capabilities && check?.state == MaintenanceCheckState.AVAILABLE) {
val target = check.version.takeIf { it.isNotBlank() }
SecondaryButton(target?.let { "Update to $it" } ?: "Update", enabled = !busy, modifier = Modifier.testTag("store-update")) {
beginPrepare(MaintenanceAction.UPDATE, context, game, scope, { busy = it }, { proposal = it }, { error = it })
}
}
if (!active) Box {
SecondaryButton("Maintenance", enabled = !busy, modifier = Modifier.testTag("store-maintenance")) { menu = !menu }
AnchoredMenu(menu, onDismiss = { menu = false }, title = "Maintenance", compact = true) { first ->
MenuItem("Check for updates", checked = false, enabled = !busy && game.sidecar.isInstalled,
modifier = Modifier.testTag("store-check"), focusRequester = first) {
menu = false
StoreMaintenance.check(context, game, force = true)
}
if (MaintenanceAction.UPDATE in capabilities) {
val legacyBootstrap = game.sidecar.store in setOf(com.droiddeck.launcher.stores.Store.EPIC, com.droiddeck.launcher.stores.Store.AMAZON) &&
check?.state != MaintenanceCheckState.AVAILABLE
MenuItem(if (legacyBootstrap) "Update / verify current build" else "Update", checked = false, enabled = !busy,
modifier = Modifier.testTag("store-update-menu")) {
beginPrepare(MaintenanceAction.UPDATE, context, game, scope, { busy = it }, { proposal = it }, { error = it })
}
}
if (MaintenanceAction.REPAIR in capabilities) MenuItem("Verify / Repair", checked = false, enabled = !busy,
modifier = Modifier.testTag("store-repair")) {
beginPrepare(MaintenanceAction.REPAIR, context, game, scope, { busy = it }, { proposal = it }, { error = it })
}
if (MaintenanceAction.REFRESH in capabilities) MenuItem("Refresh", checked = false, enabled = !busy,
modifier = Modifier.testTag("store-refresh")) {
beginPrepare(MaintenanceAction.REFRESH, context, game, scope, { busy = it }, { proposal = it }, { error = it })
}
if (MaintenanceAction.OPEN_CLIENT in capabilities) MenuItem(adapter.openClientLabel(game), checked = false, enabled = !busy,
modifier = Modifier.testTag("store-open-client")) {
menu = false
runCatching { StoreMaintenance.openClient(context, game) }.onFailure { error = it.message }
}
}
}
}
if (!active && recovery.state == RecoveryState.NEEDS_ATTENTION && recovery.message.isNotBlank())
Text(recovery.message, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
check?.let { current ->
when (current.state) {
MaintenanceCheckState.CHECKING -> Text("Checking for updates…", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
MaintenanceCheckState.CURRENT -> Text("Up to date", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
MaintenanceCheckState.AVAILABLE -> if (MaintenanceAction.UPDATE !in capabilities) {
val message = if (MaintenanceAction.OPEN_CLIENT in capabilities) {
"An update is available. Use ${adapter.openClientLabel(game)} to apply it."
} else {
"An update is available."
}
Text(message,
fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
MaintenanceCheckState.UNKNOWN, MaintenanceCheckState.FAILED -> if (current.reason.isNotBlank())
Text(current.reason, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
error?.let { Text(it, fontSize = 12.sp, color = MaterialTheme.colorScheme.error) }
proposal?.let { selected ->
val shown = rememberShown { proposal = null }
val close = { shown.targetState = false }
AppDialog(shown, close, "storeMaintenance", wide = false, maxWidth = 460.dp) {
DialogTitleRow(selected.operation.label(), close)
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text(game.sidecar.title, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(selected.targetLabel, fontSize = 15.sp, color = MaterialTheme.colorScheme.onBackground)
if (selected.description.isNotBlank()) Text(selected.description, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Row(horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
Column(Modifier.weight(1f)) {
Text("Download", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(maintenanceEstimate(selected.downloadBytes), fontSize = 14.sp)
}
Column(Modifier.weight(1f)) {
Text("Required space", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(maintenanceEstimate(selected.diskBytes), fontSize = 14.sp)
}
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
PrimaryButton(selected.operation.label(), enabled = !busy) {
busy = true
close()
scope.launch {
try {
runCatchingCancellable { withContext(Dispatchers.IO) { StoreMaintenance.enqueue(context, game, selected) } }
.onFailure { error = it.message }
} finally { busy = false }
}
}
SecondaryButton("Cancel", onClick = close)
}
}
}
}
private fun beginPrepare(
action: MaintenanceAction,
context: android.content.Context,
game: InstalledStoreGame,
scope: kotlinx.coroutines.CoroutineScope,
setBusy: (Boolean) -> Unit,
setProposal: (MaintenanceProposal) -> Unit,
setError: (String?) -> Unit,
) {
setBusy(true)
scope.launch {
try {
runCatchingCancellable { withContext(Dispatchers.IO) { StoreMaintenance.prepare(context, game, action) } }
.onSuccess(setProposal).onFailure { setError(it.message) }
} finally { setBusy(false) }
}
}
private suspend fun <T> runCatchingCancellable(block: suspend () -> T): Result<T> = try {
Result.success(block())
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Throwable) {
Result.failure(error)
}
private fun MaintenanceAction.label(): String = when (this) {
MaintenanceAction.UPDATE -> "Update"
MaintenanceAction.REPAIR -> "Repair files"
MaintenanceAction.REFRESH -> "Refresh installation"
MaintenanceAction.OPEN_CLIENT -> "Open client"
}
private fun maintenanceEstimate(bytes: Long): String =
if (bytes < 0L) "Unknown (client-determined)" else com.droiddeck.launcher.stores.formatBytes(bytes)
@@ -157,7 +157,7 @@ private fun FlathubHero(s: FrontEndState, ring: Int) {
StoreState.sections.values.flatten().mapNotNull { it.icon }.distinct().take(48).takeIf { it.size >= 8 }.orEmpty()
}
val busy = StoreState.busy == "setup"
BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp)) {
BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = if (narrow) 14.dp else 22.dp).padding(top = if (narrow) 10.dp else 14.dp)) {
val shape = RoundedCornerShape(20.dp)
Box(Modifier.fillMaxWidth().height(maxHeight.coerceAtLeast(320.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) {
androidx.compose.animation.Crossfade(icons, animationSpec = Motion.tw(600), label = "flathubWall") { tiles ->
@@ -316,7 +316,7 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) {
}
Column(
Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp)
Modifier.fillMaxSize().padding(horizontal = padH).padding(top = if (narrow) 10.dp else 14.dp)
.bumpers(
onPrevious = { if (openApp == null) mode = modes[(modes.indexOf(mode) + modes.size - 1) % modes.size] },
onNext = { if (openApp == null) mode = modes[(modes.indexOf(mode) + 1) % modes.size] },
@@ -360,8 +360,10 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
when (d.state) {
DownloadState.RUNNING, DownloadState.QUEUED -> {
RoundAction(Icons.Filled.Pause, stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(d.key) }
CancelAction { DownloadQueue.cancel(ctx, d.key) }
if (d.interruptible) {
RoundAction(Icons.Filled.Pause, stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(d.key) }
CancelAction { DownloadQueue.cancel(ctx, d.key) }
}
}
DownloadState.PAUSED -> {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.resume(ctx, d.key) }
@@ -311,7 +311,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
val backLabel = stringResource(R.string.common_back)
Box(modifier.onGloballyPositioned { hostAt = it.positionInRoot() }) {
Column(
modifier = Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp)
modifier = Modifier.fillMaxSize().padding(horizontal = padH).padding(top = if (narrow) 10.dp else 14.dp)
.then(if (openGame != null && !arranging) Modifier else Modifier.bumpers(
onPrevious = {
val picked = Store.byId(focusedChip)
@@ -1380,6 +1380,9 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
val pal = LocalPalette.current
val small = 10.sp
when {
item.store == Store.GOG && download != null -> Text("${download.percent}%", fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
item.store == Store.GOG && installed && com.droiddeck.launcher.stores.gog.GogMaintenance.checks[item.id]?.state == com.droiddeck.launcher.stores.gog.GogMaintenance.State.AVAILABLE ->
Text(stringResource(R.string.common_update), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
installed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
val ctx = LocalContext.current
val game = StoresState.installedGame(item.store, item.id)
Loaded 100 of 264 files, more files were not shown because too many files have changed in this diff. Show more