Compare commits

...
Author SHA1 Message Date
XxJSONDeruloxX efc335673d fix: persist SDL3 controller settings 2026-10-25 11:15:46 -04:00
XxJSONDeruloxX 497b92e63d fix: harden SDL3 controller lifecycle 2026-10-25 11:08:20 -04:00
XxJSONDeruloxX 6d6b6726fa build: vendor pinned SDL3 bridge sources 2026-10-25 10:45:07 -04:00
XxJSONDeruloxX 5115b4416a test: include SDL3 in drawer navigation 2026-10-25 10:38:02 -04:00
XxJSONDeruloxX a080e4a4b4 fix: preserve Android controller fallback 2026-10-25 10:38:02 -04:00
XxJSONDeruloxX d180f563da build: prepare SDL3 bridge for upstream 2026-10-25 10:38:02 -04:00
pablo89898991 a206be6230 feat: integrate SDL3 controller bridge 2026-10-25 10:38:02 -04:00
maxjivi05 6ef2bcc9c5 docs: Star History rank badge above the awards 2026-10-25 10:24:48 -04:00
MaxsTechReview 3fdc74051c feat: DroidDeck-Proton is downloaded, kept up to date and used by default (#1540) 2026-10-25 10:09:22 -04:00
Kurt Himebauch 2a69505199 feat: merge Games and store libraries into one Library and one game page (#1460) 2026-10-25 08:39:56 -04:00
Kurt Himebauch 0cf5b42788 Add an in-session microphone toggle (#1506) 2026-10-25 08:37:49 -04:00
diegodru 1f42f512e2 fix: GOG sign-in pages use the browser's own user agent (#1500)
The GOG sign-in WebView sent GOG Galaxy's Windows user agent while the page's scripts and client hints report an Android WebView, so Cloudflare's check on gog.com never passed (#1486). The sign-in flow now uses the WebView's own Chrome user agent, like the Epic, Google, Facebook and Apple sign-ins. API calls outside the WebView keep the Galaxy user agent.

Fixes #1486
2026-10-25 00:06:54 -04:00
The412Banner c5d7cdc058 Xbox Cloud Gaming: stream from the store and Games tab, native player with DroidDeck frame generation (#1531)
Xbox Cloud Gaming: stream from the store and Games tab, native player with DroidDeck frame generation

Stream Xbox games with Xbox Cloud Gaming (Game Pass) from DroidDeck, outside
the Linux session.

- Backend: `xodus-cli cloud-token` (tools/xbox/droiddeck-cloud-token.patch)
  gets the streaming tokens; they stay in memory.
- Web player (default): the Greenlight player page (tools/xcloud-player, MIT)
  in a WebView, plus Microsoft's own xbox.com/play player. In-stream menu with
  screen effects (sharpen, colour, deband, FXAA, CRT, NTSC, Toon, fps cap),
  stream quality, performance overlay (level, layout, top right / top left)
  and rumble.
- Native player (opt-in, Android 10+, Player engine: Native): Google's WebRTC
  (io.github.webrtc-sdk 125.6422.07, BSD) with the Greenlight protocol ported
  to Kotlin, in its own process (:xcloudnative) with its own instance of
  DroidDeck's compositor. Decoded frames reach the compositor as
  AHardwareBuffers (new stream mode, VK_ANDROID_external_memory_android_
  hardware_buffer import), so DDFG 2x and LSFG 2x/3x/4x run on them. Live
  frame generation, frame-rate target (presets and a 10-165 fps slider, even
  pacing), zero-copy picture, small network buffer, fast decoder, instant
  controller input, overlay with engine and on-screen fps, background end,
  restart and web fallback. It takes the main process's tokens through
  XboxCloudTokenService; they are fetched ahead while a cloud game is shown.
- The compositor requests the dma-buf import extensions only where the driver
  has them (the system driver has none).
- Catalog: cloud availability, Game Pass plan CFQ7TTC0K6L8 counted, library
  filter All / Owned / Game Pass / Cloud, Stream and Add to Games on the store
  page, stream-only Games-tab entries (Stream + Download / Play + Stream).
- Xbox games get VC++ 2015-2022 and the ARM64 runtime registry entries
  (vcredist2022_arm64, built in until the catalog has it) before each launch.
- Controller focus reaches pickers opened from a game page (install location,
  uninstall); Add / Remove from Games keep the focus.

Credits: Greenlight by UnknownSKL (Jim Kroon), MIT, player and protocol;
Better xCloud for the resolution / OS mapping; MGamer404's Bannerlator #627
for the ARM64 runtime approach. Ported from the412banner's Bannerlator.
2026-10-24 23:17:57 -04:00
The412BannerandKeegantheVeganat0r 5ca1f610ab Xbox: fix sign-in on phones with a slow StrongBox Keystore (#1521)
On some phones (tester: Honor BKQ-N49, Android 17) Xbox sign-in stopped with
"the Xbox helper stopped with exit code 1" before Microsoft's page opened.
The backend asks the app to read and save credentials over a socket and waits
10 s for each reply. The app sealed credentials with a StrongBox-backed
Keystore key, and each StrongBox operation took 7-15 s on that phone, so the
backend gave up. The app still finished those saves afterwards, leaving a
record without a username that every later attempt had to read back slowly.

- Seal new store credentials with a TEE Keystore key (v2 envelopes); v1
  envelopes still open with the old key and move to v2 on their next write.
- A sign-in discards an Xbox record without a username (an unfinished
  sign-in) before starting the backend.
- The backend waits 30 s for the app's credential reply.
- The backend names the failing step instead of only credential-io (socket
  connect/exchange, session lock, missing socket name/port/key), and falls
  back to a keyed 127.0.0.1 port when the abstract socket is refused.
- The app's credential listener logs and retries accept errors, serves each
  connection on its own thread, and logs slow requests with per-stage times.

Refs #1337, #1300


Co-authored-by: KeegantheVeganat0r <58369898+KeegantheVeganat0r@users.noreply.github.com>
2026-10-25 01:39:09 +00:00
maxjivi05 82d8eb3b79 Keep a Proton choice unless the shared build needs the other platform 2026-10-24 21:13:58 -04:00
maxjivi05 5f0e6a8b7e Match Proton tools across clients by their arm64 and a64 names 2026-10-24 21:13:58 -04:00
maxjivi05 c866bb90db Share installed games between the arm64 and x86-64 Steam clients 2026-10-24 21:13:58 -04:00
MaxsTechReview 8d407aa1e8 Focus flatpak and other sandboxed shortcuts in gaming mode (#1524) 2026-10-24 20:04:54 -04:00
Kurt Himebauch aca7fca19f fix: keep cancellation polling from ending session teardown early 2026-10-24 19:50:10 -04:00
Kurt Himebauch 96ba915378 fix: publish session stopping before clearing the running flag 2026-10-24 19:50:10 -04:00
Kurt Himebauch 71f84f0593 fix: defer automatic Proton updates until session teardown ends 2026-10-24 19:50:10 -04:00
Kurt Himebauch b56ea6122a fix: exclude pending launches and retain Proton update cooldowns 2026-10-24 19:50:10 -04:00
Kurt Himebauch 8a948fbe45 feat: automatically update installed Proton builds on app open 2026-10-24 19:50:10 -04:00
maxjivi05 74a6a88df8 fix(desktop): keep the Desktop actions and Settings handle on small phones 2026-10-24 18:58:45 -04:00
maxjivi05 c9493993af fix(desktop): keep the Desktop page from overlapping on phones 2026-10-24 18:58:45 -04:00
MaxsTechReview dc08385411 Stop the library helper when the KDE Steam client exits (#1519) 2026-10-24 17:57:59 -04:00
MaxsTechReview 49b6a0739d Present games from the KDE Steam client through software WSI (#1518) 2026-10-24 17:56:40 -04:00
MaxsTechReview 8471682b1c Collect only the Steam log lines a session wrote (#1505) 2026-10-24 14:47:21 -04:00
MaxsTechReview 4dda1c1e52 fix(epic): a paused install keeps what it downloaded (#1504) 2026-10-24 14:47:18 -04:00
Thomas Lee 8156a9649d perf: reuse Steam artwork directory scans (#1466) 2026-10-24 14:35:14 -04:00
FX1922 7b518d7e6a itch.io: platform and tag filters (#1497) 2026-10-24 13:39:57 -04:00
maxjivi05 8d66570d33 Steam file dialog: keep spaces in the chosen path, cancel when GTK 3 is missing or the bridge reconnects 2026-10-24 13:18:04 -04:00
maxjivi05 5a56d9f785 fix(steam): Browse buttons open a file chooser on the ARM64 client
Steam's ARM64 client has no desktop-portal file chooser, so
SteamClient.System.OpenFileDialog failed at once and every Browse button
(Add a Non-Steam Game, shortcut target, library folder) did nothing.
The Steam UI bridge now answers it with a GTK file chooser run under
Steam's reaper, so gamescope shows it over Steam.
2026-10-24 13:18:04 -04:00
MaxsTechReview 77e23cb397 itch.io: browse the Store tab by sort and price, with paging and a disk cache (#1473)
## What this does

The itch.io Store tab used to show only four fixed shelves. This is the
first of a series of PRs that rework it. It adds real browsing: pick an
order and a price filter, and the tab loads itch's own listing for that
choice and keeps loading as you scroll. Login, the library, downloads
and installs are unchanged.

Platform and tag filters, the game page with the install picker, updates
and collections are not in this PR. They come in the following ones.

## How it works

itch serves every listing page as an RSS feed if you add `.xml` to the
address. The app already reads those feeds for the shelves, so browsing
reuses the same parser (`ItchShelves.parse`). Nothing here needs the API
key.

The address is built the way itch builds its own links: sort, then
price, then `platform-<name>`, then `tag-<slug>`.

| Choice | Address |
|---|---|
| Popular (default) | `https://itch.io/games` |
| New & popular | `/games/new-and-popular` |
| Top sellers | `/games/top-sellers` |
| Top rated | `/games/top-rated` |
| Most recent | `/games/newest` |
| Free | `/games/free` |
| On sale | `/games/on-sale` |
| Paid | `/games/store` |
| $5 or less | `/games/5-dollars-or-less` |
| $15 or less | `/games/15-dollars-or-less` |

Choices combine, for example `/games/top-rated/free`, then `.xml` for
the feed. Page 2 and later add `?page=N`.

## Changes

**`stores/itch/ItchBrowse.kt` (new)**
- `BrowseQuery` holds sort, price, platforms and tags. The default query
is the front page, which keeps the existing shelves.
- `ItchBrowse.path` and `url` build the addresses above. Only the
spellings listed above are used. Platforms and tags are already accepted
by the builder, ready for the next PR.
- `ItchBrowse.page` loads one page of results:
- Disk cache under `cacheDir/itch-browse`, keyed by the SHA-1 of the
address, fresh for 3 hours.
  - Requests are made one at a time, at least 1.2 s apart.
  - A 429 answer waits 8 s and tries once more.
- Each request is written to the store log (address, status, number of
games).
- `ItchBrowseState` is the Compose state for the tab: the query, the
games loaded so far, and the loading, ended and failed flags. A
generation counter discards answers that arrive after the user has
changed the query. Paging skips games it has already shown.

**`ui/ItchBrowseBar.kt` (new)**
- A sort chip row and a price chip row, plus a load-more trigger at the
end of the grid.
- Chips are selectable, work with the controller (`controllerConfirm`)
and use the same glide border as the rest of the app.

**`ui/StoresPage.kt`**
- The storefront shows the chip bar for itch.io and, when a non-default
choice is active, the browse results in the existing grid instead of the
shelves.
- Games you already own are marked as owned in the results.
- Empty and failed states have their own messages.

**`stores/itch/ItchShelves.kt`**
- `open(url)` is now `internal` so browsing can reuse it.

**`stores/StoresState.kt`**
- `detailItem` also looks in the browse results for itch.io, so tapping
a result opens its detail page.

**Strings**
- 13 new strings (sort names, price names, "Load more", "Couldn't load
games"), translated in all 33 locales.

**Docs and tests**
- `docs/development/itch-browse.md` explains the address scheme, the
cache and the paging.
- `ItchBrowseTest` checks the addresses the code builds against the ones
listed above.

## Testing

I checked every address with `.xml` added, and all of them load without
errors:
- Every sort, every price filter and every platform on its own.
- Combinations: `top-rated/free`, `top-rated/on-sale`,
`top-rated/store`, `top-rated/5-dollars-or-less`,
`top-rated/free/platform-windows` and
`top-rated/free/platform-windows/tag-pixel-art`.
- Paging: `?page=2` and `top-rated.xml?page=2`.

The unit test locks those addresses in.

## Not in this PR

- Platform and tag filters in the UI, and search.
- The game page, the version picker and install for free games.
- Updates for installed games and itch collections.
- Android builds will link out to the itch.io page. Butler patching
comes last, as an add-on pack.
2026-10-24 11:33:47 -04:00
maxjivi05 1883a8c7cf itch.io browse: drop code comments 2026-10-24 11:15:35 -04:00
maxjivi05 aefd8a3b60 fix(xbox): report a failed class registration in the launch log 2026-10-24 11:14:20 -04:00
maxjivi05 fee8ce91f3 fix(xbox): register the runtime's WinRT classes and load its wintypes so Minecraft starts 2026-10-24 11:14:20 -04:00
maxjivi05 bcb18e3fb7 fix(xbox): match only the 401 rejection Xodus prints 2026-10-24 09:07:13 -04:00
maxjivi05 6855dd4467 fix(xbox): say to sign in again when Microsoft rejects the download's licenses 2026-10-24 09:07:13 -04:00
maxjivi05 a66d7d74a4 fix: Steam Input mouse clicks, scrolling and pointer moves reach games again 2026-10-24 09:07:04 -04:00
Kurt Himebauch 2bd279a0f3 fix: read Steam shader settings off the main thread 2026-10-24 08:54:41 -04:00
maxjivi05 0790cb4390 fix: keep a Proton's originals when its folder could not be fully removed 2026-10-24 08:22:00 -04:00
maxjivi05 ad6d8d824a fix: removing a Proton also deletes its stored component originals 2026-10-24 08:22:00 -04:00
maxjivi05 0b671b2144 fix: match an annotated overlay header and keep the settings file's mode 2026-10-24 06:27:46 -04:00
maxjivi05 31cead9b32 fix: keep blank lines inside the overlay section and stage settings under a unique name 2026-10-24 06:27:46 -04:00
maxjivi05 26c3dcc885 fix: turn off the Ubisoft Connect overlay so Ubisoft games stop crashing at start 2026-10-24 06:27:46 -04:00
FX192 dc57f367e1 itch.io browse: don't re-fire the load-more trigger when a page is appended 2026-10-24 13:07:16 +03:00
FX192 5838587639 itch.io browse: let a failed page be retried instead of ending the list 2026-10-24 13:02:17 +03:00
FX192 7e87cdacb5 Merge remote-tracking branch 'upstream/main' into feat/itch-browse 2026-10-24 12:46:26 +03:00
FX192 dbcbf0b6fa itch.io browse: use itch's own sort, price and platform paths
The sort and price chips now cover everything itch's browse page offers, with the
paths copied from its links: new-and-popular, top-sellers, top-rated and newest
for sorts; free, on-sale, store, 5-dollars-or-less and 15-dollars-or-less for
prices; platform-windows, -osx, -linux, -android, -ios, -web and -mobile-web.
The guessed alternative spelling of the free filter is gone, so a query is one
address. The tests assert the addresses itch itself uses.

New and reworded strings in all 33 locales.
2026-10-24 09:27:49 +03:00
maxjivi05 476642be71 chore: drop the added comments 2026-10-24 01:42:20 -04:00
Nikolay Nadorichev 8c86b718a0 fix: find the signed-in Steam account when loginusers.vdf has no MostRecent
droiddeck-steam-shortcuts and AddedGames.accountConfig took the account
marked "MostRecent" in loginusers.vdf, else the only userdata folder.
The arm64 client here writes no MostRecent, so with two accounts in one
install nothing was picked: no added or store game reached
shortcuts.vdf ("no signed-in account yet; nothing written") and Steam
answered their launch with "App configuration unavailable".

Without MostRecent, take the account marked AutoLogin, then the one with
the latest timestamp. Both sides use the same order so the app reads the
config the guest script writes.
2026-10-24 01:42:20 -04:00
maxjivi05 473ac666b3 Take over Steam's Default startup movie pick 2026-10-24 01:41:08 -04:00
FX192 cc0a4f5aa9 itch.io: browse the Store tab by sort and price, with paging and a disk cache
The Store tab only had four fixed shelves and a title search. A row of sort
(Popular, New, Top rated, Top sellers) and price (Any, Free, On sale) chips now
sets a BrowseQuery; anything but the defaults swaps the shelves for that query's
games, loaded page by page as the grid scrolls.

ItchBrowse builds itch's listing-feed URL (platform and tag segments are in the
builder for the next change), tries each spelling of a price filter until one
answers, spaces requests 1.2 s apart, backs off once on a 429, and keeps pages
in the app cache for three hours. Every request is logged with its status and
game count so a wrong URL guess can be fixed from a device. Owned games replace
their browse copy so Install and the owned markers are right, and the detail
page finds browse results.

Strings for all 33 locales; URL-builder tests; docs/development/itch-browse.md.
2026-10-24 07:49:05 +03:00
maxjivi05 f89dc04072 fix: Proton's EasyAntiCheat and BattlEye runtimes are not listed as games
Steam installs Proton EasyAntiCheat Runtime (1826330) and Proton BattlEye Runtime (1161040) as tool depots. The launcher's Games tab and the desktop's game entries now skip them like the other runtimes.
2026-10-24 00:47:45 -04:00
maxjivi05 dd79f44b3a fix: the Steam download monitor no longer stalls the main thread on a long content log
The content log was read with RandomAccessFile.readLine, one byte per read, on the main thread. A 4 MB log took about 2 s on the first poll, enough for an ANR on slower devices while a download runs. It is now read through a buffered reader with the same Latin-1 lines and offset, and the per-line regexes only run on lines that can match.
2026-10-24 00:27:22 -04:00
maxjivi05 b0e405ebf3 fix: Epic client imports get the launch command, versioned installs need a matching manifest build
Games the Epic client installed now carry their LaunchCommand arguments too, split by a new launch.split op. A doubled quote inside a quoted argument is one literal quote, and an install with a version ignores a manifest without the same build.
2026-10-23 23:59:37 -04:00
maxjivi05 42026b382f fix: keep manifest launch arguments to the installed build and their own additions
The manifest's arguments apply only when its build matches the installed version, only arguments the merge inserted are tracked as its own, escaped quotes split like a Windows command line, and the REDprelauncher rule needs Cyberpunk2077.exe beside it.
2026-10-23 23:59:37 -04:00
maxjivi05 8209a707f4 fix: Caravan SandWitch and Cyberpunk 2077 run at D3D12 feature level 12_1
Feature level 12_2 makes vkd3d-proton report mesh shaders and ray tracing that Turnip doesn't provide. Caravan SandWitch (Unreal Engine 5) then builds mesh shader pipelines without a pipeline layout and the driver crashes; Cyberpunk 2077 stops at ray tracing initialization. Only these two games get 12_1, and a value set in a game's own settings still wins.
2026-10-23 23:59:37 -04:00
maxjivi05 46cd8e1777 fix: Epic games get their manifest launch command
Epic manifests carry a launch command next to the launch executable, which the Epic launcher passes to the game. It was read and dropped, so Caravan SandWitch never got -PCStore=EGS and quit with "started outside of any known PC store". The manifest's launch command now joins the game's arguments, including for games already installed.
2026-10-23 23:59:37 -04:00
maxjivi05 6e1621fe53 fix: Steam's Ubisoft games install Ubisoft Connect again
The redistributable seeder marked every process in a game's install scripts as already run, so the Ubisoft Connect installer that Ubisoft games list was skipped and they stopped with "Unable to locate Uplay PC". It is now left to run like the Vulkan runtime installer, and a marker an earlier seeding wrote is taken back out.
2026-10-23 23:58:39 -04:00
XxJSONDeruloxX 546574e982 fix(xbox): enable proot fast path in Xodus 2026-10-23 23:56:24 -04:00
XxJSONDeruloxX b1ab55856e fix(ui): clear search focus and use store accents 2026-10-23 23:56:24 -04:00
XxJSONDeruloxX 4a0eb14d1f fix(xbox): mount selected SD library in Xodus 2026-10-23 23:56:24 -04:00
XxJSONDeruloxX 2c8ae3753c fix(xbox): mount external storage for downloads 2026-10-23 23:56:24 -04:00
Kurt Himebauch fcfbb74068 fix: one refused thermal or power query no longer drops the others from the session report (#991) 2026-10-23 23:43:01 -04:00
MaxsTechReview 0340be5a7d Steam client download: resumes, retries, shows megabytes, and isn't paused out of sight (#587)
A user's first Steam setup never finished on an Honor Pad (Snapdragon 6
Gen 1, metered Wi-Fi with a 14 Mbit/s link). Their log stops at
`downloading Steam: bins_linuxarm64_linuxarm64 (2/17)`. The log was
shared 31 s into the session, so nothing had failed yet. The way the
download works explains why it never got further.

## Why

- **The session pauses the download.** With the default background
behavior (Manual), a session pauses as soon as DroidDeck is hidden or
the screen turns off. In the user's log that happened one second after
start, before the download had begun.
- "Keep downloads running" doesn't help. It's off by default, and it
only recognizes Steam's own game downloads, not the runtime fetching the
client.
- A first run shows nothing for minutes, so leaving the app or letting
the screen time out is exactly what people do.
- **The download is bigger than the screen says.** The client is about
360 MB in 17 parts, and part 2 alone is 110 MB. The loading screen said
"~1-2 min" and counted parts, not bytes, so on a slow link it looks
frozen at about 5%.
- **Nothing handles a bad connection.** Each part was a plain `curl
-fsSL` with no timeout, no retry and no progress output.
  - A stalled connection could wait forever.
- A failed one ended the session and threw away everything fetched, so
the next try started from part 1.

## What changes

- **`droiddeck-steam-install`**:
- Parts go to `package/droiddeck-download` and stay there until the
client is installed.
  - Each part resumes from the bytes on disk (`curl -C -`).
  - A transfer under 4 KB/s for a minute is dropped and resumed.
- Attempts that make no progress back off 5–30 s, then give up with a
clear error. Whatever arrived is kept.
  - A finished part is marked unpacked, so a later session skips it.
- Bytes that fail their checksum are fetched whole again. A server that
won't resume starts the part over. Parts left over from another client
version are dropped.
- A repair redoes every part once, and keeps what an interrupted repair
already redid.
- Every 5 s the step line also carries megabytes overall: `… (2/17), 45
of 360 MB`.
- **Loading screen** (`LoadingState`): shows `Downloading the Steam
client · 45 / 360 MB`, with the bar following the bytes. Older runtimes
still show the part name.
- **`SessionService`**: until the session's first frame, the download
watch also checks whether the client is still to be fetched (no install
stamp or client binary, or a repair requested). While it is:
- the session stays awake with its wake and Wi-Fi locks, whatever the
downloads setting says;
  - the notification shows "Steam download active" with **Suspend now**;
  - a `steam.client_download` event marks start and end.
- The watch is set up before the first suspend decision, so a session
started with the screen off isn't paused first. Once the client is
there, the chosen behavior applies again.
- **`droiddeck-session`**: the step no longer promises 1–2 minutes.

## Testing

- `python3 -m unittest discover -s tools/tests -p 'test_*.py'`: 497 OK,
1 skipped.
- `test_steam_install.py` gets a fake curl that drops connections,
refuses to resume or fails on cue.
- New cases cover: megabyte progress; resuming after a dropped
connection; keeping finished and partial parts across a failed session;
restarting a part the server won't resume; re-fetching bad bytes;
dropping another version's parts; a repair resumed once.
- Kotlin: `:app:testDebugUnitTest --tests
'com.droiddeck.launcher.session.*'` passes. That includes the new
`LoadingStateTest` and the `clientInstallPending` cases in
`SteamDownloadMonitorTest`.
- RedMagic NP06J, with Background behavior set to Manual and "Keep
downloads running" off (the user's settings), and a client repair
requested:
- Started Steam and sent DroidDeck to the background straight away. The
client download stayed active for 30 s with no pause, and all 360 MB
arrived. Then the session paused as Manual should.
- Stopped a second repair during part 2. Part 1 was marked unpacked, the
110 MB part 2 was kept, and the repair marker stayed.
- Started again: it resumed at 110 of 360 MB, unpacked part 2 without
fetching it again, finished, and Steam started normally.
- The loading screen showed `Downloading the Steam client · 248 / 360
MB`.

Retested 2026-10-23 on the REDMAGIC tablet after merging main, which
brought in the stable-channel fallback. Background behavior was set to
Manual with "Keep downloads running" off. A client repair was forced,
then Home was pressed right after Start:

| Build | Session while hidden | Client download |
|---|---|---|
| main | suspended 1 s after Home | stuck at part 3/17 after 90 s |
| this PR | kept awake until the client was in | all 17 parts, 362 MB in
46 s with MB progress; suspended once done |

`tools.tests.test_steam_install` (22), `SteamDownloadMonitorTest` and
`LoadingStateTest` pass.

## Not changed

- **The download is the plain zips.** Valve's manifest also lists `.vz`
(LZMA) versions, 228 MB instead of 360 MB. Using them needs a VZ decoder
in the guest; that could be a follow-up.
- **The stall and retry path** is covered by the tests but wasn't forced
on the device.
2026-10-23 23:28:05 -04:00
maxjivi05 132f40ac97 fix: install step progress cannot overflow 2026-10-23 23:11:34 -04:00
maxjivi05 5981bbb1e2 fix: an oversized install step count falls back to the step text 2026-10-23 22:51:28 -04:00
maxjivi05 7419ba114f fix: the client install stays awake until Steam's first frame and its end is recorded 2026-10-23 22:22:14 -04:00
maxjivi05 96e2bf992d fix: an HTTP 4xx part hands over to the next CDN at once 2026-10-23 21:20:50 -04:00
Kurt Himebauch ad9eb8eb29 xbox backend x86 to arm cross compilation (#1440) 2026-10-23 21:02:20 -04:00
MaxsTechReview 116d0e4f1a fix: a game started from another launcher returns to that launcher (#1438)
A game started from another launcher (ES-DE, a `droiddeck://game/` link,
a pinned shortcut) should send the player back to that launcher when it
closes. Instead DroidDeck always opened the Android home screen, which
is a different place whenever that launcher isn't the default Home app.

## Cause
The link is handled by `FrontEndActivity`, which starts the session in
its own task and stays behind it in a second DroidDeck task. When the
session ended, DroidDeck started `CATEGORY_HOME` to cover that leftover
task, so the player always landed on the system Home.

## Fix
When a link-launched session ends, `SessionActivity` removes the task
that handled the link (a `FrontEndActivity` task whose base intent is a
game link), then removes its own task. Android then shows whatever was
underneath: ES-DE, any other app that launched the game, or Home when
Home launched it.

Sessions started from DroidDeck's own Games tab are unchanged.

## Testing
On a REDMAGIC NP06J, with the `droiddeck://game/945360` link started
using ES-DE's flags (`NEW_TASK | CLEAR_TASK`). Among Us was closed and
"Return to launcher after a game" was on.

| Launched from | main | this branch |
|---|---|---|
| Calculator (stands in for a non-Home frontend) | Android home |
Calculator |
| Home | Android home | Android home |
| DroidDeck's Games tab | DroidDeck | DroidDeck |

## Credits
Reported on Discord by whatsupbros.
2026-10-23 20:45:32 -04:00
maxjivi05 4a57c6f6f1 chore: drop the comments this change added 2026-10-23 20:45:14 -04:00
maxjivi05 2d9d4dbeb0 Merge branch 'main' into fix/steam-client-download
# Conflicts:
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install
#	tools/tests/test_steam_install.py
2026-10-23 20:23:44 -04:00
MaxsTechReview 866551e797 fix: Snapdragon 8 Gen 2 no longer pins Steam to one core by default (#1441)
## Summary

Since 0.5.0, Snapdragon 8 Gen 2 devices (Retroid Pocket 6, Galaxy S23,
AYN Thor) pin the Steam client, its UI helper and gamescope to the
single prime core whenever the core settings were never touched. The
Steam menu and overlay lag on those devices, and games launched from
Steam get CPU-starved.

This drops that default, so 8 Gen 2 behaves like 0.4.0 and every other
chip: Android schedules Steam on all cores. Core choices users saved in
Performance are kept, and the all-core restore for games launched from a
pinned Steam client stays.

## Evidence

The device reports attached to both bug reports show the default in
effect:

| Device | SoC | Client core override | Client cores |
|---|---|---|---|
| Retroid Pocket 6 | QCS8550 | true (never set) | 7 |
| Galaxy S23 | SM8550 | true (never set) | 7 |

Both reporters say 0.4.0, which left Steam on all 8 cores, was smooth.
The PR that added the default did not benchmark it.

Tablet bench (REDMAGIC, SM8850): the 8 Gen 2 default was reproduced by
pinning Steam to one prime core (7) and games to cores 0-3. The test
scrolls the Big Picture library with the d-pad for 20 s and records
frame pacing. Two runs each:

| Steam client | UI fps | 1% low | p99 frame | off-cadence |
|---|---|---|---|---|
| all cores (this PR) | 114.4 / 115.2 | **62.5 / 62.5** | 16 ms | 4.7 /
4.0 % |
| one core (old default) | 109.7 / 110.9 | 41.7 / 41.7 | 24 ms | 8.0 /
7.0 % |

Among Us ran the same either way (58.9 vs 59.0 fps).

## Tests

`CoreAllocationPrefsTest`: absent preferences leave every core to the
scheduler, and saved choices are kept.

## Credits

- shanume (RP6) and Kacper (S23): reports, and the 8-cores-vs-1 finding.
- Kurt Himebauch (#654): the core allocation work this keeps, apart from
the default.
2026-10-23 20:22:23 -04:00
maxjivi05 a0c6545e77 fix: a link that joins DroidDeck's open task still returns to the caller 2026-10-23 20:22:05 -04:00
maxjivi05 c7bcd82782 fix: Snapdragon 8 Gen 2 no longer pins Steam to one core by default 2026-10-23 19:47:41 -04:00
maxjivi05 caaf6b3a01 fix: keep the link task id when an in-app resume reaches the session 2026-10-23 19:47:32 -04:00
superboo07 8123d5b361 xbox backend x86 to arm cross compilation 2026-10-23 23:40:49 +00:00
Kurt Himebauch 2b4bba63c5 docs: add the Trendshift #1 daily and weekly badges to the README (#1435) 2026-10-23 19:18:00 -04:00
maxjivi05 69b2b8fcdf fix: only close the game-link task that started the session 2026-10-23 19:17:08 -04:00
MaxsTechReview 0d8b5a7cf2 fix: stored components can be deleted after a Proton update (#1434)
After a Proton update, stored DXVK / VKD3D / FEX packages can't be
deleted. Components says they're "in use" by a Proton that's gone
(`DroidDeck-Proton_11-9.1` after updating to 11-11.1) or by a bare
number (`4005446849`).

## Cause
`deletePackage` and the Storage page's in-use check count every recorded
selection:
- **Removed Protons:** swaps on Protons that are no longer installed.
- **Out-of-date swaps:** swaps from before the Proton's version changed.
The launcher already ignores these.
- **Game profiles:** a per-game pick blocked the delete with the "swap
that Proton" message, naming the game's id.

## Fix
- **Out-of-date selections:** a selection only counts while its Proton
is installed and at the version the swap was made on. That's the rule
launches already use. Deleting a package removes its stale entries.
- **Profile picks:** deleting a package also clears it from any game's
component profile, so those games go back to the Proton's own copy.
Storage cleanup still keeps profile picks.
- **Live swaps:** a package swapped into an installed Proton is still
blocked. The message now shows the Proton's name rather than its id.

No new strings.

## Testing
On a REDMAGIC NP06J, with the state from the reports recreated:

| Case | main | this branch |
|---|---|---|
| DXVK swapped into a removed `DroidDeck-Proton_11-9.1` | Deleting
failed: in use in DroidDeck-Proton_11-9.1 | Deleted, stale entry removed
|
| FEX picked in game profile `4005446849` | Deleting failed: in use in
4005446849 | Deleted, profile cleared |
| DXVK swapped into installed Proton Experimental | blocked | blocked:
in use in Proton Experimental (ARM64) |

<img
src="https://raw.githubusercontent.com/maxjivi05/DroidDeck/pr-media/1434/main-stale-proton.jpg"
width="420"> <img
src="https://raw.githubusercontent.com/maxjivi05/DroidDeck/pr-media/1434/main-game-profile.jpg"
width="420">
<img
src="https://raw.githubusercontent.com/maxjivi05/DroidDeck/pr-media/1434/fix-game-profile.jpg"
width="420"> <img
src="https://raw.githubusercontent.com/maxjivi05/DroidDeck/pr-media/1434/fix-live-blocked.jpg"
width="420">

`ComponentsSelectionTest` covers removed, out-of-date and live
selections.

## Credits
Reported on Discord by Siigonis, Bado and woodrow1712.
2026-10-23 19:13:29 -04:00
maxjivi05 7261b26264 fix: a game started from another launcher returns to that launcher 2026-10-23 18:56:44 -04:00
maxjivi05 db9aae7b87 fix: delete the package before saving, and match Protons the same way 2026-10-23 18:56:24 -04:00
maxjivi05 70b8ec5de4 docs: add the Trendshift #1 daily and weekly badges to the README 2026-10-23 18:36:24 -04:00
maxjivi05 94b530ecb2 fix: stored components can be deleted after a Proton update 2026-10-23 18:28:35 -04:00
MaxsTechReview 906e0d1f7d fix: other apps can record game audio (#1430)
Fixes #1314.

Screen recorders and apps that use `AudioPlaybackCapture`
(MediaProjection) get silence from DroidDeck. The app targets SDK 28,
and Android blocks playback capture for apps below SDK 29 unless they
opt in. That was a side effect of the target SDK, not a choice.
`android:allowAudioPlaybackCapture="true"` opts in. Game audio already
plays with `AAUDIO_USAGE_GAME`, a usage that capture allows.

REDMAGIC NP06J with Among Us running, `dumpsys media.audio_policy`
("Allow playback capture log"); the game's streams are AAudio
`USAGE_GAME` with no capture-blocking flags:

| Build | |
| --- | --- |
| main | `uid=10494, allowPlaybackCapture=false,
packageName=com.droiddeck.launcher` |
| this PR | `uid=10494, allowPlaybackCapture=true,
packageName=com.droiddeck.launcher` |

## Credits
Requested and diagnosed by @WilsonNet in #1314.
2026-10-23 18:01:24 -04:00
maxjivi05 992912fdf8 fix: other apps can record game audio 2026-10-23 17:43:44 -04:00
MaxsTechReview 4ff4be2371 fix: keep a slightly early vsync tick for frame pacing (#1405)
Gamescope paces from the presentation timestamp. The Choreographer tick
is often still slightly ahead of the render thread, and that tick was
thrown away, so the draw time was reported instead.

A tick within one refresh of the draw is now kept, whether it is
slightly ahead or slightly behind. A missing tick, or one more than a
refresh away, still falls back to the draw time.
2026-10-23 17:00:32 -04:00
maxjivi05 06946fe8ae chore: drop comments 2026-10-23 16:01:41 -04:00
0x1Nawaf 53c63b6dc2 fix: keep a slightly early vsync tick for frame pacing 2026-10-23 15:43:52 +00:00
Kurt Himebauch a25081df7c Merge branch 'main' into fix/steam-client-download 2026-10-23 10:16:19 -04:00
Kurt Himebauch 958446ab7c Merge current main into PR #991 2026-10-22 13:11:05 -04:00
Kurt Himebauch bde9ca733f Merge current main into PR #587 2026-10-22 13:11:02 -04:00
Kurt Himebauch 495ff952d2 Merge current main into PR #991 2026-10-22 12:13:48 -04:00
Kurt Himebauch 0819aa725d Merge current main into PR #587 2026-10-22 12:13:46 -04:00
ovurrsl 430e77178e fix: one refused thermal or power query no longer drops the others from the session report
Thermal status, thermal headroom and power saver are now read one by
one, so a vendor that throws on one of them still gets the other two
lines, and the refused one shows as unknown.
2026-10-22 18:48:39 +03:00
xXJsonDeruloXx c8cc17bf3a Merge main into Steam client download PR 2026-10-22 10:01:34 -04:00
xXJsonDeruloXx 6d105c1649 chore: merge main to catch up with 0.5.0 2026-10-18 17:05:49 -04:00
MaxsTechReview 11bd604dfd Merge branch 'main' into fix/steam-client-download 2026-10-11 15:53:38 -04:00
MaxsTechReview b834a92244 Merge branch 'main' into fix/steam-client-download 2026-10-11 15:51:21 -04:00
maxjivi05 0cd7f07725 fix: a first run's Steam client download is not paused out of sight
With the default background behavior (Manual), a session pauses as soon
as DroidDeck is hidden or the screen turns off - one second after start in
the report this came from, before the download had begun. "Keep downloads
running" did not help: it is off by default, and it only recognizes the
client's own game downloads, not the runtime fetching the client itself.

Until the session shows its first frame, the download watch now also
asks whether the client is still to be fetched (no install stamp or no
client binary, or a repair asked for). While it is, the session is kept
awake with its wake and Wi-Fi locks whatever the downloads setting says,
the notification reads "Steam download active" with Suspend now, and a
steam.client_download event marks start and end. The watch is set up
before the first suspend decision, so a session started with the screen
off is not paused first. Once the client is there, the chosen behavior
applies again.
2026-10-11 14:45:57 -04:00
maxjivi05 342d2e7f20 fix: the Steam client download resumes, retries and shows megabytes
A first run downloads the native client, about 360 MB in 17 parts, before
anything is on screen. The script ran plain `curl -fsSL` per part: no
timeout, no retry, no progress. A stalled connection could wait for ever
on "downloading Steam: bins_linuxarm64_linuxarm64 (2/17)" (a 110 MB part),
a failed one ended the session and threw away everything fetched, and
the loading screen said "~1-2 min" while counting parts, not bytes.

Parts now go to package/droiddeck-download and stay there until the client
is installed. Each one resumes from the bytes on disk (curl -C -), a
transfer under 4 KB/s for a minute is dropped and resumed, attempts
without progress back off 5-30 s before giving up, and a finished part is
marked unpacked so a later session skips it. Bytes that fail their
checksum are fetched whole again; a server that will not resume starts the
part over; parts left for another client version are dropped. A repair
redoes every part once and keeps what an interrupted repair redid.

Every 5 s the step line carries megabytes overall ("(2/17), 45 of 360
MB"), which the loading screen shows as "45 / 360 MB" with the bar
following the bytes. The session's step no longer promises 1-2 minutes.
2026-10-11 14:45:57 -04:00
304 changed files with 33528 additions and 2211 deletions

No files matched your search

+3
View File
@@ -10,3 +10,6 @@ tools/mangoapp/mangoapp text eol=lf
app/src/main/assets/desktop-removal/*.json text eol=lf
app/src/main/assets/desktop-removal/*.txt text eol=lf
*.pdf binary
third_party/sdlbridge/upstream/** -text
third_party/sdl3/upstream/** -text
third_party/*/patches/*.patch text eol=lf
+1 -1
View File
@@ -467,7 +467,7 @@ jobs:
path: |
app/.cxx
app/build/intermediates/cxx
key: cxx-${{ env.NDK_VERSION }}-${{ hashFiles('app/src/main/cpp/**', 'tools/vr/src/xr_*.h') }}
key: cxx-${{ env.NDK_VERSION }}-${{ hashFiles('app/src/main/cpp/**', 'third_party/sdlbridge/**', 'third_party/sdl3/**', 'tools/prepare_controller_sources.py', 'tools/vr/src/xr_*.h') }}
restore-keys: |
cxx-${{ env.NDK_VERSION }}-
+17 -1
View File
@@ -9,6 +9,20 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
<p align="center">
<a href="https://www.star-history.com/droid-deck/droiddeck"><img src="https://api.star-history.com/badge?repo=Droid-Deck/DroidDeck&type=rank&theme=dark" alt="Star History Rank" /></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/weekly?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/weekly?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
</p>
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
> Note: DroidDeck does not have a stand-alone website. Do not click on any download links from websites claiming to be the DroidDeck team.
@@ -47,7 +61,7 @@ Compatibility and performance vary by device; hardware validation is limited. De
## Credits and licence
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc/<pid>/status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driver in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc/<pid>/status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driver in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). Xbox games load the Windows modules of [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) runtime (LGPL-2.1-or-later), including its `wintypes.dll`, whose `ApiInformation` answer Minecraft for Windows needs to start; how Minecraft installs GameInput under Wine was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinuLine truncated
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
@@ -56,3 +70,5 @@ Joy-Con VR controllers port the arm model of Google's [Google VR SDK for Unity](
Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md).
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead.
Steam's Browse buttons open a GTK 3 file chooser through PyGObject (LGPL-2.1-or-later). It runs under Steam's own `reaper` with Steam's app ID, which [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) reads from the process tree (`GetAppIdFromReaper` in `src/Utils/Process.cpp`) to show it over Steam.
+18 -1
View File
@@ -149,6 +149,7 @@ android {
arguments '-DANDROID_STL=c++_shared'
arguments "-DDROIDDECK_VITURE_SDK_DIR=${vitureSdkDir.toString().replace('\\', '/')}"
arguments "-DDROIDDECK_UVC_DIR=${uvcDir.toString().replace('\\', '/')}"
arguments "-DDROIDDECK_CONTROLLER_SOURCES_DIR=${layout.buildDirectory.dir('controller-sources').get().asFile.absolutePath.replace('\\', '/')}"
}
}
}
@@ -275,7 +276,21 @@ if (uvcDir) {
tasks.named('preBuild').configure { dependsOn(stageUvcNotices) }
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('uvcAssets'))
}
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
def controllerSourcesDir = layout.buildDirectory.dir('controller-sources')
def prepareControllerSources = tasks.register('prepareControllerSources', Exec) {
inputs.dir(rootProject.file('third_party/sdlbridge'))
inputs.dir(rootProject.file('third_party/sdl3'))
inputs.file(rootProject.file('tools/prepare_controller_sources.py'))
outputs.dir(controllerSourcesDir)
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/prepare_controller_sources.py', '--output', controllerSourcesDir.get().asFile.absolutePath
}
android.sourceSets.main.java.srcDir(controllerSourcesDir.map { it.dir('sdlbridge/java') })
android.sourceSets.main.java.srcDir(controllerSourcesDir.map { it.dir('sdl3/java') })
tasks.configureEach { task ->
if (task.name.startsWith('configureCMake')) task.dependsOn(prepareControllerSources)
}
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets, prepareControllerSources) }
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
mustRunAfter(stageSessionScripts, stageRuntimeAssets)
@@ -337,6 +352,8 @@ dependencies {
implementation 'androidx.camera:camera-camera2:1.4.2'
implementation 'androidx.camera:camera-lifecycle:1.4.2'
implementation 'androidx.webkit:webkit:1.12.1'
// Google's WebRTC (BSD) for the native Xbox Cloud Gaming player (XboxNativePlayerActivity).
implementation 'io.github.webrtc-sdk:android:125.6422.07'
implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") {
exclude group: 'com.google.auto.value', module: 'auto-value'
}
+70
View File
@@ -29,11 +29,16 @@
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<uses-feature android:name="android.hardware.vr.headtracking" android:version="1" android:required="false" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-feature android:name="android.hardware.usb.host" android:required="false" />
<application
android:name=".App"
android:localeConfig="@xml/locales_config"
android:networkSecurityConfig="@xml/network_security_config"
android:allowBackup="false"
android:allowAudioPlaybackCapture="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
@@ -151,6 +156,27 @@
android:process=":xboxlogin" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
<activity android:name=".stores.xbox.XboxCloudPlayerActivity" android:exported="false"
android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
android:theme="@style/AppTheme" />
<service android:name=".stores.xbox.XboxCloudTokenService" android:exported="false" />
<activity android:name=".stores.xbox.XboxNativePlayerActivity" android:exported="false"
android:process=":xcloudnative" android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
android:theme="@style/AppTheme" />
<activity android:name=".stores.xbox.XboxCloudActivity" android:exported="false"
android:process=":xboxcloud" android:launchMode="singleTop" android:screenOrientation="sensorLandscape"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
android:theme="@style/AppTheme" />
<activity android:name=".stores.xbox.XboxCloudSettingsActivity" android:exported="false"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
<activity
android:name=".stores.StoreLoginActivity"
android:exported="false"
@@ -234,5 +260,49 @@
android:name="backend:com.google.android.datatransport.cct.CctBackendFactory"
tools:node="remove" />
</service>
<!-- sdl3droiddeck: the SDL3 bridge, built in. SDL3 and the bridge run in their own process (":sdl3"), so a
controller-driver crash can't take the session down; DroidDeck talks to it as to the separate app. -->
<activity
android:name="com.example.dsedge.BridgeActivity"
android:process=":sdl3"
android:exported="false"
android:label="SDL3Bridge"
android:launchMode="singleTop"
android:alwaysRetainTaskState="true"
android:taskAffinity="${applicationId}.sdl3bridge"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:configChanges="layoutDirection|locale|orientation|uiMode|screenLayout|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation" />
<activity
android:name="com.example.dsedge.SdlHostActivity"
android:process=":sdl3"
android:exported="false"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:configChanges="layoutDirection|locale|orientation|uiMode|screenLayout|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation" />
<activity
android:name="com.example.dsedge.UsbAttachActivity"
android:process=":sdl3"
android:exported="true"
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity=""
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/sdl3_device_filter" />
</activity>
<service
android:name="com.example.dsedge.BridgeService"
android:process=":sdl3"
android:exported="false"
android:foregroundServiceType="specialUse">
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="game controller bridge" />
<intent-filter><action android:name="com.example.dsedge.BRIDGE" /></intent-filter>
</service>
</application>
<uses-permission android:name="com.example.dsedge.permission.BRIDGE" />
<queries><package android:name="com.example.dsedge" /></queries>
</manifest>
@@ -0,0 +1,18 @@
Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
+3
View File
@@ -0,0 +1,3 @@
repo=embedded
tag=SdlBridge 63feeac
sdl=3.4.18
+18
View File
@@ -0,0 +1,18 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<style>
html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
#player { position: absolute; inset: 0; }
#status { position: absolute; left: 0; right: 0; bottom: 12%; text-align: center; color: #ddd;
font: 16px sans-serif; text-shadow: 0 0 4px #000; pointer-events: none; }
</style>
</head>
<body>
<div id="player"></div>
<div id="status"></div>
<script src="player.js"></script>
</body>
</html>
+187
View File
@@ -0,0 +1,187 @@
/* DroidDeck Xbox Cloud Gaming player. Includes Greenlight's player (c) UnknownSKL (Jim Kroon), MIT. */
(()=>{var _=class{_player;_dataChannel;constructor(e){this._player=e,this._dataChannel=this._player._peerConnection.createDataChannel(this.getChannelName(),this.getChannelConfig()),this._dataChannel.onopen=this.onOpen.bind(this),this._dataChannel.onmessage=this.onMessage.bind(this),this._dataChannel.onclosing=this.onClosing.bind(this),this._dataChannel.onclose=this.onClose.bind(this),this._dataChannel.onerror=this.onError.bind(this)}getChannelName(){return"channel"}getChannelConfig(){return{}}onOpen(e){console.log(this.getChannelName(),"Opening channel:",e)}onMessage(e){console.log(this.getChannelName(),"Message channel:",e)}onClosing(e){console.log(this.getChannelName(),"Closing channel:",e)}onClose(e){console.log(this.getChannelName(),"Closed channel:",e)}onError(e){console.log(this.getChannelName(),"Error channel:",e)}send(e){if(this._dataChannel.readyState!=="open"){console.log("["+this.getChannelName()+"] Tried to send data while channel is not open. readyState is:",this._dataChannel.readyState);return}return typeof e=="string"&&(e=new TextEncoder().encode(e)),this._dataChannel.send(e)}getPlayer(){return this._player}destroy(){}};var S=class extends _{_micPermissions="prompt";_micStream;constructor(e){super(e),navigator.permissions.query({name:"microphone"}).then(t=>{this._micPermissions=t.state,t.onchange=()=>{this._micPermissions=t.state}})}getChannelName(){return"chat"}getChannelConfig(){return{ordered:!0,protocol:"chatV1"}}destroy(){}};var v=class r{_player;_index;_physicalGamepadId=-1;_rumbleInterval;_isFocused=!0;_gamepadOverride={buttons:{}};_options={enable_keyboard:!1,enable_gamepad:!0,enable_vibration:!0,keyboard_mapping:{A:"Enter",B:"Backspace",X:"x",Y:"y",DPadUp:"ArrowUp",DPadDown:"ArrowDown",DPadLeft:"ArrowLeft",DPadRight:"ArrowRight",LeftShoulder:"[",RightShoulder:"]",LeftThumb:"l",RightThumb:"r",LeftTrigger:"-",RightTrigger:"=",Menu:"m",View:"v",Nexus:"n"},gamepad_mapping:{A:"0",B:"1",X:"2",Y:"3",DPadUp:"12",DPadDown:"13",DPadLeft:"14",DPadRight:"15",LeftShoulder:"4",RightShoulder:"5",LeftThumb:"10",RightThumb:"11",LeftTrigger:"6",RightTrigger:"7",Menu:"9",View:"8",Nexus:"16"},gamepad_axes_mapping:{LeftThumbXAxis:"0",LeftThumbYAxis:"1",RightThumbXAxis:"2",RightThumbYAxis:"3"},gamepad_deadzone:.08,gamepad_force_capture:!1};_listener={keyDown:this.onKeyDown.bind(this),keyUp:this.onKeyUp.bind(this),gamepadConnected:this.onGamepadConnected.bind(this),gamepadDisconnected:this.onGamepadDisconnected.bind(this),windowFocus:this.onWindowFocus.bind(this),windowBlur:this.onWindowBlur.bind(this)};constructor(e,t={}){this._index=e,this._options={...this._options,...t}}attach(e){this._player=e,this._player._channels.control.sendGamepadState(this._index,!0,this),this._options.enable_keyboard===!0&&(window.addEventListener("keydown",this._listener.keyDown),window.addEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.addEventListener("gamepadconnected",this._listener.gamepadConnected),window.addEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.addEventListener("blur",this._listener.windowBlur),window.addEventListener("focus",this._listener.windowFocus)),this.detectActiveGamepad()}detach(){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}this._player._channels.control.sendGamepadState(this._index,!1),this._physicalGamepadId=-1,this._rumbleInterval!==void 0&&clearInterval(this._rumbleInterval),this._options.enable_keyboard===!0&&(window.removeEventListener("keydown",this._listener.keyDown),window.removeEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.removeEventListener("gamepadconnected",this._listener.gamepadConnected),window.removeEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.removeEventListener("blur",this._listener.windowBlur),window.removeEventListener("focus",this._listener.windowFocus))}sendButtonState(e,t){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}if(!(e in this.getDefaultFamepadFrame())){console.log("[Gamepad] Invalid button:",e);return}let n=this.getDefaultFamepadFrame();n.GamepadIndex=this._index,this._gamepadOverride.buttons[e]=t}onKeyDown(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=1,e.preventDefault())}onKeyUp(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=0,e.preventDefault())}onWindowFocus(){this._isFocused=!0}onWindowBlur(){}getDefaultFamepadFrame(){return{GamepadIndex:0,Nexus:0,Menu:0,View:0,A:0,B:0,X:0,Y:0,DPadUp:0,DPadDown:0,DPadLeft:0,DPadRight:0,LeftShoulder:0,Line truncated
`+t.ContentText)?this.completeTransaction(e.id,{Result:0}):this.completeTransaction(e.id,{Result:1})}};var M=class extends _{_handshakeCompleted=!1;getChannelName(){return"message"}getChannelConfig(){return{protocol:"messageV1",ordered:!0}}onOpen(){console.log("[MessageChannel] Sending handshake...");let e=JSON.stringify({type:"Handshake",version:"messageV1",id:"be0bfc6d-1e83-4c8a-90ed-fa8601c5a179",cv:"0"});this.send(e)}onMessage(e){let t=JSON.parse(e.data);switch(t.type){case"HandshakeAck":console.log("[MessageChannel] Handshake completed"),this._handshakeCompleted=!0,this.getPlayer()._channels.control.sendAuthorization(),this.getPlayer()._channels.input.start(),this.sendConfig();break;case"TransactionStart":case"Message":new D(this,t);break;default:console.log("[MessageChannel] Unhandled message type:",t.type,t)}}sendConfig(){let e=[],t=[0,2,0],n=JSON.stringify(this.generateMessage("/streaming/systemUi/configuration",{version:t,systemUis:e}));this.send(n);let i=JSON.stringify(this.generateMessage("/streaming/properties/clientappinstallidchanged",{clientAppInstallId:"c97d7ee0-73b2-4239-bf1d-9d805a338429"}));this.send(i);let a=JSON.stringify(this.generateMessage("/streaming/characteristics/orientationchanged",{orientation:0}));this.send(a);let s=JSON.stringify(this.generateMessage("/streaming/characteristics/touchinputenabledchanged",{touchInputEnabled:!1}));this.send(s);let o=JSON.stringify(this.generateMessage("/streaming/characteristics/clientdevicecapabilities",{}));this.send(o);let d=JSON.stringify(this.generateMessage("/streaming/characteristics/dimensionschanged",{horizontal:1920,vertical:1080,preferredWidth:1920,preferredHeight:1080,safeAreaLeft:0,safeAreaTop:0,safeAreaRight:1920,safeAreaBottom:1080,supportsCustomResolution:!0}));this.send(d)}generateMessage(e,t){return{type:"Message",content:JSON.stringify(t),id:Q(),target:e,cv:""}}destroy(){}};var E=class{_address;_ipv4Address;_ipv4Port;constructor(e){this._address=e;let t=this._address.split(":"),n=t[6]+t[7],i=t[5],a=~parseInt(n.substring(0,2),16)&255,s=~parseInt(n.substring(2,4),16)&255,o=~parseInt(n.substring(4,6),16)&255,d=~parseInt(n.substring(6,8),16)&255,u=~parseInt(i.substring(0,4),16)&65535;this._ipv4Address=a+"."+s+"."+o+"."+d,this._ipv4Port=u}getIpv4Address(){return this._ipv4Address}getIpv4Port(){return this._ipv4Port}};var R=class{_peerConnection;_iceCandidates=[];constructor(e){this._peerConnection=e._peerConnection,this._peerConnection.addEventListener("icecandidate",t=>{t.candidate&&this._iceCandidates.push(t.candidate)})}getCandidates(){return this._iceCandidates}setRemoteCandidates(e){e.length===0&&console.warn("Error: No candidates received!");for(let t in e){if(e[t].candidate==="a=end-of-candidates")continue;let n=e[t].candidate.split(" ");if(n.length>4&&n[4].substr(0,4)==="2001"){let i=new E(n[4]);this._peerConnection.addIceCandidate({candidate:"a=candidate:10 1 UDP 1 "+i.getIpv4Address()+" 9002 typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid}),this._peerConnection.addIceCandidate({candidate:"a=candidate:11 1 UDP 1 "+i.getIpv4Address()+" "+i.getIpv4Port()+" typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid})}this._peerConnection.addIceCandidate({candidate:e[t].candidate,sdpMid:e[t].sdpMid,sdpMLineIndex:e[t].sdpMLineIndex})}}};var I=class{_player;_peerConnection;constructor(e){this._player=e,this._peerConnection=e._peerConnection}getAvailableCodecs(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[];for(let n in e)t.includes(e[n].mimeType)||t.push(e[n].mimeType);return t}setLocalSDP(e){return console.log("[SDP] setLocalSDP() Setting local SDP:",e),e.sdp=e.sdp?.replace("useinbandfec=1","useinbandfec=1; stereo=1"),e}setRemoteSDP(e){return console.log("[SDP] setRemoteSDP() Setting remote SDP:",e),e}getDefaultCodecPreferences(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[],n=[],i=[],a=[];for(let o in e)e[o].mimeType.includes("H264")?e[o].sdpFmtpLine?.includes("profile-level-id=4d")?t.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=42e")?n.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=420")&&i.push(e[o]):(e[o].mimeType.includes("ulpfec")||e[o].mimeType.includes("flexfec")||e[o].mimeType.includes("VP9")||e[o].mimeType.includes("VP8"))&&a.push(e[o]);return[...t,...n,...i,...a]}_setBitrate(e,t,n){let i=e.split(`
`),a=-1;for(let o=0;o<i.length;o++)if(i[o].indexOf("m="+t)===0){a=o;break}if(a===-1)return console.debug("Could not find the m line for",t),e;for(a++;i[a].indexOf("i=")===0||i[a].indexOf("c=")===0;)a++;if(i[a].indexOf("b")===0)return i[a]="b=AS:"+n,i.join(`
`);let s=i.slice(0,a);return s.push("b=AS:"+n),s=s.concat(i.slice(a,i.length)),s.join(`
`)}};var P=class{_player;_peerConnection;_videoCodec="";_audioCodec="";_videoWidth=0;_videoHeight=0;_videoFps=0;_rtt=0;_remoteHost="";_remotePort=0;_remoteIsLocal=!1;_remoteIsIpv6=!1;_activeRemoteCandidate="";constructor(e){this._player=e,this._peerConnection=e._peerConnection,setInterval(this.loop.bind(this),1e3)}loop(){this._peerConnection.getStats().then(e=>{e.forEach(t=>{t.type==="inbound-rtp"?this.readInboundRtp(t):t.type==="candidate-pair"&&t.packetsReceived!==void 0&&t.packetsReceived>0?this.readCandidatePair(t):t.type==="remote-candidate"&&this.readRemoteCandidate(t)})})}readInboundRtp(e){e.kind==="video"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0?(e.codecId.includes("profile-level-id=4d")?this._videoCodec="H264 (High)":e.codecId.includes("profile-level-id=42e")?this._videoCodec="H264 (Normal)":e.codecId.includes("profile-level-id=420")?this._videoCodec="H264 (Low)":this._videoCodec="Other ("+e.codecId+")",e.frameWidth&&(this._videoWidth=e.frameWidth),e.frameHeight&&(this._videoHeight=e.frameHeight),e.framesPerSecond&&(this._videoFps=e.framesPerSecond)):e.kind==="audio"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0&&(this._audioCodec=e.codecId)}readCandidatePair(e){this._activeRemoteCandidate=e.remoteCandidateId,this._rtt=e.currentRoundTripTime}readRemoteCandidate(e){e.id===this._activeRemoteCandidate&&(this.isPrivateIP(e.address)?this._remoteIsLocal=!0:this._remoteIsLocal=!1,this.isIpv6(e.address)?this._remoteIsIpv6=!0:this._remoteIsIpv6=!1,this._remoteHost=e.address,this._remotePort=e.port)}isPrivateIP(e){let t=e.split(".");return t[0]==="10"||t[0]==="172"&&parseInt(t[1],10)>=16&&parseInt(t[1],10)<=31||t[0]==="192"&&t[1]==="168"}isIpv6(e){return e.split(":").length>3}};var G=class{_player;_videoComponent;_overlays={debug:void 0};constructor(e,t){this._videoComponent=e,this._player=t}toggleDebug(){this._overlays.debug===void 0?this.createDebugOverlay():this.destroy()}createDebugOverlay(){this._overlays.debug=document.createElement("div"),this._overlays.debug.id="playerDebugOverlay",this._overlays.debug.style.position="absolute",this._overlays.debug.style.top="0",this._overlays.debug.style.left="0",this._overlays.debug.style.width=this._videoComponent.getElement()?.style.width||"100%",this._overlays.debug.style.height=this._videoComponent.getElement()?.style.height||"auto",this._overlays.debug.style.background="linear-gradient(0deg, rgba(0,0,0, 0) 0%, rgba(0,0,0, 0) 75%, rgba(0,0,0, 0.5) 100%)",this._overlays.debug.style.padding="10px",this._overlays.debug.style.pointerEvents="none",document.getElementById(this._player.getElementId())?.appendChild(this._overlays.debug),setTimeout(()=>{this.refreshDebugOverlay()},500),this.refreshDebugOverlay()}destroy(){this._overlays.debug?.remove(),this._overlays.debug=void 0}refreshDebugOverlay(){if(this._overlays.debug!==void 0){this._overlays.debug.innerHTML="",this._overlays.debug.appendChild(this.createLabel("Local Play",this._player.getStats()._remoteIsLocal?"Local":"Remote","ok")),this._overlays.debug.appendChild(this.createLabel("Resolution",this._player.getStats()._videoWidth+"x"+this._player.getStats()._videoHeight,"ok")),this._overlays.debug.appendChild(this.createLabel("Stream FPS",this._player.getStats()._videoFps.toString(),this._player.getStats()._videoFps>=58?"ok":"warning"));let e=this._videoComponent.getFrameStats?.();e&&(this._overlays.debug.appendChild(this.createLabel("Render FPS",e.renderingFps.toString(),e.renderingFps>=58?"ok":"warning")),this._overlays.debug.appendChild(this.createLabel("Render Delay",e.renderDelayMs.toString()+" ms",e.renderDelayMs<16?"ok":e.renderDelayMs<33?"warning":"error")),this._overlays.debug.appendChild(this.createLabel("Dropped Frames",e.droppedFrames.toString(),e.droppedFrames===0?"ok":e.droppedFrames<30?"warning":"error"))),this._overlays.debug.appendChild(this.createLabel("Connection",this._player.getStats()._remoteIsIpv6?"IPv6":"IPv4","ok")),this._overlays.debug.appendChild(this.createLabel("Video",this._player.getStats()._videoCodec,"ok"));let t=this._player.getStats()._rtt*1e3>75?"error":this._player.getStats()._rtt*1e3>40?"warning":"ok";this._overlays.debug.appendChild(this.createLabel("RTT",(this._player.getStats()._rtt*1e3).toString()+" ms",t)),setTimeout(()=>{this.refreshDebugOverlay()},500)}}createLabel(e,t="",n=""){let i={borderRadius:"5px",background:"linear-gradient(0deg, rgba(28,26,26,1) 0%, rgba(47,45,45,1) 100%)",padding:"10px",fontSize:"12px",marginTop:"3px",marginRight:"10px",marginBottom:"2px",textTransform:"uppercase",color:"white",display:"inline-block"},a=document.createElement("span"),s={error:"rgb(220, 53, 69)",warning:"rgb(255, 193, 7)",ok:"rgb(25, 135, 84)"};t!==""?a.innerHTML=`${e}: <span style="background: ${s[n]}; border-radius: 5px; padding: 4px; padding-left: 8px; padding-right: 8px;">${t}</span>`:a.innerText=e;for(let o in i)a.style[o]=i[o];return a}};var L=class{_player;_element;_overlay;constructor(e){this._player=e,this._overlay=new G(this,this._pLine truncated
in vec2 position;
out vec2 vUV;
void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,j=`attribute vec2 position;
varying vec2 vUV;
void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,Z=`#version 300 es
precision mediump float;
uniform sampler2D screenTexture;
uniform vec2 resolution;
uniform int filterId;
uniform float sharpenFactor;
uniform float brightness;
uniform float contrast;
uniform float gamma;
uniform float saturation;
uniform float deband;
out vec4 fragColor;
const float CAS_CONTRAST_PEAK = 0.8 * -3.0 + 8.0;
vec3 sharpen(vec2 coord, vec3 e) {
vec2 px = 1.0 / resolution;
vec3 b = texture(screenTexture, coord + px * vec2(0, 1)).rgb;
vec3 d = texture(screenTexture, coord + px * vec2(-1, 0)).rgb;
vec3 f = texture(screenTexture, coord + px * vec2(1, 0)).rgb;
vec3 h = texture(screenTexture, coord + px * vec2(0, -1)).rgb;
vec3 a = texture(screenTexture, coord + px * vec2(-1, 1)).rgb;
vec3 c = texture(screenTexture, coord + px * vec2(1, 1)).rgb;
vec3 g = texture(screenTexture, coord + px * vec2(-1, -1)).rgb;
vec3 i = texture(screenTexture, coord + px * vec2(1, -1)).rgb;
if (filterId == 1) {
vec3 blur = ((a + c + g + i) + (b + d + f + h) * 2.0 + e * 4.0) / 16.0;
return e + (e - blur) * sharpenFactor / 3.0;
}
vec3 minRgb = min(min(min(d, e), min(f, b)), h) + min(min(a, c), min(g, i));
vec3 maxRgb = max(max(max(d, e), max(f, b)), h) + max(max(a, c), max(g, i));
vec3 amplify = inversesqrt(clamp(min(minRgb, 2.0 - maxRgb) / maxRgb, 0.0, 1.0));
vec3 weight = -(1.0 / (amplify * CAS_CONTRAST_PEAK));
vec3 outColor = clamp(((b + d + f + h) * weight + e) / (4.0 * weight + 1.0), 0.0, 1.0);
return mix(e, outColor, sharpenFactor / 2.0);
}
float ign(vec2 p) { return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
void main() {
vec2 uv = gl_FragCoord.xy / resolution;
vec3 color = texture(screenTexture, uv).rgb;
if (sharpenFactor > 0.0) color = sharpen(uv, color);
color = clamp(color + brightness, 0.0, 1.0);
color = (color - 0.5) * clamp(contrast + 1.0, 0.5, 2.0) + 0.5;
color = mix(vec3(dot(color, vec3(0.2126, 0.7152, 0.0722))), color, saturation);
color = pow(max(color, 0.0), vec3(1.0 / gamma));
if (deband > 0.0) color += vec3(((ign(gl_FragCoord.xy) + ign(gl_FragCoord.xy + vec2(11.0, 17.0))) - 1.0) * (deband / 255.0));
fragColor = vec4(color, 1.0);
}`,ee=`precision highp float;
#define FXAA_MIN_REDUCE (1.0 / 128.0)
#define FXAA_MUL_REDUCE (1.0 / 8.0)
#define MAX_SPAN 8.0
uniform sampler2D screenTexture;
uniform vec2 resolution;
const vec3 luma = vec3(0.299, 0.587, 0.114);
void main() {
vec2 invResolution = 1.0 / resolution;
vec3 rgbNW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, -1.0)) * invResolution).rgb;
vec3 rgbNE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, -1.0)) * invResolution).rgb;
vec3 rgbSW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, 1.0)) * invResolution).rgb;
vec3 rgbSE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, 1.0)) * invResolution).rgb;
vec3 rgbM = texture2D(screenTexture, gl_FragCoord.xy * invResolution).rgb;
float lumaNW = dot(rgbNW, luma);
float lumaNE = dot(rgbNE, luma);
float lumaSW = dot(rgbSW, luma);
float lumaSE = dot(rgbSE, luma);
float lumaM = dot(rgbM, luma);
float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
vec2 dir;
dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));
float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * 0.25 * FXAA_MUL_REDUCE, FXAA_MIN_REDUCE);
float minDirFactor = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
dir = clamp(dir * minDirFactor, vec2(-MAX_SPAN), vec2(MAX_SPAN)) * invResolution;
vec4 rgbA = 0.5 * (
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (1.0 / 3.0 - 0.5)) +
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (2.0 / 3.0 - 0.5)));
vec4 rgbB = rgbA * 0.5 + 0.25 * (
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * -0.5) +
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * 0.5));
float lumaB = dot(rgbB, vec4(luma, 0.0));
gl_FragColor = lumaB < lumaMin || lumaB > lumaMax ? rgbA : rgbB;
}`,te=`precision highp float;
uniform sampler2D screenTexture;
uniform vec2 resolution;
void main() {
vec2 uv = gl_FragCoord.xy / resolution;
float edgeThreshold = 0.2;
vec2 offset = vec2(1.0) / resolution;
vec3 colorCenter = texture2D(screenTexture, uv).rgb;
vec3 colorLeft = texture2D(screenTexture, uv - vec2(offset.x, 0.0)).rgb;
vec3 colorRight = texture2D(screenTexture, uv + vec2(offset.x, 0.0)).rgb;
vec3 colorUp = texture2D(screenTexture, uv - vec2(0.0, offset.y)).rgb;
vec3 colorDown = texture2D(screenTexture, uv + vec2(0.0, offset.y)).rgb;
float diffHorizontal = length(colorRight - colorLeft);
float diffVertical = length(colorUp - colorDown);
float edgeFactor = step(edgeThreshold, diffHorizontal + diffVertical);
vec3 outlineColor = mix(colorCenter, vec3(0.0), edgeFactor);
gl_FragColor = vec4(outlineColor, 1.0);
}`,ne=`precision highp float;
#define CA_AMOUNT 1.0025
#define SCANLINE_INTENSITY_X 0.125
#define SCANLINE_INTENSITY_Y 0.375
#define SCANLINE_SIZE 1024.0
uniform sampler2D screenTexture;
varying vec2 vUV;
void main() {
vec4 finalColor = texture2D(screenTexture, vUV);
finalColor.rgb = vec3(
texture2D(screenTexture, (vUV - 0.5) * CA_AMOUNT + 0.5).r,
finalColor.g,
texture2D(screenTexture, (vUV - 0.5) / CA_AMOUNT + 0.5).b
);
float scanlineX = abs(sin(vUV.x * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_X);
float scanlineY = abs(sin(vUV.y * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_Y);
gl_FragColor = vec4(mix(finalColor.rgb, vec3(0.0), scanlineX + scanlineY), finalColor.a);
}`,ie=`precision highp float;
#define PI 3.14159265
#define SCANLINE_INTENSITY 0.35
#define CHROMA_OFFSET 0.005
#define BLUR_RADIUS 0.002
#define WARP_AMOUNT 0.01
#define SCANLINE_DARKEN 0.5
uniform sampler2D screenTexture;
uniform int FrameCount;
uniform vec2 TextureSize;
uniform vec2 resolution;
varying vec2 vUV;
const mat3 yiq_mat = mat3(
0.299, 0.587, 0.114,
0.596, -0.275, -0.321,
0.212, -0.523, 0.311
);
const mat3 yiq2rgb_mat = mat3(
1.0, 0.956, 0.621,
1.0, -0.272, -0.647,
1.0, -1.106, 1.705
);
vec3 applyNTSC(vec2 uv) {
vec3 col = texture2D(screenTexture, uv).rgb;
vec3 yiq = col * yiq_mat;
float chromaPhase = PI * (mod(uv.y * TextureSize.y, 2.0) + float(FrameCount));
yiq.y *= cos(chromaPhase * 0.5);
yiq.z *= sin(chromaPhase * 0.5);
vec3 rgb = yiq * yiq2rgb_mat;
vec3 finalColor;
finalColor.r = texture2D(screenTexture, uv + vec2(CHROMA_OFFSET, 0.0)).r;
finalColor.g = texture2D(screenTexture, uv + vec2(0.0, BLUR_RADIUS)).g;
finalColor.b = texture2D(screenTexture, uv - vec2(CHROMA_OFFSET, 0.0)).b;
return finalColor;
}
vec3 applyScanlines(vec2 uv) {
vec3 col = texture2D(screenTexture, uv).rgb;
float scanline = abs(sin(uv.y * resolution.y * 2.0)) * SCANLINE_INTENSITY;
col *= 1.0 - (scanline * SCANLINE_DARKEN);
return col;
}
vec2 applyWarp(vec2 uv) {
uv = uv * 2.0 - 1.0;
float r = sqrt(uv.x * uv.x + uv.y * uv.y);
uv += uv * (r * r) * WARP_AMOUNT;
return uv * 0.5 + 0.5;
}
void main() {
vec2 warpedUV = applyWarp(vUV);
vec3 ntscColor = applyNTSC(warpedUV);
vec3 scanlineColor = applyScanlines(warpedUV);
vec3 finalColor = mix(ntscColor, scanlineColor, 0.7);
gl_FragColor = vec4(finalColor, 1.0);
}`,H=class{constructor(e,t){this.video=e;this.effects=t;this.canvas=document.createElement("canvas"),Object.assign(this.canvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"contain",zIndex:"1"}),e.parentElement?.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,desynchronized:!0,powerPreference:"high-performance"});if(n===null)throw new Error("WebGL2 unavailable");this.gl=n;let i=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,i),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),n.STATIC_DRAW),this.passes.set("base",this.compile(J,Z,["screenTexture","resolution","filterId","sharpenFactor","brightness","contrast","gamma","saturation","deband"])),this.videoTexture=this.texture(),this.schedule()}canvas;gl;passes=new Map;videoTexture;targets=[];width=0;height=0;frame=0;lastDraw=0;stopped=!1;idle=!1;pending=!1;update(e){this.effects=e}pause(){this.idle||this.stopped||(this.idle=!0,this.canvas.style.display="none")}resume(e){this.effects=e,!(!this.idle||this.stopped)&&(this.idle=!1,this.canvas.style.display="",this.schedule())}schedule(){this.pending||(this.pending=!0,this.video.requestVideoFrameCallback(this.onFrame))}compile(e,t,n){let i=this.gl,a=(o,d)=>{let u=i.createShader(o);if(i.shaderSource(u,d),i.compileShader(u),!i.getShaderParameter(u,i.COMPILE_STATUS))throw new Error(`shader: ${i.getShaderInfoLog(u)}`);return u},s=i.createProgram();if(i.attachShader(s,a(i.VERTEX_SHADER,e)),i.attachShader(s,a(i.FRAGMENT_SHADER,t)),i.bindAttribLocation(s,0,"position"),i.linkProgram(s),!i.getProgramParameter(s,i.LINK_STATUS))throw new Error(`program: ${i.getProgramInfoLog(s)}`);return{program:s,uniforms:new Map(n.map(o=>[o,i.getUniformLocation(s,o)]))}}extra(e){let t=this.passes.get(e);if(t===void 0){let n={fxaa:ee,toon:te,crt:ne,ntsc:ie}[e];t=this.compile(j,n,["screenTexture","resolution","TextureSize","FrameCount"]),this.passes.set(e,t)}return t}texture(){let e=this.gl,t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t}resize(e,t){let n=this.gl;this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t;for(let i of this.targets)n.deleteFramebuffer(i.framebuffer),n.deleteTexture(i.texture);this.targets=[0,1].map(()=>{let i=this.texture();n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null);let a=n.createFramebuffer();return n.bindFramebuffer(n.FRAMEBUFFER,a),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0),{framebuffer:a,texture:i}}),n.bindFramebuffer(n.FRAMEBUFFER,null)}onFrame=e=>{if(this.pending=!1,this.stopped||this.idle)return;this.schedule();let t=this.effects.maxFps;if(!(t>0&&e-this.lastDraw<1e3/t-2)){this.lastDraw=e;try{this.draw()}catch(n){window.DDCloud?.log(`effects: ${String(n).slice(0,200)}`),this.destroy()}}};draw(){let e=this.gl,t=this.effects,n=this.video.videoWidth,i=this.video.videoHeight;if(n===0||i===0)return;(n!==this.width||i!==this.height)&&this.resize(n,i),this.frame++,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.videoTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.video);let a=["fxaa","toon","crt","ntsc"].filter(d=>t[d]);e.viewport(0,0,n,i),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0);let s=this.passes.get("base");e.bindFramebuffer(e.FRAMEBUFFER,a.length>0?this.targets[0].framebuffer:null),e.useProgram(s.program);let o=s.uniforms;e.uniform1i(o.get("screenTexture"),0),e.uniform2f(o.get("resolution"),n,i),e.uniform1i(o.get("filterId"),t.sharpenMode==="usm"?1:2),e.uniform1f(o.get("sharpenFactor"),t.sharpen),e.uniform1f(o.get("brightness"),t.brightness/100),e.uniform1f(o.get("contrast"),t.contrast/100),e.uniform1f(o.get("gamma"),Math.min(5,Math.max(.1,t.gamma))),e.uniform1f(o.get("saturation"),t.saturation/100),e.uniform1f(o.get("deband"),t.deband),e.drawArrays(e.TRIANGLES,0,3),a.forEach((d,u)=>{let h=this.extra(d),g=this.targets[u%2],p=u===a.length-1;e.bindFramebuffer(e.FRAMEBUFFER,p?null:this.targets[(u+1)%2].framebuffer),e.useProgram(h.program),e.bindTexture(e.TEXTURE_2D,g.texture);let c=h.uniforms;e.uniform1i(c.get("screenTexture")??null,0),e.uniform2f(c.get("resolution")??null,n,i),e.uniform2f(c.get("TextureSize")??null,n,i),e.uniform1i(c.get("FrameCount")??null,this.frame),e.drawArrays(e.TRIANGLES,0,3)})}destroy(){this.stopped=!0,this.canvas.remove(),this.gl.getExtension("WEBGL_lose_context")?.loseContext()}};var V=class{constructor(e){this.pc=e;this.element=document.createElement("div"),Object.assign(this.element.style,{position:"absolute",top:"8px",right:"8px",zIndex:"3",padding:"4px 8px",borderRadius:"6px",background:"rgba(0,0,0,0.55)",color:"#e8e8e8",font:"12px monospace",lineHeight:"16px",pointerEvent Line truncated
`:" \xB7 ")}destroy(){this.show(0,this.vertical,this.server,this.left),this.element.remove()}};function z(r,e){let t=e==="high"?"4d":e==="low"?"420":"42e",n=[];for(let d of r.matchAll(/a=fmtp:(\d+).*profile-level-id=([0-9a-f]{6})/g))d[2].startsWith(t)&&n.push(d[1]);if(n.length===0)return r;let i=r.split(`\r
`),a=i.findIndex(d=>d.startsWith("m=video"));if(a<0)return r;let s=i[a].trim().split(" "),o=s.slice(3).filter(d=>!n.includes(d));return i[a]=s.slice(0,3).concat(n,o).join(" "),i.join(`\r
`)}function K(r,e){let t=r.split(`\r
`),n=t.findIndex(a=>a.startsWith("m=video"));if(n<0)return r;let i=`b=AS:${e}`;for(let a=n+1;a<=t.length;a++){let s=t[a];if(s===void 0||s.startsWith("m=")){t.splice(a,0,i);break}if(!(s.startsWith("i=")||s.startsWith("c="))){if(s.startsWith("b=AS:")){t[a]=i;break}t.splice(a,0,i);break}}return t.join(`\r
`)}var m=JSON.parse(DDCloud.settings()),ae=RTCPeerConnection.prototype.setLocalDescription;RTCPeerConnection.prototype.setLocalDescription=function(r){return r?.sdp&&((m.codec==="high"||m.codec==="normal"||m.codec==="low")&&(r.sdp=z(r.sdp,m.codec)),m.bitrateMbps>0&&(r.sdp=K(r.sdp,m.bitrateMbps*1e3))),ae.call(this,r)};window.__ddRumble=m.rumble/100;window.addEventListener("error",r=>DDCloud.log(`error: ${r.message} @${r.lineno}`));window.addEventListener("unhandledrejection",r=>DDCloud.log(`rejection: ${String(r.reason).slice(0,200)}`));window.addEventListener("gamepadconnected",r=>DDCloud.log(`controller: ${r.gamepad.id.slice(0,60)} mapping=${r.gamepad.mapping||"none"} buttons=${r.gamepad.buttons.length} axes=${r.gamepad.axes.length}`));var W=new Map,re=1;window.__ddResolve=(r,e,t)=>{let n=W.get(r);W.delete(r),n&&n({status:e,body:t})};function C(r,e=""){return new Promise(t=>{let n=re++;W.set(n,t),DDCloud.call(n,r,typeof e=="string"?e:JSON.stringify(e))})}var B=r=>new Promise(e=>setTimeout(e,r)),se=r=>r.status>=200&&r.status<300;function x(r){let e=document.getElementById("status");e&&(e.textContent=r),DDCloud.status(r)}var T=class extends Error{constructor(t,n){super(t);this.stage=t;this.detail=n}};function k(r,e){if(!se(e))throw new T(r,`${e.status} ${e.body.slice(0,300)}`);return e}function oe(r,e){return new Promise(t=>{if(r.iceGatheringState==="complete")return t();let n=setTimeout(t,e);r.addEventListener("icegatheringstatechange",()=>{r.iceGatheringState==="complete"&&(clearTimeout(n),t())})})}async function de(){x("Starting the game on Xbox Cloud Gaming\u2026"),k("start",await C("start"));let r=!1,e=0;for(;;){let l=k("state",await C("state")),f=JSON.parse(l.body||"{}");if(f.state==="Provisioned")break;if(f.state==="Failed")throw new T("provision",JSON.stringify(f.errorDetails??{}).slice(0,300));f.state==="ReadyToConnect"&&!r?(r=!0,x("Signing in to the cloud console\u2026"),k("connect",await C("connect"))):f.state==="WaitingForResources"?x(`In the queue for a cloud console\u2026 ${Math.round(e/1e3)} s`):x(`Getting a cloud console ready\u2026 ${Math.round(e/1e3)} s`),await B(1e3),e+=1e3}x("Connecting\u2026");let t=new U("player");t.init();let n=t._peerConnection,i=t._channels.input,a=i.queueMetadataFrame.bind(i);i.queueMetadataFrame=l=>{if(m.preventDrops){let f=l.frameRenderedTimeMs-l.frameDecodedTimeMs;l.frameDecodedTimeMs=l.frameSubmittedTimeMs+10,l.frameRenderedTimeMs=l.frameDecodedTimeMs+f}a(l)};let s,o,d=()=>{if(!(o===void 0||s===void 0&&m.volume===100)){if(s===void 0){let l=new AudioContext;s=l.createGain(),l.createMediaStreamSource(o).connect(s).connect(l.destination);let f=document.querySelector("#player audio");f&&(f.muted=!0)}s.gain.value=m.volume/100}};n.addEventListener("track",l=>{l.track.kind==="audio"&&(o=l.streams[0],d())});let u=new V(n),h,g=()=>{let l=t.getVideoElement();if(l!==void 0){if(!X(m)){h?.pause();return}if(h===void 0)try{h=new H(l,m)}catch(f){DDCloud.log(`effects unavailable: ${String(f).slice(0,200)}`)}else h.resume(m)}};window.__ddApply=l=>{m=JSON.parse(l),window.__ddRumble=m.rumble/100,u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),d(),g()},n.addEventListener("connectionstatechange",()=>{n.connectionState==="connected"?(x(""),DDCloud.playing(),u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),setTimeout(g,500)):n.connectionState==="failed"?DDCloud.failed("webrtc","connection failed"):n.connectionState==="disconnected"&&x("Connection lost\u2026")});let p=await t.createOffer(),c=k("sdp",await C("sdp",p.sdp??"")),O=JSON.parse(JSON.parse(c.body).exchangeResponse);if(O.status&&O.status!=="success")throw new T("sdp-answer",JSON.stringify(O).slice(0,300));await t.setRemoteSDP(O.sdp),await oe(n,3e3);let Y=(await t.getICECandidates()).map(l=>JSON.stringify({candidate:l.candidate,sdpMid:l.sdpMid,sdpMLineIndex:l.sdpMLineIndex,usernameFragment:l.usernameFragment})),$=k("ice",await C("ice",Y));t.setRemoteIceCandidates(JSON.parse(JSON.parse($.body).exchangeResponse));let q=Date.now();for(;!t._channels.message._handshakeCompleted&&Date.now()-q<2e4;)await B(100);DDCloud.log(`handshake ${t._channels.message._handshakeCompleted?"done":"missing"} after ${Date.now()-q} ms`),await B(300);let b=new v(0,{enable_keyboard:!1});b.attach(t),DDCloud.log(`controllers at attach: ${Array.from(navigator.getGamepads()).filter(Boolean).length}`),window.__ddNexus=()=>{b.sendButtonState("Nexus",1),setTimeout(()=>b.sendButtonState("Nexus",0),200)},window.__ddButton=(l,f)=>b.sendButtonState(l,f),window.__ddInput=l=>{l?b.onWindowFocus():b.onWindowBlur()},setInterval(()=>{C("keepalive")},3e4),window.__ddStop=()=>{try{h?.destroy(),u.destroy(),b.detach(),t.destroy()}catch{}}}de().catch(r=>{r instanceof T?DDCloud.failed(r.stage,r.detail):DDCloud.failed("page",String(r).slice(0,300))});})();
+2
View File
@@ -63,3 +63,5 @@ if(DROIDDECK_UVC_DIR)
target_link_libraries(droiddeck_uvc PRIVATE rgb_uvc rgb_usb log)
target_link_options(droiddeck_uvc PRIVATE -Wl,-z,max-page-size=16384)
endif()
add_subdirectory(sdl3bridge)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,26 @@
set(SDL_SHARED ON CACHE BOOL "" FORCE)
set(SDL_STATIC OFF CACHE BOOL "" FORCE)
set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE)
set(SDL_TESTS OFF CACHE BOOL "" FORCE)
set(SDL_EXAMPLES OFF CACHE BOOL "" FORCE)
set(SDL_ANDROID_JAR OFF CACHE BOOL "" FORCE)
set(SDL_INSTALL OFF CACHE BOOL "" FORCE)
# The bridge draws nothing (SDL3 runs headless for controllers): no OpenGL ES, so libSDL3.so needs no libGLESv1_CM.so,
# which DroidDeck's APK check (tools/release/check_android_libraries.py) does not count as a system library.
set(SDL_OPENGLES OFF CACHE BOOL "" FORCE)
include(FetchContent)
if(POLICY CMP0135)
cmake_policy(SET CMP0135 NEW)
endif()
set(SDL3_MANIFEST "${DROIDDECK_CONTROLLER_SOURCES_DIR}/sdl3/upstream.json")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${SDL3_MANIFEST}")
file(READ "${SDL3_MANIFEST}" SDL3_UPSTREAM)
string(JSON SDL3_ARCHIVE GET "${SDL3_UPSTREAM}" source archive)
string(JSON SDL3_SHA256 GET "${SDL3_UPSTREAM}" source sha256)
FetchContent_Declare(sdl3
URL "${SDL3_ARCHIVE}"
URL_HASH "SHA256=${SDL3_SHA256}"
)
FetchContent_MakeAvailable(sdl3)
add_library(main SHARED "${DROIDDECK_CONTROLLER_SOURCES_DIR}/sdlbridge/native/main.c")
target_link_libraries(main PRIVATE SDL3::SDL3 log)
@@ -95,4 +95,5 @@ target_link_libraries(droiddeckwayland
dl
log
android
nativewindow
)
+124 -3
View File
@@ -16,6 +16,7 @@
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <android/log.h>
#include <android/hardware_buffer.h>
#include <wayland-server.h>
#include "xdg-shell-server-protocol.h"
@@ -808,10 +809,14 @@ static uint32_t nominal_refresh_ns(void) {
}
static int64_t presented_ns(int64_t render_ns) {
if (!g_tick_vsync_ns || render_ns - g_last_vsync_ns > (int64_t)nominal_refresh_ns() ||
render_ns < g_tick_vsync_ns)
int64_t tick = g_tick_vsync_ns;
int64_t refresh = (int64_t)nominal_refresh_ns();
if (!tick || render_ns - g_last_vsync_ns > refresh)
return render_ns;
return g_tick_vsync_ns;
int64_t delta = render_ns - tick;
if (delta > refresh || -delta > refresh)
return render_ns;
return tick;
}
static void feedback_present_all(struct wl_list *list, int64_t t) {
@@ -1841,7 +1846,121 @@ static void hdr_count_copied(const struct draw_list *dl, const char *reason) {
}
}
/*
* Stream mode (the Xbox Cloud Gaming native player, in its own process): no Wayland clients, the scene is one
* picture handed over as AHardwareBuffers (ImageReader images of the decoded video). Each buffer is imported once
* and kept while the reader cycles through its few buffers; the newest frame is the scene, so the screen effects
* and frame generation apply to it as to a game.
*/
#define STREAM_SLOTS 6
static pthread_mutex_t g_stream_lock = PTHREAD_MUTEX_INITIALIZER;
static atomic_int g_stream_on;
static AHardwareBuffer *g_stream_pending;
static struct { AHardwareBuffer *ahb; struct vkp_image *img; uint64_t used; } g_stream_slots[STREAM_SLOTS];
static struct vkp_image *g_stream_img;
static uint64_t g_stream_seq;
static atomic_uint g_stream_frames;
static void stream_forget_all(void) {
vkp_wait_idle();
for (int i = 0; i < STREAM_SLOTS; i++) {
if (g_stream_slots[i].img) vkp_image_destroy(g_stream_slots[i].img);
if (g_stream_slots[i].ahb) AHardwareBuffer_release(g_stream_slots[i].ahb);
g_stream_slots[i].img = NULL; g_stream_slots[i].ahb = NULL; g_stream_slots[i].used = 0;
}
g_stream_img = NULL;
}
/* Compositor thread: the newest handed-over buffer becomes the scene picture. */
static void stream_take(void) {
pthread_mutex_lock(&g_stream_lock);
AHardwareBuffer *ahb = g_stream_pending;
g_stream_pending = NULL;
pthread_mutex_unlock(&g_stream_lock);
if (!ahb) return;
if (!atomic_load(&g_stream_on)) { AHardwareBuffer_release(ahb); return; }
int slot = -1, oldest = 0;
for (int i = 0; i < STREAM_SLOTS; i++) {
if (g_stream_slots[i].ahb == ahb) { slot = i; break; }
if (g_stream_slots[i].used < g_stream_slots[oldest].used) oldest = i;
}
if (slot >= 0) {
AHardwareBuffer_release(ahb); /* the slot keeps its own reference */
} else {
struct vkp_image *img = vkp_image_from_ahb(ahb);
if (!img) {
static int said;
if (!said) { said = 1; droiddeck_log("stream", "a decoded frame could not be imported: nothing to show"); }
AHardwareBuffer_release(ahb);
return;
}
droiddeck_log("stream", "decoded frame buffer imported (%dx%d)", vkp_image_width(img), vkp_image_height(img));
slot = oldest;
if (g_stream_slots[slot].img) {
vkp_wait_idle(); /* the GPU may still read the picture being replaced */
if (g_stream_img == g_stream_slots[slot].img) g_stream_img = NULL;
vkp_image_destroy(g_stream_slots[slot].img);
}
if (g_stream_slots[slot].ahb) AHardwareBuffer_release(g_stream_slots[slot].ahb);
g_stream_slots[slot].ahb = ahb;
g_stream_slots[slot].img = img;
}
g_stream_slots[slot].used = ++g_stream_seq;
g_stream_img = g_stream_slots[slot].img;
atomic_fetch_add(&g_stream_frames, 1);
schedule_render();
}
static void render_stream(void) {
g_dirty = 0;
struct vkp_image *img = g_stream_img;
if (!img) return;
int w = vkp_image_width(img), h = vkp_image_height(img);
if (w != g_scene_w || h != g_scene_h) {
droiddeck_log("stream", "picture %dx%d", w, h);
g_scene_w = w;
g_scene_h = h;
}
struct vkp_draw d = {.img = img, .sx = 0, .sy = 0, .sw = (float)w, .sh = (float)h, .dx = 0, .dy = 0, .dw = w, .dh = h, .blend = 0};
vkp_apply_window_request();
sc_layer_hide();
int r = vkp_render(w, h, &d, 1);
if (r == 0) {
g_stat_frames++;
static int first;
if (!first) { first = 1; droiddeck_log("stream", "first stream frame presented"); }
} else {
static int failed;
if (failed++ % 600 == 0) droiddeck_log("stream", "presenting a stream frame failed (%d, %d times)", r, failed);
}
}
void droiddeck_stream_set(int on) {
atomic_store(&g_stream_on, on ? 1 : 0);
if (g_input_pipe[1] < 0) return;
struct input_msg m = { 21, on ? 1 : 0, 0, 0, 0 };
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
(void)n;
}
/* Any thread: hands over one decoded frame (acquires its own reference). */
void droiddeck_stream_frame(AHardwareBuffer *ahb) {
if (!ahb || !atomic_load(&g_stream_on) || g_input_pipe[1] < 0) return;
AHardwareBuffer_acquire(ahb);
pthread_mutex_lock(&g_stream_lock);
AHardwareBuffer *dropped = g_stream_pending;
g_stream_pending = ahb;
pthread_mutex_unlock(&g_stream_lock);
if (dropped) { AHardwareBuffer_release(dropped); return; } /* a wake-up is already queued */
struct input_msg m = { 20, 0, 0, 0, 0 };
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
(void)n;
}
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; }
struct draw_list dl = {0};
struct surface *s;
int w, h;
@@ -3001,6 +3120,8 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
break;
case 10: break;
case 11: axis_event(m.p1, m.p2); break;
case 20: stream_take(); break;
case 21: if (!m.p1) stream_forget_all(); schedule_render(); break;
default: deliver_pointer(&m); break;
}
}
+1 -1
View File
@@ -21,7 +21,7 @@
X(BindImageMemory) X(DestroyImage) X(FreeMemory) X(AcquireNextImageKHR) \
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) \
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
\
X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \
+72 -7
View File
@@ -19,6 +19,7 @@
#include <time.h>
#include <pthread.h>
#include <android/log.h>
#include <android/hardware_buffer.h>
#define TAG "DroidDeckWayland"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
@@ -39,6 +40,7 @@ struct vkp_image {
};
static ANativeWindow *g_window;
static int g_ahb_import;
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
static int g_dev_state;
static VkInstance g_inst;
@@ -459,17 +461,19 @@ static int dev_init(void) {
}
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
"VK_KHR_image_format_list", NULL, NULL};
uint32_t n_dev_exts = 5;
static const char *const import_exts[4] = {"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf",
"VK_EXT_image_drm_format_modifier", "VK_KHR_image_format_list"};
const char *dev_exts[9] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
uint32_t n_dev_exts = 1;
uint32_t ne = 0;
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
for (unsigned i = 0; i < 5; i++)
if (!has_ext(exts, ne, dev_exts[i]))
LOGE("present: driver MISSING %s (dmabuf import will fail)", dev_exts[i]);
/* Only what the driver has: the system driver lacks the dma-buf ones, which the cloud player never needs. */
for (unsigned i = 0; i < 4; i++) {
if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
}
int want_hdr_md = 0;
if (droiddeck_color_requested()) {
want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME);
@@ -477,6 +481,13 @@ static int dev_init(void) {
}
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
/* The cloud player's decoded frames arrive as AHardwareBuffers (vkp_image_from_ahb). */
g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
if (g_ahb_import) {
dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
}
free(exts);
float prio = 1.0f;
@@ -987,6 +998,60 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
return img;
}
void vkp_wait_idle(void) {
if (g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
}
struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
if (!ahb || dev_init() != 0) return NULL;
if (!g_ahb_import || !g_vk.GetAndroidHardwareBufferPropertiesANDROID) {
static int said;
if (!said) { said = 1; LOGE("ahb: the driver cannot import AHardwareBuffers (VK_ANDROID_external_memory_android_hardware_buffer)"); }
return NULL;
}
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(ahb, &desc);
VkAndroidHardwareBufferFormatPropertiesANDROID fp = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
VkAndroidHardwareBufferPropertiesANDROID props = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &fp};
VkResult pr = g_vk.GetAndroidHardwareBufferPropertiesANDROID(g_dev, ahb, &props);
if (pr != VK_SUCCESS || fp.format == VK_FORMAT_UNDEFINED) {
LOGE("ahb: %ux%u format %u: properties %s, Vulkan format %d", desc.width, desc.height, desc.format,
vk_result_name(pr), (int)fp.format);
return NULL;
}
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = (int)desc.width; img->h = (int)desc.height; img->dmabuf = 1; img->fmt = fp.format; img->sampled = 1;
VkExternalMemoryImageCreateInfo ext = {
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkImageCreateInfo ici = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &ext,
.imageType = VK_IMAGE_TYPE_2D, .format = fp.format, .extent = {desc.width, desc.height, 1},
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
VkResult cr = g_vk.CreateImage(g_dev, &ici, NULL, &img->image);
if (cr != VK_SUCCESS) { LOGE("ahb: vkCreateImage %ux%u -> %s", desc.width, desc.height, vk_result_name(cr)); free(img); return NULL; }
int idx = -1;
for (int i = 0; i < 32; i++) if (props.memoryTypeBits & (1u << i)) { idx = i; break; }
VkImportAndroidHardwareBufferInfoANDROID imp = {
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = ahb};
VkMemoryDedicatedAllocateInfo ded = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &imp, .image = img->image};
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &ded,
.allocationSize = props.allocationSize, .memoryTypeIndex = (uint32_t)(idx < 0 ? 0 : idx)};
VkResult mr = idx < 0 ? VK_ERROR_FEATURE_NOT_PRESENT : g_vk.AllocateMemory(g_dev, &mai, NULL, &img->mem);
if (mr != VK_SUCCESS || g_vk.BindImageMemory(g_dev, img->image, img->mem, 0) != VK_SUCCESS) {
LOGE("ahb: importing %ux%u -> %s", desc.width, desc.height, vk_result_name(mr));
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return NULL;
}
return img;
}
static int shm_sampled(void) {
static int known;
if (!known) {
@@ -34,6 +34,9 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
int vkp_image_is_dmabuf(const struct vkp_image *img);
struct vkp_image *vkp_image_create_shm(int w, int h);
struct AHardwareBuffer;
struct vkp_image *vkp_image_from_ahb(struct AHardwareBuffer *ahb);
void vkp_wait_idle(void);
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride);
int vkp_image_width(const struct vkp_image *img);
@@ -9,6 +9,7 @@
#include <sys/resource.h>
#include <android/log.h>
#include <android/native_window_jni.h>
#include <android/hardware_buffer_jni.h>
#include "vk_present.h"
#include "droiddeck_ext.h"
#include "ahb_swapchain.h"
@@ -27,6 +28,9 @@ extern int droiddeck_cursor_serial(void);
extern void droiddeck_wayland_send_key(int evdev, int state);
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
extern void droiddeck_stream_set(int on);
extern void droiddeck_stream_frame(AHardwareBuffer *ahb);
extern unsigned droiddeck_stream_frames(void);
extern void droiddeck_wayland_output_resized(void);
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
extern volatile int g_fps_limit;
@@ -667,3 +671,21 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardSpatialP
(*env)->GetFloatArrayRegion(env, pos, 0, 3, p);
vkp_cardboard_set_spatial_pose(m, p, live ? 1 : 0);
}
/* The Xbox Cloud Gaming native player: its decoded frames are the whole scene (no Wayland clients). */
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamMode(JNIEnv *env, jclass clazz, jboolean on) {
droiddeck_stream_set(on ? 1 : 0);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrame(JNIEnv *env, jclass clazz, jobject hardwareBuffer) {
if (!hardwareBuffer) return;
AHardwareBuffer *ahb = AHardwareBuffer_fromHardwareBuffer(env, hardwareBuffer);
if (ahb) droiddeck_stream_frame(ahb);
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) {
return (jint)droiddeck_stream_frames();
}
@@ -25,6 +25,16 @@ class App : Application() {
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xbox")
return
}
if (process == "$packageName:xboxcloud") {
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xboxcloud")
return
}
if (process == "$packageName:xcloudnative") {
// The native cloud player: the stores log and nothing that touches the Linux session.
com.droiddeck.launcher.stores.StoresState.init(this)
return
}
if (process == "$packageName:sdl3") return // sdl3droiddeck: the SDL3 bridge's process
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
CrashHandler.install(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
@@ -91,7 +91,7 @@ class FrontEndActivity : ComponentActivity() {
private val components = ComponentsMenu(this, ui)
private val decky = DeckyMenu(this, ui)
private val updates = UpdatesMenu(this, ui)
private val protons = ProtonMenu(this, ui)
private val protons = ProtonMenu(this, ui) { !busy && flood == null && pkgStage == null && components.compBusy == null }
private var installed by mutableStateOf<String?>(null)
private var flood by mutableStateOf<PendingFlood?>(null)
@@ -120,7 +120,7 @@ class FrontEndActivity : ComponentActivity() {
private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true)
private var returnAfterGame by mutableStateOf(true)
private var shaderPrecache by mutableStateOf(true)
private var shaderPrecache by mutableStateOf<Boolean?>(null)
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
@@ -172,7 +172,6 @@ class FrontEndActivity : ComponentActivity() {
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
private var navRequest by mutableStateOf<String?>(null)
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
@@ -460,7 +459,13 @@ class FrontEndActivity : ComponentActivity() {
}
private fun launchFlooded(f: PendingFlood) {
if (busy || LinuxRuntimeInstaller.isBusy()) { flood = null; floodProgress = 0f; return }
if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null ||
ProtonExtras.installInProgress || pkgStage != null) {
flood = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
return
}
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
super.startActivity(f.intent.putExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, signal.toArgb()))
overridePendingTransition(0, 0)
@@ -544,12 +549,12 @@ class FrontEndActivity : ComponentActivity() {
}
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.putExtra(SessionActivity.EXTRA_STEAMVR, steamVr)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.returnTo(returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
return true
}
return startSession(Intent(this, SessionActivity::class.java)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.returnTo(returnHome)
.apply {
if (game.gameIdString == com.droiddeck.launcher.gpu.SteamVr.APP_ID) {
putExtra(SessionActivity.EXTRA_STEAMVR, true)
@@ -560,6 +565,12 @@ class FrontEndActivity : ComponentActivity() {
}, steamSession = true)
}
private fun Intent.returnTo(returnHome: Boolean): Intent {
val task = taskId
return putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
}
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean {
val app = applicationContext
Thread({
@@ -573,7 +584,7 @@ class FrontEndActivity : ComponentActivity() {
}
com.droiddeck.launcher.session.NoSteamLaunch.remember(command)
val next = Intent(this, SessionActivity::class.java)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.returnTo(returnHome)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, command.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, command.args.toTypedArray())
@@ -582,7 +593,7 @@ class FrontEndActivity : ComponentActivity() {
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args ->
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.returnTo(returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
else -> pendingSwitch = next
}
@@ -761,7 +772,6 @@ class FrontEndActivity : ComponentActivity() {
launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
storesOpenTab = SessionPrefs.storesOpenTab(this)
storesShowMature = SessionPrefs.storesShowMature(this)
storesSort = SessionPrefs.storesSort(this)
storesView = SessionPrefs.storesView(this)
@@ -825,7 +835,6 @@ class FrontEndActivity : ComponentActivity() {
launcherIcon = launcherIcon,
gameStoresEnabled = gameStoresEnabled,
gameStoresSpeedTier = gameStoresSpeedTier,
storesOpenTab = storesOpenTab,
navigate = navRequest,
addedGamesArt = addedGamesArt,
sgdbUserKey = sgdbUserKey,
@@ -1000,7 +1009,6 @@ class FrontEndActivity : ComponentActivity() {
applyLauncherFullscreen()
},
onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
onStoresOpenTab = { tab -> SessionPrefs.setStoresOpenTab(this, tab); storesOpenTab = tab },
onNavigated = { navRequest = null },
onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show },
onStoresSort = { sort -> SessionPrefs.setStoresSort(this, sort); storesSort = sort },
@@ -1727,7 +1735,7 @@ class FrontEndActivity : ComponentActivity() {
onSteamClientArch = { id ->
SessionPrefs.setSteamClientArch(this, id)
steamClientArch = id
shaderPrecache = SessionPrefs.shaderPrecache(this)
loadShaderPrecache(mode)
refresh()
},
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
@@ -1889,6 +1897,19 @@ class FrontEndActivity : ComponentActivity() {
private var pipAutoEnter by mutableStateOf(false)
private var unfoldedControls by mutableStateOf(false)
private var unfoldedControlsWithController by mutableStateOf(false)
private var shaderPrecacheGeneration = 0
private fun loadShaderPrecache(mode: String) {
val generation = ++shaderPrecacheGeneration
shaderPrecache = null
if (mode != SessionService.MODE_STEAM) return
Thread({
val precache = SessionPrefs.shaderPrecache(this)
ui.post {
if (!isDestroyed && generation == shaderPrecacheGeneration) shaderPrecache = precache
}
}, "shader-precache").start()
}
private fun loadModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
@@ -1904,7 +1925,7 @@ class FrontEndActivity : ComponentActivity() {
steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this)
returnAfterGame = SessionPrefs.returnAfterGame(this)
shaderPrecache = SessionPrefs.shaderPrecache(this)
loadShaderPrecache(mode)
steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
loadBootMovie()
@@ -1,6 +1,8 @@
package com.droiddeck.launcher
import android.os.Handler
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
@@ -8,31 +10,48 @@ import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.frontend.AutoComponents
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
internal class ProtonMenu(
private val activity: android.app.Activity,
private val ui: Handler,
private val idle: () -> Boolean = { true },
) {
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
var protonBusyId by mutableStateOf<String?>(null)
var protonStage by mutableStateOf<String?>(null)
var protonPercent by mutableIntStateOf(-1)
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
fun installProton(id: String) {
fun installProton(id: String, automatic: Boolean = false) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
ProtonExtras.unqueue(activity, tool)
protonBusyId = id
protonStage = activity.getString(R.string.store_starting)
protonPercent = -1
Thread({
val problem = ProtonExtras.install(activity, tool) { label, value ->
ui.post { protonStage = label; protonPercent = value }
}
val problem = runCatching {
installer(tool) { label, value ->
ui.post { protonStage = label; protonPercent = value }
}
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
ui.post {
protonBusyId = null
protonStage = null
protonPercent = -1
refreshProtons()
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
if (problem != null) {
if (automatic) Log.w("ProtonMenu", "auto-update ${tool.id}: $problem")
else android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
}
if (automatic) ensureAutoUpdates()
}
}, "install-proton-$id").start()
}
@@ -45,6 +64,7 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
protonPercent = -1
Thread({
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
if (tool.id == ProtonExtras.OWN && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true)
ui.post {
protonBusyId = null
protonStage = null
@@ -64,7 +84,38 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
if (!checking.compareAndSet(false, true)) return
Thread({
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
if (asked) ui.post { refreshProtons() }
ui.post {
if (asked) refreshProtons()
ensureAutoUpdates()
}
}, "proton-updates").start()
}
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
protonBusyId = ProtonExtras.OWN
Thread({
ProtonExtras.tidy(activity)
val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
ui.post {
protonBusyId = null
refreshProtons()
if (tidied) ensureAutoUpdates()
}
}, "proton-tidy").start()
return
}
val attempts = activity.getSharedPreferences("proton-auto-updates", android.content.Context.MODE_PRIVATE)
val (tool, update) = ProtonExtras.tools.firstNotNullOfOrNull { tool ->
val update = ProtonExtras.update(activity, tool) ?: ProtonExtras.missing(activity, tool) ?: return@firstNotNullOfOrNull null
val previous = attempts.getLong("${tool.id}.at", 0L)
if (attempts.getString("${tool.id}.tag", null) != update || now - previous !in 0 until 15L * 60 * 1000) tool to update else null
} ?: return
attempts.edit().putString("${tool.id}.tag", update).putLong("${tool.id}.at", now).apply()
installProton(tool.id, automatic = true)
}
}
@@ -510,6 +510,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
padBridge = bridge
SessionState.padBridge = bridge
com.droiddeck.launcher.input.DualSenseBridge.attach(this, bridge)
if (Build.VERSION.SDK_INT >= 31) {
val vr = com.droiddeck.launcher.input.JoyConVr(this, File(filesDir, ".wayland-rt/${com.droiddeck.launcher.input.JoyConVr.FILE}")) { taken, released ->
if (joyConVr == null) return@JoyConVr
@@ -818,6 +819,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
lossless = lossless,
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground, touchMode = touchMode,
micAvailable = SessionState.micAvailable && !SessionState.suspended,
micEnabled = SessionState.micEnabled,
onMicEnabled = { SessionService.setMicEnabled(this@SessionActivity, it) },
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
@@ -1893,7 +1897,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun run() {
if (!watching) return
if (::pip.isInitialized) pip.refresh()
if (SessionState.stopRequested && !SessionState.running && !installingRuntime) {
if (SessionState.stopRequested && !SessionState.running && !installingRuntime &&
SessionState.phase != SessionPhase.STOPPING) {
SessionState.stopRequested = false
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
collectStartArtifacts("session start cancelled")
@@ -1926,6 +1931,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.relaunch?.let { next ->
SessionState.relaunch = null
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
setIntent(next)
recreate()
return@runOnUiThread
@@ -2036,6 +2042,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return super.dispatchKeyEvent(event)
}
if (pipUi) return true
if (com.droiddeck.launcher.input.DualSenseBridge.isBridged(event)) return true
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad)
val fromController = PadBridge.isControllerKeyEvent(event)
@@ -3027,6 +3034,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return
}
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
if (!intent.hasExtra(EXTRA_LINK_TASK)) intent.putExtra(EXTRA_LINK_TASK, this.intent.getIntExtra(EXTRA_LINK_TASK, -1))
setIntent(intent)
if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
SessionState.steamVr = true
@@ -3519,6 +3527,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
handCamera?.stop()
handCamera = null
padBridge?.stop()
if (isFinishing && !SessionState.running) com.droiddeck.launcher.input.DualSenseBridge.detach(this)
com.droiddeck.launcher.input.DualSenseBridge.screenClosed(this)
steamController?.stop()
if (SessionState.padBridge === padBridge) SessionState.padBridge = null
padMotion?.stop()
@@ -3549,17 +3559,33 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
return
}
super.finish()
if (!closeAtOnce && intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) {
com.droiddeck.launcher.ui.QuitFlood.take()
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
closeLinkTasks()
if (!isTaskRoot) moveTaskToBack(true)
super.finishAndRemoveTask()
} else super.finish()
if (quitFlooded) overridePendingTransition(0, 0)
else overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
}
private fun closeLinkTasks() {
val linkTask = intent.getIntExtra(EXTRA_LINK_TASK, -1)
if (linkTask == -1) return
val tasks = runCatching { getSystemService(android.app.ActivityManager::class.java)?.appTasks }.getOrNull().orEmpty()
for (task in tasks) {
runCatching {
val info = task.taskInfo
@Suppress("DEPRECATION")
val id = if (android.os.Build.VERSION.SDK_INT >= 29) info.taskId else info.persistentId
val base = info.baseIntent
if (id == linkTask && base.component?.className == FrontEndActivity::class.java.name &&
com.droiddeck.launcher.frontend.GameLaunchIntent.accepts(base.action)) task.finishAndRemoveTask()
}
}
}
private fun completeLeave() {
if (isFinishing) return
val signal = com.droiddeck.launcher.ui.Themes.current(this).signal
@@ -3571,6 +3597,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
companion object {
const val EXTRA_RETURN_HOME = "returnHome"
const val EXTRA_LINK_TASK = "linkTask"
const val EXTRA_STEAMVR = "steamVr"
const val EXTRA_REPAIR_RUNTIME = "repairRuntime"
private const val LEAVE_TIMEOUT_MS = 1_500L
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.audio;
import android.os.Process;
import android.util.Log;
import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.SessionPart;
import com.droiddeck.launcher.core.HostProcess;
@@ -19,10 +20,13 @@ public class DirectAudioRelayComponent extends SessionPart {
private volatile int pid = -1;
private final Object micLock = new Object();
private boolean micHot;
private final File micControl;
public java.util.function.Consumer<Boolean> onMicEnabled;
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
this.socketPath = socketPath;
this.micFifoPath = micFifoPath;
this.micControl = micFifoPath == null ? null : new File(micFifoPath.getParentFile(), "mic-enabled");
}
public void setLogFile(File file) {
@@ -63,8 +67,13 @@ public class DirectAudioRelayComponent extends SessionPart {
StringBuilder command = new StringBuilder(binary.getAbsolutePath());
command.append(" --socket ").append(socketPath.getAbsolutePath());
command.append(" --log");
if (micFifoPath != null) {
final boolean withMic = micFifoPath != null && setMicEnabled(true);
if (withMic) {
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
command.append(" --mic-control ").append(micControl.getAbsolutePath());
} else if (micFifoPath != null) {
Log.w(TAG, "microphone control unavailable; starting with capture disabled");
command.append(" --mic-control /dev/null");
}
ArrayList<String> env = new ArrayList<>();
env.add("HOME=" + app().getFilesDir());
@@ -73,7 +82,7 @@ public class DirectAudioRelayComponent extends SessionPart {
try {
out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
out.println("== DirectAudio relay helper starting"
+ (micFifoPath != null ? " with the microphone" : " (no microphone)"));
+ (withMic ? " with the microphone" : " (no microphone)"));
out.flush();
} catch (Exception e) {
Log.w(TAG, "could not open " + logFile, e);
@@ -84,14 +93,23 @@ public class DirectAudioRelayComponent extends SessionPart {
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
trackMic(line);
if (withMic) trackMic(line);
if (log != null) synchronized (log) { log.println(line); log.flush(); }
});
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
+ (micFifoPath != null ? " mic=" + micFifoPath : " (no microphone)"));
+ (withMic ? " mic=" + micFifoPath : " (no microphone)"));
}
public synchronized boolean setMicEnabled(boolean enabled) {
if (micControl == null) return false;
File next = new File(micControl.getPath() + ".new");
return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(micControl);
}
private void trackMic(String line) {
if (line.startsWith("DA-Relay: mic enabled=") && onMicEnabled != null) {
onMicEnabled.accept(line.equals("DA-Relay: mic enabled=1"));
}
boolean start = line.startsWith("DA-Relay: mic start ");
if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
synchronized (micLock) {
@@ -1,27 +0,0 @@
package com.droiddeck.launcher.core
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SocNames
object CpuAllocationDefaults {
data class Allocation(val client: String, val game: String)
val device: Allocation? by lazy {
forDevice(SocNames.model(), GpuInfo.systemProperty("ro.board.platform"),
CpuCores.all.associateWith(CpuCores::maxGhz))
}
fun forDevice(model: String, platform: String, frequencies: Map<Int, Double?>): Allocation? {
val chip = model.trim().uppercase().substringBefore('-')
val gen2 = chip in setOf("SM8550", "QCS8550") ||
(chip.isEmpty() && platform.trim().equals("kalama", ignoreCase = true))
if (!gen2 || frequencies.size != 8 || frequencies.keys.any { it < 0 } ||
frequencies.values.any { it == null || !it.isFinite() || it <= 0.0 }) return null
val clusters = frequencies.entries.groupBy { it.value }.toSortedMap(compareBy { it ?: 0.0 }).values.toList()
if (clusters.map { it.size } != listOf(3, 4, 1)) return null
return Allocation(
client = CpuCores.format(clusters[2].map { it.key }.toSet()),
game = CpuCores.format(clusters[1].map { it.key }.toSet()),
)
}
}
@@ -152,13 +152,17 @@ object DeviceReport {
k("RAM total", FileUtils.sizeToString(mi.totalMem))
k("RAM available", FileUtils.sizeToString(mi.availMem))
}
runCatching {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) k("Thermal status", thermalStatusName(pm.currentThermalStatus))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
k("Thermal headroom (10 s)", pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) })
val pm = runCatching { context.getSystemService(Context.POWER_SERVICE) as? PowerManager }.getOrNull()
if (pm != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
k("Thermal status", runCatching { thermalStatusName(pm.currentThermalStatus) }.getOrNull())
}
k("Power saver", pm.isPowerSaveMode)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
k("Thermal headroom (10 s)", runCatching {
pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) }
}.getOrNull())
}
k("Power saver", runCatching { pm.isPowerSaveMode }.getOrNull())
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val rate = runCatching { context.getSystemService(PerformanceHintManager::class.java)?.preferredUpdateRateNanos }.getOrNull()
@@ -387,11 +387,17 @@ object AddedGames {
}
}
private class LoginUser(val id: String, val mostRecent: Boolean, val autoLogin: Boolean, val timestamp: Long)
internal fun accountConfig(root: File): File? {
val users = runCatching { File(root, "config/loginusers.vdf").readText() }.getOrDefault("")
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users)
.lastOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
val account = recent?.groupValues?.get(1)?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users).map {
val body = it.groupValues[2]
LoginUser(it.groupValues[1], Regex(""""MostRecent"\s*"1"""").containsMatchIn(body), Regex(""""AutoLogin"\s*"1"""").containsMatchIn(body),
Regex(""""timestamp"\s*"(\d+)"""").find(body)?.groupValues?.get(1)?.toLongOrNull() ?: 0L)
}.filter { it.mostRecent || it.autoLogin || it.timestamp > 0 }.toList().asReversed()
.maxWithOrNull(compareBy<LoginUser>({ it.mostRecent }, { it.autoLogin }, { it.timestamp }))
val account = recent?.id?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
?: File(root, "userdata").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) && it != "0" }?.singleOrNull()
return account?.let { File(root, "userdata/$it/config") }
}
@@ -27,6 +27,7 @@ object Library {
const val ADDED = "added"
const val EPIC_LAUNCHER = "epic-launcher"
const val EPIC_LAUNCHER_NAME = "Epic Games Launcher"
const val XBOX_CLOUD = "xbox-cloud"
const val SOURCE_STEAM = "steam"
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
@@ -46,12 +47,14 @@ object Library {
1054830,
1070560,
1113280,
1161040,
1245040,
1391110,
1420170,
1493710,
1580130,
1628350,
1826330,
1887720,
2180100,
228980,
@@ -104,7 +107,10 @@ object Library {
.firstOrNull { it.isDirectory }
}
fun steamGames(context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context)): List<SteamGame> {
fun steamGames(
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
withShared: Boolean = true,
): List<SteamGame> {
val root = SessionPrefs.steamRoot(context, arch)
val cache = File(root, "appcache/librarycache")
val libraries = steamLibraries(context, arch)
@@ -121,8 +127,9 @@ object Library {
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
if (name.isEmpty() || flags and 4 == 0) return@forEach
val art = steamCacheImage(cache, appId, STEAM_CAPSULES)
val hero = steamCacheImage(cache, appId, STEAM_HEROES)
val images = SteamCacheImages(File(cache, appId.toString()))
val art = images.find(STEAM_CAPSULES)
val hero = images.find(STEAM_HEROES)
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
@@ -131,15 +138,25 @@ object Library {
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
gameFiles = gameFiles,
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
icon = steamCacheImage(cache, appId, listOf("icon.jpg", "icon.png"))
?: File(cache, appId.toString()).listFiles()?.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) },
logo = steamCacheImage(cache, appId, STEAM_LOGOS),
icon = images.icon(),
logo = images.find(STEAM_LOGOS),
))
}
}
if (withShared) {
val other = if (arch == "x86_64") "arm64" else "x86_64"
val shared = sharedApps(context, arch) - out.keys
if (shared.isNotEmpty()) runCatching { steamGames(context, arch = other, withShared = false) }.getOrDefault(emptyList())
.filter { it.appId in shared }.forEach { out[it.appId] = it }
}
return out.values.toList()
}
internal fun sharedApps(context: Context, arch: String): Set<Int> {
val view = File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/shared/${if (arch == "x86_64") "arm64" else "x86-64"}/steamapps")
return view.list().orEmpty().mapNotNull { Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }.toSet()
}
fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
val root = SessionPrefs.activeSteamRoot(context)
val cache = File(root, "appcache/librarycache")
@@ -210,13 +227,19 @@ object Library {
)
}
internal fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? {
val appDir = File(cache, appId.toString())
val dirs = listOf(appDir) + appDir.listFiles()
.orEmpty().filter { it.isDirectory }.sortedBy { it.name }
return names.asSequence()
internal fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? =
SteamCacheImages(File(cache, appId.toString())).find(names)
internal class SteamCacheImages(appDir: File) {
private val entries = appDir.listFiles().orEmpty()
private val dirs = listOf(appDir) + entries.filter { it.isDirectory }.sortedBy { it.name }
fun find(names: List<String>): File? = names.asSequence()
.flatMap { name -> dirs.asSequence().map { File(it, name) } }
.firstOrNull { it.isFile && it.length() > 0L }
fun icon(): File? = find(listOf("icon.jpg", "icon.png"))
?: entries.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) }
}
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>, val atPanel: Boolean = false)
@@ -3,12 +3,13 @@ package com.droiddeck.launcher.frontend
import android.content.Context
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.session.WinComponents
import org.json.JSONObject
import java.io.File
import java.util.Locale
object WinCompSources {
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER }
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER, XBOX }
data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList())
@@ -49,6 +50,17 @@ object WinCompSources {
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
private val XBOX_KNOWN = Regex("""<KnownDependency\s+Name="([A-Za-z0-9_.-]{1,40})"""")
// VC14 also registers the ARM64 runtime: launchers running as ARM64EC look for it and stop when it is missing.
private val XBOX_COMPONENTS = mapOf("VC14" to listOf("vcredist2022", WinComponents.VCREDIST_ARM64))
/** Microsoft installs a PC Game Pass game's declared runtimes with it; VC14 is wanted by nearly all and is always added. */
fun xbox(folder: File?): List<Pair<String, String>> {
val config = folder?.listFiles().orEmpty().firstOrNull { it.isFile && it.name.equals("MicrosoftGame.config", ignoreCase = true) && it.length() < 1L shl 20 }
val declared = config?.let { file -> runCatching { XBOX_KNOWN.findAll(file.readText()).map { it.groupValues[1] }.toList() }.getOrNull() }.orEmpty()
return (listOf("VC14") + declared).flatMap { name -> XBOX_COMPONENTS[name].orEmpty().map { it to name } }.distinctBy { it.first }
}
fun steamDepots(ids: List<String>): List<Pair<String, String>> = ids.mapNotNull { SteamRedists.DEPOTS[it] }.distinctBy { it.first }
@@ -94,6 +106,7 @@ object WinCompSources {
parts.forEach { out += Finding(it, original, Origin.EPIC, true) }
}
}
store == Store.XBOX -> xbox(folder).forEach { (component, original) -> out += Finding(component, original, Origin.XBOX, true) }
store == Store.AMAZON -> folder?.let { amazonPostInstall(it) }?.forEach { command ->
val parts = installer(command)
val original = command.replace('\\', '/').substringAfterLast('/')
@@ -50,8 +50,10 @@ object FrameGen {
else -> context.getString(R.string.frame_gen_off)
}
fun apply(context: Context, refreshHz: Float): String? {
val mode = mode(context)
fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz)
/** Arms [mode] in this process's compositor; the cloud player passes its own mode and frame-rate cap. */
fun apply(context: Context, mode: Mode, refreshHz: Float): String? {
when (mode.engine) {
ENGINE_LSFG -> {
val status = Lossless.sync(context)
File diff suppressed because it is too large. Load diff
@@ -88,7 +88,11 @@ public class FakeInputWriter {
public static final int PAD_TYPE_XBOX = 2;
public static final int PAD_TYPE_DS4 = 3;
public static final int PAD_TYPE_DUALSENSE = 4;
public static final int PAD_TYPE_DUALSENSE_EDGE = 5;
public static final int PAD_TYPE_STEAM_2015 = 6;
public static final int PAD_TYPE_NONE = 7;
private static volatile int padType = -1;
public static int currentPadType() { return padType; }
private static volatile boolean tritonConnected = false;
private static final int TRITON_OFFSET = RING_SIZE + 64;
private static final int TRITON_MAGIC = 0x4e525454;
@@ -0,0 +1,381 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.os.Bundle
import android.system.Os
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.MappedByteBuffer
import java.nio.channels.FileChannel
/**
* SDL3 bridge "Steam Native Hook-up", DroidDeck side.
*
* The bridge hands a USB controller over raw: its real identity and every HID report. Here each one becomes
* /dev/hidraw24..27 -- sysfs description written like the kernel would (real vendor/product id, name, serial,
* interface, report descriptor) and the reports moved through a file shared with fakeinput_steam.cpp
* (FAKE_HOOKUP_SHM). Steam's own driver then runs on the real controller, like on a PC.
*
* Layout must match the HookupHeader / HookupSlot structs in fakeinput_steam.cpp.
*/
object HookupBridge {
private const val TAG = "SessionService"
const val FILE = ".hookup"
private const val MAGIC = 0x4b4f4f48
const val SLOTS = 4
private const val IN_FIFO = 256
private const val OUT_FIFO = 64
private const val REPORT_MAX = 128
private const val REPORT_SIZE = 144
private const val DESC_MAX = 4096
private const val HEADER_SIZE = 4096
private const val SLOT_SIZE = 53248
private const val SIZE = HEADER_SIZE + SLOTS * SLOT_SIZE
private const val MINOR_BASE = 24
private const val MAJOR = 240
// header
private const val H_FF_TO_STEAM = 8
private const val H_STEAM_MS = 16 // the Steam client's heartbeat (CLOCK_MONOTONIC ms), written by fakeinput
private const val STEAM_GONE_MS = 5000L
// slot
private const val S_PRESENT = 0
private const val S_GENERATION = 4
private const val S_VENDOR = 8
private const val S_PRODUCT = 10
private const val S_VERSION = 12
private const val S_BUS = 14
private const val S_IFACE = 16
private const val S_DESC_LEN = 20
private const val S_NAME = 24
private const val S_SERIAL = 152
private const val S_MANUFACTURER = 216
private const val S_PRODUCT_NAME = 280
private const val S_IN_WRITE = 344
private const val S_OUT_WRITE = 352
private const val S_OUT_READ = 360
private const val S_GET_REQUEST = 368
private const val S_GET_REPLY = 376
private const val S_GET_REPORT_ID = 384
private const val S_GET_LENGTH = 388
private const val S_GET = 392
private const val S_DIRECT_MS = 520 // SDL3 bridge heartbeat while it serves the slot itself (fast path)
private const val S_DESC = 1024
private const val S_IN = 5120
private const val S_OUT = 41984
@Volatile private var map: MappedByteBuffer? = null
/** The shared file; handed to the SDL3 bridge as a descriptor so it can serve slots directly (fast path). */
@Volatile var shmFile: File? = null
private set
@Volatile private var logFile: File? = null
/** Also written to the session's pad.log, next to the native side's "hookup:" lines. */
internal fun note(line: String) {
Log.i(TAG, line)
val f = logFile ?: return
try {
val t = java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(java.util.Date())
f.appendText("$t app: $line\n")
} catch (_: Exception) {}
}
private val present = BooleanArray(SLOTS)
private val getAsked = LongArray(SLOTS)
@Volatile var tritonPassthrough = false
set(value) { field = value; updateFfToSteam() }
/** Creates the shared file; returns it for FAKE_HOOKUP_SHM. Called at session start. */
@JvmStatic
fun prepare(fakeInputDir: File, padLog: File? = null): File? = try {
logFile = padLog
val file = File(fakeInputDir, FILE)
file.delete()
RandomAccessFile(file, "rw").use { raf ->
raf.setLength(SIZE.toLong())
val m = raf.channel.map(FileChannel.MapMode.READ_WRITE, 0, SIZE.toLong())
m.order(ByteOrder.LITTLE_ENDIAN)
m.putInt(4, 1)
m.putInt(0, MAGIC)
map = m
}
shmFile = file
file.setReadable(true, false)
file.setWritable(true, false)
present.fill(false)
note("hookup: shared file ready (${file.path}); waiting for the SDL3 bridge to hand over controllers")
file
} catch (e: Exception) {
note("hookup: no shared file: $e")
map = null
shmFile = null
null
}
private fun slotBase(slot: Int) = HEADER_SIZE + slot * SLOT_SIZE
/** Inode of the shared file (0 if none): the bridge reports the one it mapped, so a stale mapping is noticed. */
@JvmStatic fun shmInode(): Long = try { shmFile?.let { Os.stat(it.path).st_ino } ?: 0L } catch (_: Exception) { 0L }
/**
* The SDL3 bridge writes this slot's reports into the file itself and takes Steam's output / feature reads
* from it (its heartbeat is fresh): DroidDeck must leave the slot's FIFOs alone then.
*/
private fun bridgeServes(m: ByteBuffer, slot: Int): Boolean {
val beat = m.getLong(slotBase(slot) + S_DIRECT_MS)
return beat != 0L && android.os.SystemClock.uptimeMillis() - beat < 1500
}
/**
* Is the Steam client running in this session? Its side of the hook-up writes a heartbeat into the shared file
* every 0.1 s. (No hook-up file this session: treated as running, so nothing waits for it.)
*/
@JvmStatic fun steamRunning(): Boolean {
val m = map ?: return true
val beat = m.getLong(H_STEAM_MS)
return beat != 0L && android.os.SystemClock.uptimeMillis() - beat < STEAM_GONE_MS
}
@JvmStatic fun anyPresent(): Boolean = present.any { it }
@JvmStatic fun isPresent(slot: Int): Boolean = slot in 0 until SLOTS && present[slot]
/** True while Steam is handed game rumble (a real controller it drives itself is present). */
@JvmStatic fun ffToSteam(): Boolean = map != null && (anyPresent() || tritonPassthrough)
private fun updateFfToSteam() {
val m = map ?: return
synchronized(this) {
FakeInputWriter.storeFence()
m.putInt(H_FF_TO_STEAM, if (anyPresent() || tritonPassthrough) 1 else 0)
}
}
private fun putString(m: ByteBuffer, at: Int, max: Int, s: String) {
val b = s.toByteArray(Charsets.UTF_8)
val n = minOf(b.size, max - 1)
for (i in 0 until max) m.put(at + i, if (i < n) b[i] else 0)
}
// ---------------- bridge messages (DualSenseBridge's worker thread) ----------------
@Synchronized
fun add(id: Bundle) {
val m = map ?: run {
note("hookup: the bridge handed over a controller but this session has no hook-up file " +
"(DroidDeck build without it, or the session started without the deck pad)")
return
}
val slot = id.getInt("slot", -1)
if (slot !in 0 until SLOTS) { note("hookup: the bridge handed over slot $slot, which does not exist"); return }
val base = slotBase(slot)
val desc = id.getByteArray("desc") ?: ByteArray(0)
if (present[slot] && (m.getShort(base + S_VENDOR).toInt() and 0xffff) == id.getInt("vid") &&
(m.getShort(base + S_PRODUCT).toInt() and 0xffff) == id.getInt("pid") && m.getInt(base + S_IFACE) == id.getInt("iface")) {
return // the same controller resent after a reconnect: keep it as it is (no unplug/replug in Steam)
}
if (present[slot]) remove(slot)
describeSysfs(slot, id, desc)
m.putShort(base + S_VENDOR, id.getInt("vid").toShort())
m.putShort(base + S_PRODUCT, id.getInt("pid").toShort())
m.putShort(base + S_VERSION, id.getInt("version").toShort())
m.putShort(base + S_BUS, id.getInt("bus", 3).toShort())
m.putInt(base + S_IFACE, id.getInt("iface"))
putString(m, base + S_NAME, 128, id.getString("name") ?: "")
putString(m, base + S_SERIAL, 64, id.getString("serial") ?: "")
putString(m, base + S_MANUFACTURER, 64, id.getString("manufacturer") ?: "")
putString(m, base + S_PRODUCT_NAME, 64, id.getString("product") ?: "")
val n = minOf(desc.size, DESC_MAX)
for (i in 0 until n) m.put(base + S_DESC + i, desc[i])
m.putInt(base + S_DESC_LEN, n)
// fresh FIFOs: the readers start at the current write position, so only the counters matter
m.putLong(base + S_OUT_READ, m.getLong(base + S_OUT_WRITE))
getAsked[slot] = m.getLong(base + S_GET_REQUEST)
m.putLong(base + S_GET_REPLY, getAsked[slot])
m.putInt(base + S_GENERATION, m.getInt(base + S_GENERATION) + 1)
FakeInputWriter.storeFence()
m.putInt(base + S_PRESENT, 1)
present[slot] = true
updateFfToSteam()
note("hookup: /dev/hidraw${MINOR_BASE + slot} = %04x:%04x \"%s\" interface %d, descriptor %d bytes (Steam Native Hook-up)"
.format(id.getInt("vid"), id.getInt("pid"), id.getString("name"), id.getInt("iface"), desc.size))
}
@Synchronized
fun input(slot: Int, data: ByteArray) {
val m = map ?: return
if (slot !in 0 until SLOTS || !present[slot] || data.isEmpty()) return
if (bridgeServes(m, slot)) return // a late message from before the fast path took over
val base = slotBase(slot)
val idx = m.getLong(base + S_IN_WRITE)
val at = base + S_IN + ((idx % IN_FIFO).toInt()) * REPORT_SIZE
m.putLong(at, 0L)
FakeInputWriter.storeFence()
val n = minOf(data.size, REPORT_MAX)
m.putInt(at + 8, n)
m.putInt(at + 12, 0)
for (i in 0 until n) m.put(at + 16 + i, data[i])
FakeInputWriter.storeFence()
m.putLong(at, idx + 1)
m.putLong(base + S_IN_WRITE, idx + 1)
}
@Synchronized
fun remove(slot: Int) {
val m = map ?: return
if (slot !in 0 until SLOTS) return
m.putInt(slotBase(slot) + S_PRESENT, 0)
m.putLong(slotBase(slot) + S_DIRECT_MS, 0L)
FakeInputWriter.storeFence()
if (present[slot]) note("hookup: /dev/hidraw${MINOR_BASE + slot} unplugged")
present[slot] = false
unlinkClass(slot)
updateFfToSteam()
}
@Synchronized
fun removeAll() { for (s in 0 until SLOTS) if (present[s]) remove(s) }
@Synchronized
fun reply(slot: Int, request: Long, data: ByteArray?) {
val m = map ?: return
if (slot !in 0 until SLOTS || request != getAsked[slot]) return
val base = slotBase(slot)
val n = if (data == null) 0 else minOf(data.size, REPORT_MAX)
for (i in 0 until n) m.put(base + S_GET + i, data!![i])
m.putInt(base + S_GET_LENGTH, n)
FakeInputWriter.storeFence()
m.putLong(base + S_GET_REPLY, request)
}
/**
* Steam -> controller. Calls [out](slot, kind, report) for each queued output report / feature write and
* [get](slot, request, reportId, input, length) for a new feature/input read. Run every ~1 ms.
*/
@Synchronized
fun poll(out: (Int, Int, ByteArray) -> Unit, get: (Int, Long, Int, Boolean, Int) -> Unit) {
val m = map ?: return
for (slot in 0 until SLOTS) {
if (!present[slot]) continue
FakeInputWriter.storeFence()
if (bridgeServes(m, slot)) continue // the bridge takes Steam's reports from the file itself
val base = slotBase(slot)
var read = m.getLong(base + S_OUT_READ)
val written = m.getLong(base + S_OUT_WRITE)
while (read < written) {
val at = base + S_OUT + ((read % OUT_FIFO).toInt()) * REPORT_SIZE
if (m.getLong(at) != read + 1) break // still being written
val n = m.getInt(at + 8).coerceIn(0, REPORT_MAX)
val kind = m.getInt(at + 12)
val data = ByteArray(n)
for (i in 0 until n) data[i] = m.get(at + 16 + i)
read++
if (n > 0) out(slot, kind, data)
}
m.putLong(base + S_OUT_READ, read)
val request = m.getLong(base + S_GET_REQUEST)
if (request != getAsked[slot] && request != m.getLong(base + S_GET_REPLY)) {
getAsked[slot] = request
val idWord = m.getInt(base + S_GET_REPORT_ID)
get(slot, request, idWord and 0xff, (idWord and 0x100) != 0, m.getInt(base + S_GET_LENGTH))
}
}
}
// ---------------- sysfs, as Linux would describe the device ----------------
private fun guestHid(slot: Int, id: Bundle): Triple<String, String, String> {
val bus = 10 + slot
val usb = "/sys/devices/droiddeck/usb$bus"
val iface = "$usb/$bus-1:1.${maxOf(0, id.getInt("iface"))}"
val hid = "$iface/0003:%04X:%04X.%04X".format(id.getInt("vid"), id.getInt("pid"), 0x10 + slot)
return Triple(usb, iface, hid)
}
private fun describeSysfs(slot: Int, id: Bundle, desc: ByteArray) {
val devices = com.droiddeck.launcher.session.SteamDeckPad.sysDevicesDir
val classDir = com.droiddeck.launcher.session.SteamDeckPad.sysHidrawClassDir
val context = com.droiddeck.launcher.session.SteamDeckPad.sysContext
if (devices == null || classDir == null || context == null) {
note("hookup: no session sysfs to describe /dev/hidraw${MINOR_BASE + slot} in (deck pad off?)")
return
}
try {
val (usb, iface, hid) = guestHid(slot, id)
fun dir(guest: String) = File(devices, guest.removePrefix("/sys/devices/droiddeck/")).apply { mkdirs() }
fun write(guest: String, name: String, text: String) = File(dir(guest), name).writeText(text)
fun link(file: File, target: String) {
file.parentFile?.mkdirs()
file.delete()
Os.symlink(target, file.path)
}
deleteTree(File(devices, usb.removePrefix("/sys/devices/droiddeck/"))) // the previous description
val vid = id.getInt("vid")
val pid = id.getInt("pid")
val ver = id.getInt("version")
val vidHex = "%04x".format(vid)
val pidHex = "%04x".format(pid)
val product = "%x/%x/%x".format(vid, pid, ver)
val node = "hidraw${MINOR_BASE + slot}"
val minor = MINOR_BASE + slot
val busNum = "%03d".format(10 + slot)
write(usb, "uevent", "DEVTYPE=usb_device\nPRODUCT=$product\nTYPE=0/0/0\nBUSNUM=$busNum\nDEVNUM=002\n")
write(usb, "idVendor", "$vidHex\n")
write(usb, "idProduct", "$pidHex\n")
write(usb, "bcdDevice", "%04x\n".format(ver))
write(usb, "manufacturer", "${id.getString("manufacturer") ?: ""}\n")
write(usb, "product", "${id.getString("product") ?: ""}\n")
write(usb, "serial", "${id.getString("serial") ?: ""}\n")
write(usb, "busnum", "${10 + slot}\n")
write(usb, "devnum", "2\n")
link(File(dir(usb), "subsystem"), "/sys/bus/usb")
val cls = id.getInt("ifclass", 3)
write(iface, "uevent", "DEVTYPE=usb_interface\nPRODUCT=$product\nINTERFACE=$cls/${id.getInt("ifsub")}/${id.getInt("ifproto")}\n")
write(iface, "bInterfaceNumber", "%02x\n".format(maxOf(0, id.getInt("iface"))))
write(iface, "bInterfaceClass", "%02x\n".format(cls))
write(iface, "bInterfaceSubClass", "%02x\n".format(id.getInt("ifsub")))
write(iface, "bInterfaceProtocol", "%02x\n".format(id.getInt("ifproto")))
link(File(dir(iface), "subsystem"), "/sys/bus/usb")
val name = id.getString("name") ?: ""
val serial = id.getString("serial") ?: ""
write(hid, "uevent", "DRIVER=hid-generic\nHID_ID=0003:%08X:%08X\nHID_NAME=$name\n".format(vid, pid) +
"HID_PHYS=usb-droiddeck-${10 + slot}/input${maxOf(0, id.getInt("iface"))}\nHID_UNIQ=$serial\n" +
"MODALIAS=hid:b0003g0001v%08Xp%08X\n".format(vid, pid))
File(dir(hid), "report_descriptor").writeBytes(desc)
link(File(dir(hid), "subsystem"), "/sys/bus/hid")
val hidraw = "$hid/hidraw/$node"
write(hidraw, "uevent", "MAJOR=$MAJOR\nMINOR=$minor\nDEVNAME=$node\n")
write(hidraw, "dev", "$MAJOR:$minor\n")
link(File(dir(hidraw), "subsystem"), "/sys/class/hidraw")
link(File(dir(hidraw), "device"), hid)
link(File(classDir, node), hidraw)
link(File(LinuxRuntime.liveDir(context), "drm/sys/$MAJOR:$minor"), hidraw)
val udevData = File(LinuxRuntime.rootDir(context), "run/udev/data").apply { mkdirs() }
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
} catch (e: Exception) {
note("hookup: could not describe /dev/hidraw${MINOR_BASE + slot}: $e")
}
}
/**
* Deletes a folder without following symbolic links. (File.deleteRecursively() follows them: the description
* links "subsystem" to the phone's real /sys/bus/..., and walking into the real /sys -- full of links back into
* itself -- never ends, which froze DroidDeck's bridge thread on the second hand-over of a controller.)
*/
private fun deleteTree(f: File) {
val st = try { Os.lstat(f.path) } catch (_: Exception) { return } // gone already
if (android.system.OsConstants.S_ISDIR(st.st_mode)) f.list()?.forEach { deleteTree(File(f, it)) }
f.delete()
}
private fun unlinkClass(slot: Int) {
val classDir = com.droiddeck.launcher.session.SteamDeckPad.sysHidrawClassDir ?: return
try { File(classDir, "hidraw${MINOR_BASE + slot}").delete() } catch (_: Exception) {}
}
/** True when DroidDeck should set the hook-up file up this session (the bridge app is installed). */
@JvmStatic fun wanted(context: Context): Boolean =
com.droiddeck.launcher.session.SessionPrefs.sdl3Controllers(context) && DualSenseBridge.isBridgeInstalled(context)
}
@@ -51,6 +51,7 @@ public final class PadBridge {
private volatile java.util.function.IntPredicate excluded = id -> false;
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS];
private final boolean[] bridgeSlots = new boolean[SLOTS]; // slots fed by the SDL3 bridge app
private final PadState effectiveState = new PadState();
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private boolean open;
@@ -200,6 +201,7 @@ public final class PadBridge {
}
public static boolean isControllerKeyEvent(KeyEvent event) {
if (DualSenseBridge.isBridged(event)) return false;
InputDevice device = event.getDevice();
if (device == null || device.isVirtual() || isSystemVirtualInputName(device.getName())) return false;
if (KeyEvent.isGamepadButton(event.getKeyCode())) {
@@ -224,6 +226,7 @@ public final class PadBridge {
}
public static boolean isControllerMotionEvent(MotionEvent event) {
if (DualSenseBridge.isBridged(event)) return false;
InputDevice device = event.getDevice();
return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !device.isVirtual()
&& !isSystemVirtualInputName(device.getName())
@@ -446,6 +449,39 @@ public final class PadBridge {
publish();
}
/** SDL3 bridge: reserves a free player slot (1..3) for an extra controller. @return the slot, or -1 if none is free. */
public synchronized int claimBridgeSlot() {
for (int slot = 1; slot < SLOTS; slot++) {
if (owners[slot] != NO_CONTROLLER || bridgeSlots[slot]) continue;
bridgeSlots[slot] = true;
playerStates[slot].clear();
Log.i(TAG, "SDL3 bridge controller is player " + (slot + 1));
return slot;
}
return -1;
}
/** SDL3 bridge: frees a slot taken with {@link #claimBridgeSlot()}. */
public synchronized void releaseBridgeSlot(int slot) {
if (slot < 1 || slot >= SLOTS || !bridgeSlots[slot]) return;
bridgeSlots[slot] = false;
playerStates[slot].clear();
if (playerWriters[slot] != null) {
playerWriters[slot].destroy();
playerWriters[slot] = null;
}
Log.i(TAG, "SDL3 bridge player " + (slot + 1) + " left");
}
/** SDL3 bridge: updates player [slot] (0 = primary pad, 1..3 = claimed bridge slots). */
public synchronized void applyExternalSlot(int slot, java.util.function.Consumer<PadState> mutation, boolean changed) {
if (slot <= 0) { applyExternal(mutation, changed); return; }
if (slot >= SLOTS || !bridgeSlots[slot]) return;
mutation.accept(playerStates[slot]);
if (changed) notePlayerInput();
publish(slot);
}
public synchronized void setSystemButtons(boolean guidePressed, boolean qamPressed) {
if (!builtinPad) return;
if (systemGuidePressed == guidePressed && systemQamPressed == qamPressed) return;
@@ -561,7 +597,7 @@ public final class PadBridge {
return slot;
}
for (int slot = firstPlayerSlot(); slot < SLOTS; slot++) {
if (owners[slot] != NO_CONTROLLER) continue;
if (owners[slot] != NO_CONTROLLER || bridgeSlots[slot]) continue;
owners[slot] = id;
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") is player " + (slot + 1));
return slot;
@@ -62,7 +62,7 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
val wanted = FakeInputWriter.readImuMode(SLOT) != 0 ||
touch != null && touch.plugged && touch.gyroRequested && touch.motionEnabled
idlePolls = if (wanted) 0 else idlePolls + 1
if (wanted && !reading) {
if (wanted && !DualSenseBridge.isActive() && !reading) {
reading = true
turnAt = 0L
gyroscope?.let { sensors?.registerListener(this, it, SAMPLING_US, handler) }
@@ -83,6 +83,7 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
}
override fun onSensorChanged(event: SensorEvent) {
if (DualSenseBridge.isActive()) return
if (!active) return
val values = event.values
if (event.timestamp - turnAt > ROTATION_REFRESH_NS) {
@@ -110,6 +110,11 @@ public final class LinuxRuntime {
File root = rootDir(context);
List<String> binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds);
if (sessionRoot != null) lastBinds = binds;
return commandWithBinds(context, root, binds, guestCommand);
}
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
List<String> guestCommand) {
List<String> cmd = prootPrefix(context, root, "/root");
for (String spec : binds) bind(cmd, spec);
cmd.addAll(guestCommand);
@@ -51,7 +51,7 @@ object BootMovie {
SessionPrefs.setBootMovieApplyNext(context, true)
BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}")
// Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later.
SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
}
fun customName(context: Context): String? =
@@ -167,10 +167,12 @@ object BootMovie {
* that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed.
*/
fun syncFromSteam(context: Context): Boolean {
val path = SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context)) ?: return false
if (path == SessionPrefs.bootMovieSteamSeen(context)) return false
SessionPrefs.setBootMovieSteamSeen(context, path)
if (path == SessionFiles.BOOT_MOVIE_PATH) return false
val named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false
val seen = SessionPrefs.bootMovieSteamSeen(context)
if (named == seen) return false
SessionPrefs.setBootMovieSteamSeen(context, named)
if (named == SessionFiles.BOOT_MOVIE_PATH || (named.isEmpty() && seen == null)) return false
val path = named.ifEmpty { "/movies/steam_os_startup.webm" }
val prefix = "/uioverrides/movies/"
// The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder.
val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else {
@@ -79,8 +79,9 @@ object BootMovieLibrary {
return customMovieDirs(context).map { File(it, name) }.firstOrNull { it.isFile && it.length() > 0L }
}
private fun isMovie(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) &&
file.name !in STAGED && !file.name.startsWith(".")
private fun isMovie(file: File) = isWebm(file) && file.name !in STAGED
private fun isWebm(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) && !file.name.startsWith(".")
private fun readMeta(context: Context): JSONObject =
runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject())
@@ -136,7 +137,7 @@ object BootMovieLibrary {
}
val bought = HashMap<String, String>()
for (root in steamRoots(context)) {
File(root, "steamui/movies").listFiles { f -> isMovie(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty()
File(root, "steamui/movies").listFiles { f -> isWebm(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty()
.sortedBy { it.name.lowercase() }.forEach { steam.putIfAbsent(STEAM_PREFIX + "/movies/" + it.name, it) }
val scan = pointShopMovies(root)
bought.putAll(scan.titles)
@@ -144,8 +145,8 @@ object BootMovieLibrary {
}
val seen = HashSet<String>()
for ((id, file) in steam) {
if (file.name in STAGED || !seen.add(file.canonicalPath)) continue
val native = file.nameWithoutExtension.lowercase() in NATIVE
if ((file.name in STAGED && !native) || !seen.add(file.canonicalPath)) continue
// Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it.
val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension
out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false))
@@ -153,8 +154,11 @@ object BootMovieLibrary {
return out
}
/** The three startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
private val NATIVE = mapOf("deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup")
/** The four startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
private val NATIVE = mapOf(
"deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup",
"steam_os_startup" to "SteamOS startup",
)
private val skippedFolders = setOf("uioverrides", "steamapps", "librarycache", "httpcache", "logs", "compatdata", "shadercache")
@@ -721,13 +721,19 @@ object ComponentsManager {
class StoredOriginal(val protonId: String, val protonName: String?, val comp: String, val protonVersion: String, val size: Long, val kept: Boolean)
class Stored(val packages: List<StoredPackage>, val originals: List<StoredOriginal>)
private fun packagesInUse(state: JSONObject): Set<String> {
internal fun liveSelection(key: String, entry: JSONObject, proton: Proton?): Boolean =
proton != null && (key == "queued" || entry.optString("protonVersion") == proton.version)
private fun packagesInUse(state: JSONObject, installed: Map<String, Proton>): Set<String> {
val names = HashSet<String>()
for (key in listOf("active", "queued")) {
val byProton = state.optJSONObject(key) ?: continue
for (pid in byProton.keys()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys()) comps.optJSONObject(comp)?.optString("file")?.takeIf { it.isNotEmpty() }?.let(names::add)
for (comp in comps.keys()) {
val entry = comps.optJSONObject(comp) ?: continue
if (liveSelection(key, entry, installed[pid])) entry.optString("file").takeIf { it.isNotEmpty() }?.let(names::add)
}
}
}
val profiles = state.optJSONObject("profiles")
@@ -747,8 +753,8 @@ object ComponentsManager {
fun stored(context: Context): Stored = synchronized(lock) {
val state = loadState(context)
val used = packagesInUse(state)
val installed = protons(context).associateBy { it.id }
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
val used = packagesInUse(state, installed)
val originals = originalsDir(context).listFiles()?.filter { it.isDirectory }?.flatMap { proton ->
proton.listFiles()?.filter { it.isDirectory }?.flatMap { version ->
COMPONENTS.mapNotNull { comp ->
@@ -774,27 +780,87 @@ object ComponentsManager {
true
}
fun carryOver(context: Context, fromDir: String, toDir: String) {
synchronized(lock) {
val target = protons(context).firstOrNull { it.id == safeName(toDir) } ?: return
val state = loadState(context)
val wanted = carried(state, safeName(fromDir)) { File(packagesDir(context), it).isFile }
val active = state.sub("active").optJSONObject(target.id)
val queued = state.sub("queued").sub(target.id)
var changed = false
wanted.forEach { (comp, entry) ->
if (active?.has(comp) != true && !queued.has(comp)) {
queued.put(comp, entry)
changed = true
}
}
if (queued.length() == 0) state.sub("queued").remove(target.id)
if (changed) saveState(context, state)
}
}
internal fun carried(state: JSONObject, from: String, present: (String) -> Boolean): Map<String, JSONObject> = buildMap {
state.optJSONObject("active")?.optJSONObject(from)?.let { active ->
active.keys().forEach { comp ->
val entry = active.optJSONObject(comp) ?: return@forEach
val file = entry.optString("file")
if (comp in COMPONENTS && file.endsWith(".wcp") && present(file)) {
put(comp, JSONObject().put("kind", "package").put("file", file).put("label", entry.optString("label")))
}
}
}
state.optJSONObject("queued")?.optJSONObject(from)?.let { queued ->
queued.keys().forEach { comp ->
val entry = queued.optJSONObject(comp) ?: return@forEach
if (comp in COMPONENTS && entry.optString("kind") == "package" && present(entry.optString("file"))) put(comp, entry)
}
}
}
fun forgetProton(context: Context, dirName: String) {
synchronized(lock) {
val id = safeName(dirName)
if (protons(context).any { it.id == id }) return
val state = loadState(context)
val selected = listOf("active", "queued").map { state.sub(it).remove(id) != null }.any { it }
if (selected && runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "forget $id", it) }.isFailure) return
File(originalsDir(context), id).deleteRecursively()
}
}
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val queued = state.sub("queued")
for (pid in queued.keys()) {
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
}
val active = state.sub("active")
for (pid in active.keys()) {
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
}
val profiles = state.sub("profiles")
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) }
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
var changed = false
for (key in listOf("queued", "active")) {
val byProton = state.sub(key)
for (pid in byProton.keys().asSequence().toList()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val entry = comps.optJSONObject(comp) ?: continue
if (entry.optString("file") != name) continue
check(!liveSelection(key, entry, installed[pid])) { context.getString(R.string.cmgr_package_in_use, name, installed[pid]?.name ?: pid) }
comps.remove(comp)
changed = true
}
if (comps.length() == 0) byProton.remove(pid)
}
}
val f = File(packagesDir(context), name)
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
f.delete()
val profiles = state.sub("profiles")
for (scope in profiles.keys().asSequence().toList()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS.filter { profile.optString(it) == name }) {
rememberProfiledComponent(state, comp)
profile.remove(comp)
changed = true
}
if (profile.length() == 0) profiles.remove(scope)
}
check(f.delete()) { name }
if (changed) saveState(context, state)
context.getString(R.string.cmgr_deleted, name)
}
@@ -87,11 +87,10 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
if (line.startsWith("== STEP ")) {
stepAt = at
stepText = line.substringAfter("== STEP ").substringAfter(' ')
val m = INSTALL_COUNT.find(line)
if (m != null) {
clientDownload(line)?.let { (what, percent) ->
clientDownloadAt = at
clientDownload = m.groupValues[1]
clientPercent = m.groupValues[2].toInt() * 100 / maxOf(1, m.groupValues[3].toInt())
clientDownload = what
clientPercent = percent
}
} else {
val m = UPDATE_PROGRESS.find(line)
@@ -132,6 +131,19 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
}
}
internal fun clientDownload(line: String): Pair<String, Int>? {
val count = INSTALL_COUNT.find(line) ?: return null
val mb = INSTALL_MEGABYTES.find(line.substring(count.range.last + 1))
val done = mb?.groupValues?.get(1)?.toLongOrNull()
val total = mb?.groupValues?.get(2)?.toLongOrNull()
if (done != null && total != null && total > 0) {
return "$done / $total MB" to (done * 100 / total).toInt().coerceIn(0, 100)
}
val part = count.groupValues[2].toIntOrNull() ?: return null
val all = count.groupValues[3].toIntOrNull() ?: return null
return count.groupValues[1] to (part.toLong() * 100 / maxOf(1, all)).coerceIn(0L, 100L).toInt()
}
internal fun readableScriptStep(scriptStep: String): Boolean {
val t = scriptStep.lowercase()
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
@@ -140,5 +152,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
private const val TAIL_BYTES = 48L * 1024
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
}
}
@@ -114,12 +114,19 @@ object ProtonDefault {
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
if (choices.values.none { it != null && !it.valve && it.dir in from }) return null
return choices.mapValues { (_, choice) -> if (choice != null && !choice.valve && choice.dir in from) GameChoice(false, to) else choice }
}
@Synchronized
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
require(GameEnvironment.validScope(scope))
fun moveGames(context: Context, from: Set<String>, to: String) {
val d = dir(context)
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
val moved = movedGames(parseGames(read(File(d, GAMES))), from, to) ?: return
writeGames(d, moved)
}
private fun writeGames(d: File, choices: Map<String, GameChoice?>) {
val games = JSONObject()
choices.forEach { (id, choice) ->
games.put(id, choice?.let { JSONObject().put("valve", it.valve).put("dir", it.dir) } ?: JSONObject.NULL)
@@ -134,6 +141,15 @@ object ProtonDefault {
Log.w(TAG, "could not write the per-game Proton request", e)
throw e
}
}
@Synchronized
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
require(GameEnvironment.validScope(scope))
val d = dir(context)
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
writeGames(d, choices)
val state = state(context)
val tool = proton?.let { selected -> state.tools.firstOrNull { it.valve == selected.valve && it.dir == selected.dir.name } }
return if (SessionState.running && state.live && (proton == null || tool != null && state.pending != tool.name)) {
@@ -16,16 +16,20 @@ object ProtonExtras {
private const val TAG = "ProtonExtras"
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
const val CHECK_EVERY_MS = 6L * 60 * 60 * 1000
const val CHECK_EVERY_MS = 60L * 60 * 1000
@Volatile
var installInProgress = false
private set
@Volatile
private var replacing = false
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null)
const val OWN = "droiddeck"
val tools = listOf(
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
@@ -78,11 +82,23 @@ object ProtonExtras {
fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool))
fun missing(context: Context, tool: Tool): String? =
if (tool.id == OWN && !declined(context) && installedAll(context, tool).isEmpty()) cachedLatest(context, tool) else null
private fun choices(context: Context) = context.getSharedPreferences("proton-auto-updates", Context.MODE_PRIVATE)
fun declined(context: Context): Boolean = choices(context).getBoolean("$OWN.declined", false)
fun setDeclined(context: Context, declined: Boolean) {
choices(context).edit().putBoolean("$OWN.declined", declined).apply()
}
fun cachedLatest(context: Context, tool: Tool): String? =
readJson(latestFile(context)).optJSONObject(tool.id)?.optString("tag")?.ifEmpty { null }
private val checkLock = Any()
private const val RETRY_MS = 15L * 60 * 1000
private const val USER_SETTINGS = "user_settings.py"
private var lastAttempt = 0L
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
@@ -136,11 +152,51 @@ object ProtonExtras {
fun remove(context: Context, tool: Tool, dir: String? = null) {
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
File(toolsDir(context), name).deleteRecursively()
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name)
}
fun removeOlder(context: Context, tool: Tool) {
installedAll(context, tool).dropLast(1).forEach { File(toolsDir(context), it).deleteRecursively() }
installedAll(context, tool).dropLast(1).forEach {
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
}
}
private fun replaceOlder(context: Context, tool: Tool) {
val all = installedAll(context, tool)
val newest = all.lastOrNull() ?: return
val older = all.dropLast(1)
if (older.isEmpty()) return
replacing = true
try {
for (old in older.asReversed()) {
if (SessionState.running) break
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
else Log.w(TAG, "could not remove $old")
}
} finally {
replacing = false
}
}
private fun keepUserSettings(context: Context, old: String, newest: String) {
val from = File(File(toolsDir(context), old), USER_SETTINGS)
val to = File(File(toolsDir(context), newest), USER_SETTINGS)
if (from.isFile && !to.exists()) from.copyTo(to)
}
fun tidy(context: Context) {
val tool = tools.firstOrNull { it.id == OWN } ?: return
if (installedAll(context, tool).size > 1) replaceOlder(context, tool)
}
fun awaitReplacement(timeoutMs: Long) {
val until = System.currentTimeMillis() + timeoutMs
while (replacing && System.currentTimeMillis() < until) {
try { Thread.sleep(50) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return }
}
}
@Synchronized
@@ -244,6 +300,7 @@ object ProtonExtras {
archive.delete()
unqueue(context, tool)
record(context, tool, placed, asset.tag)
if (tool.id == OWN) replaceOlder(context, tool)
if (EsyncPacks.enabled(context)) {
onProgress(context.getString(R.string.esync_fetching), -1)
try {
@@ -37,6 +37,7 @@ class RumbleComponent : SessionPart() {
}
internal var controllerMotors: (Int) -> Motors? = ::lookupController
internal var bridgeRumble: (Int, Int, Int, Int) -> Boolean = com.droiddeck.launcher.input.DualSenseBridge::routeRumble
internal var motorLooper: Looper? = null
@Synchronized private fun refreshEnabled() {
@@ -90,6 +91,11 @@ class RumbleComponent : SessionPart() {
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
if (!enabled) return
if (bridgeRumble(slot, strong, weak, ms)) {
playing.remove(slot)?.cancel()
forget(slot)
return
}
val target = target(slot)
val previous = playing[slot]
if (target !== previous) {
@@ -200,22 +200,86 @@ object SessionArtifacts {
internal fun recordedClient(dir: File): String? =
runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" }
private const val LOG_MARKS = "steam-log-marks.txt"
private const val MAX_STEAM_LOG = 8L * 1024 * 1024
private const val HEAD = 4096L
private class Mark(val size: Long, val head: String)
fun markSteamLogs(dir: File, logs: File) {
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
val size = f.length()
head(f, size)?.let { "$size\t$it\t${f.name}" }
} ?: return
runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) }
}
private fun head(f: File, length: Long): String? = runCatching {
val buf = ByteArray(minOf(length, HEAD).toInt())
f.inputStream().use { input ->
var off = 0
while (off < buf.size) {
val n = input.read(buf, off, buf.size - off)
if (n < 0) return@runCatching null
off += n
}
}
java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) }
}.getOrNull()
private fun steamLogMarks(dir: File): List<Mark>? = runCatching {
File(dir, LOG_MARKS).readLines().mapNotNull { line ->
val parts = line.split('\t', limit = 3)
parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } }
}
}.getOrNull()
private fun startOf(src: File, size: Long, marks: List<Mark>): Long {
val heads = HashMap<Long, String?>()
return marks.filter { it.size <= size }.sortedByDescending { it.size }
.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) {
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
if (!logs.isDirectory) return
val out = File(dir, "steam").apply { mkdirs() }
logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }?.forEach { src ->
copySessionLogs(logs, dir, out).forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
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> {
val marks = steamLogMarks(dir)
val copied = ArrayList<File>()
logs.listFiles { f -> f.isFile }?.forEach { src ->
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
try {
val dst = File(out, src.name)
dst.bufferedWriter().use { w ->
src.forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
src.inputStream().buffered().use { input ->
var left = if (from > 0) from - 1 else 0L
while (left > 0) {
val skipped = input.skip(left)
if (skipped <= 0) break
left -= skipped
}
if (from > 0 && input.read() != '\n'.code) {
while (true) {
val c = input.read()
if (c < 0 || c == '\n'.code) break
}
}
dst.bufferedWriter().use { w ->
input.bufferedReader().forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
}
}
record.files[dst] = Scrubbed(dst.length(), dst.lastModified())
copied.add(dst)
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${src.name}", e)
}
}
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
return copied
}
@Synchronized
@@ -61,6 +61,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders",
"usr/local/bin/droiddeck-steam-desktop-ui" to "usr/local/bin/droiddeck-steam-desktop-ui",
"usr/local/bin/droiddeck-steam-library" to "usr/local/bin/droiddeck-steam-library",
"usr/local/bin/droiddeck-steam-share" to "usr/local/bin/droiddeck-steam-share",
"usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists",
"usr/local/bin/droiddeck-launcher-cores" to "usr/local/bin/droiddeck-launcher-cores",
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
@@ -390,10 +391,12 @@ object SessionFiles {
private fun activeStartupMovie(text: String): VdfBlock? = customizationMovie(text) ?: olderMovie(text)
/** The movie Steam's config selects, as a path like `/uioverrides/movies/x.webm`; null when none is named. */
internal fun startupMoviePath(config: File): String? {
internal fun startupMoviePath(config: File): String? = startupMovieLocalPath(config)?.takeIf { it.isNotEmpty() }
internal fun startupMovieLocalPath(config: File): String? {
val text = runCatching { config.readText() }.getOrNull() ?: return null
val movie = activeStartupMovie(text) ?: return null
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")?.takeIf { it.isNotEmpty() }
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")
}
/** Both `StartupMovie` sections of Steam's config as written there, for the report; null when there is none. */
@@ -4,7 +4,6 @@ import android.content.Context
import android.content.pm.ActivityInfo
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.CpuAllocationDefaults
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.Cardboard
@@ -43,6 +42,12 @@ object SessionPrefs {
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
fun sdl3Controllers(context: Context): Boolean = prefs(context).getBoolean("sdl3Controllers", false)
fun setSdl3Controllers(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean("sdl3Controllers", enabled).apply()
}
val orientationOptions = listOf(
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
@@ -92,13 +97,6 @@ object SessionPrefs {
*/
fun storesEpicMode(context: Context): String = prefs(context).getString("storesEpicMode", "adaptive") ?: "adaptive"
fun storesOpenTab(context: Context): String =
prefs(context).getString("storesOpenTab", STORES_OPEN_LIBRARY)?.takeIf { it == STORES_OPEN_STORE } ?: STORES_OPEN_LIBRARY
fun setStoresOpenTab(context: Context, tab: String) {
prefs(context).edit().putString("storesOpenTab", if (tab == STORES_OPEN_STORE) STORES_OPEN_STORE else STORES_OPEN_LIBRARY).apply()
}
fun storesShowMature(context: Context): Boolean = prefs(context).getBoolean("storesShowMature", false)
fun setStoresShowMature(context: Context, show: Boolean) {
@@ -136,9 +134,6 @@ object SessionPrefs {
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
val STORES_VIEWS = listOf("cards", "capsules", "list")
const val STORES_OPEN_LIBRARY = "library"
const val STORES_OPEN_STORE = "store"
fun storesInstallTarget(context: Context): String = prefs(context).getString("storesInstallTarget", "") ?: ""
fun setStoresInstallTarget(context: Context, path: String) {
@@ -382,30 +377,19 @@ object SessionPrefs {
prefs(context).edit().putBoolean("wifiDiscoveryAsked", true).apply()
}
internal data class CoreAllocation(val clientOverride: Boolean, val clientCpus: String, val gameCpus: String)
internal fun coreAllocation(context: Context, defaults: CpuAllocationDefaults.Allocation? = CpuAllocationDefaults.device): CoreAllocation {
val saved = prefs(context)
return CoreAllocation(
saved.getBoolean("clientCpusOverride", defaults != null && !saved.contains("clientCpus")),
saved.getString("clientCpus", defaults?.client.orEmpty()).orEmpty(),
saved.getString("gameCpus", defaults?.game.orEmpty()).orEmpty(),
)
}
fun clientCpusOverride(context: Context): Boolean = coreAllocation(context).clientOverride
fun clientCpusOverride(context: Context): Boolean = prefs(context).getBoolean("clientCpusOverride", false)
fun setClientCpusOverride(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("clientCpusOverride", on).apply()
}
fun clientCpus(context: Context): String = coreAllocation(context).clientCpus
fun clientCpus(context: Context): String = prefs(context).getString("clientCpus", "").orEmpty()
fun setClientCpus(context: Context, list: String) {
prefs(context).edit().putString("clientCpus", list).apply()
}
fun gameCpus(context: Context): String = coreAllocation(context).gameCpus
fun gameCpus(context: Context): String = prefs(context).getString("gameCpus", "").orEmpty()
fun setGameCpus(context: Context, list: String) {
prefs(context).edit().putString("gameCpus", list).apply()
@@ -71,6 +71,7 @@ class SessionService : Service() {
private val steamDownloadMonitor = SteamDownloadMonitor()
private var downloadMonitorTask: Runnable? = null
private var downloadActive = false
private var clientInstallActive = false
@Volatile private var steamLibraryMounts = emptyMap<String, File>()
private var suspendDownloadNow = false
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
@@ -168,6 +169,7 @@ class SessionService : Service() {
updateSuspendPolicy()
}
@Volatile private var sessionGen = 0
private var bridgeSession: Any? = null
override fun onCreate() {
super.onCreate()
@@ -277,6 +279,16 @@ class SessionService : Service() {
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_MIC_CHANGED -> {
if (SessionState.running && SessionState.micAvailable && !SessionState.suspended) {
val enabled = intent.getBooleanExtra("enabled", false)
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
if (relay?.setMicEnabled(enabled) != true) {
android.widget.Toast.makeText(this, R.string.drawer_mic_failed, android.widget.Toast.LENGTH_LONG).show()
}
}
return START_NOT_STICKY
}
ACTION_SUSPEND_POLICY_CHANGED -> {
if (!SessionState.running) return START_NOT_STICKY
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
@@ -303,6 +315,7 @@ class SessionService : Service() {
}
startForeground(NOTIFICATION_ID, buildNotification())
if (SessionState.running) return START_NOT_STICKY
bridgeSession = Any().also { com.droiddeck.launcher.input.DualSenseBridge.beginSession(it) }
if (SessionState.stopRequested) {
SessionState.running = true
stopSession(0)
@@ -321,12 +334,15 @@ class SessionService : Service() {
suspendDownloadNow = false
steamDownloadMonitor.reset()
downloadActive = false
clientInstallActive = false
steamSleepToken = null
completeNativeSleep()
suspendOperationPending = false
freezePending = false
suspendAttemptFailed = false
suspendController = null
SessionState.micAvailable = false
SessionState.micEnabled = false
SessionState.suspended = false
SessionState.resumeRequested = false
SessionState.resuming = false
@@ -358,6 +374,7 @@ class SessionService : Service() {
acquireLocks()
Thread({
OrphanReaper.reap("session starting")
ProtonExtras.awaitReplacement(120_000)
runSession(gen)
}, "session-start").start()
return START_NOT_STICKY
@@ -640,8 +657,8 @@ class SessionService : Service() {
}
},
)
mainHandler.post { updateSuspendPolicy() }
updateDownloadMonitoring()
mainHandler.post { updateSuspendPolicy() }
}
}
@@ -708,7 +725,10 @@ class SessionService : Service() {
SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null
SessionState.steamClientArch?.let { arch ->
guest.add("BL_STEAM_CLIENT_ARCH=$arch")
SessionPaths.current()?.let { SessionArtifacts.recordClient(it, arch) }
SessionPaths.current()?.let {
SessionArtifacts.recordClient(it, arch)
SessionArtifacts.markSteamLogs(it, File(SessionPrefs.steamRoot(this, arch), "logs"))
}
if (arch == "x86_64") FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) }
}
if (SessionState.mode == MODE_STEAM) {
@@ -756,6 +776,15 @@ class SessionService : Service() {
components.add(pulse)
if (wantsDirectAudio || wantsMic) {
val relay = DirectAudioRelayComponent(relaySocket, micFifo)
val gen = sessionGen
relay.onMicEnabled = java.util.function.Consumer { enabled ->
mainHandler.post {
if (gen == sessionGen && SessionState.running && wantsMic) {
SessionState.micAvailable = true
SessionState.micEnabled = enabled
}
}
}
relay.setLogFile(audioLog)
relay.attach(this)
components.add(relay)
@@ -788,14 +817,21 @@ class SessionService : Service() {
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
guest.add("FAKE_EVDEV_VIBRATION=1")
val uinput = !File(Environment.getExternalStorageDirectory(), NO_UINPUT_SWITCH).exists()
val wantsDeck = uinput && builtinPad && SessionState.mode == MODE_STEAM &&
SessionState.steamUi != "desktop" &&
// sdl3bridge: the desktop (and Steam's desktop UI) get the deck pad too while the SDL3 bridge is installed,
// so its "present as" types and Steam Native Hook-up work there like in the Steam session
val sdl3Desktop = (SessionState.mode == MODE_DESKTOP ||
(SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop")) &&
com.droiddeck.launcher.input.HookupBridge.wanted(this)
val wantsDeck = uinput && builtinPad && (SessionState.mode == MODE_STEAM &&
SessionState.steamUi != "desktop" || sdl3Desktop) &&
!File(Environment.getExternalStorageDirectory(), NO_DECK_PAD_SWITCH).exists()
val wantsTouch = wantsDeck && !File(Environment.getExternalStorageDirectory(), NO_STEAM_TOUCH_SWITCH).exists()
val wantsTriton = wantsDeck && SteamControllerBle.hasPairedController(this)
val wantsTouch = wantsDeck && !sdl3Desktop && !File(Environment.getExternalStorageDirectory(), NO_STEAM_TOUCH_SWITCH).exists()
val wantsTriton = wantsDeck && (SteamControllerBle.hasPairedController(this) || com.droiddeck.launcher.input.HookupBridge.wanted(this))
deckBinds = if (wantsDeck) SteamDeckPad.prepare(this, fakeInputDir.parentFile!!.parentFile!!, wantsTouch, wantsTriton,
SessionPrefs.padType(SessionPrefs.steamController(this))) else emptyList()
SessionState.deckPad = deckBinds.isNotEmpty()
if (sdl3Desktop && SessionState.deckPad) Log.i(TAG, "deck pad: on for the SDL3 bridge on the desktop " +
"(Steam gets the controller as the bridge presents it; other programs keep Xbox 360 pads)")
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
logControllersAtStart()
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatencyController(this), SessionPrefs.lowLatencyTouch(this))
@@ -803,6 +839,7 @@ class SessionService : Service() {
guest.add("FAKE_EVDEV_UINPUT=1")
if (SessionState.deckPad) {
guest.add("FAKE_EVDEV_DECK=1")
if (SessionState.mode == MODE_DESKTOP) guest.add("FAKE_EVDEV_DESKTOP=1") // sdl3bridge
if (wantsTriton) guest.add("FAKE_EVDEV_TRITON=1")
val padType = SessionPrefs.steamController(this)
guest.add("FAKE_EVDEV_PAD_TYPE=$padType")
@@ -811,6 +848,8 @@ class SessionService : Service() {
if (wantsTouch) com.droiddeck.launcher.input.SteamTouchDevice.prepare(fakeInputDir)?.let {
guest.add("FAKE_TOUCHCTL_RING=" + it.path)
}
if (com.droiddeck.launcher.input.HookupBridge.wanted(this))
com.droiddeck.launcher.input.HookupBridge.prepare(fakeInputDir, File(sessionDir, "pad.log"))?.let { guest.add("FAKE_HOOKUP_SHM=" + it.path) }
guest.add("FAKE_DECK_SYSFS_LISTING=" + SteamDeckPad.listingDir(fakeInputDir.parentFile!!.parentFile!!).path)
}
} else if (SessionState.mode == MODE_STEAM) {
@@ -822,7 +861,7 @@ class SessionService : Service() {
guest.add("FAKE_EVDEV_LOG=1")
guest.add("FAKE_EVDEV_LOG_FILE=" + File(sessionDir, "pad.log").path)
inputSysfs = InputSysfsComponent(fakeInputDir, File(fakeInputDir.parentFile!!.parentFile!!, "sys/input"),
File(LinuxRuntime.rootDir(this), "run/udev/data"), SessionState.deckPad, !uinput && SessionState.mode == MODE_STEAM)
File(LinuxRuntime.rootDir(this), "run/udev/data"), SessionState.deckPad && SessionState.mode != MODE_DESKTOP, !uinput && SessionState.mode == MODE_STEAM)
.takeIf { it.prepare() }
SessionState.fakeInputDir = fakeInputDir
}
@@ -1413,8 +1452,7 @@ class SessionService : Service() {
private fun updateSuspendPolicy() {
if (!SessionState.running) return
val hidden = !hasVisibleSurface
val downloadsBlockingSuspend = steamDownloadsInBackground && SessionState.mode == MODE_STEAM &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER && hidden && downloadActive && !suspendDownloadNow
val downloadsBlockingSuspend = downloadsKeepAwake() && hidden && !suspendDownloadNow
if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && hidden && !downloadsBlockingSuspend) {
manualPauseRequested = true
} else if (!hidden && !SessionState.suspended) {
@@ -1647,19 +1685,23 @@ class SessionService : Service() {
completeNativeSleep()
val (ended, endedArch) = synchronized(stopLock) {
if (!SessionState.running) return
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
SessionState.running = false
bridgeSession?.let { com.droiddeck.launcher.input.DualSenseBridge.endSession(it) }
bridgeSession = null
SessionPaths.take() to SessionState.steamClientArch
}
SessionState.micAvailable = false
SessionState.micEnabled = false
xrActivityVisible = false
updateDownloadMonitoring()
val stoppedGen = sessionGen
val stoppedSession = SessionState.sessionId
val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC
SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
GpuClockPin.stop(this)
GameThreadHints.stop()
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
suspendOperationPending = false
freezePending = false
launchWatcher?.stopWatching()
@@ -1733,6 +1775,8 @@ class SessionService : Service() {
override fun onDestroy() {
stopSession(0)
GameThreadHints.stop() // also when the session never got as far as running
bridgeSession?.let { com.droiddeck.launcher.input.DualSenseBridge.endSession(it) }
bridgeSession = null
if (screenReceiverRegistered) {
unregisterReceiver(screenReceiver)
screenReceiverRegistered = false
@@ -1828,8 +1872,7 @@ class SessionService : Service() {
.setContentText(getString(
when {
SessionState.suspended -> R.string.session_notification_paused
downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER -> R.string.session_notification_downloads
downloadsKeepAwake() -> R.string.session_notification_downloads
else -> R.string.session_notification
}
))
@@ -1837,8 +1880,7 @@ class SessionService : Service() {
.apply {
if (SessionState.suspended) {
addAction(Notification.Action.Builder(null, getString(R.string.resume_session), resume).build())
} else if (downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER) {
} else if (downloadsKeepAwake()) {
val suspend = PendingIntent.getService(
this@SessionService, 3,
Intent(this@SessionService, SessionService::class.java).setAction(ACTION_SUSPEND_NOW),
@@ -1858,33 +1900,50 @@ class SessionService : Service() {
getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, buildNotification())
}
private fun downloadsKeepAwake(): Boolean =
downloadActive && (steamDownloadsInBackground || clientInstallActive) &&
SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER
private fun downloadWatchWanted(): Boolean =
SessionState.running && SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER &&
(steamDownloadsInBackground || !SessionState.firstFrameSeen)
private fun updateDownloadMonitoring() {
val enabled = SessionState.running && SessionState.mode == MODE_STEAM &&
steamDownloadsInBackground && suspendPolicy != SessionPrefs.SUSPEND_NEVER
if (!enabled) {
if (!downloadWatchWanted()) {
val wasActive = downloadActive
downloadMonitorTask?.let(mainHandler::removeCallbacks)
downloadMonitorTask = null
steamDownloadMonitor.reset()
downloadActive = false
if (clientInstallActive) SessionEvents.record("steam.client_download", mapOf("active" to false))
clientInstallActive = false
if (wasActive) refreshNotification()
return
}
if (downloadMonitorTask != null) return
val poll = object : Runnable {
override fun run() {
if (downloadMonitorTask !== this || !SessionState.running ||
SessionState.mode != MODE_STEAM || !steamDownloadsInBackground ||
suspendPolicy == SessionPrefs.SUSPEND_NEVER) {
if (downloadMonitorTask !== this) return
if (!downloadWatchWanted()) {
downloadMonitorTask = null
updateDownloadMonitoring()
updateSuspendPolicy()
return
}
val root = LinuxRuntime.rootDir(this@SessionService)
val wasActive = downloadActive
downloadActive = steamDownloadMonitor.poll(
LinuxRuntime.rootDir(this@SessionService),
val wasInstalling = clientInstallActive
clientInstallActive = !SessionState.firstFrameSeen &&
(clientInstallActive || SteamDownloadMonitor.clientInstallPending(root))
downloadActive = clientInstallActive || steamDownloadsInBackground && steamDownloadMonitor.poll(
root,
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
client = SessionState.steamClientArch,
mounts = steamLibraryMounts,
)
if (wasInstalling != clientInstallActive) {
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
}
if (wasActive != downloadActive) refreshNotification()
updateSuspendPolicy()
mainHandler.postDelayed(this, DOWNLOAD_POLL_MS)
@@ -1929,6 +1988,7 @@ class SessionService : Service() {
const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME"
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
const val ACTION_AGENT_START = "com.droiddeck.launcher.AGENT_START"
private const val ACTION_MIC_CHANGED = "com.droiddeck.launcher.MIC_CHANGED"
private const val ACTION_SUSPEND_POLICY_CHANGED = "com.droiddeck.launcher.SUSPEND_POLICY_CHANGED"
private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE"
private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN"
@@ -2059,6 +2119,11 @@ class SessionService : Service() {
}.getOrDefault(false)
}
fun setMicEnabled(context: Context, enabled: Boolean) {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_MIC_CHANGED)
.putExtra("enabled", enabled))
}
fun suspendPolicyChanged(context: Context) {
if (!SessionState.running) return
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED))
@@ -46,6 +46,8 @@ object SessionState {
var activityDisplayId = 0
@Volatile
var runtimeDriver: String? = null
var micAvailable by mutableStateOf(false)
var micEnabled by mutableStateOf(false)
var suspended by mutableStateOf(false)
var resumeRequested by mutableStateOf(false)
var resuming by mutableStateOf(false)
@@ -27,6 +27,8 @@ object SteamDeckPad {
private const val TRITON_WIRED_HID = "$TRITON_INTERFACE/0003:28DE:1302.0004"
private const val SONY_DS4_MINOR = 20
private const val SONY_DUALSENSE_MINOR = 21
private const val SONY_DUALSENSE_EDGE_MINOR = 22
private const val SC2015_MINOR = 23
private val DS4_REPORT_DESCRIPTOR = intArrayOf(
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08,
0x85, 0x01, 0x09, 0x20, 0x95, 0x3f, 0x81, 0x02, 0x85, 0x05, 0x09, 0x21, 0x95, 0x1f, 0x91, 0x02,
@@ -82,6 +84,10 @@ object SteamDeckPad {
fun listingDir(sessionRoot: File) = File(sessionRoot, "sys/deck/listing")
// sdl3bridge: where the session sysfs lives, for HookupBridge (Steam Native Hook-up) hot-plug
@Volatile @JvmStatic var sysDevicesDir: File? = null
@Volatile @JvmStatic var sysHidrawClassDir: File? = null
@Volatile @JvmStatic var sysContext: Context? = null
private val padNodes = mutableMapOf<Int, String>()
@Volatile private var hidrawClassDir: File? = null
@@ -93,6 +99,8 @@ object SteamDeckPad {
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_STEAM -> TRITON_PAD_MINOR
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DS4 -> SONY_DS4_MINOR
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DUALSENSE -> SONY_DUALSENSE_MINOR
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DUALSENSE_EDGE -> SONY_DUALSENSE_EDGE_MINOR
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_STEAM_2015 -> SC2015_MINOR
else -> -1
}
for ((minor, target) in padNodes) {
@@ -224,12 +232,8 @@ object SteamDeckPad {
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
Log.i(TAG, "steam controller: /dev/$node described as Triton (28de:$product)")
}
fun describeSony(dualSense: Boolean) {
val bus = if (dualSense) 5 else 4
val product = if (dualSense) "0ce6" else "09cc"
val minor = if (dualSense) SONY_DUALSENSE_MINOR else SONY_DS4_MINOR
fun describeSony(bus: Int, product: String, minor: Int, name: String, sonyDescriptor: ByteArray) {
val node = "hidraw$minor"
val name = if (dualSense) "DualSense Wireless Controller" else "Wireless Controller"
val usb = "$GUEST_DEVICES/usb$bus"
val iface = "$usb/$bus-1:1.3"
val hid = "$iface/0003:054C:${product.uppercase()}.000${bus + 1}"
@@ -247,7 +251,7 @@ object SteamDeckPad {
write(hid, "uevent", "DRIVER=hid-generic\nHID_ID=0003:0000054C:0000${product.uppercase()}\n" +
"HID_NAME=Sony Interactive Entertainment $name\nHID_PHYS=usb-droiddeck-$bus/input3\n" +
"HID_UNIQ=5e:43:4b:44:44:02\nMODALIAS=hid:b0003g0001v0000054Cp0000${product.uppercase()}\n")
File(dir(hid), "report_descriptor").writeBytes(if (dualSense) DUALSENSE_REPORT_DESCRIPTOR else DS4_REPORT_DESCRIPTOR)
File(dir(hid), "report_descriptor").writeBytes(sonyDescriptor)
link(File(dir(hid), "subsystem"), "/sys/bus/hid")
val hidraw = "$hid/hidraw/$node"
write(hidraw, "uevent", "MAJOR=$MAJOR\nMINOR=$minor\nDEVNAME=$node\n")
@@ -259,11 +263,48 @@ object SteamDeckPad {
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
Log.i(TAG, "playstation pad: /dev/$node described as 054c:$product")
}
describeSony(dualSense = false)
describeSony(dualSense = true)
describeSony(4, "09cc", SONY_DS4_MINOR, "Wireless Controller", DS4_REPORT_DESCRIPTOR)
describeSony(5, "0ce6", SONY_DUALSENSE_MINOR, "DualSense Wireless Controller", DUALSENSE_REPORT_DESCRIPTOR)
describeSony(6, "0df2", SONY_DUALSENSE_EDGE_MINOR, "DualSense Edge Wireless Controller", DUALSENSE_REPORT_DESCRIPTOR)
fun describeSteamController2015() {
val usb = "$GUEST_DEVICES/usb7"
val iface = "$usb/7-1:1.2"
val hid = "$iface/0003:28DE:1102.0008"
val node = "hidraw$SC2015_MINOR"
write(usb, "uevent", "DEVTYPE=usb_device\nPRODUCT=28de/1102/100\nTYPE=0/0/0\nBUSNUM=007\nDEVNUM=002\n")
write(usb, "idVendor", "28de\n")
write(usb, "idProduct", "1102\n")
write(usb, "bcdDevice", "0100\n")
write(usb, "manufacturer", "Valve Software\n")
write(usb, "product", "Steam Controller\n")
write(usb, "serial", "DROIDDECKSC15\n")
link(File(dir(usb), "subsystem"), "/sys/bus/usb")
write(iface, "uevent", "DEVTYPE=usb_interface\nPRODUCT=28de/1102/100\nINTERFACE=3/0/0\n")
write(iface, "bInterfaceNumber", "02\n")
write(iface, "bInterfaceClass", "03\n")
link(File(dir(iface), "subsystem"), "/sys/bus/usb")
write(hid, "uevent", "DRIVER=hid-steam\nHID_ID=0003:000028DE:00001102\n" +
"HID_NAME=Valve Software Steam Controller\nHID_PHYS=usb-droiddeck-7/input2\n" +
"HID_UNIQ=DROIDDECKSC15\nMODALIAS=hid:b0003g0001v000028DEp00001102\n")
File(dir(hid), "report_descriptor").writeBytes(REPORT_DESCRIPTOR)
link(File(dir(hid), "subsystem"), "/sys/bus/hid")
val hidraw = "$hid/hidraw/$node"
write(hidraw, "uevent", "MAJOR=$MAJOR\nMINOR=$SC2015_MINOR\nDEVNAME=$node\n")
write(hidraw, "dev", "$MAJOR:$SC2015_MINOR\n")
link(File(dir(hidraw), "subsystem"), "/sys/class/hidraw")
link(File(dir(hidraw), "device"), hid)
padNodes[SC2015_MINOR] = hidraw
link(File(LinuxRuntime.liveDir(context), "drm/sys/$MAJOR:$SC2015_MINOR"), hidraw)
File(udevData, "c$MAJOR:$SC2015_MINOR").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
Log.i(TAG, "steam controller: /dev/$node described as the 2015 Steam Controller (28de:1102)")
}
describeSteamController2015()
describeTriton(wired = true)
if (triton) describeTriton(wired = false)
hidrawClassDir = hidrawClass
sysDevicesDir = devices
sysHidrawClassDir = hidrawClass
sysContext = context.applicationContext
showPad(padType)
Log.i(TAG, "deck pad: /dev/$NODE described as a Steam Deck controller (28de:1205)")
@@ -1,7 +1,7 @@
package com.droiddeck.launcher.session
import java.io.File
import java.io.RandomAccessFile
import java.io.FileInputStream
internal class SteamDownloadMonitor {
private data class ManifestState(
@@ -63,16 +63,17 @@ internal class SteamDownloadMonitor {
lastContentActivityAt = 0L
}
runCatching {
RandomAccessFile(log, "r").use { input ->
input.seek(contentLogOffset)
FileInputStream(log).use { input ->
input.channel.position(contentLogOffset)
val reader = input.bufferedReader(Charsets.ISO_8859_1)
while (true) {
val line = input.readLine() ?: break
val line = reader.readLine() ?: break
when {
"Client version:" in line -> {
activeContentUpdates.clear()
lastContentActivityAt = 0L
}
CONTENT_UPDATE.find(line)?.let { match ->
" update changed : " in line && CONTENT_UPDATE.find(line)?.let { match ->
val appId = match.groupValues[1]
val updateType = match.groupValues[2]
val state = match.groupValues[3]
@@ -85,14 +86,15 @@ internal class SteamDownloadMonitor {
}
true
} == true -> Unit
CURRENT_RATE.find(line)?.groupValues?.get(1)?.toDoubleOrNull()?.let { it > 0.0 } == true ->
"Current download rate: " in line &&
CURRENT_RATE.find(line)?.groupValues?.get(1)?.toDoubleOrNull()?.let { it > 0.0 } == true ->
lastContentActivityAt = now
"Downloading " in line && " chunks for depot " in line ->
lastContentActivityAt = now
}
if (activeContentUpdates.isNotEmpty()) lastContentActivityAt = now
}
contentLogOffset = input.filePointer
contentLogOffset = input.channel.position()
}
}
return activeContentUpdates.isNotEmpty() && lastContentActivityAt > 0L &&
@@ -138,13 +140,21 @@ internal class SteamDownloadMonitor {
private fun value(text: String, key: String): String? =
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
private companion object {
const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
companion object {
fun clientInstallPending(runtimeRoot: File): Boolean {
val home = File(runtimeRoot, "root")
val steam = File(home, ".local/share/Steam")
val stamped = File(steam, "package/droiddeck-installed").isFile ||
File(steam, "package/bannerlator-installed").isFile
return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists()
}
private const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
private const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
private const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
private val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
private val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
private val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
private val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
}
}
@@ -101,10 +101,28 @@ object WinComponents {
fun cached(context: Context): List<Component>? =
runCatching { parse(File(context.filesDir, CATALOG_CACHE).readText()) }.getOrNull()
const val VCREDIST_ARM64 = "vcredist2022_arm64"
/**
* The ARM64 Visual C++ 2015-2022 runtime as registry values only (the version a 14.44.35211 installer writes, in both
* registry views). Xbox games' launchers running as ARM64EC check for it; Wine's own CRT does the work. Same approach as
* MGamer404's Bannerlator #627. Used until the catalog carries a component of this name.
*/
internal fun builtInArm64Runtime(): Component {
fun value(view: String, name: String, type: String, data: String) = Step("set_register_key", JSONObject()
.put("action", "set_register_key").put("key", "HKLM\\Software\\${view}Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\arm64")
.put("value", name).put("type", type).put("data", data))
val steps = listOf("", "Wow6432Node\\").flatMap { view ->
listOf(value(view, "Installed", "REG_DWORD", "1"), value(view, "Major", "REG_DWORD", "14"), value(view, "Minor", "REG_DWORD", "44"),
value(view, "Bld", "REG_DWORD", "35211"), value(view, "Rbld", "REG_DWORD", "0"), value(view, "Version", "REG_SZ", "v14.44.35211.00"))
}
return Component(VCREDIST_ARM64, "Microsoft Visual C++ 2015-2022 ARM64 runtime 14.44.35211 (registry entries only)", "Microsoft", "ready", emptyList(), steps)
}
private fun parse(body: String): List<Component>? {
return try {
val arr = JSONObject(body).getJSONArray("components")
(0 until arr.length()).mapNotNull { i ->
val listed = (0 until arr.length()).mapNotNull { i ->
val o = arr.getJSONObject(i)
val name = o.optString("name")
if (!validId(name)) return@mapNotNull null
@@ -117,6 +135,7 @@ object WinComponents {
o.optString("snapshot"),
)
}
if (listed.any { it.name == VCREDIST_ARM64 }) listed else listed + builtInArm64Runtime()
} catch (e: Exception) {
Log.w(TAG, "catalog: $e"); null
}
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.stores
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
@@ -13,6 +12,8 @@ import javax.crypto.spec.GCMParameterSpec
object CredentialCipher {
const val VERSION = 1
/** Sealed with the hardware-keystore (TEE) key; [VERSION] envelopes keep opening with the older, possibly StrongBox, key. */
const val VERSION_TEE = 2
const val ALG = "AES/GCM"
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val TAG_BITS = 128
@@ -21,6 +22,11 @@ object CredentialCipher {
fun key(): SecretKey
fun existing(): SecretKey = key()
/** Key for [VERSION] envelopes written before [VERSION_TEE]. */
fun legacy(): SecretKey = existing()
val version: Int get() = VERSION
}
class KeyMissing : java.security.GeneralSecurityException("no key")
@@ -29,33 +35,33 @@ object CredentialCipher {
e is android.security.keystore.KeyPermanentlyInvalidatedException ||
e is KeyMissing || e is org.json.JSONException || e is IllegalArgumentException
// StrongBox took over 10 s per Xbox credential write on a tester's phone, past the backend's
// 10 s reply timeout, so new writes use a TEE key. The old alias stays readable.
object Keystore : KeyProvider {
private const val ALIAS = "droiddeck-store-credentials"
private const val LEGACY_ALIAS = "droiddeck-store-credentials"
private const val ALIAS = "droiddeck-store-credentials-tee"
private const val PROVIDER = "AndroidKeyStore"
@Synchronized
override fun existing(): SecretKey {
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
return ks.getKey(ALIAS, null) as? SecretKey ?: throw KeyMissing()
}
override val version: Int get() = VERSION_TEE
@Synchronized
override fun key(): SecretKey {
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
(ks.getKey(ALIAS, null) as? SecretKey)?.let { return it }
if (Build.VERSION.SDK_INT >= 28) {
try { return generate(strongBox = true) } catch (e: Exception) { }
}
return generate(strongBox = false)
}
override fun existing(): SecretKey = stored(ALIAS) ?: throw KeyMissing()
private fun generate(strongBox: Boolean): SecretKey {
@Synchronized
override fun legacy(): SecretKey = stored(LEGACY_ALIAS) ?: throw KeyMissing()
@Synchronized
override fun key(): SecretKey = stored(ALIAS) ?: generate()
private fun stored(alias: String): SecretKey? =
KeyStore.getInstance(PROVIDER).apply { load(null) }.getKey(alias, null) as? SecretKey
private fun generate(): SecretKey {
val spec = KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setKeySize(256)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setUserAuthenticationRequired(false)
.apply { if (strongBox && Build.VERSION.SDK_INT >= 28) setIsStrongBoxBacked(true) }
.build()
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER).run { init(spec); generateKey() }
}
@@ -64,15 +70,16 @@ object CredentialCipher {
fun seal(plain: String, keys: KeyProvider): JSONObject {
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, keys.key()) }
val ct = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
return JSONObject().put("v", VERSION).put("alg", ALG)
return JSONObject().put("v", keys.version).put("alg", ALG)
.put("iv", b64(cipher.iv)).put("ct", b64(ct))
}
fun open(envelope: JSONObject, keys: KeyProvider): String {
require(envelope.optInt("v", -1) == VERSION && envelope.optString("alg") == ALG) { "unknown envelope" }
val version = envelope.optInt("v", -1)
require((version == VERSION || version == VERSION_TEE) && envelope.optString("alg") == ALG) { "unknown envelope" }
val iv = Base64.decode(envelope.getString("iv"), Base64.NO_WRAP)
val ct = Base64.decode(envelope.getString("ct"), Base64.NO_WRAP)
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, keys.existing(), GCMParameterSpec(TAG_BITS, iv)) }
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, if (version == VERSION) keys.legacy() else keys.existing(), GCMParameterSpec(TAG_BITS, iv)) }
return String(cipher.doFinal(ct), Charsets.UTF_8)
}
@@ -8,8 +8,8 @@ import com.droiddeck.launcher.stores.gog.GogAuth
internal object LoginFlows {
private const val TAG = "StoreLogin"
fun forStore(store: Store, state: String): StoreLoginActivity.Flow? = when (store) {
Store.GOG -> GogFlow(state)
fun forStore(store: Store, state: String, browserUserAgent: String): StoreLoginActivity.Flow? = when (store) {
Store.GOG -> GogFlow(state, browserUserAgent)
Store.EPIC -> epicFlow()
Store.AMAZON -> amazonFlow()
Store.ITCH, Store.XBOX -> null
@@ -18,9 +18,8 @@ internal object LoginFlows {
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
@Volatile var amazonFlow: () -> StoreLoginActivity.Flow? = { null }
private class GogFlow(private val state: String) : StoreLoginActivity.Flow {
private class GogFlow(private val state: String, override val userAgent: String) : StoreLoginActivity.Flow {
override val startUrl: String get() = GogAuth.authUrl(state)
override val userAgent: String get() = GogAuth.GALAXY_UA
override fun isRedirect(url: String): Boolean = url.startsWith(GogAuth.REDIRECT_PREFIX)
override fun forgetSignIn(done: () -> Unit) {
@@ -30,7 +30,7 @@ object SteamLiveShortcuts {
let added = 0;
for (const w of want) {
if (await ${KNOWN}(w.appid, w.name, w.exe)) continue;
if (await ${ADD}(w.name, w.exe, w.dir, true)) added++;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))})) added++;
}
return added;
})()
@@ -46,7 +46,7 @@ object SteamLiveShortcuts {
(async () => {
const known = await ${KNOWN}(${appId?.and(0xFFFFFFFFL) ?: 0}, ${JSONObject.quote(name)}, ${JSONObject.quote(exe)});
if (known) return known;
return await ${ADD}(${JSONObject.quote(name)}, ${JSONObject.quote(exe)}, ${JSONObject.quote(dir)}, $compat);
return await ${ADD}(${JSONObject.quote(name)}, ${JSONObject.quote(exe)}, ${JSONObject.quote(dir)}, $compat, ${JSONObject.quote(compatTool(context))});
})()
""".trimIndent()
val id = evaluate(context, js)?.toLongOrNull()?.and(0xFFFFFFFFL)?.takeIf { it != 0L } ?: return null
@@ -161,12 +161,15 @@ object SteamLiveShortcuts {
return 0;
})"""
private val ADD = """(async (name, exe, dir, compat) => {
private fun compatTool(context: Context): String =
com.droiddeck.launcher.session.ProtonDefault.state(context).default ?: COMPAT_TOOL
private val ADD = """(async (name, exe, dir, compat, tool) => {
const id = await SteamClient.Apps.AddShortcut(name, exe, dir, "");
if (!id) return 0;
try { SteamClient.Apps.SetShortcutName(id, name); } catch (e) {}
try { SteamClient.Apps.AddUserTagToApps([id], ${JSONObject.quote(TAG_NAME)}); } catch (e) {}
if (compat) { try { SteamClient.Apps.SpecifyCompatTool(id, ${JSONObject.quote(COMPAT_TOOL)}); } catch (e) {} }
if (compat) { try { SteamClient.Apps.SpecifyCompatTool(id, tool); } catch (e) {} }
for (let i = 0; i < 40; i++) {
try { if (globalThis.appStore.GetAppOverviewByAppID(id)) break; } catch (e) {}
await new Promise(r => setTimeout(r, 250));
@@ -61,33 +61,38 @@ fun installedCards(store: Store, installed: List<InstalledStoreGame>, library: L
}.distinctBy { it.id }.sortedBy { it.title.lowercase() }
}
private fun releaseDateValue(item: CatalogItem): Long =
item.releaseDate.take(10).takeIf { it.length == 10 }?.let { raw ->
runCatching { java.time.LocalDate.parse(raw).toEpochDay() }.getOrDefault(0L)
private fun releaseDateValue(raw: String): Long =
raw.take(10).takeIf { it.length == 10 }?.let { day ->
runCatching { java.time.LocalDate.parse(day).toEpochDay() }.getOrDefault(0L)
} ?: 0L
fun sortCatalogItems(
items: List<CatalogItem>,
fun <T> sortGames(
items: List<T>,
sort: String,
lastPlayed: (CatalogItem) -> Long = { 0L },
installedAt: (CatalogItem) -> Long = { 0L },
size: (CatalogItem) -> Long = { it.sizeBytes },
): List<CatalogItem> = when (sort) {
"lastPlayed" -> items.sortedWith(compareByDescending(lastPlayed).thenBy { it.title.lowercase() })
"recentlyInstalled" -> items.sortedWith(compareByDescending(installedAt).thenBy { it.title.lowercase() })
"titleAsc" -> items.sortedBy { it.title.lowercase() }
"titleDesc" -> items.sortedByDescending { it.title.lowercase() }
"sizeDesc" -> items.sortedWith(compareByDescending(size).thenBy { it.title.lowercase() })
"sizeAsc" -> items.sortedWith(compareBy<CatalogItem> { size(it).takeIf { b -> b > 0 } ?: Long.MAX_VALUE }.thenBy { it.title.lowercase() })
"releaseDateDesc" -> items.sortedWith(compareByDescending(::releaseDateValue).thenBy { it.title.lowercase() })
else -> items
title: (T) -> String,
releaseDate: (T) -> String,
lastPlayed: (T) -> Long = { 0L },
installedAt: (T) -> Long = { 0L },
size: (T) -> Long = { 0L },
): List<T> {
val byTitle = compareBy<T> { title(it).lowercase() }
return when (sort) {
"lastPlayed" -> items.sortedWith(compareByDescending(lastPlayed).then(byTitle))
"recentlyInstalled" -> items.sortedWith(compareByDescending(installedAt).then(byTitle))
"titleAsc" -> items.sortedWith(byTitle)
"titleDesc" -> items.sortedWith(byTitle.reversed())
"sizeDesc" -> items.sortedWith(compareByDescending(size).then(byTitle))
"sizeAsc" -> items.sortedWith(compareBy<T> { size(it).takeIf { b -> b > 0 } ?: Long.MAX_VALUE }.then(byTitle))
"releaseDateDesc" -> items.sortedWith(compareByDescending<T> { releaseDateValue(releaseDate(it)) }.then(byTitle))
else -> items
}
}
internal fun retainCatalogOrder(items: List<CatalogItem>, previous: List<CatalogItem>): List<CatalogItem> {
internal fun <T> retainOrder(items: List<T>, previous: List<T>, key: (T) -> String): List<T> {
if (items.size != previous.size) return items
val byKey = items.associateBy { it.key }
if (previous.any { it.key !in byKey }) return items
return previous.map { byKey.getValue(it.key) }
val byKey = items.associateBy(key)
if (previous.any { key(it) !in byKey }) return items
return previous.map { byKey.getValue(key(it)) }
}
/** A detail page opens for search results too; the library wins when it already knows the product. */
@@ -104,6 +104,29 @@ object StoreInstallRoot {
.map { it to guestFor(context, it) }
}
/** Xodus has its own PRoot mount table and cannot see the selected Steam library's SD bind. */
fun externalRootsForXodus(context: Context): List<Pair<File, String>> {
val roots = externalRoots(context).toMutableList()
val selectedLibrary = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) }
?.takeUnless { isInternal(context, it) }
if (selectedLibrary != null && roots.none { it.first.absolutePath == selectedLibrary.absolutePath }) {
roots += selectedLibrary to guestFor(context, selectedLibrary)
}
return roots
}
fun externalBindSpecs(context: Context): List<String> = externalBindSpecs(externalRoots(context), LinuxRuntime.rootDir(context))
fun externalBindSpecsForXodus(context: Context): List<String> =
externalBindSpecs(externalRootsForXodus(context), LinuxRuntime.rootDir(context))
internal fun externalBindSpecs(roots: List<Pair<File, String>>, guestRoot: File): List<String> =
roots.mapNotNull { (host, guest) ->
if (!host.isDirectory || !host.canRead()) return@mapNotNull null
val target = File(guestRoot, guest.removePrefix("/"))
if (target.isDirectory || target.mkdirs()) "${host.path}:$guest" else null
}
private fun guestFor(context: Context, root: File): String {
val sm = context.getSystemService(StorageManager::class.java)
val uuid = runCatching { sm?.getStorageVolume(root)?.uuid }.getOrNull()?.takeIf { it.isNotBlank() }?.replace(Regex("[^A-Za-z0-9-]"), "")
@@ -114,11 +137,21 @@ object StoreInstallRoot {
fun isInternal(context: Context, root: File): Boolean = root.absolutePath == internalRoot(context).absolutePath
fun externalGuestPath(context: Context, host: File): String? {
return externalGuestPath(host, externalRoots(context))
}
fun guestPath(context: Context, host: File): String = externalGuestPath(context, host) ?: host.path
fun guestPathForXodus(context: Context, host: File): String =
externalGuestPath(host, externalRootsForXodus(context)) ?: host.path
internal fun externalGuestPath(host: File, roots: List<Pair<File, String>>): String? {
val path = host.absolutePath
for ((root, guest) in externalRoots(context)) {
val dir = root.absolutePath
for ((root, guest) in roots.sortedByDescending { it.first.absolutePath.length }) {
val dir = root.absolutePath.trimEnd(File.separatorChar)
if (path == dir) return guest
if (path.startsWith("$dir/")) return guest + "/" + path.removePrefix("$dir/")
val prefix = dir + File.separator
if (path.startsWith(prefix)) return guest + "/" + path.removePrefix(prefix).replace(File.separatorChar, '/')
}
return null
}
@@ -130,7 +130,7 @@ class StoreLoginActivity : ComponentActivity() {
private fun newFlow(state: String): Flow? {
val url = clientUrl
if (url != null) return com.droiddeck.launcher.stores.epic.EpicClient.loginFlow(url, chromeUa)
return store?.let { LoginFlows.forStore(it, state) }
return store?.let { LoginFlows.forStore(it, state, chromeUa) }
}
override fun finish() {
@@ -14,6 +14,7 @@ import com.droiddeck.launcher.stores.download.DownloadEntry
object StoresState {
private const val TAG = "Stores"
private const val SEARCH_DELAY_MS = 400L
private const val LIBRARY_RETRY_MS = 60_000L
private val main = Handler(Looper.getMainLooper())
val accounts = mutableStateMapOf<Store, String>()
@@ -85,7 +86,7 @@ object StoresState {
main.post {
androidx.compose.runtime.snapshots.Snapshot.withMutableSnapshot {
val restored = found.toMap()
accounts.keys.toList().filter { it !in restored }.forEach { accounts.remove(it) }
accounts.keys.toList().filter { it !in restored }.forEach { accounts.remove(it); libraryAsked.remove(it) }
accounts.putAll(restored)
installed = onDisk
unfinished = partial
@@ -126,7 +127,9 @@ object StoresState {
fun installedGame(store: Store, id: String): InstalledStoreGame? = installed.firstOrNull { it.sidecar.store == store && it.sidecar.id == id }
fun detailItem(store: Store, id: String): CatalogItem? = detailCatalogItem(
store, id, library[store].orEmpty(), found[store].orEmpty(), shelves[store],
store, id, library[store].orEmpty(),
found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items else emptyList(),
shelves[store],
)
fun open(context: Context, store: Store, force: Boolean = false) {
@@ -137,6 +140,18 @@ object StoresState {
if (force || !shelves.containsKey(store)) backend.loadShelves(app, force)
}
private val libraryAsked = java.util.concurrent.ConcurrentHashMap<Store, Long>()
/** Once per store, again after a minute when the last sync never produced a library (offline, expired sign-in). */
fun loadLibrary(context: Context, store: Store) {
if (!isSignedIn(store) || library.containsKey(store)) return
val now = android.os.SystemClock.elapsedRealtime()
val asked = libraryAsked[store]
if (asked != null && now - asked < LIBRARY_RETRY_MS) return
libraryAsked[store] = now
backends[store]?.syncLibrary(context.applicationContext, false)
}
fun preview(context: Context, store: Store) {
if (!shelves.containsKey(store)) backends[store]?.loadShelves(context.applicationContext, false)
}
@@ -163,6 +178,7 @@ object StoresState {
fun signIn(context: Context, store: Store) {
expired.remove(store)
libraryAsked.remove(store)
backends[store]?.signIn(context) ?: logLine("${store.label}: this build has no sign-in for it yet")
}
@@ -175,13 +191,15 @@ object StoresState {
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
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)
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store)
logLine("${store.label}: signed out")
}
}
}
var openDownloads by mutableStateOf(false)
/** A "store:id" key another page asks the Stores page to open. */
var openGameRequest by mutableStateOf<String?>(null)
private fun askForNotifications(context: Context) {
val activity = context as? android.app.Activity ?: return
@@ -47,6 +47,8 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
if (!quiet) StoresState.status[store] = app.getString(R.string.stores_sync_library)
}
val result = EpicLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
// Throttled means the cache is fresh, possibly written by another sync after this one read it.
val fresh = if (result == EpicLibrary.SyncResult.Throttled) EpicLibrary.cached(app).map { EpicLibrary.toCatalogItem(app, it) } else cached
StoresState.post {
StoresState.status.remove(store)
when (result) {
@@ -56,7 +58,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
}
is EpicLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
EpicLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = cached
EpicLibrary.SyncResult.Throttled -> if (fresh.isNotEmpty()) StoresState.library[store] = mergeItems(StoresState.library[store], fresh)
EpicLibrary.SyncResult.Busy -> {}
}
}
@@ -227,12 +227,6 @@ object EpicClient {
)
}
fun withLauncher(games: List<Library.SteamGame>, launcher: Library.SteamGame?): List<Library.SteamGame> {
if (launcher == null) return games
val at = games.indexOfFirst { it.source == Store.EPIC.id }.takeIf { it >= 0 } ?: games.size
return games.subList(0, at) + launcher + games.subList(at, games.size)
}
private fun steamSession(): Boolean =
SessionState.running && !SessionState.stopRequested && SessionState.mode == SessionService.MODE_STEAM
@@ -251,7 +251,7 @@ internal object EpicClientLibrary {
SessionPrefs.addedGameStoredAppId(app, oldFolder.path)?.let { SteamLiveShortcuts.remove(app, it) }
changed = true
}
val next = StoreGameSidecar(
val next = withLaunchArgs(StoreGameSidecar(
Store.EPIC, appName, item.optString("DisplayName").ifEmpty { appName }, exe,
installVersion = item.optString("AppVersionString"), installedAt = existing?.installedAt?.takeIf { it > 0 } ?: folder.lastModified(),
cover = existing?.cover, hero = existing?.hero,
@@ -260,7 +260,7 @@ internal object EpicClientLibrary {
epic = existing?.epic ?: com.droiddeck.launcher.stores.EpicOptions(),
cloud = existing?.cloud ?: true,
launcher = StoreLaunch.LAUNCHER,
)
), commandArgs(item.optString("LaunchCommand")))
val sidecarChanged = existing?.toJson()?.toString(2) != next.toJson().toString(2)
val launcher = File(folder, StoreLaunch.LAUNCHER)
if (sidecarChanged || runCatching { launcher.readText() }.getOrNull() != StoreLaunch.launcherText(next)) {
@@ -328,6 +328,7 @@ internal object EpicClientLibrary {
.put("CatalogItemId", record.optString("itemId"))
.put("InstallLocation", dir)
.put("LaunchExecutable", record.optString("launchExecutable"))
.put("LaunchCommand", record.optString("launchCommand"))
.put("AppVersionString", record.optString("version"))
.put("SidecarDeploymentId", record.optJSONObject("sidecar")?.optString("deploymentId").orEmpty())
.put("DisplayName", title?.takeIf(String::isNotBlank) ?: dir.substringAfterLast('/'))
@@ -358,7 +359,11 @@ internal object EpicClientLibrary {
write(File(manifests, "$guid.item"), item(install, tags, ownership == true).toString(2))
runCatching { egstore(install, guid) { token } }.onFailure { Log.w(TAG, "${install.appName}: .egstore not written (${it.javaClass.simpleName})") }
after.put(install.appName, JSONObject().put("guid", guid).put("signature", install.signature).apply { if (ownership != null) put("ownership", ownership) })
StoreGameSidecar.read(install.folder)?.let { StoreLaunch.refreshLauncher(install.folder, it) }
StoreGameSidecar.read(install.folder)?.let { sidecar ->
val next = runCatching { manifestArgs(install, guid) }.getOrNull()?.let { withLaunchArgs(sidecar, it) } ?: sidecar
if (next !== sidecar) next.write(install.folder)
StoreLaunch.refreshLauncher(install.folder, next)
}
}
for (name in before.keys().asSequence().toList()) {
if (after.has(name)) continue
@@ -376,6 +381,33 @@ internal object EpicClientLibrary {
return changed
}
private const val LAUNCH_ARGS = "launchArgs"
private fun manifestArgs(install: Install, guid: String): List<String>? {
val manifest = File(install.folder, ".egstore/$guid.manifest").takeIf { it.isFile } ?: return null
val launch = EpicNative.inspect(manifest.readBytes(), JSONObject().put("op", "launch")) ?: return null
val build = launch.optString("buildVersion")
if (install.version.isNotEmpty() && build != install.version) return null
val args = launch.optJSONArray("args") ?: return null
return List(args.length()) { args.optString(it) }.filter { it.isNotEmpty() }
}
private fun commandArgs(command: String): List<String> {
if (command.isBlank()) return emptyList()
val args = EpicNative.call("launch.split", JSONObject().put("command", command))?.optJSONArray("args") ?: return emptyList()
return List(args.length()) { args.optString(it) }.filter { it.isNotEmpty() }
}
internal fun withLaunchArgs(sidecar: StoreGameSidecar, args: List<String>): StoreGameSidecar {
val previous = sidecar.extra[LAUNCH_ARGS]?.split('\n')?.filter { it.isNotEmpty() }.orEmpty()
val kept = sidecar.args.filterNot { it in previous }
val added = args.filterNot { it in kept }
val next = kept + added
val extra = LinkedHashMap(sidecar.extra).apply { if (added.isEmpty()) remove(LAUNCH_ARGS) else put(LAUNCH_ARGS, added.joinToString("\n")) }
if (next == sidecar.args && extra == sidecar.extra) return sidecar
return sidecar.copy(args = next, extra = extra)
}
private fun ownershipToken(token: String, install: Install): Boolean? =
runCatching { EpicApiClient.getCustomAttribute(token, install.namespace, install.catalogItemId, "OwnershipToken") }
.getOrNull()?.trim()?.lowercase()?.let { it == "true" }
@@ -0,0 +1,176 @@
package com.droiddeck.launcher.stores.itch
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import java.io.File
import java.security.MessageDigest
internal data class BrowseQuery(
val sort: String = ItchBrowse.SORT_POPULAR,
val price: String = ItchBrowse.PRICE_ANY,
val platforms: Set<String> = emptySet(),
val tags: List<String> = emptyList(),
) {
val isDefault: Boolean get() = this == BrowseQuery()
}
internal class BrowsePage(val items: List<CatalogItem>, val code: Int, val cached: Boolean)
internal object ItchBrowse {
const val SORT_POPULAR = "popular"
const val SORT_NEW_POPULAR = "new-and-popular"
const val SORT_TOP_SELLERS = "top-sellers"
const val SORT_TOP_RATED = "top-rated"
const val SORT_NEWEST = "newest"
val sorts = listOf(SORT_POPULAR, SORT_NEW_POPULAR, SORT_TOP_SELLERS, SORT_TOP_RATED, SORT_NEWEST)
const val PRICE_ANY = "any"
const val PRICE_FREE = "free"
const val PRICE_SALE = "on-sale"
const val PRICE_PAID = "store"
const val PRICE_UNDER_5 = "5-dollars-or-less"
const val PRICE_UNDER_15 = "15-dollars-or-less"
val prices = listOf(PRICE_ANY, PRICE_FREE, PRICE_SALE, PRICE_PAID, PRICE_UNDER_5, PRICE_UNDER_15)
val platformNames = listOf("windows", "osx", "linux", "android", "ios", "web", "mobile-web")
private const val BASE = "https://itch.io/games"
private const val FRESH_MS = 3 * 60 * 60 * 1000L
private const val GAP_MS = 1_200L
private const val RETRY_MS = 8_000L
private const val FOLDER = "itch-browse"
@Volatile private var lastRequestAt = 0L
private val lock = Any()
private fun sortSegment(sort: String): String? = sort.takeIf { it != SORT_POPULAR && it in sorts }
private fun priceSegment(price: String): String? = price.takeIf { it != PRICE_ANY && it in prices }
fun path(query: BrowseQuery): String {
val segments = listOfNotNull(sortSegment(query.sort), priceSegment(query.price)) +
platformNames.filter { it in query.platforms }.map { "platform-$it" } +
query.tags.map { "tag-" + tagSlug(it) }
return if (segments.isEmpty()) BASE else BASE + "/" + segments.joinToString("/")
}
fun url(query: BrowseQuery, page: Int): String = path(query) + ".xml" + if (page > 1) "?page=$page" else ""
fun tagSlug(tag: String): String = tag.trim().lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-')
fun page(context: Context, query: BrowseQuery, page: Int, force: Boolean = false): BrowsePage {
val app = context.applicationContext
val url = url(query, page)
if (!force) read(app, url)?.let { return BrowsePage(it, 200, true) }
val (status, body) = fetch(url)
val items = if (status in 200..299 && body != null) ItchShelves.parse(body) else emptyList()
StoresState.logLine("itch.io browse: $url answered $status with ${items.size} games")
if (items.isNotEmpty()) write(app, url, items)
return BrowsePage(items, status, false)
}
private fun fetch(url: String): Pair<Int, String?> {
synchronized(lock) {
pause()
var answer = ItchShelves.open(url)
if (answer.first == 429) {
StoresState.logLine("itch.io browse: 429, waiting before one more try")
Thread.sleep(RETRY_MS)
pause()
answer = ItchShelves.open(url)
}
lastRequestAt = System.currentTimeMillis()
return answer
}
}
private fun pause() {
val gap = GAP_MS - (System.currentTimeMillis() - lastRequestAt)
if (gap > 0) Thread.sleep(gap)
}
private fun file(context: Context, url: String): File {
val digest = MessageDigest.getInstance("SHA-1").digest(url.toByteArray()).joinToString("") { "%02x".format(it) }
return File(File(context.cacheDir, FOLDER), "$digest.json")
}
private fun read(context: Context, url: String): List<CatalogItem>? {
val file = file(context, url)
if (!file.isFile || System.currentTimeMillis() - file.lastModified() > FRESH_MS) return null
return runCatching { ItchCatalog.list(JSONArray(file.readText())) }.getOrNull()?.takeIf { it.isNotEmpty() }
}
private fun write(context: Context, url: String, items: List<CatalogItem>) {
val file = file(context, url)
runCatching {
file.parentFile?.mkdirs()
file.writeText(ItchCatalog.array(items).toString())
}
}
}
internal object ItchBrowseState {
var query by mutableStateOf(BrowseQuery())
private set
var items by mutableStateOf<List<CatalogItem>>(emptyList())
private set
var loading by mutableStateOf(false)
private set
var ended by mutableStateOf(false)
private set
var failed by mutableStateOf(false)
private set
private var next = 1
private var generation = 0
val active: Boolean get() = !query.isDefault
fun choose(context: Context, wanted: BrowseQuery) {
if (wanted == query) return
generation++
query = wanted
items = emptyList()
ended = false
failed = false
loading = false
next = 1
if (active) more(context)
}
fun more(context: Context, retry: Boolean = false) {
if (loading || ended || !active || (failed && !retry)) return
loading = true
failed = false
val app = context.applicationContext
val mine = generation
val asked = query
val page = next
Thread({
val answer = runCatching { ItchBrowse.page(app, asked, page) }.getOrNull()
StoresState.post {
if (mine != generation) return@post
loading = false
if (answer == null || answer.code !in 200..299) {
failed = true
return@post
}
if (answer.items.isEmpty()) {
ended = true
return@post
}
val known = items.mapTo(HashSet()) { it.id }
val fresh = answer.items.filter { known.add(it.id) }
if (fresh.isEmpty()) ended = true else {
items = items + fresh
next = page + 1
}
}
}, "itch-browse").start()
}
}
@@ -108,7 +108,7 @@ internal object ItchShelves {
return shelves.takeUnless { it.isEmpty }
}
private fun open(url: String): Pair<Int, String?> {
internal fun open(url: String): Pair<Int, String?> {
var conn: HttpURLConnection? = null
return try {
conn = (URL(url).openConnection() as HttpURLConnection).apply {
@@ -26,6 +26,8 @@ object XboxBackend : StoreBackend {
access = emptyMap()
}
XboxLibraryCache.clear(context)
XboxCloudSession.clear()
XboxCloudActivity.clearWebSignIn(context)
XboxRuntime.stop()
}
StoresState.post { packageChoice = null; StoresState.shelves.remove(store); StoresState.found.remove(store) }
@@ -49,7 +51,7 @@ object XboxBackend : StoreBackend {
if (current == generation) {
if (cached != null) StoresState.library[store] = mergeItems(StoresState.library[store], cached.games)
StoresState.problems.remove(store)
if (cached == null || force) StoresState.status[store] = "Syncing Xbox library…"
if (cached == null || force) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library)
else StoresState.status.remove(store)
}
}
@@ -57,9 +59,13 @@ object XboxBackend : StoreBackend {
val response = Xodus.run(app, listOf("library", "--json", "--market", market))
val licenses = XboxCatalog.access(response, account, market, report = { StoresState.logLine("Xbox: $it") })
val products = XboxCatalog.rawProducts(licenses.keys.toList(), market)
val games = products.mapNotNull { XboxCatalog.product(it, licenses) }.sortedBy { it.title.lowercase() }
val cloud = runCatching { XboxCatalog.cloudCatalog(market) }
.onFailure { StoresState.logLine("Xbox: cloud lists unavailable (${it.javaClass.simpleName})") }.getOrNull()
val games = mergeEditions(products.mapNotNull { XboxCatalog.product(it, licenses, cloud) }).sortedBy { it.title.lowercase() }
StoresState.logLine("Xbox: library catalog requested=${licenses.size} returned=${products.size} supported=${games.size} " +
"filtered=${products.size - games.size} backend-skipped=${response.optInt("skippedEntitlements")}")
"filtered=${products.size - games.size} backend-skipped=${response.optInt("skippedEntitlements")} " +
"pc=${games.count { it.xboxPc }} cloud=${games.count { it.xboxCloud }} cloud-only=${games.count { !it.xboxPc }} " +
"cloud-lists=${cloud?.gamePass?.size ?: -1}/${cloud?.all?.size ?: -1}")
synchronized(this) {
if (current != generation || StoreAccounts.signedInAs(app, store) != account) return@Thread
access = licenses
@@ -10,7 +10,7 @@ import java.time.Instant
internal object XboxCatalog {
private val productId = Regex("[A-Z0-9]{12}")
private val plans = setOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD")
/** Plans that include PC games; the retired console-only plan must not offer a Windows install. */
/** Plans whose store offers advertise PC games. Library entitlements under any active plan count, as the backend resolves a PC package for them. */
private val pcPlans = mapOf(
"CFQ7TTC0KGQ8" to "PC Game Pass",
"CFQ7TTC0KHS0" to "Game Pass Ultimate",
@@ -61,7 +61,7 @@ internal object XboxCatalog {
val parent = row.optString("satisfiedByProductId").takeUnless { it.isBlank() || it == "null" }
if (parent == null) return if (id in plans) null else "owned"
if (parent in blocked) return null
if (parent in plans) return if (parent in pcPlans && activePlan(parent)) "gamepass" else null
if (parent in plans) return if (activePlan(parent)) "gamepass" else null
return kind(parent, visited + id)
}
val result = rows.keys.mapNotNull { id -> kind(id)?.let { id to it } }.toMap()
@@ -98,7 +98,7 @@ internal object XboxCatalog {
return products(objects(body.optJSONArray("productsList")).map { it.optString("productId") }.take(24), access)
}
internal fun product(json: JSONObject, access: Map<String, String>): CatalogItem? {
internal fun product(json: JSONObject, access: Map<String, String>, cloud: XboxCloudCatalog? = null): CatalogItem? {
val id = json.optString("ProductId").uppercase()
if (!productId.matches(id) || json.optString("ProductType") != "Game") return null
val localized = objects(json.optJSONArray("LocalizedProperties")).firstOrNull() ?: return null
@@ -107,7 +107,9 @@ internal object XboxCatalog {
objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages"))
}
val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
if (pc.none { it.optString("PackageFormat").equals("MSIXVC", true) }) return null
val installable = pc.any { it.optString("PackageFormat").equals("MSIXVC", true) }
val streams = cloud?.streams(id, access[id].orEmpty()) == true
if (!installable && !streams) return null
val images = objects(localized.optJSONArray("Images"))
fun image(vararg kinds: String): String? = kinds.firstNotNullOfOrNull { purpose ->
images.firstOrNull { it.optString("ImagePurpose") == purpose }?.optString("Uri")?.let { raw ->
@@ -127,13 +129,57 @@ internal object XboxCatalog {
storeUrl = "https://www.xbox.com/games/store/$id",
publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"),
description = localized.optString("ProductDescription"),
sizeBytes = pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L,
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty()),
sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L,
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable), "cloud" to flag(streams)),
)
}
private const val CLOUD_GAME_PASS = "29a81209-df6f-41fd-a528-2ae6b91f719c"
private const val CLOUD_ALL = "ce573635-7c18-4d0c-9d68-90b932393470"
/** Microsoft's public cloud lists (catalog.gamepass.com "sigls"; ids as Better xCloud by redphx, MIT, uses them). */
fun cloudCatalog(market: String = Xodus.market()): XboxCloudCatalog =
XboxCloudCatalog(cloudList(CLOUD_GAME_PASS, market), cloudList(CLOUD_ALL, market))
private fun cloudList(id: String, market: String): Set<String> {
val body = JSONArray(StoreNet.get("https://catalog.gamepass.com/sigls/v2?id=$id&language=en-us&market=$market") ?: error("Xbox cloud list unavailable"))
return (0 until body.length()).mapNotNull { body.optJSONObject(it)?.optString("id")?.uppercase()?.takeIf(productId::matches) }.toSet()
}
fun cloudUrl(id: String, title: String, cloudId: String = id): String =
"https://www.xbox.com/play/launch/${title.lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-').ifEmpty { "game" }}/$cloudId"
internal fun flag(value: Boolean) = if (value) "1" else "0"
fun objects(array: JSONArray?): List<JSONObject> = if (array == null) emptyList() else
(0 until array.length()).mapNotNull { array.optJSONObject(it) }
private fun get(url: String): JSONObject = JSONObject(StoreNet.get(url) ?: error("Microsoft Store could not be reached. Try again."))
}
internal data class XboxCloudCatalog(val gamePass: Set<String>, val all: Set<String>) {
fun streams(id: String, access: String): Boolean = when (access) {
"gamepass" -> id in gamePass
"owned" -> id in all || id in gamePass
else -> false
}
}
val CatalogItem.xboxPc: Boolean get() = extra["pc"] != "0"
val CatalogItem.xboxCloud: Boolean get() = extra["cloud"] == "1"
val CatalogItem.xboxCloudId: String get() = extra["cloudId"]?.takeIf { it.isNotEmpty() } ?: id
/** Microsoft lists console and PC editions as separate products; a cloud-only one with a PC game's title folds into that card. */
internal fun mergeEditions(games: List<CatalogItem>): List<CatalogItem> {
fun key(title: String) = title.lowercase().replace(Regex("[^a-z0-9]+"), "")
val cloudOnly = games.filter { !it.xboxPc && it.xboxCloud }.groupBy { key(it.title) }
val folded = HashSet<String>()
val merged = games.map { game ->
if (!game.xboxPc || game.xboxCloud) game
else cloudOnly[key(game.title)]?.firstOrNull()?.let { console ->
folded.add(console.id)
game.copy(extra = game.extra + mapOf("cloud" to "1", "cloudId" to console.id))
} ?: game
}
return merged.filter { it.id !in folded }
}
@@ -0,0 +1,189 @@
package com.droiddeck.launcher.stores.xbox
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.InputDevice
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.webkit.ConsoleMessage
import android.webkit.CookieManager
import android.webkit.PermissionRequest
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.webkit.WebSettingsCompat
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
/**
* Microsoft's web player (xbox.com/play) in its own process and WebView data directory: the store sign-in
* clears its own web data after each attempt, so the player keeps a separate Microsoft session. Signing out of
* the store clears it ([clearWebSignIn]).
*/
class XboxCloudActivity : ComponentActivity() {
private var web: WebView? = null
private var custom: View? = null
private var customCallback: WebChromeClient.CustomViewCallback? = null
private lateinit var root: FrameLayout
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
hideBars()
root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
setContentView(root)
Log.i(TAG, "WebView ${WebViewCompat.getCurrentWebViewPackage(this)?.versionName}")
val view = WebView(this)
web = view
view.settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
databaseEnabled = true
mediaPlaybackRequiresUserGesture = false
allowFileAccess = false
allowContentAccess = false
mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
useWideViewPort = true
loadWithOverviewMode = true
userAgentString = chromeUserAgent(userAgentString)
}
// No "X-Requested-With: <package>" header: it marks the page as embedded in an app.
if (WebViewFeature.isFeatureSupported(WebViewFeature.REQUESTED_WITH_HEADER_ALLOW_LIST))
WebSettingsCompat.setRequestedWithHeaderOriginAllowList(view.settings, emptySet())
Log.i(TAG, "UA ${view.settings.userAgentString}")
CookieManager.getInstance().setAcceptCookie(true)
CookieManager.getInstance().setAcceptThirdPartyCookies(view, true)
view.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean =
request.url.scheme != "https"
override fun onPageFinished(view: WebView, url: String) { Log.i(TAG, "page ${url.substringBefore('?')}") }
}
view.webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(message: ConsoleMessage): Boolean {
Log.d(TAG, "console ${message.messageLevel()}: ${message.message().take(300)}")
return true
}
override fun onPermissionRequest(request: PermissionRequest) {
Log.i(TAG, "permission request ${request.resources.joinToString()} denied")
request.deny()
}
override fun onShowCustomView(view: View, callback: CustomViewCallback) {
custom?.let { root.removeView(it) }
custom = view; customCallback = callback
root.addView(view, FrameLayout.LayoutParams(-1, -1))
hideBars()
}
override fun onHideCustomView() {
custom?.let { root.removeView(it) }
custom = null; customCallback = null
}
}
root.addView(view, FrameLayout.LayoutParams(-1, -1))
if (savedInstanceState != null) view.restoreState(savedInstanceState)
else view.loadUrl(startUrl(intent))
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
web?.loadUrl(startUrl(intent))
}
private fun startUrl(intent: Intent): String =
intent.getStringExtra("url")?.takeIf { url -> runCatching { java.net.URI(url) }.getOrNull()?.let {
it.scheme == "https" && it.host == "www.xbox.com" && it.userInfo == null && it.port == -1 } == true } ?: START_URL
// Without the WebView markers the page treats this as Chrome for Android.
private fun chromeUserAgent(default: String): String =
default.replace("; wv)", ")").replace(Regex(" Version/\\d+(\\.\\d+)*"), "")
private fun hideBars() {
WindowCompat.setDecorFitsSystemWindows(window, false)
WindowInsetsControllerCompat(window, window.decorView).apply {
hide(WindowInsetsCompat.Type.systemBars())
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) hideBars()
}
// A controller's unused B arrives as BACK; ask before leaving so a stray press never ends a stream.
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {
val fromController = event.source and InputDevice.SOURCE_GAMEPAD == InputDevice.SOURCE_GAMEPAD ||
event.source and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK
when {
custom != null -> customCallback?.onCustomViewHidden()
fromController -> confirmLeave()
web?.canGoBack() == true -> web?.goBack()
else -> finish()
}
return true
}
if (event.keyCode == KeyEvent.KEYCODE_BACK) return true
return super.dispatchKeyEvent(event)
}
private var leaving: android.app.AlertDialog? = null
private fun confirmLeave() {
if (leaving?.isShowing == true) return
leaving = android.app.AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_Alert)
.setTitle("Leave Xbox Cloud Gaming?")
.setMessage("The stream ends when you leave.")
.setPositiveButton("Leave") { _, _ -> finish() }
.setNegativeButton("Stay", null)
.show()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
web?.saveState(outState)
}
override fun onPause() { super.onPause(); CookieManager.getInstance().flush() }
override fun onDestroy() {
web?.let { root.removeView(it); it.stopLoading(); it.destroy() }
web = null
super.onDestroy()
}
companion object {
private const val TAG = "XboxCloud"
const val START_URL = "https://www.xbox.com/play"
fun intent(context: Context, url: String? = null): Intent = Intent(context, XboxCloudActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
.apply { if (url != null) putExtra("url", url) }
const val PROCESS_SUFFIX = ":xboxcloud"
const val WEBVIEW_SUFFIX = "xboxcloud"
fun clearWebSignIn(context: Context) {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
am.runningAppProcesses.orEmpty().filter { it.processName.endsWith(PROCESS_SUFFIX) }
.forEach { android.os.Process.killProcess(it.pid) }
val suffix = WEBVIEW_SUFFIX
listOf(java.io.File(context.applicationInfo.dataDir, "app_webview_$suffix"), java.io.File(context.cacheDir.parentFile, "cache/webview_$suffix"))
.forEach { runCatching { it.deleteRecursively() } }
}
}
}
@@ -0,0 +1,135 @@
package com.droiddeck.launcher.stores.xbox
import android.content.Context
import android.content.Intent
import androidx.compose.runtime.mutableStateListOf
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
/** Xbox games added to the Games tab to stream before (or without) installing them. */
object XboxCloudGames {
class Entry(val id: String, val title: String, val poster: String?, val hero: String?)
private const val PREFS = "xbox_cloud_games"
private val idPattern = Regex("[A-Z0-9]{12}")
val entries = mutableStateListOf<Entry>()
@Volatile private var loaded = false
fun load(context: Context) {
if (loaded) return
loaded = true
val list = decode(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("games", null))
StoresState.post { entries.clear(); entries.addAll(list) }
}
fun isAdded(id: String) = entries.any { it.id == id }
fun add(context: Context, item: CatalogItem) {
val app = context.applicationContext
if (isAdded(item.id)) return
entries.add(Entry(item.id, item.title, item.tallImageUrl, item.imageUrl))
save(app)
Thread({
fetch(item.tallImageUrl, File(artDir(app, item.id), "poster"))
fetch(item.imageUrl, File(artDir(app, item.id), "hero"))
StoresState.post { StoresState.notifyLibraryChanged(app) }
}, "xbox-cloud-art").start()
}
fun remove(context: Context, id: String) {
val app = context.applicationContext
entries.removeAll { it.id == id }
save(app)
artDir(app, id).deleteRecursively()
}
private fun save(app: Context) {
app.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString("games", encode(entries.toList())).apply()
}
internal fun encode(list: List<Entry>): String = JSONArray().apply {
list.forEach { put(JSONObject().put("id", it.id).put("title", it.title).put("poster", it.poster.orEmpty()).put("hero", it.hero.orEmpty())) }
}.toString()
internal fun decode(text: String?): List<Entry> = runCatching {
val array = JSONArray(text ?: return emptyList())
(0 until minOf(array.length(), 2000)).mapNotNull { array.optJSONObject(it) }.mapNotNull { o ->
val id = o.optString("id")
val title = o.optString("title")
if (!idPattern.matches(id) || title.isBlank()) null
else Entry(id, title.take(200), o.optString("poster").takeIf { it.isNotEmpty() }, o.optString("hero").takeIf { it.isNotEmpty() })
}.distinctBy { it.id }
}.getOrDefault(emptyList())
/** Games-tab rows for the added games that are not installed (an installed copy has its own row). */
fun rows(context: Context, installedIds: Set<String>): List<Library.SteamGame> = entries.filter { it.id !in installedIds }.map { e ->
val dir = artDir(context, e.id)
val appId = rowId(e.id)
Library.SteamGame(appId = appId, name = e.title, art = File(dir, "poster").takeIf { it.isFile }, library = Library.XBOX_CLOUD,
hero = File(dir, "hero").takeIf { it.isFile }, source = Store.XBOX.id, storeId = e.id)
}
internal fun rowId(id: String): Int = ("xbox-cloud:$id").hashCode() or Int.MIN_VALUE
private fun artDir(context: Context, id: String) = File(context.filesDir, "xbox-cloud-art/$id")
private fun fetch(url: String?, target: File) {
if (url == null) return
runCatching {
val parsed = URL(url)
require(parsed.protocol == "https" && parsed.host in setOf("store-images.s-microsoft.com", "store-images.microsoft.com"))
val connection = parsed.openConnection() as HttpURLConnection
try {
connection.connectTimeout = 15_000; connection.readTimeout = 30_000
check(connection.responseCode == 200)
val bytes = connection.inputStream.use { it.readBytes() }
require(bytes.size in 1..12_000_000)
target.parentFile?.mkdirs()
File(target.path + ".tmp").apply { writeBytes(bytes); check(renameTo(target)) }
} finally { connection.disconnect() }
}
}
private val prefetching = java.util.concurrent.atomic.AtomicBoolean(false)
/**
* Fetches the streaming tokens in the background while a cloud game is on screen (about 20 s), so Stream starts at
* once; both players take them from this process (the native one through XboxCloudTokenService).
*/
fun prefetch(context: Context) {
val app = context.applicationContext
if (!prefetching.compareAndSet(false, true)) return
Thread({
try {
val account = com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, Store.XBOX) ?: return@Thread
runCatching { XboxCloudSession.get(app, account) }
.onFailure { StoresState.logLine("Xbox: cloud tokens not fetched ahead: ${it.message?.take(160)}") }
} finally { prefetching.set(false) }
}, "xcloud-prefetch").start()
}
/** Streaming runs outside the Linux session; the session owns the screen, audio and controllers while it runs. */
fun stream(context: Context, id: String, title: String) {
if (SessionState.running) {
android.widget.Toast.makeText(context, "Close the Steam session to stream Xbox games.", android.widget.Toast.LENGTH_LONG).show()
return
}
context.startActivity(XboxCloudPlayerActivity.playerIntent(context, id, title).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
/** Whether the signed-in library says this game streams (cached library; reads disk). */
fun streams(context: Context, id: String): Boolean = runCatching {
StoresState.library[Store.XBOX]?.firstOrNull { it.id == id }?.let { return it.xboxCloud }
val app = context.applicationContext
val account = com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, Store.XBOX) ?: return false
XboxLibraryCache.read(app, account, Xodus.market())?.games?.firstOrNull { it.id == id }?.xboxCloud == true
}.getOrDefault(false)
}
@@ -0,0 +1,399 @@
package com.droiddeck.launcher.stores.xbox
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.KeyEvent
import android.view.WindowManager
import android.webkit.JavascriptInterface
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.webkit.WebViewAssetLoader
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONObject
import java.util.concurrent.Executors
/** Runs the WebRTC client page (tools/xcloud-player); signalling and tokens stay on this side of the bridge. */
class XboxCloudPlayerActivity : ComponentActivity() {
private lateinit var root: FrameLayout
private var web: WebView? = null
private var notice: LinearLayout? = null
private val worker = Executors.newSingleThreadExecutor()
private val signalling = Executors.newCachedThreadPool()
@Volatile private var session: XboxCloudSession.Session? = null
@Volatile private var sessionPath: String? = null
@Volatile private var titleId: String? = null
@Volatile private var closed = false
@Volatile private var webUrl: String? = null
@Volatile private var settings = XboxCloudSettings()
@Volatile private var sessionSignals: XboxCloudSignalling? = null
/** The settings this stream started with (stream-start settings changed since then need a restart). */
@Volatile private var startedWith: XboxCloudSettings? = null
private var menu: androidx.compose.ui.platform.ComposeView? = null
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
hideBars()
watchBars()
root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
setContentView(root)
val requested = intent.getStringExtra("product").orEmpty()
showNotice("Signing in to Xbox Cloud Gaming…", withButtons = false)
worker.execute {
val result = runCatching {
val account = StoreAccounts.signedInAs(applicationContext, Store.XBOX) ?: error("Sign in to the Xbox store first.")
val cached = XboxLibraryCache.read(applicationContext, account, Xodus.market())?.games?.firstOrNull { it.id == requested }
val product = cached?.extra?.get("cloudId")?.takeIf { it.isNotEmpty() } ?: requested
webUrl = XboxCatalog.cloudUrl(requested, cached?.title ?: intent.getStringExtra("title").orEmpty(), product)
val active = XboxCloudSession.get(applicationContext, account)
val title = XboxCloudSession.titles(active)[product] ?: error("This game can't be streamed with this account here.")
settings = XboxCloudSettings.load(applicationContext)
startedWith = settings
session = active.forStream(settings.region, settings.osName); titleId = title
diag("cloud player: $product -> title $title, region ${java.net.URI(session!!.baseUri).host}, transfer=${active.userToken != null}")
}
runOnUiThread {
if (closed) return@runOnUiThread
result.onSuccess { openPlayer() }.onFailure {
diag("cloud player not started: ${it.javaClass.simpleName}: ${it.message?.take(160)}")
showNotice(it.message ?: "Xbox Cloud Gaming could not start.", withButtons = true)
}
}
}
}
@SuppressLint("SetJavaScriptEnabled")
private fun openPlayer() {
val loader = WebViewAssetLoader.Builder().addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this)).build()
val view = WebView(this)
web = view
view.settings.apply {
javaScriptEnabled = true
mediaPlaybackRequiresUserGesture = false
allowFileAccess = false
allowContentAccess = false
}
view.setBackgroundColor(Color.BLACK)
// The Gamepad API only sees controllers while the WebView has input focus.
view.isFocusable = true
view.isFocusableInTouchMode = true
view.addJavascriptInterface(Bridge(), "DDCloud")
view.webViewClient = object : WebViewClient() {
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
loader.shouldInterceptRequest(request.url)
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = true
}
view.webChromeClient = object : android.webkit.WebChromeClient() {
override fun onConsoleMessage(message: android.webkit.ConsoleMessage): Boolean {
android.util.Log.d("XboxCloudPlayer", "console ${message.messageLevel()}: ${message.message().take(300)}")
return true
}
}
root.addView(view, 0, FrameLayout.LayoutParams(-1, -1))
notice?.let { root.removeView(it) }
notice = null
view.requestFocus()
view.loadUrl("https://appassets.androidplatform.net/assets/xcloud/player.html")
}
private inner class Bridge {
@JavascriptInterface
fun call(id: Int, op: String, arg: String) {
signalling.execute {
val reply = runCatching { handle(op, arg) }.getOrElse { XboxCloudSession.Reply(0, it.javaClass.simpleName) }
if (reply.status !in 200..299) diag("cloud player $op: ${reply.status} ${reply.body.take(300)}")
else if (op != "state" && op != "keepalive") diag("cloud player $op: ${reply.status}")
runOnUiThread { web?.evaluateJavascript("window.__ddResolve($id, ${reply.status}, ${JSONObject.quote(reply.body)})", null) }
}
}
@JavascriptInterface
fun status(text: String) { android.util.Log.i("XboxCloudPlayer", "status: ${text.take(120)}") }
@JavascriptInterface
fun playing() {
diag("cloud player streaming")
runOnUiThread { web?.requestFocus() }
}
@JavascriptInterface
fun settings(): String = pageSettings(this@XboxCloudPlayerActivity.settings)
@JavascriptInterface
fun log(text: String) { diag("cloud player page: ${text.take(240)}") }
@JavascriptInterface
fun failed(stage: String, detail: String) {
diag("cloud player failed at ${stage.take(40)}: ${detail.take(300)}")
runOnUiThread { if (!closed) showNotice("The stream could not start ($stage).", withButtons = true) }
}
}
private fun handle(op: String, arg: String): XboxCloudSession.Reply {
val active = session ?: error("no session")
val signals = sessionSignals ?: XboxCloudSignalling(active, titleId ?: error("no title"), settings).also { sessionSignals = it }
return signals.op(op, arg).also { sessionPath = signals.path }
}
private fun showNotice(text: String, withButtons: Boolean) {
notice?.let { root.removeView(it) }
val box = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
gravity = Gravity.CENTER
setBackgroundColor(if (withButtons) Color.argb(230, 0, 0, 0) else Color.TRANSPARENT)
}
box.addView(TextView(this).apply { setTextColor(Color.WHITE); textSize = 18f; gravity = Gravity.CENTER; this.text = text; setPadding(32, 16, 32, 16) })
if (withButtons) {
val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER }
(webUrl ?: intent.getStringExtra("webUrl"))?.let { url ->
row.addView(Button(this).apply { this.text = "Open in Microsoft's player"; setOnClickListener { startActivity(XboxCloudActivity.intent(this@XboxCloudPlayerActivity, url)); finish() } })
}
row.addView(Button(this).apply { this.text = "Close"; setOnClickListener { finish() } })
box.addView(row)
}
notice = box
root.addView(box, FrameLayout.LayoutParams(-1, -1))
}
private val rehideBars = Runnable { if (window.decorView.hasWindowFocus()) hideBars() }
private fun watchBars() {
androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener(window.decorView) { v, insets ->
if (insets.isVisible(WindowInsetsCompat.Type.navigationBars()) || insets.isVisible(WindowInsetsCompat.Type.statusBars())) {
v.removeCallbacks(rehideBars)
v.postDelayed(rehideBars, 1500)
}
androidx.core.view.ViewCompat.onApplyWindowInsets(v, insets)
}
}
override fun onResume() {
super.onResume()
hideBars()
}
private fun hideBars() {
WindowCompat.setDecorFitsSystemWindows(window, false)
WindowInsetsControllerCompat(window, window.decorView).apply {
hide(WindowInsetsCompat.Type.systemBars())
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) hideBars()
}
private var guideDown = false
private var guideDownAt = 0L
private var lastGuideUp = 0L
private var pendingNexus: Runnable? = null
private var swallowGuideUp = false
private fun isGuideKey(event: KeyEvent): Boolean = event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE
/** One press is the stream's Xbox button; two quick presses or a hold open the player menu. */
private fun guideKey(event: KeyEvent): Boolean {
if (!isGuideKey(event)) return false
if (event.action == KeyEvent.ACTION_DOWN) {
if (event.repeatCount == 0) {
guideDown = true; guideDownAt = event.eventTime
val pending = pendingNexus
if (pending != null && event.eventTime - lastGuideUp <= DOUBLE_PRESS_MS) {
root.removeCallbacks(pending); pendingNexus = null; guideDown = false
swallowGuideUp = true
openMenu()
}
} else if (guideDown && event.eventTime - guideDownAt >= 600) {
guideDown = false
swallowGuideUp = true
openMenu()
}
} else if (event.action == KeyEvent.ACTION_UP && guideDown) {
guideDown = false
lastGuideUp = event.eventTime
val tap = Runnable { pendingNexus = null; pressNexus(1); root.postDelayed({ pressNexus(0) }, 150) }
pendingNexus = tap
root.postDelayed(tap, DOUBLE_PRESS_MS)
}
return true
}
private fun pressNexus(value: Int) {
web?.evaluateJavascript("window.__ddButton && window.__ddButton('Nexus', $value)", null)
}
// Back opens the player menu so a stray press never ends a stream.
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (menu != null) {
if (isGuideKey(event)) {
if (event.action == KeyEvent.ACTION_UP) { if (swallowGuideUp) swallowGuideUp = false else closeMenu() }
return true
}
if (event.keyCode == KeyEvent.KEYCODE_BACK) {
if (event.action == KeyEvent.ACTION_UP) { if (menuPage.isNotEmpty()) menuPage = "" else closeMenu() }
return true
}
return super.dispatchKeyEvent(event)
}
if (notice == null && guideKey(event)) return true
if (event.keyCode == KeyEvent.KEYCODE_BACK) {
if (event.action == KeyEvent.ACTION_UP) { if (notice == null) openMenu() else finish() }
return true
}
// Reporting controller buttons handled stops Android turning an unused one into a fallback key.
val handled = super.dispatchKeyEvent(event)
val fromController = event.source and android.view.InputDevice.SOURCE_GAMEPAD == android.view.InputDevice.SOURCE_GAMEPAD ||
event.source and android.view.InputDevice.SOURCE_JOYSTICK == android.view.InputDevice.SOURCE_JOYSTICK
return handled || (notice == null && web != null && fromController)
}
private var menuPage by androidx.compose.runtime.mutableStateOf("")
private fun openMenu() {
if (menu != null || web == null) return
web?.evaluateJavascript("window.__ddInput && window.__ddInput(false)", null)
menuPage = ""
val regions = session?.regionList?.map { it.name }.orEmpty()
val view = androidx.compose.ui.platform.ComposeView(this)
view.setContent {
com.droiddeck.launcher.ui.DroidDeckTheme {
var current by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(settings) }
val entries = androidx.compose.runtime.remember { List(6) { androidx.compose.ui.focus.FocusRequester() } }
androidx.compose.runtime.LaunchedEffect(menuPage) {
if (menuPage.isEmpty()) runCatching { entries[lastMainEntry.coerceIn(0, 5)].requestFocus() }
}
val cs = androidx.compose.material3.MaterialTheme.colorScheme
androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.fillMaxSize()) {
androidx.compose.foundation.layout.Column(
androidx.compose.ui.Modifier.fillMaxHeight().width(400.dp).background(cs.surface.copy(alpha = 0.95f))
.verticalScroll(androidx.compose.foundation.rememberScrollState()).padding(vertical = 12.dp),
) {
androidx.compose.material3.Text(intent.getStringExtra("title").orEmpty().ifEmpty { "Xbox Cloud Gaming" },
style = androidx.compose.material3.MaterialTheme.typography.titleMedium, color = cs.onSurface,
modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 4.dp))
if (menuPage.isEmpty()) {
MenuEntry("Resume", "Back to the game", entries[0], 0) { closeMenu() }
MenuEntry("Xbox menu", "The game's Xbox menu (also: Guide once, or View + Menu)", entries[1], 1) {
closeMenu(); web?.evaluateJavascript("window.__ddNexus && window.__ddNexus()", null)
}
MenuEntry("Screen effects", "Sharpen, colour, deband, FXAA, CRT, NTSC, Toon, fps cap", entries[2], 2) { menuPage = "picture" }
MenuEntry("Stream quality", "Resolution, region, language, codec, bitrate (next stream)", entries[3], 3) { menuPage = "stream" }
MenuEntry("Performance overlay and sound", "Overlay level and layout, volume, controller rumble", entries[4], 4) { menuPage = "overlay" }
MenuEntry("Leave", "End the stream", entries[5], 5) { finish() }
androidx.compose.material3.Text("Guide twice opens this menu; Back or Guide closes it.",
style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = cs.onSurfaceVariant,
modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
} else {
MenuEntry("‹ Back", null) { menuPage = "" }
if (menuPage == "stream") MenuEntry("Restart the stream with these settings",
"Ends this cloud session and starts a new one; the game restarts, unsaved progress is lost.") { restartStream() }
val page = menuPage
XboxCloudSettingsPanel(current, regions, live = true, section = page, restoreRow = lastRow[page] ?: 0,
onRowFocused = { lastRow[page] = it }, startedWith = startedWith) { changed ->
current = changed
settings = changed
XboxCloudSettings.save(this@XboxCloudPlayerActivity, changed)
web?.evaluateJavascript("window.__ddApply && window.__ddApply(${JSONObject.quote(pageSettings(changed))})", null)
}
}
}
}
}
}
menu = view
root.addView(view, FrameLayout.LayoutParams(-1, -1))
view.requestFocus()
}
private fun pageSettings(s: XboxCloudSettings): String = JSONObject(s.toJson())
.put("server", session?.let { active -> active.regionList.firstOrNull { it.baseUri == active.baseUri }?.name } ?: "").toString()
private var lastMainEntry = 0
private val lastRow = mutableMapOf<String, Int>()
@androidx.compose.runtime.Composable
private fun MenuEntry(title: String, note: String?, focus: androidx.compose.ui.focus.FocusRequester? = null, index: Int = -1, onClick: () -> Unit) =
XboxMenuEntry(title, note, focus, { if (index >= 0) lastMainEntry = index }, onClick)
private fun restartStream() {
val active = session; val path = sessionPath
sessionPath = null
closeMenu()
showNotice("Restarting the stream…", withButtons = false)
Thread({
if (active != null && path != null) runCatching { XboxCloudSession.request(active, "DELETE", "/$path") }
.onSuccess { diag("cloud player restart: session closed ${it.status}") }
runOnUiThread { if (!isFinishing) { startActivity(playerIntent(this, intent.getStringExtra("product").orEmpty(), intent.getStringExtra("title").orEmpty())); finish() } }
}, "xcloud-restart").start()
}
private fun closeMenu() {
menu?.let { root.removeView(it) }
menu = null
web?.evaluateJavascript("window.__ddInput && window.__ddInput(true)", null)
web?.requestFocus()
}
override fun onDestroy() {
closed = true
web?.let { it.evaluateJavascript("window.__ddStop && window.__ddStop()", null); root.removeView(it); it.destroy() }
web = null
val active = session; val path = sessionPath
if (active != null && path != null) Thread({
runCatching { XboxCloudSession.request(active, "DELETE", "/$path") }
.onSuccess { diag("cloud player session closed: ${it.status}") }
}, "xcloud-stop").start()
worker.shutdownNow(); signalling.shutdownNow()
super.onDestroy()
}
private fun diag(text: String) = StoresState.logLine("Xbox: $text")
companion object {
private const val DOUBLE_PRESS_MS = 350L
fun intent(context: Context, productId: String, title: String): Intent = Intent(context, XboxCloudPlayerActivity::class.java)
.putExtra("product", productId.uppercase()).putExtra("title", title)
/** The player the settings pick: the native engine (frame generation) where it can run, else the web player. */
fun playerIntent(context: Context, productId: String, title: String): Intent {
val native = XboxNativePlayerActivity.supported() && XboxCloudSettings.load(context).playerEngine == "native"
return if (!native) intent(context, productId, title) else Intent(context, XboxNativePlayerActivity::class.java)
.putExtra("product", productId.uppercase()).putExtra("title", title)
}
}
}
@@ -0,0 +1,120 @@
package com.droiddeck.launcher.stores.xbox
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
/** Streaming-service tokens stay in memory only. Request shapes follow Greenlight / xal-node by unknownskl (MIT). */
internal object XboxCloudSession {
class Region(val name: String, val baseUri: String, val isDefault: Boolean)
class Session(val account: String, val token: String, val offering: String, val baseUri: String, val regionList: List<Region>,
val userToken: String?, internal val expiresAt: Long,
val osName: String = "windows") {
val fresh get() = System.currentTimeMillis() < expiresAt - 5 * 60_000L
val regions get() = regionList.size
fun forStream(regionName: String, os: String): Session = Session(account, token, offering,
regionList.firstOrNull { it.name == regionName }?.baseUri ?: baseUri, regionList, userToken, expiresAt, os)
}
@Volatile private var cached: Session? = null
/** One fetch at a time (about 20 s: two ticket exchanges); a second caller waits and gets the same tokens. */
@Synchronized
fun get(app: Context, account: String): Session {
cached?.takeIf { it.account == account && it.fresh }?.let { return it }
val json = Xodus.run(app, listOf("cloud-token"), timeout = 60)
require(json.getInt("schema") == 1 && json.getString("account") == account)
val array = json.getJSONArray("regions")
val regions = (0 until array.length()).map { array.getJSONObject(it) }
.map { Region(it.getString("name"), it.getString("baseUri"), it.optBoolean("isDefault")) }
val default = regions.firstOrNull { it.isDefault } ?: regions.firstOrNull() ?: error("No Xbox Cloud Gaming region")
val seconds = json.optLong("durationInSeconds").coerceIn(0, 24 * 3600)
return Session(account, json.getString("gsToken"), json.getString("offering"), default.baseUri, regions,
json.optString("userToken").takeIf { !json.isNull("userToken") && it.isNotEmpty() }, System.currentTimeMillis() + seconds * 1000).also { cached = it }
}
fun clear() { cached = null; titleIds = null }
/**
* For the native player's own process: the main process's tokens (it keeps them, and fetches them ahead while a
* cloud game's page is open), handed over in memory through XboxCloudTokenService; null if that is not reachable.
*/
fun fromMainProcess(app: Context, account: String, timeoutSeconds: Long = 90): Session? {
cached?.takeIf { it.account == account && it.fresh }?.let { return it }
val reply = XboxCloudTokenService.request(app, account, timeoutSeconds) ?: return null
reply.getString("error")?.let { error(it) }
return fromBundle(reply).takeIf { it.account == account && it.fresh }?.also { cached = it }
}
internal fun toBundle(s: Session) = android.os.Bundle().apply {
putString("account", s.account); putString("token", s.token); putString("offering", s.offering)
putString("baseUri", s.baseUri); putString("userToken", s.userToken); putLong("expiresAt", s.expiresAt)
putStringArrayList("regionNames", ArrayList(s.regionList.map { it.name }))
putStringArrayList("regionUris", ArrayList(s.regionList.map { it.baseUri }))
putBooleanArray("regionDefaults", s.regionList.map { it.isDefault }.toBooleanArray())
}
internal fun fromBundle(b: android.os.Bundle): Session {
val names = b.getStringArrayList("regionNames").orEmpty()
val uris = b.getStringArrayList("regionUris").orEmpty()
val defaults = b.getBooleanArray("regionDefaults") ?: BooleanArray(0)
val regions = names.indices.map { Region(names[it], uris.getOrElse(it) { "" }, defaults.getOrElse(it) { false }) }
return Session(b.getString("account").orEmpty(), b.getString("token").orEmpty(), b.getString("offering").orEmpty(),
b.getString("baseUri").orEmpty(), regions, b.getString("userToken"), b.getLong("expiresAt"))
}
@Volatile private var titleIds: Pair<String, Map<String, String>>? = null
fun titles(session: Session): Map<String, String> {
titleIds?.takeIf { it.first == session.account }?.let { return it.second }
val reply = request(session, "GET", "/v2/titles")
check(reply.status == 200) { "Xbox Cloud Gaming answered ${reply.status}" }
val results = JSONObject(reply.body).optJSONArray("results") ?: JSONArray()
val map = (0 until results.length()).mapNotNull { index ->
val row = results.optJSONObject(index) ?: return@mapNotNull null
val product = row.optJSONObject("details")?.optString("productId")?.uppercase().orEmpty()
val title = row.optString("titleId")
if (product.matches(Regex("[A-Z0-9]{12}")) && title.isNotBlank() && title.length <= 64) product to title else null
}.toMap()
titleIds = session.account to map
return map
}
class Reply(val status: Int, val body: String)
fun request(session: Session, method: String, path: String, body: String? = null): Reply {
val connection = URL(session.baseUri + path).openConnection() as HttpURLConnection
try {
connection.connectTimeout = 15_000; connection.readTimeout = 30_000
connection.requestMethod = method
connection.setRequestProperty("Authorization", "Bearer ${session.token}")
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty("Content-Type", "application/json")
connection.setRequestProperty("X-Gssv-Client", "XboxComBrowser")
connection.setRequestProperty("X-MS-Device-Info", deviceInfo(session.osName))
if (body != null) {
connection.doOutput = true
connection.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
}
val status = connection.responseCode
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
val text = stream?.use { it.readBytes() }?.also { require(it.size <= 16_000_000) } ?: ByteArray(0)
return Reply(status, String(text, Charsets.UTF_8))
} finally { connection.disconnect() }
}
private fun deviceInfo(os: String) = JSONObject()
.put("appInfo", JSONObject().put("env", JSONObject().put("clientAppId", "www.xbox.com").put("clientAppType", "browser")
.put("clientAppVersion", "21.1.98").put("clientSdkVersion", "8.5.3").put("httpEnvironment", "prod").put("sdkInstallId", "")))
.put("dev", JSONObject()
.put("hw", JSONObject().put("make", "Microsoft").put("model", "unknown").put("sdktype", "web"))
.put("os", JSONObject().put("name", os).put("ver", "22631.2715").put("platform", "desktop"))
.put("displayInfo", JSONObject().put("dimensions", JSONObject().put("widthInPixels", 1920).put("heightInPixels", 1080))
.put("pixelDensity", JSONObject().put("dpiX", 2).put("dpiY", 2)))
.put("browser", JSONObject().put("browserName", "chrome").put("browserVersion", "119.0")))
.toString()
}
@@ -0,0 +1,108 @@
package com.droiddeck.launcher.stores.xbox
import android.content.Context
import org.json.JSONObject
data class XboxCloudSettings(
val resolution: String = "1080p", // 720p | 1080p | 1080p_hq
val region: String = "", // "" = Microsoft's choice
val language: String = "", // "" = the device's language
val codec: String = "default", // default | high | normal | low
val bitrateMbps: Int = 0, // 0 = no cap
val preventDrops: Boolean = false,
val statsLevel: Int = 0, // 0 off, 1 fps, 2 basic, 3 detailed, 4 full
val statsLayout: String = "horizontal",
val statsCorner: String = "right", // right | left
val volume: Int = 100, // 100..300 %
val rumble: Int = 100, // 0..100 %
val maxFps: Int = 0,
val brightness: Int = 0,
val contrast: Int = 0,
val gamma: Float = 1f,
val saturation: Int = 100,
val sharpen: Int = 0,
val sharpenMode: String = "cas", // cas | usm
val deband: Int = 0,
val fxaa: Boolean = false,
val toon: Boolean = false,
val crt: Boolean = false,
val ntsc: Boolean = false,
val playerEngine: String = "web", // web | native (WebRTC library + DroidDeck's compositor, frame generation)
val frameGen: String = "ddfg", // native engine: off | ddfg (2x) | lsfg | lsfg3 | lsfg4 (needs Lossless.dll)
val fpsLimit: Int = 0, // native engine target: 0 = the screen's rate, else 30/45/60/120/144/165
val fpsCustomOn: Boolean = false, // use fpsCustom instead of the presets
val fpsCustom: Int = 60, // 10..165
val instantInput: Boolean = true, // native: send controller changes at once (else every 16 ms)
val smallBuffer: Boolean = false, // native: WebRTC shows frames as soon as decoded (no playout delay)
val fastDecoder: Boolean = true, // native: the hardware decoder's low-latency mode
val zeroCopy: Boolean = false, // native, frame generation off: decode straight onto the screen
) {
/** The native engine's frame-rate target (0 = the screen's own rate). */
val fpsTarget get() = if (fpsCustomOn) fpsCustom else fpsLimit
/** The service picks the stream resolution from the reported OS (Better xCloud's mapping). */
val osName get() = when (resolution) { "720p" -> "android"; "1080p_hq" -> "tizen"; else -> "windows" }
fun toJson(): String = JSONObject()
.put("resolution", resolution).put("region", region).put("language", language).put("codec", codec)
.put("bitrateMbps", bitrateMbps).put("preventDrops", preventDrops).put("statsLevel", statsLevel).put("statsLayout", statsLayout).put("statsCorner", statsCorner)
.put("volume", volume).put("rumble", rumble).put("maxFps", maxFps).put("brightness", brightness).put("contrast", contrast)
.put("gamma", gamma.toDouble()).put("saturation", saturation).put("sharpen", sharpen).put("sharpenMode", sharpenMode)
.put("deband", deband).put("fxaa", fxaa).put("toon", toon).put("crt", crt).put("ntsc", ntsc)
.put("playerEngine", playerEngine).put("frameGen", frameGen)
.put("fpsLimit", fpsLimit).put("fpsCustomOn", fpsCustomOn).put("fpsCustom", fpsCustom)
.put("instantInput", instantInput).put("smallBuffer", smallBuffer).put("fastDecoder", fastDecoder).put("zeroCopy", zeroCopy)
.toString()
fun withoutEffects() = copy(brightness = 0, contrast = 0, gamma = 1f, saturation = 100, sharpen = 0, sharpenMode = "cas",
deband = 0, fxaa = false, toon = false, crt = false, ntsc = false)
companion object {
private const val PREFS = "xbox_cloud"
private const val KEY = "settings"
fun load(context: Context): XboxCloudSettings =
decode(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null))
internal fun decode(text: String?): XboxCloudSettings = runCatching {
val json = JSONObject(text ?: return XboxCloudSettings())
val d = XboxCloudSettings()
XboxCloudSettings(
resolution = json.optString("resolution", d.resolution).takeIf { it in setOf("720p", "1080p", "1080p_hq") } ?: d.resolution,
region = json.optString("region", d.region).take(64), language = json.optString("language", d.language).take(16),
codec = json.optString("codec", d.codec).takeIf { it in setOf("default", "high", "normal", "low") } ?: d.codec,
bitrateMbps = json.optInt("bitrateMbps", d.bitrateMbps).coerceIn(0, 100),
preventDrops = json.optBoolean("preventDrops", d.preventDrops),
statsLevel = json.optInt("statsLevel", d.statsLevel).coerceIn(0, 4),
statsLayout = json.optString("statsLayout", d.statsLayout).takeIf { it == "vertical" } ?: "horizontal",
statsCorner = json.optString("statsCorner", d.statsCorner).takeIf { it == "left" } ?: "right",
volume = json.optInt("volume", d.volume).coerceIn(100, 300), rumble = json.optInt("rumble", d.rumble).coerceIn(0, 100),
maxFps = json.optInt("maxFps", d.maxFps).coerceIn(0, 120),
brightness = json.optInt("brightness", d.brightness).coerceIn(-50, 50), contrast = json.optInt("contrast", d.contrast).coerceIn(-100, 100),
gamma = json.optDouble("gamma", 1.0).toFloat().coerceIn(0.5f, 3f), saturation = json.optInt("saturation", d.saturation).coerceIn(0, 200),
sharpen = json.optInt("sharpen", d.sharpen).coerceIn(0, 10),
sharpenMode = json.optString("sharpenMode", d.sharpenMode).takeIf { it == "usm" } ?: "cas",
deband = json.optInt("deband", d.deband).coerceIn(0, 8),
fxaa = json.optBoolean("fxaa"), toon = json.optBoolean("toon"), crt = json.optBoolean("crt"), ntsc = json.optBoolean("ntsc"),
playerEngine = json.optString("playerEngine", d.playerEngine).takeIf { it == "native" } ?: "web",
frameGen = json.optString("frameGen", d.frameGen).let { if (it == "winfg") "ddfg" else it }
.takeIf { it in setOf("off", "ddfg", "lsfg", "lsfg3", "lsfg4") } ?: d.frameGen,
fpsLimit = json.optInt("fpsLimit", d.fpsLimit).takeIf { it in setOf(0, 30, 45, 60, 120, 144, 165) } ?: 0,
fpsCustomOn = json.optBoolean("fpsCustomOn", d.fpsCustomOn),
fpsCustom = json.optInt("fpsCustom", d.fpsCustom).coerceIn(10, 165),
instantInput = json.optBoolean("instantInput", d.instantInput), smallBuffer = json.optBoolean("smallBuffer", d.smallBuffer),
fastDecoder = json.optBoolean("fastDecoder", d.fastDecoder), zeroCopy = json.optBoolean("zeroCopy", d.zeroCopy),
)
}.getOrDefault(XboxCloudSettings())
fun save(context: Context, settings: XboxCloudSettings) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, settings.toJson()).apply()
}
val LANGUAGES = listOf("" to "Device language", "en-US" to "English (US)", "en-GB" to "English (UK)", "de-DE" to "Deutsch",
"es-ES" to "Español (España)", "es-MX" to "Español (México)", "fr-FR" to "Français", "it-IT" to "Italiano",
"ja-JP" to "日本語", "ko-KR" to "한국어", "nl-NL" to "Nederlands", "pl-PL" to "Polski", "pt-BR" to "Português (Brasil)",
"pt-PT" to "Português (Portugal)", "ru-RU" to "Русский", "sv-SE" to "Svenska", "tr-TR" to "Türkçe", "zh-CN" to "中文 (简体)",
"zh-TW" to "中文 (繁體)")
}
}
@@ -0,0 +1,60 @@
package com.droiddeck.launcher.stores.xbox
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.ui.DroidDeckTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class XboxCloudSettingsActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DroidDeckTheme {
var settings by remember { mutableStateOf(XboxCloudSettings.load(this)) }
var regions by remember { mutableStateOf(emptyList<String>()) }
LaunchedEffect(Unit) {
regions = withContext(Dispatchers.IO) {
runCatching {
val account = StoreAccounts.signedInAs(applicationContext, Store.XBOX) ?: return@runCatching emptyList()
XboxCloudSession.get(applicationContext, account).regionList.map { it.name }
}.getOrDefault(emptyList())
}
}
Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).verticalScroll(rememberScrollState())) {
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
OutlinedButton(onClick = { finish() }) { Text("Back") }
Text("Xbox Cloud Gaming", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 16.dp))
}
XboxCloudSettingsPanel(settings, regions, live = false) { changed ->
settings = changed
XboxCloudSettings.save(this@XboxCloudSettingsActivity, changed)
}
}
}
}
}
}
@@ -0,0 +1,313 @@
package com.droiddeck.launcher.stores.xbox
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.foundation.border
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
/** Shared by the Xbox cloud settings page and the in-player menu; [live] changes reach the running stream. */
@Composable
fun XboxCloudSettingsPanel(
settings: XboxCloudSettings,
regions: List<String>,
live: Boolean,
/** "stream", "picture" or "overlay" shows that section only; null shows all. */
section: String? = null,
/** The row to select when the panel opens (the last one used), or null for no initial selection. */
restoreRow: Int? = null,
onRowFocused: (Int) -> Unit = {},
/** The settings the running stream started with; rows that differ say they need a restart (null: no stream). */
startedWith: XboxCloudSettings? = null,
onChange: (XboxCloudSettings) -> Unit,
) {
val focus = remember(section) { PanelFocus() }
focus.next = 0
focus.onFocused = onRowFocused
CompositionLocalProvider(LocalPanelFocus provides focus) {
PanelContent(settings, regions, live, section, startedWith, onChange)
}
LaunchedEffect(section) {
if (restoreRow != null) runCatching { focus.requester(restoreRow.coerceIn(0, (focus.count - 1).coerceAtLeast(0))).requestFocus() }
}
}
/** Gives each settings row its place in the page, so the last-used row can be selected again. */
private class PanelFocus {
var next = 0
var count = 0
var onFocused: (Int) -> Unit = {}
private val requesters = mutableMapOf<Int, FocusRequester>()
fun requester(index: Int) = requesters.getOrPut(index) { FocusRequester() }
fun take(): Int = next++.also { count = maxOf(count, next) }
}
private val LocalPanelFocus = compositionLocalOf<PanelFocus?> { null }
@Composable
private fun PanelContent(
settings: XboxCloudSettings,
regions: List<String>,
live: Boolean,
section: String?,
startedWith: XboxCloudSettings?,
onChange: (XboxCloudSettings) -> Unit,
) {
// Stream-start settings changed during a stream wait for a restart; back at the starting value, no note.
fun pending(differs: (XboxCloudSettings) -> Boolean) = startedWith != null && differs(startedWith)
if (section == null || section == "stream") Section("Stream", if (live) "Applies to the next stream." else "Applies when a stream starts.") {
if (XboxNativePlayerActivity.supported()) {
Choice("Player engine", listOf("web" to "Web", "native" to "Native (frame gen)"), settings.playerEngine,
pending { it.playerEngine != settings.playerEngine }) { onChange(settings.copy(playerEngine = it)) }
val ctx = androidx.compose.ui.platform.LocalContext.current
val lsfg = androidx.compose.runtime.remember { XboxNativeVideo.lsfgReady(ctx) }
Choice("Frame generation", XboxNativeVideo.modes(lsfg).map { it to XboxNativeVideo.modeName(it) }, settings.frameGen) {
onChange(settings.copy(frameGen = it))
}
Text("Native engine (experimental): Google's WebRTC and DroidDeck's own compositor, so DroidDeck frame generation " +
"(DDFG) or LSFG can add frames. LSFG uses the Lossless.dll DroidDeck already uses for games. Screen effects " +
"apply to the web engine.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 8.dp, bottom = 6.dp))
}
// The service picks the size from the reported device profile (the PC profile can send 1440p).
Choice("Resolution", listOf("720p" to "720p (phone)", "1080p" to "Best (PC)", "1080p_hq" to "1080p HQ (TV)"),
settings.resolution, pending { it.resolution != settings.resolution }) { onChange(settings.copy(resolution = it)) }
Choice("Server region", listOf("" to "Automatic") + regions.map { it to it }, settings.region,
pending { it.region != settings.region }) { onChange(settings.copy(region = it)) }
Choice("Game language", XboxCloudSettings.LANGUAGES, settings.language,
pending { it.language != settings.language }) { onChange(settings.copy(language = it)) }
Choice("Video codec quality", listOf("default" to "Automatic", "high" to "High", "normal" to "Normal", "low" to "Low"), settings.codec,
pending { it.codec != settings.codec }) { onChange(settings.copy(codec = it)) }
Choice("Bitrate limit", listOf(0 to "No limit") + listOf(5, 8, 10, 12, 15, 20, 25, 30, 40, 50).map { it to "$it Mb/s" }, settings.bitrateMbps,
pending { it.bitrateMbps != settings.bitrateMbps }) { onChange(settings.copy(bitrateMbps = it)) }
Toggle("Stop quality drops", "Keeps the resolution up when this device decodes slowly.", settings.preventDrops) { onChange(settings.copy(preventDrops = it)) }
}
if (section == null || section == "picture") Section("Picture", "Shader effects on the stream.") {
Step("Brightness", "${settings.brightness}", { onChange(settings.copy(brightness = (settings.brightness - 5).coerceAtLeast(-50))) },
{ onChange(settings.copy(brightness = (settings.brightness + 5).coerceAtMost(50))) })
Step("Contrast", "${settings.contrast}", { onChange(settings.copy(contrast = (settings.contrast - 10).coerceAtLeast(-100))) },
{ onChange(settings.copy(contrast = (settings.contrast + 10).coerceAtMost(100))) })
Step("Gamma", String.format("%.1f", settings.gamma), { onChange(settings.copy(gamma = ((settings.gamma * 10).toInt() - 1).coerceAtLeast(5) / 10f)) },
{ onChange(settings.copy(gamma = ((settings.gamma * 10).toInt() + 1).coerceAtMost(30) / 10f)) })
Step("Saturation", "${settings.saturation}%", { onChange(settings.copy(saturation = (settings.saturation - 10).coerceAtLeast(0))) },
{ onChange(settings.copy(saturation = (settings.saturation + 10).coerceAtMost(200))) })
Step("Sharpen", if (settings.sharpen == 0) "Off" else "${settings.sharpen}", { onChange(settings.copy(sharpen = (settings.sharpen - 1).coerceAtLeast(0))) },
{ onChange(settings.copy(sharpen = (settings.sharpen + 1).coerceAtMost(10))) })
Choice("Sharpen type", listOf("cas" to "Contrast-adaptive", "usm" to "Unsharp mask"), settings.sharpenMode) { onChange(settings.copy(sharpenMode = it)) }
Step("Deband", if (settings.deband == 0) "Off" else "${settings.deband}", { onChange(settings.copy(deband = (settings.deband - 1).coerceAtLeast(0))) },
{ onChange(settings.copy(deband = (settings.deband + 1).coerceAtMost(8))) })
Toggle("FXAA", "Smooths jagged edges.", settings.fxaa) { onChange(settings.copy(fxaa = it)) }
Toggle("CRT", "Scanlines and colour fringes.", settings.crt) { onChange(settings.copy(crt = it)) }
Toggle("NTSC", "Old TV signal look.", settings.ntsc) { onChange(settings.copy(ntsc = it)) }
Toggle("Toon", "Cartoon outlines.", settings.toon) { onChange(settings.copy(toon = it)) }
Choice("Frame-rate cap", listOf(0 to "Off", 30 to "30 fps", 45 to "45 fps", 60 to "60 fps"), settings.maxFps) { onChange(settings.copy(maxFps = it)) }
Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = { onChange(settings.withoutEffects()) }) { Text("Reset picture") }
}
Text("Effects cost a little GPU time; with none set the stream is shown directly.", style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))
}
if ((section == null && XboxNativePlayerActivity.supported()) || section == "framerate") Section("Frame rate (native engine)",
"With frame generation this is the rate shown; without it, only targets below the stream's 60 fps change anything.") {
Choice("Target", listOf(0 to "Screen's rate", 30 to "30 fps", 45 to "45 fps", 60 to "60 fps", 120 to "120 fps", 144 to "144 fps", 165 to "165 fps"),
settings.fpsLimit) { onChange(settings.copy(fpsLimit = it, fpsCustomOn = false)) }
Toggle("Custom frame rate", "Set any rate from 10 to 165 fps with the slider.", settings.fpsCustomOn) { onChange(settings.copy(fpsCustomOn = it)) }
if (settings.fpsCustomOn) SliderRow("Custom", settings.fpsCustom, 10, 165) { onChange(settings.copy(fpsCustom = it)) }
}
if ((section == null && XboxNativePlayerActivity.supported()) || section == "latency") Section("Low latency (native engine)", null) {
Toggle("Instant controller input", "Sends each press the moment it happens instead of every 16 ms.", settings.instantInput) {
onChange(settings.copy(instantInput = it))
}
Toggle("Small network buffer", "Shows frames as soon as they are decoded. Less delay; may stutter on weak Wi-Fi.",
settings.smallBuffer, pending { it.smallBuffer != settings.smallBuffer }) { onChange(settings.copy(smallBuffer = it)) }
Toggle("Fast decoder", "The video chip's low-latency mode.", settings.fastDecoder,
pending { it.fastDecoder != settings.fastDecoder }) { onChange(settings.copy(fastDecoder = it)) }
Toggle("Zero-copy picture", "Frames go straight from the video chip to the screen: the lowest delay. Used while frame generation is off and no target below 60 fps is set; switches live.",
settings.zeroCopy) { onChange(settings.copy(zeroCopy = it)) }
}
// "overlay-native": the native player's page (its sound has no volume boost).
if (section == null || section == "overlay" || section == "overlay-native") Section("Overlay and sound", null) {
Choice("Performance overlay", listOf(0 to "Off", 1 to "FPS only", 2 to "Basic", 3 to "Detailed", 4 to "Full"), settings.statsLevel) {
onChange(settings.copy(statsLevel = it))
}
Choice("Overlay layout", listOf("horizontal" to "Horizontal", "vertical" to "Vertical"), settings.statsLayout) { onChange(settings.copy(statsLayout = it)) }
Choice("Overlay position", listOf("right" to "Top right", "left" to "Top left"), settings.statsCorner) { onChange(settings.copy(statsCorner = it)) }
Text("Basic: fps, ping, resolution. Detailed: + bitrate, decode time, packet loss. Full: + codec, jitter, " +
"dropped frames, server.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
if (section != "overlay-native") Step("Volume", "${settings.volume}%", { onChange(settings.copy(volume = (settings.volume - 25).coerceAtLeast(100))) },
{ onChange(settings.copy(volume = (settings.volume + 25).coerceAtMost(300))) })
Step("Controller rumble", if (settings.rumble == 0) "Off" else "${settings.rumble}%", { onChange(settings.copy(rumble = (settings.rumble - 25).coerceAtLeast(0))) },
{ onChange(settings.copy(rumble = (settings.rumble + 25).coerceAtMost(100))) })
}
}
@Composable
private fun Section(title: String, note: String?, content: @Composable ColumnScope.() -> Unit) {
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {
Text(title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
if (note != null) Text(note, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Spacer(Modifier.height(4.dp))
content()
}
}
/**
* One settings row, driven by a controller: it takes focus as a whole (highlighted), Left / Right change its
* value, A / Enter selects; the − / + buttons and switches inside stay for touch only.
*/
@Composable
private fun SettingRow(
onLeft: (() -> Unit)?,
onRight: (() -> Unit)?,
onSelect: (() -> Unit)?,
content: @Composable RowScope.() -> Unit,
) {
val panel = LocalPanelFocus.current
val index = panel?.take() ?: -1
var focused by remember { mutableStateOf(false) }
val currentSelect by rememberUpdatedState(onSelect)
val cs = MaterialTheme.colorScheme
val shape = RoundedCornerShape(10.dp)
Row(
Modifier.fillMaxWidth().padding(vertical = 1.dp).clip(shape)
.background(if (focused) cs.primary.copy(alpha = 0.16f) else Color.Transparent)
.border(2.dp, if (focused) cs.primary else Color.Transparent, shape)
.let { if (panel != null && index >= 0) it.focusRequester(panel.requester(index)) else it }
.onFocusChanged { state -> focused = state.isFocused; if (state.isFocused && index >= 0) panel?.onFocused?.invoke(index) }
.onKeyEvent { event ->
if (event.type != KeyEventType.KeyDown) return@onKeyEvent false
val action = when (event.key) {
Key.DirectionLeft -> onLeft
Key.DirectionRight -> onRight
Key.Enter, Key.NumPadEnter, Key.DirectionCenter, Key.ButtonA -> onSelect
else -> null
}
if (action != null) { action(); true } else false
}
.focusable()
// A tap selects too, without a second focus stop (a clickable would be one).
.pointerInput(Unit) { detectTapGestures { currentSelect?.invoke() } }
.padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
content = content,
)
}
private val noFocus = Modifier.focusProperties { canFocus = false }
@Composable
private fun Step(label: String, value: String, onMinus: () -> Unit, onPlus: () -> Unit) {
SettingRow(onLeft = onMinus, onRight = onPlus, onSelect = onPlus) {
Text(label, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurface)
OutlinedButton(onClick = onMinus, modifier = noFocus.size(40.dp), contentPadding = PaddingValues(0.dp)) { Text("−") }
Text(value, Modifier.widthIn(min = 112.dp, max = 168.dp).padding(horizontal = 4.dp), textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis)
OutlinedButton(onClick = onPlus, modifier = noFocus.size(40.dp), contentPadding = PaddingValues(0.dp)) { Text("+") }
}
}
/** A value slider (touch) that a controller moves with Left / Right in steps of 1 (hold to repeat). */
@Composable
private fun SliderRow(label: String, value: Int, min: Int, max: Int, onValue: (Int) -> Unit) {
SettingRow(onLeft = { onValue((value - 1).coerceAtLeast(min)) }, onRight = { onValue((value + 1).coerceAtMost(max)) }, onSelect = null) {
Text(label, Modifier.width(72.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurface)
androidx.compose.material3.Slider(value = value.toFloat(), onValueChange = { onValue(it.toInt().coerceIn(min, max)) },
valueRange = min.toFloat()..max.toFloat(), modifier = noFocus.weight(1f))
Text("$value fps", Modifier.width(72.dp), textAlign = TextAlign.End, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface)
}
}
@Composable
private fun <T> Choice(label: String, options: List<Pair<T, String>>, selected: T, needsRestart: Boolean = false, onSelect: (T) -> Unit) {
val index = options.indexOfFirst { it.first == selected }.coerceAtLeast(0)
Step(label, options.getOrNull(index)?.second ?: "",
{ if (options.isNotEmpty()) onSelect(options[(index - 1 + options.size) % options.size].first) },
{ if (options.isNotEmpty()) onSelect(options[(index + 1) % options.size].first) })
if (needsRestart) Text("Takes effect when you restart the stream.", style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.tertiary, modifier = Modifier.padding(start = 8.dp, bottom = 4.dp))
}
@Composable
private fun Toggle(label: String, note: String, checked: Boolean, needsRestart: Boolean = false, onToggle: (Boolean) -> Unit) {
SettingRow(onLeft = { onToggle(false) }, onRight = { onToggle(true) }, onSelect = { onToggle(!checked) }) {
Column(Modifier.weight(1f)) {
Text(label, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurface)
Text(note, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Spacer(Modifier.width(8.dp))
Switch(checked = checked, onCheckedChange = onToggle, modifier = noFocus)
}
if (needsRestart) Text("Takes effect when you restart the stream.", style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.tertiary, modifier = Modifier.padding(start = 8.dp, bottom = 4.dp))
}
/** One entry of the cloud players' menu list (highlighted when selected; A or a tap opens it). */
@Composable
internal fun XboxMenuEntry(title: String, note: String?, focus: FocusRequester? = null, onFocused: () -> Unit = {}, onClick: () -> Unit) {
val cs = MaterialTheme.colorScheme
var focused by remember { mutableStateOf(false) }
val shape = RoundedCornerShape(10.dp)
androidx.compose.material3.Surface(
onClick = onClick, color = if (focused) cs.primary.copy(alpha = 0.2f) else cs.surfaceContainerHigh, shape = shape,
border = if (focused) androidx.compose.foundation.BorderStroke(2.dp, cs.primary) else null,
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 3.dp)
.let { if (focus != null) it.focusRequester(focus) else it }
.onFocusChanged { state -> focused = state.isFocused; if (state.isFocused) onFocused() }
.onKeyEvent { event -> if (event.type == KeyEventType.KeyDown && event.key == Key.ButtonA) { onClick(); true } else false },
) {
Column(Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) {
Text(title, style = MaterialTheme.typography.titleSmall, color = cs.onSurface)
if (note != null) Text(note, style = MaterialTheme.typography.bodySmall, color = cs.onSurfaceVariant)
}
}
}
@@ -0,0 +1,74 @@
package com.droiddeck.launcher.stores.xbox
import org.json.JSONArray
import org.json.JSONObject
/** Request shapes follow Microsoft's web player as Greenlight (MIT) implements them. */
internal class XboxCloudSignalling(
private val session: XboxCloudSession.Session,
private val titleId: String,
private val settings: XboxCloudSettings,
) {
@Volatile var path: String? = null
private set
fun op(op: String, arg: String = ""): XboxCloudSession.Reply = when (op) {
"start" -> start()
"state" -> XboxCloudSession.request(session, "GET", "/$path/state")
"connect" -> connect()
"sdp" -> sdp(arg)
"ice" -> ice(arg)
"keepalive" -> XboxCloudSession.request(session, "POST", "/$path/keepalive", "{}")
else -> XboxCloudSession.Reply(0, "unknown request")
}
fun start(): XboxCloudSession.Reply {
val body = JSONObject().put("clientSessionId", "").put("titleId", titleId).put("systemUpdateGroup", "")
.put("settings", JSONObject().put("nanoVersion", "V3;WebrtcTransport.dll").put("enableOptionalDataCollection", false)
.put("enableTextToSpeech", false).put("highContrast", 0).put("locale", settings.language.ifEmpty { java.util.Locale.getDefault().toLanguageTag() })
.put("useIceConnection", false).put("timezoneOffsetMinutes", java.util.TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 60_000)
.put("sdkType", "web").put("osName", settings.osName))
.put("serverId", "").put("fallbackRegionNames", JSONArray())
return XboxCloudSession.request(session, "POST", "/v5/sessions/cloud/play", body.toString()).also { reply ->
if (reply.status in 200..299) path = JSONObject(reply.body).getString("sessionPath").trim('/')
}
}
fun connect(): XboxCloudSession.Reply {
val token = session.userToken ?: return XboxCloudSession.Reply(0, "no cloud transfer token for this account")
return XboxCloudSession.request(session, "POST", "/$path/connect", JSONObject().put("userToken", token).toString())
}
fun sdp(offer: String): XboxCloudSession.Reply {
val body = JSONObject().put("messageType", "offer").put("sdp", offer).put("requestId", "1").put("configuration", JSONObject()
.put("chatConfiguration", JSONObject().put("bytesPerSample", 2).put("expectedClipDurationMs", 20)
.put("format", JSONObject().put("codec", "opus").put("container", "webm")).put("numChannels", 1).put("sampleFrequencyHz", 24000))
.put("chat", version(1, 1)).put("control", version(1, 3)).put("input", version(1, 9)).put("message", version(1, 1))
.put("reliableinput", version(9, 9)).put("unreliableinput", version(9, 9)))
val posted = XboxCloudSession.request(session, "POST", "/$path/sdp", body.toString())
return if (posted.status !in 200..299) posted else poll("/$path/sdp")
}
fun ice(candidates: String): XboxCloudSession.Reply {
val posted = XboxCloudSession.request(session, "POST", "/$path/ice", JSONObject().put("candidates", JSONArray(candidates)).toString())
return if (posted.status !in 200..299) posted else poll("/$path/ice")
}
fun stop(): XboxCloudSession.Reply? {
val current = path ?: return null
path = null
return runCatching { XboxCloudSession.request(session, "DELETE", "/$current") }.getOrNull()
}
private fun version(min: Int, max: Int) = JSONObject().put("minVersion", min).put("maxVersion", max)
/** The exchange answers 204 until the console has replied. */
private fun poll(path: String): XboxCloudSession.Reply {
repeat(60) {
val reply = XboxCloudSession.request(session, "GET", path)
if (reply.status != 204) return reply
Thread.sleep(500)
}
return XboxCloudSession.Reply(0, "no answer from the cloud console")
}
}
@@ -0,0 +1,74 @@
package com.droiddeck.launcher.stores.xbox
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/**
* Hands the main process's Xbox Cloud Gaming tokens to the native player's process (:xcloudnative) over Binder, so
* they stay in memory (not exported, same app only) and a stream does not wait for a second ~20 s token fetch.
*/
class XboxCloudTokenService : Service() {
private val worker = Executors.newSingleThreadExecutor()
private val messenger = Messenger(Handler(Looper.getMainLooper()) { message ->
val replyTo = message.replyTo ?: return@Handler true
val account = message.data?.getString("account").orEmpty()
worker.execute {
val reply = Message.obtain(null, REPLY)
reply.data = runCatching { XboxCloudSession.toBundle(XboxCloudSession.get(applicationContext, account)) }
.getOrElse { Bundle().apply { putString("error", it.message ?: it.javaClass.simpleName) } }
runCatching { replyTo.send(reply) }
}
true
})
override fun onBind(intent: Intent?): IBinder = messenger.binder
override fun onDestroy() { worker.shutdown(); super.onDestroy() }
companion object {
private const val REQUEST = 1
private const val REPLY = 2
/** Blocks until the main process answers (its tokens, or "error"), or returns null when it cannot be reached. */
fun request(context: Context, account: String, timeoutSeconds: Long): Bundle? {
val app = context.applicationContext
val done = CountDownLatch(1)
var answer: Bundle? = null
val thread = HandlerThread("xcloud-token").apply { start() }
val replies = Messenger(Handler(thread.looper) { message ->
if (message.what == REPLY) { answer = message.data; done.countDown() }
true
})
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
val ask = Message.obtain(null, REQUEST).apply { data = Bundle().apply { putString("account", account) }; replyTo = replies }
if (binder == null || runCatching { Messenger(binder).send(ask) }.isFailure) done.countDown()
}
override fun onServiceDisconnected(name: ComponentName?) { done.countDown() }
}
val bound = runCatching { app.bindService(Intent(app, XboxCloudTokenService::class.java), connection, Context.BIND_AUTO_CREATE) }
.getOrDefault(false)
try {
if (!bound) return null
done.await(timeoutSeconds, TimeUnit.SECONDS)
return answer
} finally {
if (bound) runCatching { app.unbindService(connection) }
thread.quitSafely()
}
}
}
}
@@ -14,6 +14,11 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
val name = "droiddeck-xbox-${UUID.randomUUID()}"
private val generation = lifecycle(app, expectedGeneration) { it }
private val server = LocalServerSocket(name)
// Some devices refuse the abstract socket from inside PRoot; the backend then falls back to this keyed loopback port.
private val loopback = java.net.ServerSocket(0, 8, java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)))
val port: Int get() = loopback.localPort
val key: String = ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
@Volatile private var loopbackUsed = false
@Volatile private var closed = false
private val bound = java.util.concurrent.CountDownLatch(1)
private var backend: Process? = null
@@ -79,33 +84,122 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
} }
}
init {
/** Each connection gets its own thread; an accept error is logged and retried instead of silently ending the loop. */
private fun <S> listen(route: String, accept: () -> S, serve: (S) -> Unit) = Thread({
var failures = 0
while (!closed) {
val socket = try { accept() } catch (e: Exception) {
if (closed) break
failures++
note("Credential $route accept failed: ${e.javaClass.simpleName}")
if (failures >= 20) { note("Credential $route listener stopped after repeated accept failures"); break }
Thread.sleep(100)
continue
}
failures = 0
Thread({ serve(socket) }, "xbox-credentials-$route-request").start()
}
}, "xbox-credentials-$route").start()
/** Logs requests that take 2 s or more, and the stage a request is still in after 8 s (the backend waits 30 s). */
private fun tracked(route: String, block: (step: (String) -> Unit) -> JSONObject): JSONObject {
val started = android.os.SystemClock.elapsedRealtime()
val stage = java.util.concurrent.atomic.AtomicReference("auth")
val done = java.util.concurrent.CountDownLatch(1)
val stages = java.util.Collections.synchronizedList(mutableListOf<String>())
var mark = started
val step = { next: String ->
val now = android.os.SystemClock.elapsedRealtime()
stages += "${stage.getAndSet(next)} ${now - mark} ms"
mark = now
}
Thread({
while (!closed) {
val socket = runCatching { server.accept() }.getOrNull() ?: break
socket.use {
it.soTimeout = 10_000
val reply = runCatching {
if (!done.await(8, java.util.concurrent.TimeUnit.SECONDS)) note("Credential $route request still in ${stage.get()} after 8 s")
}, "xbox-credentials-watch").apply { isDaemon = true; start() }
try {
return block(step)
} finally {
done.countDown()
step("done")
val total = android.os.SystemClock.elapsedRealtime() - started
if (total >= 2000) note("Credential $route request took $total ms (${stages.joinToString(", ")})")
}
}
init {
listen("socket", { server.accept() }) { socket ->
socket.use {
it.soTimeout = 10_000
val reply = tracked("socket") { step ->
runCatching {
val peer = it.peerCredentials
check(peer.uid == android.os.Process.myUid() && authorized(peer.pid))
step("read")
val request = JSONObject(readLine(it.inputStream.buffered(), 2_097_152))
step("lock")
storage(app) {
step("answer")
check(!closed && epoch(app) == generation && authorized(peer.pid))
answer(request)
answer(request, step)
}
}.getOrElse {
note("Credential request rejected: ${it.javaClass.simpleName}")
JSONObject().put("ok", false)
}
runCatching { it.outputStream.write((reply.toString() + "\n").toByteArray()) }
}
runCatching { it.outputStream.write((reply.toString() + "\n").toByteArray()) }
.onFailure { failure -> note("Credential reply not delivered: ${failure.javaClass.simpleName}") }
}
}, "xbox-credentials").start()
}
listen("loopback", { loopback.accept() }) { socket ->
socket.use {
it.soTimeout = 10_000
val reply = tracked("loopback") { step ->
runCatching {
val input = it.getInputStream().buffered()
check(it.inetAddress.isLoopbackAddress)
if (!java.security.MessageDigest.isEqual(readLine(input, 128).toByteArray(), key.toByteArray())) {
rejected("loopback-key"); error("loopback key")
}
if (!loopbackOwner(it.port)) { rejected("loopback-owner"); error("loopback owner") }
check(bound.await(5, java.util.concurrent.TimeUnit.SECONDS) && backend?.isAlive == true)
if (!loopbackUsed) { loopbackUsed = true; note("Backend reached the app over the loopback fallback") }
step("read")
val request = JSONObject(readLine(input, 2_097_152))
step("lock")
storage(app) {
step("answer")
check(!closed && epoch(app) == generation)
answer(request, step)
}
}.getOrElse { failure ->
note("Credential request rejected: ${failure.javaClass.simpleName}")
JSONObject().put("ok", false)
}
}
runCatching { it.getOutputStream().write((reply.toString() + "\n").toByteArray()) }
.onFailure { failure -> note("Credential reply not delivered: ${failure.javaClass.simpleName}") }
}
}
}
private fun answer(request: JSONObject): JSONObject {
/** The connecting socket must belong to this app's user; an unreadable table (newer Android) leaves the key as the check. */
private fun loopbackOwner(peerPort: Int): Boolean {
val uid = android.os.Process.myUid()
val rows = listOf("/proc/net/tcp", "/proc/net/tcp6").mapNotNull { runCatching { java.io.File(it).readLines().drop(1) }.getOrNull() }.flatten()
val owners = rows.mapNotNull { row ->
val fields = row.trim().split(Regex("\\s+"))
val local = fields.getOrNull(1)?.substringAfterLast(':')?.toIntOrNull(16)
val remote = fields.getOrNull(2)?.substringAfterLast(':')?.toIntOrNull(16)
if (local == peerPort && remote == loopback.localPort) fields.getOrNull(7)?.toIntOrNull() else null
}
return owners.isEmpty() || owners.all { it == uid }
}
private fun answer(request: JSONObject, step: (String) -> Unit = {}): JSONObject {
val key = request.getString("key")
require(key.isNotEmpty() && key.length <= 512)
step("record-read")
val record = StoreAccounts.read(app, Store.XBOX)
check(!StoreAccounts.isUnavailable(Store.XBOX))
val json = record ?: JSONObject()
@@ -118,15 +212,16 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
require(bytes.length() <= 262_144)
for (i in 0 until bytes.length()) require(bytes.getInt(i) in 0..255)
slots.put(key, bytes)
step("record-save")
StoreAccounts.write(app, Store.XBOX, json)
}
"remove" -> { slots.remove(key); StoreAccounts.write(app, Store.XBOX, json) }
"remove" -> { slots.remove(key); step("record-save"); StoreAccounts.write(app, Store.XBOX, json) }
else -> error("Invalid credential operation")
}
return result
}
override fun close() { closed = true; bound.countDown(); runCatching { server.close() } }
override fun close() { closed = true; bound.countDown(); runCatching { server.close() }; runCatching { loopback.close() } }
companion object {
val lock = Any()
@@ -39,11 +39,17 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
var sequence = -1L
try {
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, folder.path, "--market", market,
Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market,
"--progress-json", "--control-stdin") + selection).use { process ->
child = process
val diagnostics = Xodus.diagnostics(process)
val rejected = AtomicBoolean(false)
val rejectedLine = Regex(Xodus.SIGN_IN_REJECTED)
val diagnostics = Xodus.diagnostics(process) { line ->
StoresState.logLine("Xbox: $line")
if (line.matches(rejectedLine)) rejected.set(true)
}
if (cancelled.get()) process.process.destroy()
process.process.inputStream.bufferedReader().useLines { lines -> lines.forEach { line ->
if (line.startsWith("NEXUS_PROGRESS ")) {
@@ -62,6 +68,7 @@ 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
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 (content) {
@@ -23,18 +23,19 @@ internal object XboxLibraryCache {
fun clear(app: Context) { prefs(app).edit().remove("library").commit() }
internal fun encode(account: String, market: String, games: List<CatalogItem>, now: Long = System.currentTimeMillis()): String =
JSONObject().put("schema", 1).put("account", account).put("market", market).put("savedAt", now)
JSONObject().put("schema", 2).put("account", account).put("market", market).put("savedAt", now)
.put("games", JSONArray().apply {
for (game in games) put(JSONObject().put("id", game.id).put("title", game.title)
.put("image", game.imageUrl).put("poster", game.tallImageUrl).put("description", game.description)
.put("developer", game.developer).put("publisher", game.publisher).put("size", game.sizeBytes)
.put("access", if (game.subscription) "gamepass" else if (game.owned) "owned" else "none"))
.put("access", if (game.subscription) "gamepass" else if (game.owned) "owned" else "none")
.put("pc", game.xboxPc).put("cloud", game.xboxCloud).put("cloudId", game.extra["cloudId"].orEmpty()))
}).toString()
internal fun decode(text: String?, account: String, market: String, now: Long = System.currentTimeMillis()): Snapshot? = runCatching {
require(text != null && text.length <= 8_000_000)
val json = JSONObject(text)
require(json.getInt("schema") == 1 && json.getString("account") == account && json.getString("market") == market)
require(json.getInt("schema") == 2 && json.getString("account") == account && json.getString("market") == market)
val savedAt = json.getLong("savedAt")
require(savedAt > 0 && savedAt <= now + 60_000)
val rows = json.getJSONArray("games")
@@ -44,12 +45,14 @@ internal object XboxLibraryCache {
val id = row.getString("id")
val title = row.getString("title")
val access = row.getString("access")
val cloudId = row.optString("cloudId").takeIf { it.matches(Regex("[A-Z0-9]{12}")) }.orEmpty()
require(id.matches(Regex("[A-Z0-9]{12}")) && title.isNotBlank() && access in setOf("owned", "gamepass"))
CatalogItem(Store.XBOX, id, title, row.optString("image").takeIf { it.isNotEmpty() },
tallImageUrl = row.optString("poster").takeIf { it.isNotEmpty() },
description = row.optString("description"), developer = row.optString("developer"), publisher = row.optString("publisher"),
sizeBytes = row.optLong("size"), owned = access == "owned", subscription = access == "gamepass",
storeUrl = "https://www.xbox.com/games/store/$id", extra = mapOf("market" to market, "access" to access))
storeUrl = "https://www.xbox.com/games/store/$id", extra = mapOf("market" to market, "access" to access,
"pc" to XboxCatalog.flag(row.getBoolean("pc")), "cloud" to XboxCatalog.flag(row.getBoolean("cloud")), "cloudId" to cloudId))
}
require(games.map { it.id }.distinct().size == games.size)
Snapshot(games, savedAt)
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.stores.xbox
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.stores.CatalogItem
object XboxLibraryFilter {
const val ALL = "all"
const val OWNED = "owned"
const val GAME_PASS = "gamepass"
const val CLOUD = "cloud"
val ALL_FILTERS = listOf(ALL, OWNED, GAME_PASS, CLOUD)
var current by mutableStateOf(ALL)
private set
fun load(context: Context) {
current = context.getSharedPreferences("xbox", Context.MODE_PRIVATE).getString("libraryFilter", ALL)?.takeIf { it in ALL_FILTERS } ?: ALL
}
fun set(context: Context, filter: String) {
current = filter
context.getSharedPreferences("xbox", Context.MODE_PRIVATE).edit().putString("libraryFilter", filter).apply()
}
fun keeps(filter: String, item: CatalogItem): Boolean = when (filter) {
OWNED -> item.owned
GAME_PASS -> item.subscription
CLOUD -> item.xboxCloud
else -> true
}
fun label(filter: String): String = when (filter) {
OWNED -> "Owned"
GAME_PASS -> "Game Pass"
CLOUD -> "Cloud"
else -> "All"
}
}
@@ -31,6 +31,7 @@ class XboxLoginActivity : ComponentActivity() {
@Volatile private var session = 0L
@Volatile private var closed = false
@Volatile private var step = "starting"
private val codes = java.util.concurrent.CopyOnWriteArrayList<String>()
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
@@ -53,6 +54,14 @@ class XboxLoginActivity : ComponentActivity() {
Thread({
if (closed) return@Thread
try {
// A record without a username is left from a sign-in that never finished; starting clean
// also avoids reading it back with an older, slow Keystore key.
progress("preparing the sign-in", "Preparing Microsoft sign-in…")
val leftover = StoreAccounts.read(applicationContext, Store.XBOX)
if (leftover != null && leftover.optString("username").isBlank()) {
XboxCredentials.invalidate(applicationContext)
logStep("discarded credentials from an unfinished sign-in")
}
val accountGeneration = XboxCredentials.lifecycle(applicationContext) { it }
progress("downloading the Xbox components", "Downloading Xbox components…")
check(AddonPack.XBOX.await(applicationContext, { !closed }) { state ->
@@ -64,7 +73,10 @@ class XboxLoginActivity : ComponentActivity() {
child = process
if (closed) return@use
// StoresState.logLine writes no file in this process, so the reason would miss the shared log.
Xodus.diagnostics(process) { logStep(it) }
Xodus.diagnostics(process) { line ->
logStep(line)
line.removePrefix("NEXUS_CREDENTIAL_ERROR_V1 ").takeIf { it != line && it !in codes && codes.size < 6 }?.let(codes::add)
}
progress("waiting for the Xbox helper", "Waiting for the Xbox helper…")
val timer = Thread({
runCatching { if (!process.process.waitFor(10, TimeUnit.MINUTES)) process.process.destroy() }
@@ -140,7 +152,8 @@ class XboxLoginActivity : ComponentActivity() {
logStep("failed while $failed: $reason")
runOnUiThread {
disposeView()
status.text = "Microsoft sign-in did not complete.\nFailed while $failed: $reason\nClose this window and try again."
val details = if (codes.isEmpty()) "" else "\nDetails: ${codes.joinToString(", ")}"
status.text = "Microsoft sign-in did not complete.\nFailed while $failed: $reason$details\nClose this window and try again."
}
}
}, "xbox-login").start()
@@ -0,0 +1,80 @@
package com.droiddeck.launcher.stores.xbox
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
/**
* Controller state for the native cloud player, from Android key and motion events (no Gamepad API). Button
* bits follow the xCloud input report (Greenlight's packet.ts): Nexus 2, Menu 4, View 8, A 16, B 32, X 64,
* Y 128, D-pad 256..2048, shoulders 4096 / 8192, stick clicks 16384 / 32768.
*/
internal class XboxNativePad {
data class State(val buttons: Int, val lx: Float, val ly: Float, val rx: Float, val ry: Float, val lt: Float, val rt: Float) {
/** Greenlight's rule: any button change, a stick moved past 0.08 or held past 0.15, a trigger past 0.01. */
fun differsFrom(o: State): Boolean = buttons != o.buttons ||
listOf(lx to o.lx, ly to o.ly, rx to o.rx, ry to o.ry).any { (a, b) -> Math.abs(a - b) > 0.08f || Math.abs(a) > 0.15f } ||
Math.abs(lt - o.lt) > 0.01f || Math.abs(rt - o.rt) > 0.01f
}
@Volatile private var buttons = 0
@Volatile private var hatButtons = 0
@Volatile private var lx = 0f; @Volatile private var ly = 0f
@Volatile private var rx = 0f; @Volatile private var ry = 0f
@Volatile private var lt = 0f; @Volatile private var rt = 0f
/** Called after any change (instant controller input). */
@Volatile var onChanged: (() -> Unit)? = null
/** Buttons pressed on behalf of the app (the menu's Xbox button), OR-ed in. */
@Volatile var overrideButtons = 0
fun snapshot() = State(buttons or hatButtons or overrideButtons, lx, ly, rx, ry, lt, rt)
/** True when the event was a controller button this pad tracks. */
fun onKey(event: KeyEvent): Boolean {
val bit = when (event.keyCode) {
KeyEvent.KEYCODE_BUTTON_A -> 16
KeyEvent.KEYCODE_BUTTON_B -> 32
KeyEvent.KEYCODE_BUTTON_X -> 64
KeyEvent.KEYCODE_BUTTON_Y -> 128
KeyEvent.KEYCODE_DPAD_UP -> 256
KeyEvent.KEYCODE_DPAD_DOWN -> 512
KeyEvent.KEYCODE_DPAD_LEFT -> 1024
KeyEvent.KEYCODE_DPAD_RIGHT -> 2048
KeyEvent.KEYCODE_BUTTON_L1 -> 4096
KeyEvent.KEYCODE_BUTTON_R1 -> 8192
KeyEvent.KEYCODE_BUTTON_THUMBL -> 16384
KeyEvent.KEYCODE_BUTTON_THUMBR -> 32768
KeyEvent.KEYCODE_BUTTON_START -> 4
KeyEvent.KEYCODE_BUTTON_SELECT -> 8
// Digital triggers on pads without analog axes.
KeyEvent.KEYCODE_BUTTON_L2 -> { lt = if (event.action == KeyEvent.ACTION_DOWN) 1f else 0f; onChanged?.invoke(); return true }
KeyEvent.KEYCODE_BUTTON_R2 -> { rt = if (event.action == KeyEvent.ACTION_DOWN) 1f else 0f; onChanged?.invoke(); return true }
else -> return false
}
buttons = if (event.action == KeyEvent.ACTION_DOWN) buttons or bit else buttons and bit.inv()
onChanged?.invoke()
return true
}
/** True when the event came from a joystick (sticks, triggers, hat). */
fun onMotion(event: MotionEvent): Boolean {
if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) return false
val device = event.device
fun axis(code: Int): Float {
val value = event.getAxisValue(code)
val flat = device?.getMotionRange(code, event.source)?.flat ?: 0f
return if (Math.abs(value) > maxOf(flat, 0.08f)) value else 0f
}
lx = axis(MotionEvent.AXIS_X); ly = axis(MotionEvent.AXIS_Y)
rx = axis(MotionEvent.AXIS_Z); ry = axis(MotionEvent.AXIS_RZ)
lt = maxOf(axis(MotionEvent.AXIS_LTRIGGER), axis(MotionEvent.AXIS_BRAKE))
rt = maxOf(axis(MotionEvent.AXIS_RTRIGGER), axis(MotionEvent.AXIS_GAS))
val hx = event.getAxisValue(MotionEvent.AXIS_HAT_X); val hy = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
hatButtons = (if (hy < -0.5f) 256 else 0) or (if (hy > 0.5f) 512 else 0) or (if (hx < -0.5f) 1024 else 0) or (if (hx > 0.5f) 2048 else 0)
onChanged?.invoke()
return true
}
fun reset() { buttons = 0; hatButtons = 0; overrideButtons = 0; lx = 0f; ly = 0f; rx = 0f; ry = 0f; lt = 0f; rt = 0f }
}
@@ -0,0 +1,852 @@
package com.droiddeck.launcher.stores.xbox
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.view.Gravity
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import org.json.JSONArray
import org.json.JSONObject
import org.webrtc.DataChannel
import org.webrtc.DefaultVideoEncoderFactory
import org.webrtc.EglBase
import org.webrtc.IceCandidate
import org.webrtc.MediaConstraints
import org.webrtc.MediaStream
import org.webrtc.MediaStreamTrack
import org.webrtc.PeerConnection
import org.webrtc.PeerConnectionFactory
import org.webrtc.RtpReceiver
import org.webrtc.RtpTransceiver
import org.webrtc.SdpObserver
import org.webrtc.SessionDescription
import org.webrtc.VideoTrack
import org.webrtc.audio.JavaAudioDeviceModule
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/**
* Native Xbox Cloud Gaming player (opt-in, Android 10+): Google's WebRTC library instead of the web page, the
* xCloud channels ported from Greenlight (XboxNativeProtocol), controller from Android input events, and the
* picture through DroidDeck's own compositor (XboxNativeVideo) so DDFG or LSFG can generate frames. Runs in
* its own process (:xcloudnative): that compositor instance is never the Linux session's.
* Sign-in and session requests are the web player's (XboxCloudSession, XboxCloudSignalling).
*/
class XboxNativePlayerActivity : ComponentActivity() {
private lateinit var root: FrameLayout
private lateinit var surfaceView: SurfaceView
private lateinit var status: TextView
private lateinit var overlay: TextView
private val worker = Executors.newSingleThreadExecutor()
private val ticker = Executors.newSingleThreadScheduledExecutor()
private val pad = XboxNativePad()
private var eglBase: EglBase? = null
private var factory: PeerConnectionFactory? = null
private var pc: PeerConnection? = null
private var protocol: XboxNativeProtocol? = null
private var video: XboxNativeVideo? = null
@Volatile private var signalling: XboxCloudSignalling? = null
@Volatile private var settings = XboxCloudSettings()
@Volatile private var closed = false
/** The stream reached the screen at least once (a later failure is a lost connection, not a failed start). */
@Volatile private var connectedOnce = false
/** The session was ended because the player stayed in the background (Android freezes the app soon after). */
@Volatile private var endedInBackground = false
private var backgroundEnd: Runnable? = null
private var notice: androidx.compose.ui.platform.ComposeView? = null
@Volatile private var regionNames = emptyList<String>()
@Volatile private var serverName: String? = null
private val candidates = mutableListOf<IceCandidate>()
private val gathered = CountDownLatch(1)
private var menu: androidx.compose.ui.platform.ComposeView? = null
private var menuPage by androidx.compose.runtime.mutableStateOf("")
private var lastMainEntry = 0
private val lastRow = mutableMapOf<String, Int>()
/** The settings this stream started with (stream-start settings changed since then need a restart). */
private var startedWith: XboxCloudSettings? = null
/**
* The picture's route right now: true = zero-copy (decoder straight onto the screen), false = WebRTC's texture
* through the Vulkan compositor. Zero-copy whenever it is chosen and frame generation is off; switched live.
*/
@Volatile private var zeroCopy = false
/** The SurfaceView's surface while it exists (UI thread). */
private var screen: android.view.Surface? = null
private var screenW = 0
private var screenH = 0
@Volatile private var zeroCopyFrames = 0L
@Volatile private var decoders: org.webrtc.DroidDeckLowLatencyDecoderFactory? = null
private var lastZeroCopyFrames = 0L
private var lastSubmitted = 0L
/** The release of the Guide press that opened the menu must not close it again. */
private var swallowGuideUp = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
hideBars()
watchBars()
root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
surfaceView = SurfaceView(this)
root.addView(surfaceView, FrameLayout.LayoutParams(-1, -1))
status = TextView(this).apply { setTextColor(Color.WHITE); textSize = 16f; gravity = Gravity.CENTER }
root.addView(status, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM).apply { bottomMargin = 120 })
overlay = TextView(this).apply {
setTextColor(Color.WHITE); textSize = 12f; typeface = android.graphics.Typeface.MONOSPACE
setBackgroundColor(Color.argb(140, 0, 0, 0)); setPadding(12, 6, 12, 6); visibility = android.view.View.GONE
}
root.addView(overlay, FrameLayout.LayoutParams(-2, -2, Gravity.TOP or Gravity.END).apply { topMargin = 16; rightMargin = 16 })
setContentView(root)
settings = XboxCloudSettings.load(this)
startedWith = settings
applyDisplayRate(settings.fpsTarget)
applyOverlay()
val egl = EglBase.create().also { eglBase = it }
val nativeVideo = XboxNativeVideo(this, egl) { log(it) }.also { video = it }
surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
screen = holder.surface; screenW = width; screenH = height
// Zero-copy: the decoder owns this surface (back on it after a stand-in); the Vulkan compositor must not connect to it.
if (zeroCopy) { decoders?.setZeroCopySurface(holder.surface); return }
@Suppress("DEPRECATION")
nativeVideo.setSurface(holder.surface, width, height, windowManager.defaultDisplay.refreshRate)
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
screen = null
if (zeroCopy) decoders?.setZeroCopySurface(null) else nativeVideo.setSurface(null, 0, 0, 60f)
}
})
show("Signing in to Xbox Cloud Gaming…")
worker.execute { runCatching { run() }.onFailure { fail("start", it.message ?: it.javaClass.simpleName) } }
}
private fun log(text: String) = com.droiddeck.launcher.stores.StoresState.logLine("Xbox: native player: ${text.take(240)}")
private fun show(text: String) = runOnUiThread { status.text = text; status.visibility = if (text.isEmpty()) android.view.View.GONE else android.view.View.VISIBLE }
private fun fail(stage: String, detail: String) {
log("failed at $stage: $detail")
if (closed) return
if (connectedOnce) showNotice("The connection to the cloud console was lost",
"The stream stopped reaching this device ($detail). Restart the stream to play again: the game starts over, " +
"unsaved progress is lost.", webPlayer = false)
else showNotice("The native stream could not start ($stage)",
"$detail\n\nYou can try again, or use the web player instead (Stores › Xbox › Cloud settings › Player engine).",
webPlayer = true)
}
/** One popup at a time, in the app's dialog style; A or Enter picks the selected button, Back closes the player. */
private fun showNotice(title: String, text: String, webPlayer: Boolean) = runOnUiThread {
if (notice != null || isFinishing || isDestroyed) return@runOnUiThread
closeMenu()
show("")
// The stream is over: stale numbers must not stay on screen.
overlayOn = false
overlay.visibility = android.view.View.GONE
val view = androidx.compose.ui.platform.ComposeView(this)
view.setContent {
com.droiddeck.launcher.ui.DroidDeckTheme {
val first = androidx.compose.runtime.remember { androidx.compose.ui.focus.FocusRequester() }
androidx.compose.runtime.LaunchedEffect(Unit) { androidx.compose.runtime.withFrameNanos { }; runCatching { first.requestFocus() } }
@androidx.compose.runtime.Composable
fun NoticeButton(label: String, focus: androidx.compose.ui.focus.FocusRequester?, onClick: () -> Unit) =
androidx.compose.material3.TextButton(onClick = onClick,
modifier = androidx.compose.ui.Modifier.let { if (focus != null) it.focusRequester(focus) else it }
.onKeyEvent { e -> if (e.type == KeyEventType.KeyDown && e.key == Key.ButtonA) { onClick(); true } else false }) {
androidx.compose.material3.Text(label)
}
androidx.compose.material3.AlertDialog(
onDismissRequest = { finish() },
properties = androidx.compose.ui.window.DialogProperties(dismissOnClickOutside = false),
title = { androidx.compose.material3.Text(title) },
text = { androidx.compose.material3.Text(text) },
confirmButton = {
androidx.compose.foundation.layout.Row {
NoticeButton(if (connectedOnce) "Restart the stream" else "Try again", first) { restartStream() }
if (webPlayer) NoticeButton("Open the web player", null) {
startActivity(Intent(this@XboxNativePlayerActivity, XboxCloudPlayerActivity::class.java).putExtras(intent)); finish()
}
}
},
dismissButton = { NoticeButton("Close", null) { finish() } },
)
}
}
notice = view
root.addView(view, FrameLayout.LayoutParams(-1, -1))
}
// ---- background ----
override fun onStop() {
super.onStop()
if (closed || isChangingConfigurations || signalling == null || endedInBackground) return
// Android freezes a background app about a minute after it leaves the screen; the connection then dies
// without a goodbye. End the session cleanly before that and offer a restart on return.
log("in the background")
val end = Runnable { backgroundEnd = null; endInBackground() }
backgroundEnd = end
root.postDelayed(end, BACKGROUND_GRACE_MS)
}
override fun onStart() {
super.onStart()
backgroundEnd?.let { root.removeCallbacks(it); log("back before the stream was ended") }
backgroundEnd = null
if (endedInBackground && notice == null) showNotice("The stream ended while DroidDeck was in the background",
"Cloud sessions are closed after ${BACKGROUND_GRACE_MS / 1000} s away, before Android pauses the app. Restart the " +
"stream to play again: the game starts over, unsaved progress is lost.", webPlayer = false)
}
private fun endInBackground() {
if (closed || endedInBackground) return
endedInBackground = true
closed = true
log("ending the session: ${BACKGROUND_GRACE_MS / 1000} s in the background")
val signals = signalling
signalling = null
ticker.shutdownNow()
runOnUiThread { overlayOn = false; overlay.visibility = android.view.View.GONE }
Thread({ signals?.stop()?.let { log("session closed: ${it.status}") } }, "xcloud-native-stop").start()
runCatching { protocol?.close() }
runCatching { pc?.close() }
}
// ---- session ----
private fun run() {
val account = com.droiddeck.launcher.stores.StoreAccounts.signedInAs(applicationContext, com.droiddeck.launcher.stores.Store.XBOX)
?: error("Sign in to the Xbox store first.")
val requested = intent.getStringExtra("product").orEmpty()
val cached = XboxLibraryCache.read(applicationContext, account, Xodus.market())?.games?.firstOrNull { it.id == requested }
val product = cached?.extra?.get("cloudId")?.takeIf { it.isNotEmpty() } ?: requested
// The main process's tokens when it has them (no second ~20 s fetch); else this process fetches its own.
val shared = runCatching { XboxCloudSession.fromMainProcess(applicationContext, account) }
.onFailure { log("tokens from the main process: ${it.message?.take(160)}") }.getOrNull()
log(if (shared != null) "tokens from the main process" else "tokens fetched here")
val active = (shared ?: XboxCloudSession.get(applicationContext, account)).forStream(settings.region, settings.osName)
regionNames = active.regionList.map { it.name }
serverName = active.regionList.firstOrNull { it.baseUri == active.baseUri }?.name
val title = XboxCloudSession.titles(active)[product] ?: error("This game can't be streamed with this account here.")
val signals = XboxCloudSignalling(active, title, settings).also { signalling = it }
log("$product -> $title, region ${java.net.URI(active.baseUri).host}, frame gen ${settings.frameGen}")
show("Starting the game on Xbox Cloud Gaming…")
expect("start", signals.start())
var connected = false
var waited = 0
while (!closed) {
val state = JSONObject(expect("state", signals.op("state")).body.ifEmpty { "{}" })
when (state.optString("state")) {
"Provisioned" -> break
"Failed" -> error("provision: ${state.optJSONObject("errorDetails")}")
"ReadyToConnect" -> if (!connected) { connected = true; show("Signing in to the cloud console…"); expect("connect", signals.connect()) }
"WaitingForResources" -> show("In the queue for a cloud console… ${waited / 1000} s")
else -> show("Getting a cloud console ready… ${waited / 1000} s")
}
Thread.sleep(1000); waited += 1000
}
if (closed) return
show("Connecting…")
// Small network buffer: no playout delay, frames go to the decoder and screen as soon as they are complete.
val trials = if (settings.smallBuffer) "WebRTC-ForcePlayoutDelay/min_ms:0,max_ms:0/WebRTC-ZeroPlayoutDelay/min_pacing:0ms,max_decode_queue_size:8/" else ""
PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions.builder(applicationContext)
.setFieldTrials(trials).createInitializationOptions())
val egl = eglBase!!
val zeroSurface = if (zeroCopyWanted(settings)) {
repeat(40) { if (!surfaceView.holder.surface.isValid) Thread.sleep(50) }
surfaceView.holder.surface.takeIf { it.isValid }
} else null
if (zeroSurface != null) {
// The compositor may already hold the screen; it must let go before the decoder takes it.
val ready = CountDownLatch(1)
runOnUiThread { zeroCopy = true; video?.setSurface(null, 0, 0, 60f); ready.countDown() }
ready.await(2, TimeUnit.SECONDS)
}
log("latency: instant input ${settings.instantInput}, small buffer ${settings.smallBuffer}, fast decoder ${settings.fastDecoder}, " +
"zero-copy ${zeroSurface != null}")
val f = PeerConnectionFactory.builder()
.setAudioDeviceModule(JavaAudioDeviceModule.builder(applicationContext).createAudioDeviceModule())
.setVideoDecoderFactory(org.webrtc.DroidDeckLowLatencyDecoderFactory(egl.eglBaseContext, settings.fastDecoder, zeroSurface) { zeroCopyFrames++ }
.also { decoders = it })
.setVideoEncoderFactory(DefaultVideoEncoderFactory(egl.eglBaseContext, true, true))
.createPeerConnectionFactory().also { factory = it }
val config = PeerConnection.RTCConfiguration(emptyList()).apply { sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN }
val peer = f.createPeerConnection(config, observer) ?: error("WebRTC unavailable")
pc = peer
peer.addTransceiver(MediaStreamTrack.MediaType.MEDIA_TYPE_AUDIO, RtpTransceiver.RtpTransceiverInit(RtpTransceiver.RtpTransceiverDirection.SEND_RECV))
peer.addTransceiver(MediaStreamTrack.MediaType.MEDIA_TYPE_VIDEO, RtpTransceiver.RtpTransceiverInit(RtpTransceiver.RtpTransceiverDirection.RECV_ONLY))
protocol = XboxNativeProtocol(peer, pad, { log(it) }, ::rumble) { runOnUiThread { finish() } }
pad.onChanged = { if (settings.instantInput) protocol?.inputChanged() }
val offer = await<SessionDescription> { done -> peer.createOffer(sdpObserver(done), MediaConstraints()) }
val local = SessionDescription(offer.type, tweakOffer(offer.description))
await<Unit> { done -> peer.setLocalDescription(sdpObserver(done), local) }
val sdpReply = expect("sdp", signals.sdp(local.description))
val answer = JSONObject(JSONObject(sdpReply.body).getString("exchangeResponse"))
if (answer.has("status") && answer.optString("status") != "success") error("sdp answer: $answer")
await<Unit> { done -> peer.setRemoteDescription(sdpObserver(done), SessionDescription(SessionDescription.Type.ANSWER, answer.getString("sdp"))) }
gathered.await(3, TimeUnit.SECONDS)
val local2 = synchronized(candidates) { candidates.toList() }.map { c ->
JSONObject().put("candidate", c.sdp).put("sdpMid", c.sdpMid).put("sdpMLineIndex", c.sdpMLineIndex).put("usernameFragment", JSONObject.NULL).toString()
}
val iceReply = expect("ice", signals.ice(JSONArray(local2).toString()))
val remote = JSONArray(JSONObject(iceReply.body).getString("exchangeResponse"))
for (i in 0 until remote.length()) addRemoteCandidate(peer, remote.getJSONObject(i))
log("signalling done: ${local2.size} local / ${remote.length()} remote candidates")
ticker.scheduleWithFixedDelay({ runCatching { signals.op("keepalive") } }, 30, 30, TimeUnit.SECONDS)
ticker.scheduleWithFixedDelay({ runCatching { updateOverlay() } }, 1, 1, TimeUnit.SECONDS)
}
private fun expect(stage: String, reply: XboxCloudSession.Reply): XboxCloudSession.Reply {
if (reply.status !in 200..299) error("$stage: ${reply.status} ${reply.body.take(200)}")
return reply
}
/** Opus stereo (Greenlight), H.264 profile order (Main first unless the user picked one) and the bitrate cap. */
private fun tweakOffer(sdp: String): String {
var out = sdp.replace("useinbandfec=1", "useinbandfec=1; stereo=1")
val prefix = when (settings.codec) { "low" -> "420"; "normal" -> "42e"; else -> "4d" }
val ids = Regex("a=fmtp:(\\d+).*profile-level-id=([0-9a-f]{6})").findAll(out).filter { it.groupValues[2].startsWith(prefix) }.map { it.groupValues[1] }.toList()
if (ids.isNotEmpty()) out = out.split("\r\n").joinToString("\r\n") { line ->
if (!line.startsWith("m=video")) line else {
val parts = line.trim().split(" ")
(parts.take(3) + ids + parts.drop(3).filter { it !in ids }).joinToString(" ")
}
}
if (settings.bitrateMbps > 0) {
val lines = out.split("\r\n").toMutableList()
val start = lines.indexOfFirst { it.startsWith("m=video") }
if (start >= 0) {
var i = start + 1
while (i < lines.size && (lines[i].startsWith("i=") || lines[i].startsWith("c="))) i++
if (i < lines.size && lines[i].startsWith("b=AS:")) lines[i] = "b=AS:${settings.bitrateMbps * 1000}" else lines.add(i, "b=AS:${settings.bitrateMbps * 1000}")
out = lines.joinToString("\r\n")
}
}
return out
}
/** The server's candidates, plus the IPv4 behind a Teredo address (Greenlight's ice.ts / teredo.ts). */
private fun addRemoteCandidate(peer: PeerConnection, c: JSONObject) {
val line = c.optString("candidate").removePrefix("a=")
if (line.isEmpty() || line == "end-of-candidates") return
val mid = c.optString("sdpMid", "0"); val index = c.optString("sdpMLineIndex", "0").toIntOrNull() ?: 0
val address = line.split(" ").getOrNull(4).orEmpty()
if (address.startsWith("2001")) runCatching {
val p = address.split(":")
val hex = p[6].padStart(4, '0') + p[7].padStart(4, '0')
val ip = (0 until 4).joinToString(".") { k -> ((hex.substring(k * 2, k * 2 + 2).toInt(16)).inv() and 0xFF).toString() }
val port = p[5].toInt(16).inv() and 0xFFFF
peer.addIceCandidate(IceCandidate(mid, index, "candidate:10 1 UDP 1 $ip 9002 typ host "))
peer.addIceCandidate(IceCandidate(mid, index, "candidate:11 1 UDP 1 $ip $port typ host "))
}
peer.addIceCandidate(IceCandidate(mid, index, line))
}
private val observer = object : PeerConnection.Observer {
override fun onSignalingChange(state: PeerConnection.SignalingState) {}
override fun onIceConnectionChange(state: PeerConnection.IceConnectionState) { log("ice $state") }
override fun onIceConnectionReceivingChange(receiving: Boolean) {}
override fun onIceGatheringChange(state: PeerConnection.IceGatheringState) { if (state == PeerConnection.IceGatheringState.COMPLETE) gathered.countDown() }
override fun onIceCandidate(candidate: IceCandidate) { synchronized(candidates) { candidates.add(candidate) } }
override fun onIceCandidatesRemoved(removed: Array<out IceCandidate>) {}
override fun onAddStream(stream: MediaStream) {}
override fun onRemoveStream(stream: MediaStream) {}
override fun onDataChannel(channel: DataChannel) {}
override fun onRenegotiationNeeded() {}
override fun onAddTrack(receiver: RtpReceiver, streams: Array<out MediaStream>) { attach(receiver) }
override fun onTrack(transceiver: RtpTransceiver) { attach(transceiver.receiver) }
override fun onConnectionChange(state: PeerConnection.PeerConnectionState) {
log("connection $state")
when (state) {
PeerConnection.PeerConnectionState.CONNECTED -> {
connectedOnce = true
show("")
video?.setFpsTarget(settings.fpsTarget)
video?.setFrameGeneration(effectiveFrameGen())
}
PeerConnection.PeerConnectionState.FAILED -> fail("webrtc", "connection failed")
PeerConnection.PeerConnectionState.DISCONNECTED -> show("Connection lost…")
else -> {}
}
}
}
private var videoAttached = false
private fun attach(receiver: RtpReceiver) = synchronized(this) {
val track = receiver.track()
// Always attached: in zero-copy WebRTC delivers no frames, and after a live switch back they flow again.
if (track is VideoTrack && !videoAttached) { videoAttached = true; video?.let { track.addSink(it) }; log("video track") }
}
/** LSFG needs the Lossless.dll and its shader cache built; otherwise DDFG. */
private fun effectiveFrameGen(): String {
if (!XboxNativeVideo.isLsfg(settings.frameGen)) return settings.frameGen
val status = com.droiddeck.launcher.gpu.Lossless.sync(applicationContext)
if (status == 0) return settings.frameGen
log("LSFG unavailable (status $status), using DDFG")
return XboxNativeVideo.FG_DDFG
}
private fun <T> await(start: (done: (Result<T>) -> Unit) -> Unit): T {
val latch = CountDownLatch(1)
var result: Result<T>? = null
start { r -> result = r; latch.countDown() }
check(latch.await(15, TimeUnit.SECONDS)) { "WebRTC timed out" }
return result!!.getOrThrow()
}
@Suppress("UNCHECKED_CAST")
private fun <T> sdpObserver(done: (Result<T>) -> Unit) = object : SdpObserver {
override fun onCreateSuccess(description: SessionDescription) = done(Result.success(description as T))
override fun onSetSuccess() = done(Result.success(Unit as T))
override fun onCreateFailure(error: String) = done(Result.failure(IllegalStateException(error)))
override fun onSetFailure(error: String) = done(Result.failure(IllegalStateException(error)))
}
// ---- input, rumble, overlay ----
private var guideDown = false
private var guideDownAt = 0L
private var lastGuideUp = 0L
private var pendingNexus: Runnable? = null
private fun isGuide(event: KeyEvent) = event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE
private fun pressNexus() {
pad.overrideButtons = pad.overrideButtons or 2
root.postDelayed({ pad.overrideButtons = pad.overrideButtons and 2.inv() }, 200)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (menu != null) {
// Guide closes the menu; Back goes up one page, then closes it.
if (isGuide(event)) { if (event.action == KeyEvent.ACTION_UP) { if (swallowGuideUp) swallowGuideUp = false else closeMenu() }; return true }
if (event.keyCode == KeyEvent.KEYCODE_BACK) {
if (event.action == KeyEvent.ACTION_UP) { if (menuPage.isNotEmpty()) menuPage = "" else closeMenu() }
return true
}
return super.dispatchKeyEvent(event)
}
// Guide / the Input Controls menu button: once = the Xbox button, twice or held = the player menu.
if (isGuide(event)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
val pending = pendingNexus
if (pending != null && event.eventTime - lastGuideUp <= 350) { root.removeCallbacks(pending); pendingNexus = null; swallowGuideUp = true; openMenu() }
else { guideDown = true; guideDownAt = event.eventTime }
} else if (event.action == KeyEvent.ACTION_DOWN && guideDown && event.eventTime - guideDownAt >= 600) {
guideDown = false; swallowGuideUp = true; openMenu()
} else if (event.action == KeyEvent.ACTION_UP && guideDown) {
guideDown = false; lastGuideUp = event.eventTime
val tap = Runnable { pendingNexus = null; pressNexus() }
pendingNexus = tap; root.postDelayed(tap, 350)
}
return true
}
if (event.keyCode == KeyEvent.KEYCODE_BACK) { if (event.action == KeyEvent.ACTION_UP) openMenu(); return true }
if (pad.onKey(event)) return true
return super.dispatchKeyEvent(event)
}
// With the menu open, sticks and the hat go to Android unhandled, which turns them into D-pad keys for the menu.
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean =
(menu == null && pad.onMotion(event)) || super.dispatchGenericMotionEvent(event)
private fun rumble(strong: Float, weak: Float, durationMs: Int) {
val scale = settings.rumble / 100f
val amplitude = (maxOf(strong, weak) * scale * 255).toInt().coerceIn(0, 255)
if (amplitude == 0 || durationMs <= 0) return
val vibrator = (if (Build.VERSION.SDK_INT >= 31) getSystemService(android.os.VibratorManager::class.java)?.defaultVibrator
else @Suppress("DEPRECATION") getSystemService(android.os.Vibrator::class.java)) ?: return
runCatching { vibrator.vibrate(VibrationEffect.createOneShot(durationMs.coerceAtMost(1000).toLong(), amplitude)) }
}
/** The overlay is remembered with the other cloud settings (on = overlay level above 0). */
@Volatile private var overlayOn = false
private var lastJitterDelay = 0.0
private var lastJitterCount = 0.0
private var lastDecodeTime = 0.0
private var lastDecoded = 0.0
private var lastBytes = 0.0
private var lastStatsMs = 0.0
private var lastLost = 0.0
private var lastReceived = 0.0
/**
* The overlay, at the web player's levels and layout (settings statsLevel / statsLayout): 1 fps and frame
* generation base -> shown; 2 + resolution, ping; 3 + bitrate, jitter buffer, decode time, packet loss; 4 + frame
* generation's added delay, the estimated picture delay (one-way network + buffer + decode + frame generation +
* one screen refresh), codec and server.
*/
private fun updateOverlay() {
val level = settings.statsLevel
if (!overlayOn || level <= 0) return
val peer = pc ?: return
peer.getStats { report ->
var size = ""; var fps = 0; var codec = ""
var rttMs = -1.0; var bufferMs = 0.0; var decodeMs = 0.0; var mbps = 0.0; var loss = 0.0
val codecs = HashMap<String, String>()
report.statsMap.values.forEach { s -> if (s.type == "codec") codecs[s.id] = (s.members["mimeType"] as? String).orEmpty().removePrefix("video/") }
report.statsMap.values.forEach { s ->
val m = s.members
if (s.type == "inbound-rtp" && m["kind"] == "video") {
size = "${m["frameWidth"]}x${m["frameHeight"]}"
fps = (m["framesPerSecond"] as? Number)?.toInt() ?: 0
codec = codecs[m["codecId"] as? String].orEmpty()
val jd = (m["jitterBufferDelay"] as? Number)?.toDouble() ?: 0.0
val jc = (m["jitterBufferEmittedCount"] as? Number)?.toDouble() ?: 0.0
if (jc > lastJitterCount) bufferMs = (jd - lastJitterDelay) * 1000 / (jc - lastJitterCount)
lastJitterDelay = jd; lastJitterCount = jc
val dt = (m["totalDecodeTime"] as? Number)?.toDouble() ?: 0.0
val df = (m["framesDecoded"] as? Number)?.toDouble() ?: 0.0
if (df > lastDecoded) decodeMs = (dt - lastDecodeTime) * 1000 / (df - lastDecoded)
lastDecodeTime = dt; lastDecoded = df
val bytes = (m["bytesReceived"] as? Number)?.toDouble() ?: 0.0
val now = s.timestampUs / 1000.0
if (lastStatsMs > 0 && now > lastStatsMs) mbps = (bytes - lastBytes) * 8 / ((now - lastStatsMs) * 1000)
lastBytes = bytes; lastStatsMs = now
val lost = (m["packetsLost"] as? Number)?.toDouble() ?: 0.0
val received = (m["packetsReceived"] as? Number)?.toDouble() ?: 0.0
val dl = lost - lastLost; val dr = received - lastReceived
if (dl + dr > 0) loss = dl * 100 / (dl + dr)
lastLost = lost; lastReceived = received
} else if (s.type == "candidate-pair" && m["state"] == "succeeded" && m["nominated"] == true) {
(m["currentRoundTripTime"] as? Number)?.toDouble()?.let { rttMs = it * 1000 }
}
}
// Zero-copy: WebRTC never sees a decoded frame, so size and decode time come from the decoder itself.
if (zeroCopy) decoders?.let { d ->
d.videoSize()?.let { size = it }
val ms = d.takeDecodeMs()
if (ms >= 0) decodeMs = ms
}
val fg = video?.stats()
val fgOn = fg != null && settings.frameGen != XboxNativeVideo.FG_OFF && fg[2] > 1f
val fgWaitMs = if (fgOn) 1000.0 / fg!![2] else 0.0
val fgGpuMs = if (fgOn && fg!![5] > 0f) fg[5].toDouble() else 0.0
@Suppress("DEPRECATION") val refreshMs = 1000.0 / windowManager.defaultDisplay.refreshRate
val total = (if (rttMs >= 0) rttMs / 2 else 0.0) + bufferMs + decodeMs + fgWaitMs + fgGpuMs + refreshMs
// What reaches the screen: the decoder's own count in zero-copy, the presented rate with frame generation,
// else the frames handed to the compositor (a frame-rate target drops some of WebRTC's decoded frames).
val submitted = video?.frames ?: 0L
val handed = (submitted - lastSubmitted).toInt().also { lastSubmitted = submitted }
val shownFps = when {
zeroCopy -> (zeroCopyFrames - lastZeroCopyFrames).toInt().also { lastZeroCopyFrames = zeroCopyFrames }
fgOn -> fg!![3].toInt()
else -> handed
}
val items = buildList {
add("native · " + if (settings.frameGen == XboxNativeVideo.FG_OFF) "no frame gen" else XboxNativeVideo.modeName(settings.frameGen))
add("$shownFps fps" + if (zeroCopy) " zero-copy" else "")
if (fgOn) add("${settings.frameGen} ${fg!![2].toInt()} → ${fg[3].toInt()}")
if (level >= 2) { add(size); add(if (rttMs >= 0) "ping ${rttMs.toInt()} ms" else "ping –") }
if (level >= 3) {
add("${"%.1f".format(mbps)} Mb/s"); add("buffer ${"%.1f".format(bufferMs)} ms")
add("decode ${"%.1f".format(decodeMs)} ms"); add("loss ${"%.1f".format(loss)}%")
}
if (level >= 4) {
if (fgOn) add("frame gen +${"%.1f".format(fgWaitMs + fgGpuMs)} ms (gpu ${"%.1f".format(fgGpuMs)})")
add("picture delay ≈ ${total.toInt()} ms (est.)")
if (codec.isNotEmpty()) add(codec)
serverName?.let { add(it) }
}
}
val text = items.joinToString(if (settings.statsLayout == "vertical") "\n" else " · ")
runOnUiThread { overlay.text = text }
}
}
// ---- menu ----
/** The player menu (as the web player's): Resume, Xbox menu, Frame generation, Stream quality, overlay, Leave. */
private fun openMenu() {
if (menu != null) return
pad.reset()
menuPage = ""
val regions = regionNames
val lsfg = XboxNativeVideo.lsfgReady(this)
val view = androidx.compose.ui.platform.ComposeView(this)
view.setContent {
com.droiddeck.launcher.ui.DroidDeckTheme {
var current by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(settings) }
val entries = androidx.compose.runtime.remember { List(7) { androidx.compose.ui.focus.FocusRequester() } }
val choices = androidx.compose.runtime.remember { List(5) { androidx.compose.ui.focus.FocusRequester() } }
androidx.compose.runtime.LaunchedEffect(menuPage) {
// Wait a frame so the entries are attached before one of them takes the selection.
androidx.compose.runtime.withFrameNanos { }
runCatching {
if (menuPage.isEmpty()) entries[lastMainEntry.coerceIn(0, 6)].requestFocus()
else if (menuPage == "framegen") choices[FG_MODES.indexOf(current.frameGen).coerceIn(0, if (lsfg) 4 else 1)].requestFocus()
}
}
val cs = androidx.compose.material3.MaterialTheme.colorScheme
// A full-size box first: the root of a ComposeView gets fixed full-screen constraints, so the panel's
// width only holds inside it (as the web player's menu does).
androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.fillMaxSize()) {
androidx.compose.foundation.layout.Column(
androidx.compose.ui.Modifier.fillMaxHeight().width(400.dp).background(cs.surface.copy(alpha = 0.95f))
.verticalScroll(androidx.compose.foundation.rememberScrollState()).padding(vertical = 12.dp),
) {
androidx.compose.material3.Text("${intent.getStringExtra("title").orEmpty()} · native",
style = androidx.compose.material3.MaterialTheme.typography.titleMedium, color = cs.onSurface,
modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 4.dp))
fun fgName(mode: String) = when (mode) {
XboxNativeVideo.FG_DDFG -> "DDFG 2×"; XboxNativeVideo.FG_LSFG -> "LSFG 2×"
XboxNativeVideo.FG_LSFG3 -> "LSFG 3×"; XboxNativeVideo.FG_LSFG4 -> "LSFG 4×"; else -> "Off"
}
fun fpsName(s: XboxCloudSettings) = if (s.fpsTarget == 0) "the screen's rate" else "${s.fpsTarget} fps"
when (menuPage) {
"" -> {
XboxMenuEntry("Resume", "Back to the game", entries[0], { lastMainEntry = 0 }) { closeMenu() }
XboxMenuEntry("Xbox menu", "The game's Xbox menu (also: Guide once)", entries[1], { lastMainEntry = 1 }) { closeMenu(); pressNexus() }
XboxMenuEntry("Frame generation & low latency", "Now: ${fgName(current.frameGen)}" + if (zeroCopy) " · zero-copy" else "",
entries[2], { lastMainEntry = 2 }) { menuPage = "framegen" }
XboxMenuEntry("Frame rate", "Target: ${fpsName(current)}", entries[3], { lastMainEntry = 3 }) { menuPage = "framerate" }
XboxMenuEntry("Stream quality", "Engine, resolution, region, codec, bitrate (next stream)", entries[4], { lastMainEntry = 4 }) { menuPage = "stream" }
XboxMenuEntry("Performance overlay and rumble", if (current.statsLevel == 0) "Overlay off"
else "Overlay: " + listOf("", "FPS only", "Basic", "Detailed", "Full")[current.statsLevel] + ", " + current.statsLayout,
entries[5], { lastMainEntry = 5 }) { menuPage = "overlay-native" }
XboxMenuEntry("Leave", "End the stream", entries[6], { lastMainEntry = 6 }) { finish() }
androidx.compose.material3.Text("Guide twice opens this menu; Back or Guide closes it.",
style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = cs.onSurfaceVariant,
modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
}
"framegen" -> {
XboxMenuEntry("‹ Back", null) { menuPage = "" }
val modes = if (lsfg) FG_MODES else FG_MODES.take(2)
modes.forEachIndexed { i, mode ->
XboxMenuEntry((if (current.frameGen == mode) "✓ " else "") + fgName(mode), when (mode) {
XboxNativeVideo.FG_DDFG -> "DroidDeck's own frame generation (DDFG); doubles the shown frame rate"
XboxNativeVideo.FG_LSFG, XboxNativeVideo.FG_LSFG3, XboxNativeVideo.FG_LSFG4 ->
"Lossless Scaling frame generation (the Lossless.dll DroidDeck uses for games); the frame-rate target caps the output"
else -> "Show the stream's own frames only"
}, choices[i]) { current = current.copy(frameGen = mode); setFrameGen(mode) }
}
if (!lsfg) androidx.compose.material3.Text("LSFG appears here once DroidDeck has the Lossless.dll (frame generation settings).",
style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = cs.onSurfaceVariant,
modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
if (current.zeroCopy) androidx.compose.material3.Text(
"Zero-copy is used while frame generation is Off; picking a frame generation mode switches to the compositor live.",
style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = cs.onSurfaceVariant,
modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
XboxCloudSettingsPanel(current, regionNames, live = true, section = "latency", restoreRow = null,
startedWith = startedWith) { changed ->
val before = current
current = changed
applyLive(before, changed)
}
XboxMenuEntry("Restart the stream with these settings",
"Ends this cloud session and starts a new one; the game restarts, unsaved progress is lost.") { restartStream() }
}
else -> {
XboxMenuEntry("‹ Back", null) { menuPage = "" }
if (menuPage == "stream") XboxMenuEntry("Restart the stream with these settings",
"Ends this cloud session and starts a new one; the game restarts, unsaved progress is lost.") { restartStream() }
val page = menuPage
XboxCloudSettingsPanel(current, regions, live = true, section = page, restoreRow = lastRow[page] ?: 0,
onRowFocused = { lastRow[page] = it }, startedWith = startedWith) { changed ->
val before = current
current = changed
applyLive(before, changed)
}
}
}
}
}
}
}
menu = view
root.addView(view, FrameLayout.LayoutParams(-1, -1))
view.requestFocus()
}
/**
* Applies a settings change from any menu page at once: frame generation, the frame-rate target, zero-copy, instant
* input and the overlay. Resolution, region, language, codec, bitrate, the network buffer, the decoder mode and the
* engine belong to the cloud session and need a restart (the page says so).
*/
private fun applyLive(before: XboxCloudSettings, changed: XboxCloudSettings) {
settings = changed
XboxCloudSettings.save(this, changed)
if (changed.frameGen != before.frameGen) setFrameGen(changed.frameGen)
else if (changed.zeroCopy != before.zeroCopy) applyRoute()
if (changed.fpsTarget != before.fpsTarget) { applyDisplayRate(changed.fpsTarget); video?.setFpsTarget(changed.fpsTarget); applyRoute() }
applyOverlay()
}
/**
* Zero-copy draws every decoded frame straight onto the screen, so it is used only when nothing has to touch the
* frames: frame generation off and no frame-rate target below the stream's 60 fps (the compositor drops frames for that).
*/
private fun zeroCopyWanted(s: XboxCloudSettings) =
s.zeroCopy && s.frameGen == XboxNativeVideo.FG_OFF && (s.fpsTarget == 0 || s.fpsTarget >= 60)
private fun applyOverlay() {
overlayOn = settings.statsLevel > 0
overlay.visibility = if (overlayOn) android.view.View.VISIBLE else android.view.View.GONE
overlay.textSize = 12f
// Top left keeps clear of the clock Xbox draws top right while its guide is open.
val left = settings.statsCorner == "left"
overlay.layoutParams = (overlay.layoutParams as FrameLayout.LayoutParams).apply {
gravity = Gravity.TOP or (if (left) Gravity.START else Gravity.END)
leftMargin = if (left) 16 else 0; rightMargin = if (left) 0 else 16
}
overlay.gravity = if (left) Gravity.START else Gravity.END
}
/** Stream-start settings need a new cloud session: end this one, then open the player again. */
private fun restartStream() {
val signals = signalling
closed = true
closeMenu()
notice?.let { root.removeView(it) }
notice = null
show("Restarting the stream…")
Thread({
signals?.stop()?.let { log("restart: session closed ${it.status}") }
runOnUiThread { if (!isFinishing) { startActivity(XboxCloudPlayerActivity.playerIntent(this, intent.getStringExtra("product").orEmpty(), intent.getStringExtra("title").orEmpty())); finish() } }
}, "xcloud-native-restart").start()
}
private fun closeMenu() {
menu?.let { root.removeView(it) }
menu = null
pad.reset()
}
private fun setFrameGen(mode: String) {
settings = settings.copy(frameGen = mode)
XboxCloudSettings.save(this, settings)
applyRoute()
worker.execute { video?.setFrameGeneration(effectiveFrameGen()) }
}
/**
* Live route switch (UI thread): zero-copy when chosen and frame generation is off, else the compositor.
* The screen surface takes one producer at a time, so the old one lets go before the new one connects.
*/
private fun applyRoute() {
val d = decoders ?: return
val want = zeroCopyWanted(settings)
if (want == zeroCopy) return
val target = screen
if (want) {
if (target == null) return
video?.setSurface(null, 0, 0, 60f)
if (d.useScreen(target)) { lastZeroCopyFrames = zeroCopyFrames; zeroCopy = true; log("route: zero-copy") }
else { attachCompositor(target); log("route: zero-copy refused by the decoder, compositor kept") }
} else {
if (!d.useScreen(null)) { log("route: decoder could not leave the screen, zero-copy kept"); return }
zeroCopy = false
target?.let { attachCompositor(it) }
log("route: compositor")
}
}
private fun attachCompositor(target: android.view.Surface) {
@Suppress("DEPRECATION")
video?.setSurface(target, screenW, screenH, windowManager.defaultDisplay.refreshRate)
}
/**
* Ask Android for the display mode whose refresh rate fits the target (at least the target when possible,
* else the fastest; the fastest for "the screen's rate"), so generated frames are not held back at 60 Hz.
*/
private fun applyDisplayRate(target: Int) {
@Suppress("DEPRECATION") val display = windowManager.defaultDisplay
val current = display.mode
val modes = display.supportedModes.filter { it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight }
val pick = (if (target > 0) modes.filter { it.refreshRate >= target - 0.5f }.minByOrNull { it.refreshRate } else null)
?: modes.maxByOrNull { it.refreshRate } ?: return
window.attributes = window.attributes.apply { preferredDisplayModeId = pick.modeId }
log("display mode ${pick.refreshRate.toInt()} Hz for target ${if (target > 0) target else "screen"}")
}
private val rehideBars = Runnable { if (window.decorView.hasWindowFocus()) hideBars() }
/**
* Bars that come back while the player has focus (return from recents or another app, a swipe) are hidden
* again after a moment; focus alone missed the return from the background (10-24).
*/
private fun watchBars() {
androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener(window.decorView) { v, insets ->
if (insets.isVisible(WindowInsetsCompat.Type.navigationBars()) || insets.isVisible(WindowInsetsCompat.Type.statusBars())) {
v.removeCallbacks(rehideBars)
v.postDelayed(rehideBars, 1500)
}
androidx.core.view.ViewCompat.onApplyWindowInsets(v, insets)
}
}
override fun onResume() {
super.onResume()
hideBars()
}
private fun hideBars() {
WindowCompat.setDecorFitsSystemWindows(window, false)
WindowInsetsControllerCompat(window, window.decorView).apply {
hide(WindowInsetsCompat.Type.systemBars())
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus); if (hasFocus) hideBars() }
override fun onDestroy() {
closed = true
ticker.shutdownNow()
val signals = signalling
Thread({ signals?.stop()?.let { log("session closed: ${it.status}") } }, "xcloud-native-stop").start()
runCatching { protocol?.close() }
runCatching { pc?.close(); pc?.dispose() }
runCatching { video?.release() }
runCatching { factory?.dispose() }
runCatching { decoders?.release() }
runCatching { eglBase?.release() }
worker.shutdownNow()
super.onDestroy()
}
companion object {
/** How long a stream may stay in the background (Android froze the app ~70 s after it left the screen, 10-24). */
private const val BACKGROUND_GRACE_MS = 45_000L
private val FG_MODES = listOf(XboxNativeVideo.FG_OFF, XboxNativeVideo.FG_DDFG, XboxNativeVideo.FG_LSFG, XboxNativeVideo.FG_LSFG3, XboxNativeVideo.FG_LSFG4)
/** True when the native engine can run here (ImageReader GPU buffers need Android 10). */
fun supported(): Boolean = Build.VERSION.SDK_INT >= 29
}
}
@@ -0,0 +1,186 @@
package com.droiddeck.launcher.stores.xbox
import org.json.JSONObject
import org.webrtc.DataChannel
import org.webrtc.PeerConnection
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.charset.StandardCharsets
import java.util.UUID
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
/**
* The xCloud data-channel protocol for the native player, ported from Greenlight's player (UnknownSKL, MIT;
* tools/xcloud-player/greenlight/lib/channel): chat / control / input / message channels, the message
* handshake, authorization and gamepad announcements, and the binary input reports. The controller state
* comes from Android input events ([pad]); rumble reports come back through [onRumble].
*/
internal class XboxNativeProtocol(
pc: PeerConnection,
private val pad: XboxNativePad,
private val log: (String) -> Unit,
private val onRumble: (strong: Float, weak: Float, durationMs: Int) -> Unit,
private val onServerDisconnect: () -> Unit,
) {
private val chat = pc.createDataChannel("chat", init("chatV1"))
private val control = pc.createDataChannel("control", init("controlV1"))
private val input = pc.createDataChannel("input", init("1.0"))
private val message = pc.createDataChannel("message", init("messageV1"))
private val timer = Executors.newSingleThreadScheduledExecutor { r -> Thread(r, "xcloud-input") }
private var loop: ScheduledFuture<*>? = null
private var sequence = 0
private var lastSent: XboxNativePad.State? = null
private var lastSentAt = 0L
@Volatile var handshakeDone = false
private set
init {
message.registerObserver(ChannelObserver(message, ::onMessageOpen, ::onMessageData))
control.registerObserver(ChannelObserver(control, {}, {}))
input.registerObserver(ChannelObserver(input, {}, ::onInputData))
chat.registerObserver(ChannelObserver(chat, {}, {}))
}
private fun init(protocol: String) = DataChannel.Init().apply { ordered = true; this.protocol = protocol }
private inner class ChannelObserver(
private val channel: DataChannel,
private val onOpen: () -> Unit,
private val onData: (DataChannel.Buffer) -> Unit,
) : DataChannel.Observer {
private var opened = false
override fun onBufferedAmountChange(previous: Long) {}
override fun onStateChange() {
if (!opened && channel.state() == DataChannel.State.OPEN) { opened = true; runCatching(onOpen).onFailure { log("channel open failed: ${it.message}") } }
}
override fun onMessage(buffer: DataChannel.Buffer) { runCatching { onData(buffer) }.onFailure { log("channel message failed: ${it.message}") } }
}
private fun send(channel: DataChannel, text: String) {
if (channel.state() != DataChannel.State.OPEN) return
channel.send(DataChannel.Buffer(ByteBuffer.wrap(text.toByteArray(StandardCharsets.UTF_8)), false))
}
private fun send(channel: DataChannel, bytes: ByteBuffer) {
if (channel.state() != DataChannel.State.OPEN) return
channel.send(DataChannel.Buffer(bytes, true))
}
private fun onMessageOpen() {
log("message channel open, handshake")
send(message, JSONObject().put("type", "Handshake").put("version", "messageV1")
.put("id", "be0bfc6d-1e83-4c8a-90ed-fa8601c5a179").put("cv", "0").toString())
}
private fun onMessageData(buffer: DataChannel.Buffer) {
val bytes = ByteArray(buffer.data.remaining()).also { buffer.data.get(it) }
val data = JSONObject(String(bytes, StandardCharsets.UTF_8))
when (data.optString("type")) {
"HandshakeAck" -> {
handshakeDone = true
log("handshake done")
// Greenlight's order: authorization (announces controller 0 and removes it), input start, config.
send(control, JSONObject().put("message", "authorizationRequest").put("accessKey", "4BDB3609-C1F1-4195-9B37-FEFF45DA8B8E").toString())
gamepadChanged(0, true); gamepadChanged(0, false)
startInput()
sendConfig()
// Our controller, after the authorization's add/remove.
gamepadChanged(0, true)
send(control, JSONObject().put("message", "videoKeyframeRequested").put("ifrRequested", true).toString())
}
"TransactionStart", "Message" -> handleTransaction(data)
else -> {}
}
}
private fun handleTransaction(data: JSONObject) {
when (data.optString("target")) {
"/streaming/sessionLifetimeManagement/serverInitiatedDisconnect" -> {
complete(data.optString("id"), "")
onServerDisconnect()
}
// The game's own dialogs: accept (Greenlight shows a confirm; the native player has no page).
"/streaming/systemUi/messages/ShowMessageDialog" -> complete(data.optString("id"), JSONObject().put("Result", 0))
else -> {}
}
}
private fun complete(id: String, content: Any) {
send(message, JSONObject().put("type", "TransactionComplete").put("content", content.toString().let { if (content is String) JSONObject.quote(it) else it })
.put("id", id).put("cv", "").toString())
}
private fun gamepadChanged(index: Int, added: Boolean) {
send(control, JSONObject().put("message", "gamepadChanged").put("gamepadIndex", index).put("wasAdded", added).toString())
}
private fun sendConfig() {
fun msg(path: String, content: JSONObject) = JSONObject().put("type", "Message").put("content", content.toString())
.put("id", UUID.randomUUID().toString()).put("target", path).put("cv", "").toString()
send(message, msg("/streaming/systemUi/configuration", JSONObject().put("version", org.json.JSONArray(listOf(0, 2, 0))).put("systemUis", org.json.JSONArray())))
send(message, msg("/streaming/properties/clientappinstallidchanged", JSONObject().put("clientAppInstallId", "c97d7ee0-73b2-4239-bf1d-9d805a338429")))
send(message, msg("/streaming/characteristics/orientationchanged", JSONObject().put("orientation", 0)))
send(message, msg("/streaming/characteristics/touchinputenabledchanged", JSONObject().put("touchInputEnabled", false)))
send(message, msg("/streaming/characteristics/clientdevicecapabilities", JSONObject()))
send(message, msg("/streaming/characteristics/dimensionschanged", JSONObject().put("horizontal", 1920).put("vertical", 1080)
.put("preferredWidth", 1920).put("preferredHeight", 1080).put("safeAreaLeft", 0).put("safeAreaTop", 0)
.put("safeAreaRight", 1920).put("safeAreaBottom", 1080).put("supportsCustomResolution", true)))
}
private fun header(type: Int, size: Int): ByteBuffer = ByteBuffer.allocateDirect(size).order(ByteOrder.LITTLE_ENDIAN).apply {
putShort(type.toShort()); putInt(sequence++); putDouble(System.nanoTime() / 1e6)
}
private fun startInput() {
// Client metadata: max touch points.
send(input, header(8, 15).apply { put(1.toByte()); flip() })
loop = timer.scheduleWithFixedDelay({ runCatching { tick() } }, 16, 16, TimeUnit.MILLISECONDS)
}
/** Instant controller input: send a report now if the state changed (the 16 ms loop stays as the heartbeat). */
fun inputChanged() {
// At most one extra report every 4 ms (stick motion arrives far faster than that).
if (handshakeDone && loop != null && System.nanoTime() - lastSentAt > 4_000_000L) timer.execute { runCatching { tick() } }
}
/** Greenlight's queue: a gamepad frame when the state changed (sticks past a small threshold) or every 33 ms. */
@Synchronized
private fun tick() {
val state = pad.snapshot()
val now = System.nanoTime()
val changed = lastSent?.let { state.differsFrom(it) } ?: true
if (!changed && now - lastSentAt < 33_000_000L) return
lastSent = state; lastSentAt = now
val packet = header(2, 14 + 1 + 23).apply {
put(1.toByte()) // one frame
put(0.toByte()) // gamepad index
putShort(state.buttons.toShort())
putShort(axis(state.lx)); putShort(axis(-state.ly)); putShort(axis(state.rx)); putShort(axis(-state.ry))
putShort(trigger(state.lt)); putShort(trigger(state.rt))
putInt(1) // physical physicality
order(ByteOrder.BIG_ENDIAN); putInt(1); order(ByteOrder.LITTLE_ENDIAN) // virtual physicality (Greenlight writes it big-endian)
flip()
}
send(input, packet)
}
private fun axis(value: Float): Short = (value * 32767).toInt().coerceIn(-32767, 32767).toShort()
private fun trigger(value: Float): Short = if (value <= 0f) 0 else if (value >= 1f) 65535.toShort() else (value * 65535).toInt().toShort()
private fun onInputData(buffer: DataChannel.Buffer) {
val data = buffer.data.order(ByteOrder.LITTLE_ENDIAN)
if (data.remaining() < 13 || (data.get(0).toInt() and 0xFF) != 128) return // vibration report
val strong = (data.get(4).toInt() and 0xFF) / 100f
val weak = (data.get(5).toInt() and 0xFF) / 100f
val duration = data.getShort(8).toInt() and 0xFFFF
onRumble(strong, weak, duration)
}
fun close() {
loop?.cancel(false)
timer.shutdownNow()
listOf(chat, control, input, message).forEach { runCatching { it.unregisterObserver(); it.close(); it.dispose() } }
}
}
@@ -0,0 +1,183 @@
package com.droiddeck.launcher.stores.xbox
import android.content.Context
import android.graphics.PixelFormat
import android.hardware.HardwareBuffer
import android.media.Image
import android.media.ImageReader
import android.os.Handler
import android.os.HandlerThread
import android.view.Surface
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
import org.webrtc.EglBase
import org.webrtc.EglRenderer
import org.webrtc.GlRectDrawer
import org.webrtc.VideoFrame
import org.webrtc.VideoSink
import java.io.File
import java.util.ArrayDeque
/**
* The native player's picture: WebRTC's hardware-decoded frames are drawn (GL, WebRTC's EglRenderer) into an
* ImageReader whose images are GPU-shareable HardwareBuffers, and each one goes to DroidDeck's own compositor in
* stream mode (WaylandCompositor.nativeStreamFrame) as the whole scene, where DroidDeck's frame generation (DDFG,
* or LSFG with the Lossless.dll) multiplies it. The player runs in its own process (:xcloudnative), so this
* compositor is never the one a Linux session uses. Android 10+ (ImageReader usage flags).
*/
internal class XboxNativeVideo(private val context: Context, eglBase: EglBase, private val log: (String) -> Unit) : VideoSink {
companion object {
const val FG_OFF = "off"
const val FG_DDFG = "ddfg"
const val FG_LSFG = "lsfg"
const val FG_LSFG3 = "lsfg3"
const val FG_LSFG4 = "lsfg4"
fun isLsfg(mode: String) = mode == FG_LSFG || mode == FG_LSFG3 || mode == FG_LSFG4
fun multiplier(mode: String) = when (mode) { FG_LSFG3 -> 3; FG_LSFG4 -> 4; FG_OFF -> 0; else -> 2 }
fun modes(lsfg: Boolean) = if (lsfg) listOf(FG_OFF, FG_DDFG, FG_LSFG, FG_LSFG3, FG_LSFG4) else listOf(FG_OFF, FG_DDFG)
fun modeName(mode: String) = when (mode) {
FG_DDFG -> "DDFG 2×"; FG_LSFG -> "LSFG 2×"; FG_LSFG3 -> "LSFG 3×"; FG_LSFG4 -> "LSFG 4×"; else -> "Off"
}
/** LSFG can run: the Lossless.dll was imported (or found in Steam) and its shader cache built. */
fun lsfgReady(context: Context) = Lossless.state(context).ready
private const val SCALE_FIT = 1
private const val ALIGN_CENTER = 0
}
private val lock = Any()
private val egl = EglRenderer("xcloud-native").apply { init(eglBase.eglBaseContext, EglBase.CONFIG_RGBA, GlRectDrawer()) }
private val readerThread = HandlerThread("xcloud-frames").apply { start() }
private val readerHandler = Handler(readerThread.looper)
private var reader: ImageReader? = null
private var readerW = 0
private var readerH = 0
/** Images the compositor may still read: the oldest goes back to the reader once two newer ones arrived. */
private val held = ArrayDeque<Image>()
private var surface: Surface? = null
private var attached = false
@Volatile private var frameGen = FG_OFF
@Volatile private var refreshHz = 60f
/** The frame-rate target (0 = the screen's rate): the frame-gen pacer's cap, or a limit on stream frames without it. */
@Volatile private var fpsTarget = 0
private var nextDueNs = 0L
@Volatile var frames = 0L
private set
/** The screen: the compositor presents to it (null detaches, e.g. for zero-copy or when the surface goes). */
fun setSurface(target: Surface?, width: Int, height: Int, displayRefreshHz: Float) = synchronized(lock) {
refreshHz = displayRefreshHz
if (target == null) {
if (attached) letGo()
attached = false; surface = null
return@synchronized
}
surface = target
val runtime = File(context.cacheDir, "xcloud-wayland").apply { mkdirs() }
// System Vulkan driver; this process's compositor shows only the stream.
val started = CompositorHost.startOrAttach(context, target, runtime.path, null, null, context.applicationInfo.nativeLibraryDir,
width, height, displayRefreshHz, 0)
if (started) {
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, ALIGN_CENTER)
log("compositor started on ${width}x$height at ${displayRefreshHz.toInt()} Hz")
} else {
WaylandCompositor.nativeResizeOutput(width, height)
}
WaylandCompositor.nativeStreamMode(true)
attached = true
applyFrameGen()
}
/**
* Gives the screen surface up and waits until the compositor has really disconnected from it: the window request
* is applied on the compositor thread at its next tick, and the decoder (zero-copy) can only connect after that.
*/
private fun letGo() {
WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
CompositorHost.detach(surface)
WaylandCompositor.nativeVsync(System.nanoTime())
if (!WaylandCompositor.nativeWaitSurface(1000)) log("compositor did not let go of the screen within 1 s")
}
/** Frame-rate target, 0 = the screen's rate. Live. */
fun setFpsTarget(fps: Int) {
fpsTarget = fps
synchronized(lock) { if (attached) applyFrameGen() }
}
/** off, ddfg (2x) or lsfg / lsfg3 / lsfg4 (needs the Lossless.dll). Live. */
fun setFrameGeneration(mode: String) {
frameGen = mode
synchronized(lock) { if (attached) applyFrameGen() }
}
override fun onFrame(frame: VideoFrame) {
val w = frame.rotatedWidth; val h = frame.rotatedHeight
synchronized(lock) { if (w != readerW || h != readerH) startReader(w, h) }
egl.onFrame(frame)
}
private fun startReader(w: Int, h: Int) {
val old = reader
if (old != null) egl.releaseEglSurface { }
held.forEach { runCatching { it.close() } }; held.clear()
old?.close()
readerW = w; readerH = h
val next = ImageReader.newInstance(w, h, PixelFormat.RGBA_8888, 4,
HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT)
next.setOnImageAvailableListener({ r -> onImage(r) }, readerHandler)
reader = next
egl.createEglSurface(next.surface)
log("native video ${w}x$h")
}
private fun onImage(r: ImageReader) {
val image = runCatching { r.acquireLatestImage() }.getOrNull() ?: return
synchronized(lock) {
if (r !== reader) { image.close(); return }
val buffer = image.hardwareBuffer
// Without frame generation a target below the stream's rate drops stream frames evenly: each frame has a
// due time one interval after the last one's, so 30 of 60 frames (or 45: three of four) reach the screen.
val now = System.nanoTime()
val target = fpsTarget
val skip = frameGen == FG_OFF && target in 1 until 60 && run {
val interval = 1_000_000_000L / target
if (nextDueNs == 0L || now - nextDueNs > interval) nextDueNs = now
if (now + 4_000_000L < nextDueNs) true else { nextDueNs += interval; false }
}
if (attached && buffer != null && !skip) { WaylandCompositor.nativeStreamFrame(buffer); frames++ }
buffer?.close()
held.addLast(image)
while (held.size > 2) held.removeFirst().close()
}
}
private fun applyFrameGen() {
// The pacer caps generated output at this rate: the user's target, else the screen's.
val cap = if (fpsTarget > 0) fpsTarget.toFloat() else refreshHz
val mode = when {
frameGen == FG_DDFG -> FrameGen.Mode(FrameGen.ENGINE_DDFG, 2)
isLsfg(frameGen) -> FrameGen.Mode(FrameGen.ENGINE_LSFG, multiplier(frameGen))
else -> FrameGen.Mode.OFF
}
val problem = FrameGen.apply(context, mode, cap)
log("native frame generation: $frameGen, target ${if (fpsTarget > 0) fpsTarget else "screen"} fps" + (problem?.let { " ($it)" } ?: ""))
}
/** {planned, planned, sourceFps, presentedFps, thermal, -1}, or null while nothing is shown. */
fun stats(): FloatArray? = synchronized(lock) { if (attached) WaylandCompositor.nativeFrameGenStats() else null }
fun frameGenProblem(): Int = synchronized(lock) { if (attached) WaylandCompositor.nativeFrameGenProblem() else -1 }
fun release() {
egl.release()
synchronized(lock) {
if (attached) { WaylandCompositor.nativeStreamMode(false); letGo() }
attached = false; surface = null
held.forEach { runCatching { it.close() } }; held.clear()
reader?.close(); reader = null
}
readerThread.quitSafely()
}
}
@@ -46,7 +46,7 @@ internal object XboxRuntime {
val market = game.second.extra["market"]?.takeIf { it.matches(Regex("[A-Z]{2}")) } ?: Xodus.market()
val directory = views.create(app.filesDir)
val process = try {
Xodus.start(app, listOf("run", game.first.path, "droiddeck:prepare", "--exe", game.second.exe,
Xodus.start(app, listOf("run", StoreInstallRoot.guestPathForXodus(app, game.first), "droiddeck:prepare", "--exe", game.second.exe,
"--materialize-chain", "--market", market), launchDirectory = directory, credentialGeneration = credentials)
} catch (e: Exception) { XboxLaunchViews.remove(directory); throw e }
if (!launches.attach(token, process)) { process.close(); error("Xbox launch was cancelled") }
@@ -5,7 +5,9 @@ import android.os.Environment
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.json.JSONObject
import java.io.Closeable
import java.io.File
@@ -79,17 +81,34 @@ internal object Xodus {
networkLink.publish()
networkLink.start()
val runtime = (runtimeDirectory ?: File(app.filesDir, "xbox-runtime")).apply { mkdirs() }
val command = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), listOf(
val root = LinuxRuntime.rootDir(app)
val external = Environment.getExternalStorageDirectory()
val extraBinds = StoreInstallRoot.externalBindSpecsForXodus(app)
val binds = LinuxRuntime.binds(app, null, null, external, extraBinds)
val fastPathPreloaded = runCatching {
File(root, "etc/ld.so.preload").useLines { lines -> lines.any { it.trim() == ProotFastPath.LIBRARY } }
}.getOrDefault(false)
val fastPathKey = if (ProotFastPath.enabled(app) && fastPathPreloaded &&
File(root, ProotFastPath.LIBRARY.removePrefix("/")).isFile) ProotFastPath.key(root, binds) else null
val guestCommand = mutableListOf(
"/usr/bin/env", "HOME=/root", "XODUS_LOG=off", "RUST_LOG=off",
"XDG_RUNTIME_DIR=${runtime.path}", "DROIDDECK_XBOX_CREDENTIAL_SOCKET=${credentials.name}", binary,
) + args)
)
fastPathKey?.let { key ->
guestCommand.addAll(guestCommand.lastIndex, ProotFastPath.guestEnv(root, binds, key))
}
guestCommand.addAll(args)
val command = LinuxRuntime.commandWithBinds(app, root, binds, guestCommand)
val builder = ProcessBuilder(command).directory(LinuxRuntime.rootDir(app))
if (launchDirectory != null) builder.environment()["TMPDIR"] = launchDirectory.path
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_PORT"] = credentials.port.toString()
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_KEY"] = credentials.key
builder.environment().apply {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (key, value) -> put(key, value) } }
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
val digest = java.security.MessageDigest.getInstance("SHA-256")
@@ -133,11 +152,13 @@ internal object Xodus {
}
}
const val SIGN_IN_REJECTED = "Microsoft content licensing rejected sign-in \\(HTTP 401\\)\\. Sign in again in Settings\\."
/** Passes the backend's known stderr diagnostics to [report]; other stderr text never leaves the process. */
fun diagnostics(child: Child, report: (String) -> Unit = { com.droiddeck.launcher.stores.StoresState.logLine("Xbox: $it") }): Thread = Thread({
runCatching {
child.process.errorStream.bufferedReader().useLines { lines -> lines.forEach { line ->
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.")))
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.|NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{3}|$SIGN_IN_REJECTED")))
report(line)
} }
}
@@ -676,14 +676,15 @@ private fun MoviePreview(url: String, modifier: Modifier = Modifier) {
/** A dialog with one text box, for a search term or a page number; the Android keyboard comes up with it. */
@Composable
private fun TextEntryDialog(
internal fun TextEntryDialog(
title: String, initial: String, number: Boolean, confirm: String, onSubmit: (String) -> Unit, onDismiss: () -> Unit,
id: String = "boot-movie-entry",
) {
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
var text by remember { mutableStateOf(initial) }
val submit = { onSubmit(text.trim()); close() }
AppDialog(shown, close, "boot-movie-entry", wide = false, maxWidth = 460.dp) {
AppDialog(shown, close, id, wide = false, maxWidth = 460.dp) {
DialogTitleRow(title, close)
AdbTextField(
value = text, onValueChange = { text = it }, label = "", keyboardType = if (number) KeyboardType.Number else KeyboardType.Text,
@@ -0,0 +1,136 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
/** A grid of cards with a game page that floods out of the opened card and drains back into it. */
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
internal fun CardDetailHost(
open: String?,
detailScroll: ScrollState,
gridScrolled: () -> Boolean,
onDetailFocus: (Boolean) -> Unit,
modifier: Modifier = Modifier,
wrap: @Composable (key: String, content: @Composable () -> Unit) -> Unit = { _, content -> content() },
grid: @Composable () -> Unit,
detail: @Composable (key: String) -> Unit,
) {
val ctx = LocalContext.current
val ff = LocalFrontFocus.current
val density = LocalDensity.current
var shown by remember { mutableStateOf<String?>(null) }
var leaving by remember { mutableStateOf(false) }
var from by remember { mutableStateOf<Origin?>(null) }
var art by remember { mutableStateOf<String?>(null) }
var viewportAt by remember { mutableStateOf(Offset.Zero) }
LaunchedEffect(open) {
if (open != null) {
val mark = StoresMotion.takeCard(open)
from = mark?.let { Origin(it.bounds.translate(-viewportAt), it.corner) }
art = mark?.art
StoresMotion.heroLands = mark != null
leaving = false
shown = open
} else if (shown != null) {
if (from != null) {
leaving = true
delay(Motion.ms(PAGE_RETURN_MS).toLong())
}
shown = null
leaving = false
from = null
}
}
LaunchedEffect(shown) { detailScroll.scrollTo(0) }
val covering = shown != null && !leaving
val coveringNow = rememberUpdatedState(covering)
val gridScale by animateFloatAsState(if (covering) 0.95f else 1f, if (covering) Motion.tw(480) else Motion.tw(460, 40), label = "gridSink")
val gridAlpha by animateFloatAsState(if (covering) 0f else 1f, if (covering) Motion.tw(320, 80) else Motion.tw(300, 100), label = "gridFade")
val fade = with(density) { 14.dp.toPx() }
Box(
modifier.clipToBounds()
.onGloballyPositioned { viewportAt = it.positionInRoot() }
.graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen }
.drawWithContent {
drawContent()
val scrolled = if (shown != null) detailScroll.value > 0 else gridScrolled()
if (scrolled && size.height > fade) drawRect(
Brush.verticalGradient(0f to Color.Transparent, fade / size.height to Color.Black),
blendMode = androidx.compose.ui.graphics.BlendMode.DstIn,
)
},
) {
CompositionLocalProvider(LocalFrontFocus provides if (covering) null else ff) {
Column(
modifier = Modifier.fillMaxSize()
.graphicsLayer { scaleX = gridScale; scaleY = gridScale; alpha = gridAlpha }
.focusProperties { enter = { if (coveringNow.value) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup(),
) { grid() }
}
shown?.let { key ->
wrap(key) {
val body: @Composable () -> Unit = {
Column(
Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { } }
.verticalScroll(detailScroll).padding(top = 4.dp, bottom = 16.dp),
) {
Column(
Modifier.fillMaxWidth()
.onFocusChanged { onDetailFocus(it.hasFocus) }
.focusProperties { exit = { if (coveringNow.value && Steps.step == null && StoresMotion.step == null) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup(),
) { detail(key) }
}
}
val origin = from
if (origin == null) body()
else {
val painter = art?.let { url ->
coil.compose.rememberAsyncImagePainter(
remember(url) {
coil.request.ImageRequest.Builder(ctx).data(url).size(1280, 720)
.placeholderMemoryCacheKey(url).build()
},
)
}
PageFlood(origin, leaving, painter, onto = { StoresMotion.heroAt }, ontoCorner = 16.dp) { body() }
}
}
}
}
}
@@ -70,6 +70,7 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
@@ -102,6 +103,7 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
val ctx = LocalContext.current
val density = LocalDensity.current
val narrow = LocalNarrowPane.current
val short = compactDesktop()
val colors = MaterialTheme.colorScheme
LaunchedEffect(Unit) { UserAppsState.refresh(ctx) }
LaunchedEffect(s.ready) { com.droiddeck.launcher.store.StoreState.refresh(ctx) }
@@ -120,7 +122,7 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
key = "desktop", tabs = tabs,
onOpen = a.onDesktopSettings, onPrimary = a.onDesktop,
modifier = modifier.clipToBounds(),
start = if (narrow) 20.dp else 44.dp, bottom = if (narrow) 20.dp else 44.dp,
start = if (narrow) 20.dp else 44.dp, bottom = 44.dp,
background = {
DesktopWall(installed.map { it.iconRes } + apps.mapNotNull { it.icon })
},
@@ -132,8 +134,8 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
},
words = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
stringResource(R.string.rail_desktop), fontSize = if (narrow) 30.sp else 42.sp, lineHeight = if (narrow) 34.sp else 46.sp,
if (LocalConfiguration.current.screenHeightDp >= 400) Text(
stringResource(R.string.rail_desktop), fontSize = if (short) 30.sp else 42.sp, lineHeight = if (short) 34.sp else 46.sp,
fontWeight = FontWeight.Black, color = colors.onBackground,
)
BusyChip(s)
@@ -143,11 +145,12 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
PrimaryButton(open, enabled = !s.busy, main = true, large = true, icon = Icons.Outlined.DesktopWindows, onClick = click)
},
beside = {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") }
HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true }
}
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.horizontalScroll(rememberScrollState()),
) {
HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") }
HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true }
if (s.desktopPresent) UninstallDesktop(enabled = !s.runtimeActionsBlocked, onUninstall = a.onRemoveDesktop)
}
},
@@ -159,6 +162,9 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
if (adding && !s.busy) AddAppDialog(s.ready, onDismiss = { adding = false }) { request, label -> UserAppsState.add(ctx, request, label) }
}
@Composable
private fun compactDesktop() = LocalNarrowPane.current || LocalConfiguration.current.screenHeightDp < 600
@Composable
private fun DesktopDock(
s: FrontEndState, a: FrontEndActions, installed: List<Library.Emulator>, apps: List<UserApps.App>,
@@ -177,7 +183,7 @@ private fun DesktopDock(
LaunchedEffect(Unit) { mounted[0] = true }
val scroll = rememberScrollState()
if (keys.isEmpty() && available.isEmpty() && UserAppsState.working == null && UserAppsState.lastError == null) return
Column(Modifier.fillMaxWidth().padding(top = if (narrow) 14.dp else 22.dp)) {
Column(Modifier.fillMaxWidth().padding(top = if (compactDesktop()) 14.dp else 22.dp)) {
Text(
stringResource(R.string.user_apps_section).uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.6.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(start = if (narrow) 20.dp else 44.dp, bottom = 8.dp),
@@ -254,7 +254,7 @@ private fun Content(
return
}
if (selected == "games" || selected.startsWith("app:")) {
GamesPage(s, a, selected, onSelect, modifier)
LibraryPage(s, a, selected, onSelect, modifier)
return
}
if (selected == "desktop") {
@@ -5,7 +5,6 @@ import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
@@ -13,144 +12,39 @@ import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.key
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.ui.semantics.semantics
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.PlayArrow
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.remember
import kotlinx.coroutines.flow.first
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.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.epic.EpicClient
import kotlinx.coroutines.launch
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
@Composable
internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, onSelect: (String) -> Unit, modifier: Modifier) {
val pageContext = androidx.compose.ui.platform.LocalContext.current
LaunchedEffect(Unit) { EpicClient.refresh(pageContext) }
val launcherName = stringResource(R.string.epic_client_title)
val epic = EpicClient.status
val launcherArt by androidx.compose.runtime.produceState<java.io.File?>(null, epic.version) {
value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { EpicClient.icon(pageContext, epic.version) }
}
val games = remember(s.steamGames, s.shortcutPicker, epic, launcherName, launcherArt) {
val sorted = s.steamGames.sortedByDescending { it.lastPlayed }
if (s.shortcutPicker) sorted else EpicClient.withLauncher(sorted, EpicClient.launcherEntry(pageContext, launcherName, epic, launcherArt))
}
val gameCount = games.count { it.library != Library.EPIC_LAUNCHER }
val narrow = LocalNarrowPane.current
val current = games.firstOrNull { "app:${it.appId}" == selected } ?: games.firstOrNull()
GamesDialogs(a, s.steamGames)
val onAdd: (() -> Unit)? = if (s.shortcutPicker) null else ({ GamesDialogState.adding = true })
val launch: (Library.SteamGame) -> Unit = { g -> if (g.library == Library.EPIC_LAUNCHER) a.onEpicLauncher() else a.onSteamGame(g) }
val onEdit: (Library.SteamGame) -> Unit = { g ->
g.gameFiles?.let { GamesDialogState.editing = EditRequest(it.path, openTarget = false, fromSummary = false, preview = EditPreview.of(pageContext, g, it.path)) }
}
if (current == null || gameCount == 0) {
Column(modifier = modifier.padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
Rise(0) {
PageHeader(stringResource(R.string.content_games)) {
if (s.steamGamesX64) ClientTag()
onAdd?.let { AddGameButton(it) }
}
}
Rise(1) { Note(stringResource(if (s.shortcutPicker && s.shortcutLibraryScanning) R.string.game_shortcut_scanning else R.string.games_empty)) }
if (!s.shortcutPicker) Rise(2) {
Actions {
PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp).testTag("play-steam"), onClick = a.onPlay)
games.firstOrNull { it.library == Library.EPIC_LAUNCHER }?.let { SecondaryButton(it.name, enabled = !s.busy, modifier = Modifier.padding(top = 12.dp)) { a.onEpicLauncher() } }
}
}
GameFileFolderActions(s, a)
}
return
}
val host = rememberMenuHost()
if (games.size == 1) {
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
if (onAdd != null) Rise(0) { GamesHeader(gameCount, s.steamGamesX64, onAdd, Modifier.padding(bottom = 10.dp)) }
Rise(0) {
Row(verticalAlignment = Alignment.Bottom) {
GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp), corner = { GameRemoveButton(current, s, a) }) {
GameHeroCopy(current, if (narrow) 28.sp else 38.sp)
GameActions(current, s, a, onEdit, launch)
}
if (!narrow) Poster(current.art, current.name, Modifier.width(168.dp))
}
}
Rise(1) { SectionTitle(stringResource(R.string.games_launch_settings), null) }
Rise(2) { LaunchSettings(s, a, host, current) }
Rise(3) { GameFileFolderActions(s, a) }
}
return
}
val pal = LocalPalette.current
Row(modifier = modifier) {
GameList(games, gameCount, s.steamGamesX64, current, onSelect = { onSelect("app:${it.appId}") }, onLaunch = launch, onAdd = onAdd,
modifier = Modifier.width(if (narrow) 168.dp else 250.dp).fillMaxHeight())
Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line))
Column(
modifier = Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState())
.padding(horizontal = if (narrow) 14.dp else 20.dp, vertical = 16.dp),
) {
GameHero(current, Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 200.dp), corner = { GameRemoveButton(current, s, a) }) {
GameHeroCopy(current, if (narrow) 24.sp else 32.sp)
GameActions(current, s, a, onEdit, launch)
}
SectionTitle(stringResource(R.string.games_launch_settings), null)
LaunchSettings(s, a, host, current)
GameFileFolderActions(s, a)
}
}
}
@Composable
private fun GameFileFolderActions(s: FrontEndState, a: FrontEndActions) {
internal fun GameFileFolderActions(s: FrontEndState, a: FrontEndActions) {
if (s.shortcutPicker) return
var open by remember { androidx.compose.runtime.mutableStateOf(false) }
Box(Modifier.padding(top = 12.dp)) {
Box {
SecondaryButton(stringResource(R.string.game_frontend_files), compact = true) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = s.gameSyncFolder ?: stringResource(R.string.game_frontend_files)) { first ->
MenuItem(stringResource(R.string.game_file_sync), checked = false, focusRequester = first) {
@@ -165,31 +59,7 @@ private fun GameFileFolderActions(s: FrontEndState, a: FrontEndActions) {
@Composable
private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions, onEdit: (Library.SteamGame) -> Unit, launch: (Library.SteamGame) -> Unit) {
Actions {
PrimaryButton(stringResource(if (s.shortcutPicker) R.string.game_shortcut_choose else R.string.games_launch), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { launch(g) }
if (g.library == Library.EPIC_LAUNCHER) {
if (!s.shortcutPicker) UninstallEpicLauncher(s, a)
BusyChip(s)
return@Actions
}
g.gameFiles?.takeIf { it.isDirectory }?.let { dir ->
SecondaryButton(stringResource(R.string.games_files), compact = true) { a.onBrowseFiles(dir) }
}
g.protonPrefix?.takeIf { it.isDirectory }?.let { dir ->
SecondaryButton(stringResource(R.string.games_prefix), compact = true) { a.onBrowseFiles(dir) }
if (g.library == Library.ADDED) ManageSaves(g, dir, a)
}
if (!s.shortcutPicker) GameShortcutMenu(g, a)
if (!s.shortcutPicker && g.library == Library.ADDED && g.source == Library.ADDED && g.gameFiles != null) EditGameButton { onEdit(g) }
else if (!s.shortcutPicker && g.library != Library.ADDED && g.source == Library.SOURCE_STEAM) EditGameButton { GamesDialogState.steamArt = g }
else if (!s.shortcutPicker && g.library == Library.ADDED && g.source != Library.ADDED && g.gameFiles != null) EditGameButton { GamesDialogState.storeArt = g }
BusyChip(s)
}
}
@Composable
private fun UninstallEpicLauncher(s: FrontEndState, a: FrontEndActions) {
internal fun UninstallEpicLauncher(s: FrontEndState, a: FrontEndActions) {
var asking by remember { androidx.compose.runtime.mutableStateOf(false) }
SecondaryButton(stringResource(R.string.common_uninstall), enabled = !s.busy, compact = true) { asking = true }
if (asking) {
@@ -204,71 +74,6 @@ private fun UninstallEpicLauncher(s: FrontEndState, a: FrontEndActions) {
}
}
@Composable
private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
var open by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) }
Box {
SecondaryButton(stringResource(R.string.game_shortcut), compact = true) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = stringResource(R.string.game_shortcut)) { first ->
MenuItem(stringResource(R.string.game_shortcut_add), checked = false, focusRequester = first) {
open = false; a.onGameShortcut(g)
}
MenuItem(stringResource(R.string.game_file_export), checked = false) {
open = false; a.onExportGameFile(g)
}
MenuItem(stringResource(R.string.game_link_copy), checked = false) {
open = false; a.onCopyGameLink(g)
}
}
}
}
@Composable
private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndActions) {
var open by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) }
val saves by androidx.compose.runtime.produceState<List<com.droiddeck.launcher.session.GameSaves.SaveDir>?>(null, g.gameId, open) {
if (open) value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { com.droiddeck.launcher.session.GameSaves.locate(prefix, g) }.getOrDefault(emptyList())
}
}
val found = saves
val summary = when {
found == null -> stringResource(R.string.games_saves_looking)
found.isEmpty() -> stringResource(R.string.games_saves_none)
else -> {
val mb = found.sumOf { it.bytes } / 1048576.0
stringResource(
R.string.games_saves_summary,
if (found.size == 1) found[0].relPath else stringResource(R.string.games_saves_folders, found.size),
found.sumOf { it.files },
if (mb < 1) stringResource(R.string.games_kb, (mb * 1024).toInt()) else stringResource(R.string.common_size_mb, mb),
)
}
}
Box {
val cloudGame = com.droiddeck.launcher.stores.Store.byId(g.source).let { it == com.droiddeck.launcher.stores.Store.GOG || it == com.droiddeck.launcher.stores.Store.EPIC }
val label = stringResource(if (cloudGame) R.string.store_cloud_saves else R.string.games_manage_saves)
SecondaryButton(label, compact = true) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = if (cloudGame) label else stringResource(R.string.games_saves), note = summary) { first ->
if (cloudGame) CloudRows(g, open, first)
MenuItem(stringResource(R.string.games_import_saves), checked = false, focusRequester = if (cloudGame) null else first) {
open = false; a.onSaveImport(g)
}
MenuItem(stringResource(R.string.games_export_gamehub), checked = false) {
open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.GAMEHUB)
}
MenuItem(stringResource(R.string.games_export_winlator), checked = false) {
open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.WINLATOR)
}
found?.firstOrNull()?.let { d ->
MenuItem(stringResource(R.string.games_open_save_folder), checked = false, detail = d.relPath) {
open = false; a.onBrowseFiles(java.io.File(prefix, "drive_c/users/steamuser/" + d.relPath))
}
}
}
}
}
/** A skipped sync is not a success: "0 files" used to show for a signed-out store or cloud saves turned off. */
internal fun cloudMessage(context: android.content.Context, r: com.droiddeck.launcher.stores.CloudSaves.Result): String = when (r.result) {
"ok" -> when {
@@ -285,125 +90,7 @@ internal fun cloudMessage(context: android.content.Context, r: com.droiddeck.lau
}
@Composable
private fun CloudRows(g: Library.SteamGame, open: Boolean, first: androidx.compose.ui.focus.FocusRequester) {
val store = com.droiddeck.launcher.stores.Store.byId(g.source)?.takeIf { it != com.droiddeck.launcher.stores.Store.AMAZON } ?: return
val id = g.storeId ?: return
val context = androidx.compose.ui.platform.LocalContext.current.applicationContext
var busy by remember(g.gameId) { androidx.compose.runtime.mutableStateOf<String?>(null) }
var tick by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(0) }
val status by androidx.compose.runtime.produceState<com.droiddeck.launcher.stores.CloudSaves.Status?>(null, g.gameId, open, tick) {
if (open) value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { com.droiddeck.launcher.stores.CloudSaves.status(context, store, id) }.getOrNull()
}
}
val folder = g.gameFiles
var enabled by remember(g.gameId, open) { androidx.compose.runtime.mutableStateOf(folder?.let { com.droiddeck.launcher.stores.StoreGameSidecar.read(it)?.cloud } ?: true) }
val st = status
val supported = st?.supported ?: true
val conflict = st != null && st.conflicts.isNotEmpty()
fun sync(up: Boolean, force: Boolean = false) {
if (busy != null) return
busy = if (up) "up" else "down"
Thread({
val r = if (up) com.droiddeck.launcher.stores.CloudSaves.upload(context, store, id, force) else com.droiddeck.launcher.stores.CloudSaves.download(context, store, id, force)
com.droiddeck.launcher.stores.StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() }
}, "cloud-manual").start()
}
MenuItem(stringResource(R.string.store_cloud_saves), checked = enabled && supported, enabled = supported, focusRequester = first,
detail = if (!supported) stringResource(R.string.cloud_none) else null) {
val f = folder ?: return@MenuItem
val next = !enabled
Thread({
val written = runCatching { com.droiddeck.launcher.stores.StoreGameSidecar.updateCloud(f, next) }.getOrNull()
com.droiddeck.launcher.stores.StoresState.post { enabled = written?.cloud ?: enabled }
}, "cloud-switch").start()
}
val ready = st != null && supported && enabled && busy == null
val pending = stringResource(R.string.cloud_pending)
val summary = when {
st == null || busy != null -> pending
!supported -> stringResource(R.string.cloud_none)
conflict -> stringResource(R.string.cloud_conflict_files, st.conflicts.size)
st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString())
else -> stringResource(R.string.cloud_never)
}
MenuItem(stringResource(if (conflict) R.string.cloud_keep_local else R.string.cloud_upload), checked = false, enabled = ready, detail = summary) { sync(up = true, force = conflict) }
MenuItem(stringResource(if (conflict) R.string.cloud_keep_cloud else R.string.cloud_download), checked = false, enabled = ready, detail = if (st == null || busy != null) pending else null) { sync(up = false, force = conflict) }
}
@Composable
private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SourceChip(g.source)
val eyebrow = lastPlayedText(g.lastPlayed) ?: libraryLabel(g)
if (eyebrow.isNotEmpty()) Text(
eyebrow.uppercase(),
fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = LocalPalette.current.signal,
maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
GameTitle(g, titleSize)
Spacer(Modifier.height(8.dp))
}
@Composable
private fun GameTitle(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
val logo = g.logo
var failed by remember(logo) { androidx.compose.runtime.mutableStateOf(false) }
if (logo != null && !failed) {
AsyncImage(
model = logo, contentDescription = g.name, contentScale = ContentScale.Fit, alignment = Alignment.CenterStart,
onError = { failed = true },
modifier = Modifier.padding(vertical = 4.dp).height((titleSize.value * 2.2f).dp).widthIn(max = (titleSize.value * 9f).dp).testTag("game-logo"),
)
} else Text(
g.name, fontSize = titleSize, lineHeight = titleSize * 1.15f, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis,
)
}
@Composable
private fun GameList(
games: List<Library.SteamGame>, count: Int, x64: Boolean, current: Library.SteamGame,
onSelect: (Library.SteamGame) -> Unit, onLaunch: (Library.SteamGame) -> Unit, onAdd: (() -> Unit)?, modifier: Modifier,
) {
val colors = MaterialTheme.colorScheme
Column(
verticalArrangement = Arrangement.spacedBy(2.dp),
modifier = modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 10.dp, top = 16.dp, bottom = 16.dp),
) {
GamesHeader(count, x64, onAdd, Modifier.padding(start = 6.dp, bottom = 10.dp))
val seen = remember { HashSet<Int>() }
var settled by remember { androidx.compose.runtime.mutableStateOf(false) }
for (g in games) key(g.appId) {
Box(Modifier.arriveIn(settled && g.appId !in seen)) {
GameRow(g, g.appId == current.appId, onSelect = { onSelect(g) }, onLaunch = { onLaunch(g) })
}
}
androidx.compose.runtime.SideEffect {
seen.addAll(games.map { it.appId })
if (games.isNotEmpty()) settled = true
}
}
}
@Composable
private fun GamesHeader(count: Int, x64: Boolean, onAdd: (() -> Unit)?, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
Column(modifier) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(stringResource(R.string.content_games), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
Text(count.toString(), fontSize = 13.sp, color = colors.onSurfaceVariant)
if (x64 && !narrow) ClientTag()
if (onAdd != null) AddGameButton(onAdd)
}
if (x64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() }
}
}
@Composable
private fun ClientTag() {
internal fun ClientTag() {
Box(Modifier.testTag("games-client-x64")) { StateChip(stringResource(R.string.mode_client_arch_x64), ChipTone.PLAIN) }
}
@@ -418,7 +105,7 @@ internal object GamesDialogState {
}
@Composable
private fun GamesDialogs(a: FrontEndActions, games: List<Library.SteamGame>) {
internal fun GamesDialogs(a: FrontEndActions, games: List<Library.SteamGame>) {
val ctx = androidx.compose.ui.platform.LocalContext.current
val scope = androidx.compose.runtime.rememberCoroutineScope()
val st = GamesDialogState
@@ -472,68 +159,7 @@ private fun GamesDialogs(a: FrontEndActions, games: List<Library.SteamGame>) {
}
@Composable
private fun GameRemoveButton(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions) {
val kind = com.droiddeck.launcher.frontend.GameRemoval.kind(g)
if (s.shortcutPicker || kind == com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER) return
if (g.gameFiles?.isDirectory != true) return
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
var asking by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) }
val shortcut = kind == com.droiddeck.launcher.frontend.GameRemoval.Kind.SHORTCUT
val label = stringResource(if (shortcut) R.string.edit_remove else R.string.common_uninstall)
val title = if (shortcut) stringResource(R.string.games_remove_title, g.name) else stringResource(R.string.stores_uninstall_title, g.name)
val body = when {
shortcut -> stringResource(R.string.games_remove_body)
g.library == Library.ADDED -> stringResource(R.string.stores_uninstall_body)
else -> stringResource(R.string.games_uninstall_body)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("game:remove").downToFirstTile().size(44.dp).clip(Shape12)
.background(if (hot) colors.error.copy(alpha = 0.22f) else Color.Black.copy(alpha = 0.34f))
.glideBorder(hot, Shape12, colors.error, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button) { asking = true }
.controllerConfirm { asking = true }
.semantics { contentDescription = label },
) {
androidx.compose.material3.Icon(
Icons.Outlined.Delete, contentDescription = null,
tint = if (hot) colors.error else Color.White, modifier = Modifier.size(18.dp),
)
}
if (asking) ConfirmDialog(
title = title,
text = body,
confirm = label,
onConfirm = { a.onGameRemoved(g) },
onDismiss = { asking = false },
)
}
@Composable
private fun EditGameButton(onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val label = stringResource(R.string.common_edit)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("game:edit").downToFirstTile().size(44.dp).clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f))
.glideBorder(hot, Shape12, pal.signal, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = label },
) {
androidx.compose.material3.Icon(Icons.Outlined.Edit, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp))
}
}
@Composable
private fun AddGameButton(onClick: () -> Unit) {
internal fun AddGameButton(onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
@@ -553,48 +179,6 @@ private fun AddGameButton(onClick: () -> Unit) {
}
}
@Composable
internal fun Modifier.arriveIn(arriving: Boolean): Modifier {
val t = remember { androidx.compose.animation.core.Animatable(if (arriving) 0f else 1f) }
LaunchedEffect(Unit) { if (t.value < 1f) t.animateTo(1f, Motion.tw(280)) }
return graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 12.dp.toPx() }
}
@Composable
private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Unit, onLaunch: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val focused by src.collectIsFocusedAsState()
val hovered by src.collectIsHoveredAsState()
LaunchedEffect(focused) { if (focused && !selected) onSelect() }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().paneItem("game:${g.appId}")
.clip(Shape12)
.background(if (selected) pal.signal.copy(alpha = 0.14f) else if (hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent)
.glideBorder(focused, Shape12, pal.signal)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onSelect)
.controllerConfirm(onClick = onLaunch)
.padding(horizontal = 10.dp, vertical = 6.dp),
) {
Box(Modifier.width(30.dp).height(45.dp).clip(RoundedCornerShape(5.dp)).background(artBrush(hueOf(g.name)))) {
if (g.art != null) AsyncImage(model = g.art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
}
Column(modifier = Modifier.weight(1f)) {
Text(g.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SourceChip(g.source, small = true)
Text(
if (g.library == Library.EPIC_LAUNCHER) libraryLabel(g)
else playedSpan(g.lastPlayed)?.replaceFirstChar { it.uppercase() } ?: stringResource(R.string.games_never_played),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
}
}
}
@Composable
internal fun PageHeader(title: String, trailing: @Composable RowScope.() -> Unit = {}) {
Row(
@@ -623,11 +207,7 @@ internal fun RuntimeChip(s: FrontEndState) = when {
else -> Chip(stringResource(R.string.games_runtime_ready), ok = true)
}
@Composable
private fun lastPlayedText(lastPlayed: Long): String? =
playedSpan(lastPlayed)?.let { stringResource(R.string.games_last_played, it.replaceFirstChar { c -> c.lowercase() }) }
private fun playedSpan(lastPlayed: Long): String? {
internal fun playedSpan(lastPlayed: Long): String? {
if (lastPlayed <= 0L) return null
return android.text.format.DateUtils.getRelativeTimeSpanString(
lastPlayed * 1000L, System.currentTimeMillis(), android.text.format.DateUtils.MINUTE_IN_MILLIS,
@@ -635,37 +215,9 @@ private fun playedSpan(lastPlayed: Long): String? {
}
@Composable
private fun libraryLabel(g: Library.SteamGame): String = when {
g.library == Library.EPIC_LAUNCHER -> EpicClient.status.version?.substringBefore('+')?.let { stringResource(R.string.epic_client_version, it) } ?: ""
internal fun libraryLabel(g: Library.SteamGame): String = when {
g.library == Library.XBOX_CLOUD -> stringResource(R.string.xbox_cloud_gaming)
g.library != Library.ADDED -> if (g.library == "internal") stringResource(R.string.games_internal) else g.library
g.source != Library.ADDED -> stringResource(R.string.games_store_storage)
else -> ""
}
@Composable
private fun GameHero(g: Library.SteamGame, modifier: Modifier, corner: @Composable BoxScope.() -> Unit = {}, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
Box(modifier = modifier.clip(Shape16).background(artBrush(hueOf(g.name)))) {
val image = g.hero ?: g.art.takeIf { g.library != Library.EPIC_LAUNCHER }
if (image != null) AsyncImage(
model = image, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.matchParentSize()
.then(if (g.hero == null) Modifier.blur(24.dp).graphicsLayer { scaleX = 1.3f; scaleY = 1.3f } else Modifier),
)
Spacer(
Modifier.matchParentSize().background(
Brush.horizontalGradient(
0f to colors.background.copy(alpha = 0.92f),
0.55f to colors.background.copy(alpha = 0.6f),
1f to Color.Transparent,
),
),
)
Column(
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp),
content = content,
)
Box(Modifier.align(Alignment.TopEnd).padding(12.dp), content = corner)
}
}
@@ -141,7 +141,6 @@ class FrontEndState(
val launcherIcon: String = com.droiddeck.launcher.LauncherIcon.DARK,
val gameStoresEnabled: Boolean = true,
val gameStoresSpeedTier: String = "fast",
val storesOpenTab: String = SessionPrefs.STORES_OPEN_LIBRARY,
val navigate: String? = null,
val addedGamesArt: Boolean = true,
val sgdbUserKey: Boolean = false,
@@ -217,7 +216,6 @@ class FrontEndActions(
val onDownloadPrefix: (String) -> Unit = {},
val onGameStoresEnabled: (Boolean) -> Unit = {},
val onGameStoresSpeedTier: (String) -> Unit = {},
val onStoresOpenTab: (String) -> Unit = {},
val onNavigated: () -> Unit = {},
val onStoresShowMature: (Boolean) -> Unit = {},
val onStoresSort: (String) -> Unit = {},
@@ -395,6 +393,9 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
a.onNavigated()
}
LaunchedEffect(com.droiddeck.launcher.stores.StoresState.openGameRequest) {
if (com.droiddeck.launcher.stores.StoresState.openGameRequest != null) selected = "stores"
}
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
@@ -437,7 +438,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
LaunchedEffect(s.steamGames.isEmpty()) {
if (s.steamGames.isEmpty() && selected.startsWith("app:")) selected = "games"
if (s.steamGames.isEmpty() && selected.startsWith("app:") && GameRef.parse(selected).appId != null) selected = "games"
}
remember { Motion.refresh(ctx); true }
@@ -550,6 +551,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
FlightsLayer(screenAt)
GamesDialogs(a, s.steamGames)
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
StepsLayer(screenAt)
appToChooseDisplay?.let { app ->
@@ -181,7 +181,7 @@ internal fun SetupPanel(
onDismiss = { editDownloadPrefix = false },
onSave = { a.onDownloadPrefix(it); editDownloadPrefix = false },
)
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses), "SDL3Bridge")
var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) }
SetupTabs.openLauncher = false
val chipFocus = remember { List(tabs.size) { FocusRequester() } }
@@ -460,6 +460,7 @@ internal fun SetupPanel(
}
}
GLASSES_TAB -> GlassesSetupPanel()
GLASSES_TAB + 1 -> SdlBridgeSettingsTab(host) // sdl3bridge: SDL3Bridge tab
}
}
}
@@ -508,7 +509,7 @@ private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
}
@Composable
internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost, game: com.droiddeck.launcher.frontend.Library.SteamGame? = null) {
internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost, game: com.droiddeck.launcher.frontend.Library.SteamGame? = null, hopRail: String = "games") {
val columns = if (LocalNarrowPane.current) 2 else 3
val controller = a.controller
val context = androidx.compose.ui.platform.LocalContext.current
@@ -527,7 +528,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val at = Hops.sources["card:components"]
val open = { if (game == null) a.onComponents(true) else a.onGameComponents(game) }
if (at == null) open()
else Hops.go(HopOrigin("games", HOP_SURFACE_GAMES, null, "card:components", at, back, dest = "components", page = "components"), open)
else Hops.go(HopOrigin(hopRail, HOP_SURFACE_GAMES, null, "card:components", at, back, dest = "components", page = "components"), open)
}
}
add { m ->
@@ -570,18 +571,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
}
@Composable
private fun GameSettingsCard(host: MenuHost, game: com.droiddeck.launcher.frontend.Library.SteamGame, scope: String) {
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
val colors = MaterialTheme.colorScheme
var config by remember(scope) { mutableStateOf(runCatching { com.droiddeck.launcher.session.GameEnvironmentStore.read(appContext) }.getOrNull()) }
var saving by remember(scope) { mutableStateOf(false) }
val current = config
val noSteam = current != null && com.droiddeck.launcher.core.GameEnvironment.gameNoSteam(current, scope)
val fex = current?.let { runCatching { com.droiddeck.launcher.core.GameEnvironment.gameFexPreset(it, scope) }.getOrNull() }
val sync = current?.let { runCatching { com.droiddeck.launcher.core.GameEnvironment.gameSync(it, scope) }.getOrNull() }
val ready = current != null && !saving
val launcher = game.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER
internal class GameSettingsState(private val appContext: android.content.Context, val scope: String) {
var config by mutableStateOf(runCatching { com.droiddeck.launcher.session.GameEnvironmentStore.read(appContext) }.getOrNull())
var saving by mutableStateOf(false)
val noSteam: Boolean get() = config?.let { com.droiddeck.launcher.core.GameEnvironment.gameNoSteam(it, scope) } == true
fun save(change: (android.content.Context) -> com.droiddeck.launcher.core.GameEnvironment.Config?) {
if (saving) return
saving = true
@@ -595,7 +589,37 @@ private fun GameSettingsCard(host: MenuHost, game: com.droiddeck.launcher.fronte
}
}, "game-settings").start()
}
val key = "game-settings"
}
@Composable
internal fun rememberGameSettings(scope: String): GameSettingsState {
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
return remember(scope) { GameSettingsState(appContext, scope) }
}
@Composable
private fun GameSettingsCard(host: MenuHost, game: com.droiddeck.launcher.frontend.Library.SteamGame, scope: String) {
val state = rememberGameSettings(scope)
SettingCard(stringResource(R.string.game_settings_card), stringResource(if (state.noSteam) R.string.game_steam_without else R.string.game_steam_with), "card:$GAME_SETTINGS_MENU", Modifier.fillMaxSize()) {
host.open = if (host.open == GAME_SETTINGS_MENU) null else GAME_SETTINGS_MENU
}
GameSettingsMenus(host, game, state)
}
/** The per-game settings menus, opened by setting [MenuHost.open] to [GAME_SETTINGS_MENU]. */
@Composable
internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.frontend.Library.SteamGame, state: GameSettingsState) {
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
val colors = MaterialTheme.colorScheme
val scope = state.scope
val current = state.config
val noSteam = state.noSteam
val fex = current?.let { runCatching { com.droiddeck.launcher.core.GameEnvironment.gameFexPreset(it, scope) }.getOrNull() }
val sync = current?.let { runCatching { com.droiddeck.launcher.core.GameEnvironment.gameSync(it, scope) }.getOrNull() }
val ready = current != null && !state.saving
val launcher = game.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER
fun save(change: (android.content.Context) -> com.droiddeck.launcher.core.GameEnvironment.Config?) = state.save(change)
val key = GAME_SETTINGS_MENU
val fexKey = "game-settings-fex"
val syncKey = "game-settings-sync"
val syncLabels = mapOf(
@@ -609,9 +633,6 @@ private fun GameSettingsCard(host: MenuHost, game: com.droiddeck.launcher.fronte
val custom = stringResource(R.string.comp_game_fex_custom)
val customSync = stringResource(R.string.game_sync_custom)
val resetDone = stringResource(R.string.comp_game_reset_done, game.name)
SettingCard(stringResource(R.string.game_settings_card), stringResource(if (noSteam) R.string.game_steam_without else R.string.game_steam_with), "card:$key", Modifier.fillMaxSize()) {
host.open = if (host.open == key) null else key
}
AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = stringResource(R.string.game_settings_menu_title, game.name)) { first ->
MenuItem(stringResource(R.string.game_no_steam_title), checked = noSteam, enabled = ready,
detail = stringResource(R.string.game_no_steam_detail), focusRequester = first) {
@@ -686,6 +707,8 @@ private fun GameSettingsCard(host: MenuHost, game: com.droiddeck.launcher.fronte
}
}
internal const val GAME_SETTINGS_MENU = "game-settings"
private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal"
@Composable
@@ -0,0 +1,830 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material3.CircularProgressIndicator
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.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.GameRemoval
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.CloudSaves
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Lookup
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAchievements
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.xbox.XboxBackend
import com.droiddeck.launcher.stores.xbox.XboxCloudGames
import com.droiddeck.launcher.stores.xbox.XboxContent
import com.droiddeck.launcher.stores.xbox.xboxCloud
import com.droiddeck.launcher.stores.xbox.xboxPc
import com.droiddeck.launcher.stores.xbox.XboxRuntime
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
/** What a game page shows: `app:<appId>` for a game in the library, `[app:]<store>:<id>` for a store product. */
internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) {
fun game(games: List<Library.SteamGame>): Library.SteamGame? = when {
appId != null -> games.firstOrNull { it.appId == appId }
store != null && storeId != null -> games.firstOrNull { it.source == store.id && it.storeId == storeId }
else -> null
}
companion object {
fun parse(key: String): GameRef {
val rest = key.removePrefix("app:")
rest.toIntOrNull()?.let { return GameRef(it, null, null) }
val store = Store.byId(rest.substringBefore(':'))
return GameRef(null, store, rest.substringAfter(':', "").takeIf { store != null && it.isNotEmpty() })
}
fun key(game: Library.SteamGame) = "app:${game.appId}"
fun key(item: CatalogItem) = "app:${item.key}"
}
}
internal enum class GameTab { ABOUT, ACHIEVEMENTS, LAUNCH, SAVES, INSTALL }
@Composable
internal fun GameDetail(
key: String, s: FrontEndState, a: FrontEndActions, lead: FocusRequester, backLabel: String, hopRail: String?, onBack: () -> Unit,
) {
val narrow = LocalNarrowPane.current
val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700
val ref = remember(key) { GameRef.parse(key) }
val games = s.steamGames + rememberXboxCloudRows(s)
val found = ref.game(games)
val known = remember(key) { arrayOfNulls<Pair<Store, String>>(1) }
val store = ref.store ?: Store.byId(found?.source) ?: known[0]?.first
val id = ref.storeId ?: found?.storeId ?: known[0]?.second
SideEffect { if (store != null && id != null) known[0] = store to id }
val game = found ?: if (store != null && id != null) s.steamGames.firstOrNull { it.source == store.id && it.storeId == id } else null
val item = if (store != null && id != null) StoresState.detailItem(store, id) else null
val installed = if (store != null && id != null) StoresState.installedGame(store, id) else null
val rawDownload = if (store != null && id != null) StoresState.download("${store.id}:$id") else null
val download = rawDownload?.takeIf { it.isActive }
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
val nothing = game == null && store == null
LaunchedEffect(nothing) { if (nothing) onBack() }
if (nothing) return
val source = game?.source ?: store?.id ?: Library.SOURCE_STEAM
val title = game?.name ?: item?.title ?: installed?.sidecar?.title ?: id.orEmpty()
val scores = if (source != Library.ADDED) rememberGameScores(title.takeIf { it.isNotBlank() && it != id }) else null
val achievements = remember(store, id, item?.accessible, installed) {
when {
store == null || StoreAchievements.forSource(store.id) == null -> null
item?.accessible == true -> StoreAchievements.Game.of(item)
installed != null -> StoreAchievements.Game.of(installed.sidecar)
else -> null
}
}
val achievementState = rememberAchievements(achievements)
val listed = if (store == null) null else (StoresState.found[store].orEmpty() + StoresState.shelves[store]?.all.orEmpty()).firstOrNull { it.id == id }
val developer = item?.developer?.ifBlank { null } ?: listed?.developer.orEmpty()
val publisher = item?.publisher?.ifBlank { null } ?: listed?.publisher.orEmpty()
val releaseDate = item?.releaseDate?.ifBlank { null } ?: listed?.releaseDate.orEmpty()
val description = item?.let { com.droiddeck.launcher.stores.cleanStoreText(it.description) }.orEmpty()
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
val scored = scores != null && (scores.metacritic != Lookup.None || scores.hltb != Lookup.None)
val prefix = game?.protonPrefix?.takeIf { it.isDirectory }
val tabs = buildList {
if (description.isNotBlank() || developer.isNotBlank() || publisher.isNotBlank() || releaseDate.isNotBlank() || (scored && stacked)) add(GameTab.ABOUT)
if (achievementState != null) add(GameTab.ACHIEVEMENTS)
val cloud = game?.library == Library.XBOX_CLOUD
if (game != null && !cloud) add(GameTab.LAUNCH)
if (game != null && game.library == Library.ADDED && prefix != null) add(GameTab.SAVES)
if ((game != null && !cloud) || installed != null) add(GameTab.INSTALL)
}
var picked by remember(key) { mutableStateOf<GameTab?>(null) }
val tab = picked?.takeIf { it in tabs } ?: tabs.firstOrNull()
val tabFocus = remember(key) { GameTab.entries.associateWith { FocusRequester() } }
var inPanel by remember(key) { mutableStateOf(false) }
var inPage by remember(key) { mutableStateOf(false) }
var onStrip by remember(key) { mutableStateOf(false) }
var dropped by remember(key) { mutableStateOf(0) }
// A tab's content is swapped or refreshed under the focused row; focus goes back to the tabs, not to the rail.
LaunchedEffect(dropped) {
if (dropped == 0) return@LaunchedEffect
androidx.compose.runtime.withFrameNanos { }
val t = tab ?: return@LaunchedEffect
if (!inPage) focusWithinFrames({ onStrip }) { tabFocus.getValue(t) }
}
fun cycle(step: Int) {
if (tabs.size < 2) return
val at = tabs.indexOf(tab).coerceAtLeast(0)
picked = tabs[(at + step + tabs.size) % tabs.size]
}
Column(Modifier.fillMaxWidth().onFocusChanged { inPage = it.hasFocus }.bumpers(onPrevious = { cycle(-1) }, onNext = { cycle(1) })) {
Rise(0) {
Box(Modifier.padding(bottom = 12.dp)) { BackLink(backLabel, compact = true, onClick = onBack) }
}
val hero: @Composable () -> Unit = {
DisposableEffect(Unit) { onDispose { StoresMotion.heroAt = null } }
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) },
scores = scores.takeIf { !stacked },
) {
HeroEyebrow(source, game, item, installed, download?.location ?: failed?.location)
GameTitle(title, game?.logo ?: item?.logoUrl, if (narrow) 26.sp else 34.sp)
if (!failed?.error.isNullOrBlank()) Text(
failed!!.error!!, fontSize = 13.sp, lineHeight = 17.sp, fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(4.dp))
GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead))
}
}
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
if (tab != null) Rise(2) {
Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
val labels = tabs.map { t ->
when (t) {
GameTab.ABOUT -> stringResource(R.string.game_tab_about)
GameTab.ACHIEVEMENTS -> achievementState?.list?.takeIf { it.isNotEmpty() }?.let { list ->
stringResource(R.string.game_tab_achievements_count, stringResource(R.string.achievements_title), achievementState.done, list.size)
} ?: stringResource(R.string.achievements_title)
GameTab.LAUNCH -> stringResource(R.string.game_tab_launch)
GameTab.SAVES -> stringResource(if (Store.byId(source).let { it == Store.GOG || it == Store.EPIC }) R.string.game_tab_saves_cloud else R.string.games_saves)
GameTab.INSTALL -> stringResource(R.string.game_tab_install)
}
}
TabStrip(
labels, tabs.indexOf(tab), { picked = tabs[it] }, Modifier.onFocusChanged { onStrip = it.hasFocus },
focusRequesters = tabs.map { tabFocus.getValue(it) }, bumpers = tabs.size > 1, compact = narrow,
)
Box(Modifier.fillMaxWidth().onFocusChanged { if (inPanel && !it.hasFocus) dropped++; inPanel = it.hasFocus }.testTag("game-tab-${tab.name.lowercase()}")) {
when (tab) {
GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked)
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
GameTab.INSTALL -> InstallTab(game, installed, item, store)
}
}
}
}
}
}
@Composable
private fun GameHero(
title: String, item: CatalogItem?, installed: InstalledStoreGame?, game: Library.SteamGame?, modifier: Modifier,
corner: @Composable BoxScope.() -> Unit, scores: GameScores?, content: @Composable ColumnScope.() -> Unit,
) {
val colors = MaterialTheme.colorScheme
Box(modifier.clip(Shape16).background(artBrush(hueOf(title)))) {
val wide: Any? = game?.hero ?: item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover
if (wide != null) {
// The card it came from keeps its own bitmap under the hero until the wide art is decoded.
val request = if (wide is String) cardArtRequest(wide, item?.tallImageUrl) else wide
AsyncImage(model = request, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
} else game?.art?.let { art ->
AsyncImage(
model = art, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.matchParentSize().blur(24.dp).graphicsLayer { scaleX = 1.3f; scaleY = 1.3f },
)
}
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.55f to colors.background.copy(alpha = 0.58f), 1f to Color.Transparent)))
if (scores != null) {
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0.45f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp))
}
Column(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp),
content = content,
)
Box(Modifier.align(Alignment.TopEnd).padding(12.dp), content = corner)
}
}
@Composable
private fun HeroEyebrow(source: String, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?, downloadAt: String?) {
val ctx = LocalContext.current
val pal = LocalPalette.current
val folder = installed?.folder ?: game?.gameFiles
val passName = item?.includedWith.orEmpty()
val state = when {
installed != null -> listOf(stringResource(R.string.stores_eyebrow_installed), StoreInstallRoot.labelFor(ctx, installed.folder))
game?.library == Library.XBOX_CLOUD -> listOf(libraryLabel(game))
game != null -> listOf(stringResource(R.string.stores_eyebrow_installed), libraryLabel(game))
!downloadAt.isNullOrBlank() -> listOf(stringResource(R.string.stores_eyebrow_library), downloadAt)
item?.owned == true -> listOf(stringResource(R.string.stores_eyebrow_library))
item?.subscription == true -> listOf(passName.ifBlank { stringResource(R.string.stores_game_pass) })
passName.isNotBlank() -> listOf(stringResource(R.string.stores_eyebrow_pass, passName))
item?.accessible == true -> listOf(stringResource(R.string.stores_eyebrow_library))
else -> listOf(stringResource(R.string.stores_eyebrow_store))
}
val size = if (folder != null && (installed != null || game != null)) diskSize(installed, folder) else (item?.sizeBytes ?: 0L).takeIf { it > 0 }
val line = (state + listOfNotNull(size?.let { formatBytes(it) })).filter { it.isNotBlank() }.joinToString(" · ")
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SourceChip(source)
Text(line.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@Composable
private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
var failed by remember(logo) { mutableStateOf(false) }
if (logo != null && !failed) AsyncImage(
model = logo, contentDescription = title, contentScale = ContentScale.Fit, alignment = Alignment.CenterStart,
onError = { failed = true },
modifier = Modifier.padding(vertical = 4.dp).height((titleSize.value * 2.2f).dp).widthIn(max = (titleSize.value * 9f).dp).testTag("game-logo"),
) else Text(
title, fontSize = titleSize, lineHeight = titleSize * 1.12f, fontWeight = FontWeight.Black,
color = MaterialTheme.colorScheme.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis,
)
}
@Composable
private fun GameActions(
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
s: FrontEndState, a: FrontEndActions, leadOn: Modifier,
) {
val ctx = LocalContext.current
val storeKey = if (store != null && id != null) "${store.id}:$id" else null
val rawDownload = storeKey?.let { StoresState.download(it) }
val download = rawDownload?.takeIf { it.isActive }
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
Actions {
when {
s.shortcutPicker && game != null -> {
PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
FileButtons(game, a)
}
game?.library == Library.XBOX_CLOUD -> {
val cloudId = game.storeId.orEmpty()
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
if (download != null) ActionChip(downloadLabel(download), ok = false)
else if (item?.installable == true) SecondaryButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
) { StoresState.requestInstall(ctx, item) }
XboxLibraryButton(cloudId, item)
}
game != null || installed != null -> {
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,
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)
}
if ((game?.source ?: store?.id) != Library.SOURCE_STEAM) ActionChip(stringResource(R.string.stores_in_steam), ok = true)
if (game != null) {
FileButtons(game, a)
GameShortcutMenu(game, a)
EditArtButton(game)
}
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)) {
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) }
}
}
download != null -> {
ActionChip(downloadLabel(download), ok = false)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
}
failed != null -> {
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) {
if (item != null) StoresState.requestInstall(ctx, item) else DownloadQueue.retry(ctx, failed.key)
}
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
}
store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> {
XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
XboxLibraryButton(item.id, item)
}
item?.installable == true && StoresState.isUnfinished(item) -> {
InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
}
item?.installable == true -> {
InstallButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
leadOn,
) { StoresState.requestInstall(ctx, item) }
if (store == Store.XBOX && item.xboxCloud) {
XboxStreamButton(item.id, item.title)
XboxLibraryButton(item.id, item)
}
if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
}
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
}
BusyChip(s)
}
}
/** Xbox Cloud Gaming rows the user added to the Library, for games not installed here. */
@Composable
internal fun rememberXboxCloudRows(s: FrontEndState): List<Library.SteamGame> {
val ctx = LocalContext.current
LaunchedEffect(Unit) { XboxCloudGames.load(ctx) }
if (s.shortcutPicker) return emptyList()
val added = XboxCloudGames.entries.toList()
return remember(added, s.steamGames) {
val installedXbox = s.steamGames.filter { it.source == Store.XBOX.id }.mapNotNull { it.storeId }.toSet()
XboxCloudGames.rows(ctx, installedXbox)
}
}
@Composable
private fun XboxStreamButton(id: String, title: String, main: Boolean = false, modifier: Modifier = Modifier) {
val ctx = LocalContext.current
LaunchedEffect(Unit) { XboxCloudGames.prefetch(ctx) }
val label = stringResource(R.string.game_stream)
if (main) PrimaryButton(label, main = true, icon = Icons.Filled.PlayArrow, modifier = modifier) { XboxCloudGames.stream(ctx, id, title) }
else SecondaryButton(label, modifier = modifier) { XboxCloudGames.stream(ctx, id, title) }
}
@Composable
private fun XboxInstalledStream(id: String, title: String, item: CatalogItem?) {
val ctx = LocalContext.current
val streams by produceState(item?.xboxCloud == true, id) {
if (!value) value = withContext(Dispatchers.IO) { XboxCloudGames.streams(ctx, id) }
}
if (streams) XboxStreamButton(id, title)
}
@Composable
private fun XboxLibraryButton(id: String, item: CatalogItem?) {
val ctx = LocalContext.current
LaunchedEffect(Unit) { XboxCloudGames.load(ctx) }
// Add and Remove replace each other; the controller focus moves to the new button instead of getting lost.
val slot = remember { FocusRequester() }
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
val scope = rememberCoroutineScope()
fun refocus() { if (inputMode.inputMode == androidx.compose.ui.input.InputMode.Keyboard) scope.launch { focusSoon { slot } } }
if (XboxCloudGames.isAdded(id)) {
ActionChip(stringResource(R.string.library_in), ok = true)
SecondaryButton(stringResource(R.string.library_remove), compact = true, modifier = Modifier.focusRequester(slot)) { XboxCloudGames.remove(ctx, id); refocus() }
} else if (item != null) SecondaryButton(stringResource(R.string.library_add), modifier = Modifier.focusRequester(slot)) { XboxCloudGames.add(ctx, item); refocus() }
}
@Composable
private fun buyLabel(item: CatalogItem): String = when {
item.isFree -> stringResource(R.string.stores_get_free)
item.hasPrice && item.finalPrice.isNotBlank() -> stringResource(R.string.stores_buy_price, item.finalPrice)
else -> stringResource(R.string.stores_view_on, item.store.shortLabel)
}
@Composable
private fun FileButtons(game: Library.SteamGame, a: FrontEndActions) {
game.gameFiles?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton(stringResource(R.string.games_files), compact = true) { a.onBrowseFiles(dir) } }
game.protonPrefix?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton(stringResource(R.string.games_prefix), compact = true) { a.onBrowseFiles(dir) } }
}
@Composable
private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
var open by remember(g.gameId) { mutableStateOf(false) }
Box {
SecondaryButton(stringResource(R.string.game_shortcut), compact = true) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = stringResource(R.string.game_shortcut)) { first ->
MenuItem(stringResource(R.string.game_shortcut_add), checked = false, focusRequester = first) { open = false; a.onGameShortcut(g) }
MenuItem(stringResource(R.string.game_file_export), checked = false) { open = false; a.onExportGameFile(g) }
MenuItem(stringResource(R.string.game_link_copy), checked = false) { open = false; a.onCopyGameLink(g) }
}
}
}
/** The pencil opens the editor each kind of game always had: the shortcut editor for added games, art for the rest. */
@Composable
private fun EditArtButton(g: Library.SteamGame) {
val ctx = LocalContext.current
val folder = g.gameFiles
val open: (() -> Unit)? = when {
g.library == Library.ADDED && g.source == Library.ADDED && folder != null -> {
{ GamesDialogState.editing = EditRequest(folder.path, openTarget = false, fromSummary = false, preview = EditPreview.of(ctx, g, folder.path)) }
}
g.library != Library.ADDED && g.source == Library.SOURCE_STEAM -> { { GamesDialogState.steamArt = g } }
g.library == Library.ADDED && g.source != Library.ADDED && folder != null -> { { GamesDialogState.storeArt = g } }
else -> null
}
if (open != null) IconAction(Icons.Outlined.Edit, stringResource(R.string.common_edit), "game:edit", onClick = open)
}
@Composable
private 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() }
val hot = rememberHot(src) && enabled
val accent = if (danger) colors.error else pal.signal
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem(id).downToFirstTile().size(44.dp).clip(Shape12)
.background(if (hot) accent.copy(alpha = if (danger) 0.22f else 0.14f) else if (danger) Color.Black.copy(alpha = 0.34f) else Color.White.copy(alpha = 0.03f))
.glideBorder(hot, Shape12, accent, pal.line2)
.alpha(if (enabled) 1f else 0.45f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.semantics { contentDescription = label },
) {
Icon(icon, contentDescription = null, tint = if (danger && hot) colors.error else if (danger) Color.White else colors.onBackground, modifier = Modifier.size(18.dp))
}
}
@Composable
private fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
if (installed != null) {
val key = installed.key
val gone = StoresState.uninstalling[key]
if (gone != null) {
val uninstalling = stringResource(R.string.stores_uninstalling)
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(44.dp).clip(Shape12).background(Color.Black.copy(alpha = 0.34f)).semantics { contentDescription = uninstalling }) {
if (gone > 0f) CircularProgressIndicator(progress = { gone }, strokeWidth = 2.dp, color = colors.error, trackColor = colors.error.copy(alpha = 0.22f), modifier = Modifier.size(20.dp))
else CircularProgressIndicator(strokeWidth = 2.dp, color = colors.error, modifier = Modifier.size(20.dp))
}
return
}
val heading = stringResource(R.string.stores_uninstall_title, title)
val size = StoreSizes.onDisk[key]
val body = if (size != null && size > 0) stringResource(R.string.stores_uninstall_body_size, formatBytes(size)) else stringResource(R.string.stores_uninstall_body)
val keep = stringResource(R.string.stores_notification_keep)
val remove = stringResource(R.string.stores_uninstall)
val busy = StoresState.download(key)?.isActive == true || (installed.sidecar.store == Store.XBOX && XboxContent.busy(installed.sidecar.id))
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
IconAction(Icons.Outlined.Delete, remove, "game:remove", danger = true, enabled = !busy) {
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot() ?: return@IconAction
var confirmed = false
Steps.ask(StepAsk(anchor = at, side = StepSide.Left, accent = colors.error, items = 3, pillCorner = 12.dp, maxWidth = 340.dp,
onDismiss = { if (confirmed) StoresState.uninstall(ctx, installed) { StoresState.refresh(ctx); a.onLibraryChanged() } },
handle = { Icon(Icons.Outlined.Delete, null, tint = colors.error, modifier = Modifier.size(18.dp)) }) {
StepTitle(heading)
Text(body, fontSize = 13.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) {
StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() }
StepChoice(remove, danger = true, enabled = open) { confirmed = true; Steps.fold() }
}
})
}
}
return
}
val g = game ?: return
val kind = GameRemoval.kind(g)
if (kind == GameRemoval.Kind.LAUNCHER || g.gameFiles?.isDirectory != true) return
var asking by remember(g.gameId) { mutableStateOf(false) }
val shortcut = kind == GameRemoval.Kind.SHORTCUT
val label = stringResource(if (shortcut) R.string.edit_remove else R.string.common_uninstall)
IconAction(Icons.Outlined.Delete, label, "game:remove", danger = true) { asking = true }
if (asking) ConfirmDialog(
title = if (shortcut) stringResource(R.string.games_remove_title, g.name) else stringResource(R.string.stores_uninstall_title, g.name),
text = when {
shortcut -> stringResource(R.string.games_remove_body)
g.library == Library.ADDED -> stringResource(R.string.stores_uninstall_body)
else -> stringResource(R.string.games_uninstall_body)
},
confirm = label,
onConfirm = { a.onGameRemoved(g) },
onDismiss = { asking = false },
)
}
@Composable
private fun InstallButton(label: String, modifier: Modifier = Modifier, onInstall: () -> Unit) {
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
PrimaryButton(label, main = true, modifier = modifier) {
StoresMotion.markInstall(placed[0]?.takeIf { it.isAttached }?.boundsInRoot(), label)
onInstall()
}
}
}
@Composable
private fun AboutTab(developer: String, publisher: String, releaseDate: String, description: String, scores: GameScores?, stacked: Boolean) {
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().tabPanel()) {
if (scores != null) Box(Modifier.readable()) { StoreGameFacts(developer, publisher, releaseDate, scores, scoresInHero = !stacked) }
else if (developer.isNotBlank() || publisher.isNotBlank() || releaseDate.isNotBlank()) {
val parts = listOf(developer, publisher, com.droiddeck.launcher.stores.GameFacts.releaseLabel(releaseDate).orEmpty()).filter { it.isNotBlank() }.distinct()
Text(parts.joinToString(" · "), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.readable())
}
if (description.isNotBlank()) StoreAbout(description, AboutHeight, Modifier.fillMaxWidth())
}
}
private val AboutHeight = 260.dp
@Composable
internal fun Modifier.tabPanel(): Modifier {
val shape = RoundedCornerShape(16.dp)
return clip(shape).background(MaterialTheme.colorScheme.surface).border(1.dp, LocalPalette.current.line, shape).padding(horizontal = 16.dp, vertical = 14.dp)
}
@Composable
private fun StoreAbout(text: String, height: Dp, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scroll = rememberScrollState()
val scope = rememberCoroutineScope()
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(12.dp)
Box(
modifier.heightIn(max = height).clip(shape)
.glideBorder(hot, shape, pal.signal, restColor = Color.Transparent)
.paneItem("about")
.focusable(interactionSource = src)
.onPreviewKeyEvent { e ->
val step = when (e.nativeKeyEvent.keyCode) {
android.view.KeyEvent.KEYCODE_DPAD_DOWN -> if (scroll.value < scroll.maxValue) 120f else return@onPreviewKeyEvent false
android.view.KeyEvent.KEYCODE_DPAD_UP -> if (scroll.value > 0) -120f else return@onPreviewKeyEvent false
else -> return@onPreviewKeyEvent false
}
if (e.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) scope.launch { scroll.animateScrollBy(step) }
true
},
) {
Text(text, fontSize = 14.sp, lineHeight = 21.sp, color = colors.onSurfaceVariant, modifier = Modifier.verticalScroll(scroll).padding(horizontal = 4.dp, vertical = 6.dp))
if (scroll.value < scroll.maxValue) Box(
Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(28.dp)
.background(Brush.verticalGradient(listOf(Color.Transparent, colors.surface))),
)
}
}
@Composable
private fun LaunchTab(game: Library.SteamGame, s: FrontEndState, a: FrontEndActions, hopRail: String?) {
val host = rememberMenuHost()
Column(verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) {
LaunchSettings(s, a, host, game, hopRail ?: GameRef.key(game))
val folder = game.gameFiles
if (game.library == Library.ADDED && game.source == Library.ADDED && !s.shortcutPicker && folder != null) ShortcutFields(game, folder)
}
}
@Composable
private fun ShortcutFields(game: Library.SteamGame, folder: File) {
val ctx = LocalContext.current
val preview = remember(game.gameId, game.name, GamesDialogState.editing) { EditPreview.of(ctx, game, folder.path) }
fun edit(target: Boolean) { GamesDialogState.editing = EditRequest(folder.path, openTarget = target, fromSummary = false, preview = EditPreview.of(ctx, game, folder.path)) }
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
SectionLabel(stringResource(R.string.game_launch_shortcut))
MenuItem(stringResource(R.string.edit_name), checked = false, detail = preview.name) { edit(false) }
MenuItem(stringResource(R.string.edit_target), checked = false, detail = preview.exeName ?: "—") { edit(true) }
MenuItem(stringResource(R.string.edit_start_in), checked = false, detail = preview.startIn ?: "—") { edit(false) }
MenuItem(stringResource(R.string.edit_launch_options), checked = false, detail = preview.launchOptions.ifEmpty { "—" }) { edit(false) }
}
}
@Composable
private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
val saves by produceState<List<GameSaves.SaveDir>?>(null, g.gameId) {
value = withContext(Dispatchers.IO) { runCatching { GameSaves.locate(prefix, g) }.getOrDefault(emptyList()) }
}
val found = saves
val summary = when {
found == null -> stringResource(R.string.games_saves_looking)
found.isEmpty() -> stringResource(R.string.games_saves_none)
else -> {
val mb = found.sumOf { it.bytes } / 1048576.0
stringResource(
R.string.games_saves_summary,
if (found.size == 1) found[0].relPath else stringResource(R.string.games_saves_folders, found.size),
found.sumOf { it.files },
if (mb < 1) stringResource(R.string.games_kb, (mb * 1024).toInt()) else stringResource(R.string.common_size_mb, mb),
)
}
}
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(summary, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 6.dp).readable().padding(4.dp))
if (Store.byId(g.source).let { it == Store.GOG || it == Store.EPIC }) {
SectionLabel(stringResource(R.string.store_cloud_saves))
CloudRows(g)
SectionLabel(stringResource(R.string.games_saves))
}
MenuItem(stringResource(R.string.games_import_saves), checked = false) { a.onSaveImport(g) }
MenuItem(stringResource(R.string.games_export_gamehub), checked = false) { a.onSaveExport(g, GameSaves.Layout.GAMEHUB) }
MenuItem(stringResource(R.string.games_export_winlator), checked = false) { a.onSaveExport(g, GameSaves.Layout.WINLATOR) }
found?.firstOrNull()?.let { d ->
MenuItem(stringResource(R.string.games_open_save_folder), checked = false, detail = d.relPath) {
a.onBrowseFiles(File(prefix, "drive_c/users/steamuser/" + d.relPath))
}
}
}
}
@Composable
private fun CloudRows(g: Library.SteamGame) {
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
val id = g.storeId ?: return
val context = LocalContext.current.applicationContext
var busy by remember(g.gameId) { mutableStateOf<String?>(null) }
var tick by remember(g.gameId) { mutableStateOf(0) }
val status by produceState<CloudSaves.Status?>(null, g.gameId, tick) {
value = withContext(Dispatchers.IO) { runCatching { CloudSaves.status(context, store, id) }.getOrNull() }
}
val folder = g.gameFiles
var enabled by remember(g.gameId) { mutableStateOf(folder?.let { StoreGameSidecar.read(it)?.cloud } ?: true) }
val st = status
val supported = st?.supported ?: true
val conflict = st != null && st.conflicts.isNotEmpty()
fun sync(up: Boolean, force: Boolean = false) {
if (busy != null) return
busy = if (up) "up" else "down"
Thread({
val r = if (up) CloudSaves.upload(context, store, id, force) else CloudSaves.download(context, store, id, force)
StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() }
}, "cloud-manual").start()
}
MenuItem(stringResource(R.string.store_cloud_saves), checked = enabled && supported, enabled = supported,
detail = if (!supported) stringResource(R.string.cloud_none) else null) {
val f = folder ?: return@MenuItem
val next = !enabled
Thread({
val written = runCatching { StoreGameSidecar.updateCloud(f, next) }.getOrNull()
StoresState.post { enabled = written?.cloud ?: enabled }
}, "cloud-switch").start()
}
val ready = st != null && supported && enabled && busy == null
val pending = stringResource(R.string.cloud_pending)
val summary = when {
st == null || busy != null -> pending
!supported -> stringResource(R.string.cloud_none)
conflict -> stringResource(R.string.cloud_conflict_files, st.conflicts.size)
st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString())
else -> stringResource(R.string.cloud_never)
}
MenuItem(stringResource(if (conflict) R.string.cloud_keep_local else R.string.cloud_upload), checked = false, enabled = ready, detail = summary) { sync(up = true, force = conflict) }
MenuItem(stringResource(if (conflict) R.string.cloud_keep_cloud else R.string.cloud_download), checked = false, enabled = ready, detail = if (st == null || busy != null) pending else null) { sync(up = false, force = conflict) }
}
@Composable
private fun InstallTab(game: Library.SteamGame?, installed: InstalledStoreGame?, item: CatalogItem?, store: Store?) {
val ctx = LocalContext.current
val folder = installed?.folder ?: game?.gameFiles
val sidecar = installed?.sidecar
val size = folder?.let { diskSize(installed, it) }
val rows = buildList {
add(stringResource(R.string.game_install_location) to when {
installed != null -> StoreInstallRoot.labelFor(ctx, installed.folder)
game != null -> libraryLabel(game).ifBlank { stringResource(R.string.games_internal) }
else -> ""
})
if (folder != null) {
add(stringResource(R.string.game_install_folder) to folder.path)
add(stringResource(R.string.game_install_size) to (size?.let { formatBytes(it) } ?: stringResource(R.string.cloud_pending)))
}
sidecar?.extra?.get(StoreLanguage.EXTRA)?.takeIf { it.isNotBlank() }?.let { add(stringResource(R.string.stores_install_language) to StoreLanguage.displayName(it)) }
sidecar?.installVersion?.takeIf { it.isNotBlank() }?.let { add(stringResource(R.string.game_install_version) to it) }
sidecar?.installedAt?.takeIf { it > 0 }?.let {
add(stringResource(R.string.game_install_date) to java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).format(java.util.Date(it)))
}
if (game != null) add(stringResource(R.string.game_install_played) to (playedSpan(game.lastPlayed)?.replaceFirstChar { it.uppercase() } ?: stringResource(R.string.games_never_played)))
if (store == Store.XBOX) {
val access = sidecar?.extra?.get("access") ?: if (item?.subscription == true) "gamepass" else if (item?.owned == true) "owned" else null
if (access != null) add(stringResource(R.string.game_install_access) to stringResource(if (access == "gamepass") R.string.stores_game_pass else R.string.game_install_access_owned))
}
}.filter { it.second.isNotBlank() }
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
for ((label, value) in rows) FactRow(label, value)
}
}
/** Text a controller has to land on to bring it into view: focusable, with the focus ring. */
@Composable
internal fun Modifier.readable(): Modifier {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(8.dp)
return clip(shape).glideBorder(hot, shape, pal.signal, restColor = Color.Transparent).focusable(interactionSource = src)
}
@Composable
private fun FactRow(label: String, value: String) {
Row(
horizontalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.fillMaxWidth().readable().padding(horizontal = 8.dp, vertical = 7.dp),
) {
Text(label, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.width(150.dp))
Text(value, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.weight(1f), maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
/** Store installs are measured by [StoreSizes]; Steam and added games by walking their folder once. */
@Composable
internal fun diskSize(installed: InstalledStoreGame?, folder: File): Long? {
val ctx = LocalContext.current
if (installed != null) {
LaunchedEffect(installed.key) { StoreSizes.requestDisk(ctx, installed.key, installed) }
return StoreSizes.onDisk[installed.key]
}
LaunchedEffect(folder.path) { FolderSizes.request(folder) }
return FolderSizes.known[folder.path]
}
internal object FolderSizes {
val known = androidx.compose.runtime.mutableStateMapOf<String, Long>()
private val asked = java.util.Collections.synchronizedSet(HashSet<String>())
fun request(folder: File) {
if (!asked.add(folder.path)) return
Thread({
var total = 0L
val walked = runCatching {
java.nio.file.Files.walkFileTree(folder.toPath(), object : java.nio.file.SimpleFileVisitor<java.nio.file.Path>() {
override fun visitFile(file: java.nio.file.Path, attrs: java.nio.file.attribute.BasicFileAttributes): java.nio.file.FileVisitResult {
if (attrs.isRegularFile) total += attrs.size()
return java.nio.file.FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException): java.nio.file.FileVisitResult = java.nio.file.FileVisitResult.CONTINUE
})
}.isSuccess
if (walked) StoresState.post { known[folder.path] = total } else asked.remove(folder.path)
}, "folder-size").start()
}
}
@@ -0,0 +1,145 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.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.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.itch.ItchBrowse
import com.droiddeck.launcher.stores.itch.ItchBrowseState
@Composable
internal fun ItchBrowseBar() {
val ctx = LocalContext.current
val query = ItchBrowseState.query
var picking by remember { mutableStateOf(false) }
Column(Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
ChipRow {
for (sort in ItchBrowse.sorts) BrowseChip(sortLabel(sort), query.sort == sort) { ItchBrowseState.choose(ctx, query.copy(sort = sort)) }
}
ChipRow {
for (price in ItchBrowse.prices) BrowseChip(priceLabel(price), query.price == price) { ItchBrowseState.choose(ctx, query.copy(price = price)) }
}
ChipRow {
BrowseChip(stringResource(R.string.stores_itch_platform_any), query.platforms.isEmpty()) { ItchBrowseState.choose(ctx, query.copy(platforms = emptySet())) }
for (platform in ItchBrowse.platformNames) {
val on = platform in query.platforms
BrowseChip(platformLabel(platform), on) { ItchBrowseState.choose(ctx, query.copy(platforms = if (on) query.platforms - platform else query.platforms + platform)) }
}
}
ChipRow {
for (tag in query.tags) BrowseChip("$tag ✕", true) { ItchBrowseState.choose(ctx, query.copy(tags = query.tags - tag)) }
BrowseChip(stringResource(R.string.stores_itch_tag_add), false) { picking = true }
}
}
if (picking) TextEntryDialog(
stringResource(R.string.stores_itch_tag_title), "", number = false, confirm = stringResource(R.string.common_ok),
onSubmit = { value -> ItchBrowse.tagSlug(value).takeIf { it.isNotEmpty() }?.let { ItchBrowseState.choose(ctx, query.copy(tags = (query.tags + it).distinct())) } },
onDismiss = { picking = false }, id = "itch-tag",
)
}
@Composable
internal fun ItchLoadMore() {
val ctx = LocalContext.current
val count = ItchBrowseState.items.size
LaunchedEffect(Unit) { ItchBrowseState.more(ctx) }
if (ItchBrowseState.loading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 12.dp))
else if (ItchBrowseState.failed) Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
BrowseChip(stringResource(R.string.stores_dl_retry), false) { ItchBrowseState.more(ctx, retry = true) }
}
else if (!ItchBrowseState.ended && count > 0) Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
BrowseChip(stringResource(R.string.stores_itch_load_more), false) { ItchBrowseState.more(ctx) }
}
}
@Composable
private fun ChipRow(content: @Composable () -> Unit) {
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).selectableGroup(),
) { content() }
}
@Composable
private fun BrowseChip(label: String, selected: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(8.dp)
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Text(
label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1,
color = if (selected) pal.onSignal else if (hot) colors.onBackground else colors.onSurfaceVariant,
modifier = Modifier.clip(shape).background(if (selected) pal.signal else colors.surfaceVariant)
.glideBorder(hot, shape, pal.signal)
.hoverable(src).selectable(selected = selected, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 7.dp),
)
}
@Composable
private fun sortLabel(sort: String): String = stringResource(
when (sort) {
ItchBrowse.SORT_NEW_POPULAR -> R.string.stores_itch_sort_new_popular
ItchBrowse.SORT_TOP_SELLERS -> R.string.stores_itch_sort_top_sellers
ItchBrowse.SORT_TOP_RATED -> R.string.stores_itch_sort_top_rated
ItchBrowse.SORT_NEWEST -> R.string.stores_itch_sort_new
else -> R.string.stores_itch_sort_popular
},
)
@Composable
private fun platformLabel(platform: String): String = stringResource(
when (platform) {
"windows" -> R.string.stores_itch_platform_windows
"osx" -> R.string.stores_itch_platform_macos
"linux" -> R.string.stores_itch_platform_linux
"android" -> R.string.stores_itch_platform_android
"ios" -> R.string.stores_itch_platform_ios
"web" -> R.string.stores_itch_platform_web
else -> R.string.stores_itch_platform_mobile_web
},
)
@Composable
private fun priceLabel(price: String): String = stringResource(
when (price) {
ItchBrowse.PRICE_FREE -> R.string.stores_itch_price_free
ItchBrowse.PRICE_SALE -> R.string.stores_itch_price_sale
ItchBrowse.PRICE_PAID -> R.string.stores_itch_price_paid
ItchBrowse.PRICE_UNDER_5 -> R.string.stores_itch_price_under_5
ItchBrowse.PRICE_UNDER_15 -> R.string.stores_itch_price_under_15
else -> R.string.stores_itch_price_any
},
)
@@ -0,0 +1,690 @@
package com.droiddeck.launcher.ui
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.horizontalScroll
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.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridScope
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.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material.icons.filled.ViewList
import androidx.compose.material.icons.filled.ViewModule
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.retainOrder
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
import com.droiddeck.launcher.stores.sortGames
import kotlinx.coroutines.launch
import androidx.compose.runtime.setValue
/** One owned game: installed ones carry their [game], store products not installed yet only their [item]. */
internal class LibraryEntry(
val key: String, val source: String, val title: String,
val game: Library.SteamGame?, val item: CatalogItem?, val installed: Boolean,
) {
val storeKey: String? get() = item?.key ?: game?.storeId?.let { "${game.source}:$it" }
}
/** Installed games first claim their store product, so a game owned and installed shows once. */
internal fun libraryEntries(
games: List<Library.SteamGame>, owned: Map<Store, List<CatalogItem>>, installedStore: Set<String>,
): List<LibraryEntry> {
val claimed = HashSet<String>()
val out = ArrayList<LibraryEntry>()
for (g in games) {
if (g.library == Library.EPIC_LAUNCHER) continue
val storeKey = g.storeId?.let { "${g.source}:$it" }
val item = storeKey?.let { k -> Store.byId(g.source)?.let { st -> owned[st]?.firstOrNull { it.key == k } } }
if (storeKey != null) claimed += storeKey
out += LibraryEntry(GameRef.key(g), g.source, g.name, g, item, installed = true)
}
for (store in Store.entries) for (item in owned[store].orEmpty()) {
if (!claimed.add(item.key)) continue
out += LibraryEntry(GameRef.key(item), store.id, item.title, null, item, installed = item.key in installedStore)
}
return out.distinctBy { it.key }
}
internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off }
internal const val LIBRARY_ALL = "all"
internal val LIBRARY_SOURCES = listOf(Library.SOURCE_STEAM) + Store.entries.map { it.id } + Library.ADDED
/** Survives leaving the page, so Stores can open the Library on one store's owned games. */
internal object LibraryView {
var source by mutableStateOf(LIBRARY_ALL)
var query by mutableStateOf("")
var focusFirst = false
fun showOwned(store: Store) {
source = store.id
query = ""
focusFirst = true
}
}
@Composable
internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, onSelect: (String) -> Unit, modifier: Modifier) {
val ctx = LocalContext.current
val narrow = LocalNarrowPane.current
val ff = LocalFrontFocus.current
val focusManager = androidx.compose.ui.platform.LocalFocusManager.current
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
LaunchedEffect(Unit) { StoresState.refresh(ctx) }
val stores = s.gameStoresEnabled && !s.shortcutPicker
val signedIn = Store.entries.filter { StoresState.isSignedIn(it) }
LaunchedEffect(stores, signedIn) { if (stores) signedIn.forEach { StoresState.loadLibrary(ctx, it) } }
val owned = if (stores) signedIn.associateWith { StoresState.library[it].orEmpty() } else emptyMap()
val installedStore = StoresState.installed.map { it.key }.toSet()
val syncing = if (stores) signedIn.mapNotNull { st -> StoresState.status[st]?.let { st to it } } else emptyList()
val cloudRows = rememberXboxCloudRows(s)
val all = remember(s.steamGames, cloudRows, owned, installedStore) { libraryEntries(s.steamGames + cloudRows, owned, installedStore) }
LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) }
val sources = LIBRARY_SOURCES.filter { src -> all.any { it.source == src } }
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
val candidates = all.filter {
(source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
}
val sort = s.storesSort
val sizeSort = sort == "sizeAsc" || sort == "sizeDesc"
val installedAt = StoresState.installed.associate { it.key to it.sidecar.installedAt }
val lastPlayed = s.steamGames.filter { it.storeId != null }.associate { "${it.source}:${it.storeId}" to it.lastPlayed }
fun sizeOf(e: LibraryEntry): Long? {
val key = e.storeKey
return when {
key != null && key in installedStore -> StoreSizes.onDisk[key]
e.game?.gameFiles != null -> FolderSizes.known[e.game.gameFiles.path]
e.item != null -> StoreSizes.size(e.item).takeIf { it > 0 }
else -> 0L
}
}
LaunchedEffect(sizeSort, candidates.map { it.key }) {
if (!sizeSort) return@LaunchedEffect
for (e in candidates) {
val key = e.storeKey
val inst = key?.let { k -> StoresState.installed.firstOrNull { it.key == k } }
when {
inst != null -> StoreSizes.requestDisk(ctx, inst.key, inst)
e.game?.gameFiles != null -> FolderSizes.request(e.game.gameFiles)
e.item != null && e.item.accessible -> StoreSizes.request(ctx, e.item)
}
}
}
var sizesWaited by remember(sizeSort) { mutableStateOf(false) }
LaunchedEffect(sizeSort) { if (sizeSort) { kotlinx.coroutines.delay(8_000); sizesWaited = true } }
val sizesPending = sizeSort && !sizesWaited && candidates.any { sizeOf(it) == null }
val sorted = sortGames(
candidates, sort, title = { it.title }, releaseDate = { it.item?.releaseDate.orEmpty() },
lastPlayed = { e -> e.game?.lastPlayed ?: e.storeKey?.let { lastPlayed[it] } ?: 0L },
installedAt = { e -> e.storeKey?.let { installedAt[it] } ?: 0L },
size = { e -> sizeOf(e) ?: 0L },
)
var stable by remember { mutableStateOf(emptyList<LibraryEntry>()) }
val ordered = if (sizesPending) retainOrder(candidates, stable) { it.key } else sorted
SideEffect { if (!sizesPending) stable = sorted }
val visible = installedFirst(ordered)
val split = visible.count { it.installed }.takeIf { it in 1 until visible.size } ?: 0
val open = selected.takeIf { it.startsWith("app:") }
val back = { onSelect("games") }
BackHandler(enabled = open != null) { back() }
val lead = remember { FocusRequester() }
var detailFocused by remember { mutableStateOf(false) }
var lastOpened by remember { mutableStateOf<String?>(null) }
val wasOpen = remember { booleanArrayOf(false) }
val backLabel = stringResource(R.string.rail_games)
LaunchedEffect(open) {
val closing = open == null && wasOpen[0]
wasOpen[0] = open != null
if (open != null) lastOpened = open
else if (!closing) return@LaunchedEffect
if (inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard || ff == null) return@LaunchedEffect
repeat(60) { if (!HeldKeys.confirm) return@repeat; androidx.compose.runtime.withFrameNanos { } }
if (open != null) {
val backId = "back:$backLabel"
repeat(45) { n ->
androidx.compose.runtime.withFrameNanos { }
if (detailFocused) return@LaunchedEffect
val req = if (n < 20) lead else ff.items[backId]?.takeIf { (ff.attached[backId] ?: 0) > 0 } ?: lead
runCatching { req.requestFocus() }
}
return@LaunchedEffect
}
val id = lastOpened?.let { "card:$it" }
repeat(45) {
androidx.compose.runtime.withFrameNanos { }
if (id != null && ff.last == id) return@LaunchedEffect
val card = id?.let { ff.items[it] }?.takeIf { (ff.attached[id] ?: 0) > 0 }
if (card != null) runCatching { card.requestFocus() }
else if (ff.firstTileAttached > 0 && runCatching { ff.firstTile.requestFocus() }.isSuccess) return@LaunchedEffect
}
}
LaunchedEffect(Unit) {
if (!LibraryView.focusFirst || ff == null) return@LaunchedEffect
LibraryView.focusFirst = false
if (inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
kotlinx.coroutines.delay(Motion.ms(240).toLong())
focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
}
if (all.isEmpty() && open == null) {
LibraryEmpty(s, a, modifier)
return
}
val grid = remember { LazyGridState() }
val detailScroll = rememberScrollState()
var cycled by remember { mutableIntStateOf(0) }
var gridFocused by remember { mutableStateOf(false) }
LaunchedEffect(source, sort) { grid.scrollToItem(0) }
LaunchedEffect(cycled) {
if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
focusWithinFrames({ gridFocused }) {
if (ff.firstTileAttached > 0) ff.firstTile else ff.items["libchip:$source"] ?: FocusRequester.Default
}
}
CardDetailHost(
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),
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, all.size, sources, source, sizesPending, syncing,
onSource = { LibraryView.source = it },
onCycle = { step ->
val ids = listOf(LIBRARY_ALL) + sources
LibraryView.source = ids[(ids.indexOf(source).coerceAtLeast(0) + step + ids.size) % ids.size]
cycled++
},
onOpen = { focusManager.clearFocus(force = true); onSelect(it) },
searchCleared = open != null,
onFocus = { gridFocused = it },
)
},
) { key -> GameDetail(key, s, a, lead, backLabel, hopRail = "games", onBack = back) }
}
@Composable
private fun LibraryEmpty(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
val narrow = LocalNarrowPane.current
Column(modifier = modifier.padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
Rise(0) {
PageHeader(stringResource(R.string.rail_games)) {
if (s.steamGamesX64) ClientTag()
if (!s.shortcutPicker) AddGameButton { GamesDialogState.adding = true }
}
}
Rise(1) { Note(stringResource(if (s.shortcutPicker && s.shortcutLibraryScanning) R.string.game_shortcut_scanning else R.string.games_empty)) }
if (!s.shortcutPicker) Rise(2) {
Actions {
PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp).testTag("play-steam"), onClick = a.onPlay)
}
}
Box(Modifier.padding(top = 12.dp)) { GameFileFolderActions(s, a) }
}
}
@Composable
private fun LibraryGrid(
s: FrontEndState, a: FrontEndActions, grid: LazyGridState, visible: List<LibraryEntry>, split: Int, total: Int,
sources: List<String>, source: String, sizesPending: Boolean, syncing: List<Pair<Store, String>>,
onSource: (String) -> Unit, onCycle: (Int) -> Unit, onOpen: (String) -> Unit, onFocus: (Boolean) -> Unit, searchCleared: Boolean,
) {
val listMode = s.storesView == "list"
val capsules = s.storesView == "capsules"
val tileWidth = if (capsules) CapsuleWidth else CardWidth
val focus = LocalFrontFocus.current
val scope = rememberCoroutineScope()
val density = androidx.compose.ui.platform.LocalDensity.current
var columns by remember { mutableIntStateOf(1) }
val headerItems = 2 + (if (sizesPending) 1 else 0) + syncing.size
val tile: @Composable (LibraryEntry) -> Unit = { e ->
val first = e.key == visible.firstOrNull()?.key
val navigation = if (focus == null) Modifier else Modifier.onPreviewKeyEvent { event ->
val key = event.nativeKeyEvent
val direction = when (key.keyCode) {
KeyEvent.KEYCODE_DPAD_DOWN -> 1
KeyEvent.KEYCODE_DPAD_UP -> -1
else -> 0
}
val index = visible.indexOfFirst { it.key == e.key }
val next = storeGridNeighbor(index, visible.size, if (listMode) 1 else columns, direction, split)
when {
direction == 0 || index < 0 -> false
next == null -> direction > 0
else -> {
if (key.action == KeyEvent.ACTION_DOWN) {
val target = "card:${visible[next].key}"
val targetIndex = headerItems + next + if (split == 0) 0 else if (next < split) 1 else 2
val shown = grid.layoutInfo.visibleItemsInfo.any { it.index == targetIndex }
if (!shown || (focus.attached[target] ?: 0) == 0 ||
runCatching { focus.items.getValue(target).requestFocus() }.isFailure) scope.launch {
grid.scrollToItem(targetIndex)
focusWithinFrames({ focus.last == target }) { focus.items[target] ?: FocusRequester.Default }
}
}
true
}
}
}
val picker = s.shortcutPicker && e.game != null
val choose = if (picker) ({ a.onSteamGame(e.game!!) }) else null
if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen)
}
LazyVerticalGrid(
columns = if (listMode) GridCells.Fixed(1) else GridCells.Adaptive(tileWidth), state = grid,
modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup().bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }).onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
val minimum = with(density) { (if (listMode) CardWidth * 2 else tileWidth).roundToPx() }
columns = ((it.width + gap) / (minimum + gap)).coerceAtLeast(1)
},
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
) {
item(key = "header", span = { GridItemSpan(maxLineSpan) }) { Rise(0) { LibraryHeader(s, a, total, searchCleared, xbox = source == Store.XBOX.id) } }
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
Rise(1) { LibraryFilters(sources, source, onSource) }
}
for ((store, line) in syncing) item(key = "sync-${store.id}", span = { GridItemSpan(maxLineSpan) }) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
Text(store.shortLabel + " · " + line, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (syncCount(line) != null) SyncBar(line)
else androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().padding(bottom = 8.dp).height(3.dp))
}
}
if (sizesPending) item(key = "size-sort-progress", span = { GridItemSpan(maxLineSpan) }) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 4.dp)) {
androidx.compose.material3.LinearProgressIndicator(Modifier.weight(1f).height(3.dp))
Text(stringResource(R.string.store_section_loading), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
val empty = R.string.stores_nothing_matches
if (split == 0) libraryGrid(visible, empty, tile)
else {
item(key = "installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_installed)) }
libraryGrid(visible.take(split), empty, tile)
item(key = "not-installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_not_installed)) }
libraryGrid(visible.drop(split), empty, tile)
}
}
}
private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, tile: @Composable (LibraryEntry) -> Unit) {
if (entries.isEmpty()) item(key = "empty", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.padding(vertical = 32.dp).fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(stringResource(empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
else items(entries, key = { it.key }, contentType = { "game" }) { tile(it) }
}
@Composable
private fun LibraryHeader(s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean) {
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
ModeHeader(
stringResource(R.string.rail_games), LibraryView.query, { LibraryView.query = it },
placeholder = stringResource(R.string.stores_search_library),
clearSearchFocus = searchCleared,
lead = {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
Text(stringResource(R.string.rail_games), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
Text(pluralStringResource(R.plurals.mode_added_count, total, total), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
if (s.steamGamesX64 && !narrow) ClientTag()
}
},
) {
if (xbox) XboxFilterButton()
SortButton(s, a)
ViewButton(s, a)
GameFileFolderActions(s, a)
if (!s.shortcutPicker) AddGameButton { GamesDialogState.adding = true }
}
if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() }
}
@Composable
private fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit) {
if (sources.size < 2) return
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(top = 4.dp, bottom = 2.dp),
) {
SourceFilterChip(LIBRARY_ALL, stringResource(R.string.stores_tab_all), source == LIBRARY_ALL, dot = null) { onSource(LIBRARY_ALL) }
for (src in sources) {
val store = Store.byId(src)
val dot = when {
store != null -> sourceColours(src).dot.copy(alpha = if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f)
src == Library.SOURCE_STEAM -> sourceColours(src).dot
else -> null
}
SourceFilterChip(src, if (src == Library.ADDED) stringResource(R.string.library_filter_added) else store?.shortLabel ?: sourceLabel(src), source == src, dot) { onSource(src) }
}
}
}
@Composable
private fun SourceFilterChip(key: String, label: String, on: Boolean, dot: Color?, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(99.dp)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp),
modifier = Modifier.paneItem("libchip:$key").testTag("library-source-$key").heightIn(min = 40.dp).clip(shape)
.background(if (on) pal.signal.copy(alpha = 0.16f) else colors.surface)
.glideBorder(hot, shape, pal.signal, if (on) pal.signal else pal.line)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape))
Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (on || hot) colors.onBackground else colors.onSurfaceVariant, maxLines = 1)
}
}
private fun entryArt(e: LibraryEntry, tall: Boolean): Any? {
val inst = e.storeKey?.let { k -> StoresState.installed.firstOrNull { it.key == k } }
val wide: Any? = e.game?.hero ?: e.item?.imageUrl ?: inst?.sidecar?.hero ?: inst?.sidecar?.cover
val portrait: Any? = e.game?.art ?: e.item?.tallImageUrl ?: inst?.sidecar?.cover
return if (tall) portrait ?: wide else wide ?: portrait
}
@Composable
private fun LibraryTile(e: LibraryEntry, capsule: Boolean, first: Boolean, navigation: Modifier, choose: (() -> Unit)?, onOpen: (String) -> Unit) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.985f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "tileScale")
val download = e.storeKey?.let { StoresState.download(it) }?.takeIf { it.isActive }
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
val corner = with(androidx.compose.ui.platform.LocalDensity.current) { 10.dp.toPx() }
val wide = entryArt(e, tall = false)
val tall = entryArt(e, tall = true)
RequestSize(e)
val open = {
val art = if (capsule) tall else wide
placed[0]?.takeIf { it.isAttached }?.let { StoresMotion.markCard(CardMark(e.key, it.boundsInRoot(), corner, (art as? java.io.File)?.path ?: art as? String)) }
onOpen(e.key)
}
Column(
modifier = Modifier.fillMaxWidth().onGloballyPositioned { placed[0] = it }
.then(navigation).paneItem("card:${e.key}").then(if (first) Modifier.firstTile().paneEntry() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale }
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open)
.controllerConfirm(onClick = choose ?: open),
) {
CardFace(e.title, wide, tall, download, hot, capsule, dim = !e.installed && download == null,
badge = { SourceChip(e.source, small = true, modifier = Modifier.align(Alignment.TopStart).padding(6.dp)) }) {
LibraryMarker(e, download)
}
}
}
@Composable
private fun RequestSize(e: LibraryEntry) {
val ctx = LocalContext.current
val item = e.item?.takeIf { !e.installed && it.accessible && it.sizeBytes <= 0 } ?: return
LaunchedEffect(item.key) { StoreSizes.request(ctx, item) }
}
@Composable
private fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
val pal = LocalPalette.current
when {
download != null -> Text("${download.percent}%", fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
e.installed -> Unit
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 -> Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
}
}
@Composable
private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, choose: (() -> Unit)?, onOpen: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val download = e.storeKey?.let { StoresState.download(it) }?.takeIf { it.isActive }
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
val corner = with(androidx.compose.ui.platform.LocalDensity.current) { 10.dp.toPx() }
val wide = entryArt(e, tall = false)
val open = {
placed[0]?.takeIf { it.isAttached }?.let { StoresMotion.markCard(CardMark(e.key, it.boundsInRoot(), corner, (wide as? java.io.File)?.path ?: wide as? String)) }
onOpen(e.key)
}
RequestSize(e)
val inst = e.storeKey?.let { k -> StoresState.installed.firstOrNull { it.key == k } }
val folder = inst?.folder ?: e.game?.gameFiles
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 -> 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)
}
val meta = listOfNotNull(status, size?.let { formatBytes(it) }?.takeIf { it.isNotEmpty() })
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 64.dp).onGloballyPositioned { placed[0] = it }.then(navigation).paneItem("card:${e.key}")
.then(if (first) Modifier.firstTile().paneEntry() else Modifier)
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open)
.controllerConfirm(onClick = choose ?: open)
.padding(horizontal = 10.dp, vertical = 8.dp),
) {
Box(Modifier.width(96.dp).height(54.dp).clip(RoundedCornerShape(8.dp)).background(artBrush(hueOf(e.title))).graphicsLayer { alpha = if (e.installed || download != null) 1f else 0.55f }) {
if (wide != null) AsyncImage(model = wide, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(e.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SourceChip(e.source, small = true)
Text(meta.joinToString(" · "), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
if (download != null) Text("${download.percent}%", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
else if (!e.installed) Icon(Icons.Outlined.Download, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
@Composable
private 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() }
val hot = rememberHot(src)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("btn:$key").size(32.dp).clip(CircleShape).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, CircleShape, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = description },
) { Icon(icon, null, tint = if (hot) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(18.dp)) }
}
/** Choosing Library in the rail lands on the first game, as Play Steam does on the Steam page. */
@Composable
private fun Modifier.paneEntry(): Modifier {
val ff = LocalFrontFocus.current ?: return this
androidx.compose.runtime.DisposableEffect(ff) {
ff.primaryAttached++
onDispose { ff.primaryAttached-- }
}
return focusRequester(ff.primary)
}
internal fun keepsXbox(filter: String, e: LibraryEntry): Boolean = when {
filter == XboxLibraryFilter.ALL || e.source != Store.XBOX.id -> true
e.game?.library == Library.XBOX_CLOUD -> filter == XboxLibraryFilter.CLOUD
else -> e.item?.let { XboxLibraryFilter.keeps(filter, it) } == true
}
@Composable
private fun xboxFilterLabel(filter: String): String = when (filter) {
XboxLibraryFilter.OWNED -> stringResource(R.string.game_install_access_owned)
XboxLibraryFilter.GAME_PASS -> stringResource(R.string.xbox_filter_game_pass)
XboxLibraryFilter.CLOUD -> stringResource(R.string.xbox_filter_cloud)
else -> stringResource(R.string.stores_tab_all)
}
@Composable
private fun XboxFilterButton() {
val pal = LocalPalette.current
val ctx = LocalContext.current
val title = stringResource(R.string.xbox_filter_show)
var at by remember { mutableStateOf<Rect?>(null) }
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
HeaderIconButton(title + " · " + xboxFilterLabel(XboxLibraryFilter.current), Icons.Filled.FilterList, "xbox-filter") {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = XboxLibraryFilter.ALL_FILTERS.size,
handle = { Text(title, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis) },
) {
StepTitle(title)
StepList {
XboxLibraryFilter.ALL_FILTERS.forEachIndexed { i, filter ->
StepChoice(
xboxFilterLabel(filter), selected = filter == XboxLibraryFilter.current, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (filter == XboxLibraryFilter.current) Modifier.focusRequester(first) else Modifier),
) {
XboxLibraryFilter.set(ctx, filter)
Steps.fold()
}
}
}
})
}
}
}
@Composable
private fun SortButton(s: FrontEndState, a: FrontEndActions) {
val pal = LocalPalette.current
val title = stringResource(R.string.stores_sort)
var at by remember { mutableStateOf<Rect?>(null) }
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
HeaderIconButton(title, Icons.Filled.Sort, "sort") {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = SessionPrefs.STORES_SORTS.size,
handle = { Text(title, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis) },
) {
StepTitle(title)
StepList {
SessionPrefs.STORES_SORTS.forEachIndexed { i, sort ->
val label = when (sort) {
"lastPlayed" -> stringResource(R.string.stores_sort_last_played)
"recentlyInstalled" -> stringResource(R.string.stores_sort_recently_installed)
"titleAsc" -> stringResource(R.string.stores_sort_title_asc)
"titleDesc" -> stringResource(R.string.stores_sort_title_desc)
"sizeDesc" -> stringResource(R.string.stores_sort_size_desc)
"sizeAsc" -> stringResource(R.string.stores_sort_size_asc)
else -> stringResource(R.string.stores_sort_release_date)
}
StepChoice(
label, selected = sort == s.storesSort, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (sort == s.storesSort) Modifier.focusRequester(first) else Modifier),
) {
a.onStoresSort(sort)
Steps.fold()
}
}
}
})
}
}
}
@Composable
private fun ViewButton(s: FrontEndState, a: FrontEndActions) {
val views = SessionPrefs.STORES_VIEWS
val next = views[(views.indexOf(s.storesView) + 1) % views.size]
HeaderIconButton(
stringResource(when (next) { "capsules" -> R.string.stores_view_capsules; "list" -> R.string.stores_view_list; else -> R.string.stores_view_cards }),
when (next) { "capsules" -> Icons.Filled.ViewModule; "list" -> Icons.Filled.ViewList; else -> Icons.Filled.GridView },
"view",
) { a.onStoresView(next) }
}
@@ -0,0 +1,385 @@
package com.droiddeck.launcher.ui
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.os.RemoteException
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
// sdl3bridge: SDL3Bridge settings tab
/**
* DroidDeck's link to the SDL3 bridge app's settings. A connection of its own (not DualSenseBridge's): it never
* registers for controller frames, it only asks for the settings state (MSG_SETTINGS_GET, once a second while
* the tab is open) and sends single changes (MSG_SETTINGS_SET); the bridge answers both with MSG_SETTINGS.
* The bridge sends the choices too (mode names, button names, ...), so nothing here has to match its lists.
*/
internal object SdlBridgeLink {
private const val ACTION = "com.example.dsedge.BRIDGE"
private const val SCREEN = "com.example.dsedge.BridgeActivity"
// the bridge built into this app (SDL3DroidDeck), else the separate SDL3Bridge app
private fun pkg(ctx: Context) = com.droiddeck.launcher.input.DualSenseBridge.bridgePackage(ctx)
private const val MSG_SETTINGS_GET = 40
private const val MSG_SETTINGS_SET = 41
private const val MSG_SETTINGS = 42
var snapshot by mutableStateOf<Bundle?>(null)
private set
private var server: Messenger? = null
private var bound = false
private var users = 0
private val inbox = Messenger(object : Handler(Looper.getMainLooper()) {
override fun handleMessage(m: Message) {
if (m.what == MSG_SETTINGS) snapshot = Bundle(m.data)
}
})
private val conn = object : ServiceConnection {
override fun onServiceConnected(n: ComponentName, b: IBinder) {
server = Messenger(b)
refresh()
}
override fun onServiceDisconnected(n: ComponentName) { server = null }
}
fun installed(ctx: Context): Boolean = try { ctx.packageManager.getPackageInfo(pkg(ctx), 0); true } catch (_: Exception) { false }
fun start(ctx: Context) {
users++
if (bound) return
bound = try {
ctx.applicationContext.bindService(Intent(ACTION).setPackage(pkg(ctx)), conn, Context.BIND_AUTO_CREATE)
} catch (_: Exception) { false }
}
fun stop(ctx: Context) {
users = maxOf(0, users - 1)
if (users > 0 || !bound) return
try { ctx.applicationContext.unbindService(conn) } catch (_: Exception) {}
bound = false
server = null
}
fun connected(): Boolean = server != null
fun refresh() = send(Message.obtain(null, MSG_SETTINGS_GET))
/** One change. Shown at once; the bridge's answer then confirms it. */
fun set(key: String, p: Int = 0, i: Int = 0, int: Int? = null, bool: Boolean? = null) {
snapshot?.let { old -> snapshot = Bundle(old).also { applyLocally(it, key, p, i, int, bool) } }
send(Message.obtain(null, MSG_SETTINGS_SET).apply {
data = Bundle().apply {
putString("key", key); putInt("p", p); putInt("i", i)
if (int != null) putInt("int", int)
if (bool != null) putBoolean("bool", bool)
}
})
}
/** The bridge's own screen (controller test, USB access, ...): in this app when built in, else SDL3Bridge. */
fun open(ctx: Context) {
val screen = Intent().setClassName(pkg(ctx), SCREEN).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try { ctx.startActivity(screen) } catch (_: Exception) {
val launch = ctx.packageManager.getLaunchIntentForPackage(pkg(ctx)) ?: return
try { ctx.startActivity(launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {}
}
}
private fun send(m: Message) {
val s = server ?: return
m.replyTo = inbox
try { s.send(m) } catch (_: RemoteException) { server = null }
}
private fun applyLocally(b: Bundle, key: String, p: Int, i: Int, int: Int?, bool: Boolean?) {
val remapCount = b.getStringArray("remapTargets")?.size ?: 8
fun setInt(k: String, index: Int, v: Int) {
val a = b.getIntArray(k)?.clone() ?: return
if (index in a.indices) a[index] = v
b.putIntArray(k, a)
}
fun setBool(k: String, index: Int, v: Boolean) {
val a = b.getBooleanArray(k)?.clone() ?: return
if (index in a.indices) a[index] = v
b.putBooleanArray(k, a)
}
when (key) {
"presentAs", "pollMs" -> if (int != null) b.putInt(key, int)
"driverEnabled", "forceUsb", "bubble" -> if (bool != null) b.putBoolean(key, bool)
"gyroMap" -> if (int != null) setInt(key, p * 3 + i, int)
"remap" -> if (int != null) setInt(key, p * remapCount + i, int)
"calibrate" -> b.putInt("calibrating", p)
"resetCalibration" -> b.getFloatArray("gyroBias")?.clone()?.let { a ->
for (k in 0 until 3) if (p * 3 + k in a.indices) a[p * 3 + k] = 0f
b.putFloatArray("gyroBias", a)
}
else -> {
if (int != null) setInt(key, p, int)
if (bool != null) setBool(key, p, bool)
}
}
}
}
/**
* The SDL3Bridge settings page: a tab of DroidDeck's Setup screen, and a page of the in-session drawer.
* [track] gives each control the drawer's focus tracking (controller navigation); Setup passes nothing.
*/
@Composable
internal fun SdlBridgeSettingsTab(host: MenuHost, track: (String) -> Modifier = { Modifier }) {
val ctx = LocalContext.current
val installed = remember { SdlBridgeLink.installed(ctx) }
if (!installed) {
SettingsGroup("SDL3Bridge") {
SettingsRow("SDL3Bridge is not installed",
"Install the SDL3Bridge app to use any SDL3-supported controller with DroidDeck: USB or Bluetooth, " +
"re-presented as a Steam Deck / Sony / Steam Controller pad, or handed to Steam as itself.") {}
}
return
}
var waited by remember { mutableIntStateOf(0) }
DisposableEffect(Unit) {
SdlBridgeLink.start(ctx)
onDispose { SdlBridgeLink.stop(ctx) }
}
LaunchedEffect(Unit) {
while (true) {
SdlBridgeLink.refresh()
delay(1000)
waited++
}
}
val s = SdlBridgeLink.snapshot
var sessionEnabled by remember { mutableStateOf(com.droiddeck.launcher.session.SessionPrefs.sdl3Controllers(ctx)) }
SettingsGroup("Session integration") {
ToggleRow(host, "sdl3-session", "Use SDL3 controllers in sessions",
"Enable USB controller input, controller presentation and Steam Native Hook-up for the next session.",
sessionEnabled, chipModifier = track("sdl3-session")) {
sessionEnabled = it
com.droiddeck.launcher.session.SessionPrefs.setSdl3Controllers(ctx, it)
}
}
// ---------------- status ----------------
SettingsGroup("SDL3Bridge") {
if (s == null) {
SettingsRow(if (SdlBridgeLink.connected()) "Waiting for SDL3Bridge…" else "Connecting to SDL3Bridge…",
if (waited >= 3) "No answer yet. Update SDL3Bridge (this tab needs a recent build), or open it once." else null) {}
} else {
SettingsRow("Status", s.getString("status") ?: "") {}
val engineError = s.getString("engineError") ?: ""
val engineMode = s.getString("engineMode") ?: ""
if (engineError.isNotEmpty()) SettingsRow("SDL3 is not running", engineError) {}
else if (engineMode.isNotEmpty() && engineMode != "background service") SettingsRow("SDL3 runs in", engineMode) {}
if (!s.getBoolean("notifications", true)) SettingsRow("Status bar icon is hidden",
"SDL3Bridge may not show notifications: open it once and tap Allow (or allow it in Android's app settings).") {}
val padNames = s.getStringArray("padNames") ?: emptyArray()
val padIds = s.getStringArray("padIds") ?: emptyArray()
val battery = s.getIntArray("padBattery") ?: IntArray(0)
val hookNames = s.getStringArray("hookNames") ?: emptyArray()
val hookIds = s.getStringArray("hookIds") ?: emptyArray()
val triton = s.getString("triton") ?: ""
var any = false
padNames.forEachIndexed { i, name ->
if (name.isEmpty()) return@forEachIndexed
any = true
val bat = battery.getOrElse(i) { -1 }
SettingsRow("Player ${i + 1}: $name",
listOfNotNull(padIds.getOrNull(i), if (bat >= 0) "battery $bat%" else null).joinToString(" · ")) {}
}
hookNames.forEachIndexed { i, name ->
if (name.isEmpty()) return@forEachIndexed
any = true
SettingsRow("Handed to Steam: $name",
listOfNotNull(hookIds.getOrNull(i), "/dev/hidraw${24 + i}",
if (s.getBoolean("fastPath")) "fast path" else null).joinToString(" · ")) {}
}
if (triton.isNotEmpty()) {
any = true
SettingsRow("Steam Controller (2026)", "$triton · raw passthrough") {}
}
if (!any) SettingsRow("No controller", "Plug a controller in with USB-C, or pair it over Bluetooth.") {}
}
ActionRow("Open SDL3Bridge", "Controller test screen, USB access, USB audio and everything else.", "Open",
onClick = { SdlBridgeLink.open(ctx) }, modifier = track("sdl3-open"))
}
if (s == null) return
val ints = { k: String -> s.getIntArray(k) ?: IntArray(0) }
val bools = { k: String -> s.getBooleanArray(k) ?: BooleanArray(0) }
val names = { k: String -> s.getStringArray(k) ?: emptyArray() }
fun indexed(k: String) = names(k).mapIndexed { i, n -> i to n }
// ---------------- global ----------------
SettingsGroup("Controller mode") {
BridgeChoiceRow(host, "sdl3-present", "Present controller as",
"How Steam sees the controller, in the Steam session and on the desktop. Steam Native Hook-up hands USB " +
"controllers to Steam as themselves, like on a PC (on the desktop: while Steam runs; other programs " +
"there see an Xbox 360 controller).",
indexed("presentNames"), s.getInt("presentAs"), chipModifier = track("sdl3-present")) { SdlBridgeLink.set("presentAs", int = it) }
ToggleRow(host, "sdl3-driver", "SDL3 driver",
"On: SDL3 reads the controller (all its features). Off: the controller goes back to Android and DroidDeck.",
s.getBoolean("driverEnabled"), chipModifier = track("sdl3-driver")) { SdlBridgeLink.set("driverEnabled", bool = it) }
if (s.getBoolean("embedded")) SettingsRow("Bluetooth and built-in controllers",
"Handled by DroidDeck's Android input. SDL3 handles USB controllers.") {}
else BridgeChoiceRow(host, "sdl3-source", "Controller source", "Which controllers SDL3 uses.",
listOf(false to "USB + Bluetooth (auto)", true to "USB only (forced)"), s.getBoolean("forceUsb"), chipModifier = track("sdl3-source")) {
SdlBridgeLink.set("forceUsb", bool = it)
}
val rateMs = ints("rateMs")
BridgeChoiceRow(host, "sdl3-rate", "Poll rate", "Higher = lower gyro and trackpad latency, a little more battery. In Steam Native Hook-up it is also how often Steam gets the newest report (lower if games lag).",
names("rateNames").mapIndexed { i, n -> rateMs.getOrElse(i) { 2 } to n }, s.getInt("pollMs"), chipModifier = track("sdl3-rate")) {
SdlBridgeLink.set("pollMs", int = it)
}
val overlay = s.getBoolean("overlayAllowed")
ToggleRow(host, "sdl3-bubble", "Floating bubble",
if (overlay) "Tap: SDL3 driver on/off. Double tap: Steam Native Hook-up. Hold 3 s: open SDL3Bridge."
else "Needs SDL3Bridge's \"Draw over other apps\" permission: turn the bubble on once in SDL3Bridge.",
s.getBoolean("bubble"), enabled = overlay || s.getBoolean("bubble"), chipModifier = track("sdl3-bubble")) { SdlBridgeLink.set("bubble", bool = it) }
}
// ---------------- per player ----------------
var player by rememberSaveable { mutableIntStateOf(0) }
val p = player
Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
SegmentedTabs((0 until 4).map { it to "P${it + 1}" }, player, tabModifier = { track("sdl3-player-$it") }) { player = it }
}
SettingsGroup("Gyro · player ${p + 1}") {
SliderRow("Gyro speed", "100 % = 1:1", ints("gyroGain").getOrElse(p) { 100 }, 5..800, step = 5,
format = { "$it %" }, modifier = track("sdl3-gyrospeed-$p")) { SdlBridgeLink.set("gyroGain", p, int = it) }
BridgeChoiceRow(host, "sdl3-gyroinv-$p", "Invert gyro axes", null, indexed("gyroInvNames"),
ints("gyroInvert").getOrElse(p) { 0 }, chipModifier = track("sdl3-gyroinv-$p")) { SdlBridgeLink.set("gyroInvert", p, int = it) }
for (i in 0 until 3) {
BridgeChoiceRow(host, "sdl3-gyromap-$p-$i", "DroidDeck gyro ${"XYZ"[i]} comes from", null, indexed("axisNames"),
ints("gyroMap").getOrElse(p * 3 + i) { i }, chipModifier = track("sdl3-gyromap-$p-$i")) { SdlBridgeLink.set("gyroMap", p, i, int = it) }
}
ToggleRow(host, "sdl3-accel-$p", "Accelerometer follows the axis remap",
"Keeps gravity consistent with rotation.", bools("accelFollows").getOrElse(p) { true }, chipModifier = track("sdl3-accel-$p")) {
SdlBridgeLink.set("accelFollows", p, bool = it)
}
SliderRow("Gyro deadzone", "Motion slower than this is ignored, so the view doesn't drift while you hold still.",
ints("gyroDeadzone").getOrElse(p) { 0 }, 0..50, format = { "$it °/s" }, modifier = track("sdl3-gyrodeadzone-$p")) { SdlBridgeLink.set("gyroDeadzone", p, int = it) }
val bias = s.getFloatArray("gyroBias") ?: FloatArray(0)
val calibrating = s.getInt("calibrating", -1) == p
val b = (0 until 3).map { bias.getOrElse(p * 3 + it) { 0f } }
ActionRow("Calibrate gyro",
when {
calibrating -> "Hold player ${p + 1}'s controller flat and still…"
b.all { it == 0f } -> "Lay the controller flat and still, then tap. Not calibrated yet."
else -> "Drift removed: x %.2f, y %.2f, z %.2f °/s".format(b[0], b[1], b[2])
}, "Calibrate", onClick = { SdlBridgeLink.set("calibrate", p) },
modifier = track("sdl3-calibrate-$p"))
ActionRow("Reset calibration", null, "Reset", onClick = { SdlBridgeLink.set("resetCalibration", p) },
modifier = track("sdl3-uncalibrate-$p"))
}
SettingsGroup("Touchpad · player ${p + 1}") {
BridgeChoiceRow(host, "sdl3-touch-$p", "Layout", "How the controller's touchpad maps to the Deck's two trackpads.",
indexed("touchNames"), ints("touchMode").getOrElse(p) { 0 }, chipModifier = track("sdl3-touch-$p")) {
SdlBridgeLink.set("touchMode", p, int = it)
}
ToggleRow(host, "sdl3-tinvx-$p", "Invert X", null, bools("touchInvX").getOrElse(p) { false }, chipModifier = track("sdl3-tinvx-$p")) { SdlBridgeLink.set("touchInvX", p, bool = it) }
ToggleRow(host, "sdl3-tinvy-$p", "Invert Y", null, bools("touchInvY").getOrElse(p) { false }, chipModifier = track("sdl3-tinvy-$p")) { SdlBridgeLink.set("touchInvY", p, bool = it) }
ToggleRow(host, "sdl3-tswap-$p", "Swap X and Y", "Applied before inverting.", bools("touchSwap").getOrElse(p) { false }, chipModifier = track("sdl3-tswap-$p")) {
SdlBridgeLink.set("touchSwap", p, bool = it)
}
}
SettingsGroup("Button remap · player ${p + 1}") {
val targets = names("remapTargets")
val remap = ints("remap")
val sources = indexed("srcNames")
targets.forEachIndexed { i, target ->
BridgeChoiceRow(host, "sdl3-remap-$p-$i", target, "Pressed by", sources, remap.getOrElse(p * targets.size + i) { 0 }, chipModifier = track("sdl3-remap-$p-$i")) {
SdlBridgeLink.set("remap", p, i, int = it)
}
}
}
SettingsGroup("Lightbar · player ${p + 1}") {
SliderRow("Red", null, ints("lightR").getOrElse(p) { 0 }, 0..255, modifier = track("sdl3-red-$p")) { SdlBridgeLink.set("lightR", p, int = it) }
SliderRow("Green", null, ints("lightG").getOrElse(p) { 0 }, 0..255, modifier = track("sdl3-green-$p")) { SdlBridgeLink.set("lightG", p, int = it) }
SliderRow("Blue", null, ints("lightB").getOrElse(p) { 255 }, 0..255, modifier = track("sdl3-blue-$p")) { SdlBridgeLink.set("lightB", p, int = it) }
SliderRow("Brightness", null, ints("brightness").getOrElse(p) { 100 }, 0..100, format = { "$it %" }, modifier = track("sdl3-brightness-$p")) {
SdlBridgeLink.set("brightness", p, int = it)
}
BridgeChoiceRow(host, "sdl3-pled-$p", "Player LEDs", null, indexed("playerLedNames"), ints("playerLed").getOrElse(p) { 0 }, chipModifier = track("sdl3-pled-$p")) {
SdlBridgeLink.set("playerLed", p, int = it)
}
}
}
/** "Steam Native Hook-up (Steam sees the real controller)" -> "Steam Native Hook-up" + "Steam sees the real controller";
* "Split (decoupled): left half = ..." -> "Split (decoupled)" + "left half = ...". */
private fun splitName(name: String): Pair<String, String?> {
val colon = name.indexOf(": ")
if (colon > 0) return name.substring(0, colon) to name.substring(colon + 2)
val paren = name.indexOf(" (")
if (paren > 0 && name.endsWith(")")) return name.substring(0, paren) to name.substring(paren + 2, name.length - 1)
return name to null
}
/**
* DroidDeck's ChoiceRow, for the bridge's (long) names. The chip shows the short name and the menu the short name
* with the rest under it. When the chip would squeeze the label -- the session drawer is narrow, and a long chip
* left the label no width at all, so the rows looked empty -- the chip goes under the label instead of beside it.
*/
@Composable
private fun <T> BridgeChoiceRow(
host: MenuHost, key: String, label: String, hint: String?,
options: List<Pair<T, String>>, selected: T, chipModifier: Modifier = Modifier,
onPick: (T) -> Unit,
) {
val open = host.open == key
val parts = remember(options) { options.map { (value, name) -> splitName(name).let { Triple(value, it.first, it.second) } } }
val chip = parts.firstOrNull { it.first == selected }?.second ?: "-"
BoxWithConstraints(Modifier.fillMaxWidth()) {
// ~7 dp per character of the chip's 13 sp text, plus its padding and caret; beside the label only while
// the label keeps at least half of the row
val chipWidth = (parts.maxOfOrNull { it.second.length } ?: 0) * 7f + 40f
val stacked = chipWidth > maxWidth.value * 0.5f
Column(Modifier.fillMaxWidth()) {
SettingsRow(label, hint, highlighted = open, stacked = stacked) {
Box {
ValueChip(chip, open, modifier = chipModifier.testTag("setting-$key")) { host.open = if (open) null else key }
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label) { firstItemFocus ->
parts.forEachIndexed { index, (value, text, detail) ->
MenuItem(text, checked = value == selected, detail = detail,
focusRequester = if (index == 0) firstItemFocus else null) {
onPick(value)
host.open = null
}
}
}
}
}
}
}
}
@@ -8,6 +8,7 @@ internal enum class SessionDrawerPage(val firstControl: String) {
EFFECTS("look"),
VR("steamvr"),
GAMES("anisotropy"),
SDL3BRIDGE("sdl3-open"), // sdl3bridge: SDL3Bridge page
SESSION("suspend"),
}
@@ -42,6 +42,7 @@ import androidx.compose.material.icons.outlined.PictureInPictureAlt
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material.icons.outlined.Usb
import androidx.compose.material3.Icon
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
@@ -157,6 +158,7 @@ private val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.VR -> R.string.vr_title
SessionDrawerPage.EFFECTS -> R.string.drawer_page_effects
SessionDrawerPage.GAMES -> R.string.game_settings_title
SessionDrawerPage.SDL3BRIDGE -> R.string.drawer_page_sdl3bridge
SessionDrawerPage.SESSION -> R.string.mode_session
}
@@ -168,6 +170,7 @@ private val SessionDrawerPage.icon get() = when (this) {
SessionDrawerPage.VR -> VrHeadsetIcon
SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
SessionDrawerPage.SDL3BRIDGE -> Icons.Outlined.Usb
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
}
@@ -208,6 +211,9 @@ class DrawerActions(
val onScreenButtonsVisible: Boolean,
val suspendPolicy: String,
val steamDownloadsInBackground: Boolean = false,
val micAvailable: Boolean = false,
val micEnabled: Boolean = false,
val onMicEnabled: (Boolean) -> Unit = {},
val backActionsInverted: Boolean,
val padType: String? = null,
val onPadType: (String) -> Unit = {},
@@ -639,6 +645,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
track = { key -> focus.track(page, key) },
)
}
SessionDrawerPage.SDL3BRIDGE -> SdlBridgeSettingsTab(host) { key -> focus.track(page, key) }
SessionDrawerPage.SESSION -> {
if (a.isHomeApp) SettingsGroup(stringResource(R.string.drawer_android_apps)) {
SettingsRow(stringResource(R.string.drawer_launch_app), null) {
@@ -669,6 +676,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
SettingsGroup(stringResource(R.string.drawer_session_behavior)) {
if (a.micAvailable) ToggleRow(host, "microphone", stringResource(R.string.mode_mic),
stringResource(R.string.drawer_mic_hint), a.micEnabled,
chipModifier = focus.track(page, "microphone"), onChange = a.onMicEnabled)
ChoiceRow(
host, "suspend", stringResource(R.string.mode_suspend),
null,
@@ -270,6 +270,23 @@ internal fun StoreAchievementsCardContent(label: String, state: AchievementsStat
}
}
@Composable
internal fun AchievementsTab(label: String, state: AchievementsState, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
val list = state.list
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier.fillMaxWidth().tabPanel()) {
if (list.isNullOrEmpty()) {
Text(achievementsNote(state, label).orEmpty(), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.readable().padding(4.dp))
return@Column
}
Box(Modifier.fillMaxWidth().readable().padding(4.dp)) { AchievementsProgress(state) }
for ((group, items) in groups(list)) {
AchievementGroupLabel(stringResource(group, items.size))
for (a in items) androidx.compose.runtime.key(a.id) { AchievementRow(a, compact = true) }
}
}
}
private fun LazyListScope.achievementItems(list: List<Achievement>, compact: Boolean, first: FocusRequester, labels: Boolean = true) {
var index = 0
for ((label, group) in groups(list)) {
@@ -1,292 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.input.key.onPreviewKeyEvent
import kotlinx.coroutines.launch
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.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAchievements
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
@Composable
internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: FrontEndActions, lead: androidx.compose.ui.focus.FocusRequester, onBack: () -> Unit) {
val leadOn = Modifier.focusRequester(lead)
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700
val id = key.substringAfter(':')
val item = StoresState.detailItem(store, id)
val installed = StoresState.installedGame(store, id)
val rawDownload = StoresState.download("${store.id}:$id")
val download = rawDownload?.takeIf { it.isActive }
val failedDownload = rawDownload?.takeIf { it.state == DownloadState.FAILED }
val title = item?.title ?: installed?.sidecar?.title ?: id
Rise(0) {
Box(Modifier.padding(bottom = 12.dp)) { BackLink(stringResource(R.string.common_back), compact = true, onClick = onBack) }
}
val scores = if (store == Store.GOG || store == Store.EPIC) rememberGameScores(title.takeIf { it != id }) else null
val hero: @Composable () -> Unit = {
androidx.compose.runtime.DisposableEffect(Unit) { onDispose { StoresMotion.heroAt = null } }
Box(
Modifier.fillMaxWidth().heightIn(min = if (narrow) 150.dp else 180.dp)
.onGloballyPositioned { StoresMotion.heroAt = it.boundsInRoot() }
.clip(Shape16).background(artBrush(hueOf(title))),
) {
val art = item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover
// The card it came from keeps its own bitmap under the hero until the wide art is decoded.
val heroArt = cardArtRequest(art, item?.tallImageUrl)
if (heroArt != null) AsyncImage(model = heroArt, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.5f to colors.background.copy(alpha = 0.55f), 1f to Color.Transparent)))
if (scores != null && !stacked) {
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0.45f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp))
}
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp)) {
val passName = item?.includedWith.orEmpty()
val state = when {
installed != null -> stringResource(R.string.stores_eyebrow_installed) + " · " + com.droiddeck.launcher.stores.StoreInstallRoot.labelFor(ctx, installed.folder)
download != null && download.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + download.location
failedDownload != null && failedDownload.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + failedDownload.location
item?.owned == true -> stringResource(R.string.stores_eyebrow_library)
item?.subscription == true -> passName.ifBlank { "PC Game Pass" }
passName.isNotBlank() -> "Available with $passName"
item?.accessible == true -> stringResource(R.string.stores_eyebrow_library)
else -> stringResource(R.string.stores_eyebrow_store)
}
val size = (item?.sizeBytes ?: 0L).takeIf { it > 0 }?.let { " · " + formatBytes(it) } ?: ""
Text((state + size).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = pal.signal)
Text(title, fontSize = if (narrow) 24.sp else 30.sp, lineHeight = if (narrow) 27.sp else 33.sp, fontWeight = FontWeight.Black, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (!failedDownload?.error.isNullOrBlank()) {
Text(
failedDownload!!.error!!,
fontSize = 13.sp,
lineHeight = 17.sp,
fontWeight = FontWeight.Medium,
color = colors.error,
maxLines = 3,
overflow = TextOverflow.Ellipsis
)
}
Actions {
when {
installed != null -> {
val gone = StoresState.uninstalling["${store.id}:$id"]
PrimaryButton(stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && (store != Store.XBOX || !com.droiddeck.launcher.stores.xbox.XboxContent.busy(id)), main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) {
launchStoreGame(ctx, store, id, s, a)
}
ActionChip(stringResource(R.string.stores_in_steam), ok = true)
if (store == Store.XBOX) {
SecondaryButton("Update / verify", enabled = download == null && !com.droiddeck.launcher.stores.xbox.XboxRuntime.isActive(id)) {
runCatching { com.droiddeck.launcher.stores.xbox.XboxBackend.update(ctx, installed) }
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: "Close this Xbox game before updating it." }
}
SecondaryButton("Manage content", enabled = download == null) {
com.droiddeck.launcher.stores.xbox.XboxContent.manage(ctx, installed)
}
}
if (gone != null) SecondaryButton(stringResource(R.string.stores_uninstalling), enabled = false, progress = gone) {}
else UninstallButton(title, installed, enabled = download == null && (store != Store.XBOX || !com.droiddeck.launcher.stores.xbox.XboxContent.busy(id))) {
StoresState.uninstall(ctx, installed) { StoresState.refresh(ctx); a.onLibraryChanged() }
}
}
download != null -> {
ActionChip(downloadLabel(download), ok = false)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { com.droiddeck.launcher.stores.download.DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { com.droiddeck.launcher.stores.download.DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { com.droiddeck.launcher.stores.download.DownloadQueue.cancel(ctx, download.key) }
}
failedDownload != null -> {
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) {
if (item != null) StoresState.requestInstall(ctx, item)
else com.droiddeck.launcher.stores.download.DownloadQueue.retry(ctx, failedDownload.key)
}
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) {
com.droiddeck.launcher.stores.download.DownloadQueue.clear(ctx, failedDownload.key)
}
}
item?.installable == true && StoresState.isUnfinished(item) -> {
InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
}
item?.installable == true -> {
InstallButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
leadOn,
) { StoresState.requestInstall(ctx, item) }
if (!item.accessible) {
SecondaryButton(
when {
item.isFree -> stringResource(R.string.stores_get_free)
item.hasPrice && item.finalPrice.isNotBlank() -> stringResource(R.string.stores_buy_price, item.finalPrice)
else -> stringResource(R.string.stores_view_on, store.shortLabel)
},
) { openStoreUrl(ctx, item) }
}
}
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
item != null -> PrimaryButton(if (item.hasPrice && item.finalPrice.isNotBlank()) stringResource(R.string.stores_buy_price, item.finalPrice) else stringResource(R.string.stores_view_on, store.shortLabel), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
}
BusyChip(s)
}
}
}
}
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
if (scores != null) Rise(2) {
val listed = (StoresState.found[store].orEmpty() + StoresState.shelves[store]?.all.orEmpty()).firstOrNull { it.id == id }
val developer = item?.developer?.ifBlank { null } ?: listed?.developer.orEmpty()
val publisher = item?.publisher?.ifBlank { null } ?: listed?.publisher.orEmpty()
val releaseDate = item?.releaseDate?.ifBlank { null } ?: listed?.releaseDate.orEmpty()
StoreGameFacts(developer, publisher, releaseDate, scores, scoresInHero = !stacked)
}
val description = item?.let { com.droiddeck.launcher.stores.cleanStoreText(it.description) }.orEmpty()
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
val achievements = remember(store, id, item?.accessible, installed) {
when {
StoreAchievements.forSource(store.id) == null -> null
item?.accessible == true -> StoreAchievements.Game.of(item)
installed != null -> StoreAchievements.Game.of(installed.sidecar)
else -> null
}
}
if (description.isNotBlank() || achievements != null) Rise(3) {
val about: @Composable (Modifier, Dp) -> Unit = { m, h -> if (description.isNotBlank()) StoreAbout(description, h, m) }
val card: @Composable (Modifier) -> Unit = { m -> if (achievements != null) StoreAchievementsCard(achievements, title, m) }
if (stacked) Column(verticalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth().padding(top = 14.dp)) {
about(Modifier.fillMaxWidth(), AboutHeight)
card(Modifier.fillMaxWidth())
} else Row(horizontalArrangement = Arrangement.spacedBy(24.dp), modifier = Modifier.fillMaxWidth().padding(top = 14.dp)) {
val density = LocalDensity.current
var cardHeight by remember { mutableStateOf<Dp?>(null) }
about(Modifier.weight(1f), cardHeight ?: AboutHeight)
card(Modifier.width(340.dp).onSizeChanged { cardHeight = with(density) { it.height.toDp() } })
}
}
}
private val AboutHeight = 150.dp
@Composable
private fun StoreAbout(text: String, height: Dp, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scroll = rememberScrollState()
val scope = rememberCoroutineScope()
val src = remember { MutableInteractionSource() }
val more = scroll.maxValue > 0
val hot = more && rememberHot(src)
val shape = RoundedCornerShape(12.dp)
Box(
modifier.heightIn(max = height).clip(shape)
.glideBorder(hot, shape, pal.signal, restColor = Color.Transparent)
.then(if (more) Modifier.paneItem("about") else Modifier)
.focusable(enabled = more, interactionSource = src)
.onPreviewKeyEvent { e ->
val step = when (e.nativeKeyEvent.keyCode) {
android.view.KeyEvent.KEYCODE_DPAD_DOWN -> if (scroll.value < scroll.maxValue) 120f else return@onPreviewKeyEvent false
android.view.KeyEvent.KEYCODE_DPAD_UP -> if (scroll.value > 0) -120f else return@onPreviewKeyEvent false
else -> return@onPreviewKeyEvent false
}
if (e.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) scope.launch { scroll.animateScrollBy(step) }
true
},
) {
Text(text, fontSize = 14.sp, lineHeight = 21.sp, color = colors.onSurfaceVariant, modifier = Modifier.verticalScroll(scroll).padding(horizontal = 10.dp, vertical = 6.dp))
if (scroll.value < scroll.maxValue) Box(
Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(28.dp)
.background(Brush.verticalGradient(listOf(Color.Transparent, colors.background))),
)
}
}
@Composable
private fun UninstallButton(title: String, game: com.droiddeck.launcher.stores.InstalledStoreGame, enabled: Boolean, modifier: Modifier = Modifier, onUninstall: () -> Unit) {
val colors = MaterialTheme.colorScheme
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
val heading = stringResource(R.string.stores_uninstall_title, title)
val size = com.droiddeck.launcher.stores.StoreSizes.onDisk["${game.sidecar.store.id}:${game.sidecar.id}"]
val body = if (size != null && size > 0) stringResource(R.string.stores_uninstall_body_size, formatBytes(size)) else stringResource(R.string.stores_uninstall_body)
val keep = stringResource(R.string.stores_notification_keep)
val remove = stringResource(R.string.stores_uninstall)
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
SecondaryButton(remove, enabled = enabled, modifier = modifier) {
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot() ?: return@SecondaryButton
var confirmed = false
StoresMotion.ask(StepAsk(anchor = at, side = StepSide.Right, accent = colors.error, items = 3, pillCorner = 12.dp, maxWidth = 340.dp,
onDismiss = { if (confirmed) onUninstall() }, handle = {
Text(remove, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.error, maxLines = 1)
}) {
StepTitle(heading)
Text(body, fontSize = 13.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) {
StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { StoresMotion.fold() }
StepChoice(remove, danger = true, enabled = open) { confirmed = true; StoresMotion.fold() }
}
})
}
}
}
@Composable
private fun InstallButton(label: String, modifier: Modifier = Modifier, onInstall: () -> Unit) {
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
PrimaryButton(label, main = true, modifier = modifier) {
StoresMotion.markInstall(placed[0]?.takeIf { it.isAttached }?.boundsInRoot(), label)
onInstall()
}
}
}
@@ -498,16 +498,10 @@ internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<Fron
val st = s.value
val context = androidx.compose.ui.platform.LocalContext.current
SettingsRow(stringResource(R.string.stores_tabs_arrange), null) {
RoundAction(Icons.Filled.SwapHoriz, stringResource(R.string.stores_tabs_arrange), size = 36.dp) {
Box(Modifier.focusRequester(first).focusGroup()) { RoundAction(Icons.Filled.SwapHoriz, stringResource(R.string.stores_tabs_arrange), size = 36.dp) {
StoresMotion.fold()
onArrange()
}
}
SettingsRow(stringResource(R.string.setup_stores_open_on), null, stacked = true) {
Box(Modifier.focusRequester(first).focusGroup()) { SegmentedTabs(
listOf(SessionPrefs.STORES_OPEN_LIBRARY to stringResource(R.string.stores_tab_library), SessionPrefs.STORES_OPEN_STORE to stringResource(R.string.stores_tab_store)),
st.storesOpenTab,
) { a.onStoresOpenTab(it) } }
} }
}
SettingsRow(stringResource(R.string.stores_show_mature), null) {
ToggleSwitch(st.storesShowMature, label = stringResource(R.string.stores_show_mature)) { a.onStoresShowMature(it) }
Loaded 100 of 304 files, more files were not shown because too many files have changed in this diff. Show more