Compare commits

...
Author SHA1 Message Date
Kurt Himebauch 197fc3f163 Merge pull request #52 from maxjivi05/fix/splash-screen
Reduce Steam startup movie software decoding load
2026-09-28 11:35:25 -04:00
MaxsTechReview 0e0f133496 Reduce Steam startup movie software decoding load 2026-09-28 10:49:25 -04:00
Kurt Himebauch d98c211168 Merge pull request #50 from Droid-Deck/fix/release-blockers
Fix/release blockers
2026-09-28 10:32:44 -04:00
xXJsonDeruloXx 614b4d4de4 chore(release): set version 0.2.0 and remove code comments 2026-09-28 10:32:12 -04:00
Kurt Himebauch 43a19a831a docs(release): show every 0.2.0 section open (#48) 2026-09-28 10:24:24 -04:00
Kurt Himebauch 0d308af024 Merge branch 'main' into fix/release-blockers 2026-09-28 10:22:22 -04:00
The412Banner 128f73da8f Merge pull request #51 from Droid-Deck/fix/child-process-check
Child-process check: read the Developer options toggle too
2026-09-28 09:30:58 -04:00
The412Banner e22a55e949 Child-process check: read the Developer options toggle too
Developer options' "Disable child process restrictions" writes only the
feature-flag property persist.sys.fflag.override.settings_enable_monitor_phantom_procs,
never the global setting. Android (FeatureFlagUtils.isEnabled) uses the global
setting when it is set and that property otherwise, but the check read only the
global setting, so a device switched off in Developer options stayed flagged as
unset however often Check again was pressed.

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

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

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

* chore: update readme

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Now a session stop also kills every process of ours whose executable lives
in the Linux runtime, and bannerlator-session keeps only the first
BL_LOG_CAP bytes (256 MB) of session.log, draining the rest so a writer
that filled it is not killed by SIGPIPE.
2026-09-27 16:52:51 -04:00
Kurt Himebauch 91beced154 Merge pull request #41 from Droid-Deck/fix/ui-ux-critique
Fix/UI ux critique
2026-09-27 16:41:18 -04:00
The412Banner ebc3da08b4 Merge pull request #42 from Droid-Deck/feat/cemu-wiiu
Cemu (Wii U) from the front end and the desktop, and two session fixes
2026-09-27 16:39:17 -04:00
xXJsonDeruloXx 41eb780495 fix(ui): remove duplicate focus imports 2026-09-27 16:34:34 -04:00
The412Banner 65fc2a38a3 Cemu (Wii U) from the front end and the desktop, and two session fixes
Cemu never showed a frame on DroidDeck: its Getting Started dialog blocked
every first launch (the folder picker cannot reach ROMs), the session's
controller helper aborted it, and the desktop's Vulkan renderer drew no
cursor. With the Turnip KGSL fix in the driver and the haptic-optional
Cemu in the catalog, this makes the app side complete:

- bannerlator-pad-defaults seeds Cemu's settings.xml once: the Wii U games
  folder, Vulkan, and Cubeb audio on the default device for both the TV
  and the GamePad speaker at full volume (Wipeout 3 plays through the
  GamePad; Cemu's own default is 20 %).
- The Cemu tile launches full screen (-f).
- libfakeinput.so is preloaded into every session process and exported its
  static C++ runtime (~7000 symbols); programs unwound through it and
  aborted (shadPS4 in pthread_exit, Cemu's controller thread). Link with
  --exclude-libs,ALL, and fail the build if the runtime leaks out again.
- On the Vulkan and GLES desktops the pointer worked but no cursor was
  drawn: wlroots hands the cursor to the app's compositor, which draws
  none. WLR_NO_HARDWARE_CURSORS=1 makes labwc composite it itself.

Device-tested on the FIT: Super Mario 3D World in-game at 35-37 fps with
sound, Deus Ex HR DC and Wipeout 3 launch with sound; RPCS3, Dolphin and a
Steam session (FlatOut) unchanged on the same driver.
2026-09-27 16:30:49 -04:00
Kurt Himebauch 359d1535ac fix(copy): american spelling, clearer keyboard and package labels 2026-09-27 14:23:19 -04:00
Kurt Himebauch 4c3a9f027c fix(focus): land controller focus by frame instead of fixed delays 2026-09-27 14:22:56 -04:00
Kurt Himebauch 5a6cc3c76e fix(motion): honor the system animation scale everywhere and on resume 2026-09-27 14:22:17 -04:00
Kurt Himebauch 89bd7deceb refactor(ui): share one frame generation menu and drop the unused dialog 2026-09-27 14:21:41 -04:00
Kurt Himebauch 169f2c3e34 fix(rail): keep sections in fixed places with an empty games state 2026-09-27 14:21:01 -04:00
Kurt Himebauch e6a797695a fix(setup): trim child-process fix to one line and three actions 2026-09-27 14:20:35 -04:00
Kurt Himebauch f1a2ecc857 fix(ui): raise buttons, chips and tabs to handheld touch sizes 2026-09-27 14:20:03 -04:00
Kurt Himebauch 36916f6bde fix(ui): show launch and tab hints where a pad does that 2026-09-27 14:19:32 -04:00
Kurt Himebauch 1b96d13a51 fix(ui): enable launches like play and say why they are disabled 2026-09-27 14:19:02 -04:00
Kurt Himebauch cb1d70bb14 fix(ui): flip booleans with a switch instead of on/off menus 2026-09-27 14:18:29 -04:00
Kurt Himebauch 37af590ca2 fix(ui): use one name each for child-process limit, proton and components 2026-09-27 14:17:49 -04:00
Kurt Himebauch 02f356f8c0 fix(session): keep ended screen with retry, share logs and back 2026-09-27 14:17:16 -04:00
Kurt Himebauch 5448177814 Merge pull request #40 from Droid-Deck/fix/review-hardening
Fix/review hardening
2026-09-27 13:57:20 -04:00
Kurt Himebauch ed6ce0ca41 Merge branch 'main' into fix/review-hardening 2026-09-27 12:27:22 -04:00
Kurt Himebauch 9b440686c5 Merge pull request #37 from maxjivi05/fix/performance-enhancements 2026-09-27 12:26:53 -04:00
xXJsonDeruloXx e7b7e9dc43 refactor(session): move the overlay setup out of SessionActivity.onCreate 2026-09-27 11:57:43 -04:00
xXJsonDeruloXx 1120040aee refactor(session): split runSession into its setup stages 2026-09-27 11:57:08 -04:00
xXJsonDeruloXx 3506a272da refactor(core): share one checksum helper across downloads 2026-09-27 11:56:15 -04:00
xXJsonDeruloXx b752748b7d refactor(compositor): move zwp_linux_dmabuf_v1 into wl_dmabuf.c 2026-09-27 11:54:48 -04:00
xXJsonDeruloXx 8990e7d7a4 refactor(launcher): resolve displayNameOf on the activity in DriverMenus 2026-09-27 11:48:05 -04:00
xXJsonDeruloXx c92a423ba1 refactor(launcher): move components, decky and proton state out of MainActivity 2026-09-27 11:43:35 -04:00
xXJsonDeruloXx 3b82b3e1f8 refactor(launcher): move driver menu state out of MainActivity 2026-09-27 11:41:21 -04:00
xXJsonDeruloXx e985ce1975 refactor(ui): move the session loading screen out of SessionOverlay 2026-09-27 11:39:57 -04:00
xXJsonDeruloXx 8496ce3e51 refactor(files): split FileManagerScreen helpers, items and dialog 2026-09-27 11:39:57 -04:00
xXJsonDeruloXx 47188f40ed refactor(ui): split FrontEndScreen into per-page files 2026-09-27 11:33:09 -04:00
Kurt Himebauch e186c9bc4c Merge branch 'main' into fix/performance-enhancements 2026-09-27 11:31:48 -04:00
xXJsonDeruloXx 7705f3c222 feat(runtime): install the runtime from a foreground service 2026-09-27 11:01:55 -04:00
xXJsonDeruloXx 5675b4897f build(deps): bump commons-compress to 1.27.1 2026-09-27 11:00:47 -04:00
xXJsonDeruloXx 1c87d92ef7 build(native): enable warnings for the compositor 2026-09-27 10:55:25 -04:00
xXJsonDeruloXx 031e64dfe1 fix(compositor): bound cursor buffer copies by stride and 64-bit size 2026-09-27 10:55:25 -04:00
xXJsonDeruloXx f590dd9763 fix(security): require a verified checksum for proton downloads 2026-09-27 10:54:31 -04:00
xXJsonDeruloXx af7dc40538 fix(security): require sha256 for every catalog and release download 2026-09-27 10:54:05 -04:00
xXJsonDeruloXx a28aae6e4a test: add unit tests for archive paths and log redaction 2026-09-27 10:52:01 -04:00
xXJsonDeruloXx c024470cc7 fix(runtime): refuse hard links that point outside the rootfs 2026-09-27 10:51:14 -04:00
xXJsonDeruloXx 16ae5ab84a fix(ui): keep the launcher alive when a pad connects 2026-09-27 10:49:54 -04:00
xXJsonDeruloXx 144947305a fix(runtime): single-flight the runtime install and reattach after rebuild 2026-09-27 10:49:54 -04:00
Kurt Himebauch 563bc6cad7 Merge pull request #38 from Droid-Deck/feat/steam-startup-toggle
Add optional Steam startup
2026-09-27 09:55:22 -04:00
xXJsonDeruloXx 59cde93821 Add optional Steam startup 2026-09-27 09:27:30 -04:00
maxjivi05 c104e1c276 proot: port WinNative's seccomp and tracee performance fixes
Brings the proot patch set up to WinNative 53836ca9 on top of the #772 port:

- trace prctl, setrlimit and prlimit64 in the seccomp filter only for the
  arguments proot acts on, and uname only where the core rewrites it
- answer a seccomp stop's filter flags from the registers fetched for its
  translation, reuse those registers, and skip the sysexit stop of wait4 left
  to the kernel and accept without a sockaddr; the flags come from proot's list
  merged with the enabled extensions, and a syscall an extension replaced
  keeps its exit stop
- take a clone3 child's flags and exit signal from struct clone_args
- name a thread's /proc/self by its thread group and resolve /proc/thread-self
- translate fchmodat2, send openat2 callers to openat, and bound sysnum lookups
  by the table length
- sweep relatives only for tracees that have children or ptracees, and empty
  the per-stop memory collector instead of reallocating it
2026-09-27 08:10:58 -04:00
Kurt Himebauch b5da0d0db6 Merge pull request #36 from Droid-Deck/fix/steam-startup-movie-overrides
Fix Steam startup movie override paths
2026-09-27 00:31:31 -04:00
xXJsonDeruloXx 5defc3e38b fix: use Steam startup movie override names 2026-09-27 00:16:37 -04:00
Kurt Himebauch 6a9f52f932 Merge pull request #35 from Droid-Deck/ui/launcher-refresh
feat(ui): launcher ui refresh
2026-09-26 23:19:09 -04:00
xXJsonDeruloXx 06a8d75769 feat(session): animate the logo on the loading screen 2026-09-26 22:44:09 -04:00
xXJsonDeruloXx ec12ddd0a8 ui: preserve rail focus on components 2026-09-26 22:16:38 -04:00
xXJsonDeruloXx 570902d5f3 ui: add fullscreen launcher and focus tabs 2026-09-26 22:10:17 -04:00
xXJsonDeruloXx 6120069975 ui: simplify suspended session overlay 2026-09-26 21:56:55 -04:00
xXJsonDeruloXx 3e337c9bda fix(ui): name the desktop cog's click 2026-09-26 21:37:40 -04:00
xXJsonDeruloXx 2869e76406 feat(ui): turn the steam tab into a capsule wall 2026-09-26 21:31:26 -04:00
xXJsonDeruloXx 61fdb80823 feat(ui): add a games tab with list and detail 2026-09-26 21:30:19 -04:00
Kurt Himebauch fd180a108a Merge branch 'main' into ui/launcher-refresh 2026-09-26 20:46:47 -04:00
Kurt Himebauch 4de74c740c Merge pull request #34 from Droid-Deck/fix/droiddeck-logo-white-on-black
Invert DroidDeck logo colors
2026-09-26 20:41:45 -04:00
xXJsonDeruloXx b7c32c92d2 Invert DroidDeck logo colors 2026-09-26 20:39:52 -04:00
xXJsonDeruloXx 8610ca0928 fix(ui): raise small text on the remaining pages 2026-09-26 16:43:46 -04:00
The412Banner a6b1ad37d0 Merge pull request #33 from Droid-Deck/fix/steam-readonly-files
First Steam session: Proton ARM64 ready at sign-in; Steam updates past read-only files
2026-09-26 16:43:35 -04:00
xXJsonDeruloXx 97b13f7488 feat(session): stack the loading screen on small screens 2026-09-26 16:42:58 -04:00
xXJsonDeruloXx 5d5b45a012 feat(session): explain paused sessions and offer stop 2026-09-26 16:42:28 -04:00
xXJsonDeruloXx 5ebafaabda feat(session): compact the session menu on short screens 2026-09-26 16:41:17 -04:00
xXJsonDeruloXx 56627a8aaf feat(session): redesign the session menu header and actions 2026-09-26 16:40:30 -04:00
xXJsonDeruloXx f59ced4e98 feat(ui): rework the components page layout 2026-09-26 16:38:53 -04:00
xXJsonDeruloXx 296e848718 feat(ui): split setup into tabs 2026-09-26 16:36:49 -04:00
xXJsonDeruloXx 8c63413019 feat(ui): redesign the desktop and emulator pages 2026-09-26 16:35:07 -04:00
xXJsonDeruloXx 2861c6d284 feat(ui): fit the game page to narrow screens 2026-09-26 16:33:53 -04:00
xXJsonDeruloXx 69c2d8e566 feat(ui): condense the steam page on small screens 2026-09-26 16:33:19 -04:00
xXJsonDeruloXx 414fddf7b8 feat(ui): scroll launcher pages as one and wrap actions 2026-09-26 16:32:04 -04:00
xXJsonDeruloXx b5ca6145a6 feat(ui): show an icon-only rail on narrow screens 2026-09-26 16:31:10 -04:00
xXJsonDeruloXx 5a5948b071 feat(ui): reflow settings pages in narrow panes 2026-09-26 16:30:21 -04:00
xXJsonDeruloXx e58b5088b3 feat(theme): add readable text colour for signal fills 2026-09-26 16:29:05 -04:00
The412Banner ecbce4c8d3 Steam updates: the client is not uid 0 in the session - drop that test
The session's proot runs with -i <app uid>, and the rootfs names that uid
root, so the client calls itself root while geteuid() returns the app's
uid. The read-only retry required geteuid() == 0 and never ran: the
Proton Experimental (ARM64) update still failed with Missing file
permissions on wineopenxr.dll (2026-09-26 16:07, 2,471 read-only files).

Also recognise the client by the path it was started by: the kernel's
/proc/self/exe names proot's loader for every process in the session.
2026-09-26 16:10:11 -04:00
The412Banner 96bf0a3bf3 First Steam session: Play sends no mode, and no mode is Steam - seed the Proton then too 2026-09-26 15:44:20 -04:00
The412Banner da7522a3ee First Steam session: place Valve's ARM64 Proton before the client first starts
The runtime setup now also fetches Proton Experimental (ARM64) and its
appmanifest from a catalog of their own (steam-seed.json) and unpacks them
where the client keeps them. At the first sign-in the compatibility tool is
already installed and the default, with no install dialog, no download and
no client restart; the client adopts the manifest and updates it like any
other app.

Done once: an install the client fetched itself, or one the user removed,
is left alone. A failed fetch stops nothing - the session asks the client
for it after sign-in, as before.
2026-09-26 15:36:23 -04:00
The412Banner 5605e777ca Merge remote-tracking branch 'org/main' into fix/steam-readonly-files 2026-09-26 15:33:02 -04:00
The412Banner a10e2e1fe8 Merge remote-tracking branch 'org/fix/first-login-proton-timing' into fix/steam-readonly-files 2026-09-26 15:33:01 -04:00
xXJsonDeruloXx 4fb623fa33 fix(ui): guard missing runtime version in setup 2026-09-26 15:19:40 -04:00
xXJsonDeruloXx 3b4956d088 feat(ui): add controller button hints 2026-09-26 15:19:00 -04:00
xXJsonDeruloXx 18deaafc34 feat(session): show staged progress on loading screen 2026-09-26 15:18:35 -04:00
xXJsonDeruloXx 0c4eede6d2 feat(ui): add system check to setup 2026-09-26 15:16:14 -04:00
xXJsonDeruloXx 54681f2647 feat(ui): add hero and launch settings to game page 2026-09-26 15:14:59 -04:00
xXJsonDeruloXx 5271edd972 feat(ui): add continue hero to steam page 2026-09-26 15:13:20 -04:00
xXJsonDeruloXx e4bb9856ef style(ui): drop random hue washes behind pages 2026-09-26 15:12:14 -04:00
xXJsonDeruloXx e462bbb24a feat(ui): replace nav drawer with permanent side rail 2026-09-26 15:11:47 -04:00
xXJsonDeruloXx d8f3090d9b refactor(ui): move build label into setup about 2026-09-26 15:09:34 -04:00
xXJsonDeruloXx d1af8b0114 feat(library): read hero art and last played from steam 2026-09-26 15:09:07 -04:00
xXJsonDeruloXx dae64bbe69 feat(ui): show game titles on library tiles 2026-09-26 15:08:30 -04:00
xXJsonDeruloXx 8b127bed84 fix(ui): raise small text to 12sp minimum 2026-09-26 15:07:42 -04:00
xXJsonDeruloXx 67187b1340 feat(theme): add graphite theme as default 2026-09-26 15:07:10 -04:00
Kurt Himebauch 02cac57438 Merge pull request #31 from Droid-Deck/docs/readme-banner
docs: add readme banner
2026-09-26 15:03:58 -04:00
The412Banner 277dcd174c Steam updates: rewrite read-only content files the way root could
The client runs as proot's root, which the kernel does not see, and
leaves many content files read-only; an update that rewrites one was
refused (EACCES) and cancelled with "Missing file permissions"
(Proton Experimental (ARM64), wineopenxr.dll). For the client's own
processes, a refused write-open of a file the app owns now gets the
owner's write bit - on the file, or on the directory a new file goes
into - and one more try. Games and Wine keep ordinary permissions.
2026-09-26 10:41:06 -04:00
xXJSONDeruloXx 3c23ae7310 docs: add readme banner 2026-09-26 09:48:11 -04:00
The412Banner 8cb13d40b5 First sign-in: ask for the ARM64 Proton after the client's post-logon compat phase, and retry
With Steam publicbeta 1790380355 the client spent 27 s in its post-logon
compat phase and dropped the install request the session sent 15 s after
sign-in, so a clean install never offered Proton Experimental (ARM64).
Wait for the console log's "Waiting for compat in post-logon took" (90 s
at most), then ask, up to three times a minute apart until the install
starts.
2026-09-26 08:21:14 -04:00
The412Banner c950d31960 Merge pull request #29 from Droid-Deck/feat/components-manager
Components manager: swap FEX / DXVK / VKD3D-Proton per Proton, enforced at launch
2026-09-26 06:16:04 -04:00
The412Banner ae570cd5b7 Components drawer: stacked rows so long names never squeeze the text, a focusable Running now card the pad can reach, and only the Proton a game actually runs on counts as running 2026-09-26 05:30:02 -04:00
The412Banner 0fd1dc4fce Proton wrappers: run the components check for non-Steam shortcuts too - decide by the game's own prefix rather than the app id, which is 0 for a shortcut 2026-09-26 05:15:36 -04:00
The412Banner f0854e8518 Merge org main into feat/components-manager 2026-09-26 04:41:10 -04:00
The412Banner ceffd3f759 Merge org main into feat/components-manager
Keeps both onResume additions: the phantom status refresh from main and the queued component swaps.
2026-09-26 04:36:02 -04:00
Kurt Himebauch dc1816612c Merge pull request #28 from Droid-Deck/fix/session-desktop-button-label
Keep the session Desktop button on one line
2026-09-26 00:53:17 -04:00
xXJsonDeruloXx 1d04a7e0e3 Keep session desktop button label on one line 2026-09-26 00:52:53 -04:00
Kurt Himebauch 1e523c4e93 Merge pull request #27 from Droid-Deck/fix/boot-video-pitch-black
Set boot movie background to pitch black
2026-09-26 00:36:22 -04:00
xXJsonDeruloXx d83f766cf3 Set boot movie background to pitch black 2026-09-26 00:35:54 -04:00
The412Banner bb5e1ae63d Proton wrappers: run the components check only for a real game launch (waitforexitandrun, non-zero app id)
With the check reached from the client's own runs right after login, the Steam client segfaulted
within seconds, four sessions out of four; the same build without the check (test/bisect-no-launch-check)
and the last build before it both reach Big Picture. Now every run that is not a game launch -
the client's probes, app id 0 - is left exactly as before. Each check logs one line.
2026-09-26 00:28:49 -04:00
Kurt Himebauch f27a4f6c95 Merge pull request #26 from Droid-Deck/ui/build-info-top-bar
Show build identity in the launcher top bar
2026-09-26 00:24:39 -04:00
The412Banner d7ff92106a Remove a stray __pycache__ from the overlay scripts and ignore it 2026-09-26 00:20:41 -04:00
xXJsonDeruloXx 34a17acaba Show build identity in launcher top bar 2026-09-26 00:03:56 -04:00
The412Banner 110aec0b6f Proton wrappers: drop the per-tool prefix for Steam's tool-0 runs - the client segfaulted right after its probe started (first in 25 sessions); keep the launch-time component check 2026-09-26 00:03:45 -04:00
The412Banner 06502bb49b Components: choices enforced at every game launch; Steam's tool-0 probes get their own prefix per Proton
Steam runs its graphics probe through every registered Proton at once after login, all in
compatdata/0. Prefix system32 links point into the Proton that set it up last, and the other
Protons' Wines, running outside Proton's pfx.lock, wrote their builtin DLLs through them into that
Proton's tree (device: GE's FEX DLLs became Proton Experimental's at session start).

- bannerlator-steam-compat: both wrappers (Valve's depot launcher and the third-party
  bannerlator-proton-wrap) give a tool-0 run STEAM_COMPAT_DATA_PATH=.../compatdata/0-<tool>, and
  before every other launch check the Proton's files against the app's desired.tsv and put back
  anything that differs (same Proton build only), logging to reapplied.log.
- ComponentsManager writes desired.tsv plus unpacked copies of the packages in use into the
  runtime after every change; the page and the drawer show 're-applied at launch'.
2026-09-25 23:54:10 -04:00
Kurt Himebauch c20a166134 Merge pull request #21 from Droid-Deck/fix/phantom-process-setup-gate
Gate Steam sessions on Android process limit
2026-09-25 23:51:11 -04:00
xXJsonDeruloXx 162fa8e2de Merge remote-tracking branch 'origin/main' into fix/phantom-process-setup-gate 2026-09-25 23:50:57 -04:00
xXJsonDeruloXx ae5614d212 Reuse saved wireless ADB pairing and connection 2026-09-25 23:48:47 -04:00
xXJsonDeruloXx b72d8a8bab Clarify Wireless debugging connection address after pairing 2026-09-25 23:39:31 -04:00
Kurt Himebauch d4cf890d8a feat: set DroidDeck startup movie by default (#25) 2026-09-25 23:36:29 -04:00
xXJsonDeruloXx 82e494269d Improve wireless ADB text input 2026-09-25 23:17:28 -04:00
The412Banner c982d65675 Session drawer: tab spacing fits the room between LB and RB, so all four tabs show 2026-09-25 22:59:50 -04:00
The412Banner f4e606fb15 Components: the pad's LB / RB step through FEX, DXVK and VKD3D-Proton (wrapping), with LB / RB badges beside the tabs 2026-09-25 22:49:10 -04:00
The412Banner 9dbdb5e771 Components: fixed columns so details and Download buttons line up; focused button is a solid blue fill with a white outline 2026-09-25 22:37:07 -04:00
The412Banner fa12478fdd Components: compact layout - one toolbar line (title, Proton drop-down, component tabs, in use, (i), refresh) and one list of short rows for installed and available packages 2026-09-25 22:27:25 -04:00
The412Banner c3b0d8ef03 Merge pull request #23 from Droid-Deck/docs/progress-log-0925
Progress log: 2026-09-25
2026-09-25 22:06:23 -04:00
The412Banner cbb9a168e6 Components: FEX, DXVK and VKD3D-Proton per Proton
A Components entry under Desktop opens a page built like the driver pages: a
Proton drop-down, FEX / DXVK / VKD3D-Proton tabs, what is in use, the installed
rows (each Proton build's original bundle and the stored packages; tap to
swap in, trash to delete), downloads from the Nightlies -Linux releases behind
the refresh button, and Import .wcp.

The session drawer gets a fourth tab, Components, for quick swaps between
what is installed. A swap into the Proton a running game uses waits until the
game closes and is applied then (drawer refresh, or the main screen on resume).

ComponentsManager keeps the same package format, originals layout and state as
the Decky Components Manager plugin and takes its data over once. A swap clears
only the component's own DLLs, so files a Proton keeps beside them stay.
2026-09-25 22:04:38 -04:00
The412Banner 73e2fc58a0 Merge pull request #24 from Droid-Deck/feat/drawer-tab-icons
Session drawer: QAM-style page tabs (Display, Controls, Settings)
2026-09-25 21:55:16 -04:00
The412Banner 500f4c69eb Session drawer: QAM-style page tabs - Display, Controls, Settings
The three page dots between LB and RB become icons standing in a line in page order, as in
Steam's Quick Access Menu. The selected one steps forward (full size, bright, a soft glow in the
accent), the others step back to half size and fade, and the line leans a little toward the
selection; tapping or picking a tab with the pad, and LB / RB, turn the page as before. The
first page's heading becomes Display to match its icon.
2026-09-25 18:11:04 -04:00
xXJsonDeruloXx aa843b5a31 Merge remote-tracking branch 'origin/main' into fix/phantom-process-setup-gate 2026-09-25 17:23:08 -04:00
xXJsonDeruloXx f249acc50f Compact Steam process limit recovery for split screen 2026-09-25 17:21:43 -04:00
xXJsonDeruloXx 9422608960 Replace process gate dialogs with compact pages 2026-09-25 16:34:30 -04:00
Kurt Himebauch de37ddcfb5 Merge branch 'main' into fix/phantom-process-setup-gate 2026-09-25 16:28:53 -04:00
xXJsonDeruloXx 4c90196890 Replace process gate dialogs with pages 2026-09-25 16:28:15 -04:00
xXJsonDeruloXx 30f6ca6ffc Replace wireless ADB modal with setup page 2026-09-25 16:19:01 -04:00
xXJsonDeruloXx ecff3240a6 Add reversible process limit controls 2026-09-25 14:52:04 -04:00
xXJsonDeruloXx ddd4a0c24d Add wireless ADB process-limit repair 2026-09-25 14:35:37 -04:00
xXJsonDeruloXx 019949847a Auto-dismiss process limit gate after status clears 2026-09-25 13:55:04 -04:00
xXJsonDeruloXx 4dcbf269d2 Gate Steam sessions on Android process limit 2026-09-25 13:49:58 -04:00
129 changed files with 11515 additions and 3423 deletions

No files matched your search

+11 -2
View File
@@ -26,7 +26,7 @@ concurrency:
cancel-in-progress: true
env:
PRELOAD_CACHE_VERSION: v1
PRELOAD_CACHE_VERSION: v2
jobs:
build:
@@ -160,7 +160,7 @@ jobs:
D=app/src/main/assets/linuxfs
mkdir -p "$D"
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
-pthread -std=c++17 -static-libstdc++ -static-libgcc \
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
-o "$D/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
aarch64-linux-gnu-strip --strip-unneeded "$D/libfakeinput.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
@@ -270,6 +270,12 @@ jobs:
for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do
grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; }
done
# The static C++ runtime stays private: every session process preloads this library,
# and an exported personality routine takes over other programs' unwinding (shadPS4
# aborted in pthread_exit).
if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then
echo "::error::libfakeinput.so exports the C++ runtime"; exit 1
fi
SESSION=$(syms "$D/libblsession.so")
for sym in socket bind getsockname setsockopt statfs statvfs; do
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
@@ -295,6 +301,9 @@ jobs:
set -o pipefail
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
- name: Unit tests
run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION"
- name: Check the native dependency closure
run: |
set -euo pipefail
+3 -2
View File
@@ -79,8 +79,9 @@ jobs:
}
stable=$(package_line "$RUNNER_TEMP/stable/DroidDeck-$stable_tag.apk")
candidate=$(package_line "${apks[0]}")
[[ "$stable" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && "$candidate" == "$stable" ]] || {
echo "::error::PR package/versionCode '$candidate' differs from stable '$stable'"; exit 1;
[[ "$stable" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && "$candidate" =~ ^com\.droiddeck\.launcher\ [0-9]+$ &&
${candidate##* } -ge ${stable##* } ]] || {
echo "::error::PR package/versionCode '$candidate' cannot install over stable '$stable'"; exit 1;
}
current=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
+4
View File
@@ -35,6 +35,10 @@ jobs:
run: |
set -euo pipefail
[[ $VERSION =~ ^[0-9A-Za-z._-]+$ ]] || { echo "::error::version '$VERSION': letters, digits, . _ - only"; exit 1; }
name=$(sed -n 's/^ *versionName "\(.*\)"$/\1/p' app/build.gradle)
[[ $VERSION == "$name" || $VERSION == "$name"-* ]] || {
echo "::error::version '$VERSION' does not match versionName '$name' in app/build.gradle: bump versionName and versionCode first"; exit 1;
}
runs=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml --branch main --commit "$GITHUB_SHA" \
--status success --json databaseId,event,headSha -L 20)
id=$(jq -r --arg sha "$GITHUB_SHA" \
+1
View File
@@ -28,3 +28,4 @@ app/src/main/jniLibs/arm64-v8a/libproot-loader.so
!keystore/testkey.p12
droiddeck-release-key/
password.txt
__pycache__/
+9 -2
View File
@@ -1,6 +1,13 @@
# DroidDeck
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="artwork/droiddeck-banner-dark.svg">
<img alt="DroidDeck" src="artwork/droiddeck-banner-light.svg" width="100%">
</picture>
</p>
Run Valve's native ARM64 Steam client on an Adreno Android device. Steam runs in a Linux runtime under proot, with gamescope and an in-app Vulkan compositor. Windows games use Valve's ARM64 Proton and FEX. A desktop with LXQt, Firefox, and emulators is also available.
DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Adreno handheld, with Windows games through Valve's ARM64 Proton.
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
## Requirements and install
+17 -3
View File
@@ -63,8 +63,8 @@ android {
// file out of its own data directory, and this app's entire job is to exec a rootfs:
// proot, gamescope, the Steam client and everything it launches all live under files/.
targetSdkVersion 28
versionCode 8
versionName "0.1.7"
versionCode 9
versionName "0.2.0"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
ndk {
@@ -121,6 +121,10 @@ android {
}
packagingOptions {
resources {
// Kadb's Bouncy Castle artifacts repeat the same multi-release JAR manifest.
excludes += ['META-INF/versions/9/OSGI-INF/MANIFEST.MF']
}
jniLibs {
// The PulseAudio daemon is executed from the native library directory and its
// libraries are read out of the apk by the class loader: both want the old,
@@ -136,6 +140,11 @@ android {
buildConfig true
}
testOptions {
// Plain JVM tests: a stray android.util.Log call returns a default instead of throwing.
unitTests.returnDefaultValues = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
@@ -148,7 +157,7 @@ android {
dependencies {
// The runtime tarball is a zstd-compressed tar.
implementation 'com.github.luben:zstd-jni:1.5.2-3@aar'
implementation 'org.apache.commons:commons-compress:1.20'
implementation 'org.apache.commons:commons-compress:1.27.1'
// The UI: every menu, dialog and overlay is Compose. The session's SurfaceView and the
// on-screen pad are Views underneath it, which is what they are in every Compose app.
implementation platform('androidx.compose:compose-bom:2024.02.00')
@@ -160,6 +169,11 @@ dependencies {
implementation 'androidx.compose.material:material-icons-extended'
implementation 'io.coil-kt:coil-compose:2.6.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
// ADB-over-Wi-Fi pairing and authenticated shell client. Users still approve pairing from
// Android's Wireless debugging screen; DroidDeck only runs its one fixed setting command.
implementation 'com.flyfishxu:kadb-android:1.2.1'
// Android terminal view/emulator used by the in-session secondary-display Linux shell.
implementation 'com.termux.termux-app:terminal-view:0.118.0'
testImplementation 'junit:junit:4.13.2'
}
+7 -1
View File
@@ -2,6 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Session logs go to Downloads so a failed run can be handed over as one folder. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
@@ -47,7 +48,8 @@
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="sensorLandscape">
android:screenOrientation="sensorLandscape"
android:configChanges="keyboard|keyboardHidden|navigation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -124,6 +126,10 @@
android:name=".session.SessionService"
android:exported="false"
android:stopWithTask="false" />
<!-- Holds the process in the foreground while the Linux runtime downloads and unpacks. -->
<service
android:name=".runtime.RuntimeInstallService"
android:exported="false" />
<!-- Hands a zipped session folder to the share sheet; nothing else is exposed. -->
<provider
android:name="androidx.core.content.FileProvider"
@@ -13,6 +13,7 @@ add_library(bannerwayland SHARED
src/ahb_swapchain.c
src/waylandcomp_jni.c
src/banner_ext.c
src/wl_dmabuf.c
src/wl_clipboard.c
src/wl_text_input.c
src/wl_toplevel_icon.c
@@ -33,6 +34,9 @@ add_library(bannerwayland SHARED
src/framegen_bridge.c
src/framegen_jni.c
)
# Warnings on for the compositor's own C. They do not fail the build; they are there to be read.
target_compile_options(bannerwayland PRIVATE
$<$<COMPILE_LANGUAGE:C>:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>)
target_include_directories(bannerwayland PRIVATE
generated
prebuilt/include
+13 -366
View File
@@ -51,6 +51,7 @@
#include "effects_chain.h"
#include "banner_ext.h"
#include "banner_color.h"
#include "compositor_internal.h"
#define WLOGI(...) __android_log_print(ANDROID_LOG_INFO, "BannerWayland", __VA_ARGS__)
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "BannerWayland", __VA_ARGS__)
@@ -161,21 +162,9 @@ static int log_budget(void) {
static struct wl_display *g_display;
/* Which program each Wayland client is (from /proc/<pid>/cmdline), for the session log. */
struct client_info {
struct wl_client *client;
struct wl_listener destroy;
pid_t pid;
char name[64];
/* An OpenGL program whose EGL gave up on the GPU: it asked for dma-buf feedback (EGL's
* Wayland GPU path always does), never made a dma-buf buffer, and draws wl_shm frames. */
unsigned asked_feedback : 1, shm_gl_said : 1;
unsigned dmabuf_buffers, shm_frames;
struct client_info *next;
};
static struct client_info *g_clients;
static struct client_info *client_info_of(struct wl_client *client) {
struct client_info *client_info_of(struct wl_client *client) {
for (struct client_info *ci = g_clients; ci; ci = ci->next)
if (ci->client == client) return ci;
return NULL;
@@ -500,7 +489,7 @@ static void cursor_publish_hidden(void) {
}
static void cursor_publish_pixels(const uint8_t *src, int w, int h, size_t stride, int hx, int hy) {
if (w <= 0 || h <= 0 || w * h > CURSOR_MAX_PX) return;
if (w <= 0 || h <= 0 || (int64_t)w * h > CURSOR_MAX_PX) return;
pthread_mutex_lock(&g_cursor_lock);
for (int y = 0; y < h; y++)
memcpy(&g_cursor_px[y * w], src + (size_t)y * stride, (size_t)w * 4);
@@ -513,10 +502,13 @@ static void cursor_publish_pixels(const uint8_t *src, int w, int h, size_t strid
static void cursor_publish_shm(struct wl_shm_buffer *shm, int hx, int hy) {
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
if (w <= 0 || h <= 0 || w * h > CURSOR_MAX_PX) return;
int32_t stride = wl_shm_buffer_get_stride(shm);
if (w <= 0 || h <= 0 || (int64_t)w * h > CURSOR_MAX_PX) return;
/* libwayland only promises stride >= width; each row copied here is width * 4 bytes, so a
* shorter stride would read past the end of the client's pool. */
if ((int64_t)stride < (int64_t)w * 4) return;
wl_shm_buffer_begin_access(shm);
cursor_publish_pixels((const uint8_t *)wl_shm_buffer_get_data(shm), w, h,
(size_t)wl_shm_buffer_get_stride(shm), hx, hy);
cursor_publish_pixels((const uint8_t *)wl_shm_buffer_get_data(shm), w, h, (size_t)stride, hx, hy);
wl_shm_buffer_end_access(shm);
}
@@ -557,40 +549,7 @@ static void constraints_focus_entered(struct wl_resource *target, struct wl_clie
/* ------------------------------------------------------------------ dmabuf buffers */
#define FOURCC(a, b, c, d) \
((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))
#define DRM_ARGB8888 FOURCC('A', 'R', '2', '4')
#define DRM_XRGB8888 FOURCC('X', 'R', '2', '4')
#define DRM_ABGR8888 FOURCC('A', 'B', '2', '4')
#define DRM_XBGR8888 FOURCC('X', 'B', '2', '4')
#define MOD_LINEAR VKP_MOD_LINEAR
#define MOD_INVALID VKP_MOD_INVALID
#define MAX_PLANES 4
struct dmabuf_params {
int fd[MAX_PLANES];
uint32_t offset[MAX_PLANES], stride[MAX_PLANES];
uint64_t modifier[MAX_PLANES];
int n_planes;
};
struct dmabuf_buffer {
int fd[MAX_PLANES];
uint32_t offset[MAX_PLANES], stride[MAX_PLANES];
int n_planes;
int32_t width, height;
uint32_t format;
uint64_t modifier;
struct vkp_image *img; /* imported once, reused for every frame */
int import_failed;
/* One reference for the wl_buffer resource, one per surface showing the buffer. Mesa destroys
* a swapchain's wl_buffers the moment the game rebuilds its swapchain, i.e. while the last
* committed one is still what is on screen: the import (and the dma-buf memory it pins) stays
* until the surface commits something newer, so the picture never blinks to black. */
int refs;
void *ahb_state; /* zero-copy: ahb_swapchain.c's record (the game's AHardwareBuffer) */
};
static void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
if (!b || --b->refs > 0) return;
vkp_image_destroy(b->img);
for (int i = 0; i < b->n_planes; i++)
@@ -601,7 +560,7 @@ static void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
static void dbuf_buffer_destroy_req(struct wl_client *c, struct wl_resource *r) {
wl_resource_destroy(r);
}
static const struct wl_buffer_interface dbuf_buffer_impl = {
const struct wl_buffer_interface dbuf_buffer_impl = {
.destroy = dbuf_buffer_destroy_req,
};
@@ -1018,7 +977,8 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
cursor_publish_hidden(); /* wlroots clears its cursor surface to hide the pointer */
} else if (shm) {
cursor_publish_shm(shm, g_cursor_hx, g_cursor_hy);
} else if (db && db->n_planes >= 1 && db->width * db->height <= CURSOR_MAX_PX) {
} else if (db && db->n_planes >= 1 && db->width > 0 && db->height > 0 &&
(int64_t)db->width * db->height <= CURSOR_MAX_PX) {
if (!db->img && !db->import_failed) {
db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height,
db->stride[0], db->offset[0]);
@@ -1570,319 +1530,6 @@ static void bind_desktop(struct wl_client *c, void *data, uint32_t ver, uint32_t
wl_resource_set_implementation(r, &desktop_impl, NULL, NULL);
}
/* ------------------------------------------------------------ zwp_linux_dmabuf_v1 */
static void dbuf_buffer_resource_destroy(struct wl_resource *r) {
dmabuf_buffer_unref(wl_resource_get_user_data(r));
}
static void params_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static void params_add(struct wl_client *c, struct wl_resource *r, int32_t fd, uint32_t plane,
uint32_t offset, uint32_t stride, uint32_t mod_hi, uint32_t mod_lo) {
struct dmabuf_params *p = wl_resource_get_user_data(r);
if (plane >= MAX_PLANES) { close(fd); return; }
if (p->fd[plane] >= 0) close(p->fd[plane]);
p->fd[plane] = fd;
p->offset[plane] = offset;
p->stride[plane] = stride;
p->modifier[plane] = ((uint64_t)mod_hi << 32) | mod_lo;
if ((int)plane + 1 > p->n_planes) p->n_planes = plane + 1;
}
static struct wl_resource *params_do_create(struct wl_client *c, struct wl_resource *r, uint32_t id,
int32_t w, int32_t h, uint32_t format, uint32_t flags) {
struct dmabuf_params *p = wl_resource_get_user_data(r);
struct dmabuf_buffer *b = calloc(1, sizeof(*b));
if (!b) return NULL;
b->n_planes = p->n_planes;
b->refs = 1; /* the wl_buffer resource's */
b->width = w; b->height = h; b->format = format;
b->modifier = p->modifier[0];
for (int i = 0; i < MAX_PLANES; i++) b->fd[i] = -1;
for (int i = 0; i < p->n_planes; i++) {
b->fd[i] = p->fd[i];
b->offset[i] = p->offset[i];
b->stride[i] = p->stride[i];
p->fd[i] = -1; /* ownership moves to the buffer */
}
struct wl_resource *buf = wl_resource_create(c, &wl_buffer_interface, 1, id);
if (!buf) {
for (int i = 0; i < b->n_planes; i++) if (b->fd[i] >= 0) close(b->fd[i]);
free(b);
wl_client_post_no_memory(c);
return NULL;
}
wl_resource_set_implementation(buf, &dbuf_buffer_impl, b, dbuf_buffer_resource_destroy);
struct client_info *ci = client_info_of(c);
if (ci) ci->dmabuf_buffers++;
return buf;
}
static void params_create(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h,
uint32_t format, uint32_t flags) {
struct wl_resource *buf = params_do_create(c, r, 0, w, h, format, flags);
if (buf) zwp_linux_buffer_params_v1_send_created(r, buf);
else zwp_linux_buffer_params_v1_send_failed(r);
}
static void params_create_immed(struct wl_client *c, struct wl_resource *r, uint32_t buffer_id,
int32_t w, int32_t h, uint32_t format, uint32_t flags) {
params_do_create(c, r, buffer_id, w, h, format, flags);
}
static const struct zwp_linux_buffer_params_v1_interface params_impl = {
.destroy = params_destroy,
.add = params_add,
.create = params_create,
.create_immed = params_create_immed,
};
static void params_resource_destroy(struct wl_resource *r) {
struct dmabuf_params *p = wl_resource_get_user_data(r);
if (!p) return;
for (int i = 0; i < MAX_PLANES; i++)
if (p->fd[i] >= 0) close(p->fd[i]);
free(p);
}
static void dmabuf_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static void dmabuf_create_params(struct wl_client *c, struct wl_resource *r, uint32_t id) {
struct dmabuf_params *p = calloc(1, sizeof(*p));
if (!p) { wl_client_post_no_memory(c); return; }
for (int i = 0; i < MAX_PLANES; i++) p->fd[i] = -1;
struct wl_resource *pr = wl_resource_create(c, &zwp_linux_buffer_params_v1_interface,
wl_resource_get_version(r), id);
if (!pr) { free(p); wl_client_post_no_memory(c); return; }
wl_resource_set_implementation(pr, &params_impl, p, params_resource_destroy);
}
static void dmabuf_get_default_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id);
static void dmabuf_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id,
struct wl_resource *surface);
static const struct zwp_linux_dmabuf_v1_interface dmabuf_impl = {
.destroy = dmabuf_destroy,
.create_params = dmabuf_create_params,
.get_default_feedback = dmabuf_get_default_feedback,
.get_surface_feedback = dmabuf_get_surface_feedback,
};
/* The advertised format/modifier table, built at the first bind from what the renderer's driver
* can import (vkp_dmabuf_modifiers). INVALID is always offered too (Mesa drops it; other clients
* may use it for the implicit path). Without a renderer the list is LINEAR + INVALID, as before. */
/* The last two rows are HDR10's (banner_color.h): A2B10G10R10 as AB30 (alpha) + XB30 (opaque) - Mesa
* lists a VkFormat only when both are advertised, and it is the one 10-bit layout our zero-copy WSI
* can put in a gralloc buffer (AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM). They are advertised ONLY
* while the HDR gate is open, and after the 8-bit rows, so every other session - and every client that
* takes the first format it sees - gets exactly the table it always had. */
#define DMABUF_NFMT_MAX 6
#define DMABUF_NFMT_SDR 4
#define DMABUF_NMOD 4
#define DRM_ABGR2101010 FOURCC('A', 'B', '3', '0')
#define DRM_XBGR2101010 FOURCC('X', 'B', '3', '0')
static struct { uint32_t fmt; uint64_t mods[DMABUF_NMOD]; int n; } g_dmabuf_fmts[DMABUF_NFMT_MAX] = {
{DRM_ARGB8888}, {DRM_XRGB8888}, {DRM_ABGR8888}, {DRM_XBGR8888}, {DRM_ABGR2101010}, {DRM_XBGR2101010}};
static int g_dmabuf_nfmt = DMABUF_NFMT_SDR; /* rows advertised: the SDR four, + 2 with the HDR gate open */
static int g_dmabuf_fmts_ready;
static void dmabuf_build_feedback(void);
static void dmabuf_build_formats(void) {
char line[320];
int pos = 0, compressed = 0;
g_dmabuf_fmts_ready = 1;
g_dmabuf_nfmt = banner_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR;
for (int f = 0; f < g_dmabuf_nfmt; f++) {
uint64_t got[DMABUF_NMOD];
int n = vkp_dmabuf_modifiers(g_dmabuf_fmts[f].fmt, got, DMABUF_NMOD), k = 0;
/* LINEAR first: it is the layout every client and the shm fallback agree on, and the one
* we advertised before this table existed. */
g_dmabuf_fmts[f].mods[k++] = MOD_LINEAR;
for (int i = 0; i < n && k < DMABUF_NMOD - 1; i++) {
if (got[i] == MOD_LINEAR) continue;
if (got[i] == VKP_MOD_QCOM_COMPRESSED && !g_ubwc) continue;
g_dmabuf_fmts[f].mods[k++] = got[i];
if (got[i] == VKP_MOD_QCOM_COMPRESSED) compressed++;
}
g_dmabuf_fmts[f].mods[k++] = MOD_INVALID;
g_dmabuf_fmts[f].n = k;
uint32_t fmt = g_dmabuf_fmts[f].fmt;
pos += snprintf(line + pos, sizeof(line) - (size_t)pos, "%s%c%c%c%c", f ? ", " : "",
fmt & 0xff, (fmt >> 8) & 0xff, (fmt >> 16) & 0xff, (fmt >> 24) & 0xff);
for (int i = 0; i < k - 1 && pos < (int)sizeof(line); i++)
pos += snprintf(line + pos, sizeof(line) - (size_t)pos, "%s%s", i ? "+" : " ",
vkp_modifier_name(g_dmabuf_fmts[f].mods[i]));
if (pos >= (int)sizeof(line)) pos = (int)sizeof(line) - 1;
}
banner_log("dmabuf", "formats: %s%s", line,
!g_ubwc ? " (BANNER_WAYLAND_UBWC=0: qcom_compressed not advertised)" : "");
if (g_ubwc && !compressed)
banner_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: "
"game swapchains stay linear", vkp_gpu_name());
if (g_dmabuf_nfmt > DMABUF_NFMT_SDR) {
/* The rows above always carry LINEAR; say what the compositor's own driver can really import
* for 10-bit, since a gralloc buffer it cannot import is shown on the display layer only. */
uint64_t got[DMABUF_NMOD];
int n = vkp_dmabuf_modifiers(DRM_XBGR2101010, got, DMABUF_NMOD), ubwc10 = 0;
for (int i = 0; i < n; i++) if (got[i] == VKP_MOD_QCOM_COMPRESSED) ubwc10 = 1;
banner_log("color", "10-bit dma-buf formats AB30/XB30 advertised for HDR10; the compositor's driver (%s) "
"imports XB30 %s", vkp_gpu_name(),
n == 0 ? "with no layout it reports (copy path unlikely; display layer only)"
: ubwc10 ? "linear and UBWC" : "linear only (UBWC 10-bit frames: display layer only)");
}
dmabuf_build_feedback();
}
/* ---- dmabuf feedback (zwp_linux_dmabuf_v1 version 4)
*
* Turnip's Vulkan WSI is happy with the version 3 format/modifier events, so every Vulkan game
* worked while we only advertised 3. Mesa's EGL is not: its Wayland platform only takes the GPU
* (kopper/Zink) path when it can bind this interface with FEEDBACK, and with 3 it silently drops
* to its wl_shm software path. On this Proton layer that path has no software rasteriser to fall
* back to (the gallium build is zink+kopper+swrast, no llvmpipe), so the shm buffer it commits is
* never written: a native OpenGL window came out solid black, ~30 shm commits/s and no GPU frame
* at all (Wizardry: The Labyrinth of Lost Souls). Feedback is what makes that path work.
*
* What a client needs from us is one tranche describing "everything the compositor can import":
* a format table it mmaps read-only, the device to allocate on, and the indices it may use.
* Clients binding versions 1-3 keep getting the old format/modifier events instead. */
#ifndef MFD_CLOEXEC
#define MFD_CLOEXEC 0x0001U
#endif
#ifndef MFD_ALLOW_SEALING
#define MFD_ALLOW_SEALING 0x0002U
#endif
#ifndef F_ADD_SEALS
#define F_ADD_SEALS 1033
#define F_SEAL_SEAL 0x0001
#define F_SEAL_SHRINK 0x0002
#define F_SEAL_GROW 0x0004
#define F_SEAL_WRITE 0x0008
#endif
struct dmabuf_fmt_entry { uint32_t format; uint32_t pad; uint64_t modifier; }; /* the wire layout */
static int g_fmt_table_fd = -1; /* sealed read-only memfd of dmabuf_fmt_entry[] */
static size_t g_fmt_table_size;
static uint16_t g_fmt_table_n; /* entries, == the indices a tranche may name */
static dev_t g_main_device; /* the render node clients should allocate on */
/* The GPU we import through is reached with KGSL, not DRM, so there is no render node of our own
* to name. Clients only use main_device to match "the same device as the compositor" and to pick
* a driver; the one DRM render node this platform has is the right answer, and Zink ignores it
* anyway (it renders on the Vulkan device it already has). 0 if the platform has none. */
static dev_t dmabuf_render_node(void) {
static const char *nodes[] = {"/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/card0"};
struct stat st;
if (g_no_render_node) return 0;
for (size_t i = 0; i < sizeof(nodes) / sizeof(nodes[0]); i++)
if (!stat(nodes[i], &st) && S_ISCHR(st.st_mode)) return st.st_rdev;
return 0;
}
static void dmabuf_build_feedback(void) {
struct dmabuf_fmt_entry entries[DMABUF_NFMT_MAX * DMABUF_NMOD];
int n = 0;
g_main_device = dmabuf_render_node();
for (int f = 0; f < g_dmabuf_nfmt; f++)
for (int m = 0; m < g_dmabuf_fmts[f].n; m++) {
if (g_dmabuf_fmts[f].mods[m] == MOD_INVALID) continue; /* never offer INVALID here */
entries[n].format = g_dmabuf_fmts[f].fmt;
entries[n].pad = 0;
entries[n].modifier = g_dmabuf_fmts[f].mods[m];
n++;
}
if (!n) return;
int fd = (int)syscall(__NR_memfd_create, "banner-dmabuf-formats",
MFD_CLOEXEC | MFD_ALLOW_SEALING);
if (fd < 0) { WLOGE("dmabuf feedback: memfd_create failed (%s)", strerror(errno)); return; }
size_t size = (size_t)n * sizeof(entries[0]);
if (write(fd, entries, size) != (ssize_t)size) {
WLOGE("dmabuf feedback: could not write the format table (%s)", strerror(errno));
close(fd);
return;
}
/* The client mmaps this read-only and trusts it not to change under it. */
fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
g_fmt_table_fd = fd;
g_fmt_table_size = size;
g_fmt_table_n = (uint16_t)n;
banner_log("dmabuf", "feedback ready: %d format/modifier pairs, main device %u:%u",
n, (unsigned)major(g_main_device), (unsigned)minor(g_main_device));
/* Vulkan games never need the node. Mesa's EGL did until Wayland layer versionCode 9: without
* one it fell back to a software path that draws nothing here (black window, sound plays). */
if (!g_main_device)
banner_log("dmabuf", "%s: OpenGL games need Wayland layer versionCode 9 or newer, "
"which runs OpenGL on the GPU without a DRM node; older layers show a black window",
g_no_render_node ? "no DRM device named (forced by BANNER_WAYLAND_NO_RENDER_NODE=1)"
: "this device gives apps no display (DRM) device (/dev/dri)");
}
/* One tranche: our device, every pair in the table, no scanout flag. */
static void dmabuf_feedback_send(struct wl_resource *fb) {
struct wl_array dev, idx;
uint16_t *ind;
if (g_fmt_table_fd < 0) { zwp_linux_dmabuf_feedback_v1_send_done(fb); return; }
zwp_linux_dmabuf_feedback_v1_send_format_table(fb, g_fmt_table_fd, (uint32_t)g_fmt_table_size);
wl_array_init(&dev);
memcpy(wl_array_add(&dev, sizeof(dev_t)), &g_main_device, sizeof(dev_t));
zwp_linux_dmabuf_feedback_v1_send_main_device(fb, &dev);
zwp_linux_dmabuf_feedback_v1_send_tranche_target_device(fb, &dev);
wl_array_release(&dev);
wl_array_init(&idx);
ind = wl_array_add(&idx, (size_t)g_fmt_table_n * sizeof(uint16_t));
if (ind) for (uint16_t i = 0; i < g_fmt_table_n; i++) ind[i] = i;
zwp_linux_dmabuf_feedback_v1_send_tranche_formats(fb, &idx);
wl_array_release(&idx);
zwp_linux_dmabuf_feedback_v1_send_tranche_flags(fb, 0);
zwp_linux_dmabuf_feedback_v1_send_tranche_done(fb);
zwp_linux_dmabuf_feedback_v1_send_done(fb);
}
static void dmabuf_feedback_destroy(struct wl_client *c, struct wl_resource *r) {
wl_resource_destroy(r);
}
static const struct zwp_linux_dmabuf_feedback_v1_interface dmabuf_feedback_impl = {
.destroy = dmabuf_feedback_destroy,
};
static void dmabuf_new_feedback(struct wl_client *c, struct wl_resource *parent, uint32_t id) {
struct wl_resource *fb = wl_resource_create(c, &zwp_linux_dmabuf_feedback_v1_interface,
wl_resource_get_version(parent), id);
if (!fb) { wl_client_post_no_memory(c); return; }
wl_resource_set_implementation(fb, &dmabuf_feedback_impl, NULL, NULL);
if (!g_dmabuf_fmts_ready) dmabuf_build_formats();
dmabuf_feedback_send(fb);
}
static void dmabuf_get_default_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id) {
struct client_info *ci = client_info_of(c);
if (ci) ci->asked_feedback = 1;
dmabuf_new_feedback(c, r, id);
}
/* Per-surface feedback would let us hint a different tranche for a window on its own display
* layer; we have nothing better to say per surface, so it is the default one. */
static void dmabuf_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id,
struct wl_resource *surface) {
dmabuf_new_feedback(c, r, id);
}
static void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
struct wl_resource *r = wl_resource_create(c, &zwp_linux_dmabuf_v1_interface, ver, id);
wl_resource_set_implementation(r, &dmabuf_impl, NULL, NULL);
if (!g_dmabuf_fmts_ready) dmabuf_build_formats();
/* From version 4 the format and modifier events are gone: the client asks for feedback
* instead, and sending both would only confuse it about which list is authoritative. */
if (ver >= 4) return;
for (int f = 0; f < g_dmabuf_nfmt; f++) {
zwp_linux_dmabuf_v1_send_format(r, g_dmabuf_fmts[f].fmt);
if (ver >= 3)
for (int m = 0; m < g_dmabuf_fmts[f].n; m++)
zwp_linux_dmabuf_v1_send_modifier(r, g_dmabuf_fmts[f].fmt,
(uint32_t)(g_dmabuf_fmts[f].mods[m] >> 32),
(uint32_t)(g_dmabuf_fmts[f].mods[m] & 0xffffffff));
}
}
/* ------------------------------------------------------------------ wl_output */
/* wl_output v3+ has a request (release); without an implementation the first client to send it
@@ -0,0 +1,76 @@
/*
* What compositor.c shares with the protocol modules split out of it (wl_dmabuf.c): the dma-buf
* buffer records, the per-client bookkeeping and the few functions and globals both sides use.
* Everything declared here is hidden: it is internal to libbannerwayland, not part of its ABI.
*/
#pragma once
#include <stdint.h>
#include <sys/types.h>
#include <android/log.h>
#include <wayland-server.h>
#include "vk_present.h"
#define COMPOSITOR_INTERNAL __attribute__((visibility("hidden")))
#ifndef WLOGE
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "BannerWayland", __VA_ARGS__)
#endif
/* ------------------------------------------------------------------ dmabuf buffers */
#define FOURCC(a, b, c, d) \
((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))
#define DRM_ARGB8888 FOURCC('A', 'R', '2', '4')
#define DRM_XRGB8888 FOURCC('X', 'R', '2', '4')
#define DRM_ABGR8888 FOURCC('A', 'B', '2', '4')
#define DRM_XBGR8888 FOURCC('X', 'B', '2', '4')
#define MOD_LINEAR VKP_MOD_LINEAR
#define MOD_INVALID VKP_MOD_INVALID
#define MAX_PLANES 4
struct dmabuf_params {
int fd[MAX_PLANES];
uint32_t offset[MAX_PLANES], stride[MAX_PLANES];
uint64_t modifier[MAX_PLANES];
int n_planes;
};
struct dmabuf_buffer {
int fd[MAX_PLANES];
uint32_t offset[MAX_PLANES], stride[MAX_PLANES];
int n_planes;
int32_t width, height;
uint32_t format;
uint64_t modifier;
struct vkp_image *img; /* imported once, reused for every frame */
int import_failed;
/* One reference for the wl_buffer resource, one per surface showing the buffer. Mesa destroys
* a swapchain's wl_buffers the moment the game rebuilds its swapchain, i.e. while the last
* committed one is still what is on screen: the import (and the dma-buf memory it pins) stays
* until the surface commits something newer, so the picture never blinks to black. */
int refs;
void *ahb_state; /* zero-copy: ahb_swapchain.c's record (the game's AHardwareBuffer) */
};
/* Which program each Wayland client is (from /proc/<pid>/cmdline), for the session log. */
struct client_info {
struct wl_client *client;
struct wl_listener destroy;
pid_t pid;
char name[64];
/* An OpenGL program whose EGL gave up on the GPU: it asked for dma-buf feedback (EGL's
* Wayland GPU path always does), never made a dma-buf buffer, and draws wl_shm frames. */
unsigned asked_feedback : 1, shm_gl_said : 1;
unsigned dmabuf_buffers, shm_frames;
struct client_info *next;
};
/* ---- compositor.c */
COMPOSITOR_INTERNAL struct client_info *client_info_of(struct wl_client *client);
COMPOSITOR_INTERNAL void dmabuf_buffer_unref(struct dmabuf_buffer *b);
COMPOSITOR_INTERNAL extern const struct wl_buffer_interface dbuf_buffer_impl;
extern volatile int g_ubwc; /* BANNER_WAYLAND_UBWC (waylandcomp_jni.c sets it) */
extern volatile int g_no_render_node; /* BANNER_WAYLAND_NO_RENDER_NODE */
/* ---- wl_dmabuf.c */
COMPOSITOR_INTERNAL extern dev_t g_main_device; /* the render node clients are told to allocate on */
COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id);
@@ -0,0 +1,334 @@
/*
* zwp_linux_dmabuf_v1: the buffer params a client builds a dma-buf wl_buffer from, the format and
* modifier table the renderer can import, and dma-buf feedback (version 4). Split out of
* compositor.c; the buffer records themselves are in compositor_internal.h.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <wayland-server.h>
#include "linux-dmabuf-v1-server-protocol.h"
#include "vk_present.h"
#include "banner_ext.h"
#include "banner_color.h"
#include "compositor_internal.h"
/* ------------------------------------------------------------ zwp_linux_dmabuf_v1 */
static void dbuf_buffer_resource_destroy(struct wl_resource *r) {
dmabuf_buffer_unref(wl_resource_get_user_data(r));
}
static void params_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static void params_add(struct wl_client *c, struct wl_resource *r, int32_t fd, uint32_t plane,
uint32_t offset, uint32_t stride, uint32_t mod_hi, uint32_t mod_lo) {
struct dmabuf_params *p = wl_resource_get_user_data(r);
if (plane >= MAX_PLANES) { close(fd); return; }
if (p->fd[plane] >= 0) close(p->fd[plane]);
p->fd[plane] = fd;
p->offset[plane] = offset;
p->stride[plane] = stride;
p->modifier[plane] = ((uint64_t)mod_hi << 32) | mod_lo;
if ((int)plane + 1 > p->n_planes) p->n_planes = plane + 1;
}
static struct wl_resource *params_do_create(struct wl_client *c, struct wl_resource *r, uint32_t id,
int32_t w, int32_t h, uint32_t format, uint32_t flags) {
struct dmabuf_params *p = wl_resource_get_user_data(r);
struct dmabuf_buffer *b = calloc(1, sizeof(*b));
if (!b) return NULL;
b->n_planes = p->n_planes;
b->refs = 1; /* the wl_buffer resource's */
b->width = w; b->height = h; b->format = format;
b->modifier = p->modifier[0];
for (int i = 0; i < MAX_PLANES; i++) b->fd[i] = -1;
for (int i = 0; i < p->n_planes; i++) {
b->fd[i] = p->fd[i];
b->offset[i] = p->offset[i];
b->stride[i] = p->stride[i];
p->fd[i] = -1; /* ownership moves to the buffer */
}
struct wl_resource *buf = wl_resource_create(c, &wl_buffer_interface, 1, id);
if (!buf) {
for (int i = 0; i < b->n_planes; i++) if (b->fd[i] >= 0) close(b->fd[i]);
free(b);
wl_client_post_no_memory(c);
return NULL;
}
wl_resource_set_implementation(buf, &dbuf_buffer_impl, b, dbuf_buffer_resource_destroy);
struct client_info *ci = client_info_of(c);
if (ci) ci->dmabuf_buffers++;
return buf;
}
static void params_create(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h,
uint32_t format, uint32_t flags) {
struct wl_resource *buf = params_do_create(c, r, 0, w, h, format, flags);
if (buf) zwp_linux_buffer_params_v1_send_created(r, buf);
else zwp_linux_buffer_params_v1_send_failed(r);
}
static void params_create_immed(struct wl_client *c, struct wl_resource *r, uint32_t buffer_id,
int32_t w, int32_t h, uint32_t format, uint32_t flags) {
params_do_create(c, r, buffer_id, w, h, format, flags);
}
static const struct zwp_linux_buffer_params_v1_interface params_impl = {
.destroy = params_destroy,
.add = params_add,
.create = params_create,
.create_immed = params_create_immed,
};
static void params_resource_destroy(struct wl_resource *r) {
struct dmabuf_params *p = wl_resource_get_user_data(r);
if (!p) return;
for (int i = 0; i < MAX_PLANES; i++)
if (p->fd[i] >= 0) close(p->fd[i]);
free(p);
}
static void dmabuf_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static void dmabuf_create_params(struct wl_client *c, struct wl_resource *r, uint32_t id) {
struct dmabuf_params *p = calloc(1, sizeof(*p));
if (!p) { wl_client_post_no_memory(c); return; }
for (int i = 0; i < MAX_PLANES; i++) p->fd[i] = -1;
struct wl_resource *pr = wl_resource_create(c, &zwp_linux_buffer_params_v1_interface,
wl_resource_get_version(r), id);
if (!pr) { free(p); wl_client_post_no_memory(c); return; }
wl_resource_set_implementation(pr, &params_impl, p, params_resource_destroy);
}
static void dmabuf_get_default_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id);
static void dmabuf_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id,
struct wl_resource *surface);
static const struct zwp_linux_dmabuf_v1_interface dmabuf_impl = {
.destroy = dmabuf_destroy,
.create_params = dmabuf_create_params,
.get_default_feedback = dmabuf_get_default_feedback,
.get_surface_feedback = dmabuf_get_surface_feedback,
};
/* The advertised format/modifier table, built at the first bind from what the renderer's driver
* can import (vkp_dmabuf_modifiers). INVALID is always offered too (Mesa drops it; other clients
* may use it for the implicit path). Without a renderer the list is LINEAR + INVALID, as before. */
/* The last two rows are HDR10's (banner_color.h): A2B10G10R10 as AB30 (alpha) + XB30 (opaque) - Mesa
* lists a VkFormat only when both are advertised, and it is the one 10-bit layout our zero-copy WSI
* can put in a gralloc buffer (AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM). They are advertised ONLY
* while the HDR gate is open, and after the 8-bit rows, so every other session - and every client that
* takes the first format it sees - gets exactly the table it always had. */
#define DMABUF_NFMT_MAX 6
#define DMABUF_NFMT_SDR 4
#define DMABUF_NMOD 4
#define DRM_ABGR2101010 FOURCC('A', 'B', '3', '0')
#define DRM_XBGR2101010 FOURCC('X', 'B', '3', '0')
static struct { uint32_t fmt; uint64_t mods[DMABUF_NMOD]; int n; } g_dmabuf_fmts[DMABUF_NFMT_MAX] = {
{DRM_ARGB8888}, {DRM_XRGB8888}, {DRM_ABGR8888}, {DRM_XBGR8888}, {DRM_ABGR2101010}, {DRM_XBGR2101010}};
static int g_dmabuf_nfmt = DMABUF_NFMT_SDR; /* rows advertised: the SDR four, + 2 with the HDR gate open */
static int g_dmabuf_fmts_ready;
static void dmabuf_build_feedback(void);
static void dmabuf_build_formats(void) {
char line[320];
int pos = 0, compressed = 0;
g_dmabuf_fmts_ready = 1;
g_dmabuf_nfmt = banner_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR;
for (int f = 0; f < g_dmabuf_nfmt; f++) {
uint64_t got[DMABUF_NMOD];
int n = vkp_dmabuf_modifiers(g_dmabuf_fmts[f].fmt, got, DMABUF_NMOD), k = 0;
/* LINEAR first: it is the layout every client and the shm fallback agree on, and the one
* we advertised before this table existed. */
g_dmabuf_fmts[f].mods[k++] = MOD_LINEAR;
for (int i = 0; i < n && k < DMABUF_NMOD - 1; i++) {
if (got[i] == MOD_LINEAR) continue;
if (got[i] == VKP_MOD_QCOM_COMPRESSED && !g_ubwc) continue;
g_dmabuf_fmts[f].mods[k++] = got[i];
if (got[i] == VKP_MOD_QCOM_COMPRESSED) compressed++;
}
g_dmabuf_fmts[f].mods[k++] = MOD_INVALID;
g_dmabuf_fmts[f].n = k;
uint32_t fmt = g_dmabuf_fmts[f].fmt;
pos += snprintf(line + pos, sizeof(line) - (size_t)pos, "%s%c%c%c%c", f ? ", " : "",
fmt & 0xff, (fmt >> 8) & 0xff, (fmt >> 16) & 0xff, (fmt >> 24) & 0xff);
for (int i = 0; i < k - 1 && pos < (int)sizeof(line); i++)
pos += snprintf(line + pos, sizeof(line) - (size_t)pos, "%s%s", i ? "+" : " ",
vkp_modifier_name(g_dmabuf_fmts[f].mods[i]));
if (pos >= (int)sizeof(line)) pos = (int)sizeof(line) - 1;
}
banner_log("dmabuf", "formats: %s%s", line,
!g_ubwc ? " (BANNER_WAYLAND_UBWC=0: qcom_compressed not advertised)" : "");
if (g_ubwc && !compressed)
banner_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: "
"game swapchains stay linear", vkp_gpu_name());
if (g_dmabuf_nfmt > DMABUF_NFMT_SDR) {
/* The rows above always carry LINEAR; say what the compositor's own driver can really import
* for 10-bit, since a gralloc buffer it cannot import is shown on the display layer only. */
uint64_t got[DMABUF_NMOD];
int n = vkp_dmabuf_modifiers(DRM_XBGR2101010, got, DMABUF_NMOD), ubwc10 = 0;
for (int i = 0; i < n; i++) if (got[i] == VKP_MOD_QCOM_COMPRESSED) ubwc10 = 1;
banner_log("color", "10-bit dma-buf formats AB30/XB30 advertised for HDR10; the compositor's driver (%s) "
"imports XB30 %s", vkp_gpu_name(),
n == 0 ? "with no layout it reports (copy path unlikely; display layer only)"
: ubwc10 ? "linear and UBWC" : "linear only (UBWC 10-bit frames: display layer only)");
}
dmabuf_build_feedback();
}
/* ---- dmabuf feedback (zwp_linux_dmabuf_v1 version 4)
*
* Turnip's Vulkan WSI is happy with the version 3 format/modifier events, so every Vulkan game
* worked while we only advertised 3. Mesa's EGL is not: its Wayland platform only takes the GPU
* (kopper/Zink) path when it can bind this interface with FEEDBACK, and with 3 it silently drops
* to its wl_shm software path. On this Proton layer that path has no software rasteriser to fall
* back to (the gallium build is zink+kopper+swrast, no llvmpipe), so the shm buffer it commits is
* never written: a native OpenGL window came out solid black, ~30 shm commits/s and no GPU frame
* at all (Wizardry: The Labyrinth of Lost Souls). Feedback is what makes that path work.
*
* What a client needs from us is one tranche describing "everything the compositor can import":
* a format table it mmaps read-only, the device to allocate on, and the indices it may use.
* Clients binding versions 1-3 keep getting the old format/modifier events instead. */
#ifndef MFD_CLOEXEC
#define MFD_CLOEXEC 0x0001U
#endif
#ifndef MFD_ALLOW_SEALING
#define MFD_ALLOW_SEALING 0x0002U
#endif
#ifndef F_ADD_SEALS
#define F_ADD_SEALS 1033
#define F_SEAL_SEAL 0x0001
#define F_SEAL_SHRINK 0x0002
#define F_SEAL_GROW 0x0004
#define F_SEAL_WRITE 0x0008
#endif
struct dmabuf_fmt_entry { uint32_t format; uint32_t pad; uint64_t modifier; }; /* the wire layout */
static int g_fmt_table_fd = -1; /* sealed read-only memfd of dmabuf_fmt_entry[] */
static size_t g_fmt_table_size;
static uint16_t g_fmt_table_n; /* entries, == the indices a tranche may name */
dev_t g_main_device; /* the render node clients should allocate on */
/* The GPU we import through is reached with KGSL, not DRM, so there is no render node of our own
* to name. Clients only use main_device to match "the same device as the compositor" and to pick
* a driver; the one DRM render node this platform has is the right answer, and Zink ignores it
* anyway (it renders on the Vulkan device it already has). 0 if the platform has none. */
static dev_t dmabuf_render_node(void) {
static const char *nodes[] = {"/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/card0"};
struct stat st;
if (g_no_render_node) return 0;
for (size_t i = 0; i < sizeof(nodes) / sizeof(nodes[0]); i++)
if (!stat(nodes[i], &st) && S_ISCHR(st.st_mode)) return st.st_rdev;
return 0;
}
static void dmabuf_build_feedback(void) {
struct dmabuf_fmt_entry entries[DMABUF_NFMT_MAX * DMABUF_NMOD];
int n = 0;
g_main_device = dmabuf_render_node();
for (int f = 0; f < g_dmabuf_nfmt; f++)
for (int m = 0; m < g_dmabuf_fmts[f].n; m++) {
if (g_dmabuf_fmts[f].mods[m] == MOD_INVALID) continue; /* never offer INVALID here */
entries[n].format = g_dmabuf_fmts[f].fmt;
entries[n].pad = 0;
entries[n].modifier = g_dmabuf_fmts[f].mods[m];
n++;
}
if (!n) return;
int fd = (int)syscall(__NR_memfd_create, "banner-dmabuf-formats",
MFD_CLOEXEC | MFD_ALLOW_SEALING);
if (fd < 0) { WLOGE("dmabuf feedback: memfd_create failed (%s)", strerror(errno)); return; }
size_t size = (size_t)n * sizeof(entries[0]);
if (write(fd, entries, size) != (ssize_t)size) {
WLOGE("dmabuf feedback: could not write the format table (%s)", strerror(errno));
close(fd);
return;
}
/* The client mmaps this read-only and trusts it not to change under it. */
fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
g_fmt_table_fd = fd;
g_fmt_table_size = size;
g_fmt_table_n = (uint16_t)n;
banner_log("dmabuf", "feedback ready: %d format/modifier pairs, main device %u:%u",
n, (unsigned)major(g_main_device), (unsigned)minor(g_main_device));
/* Vulkan games never need the node. Mesa's EGL did until Wayland layer versionCode 9: without
* one it fell back to a software path that draws nothing here (black window, sound plays). */
if (!g_main_device)
banner_log("dmabuf", "%s: OpenGL games need Wayland layer versionCode 9 or newer, "
"which runs OpenGL on the GPU without a DRM node; older layers show a black window",
g_no_render_node ? "no DRM device named (forced by BANNER_WAYLAND_NO_RENDER_NODE=1)"
: "this device gives apps no display (DRM) device (/dev/dri)");
}
/* One tranche: our device, every pair in the table, no scanout flag. */
static void dmabuf_feedback_send(struct wl_resource *fb) {
struct wl_array dev, idx;
uint16_t *ind;
if (g_fmt_table_fd < 0) { zwp_linux_dmabuf_feedback_v1_send_done(fb); return; }
zwp_linux_dmabuf_feedback_v1_send_format_table(fb, g_fmt_table_fd, (uint32_t)g_fmt_table_size);
wl_array_init(&dev);
memcpy(wl_array_add(&dev, sizeof(dev_t)), &g_main_device, sizeof(dev_t));
zwp_linux_dmabuf_feedback_v1_send_main_device(fb, &dev);
zwp_linux_dmabuf_feedback_v1_send_tranche_target_device(fb, &dev);
wl_array_release(&dev);
wl_array_init(&idx);
ind = wl_array_add(&idx, (size_t)g_fmt_table_n * sizeof(uint16_t));
if (ind) for (uint16_t i = 0; i < g_fmt_table_n; i++) ind[i] = i;
zwp_linux_dmabuf_feedback_v1_send_tranche_formats(fb, &idx);
wl_array_release(&idx);
zwp_linux_dmabuf_feedback_v1_send_tranche_flags(fb, 0);
zwp_linux_dmabuf_feedback_v1_send_tranche_done(fb);
zwp_linux_dmabuf_feedback_v1_send_done(fb);
}
static void dmabuf_feedback_destroy(struct wl_client *c, struct wl_resource *r) {
wl_resource_destroy(r);
}
static const struct zwp_linux_dmabuf_feedback_v1_interface dmabuf_feedback_impl = {
.destroy = dmabuf_feedback_destroy,
};
static void dmabuf_new_feedback(struct wl_client *c, struct wl_resource *parent, uint32_t id) {
struct wl_resource *fb = wl_resource_create(c, &zwp_linux_dmabuf_feedback_v1_interface,
wl_resource_get_version(parent), id);
if (!fb) { wl_client_post_no_memory(c); return; }
wl_resource_set_implementation(fb, &dmabuf_feedback_impl, NULL, NULL);
if (!g_dmabuf_fmts_ready) dmabuf_build_formats();
dmabuf_feedback_send(fb);
}
static void dmabuf_get_default_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id) {
struct client_info *ci = client_info_of(c);
if (ci) ci->asked_feedback = 1;
dmabuf_new_feedback(c, r, id);
}
/* Per-surface feedback would let us hint a different tranche for a window on its own display
* layer; we have nothing better to say per surface, so it is the default one. */
static void dmabuf_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id,
struct wl_resource *surface) {
dmabuf_new_feedback(c, r, id);
}
void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
struct wl_resource *r = wl_resource_create(c, &zwp_linux_dmabuf_v1_interface, ver, id);
wl_resource_set_implementation(r, &dmabuf_impl, NULL, NULL);
if (!g_dmabuf_fmts_ready) dmabuf_build_formats();
/* From version 4 the format and modifier events are gone: the client asks for feedback
* instead, and sending both would only confuse it about which list is authoritative. */
if (ver >= 4) return;
for (int f = 0; f < g_dmabuf_nfmt; f++) {
zwp_linux_dmabuf_v1_send_format(r, g_dmabuf_fmts[f].fmt);
if (ver >= 3)
for (int m = 0; m < g_dmabuf_fmts[f].n; m++)
zwp_linux_dmabuf_v1_send_modifier(r, g_dmabuf_fmts[f].fmt,
(uint32_t)(g_dmabuf_fmts[f].mods[m] >> 32),
(uint32_t)(g_dmabuf_fmts[f].mods[m] & 0xffffffff));
}
}
@@ -0,0 +1,84 @@
package com.droiddeck.launcher
import android.os.Handler
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ComponentsManager
/**
* The Components page's state and work: the Protons and their DXVK/VKD3D sets, the Nightlies
* catalog, downloads and the swap/restore actions. The launcher screen keeps one and shows it.
*/
internal class ComponentsMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
var compSnapshot by mutableStateOf<ComponentsManager.Snapshot?>(null)
var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList())
var compCatalogAt by mutableStateOf(0L)
var compProton by mutableStateOf<String?>(null)
var compComp by mutableStateOf("dxvk")
var compChecking by mutableStateOf(false)
var compBusy by mutableStateOf<String?>(null)
var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap())
/** Reads the Protons (and on first open saves their originals) off the UI thread; the Nightlies list comes from its cache. */
fun refreshComponents(snapshotFirst: Boolean = false) {
Thread({
if (snapshotFirst) runCatching { ComponentsManager.snapshotAll(activity) }
runCatching { ComponentsManager.applyQueued(activity) }
val snap = runCatching { ComponentsManager.snapshot(activity) }.onFailure { Log.w(TAG, "components", it) }.getOrNull()
val cat = runCatching { ComponentsManager.catalog(activity, false) }.getOrNull()
ui.post {
compSnapshot = snap ?: ComponentsManager.Snapshot(emptyList(), emptyList())
if (cat != null && cat.fetchedAt > 0) { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
if (compProton == null || snap?.protons?.none { it.proton.id == compProton } == true) compProton = snap?.protons?.firstOrNull()?.proton?.id
}
}, "components").start()
}
fun componentAction(label: String, work: () -> String) {
if (compBusy != null) return
compBusy = label
Thread({
val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
ui.post {
compBusy = null
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
refreshComponents()
}
}, "components-action").start()
}
fun refreshComponentCatalog() {
if (compChecking) return
compChecking = true
Thread({
val cat = runCatching { ComponentsManager.catalog(activity, true) }.getOrNull()
ui.post {
compChecking = false
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(activity, "The Nightlies could not be reached", android.widget.Toast.LENGTH_LONG).show()
else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
}
}, "components-catalog").start()
}
fun downloadComponent(item: ComponentsManager.CatalogItem) {
if (compDownloads.containsKey(item.file)) return
compDownloads = compDownloads + (item.file to -1)
Thread({
val message = runCatching {
val pkg = ComponentsManager.download(activity, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } }
"Stored ${pkg.version}"
}.getOrElse { e -> "Download failed: ${e.message ?: e.javaClass.simpleName}" }
ui.post {
compDownloads = compDownloads - item.file
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_SHORT).show()
refreshComponents()
}
}, "components-download").start()
}
private companion object {
const val TAG = "MainActivity"
}
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher
import android.os.Handler
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.session.SessionState
/**
* Decky Loader's state in the launcher: what is installed, the releases on offer and an install
* in progress. The launcher screen keeps one and shows it.
*/
internal class DeckyMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
var deckyInstalled by mutableStateOf<String?>(null)
var deckyReleases by mutableStateOf<List<DeckyManager.Release>>(emptyList())
var deckyChecking by mutableStateOf(false)
var deckyStage by mutableStateOf<String?>(null)
var deckyPercent by mutableIntStateOf(-1)
var deckySupervisor by mutableStateOf(false)
var deckyReleaseRequest = 0
fun refreshDecky() {
val request = ++deckyReleaseRequest
deckyChecking = true
Thread({
val channels = runCatching { DeckyManager.releaseChannels(activity) }
.getOrElse { DeckyManager.ReleaseChannels(emptyList(), emptyList()) }
ui.post {
if (request == deckyReleaseRequest) {
// Use the newest compatible stable build, or the newest compatible
// prerelease when the fork has not published a stable ARM64 asset.
deckyReleases = channels.stable.ifEmpty { channels.prerelease }
deckyChecking = false
}
}
}, "decky-releases").start()
}
fun installDecky(release: DeckyManager.Release) {
if (deckyStage != null || SessionState.running) return
deckyStage = "Starting…"; deckyPercent = -1
Thread({
val problem = runCatching {
DeckyManager.install(activity, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
}.getOrElse { error -> "Decky install failed: ${error.message ?: error.javaClass.simpleName}" }
ui.post {
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(activity)
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
}
}, "install-decky").start()
}
}
@@ -0,0 +1,217 @@
package com.droiddeck.launcher
import android.app.Activity
import android.content.Context
import java.io.File
import android.net.Uri
import android.provider.OpenableColumns
import android.os.Handler
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.DriverRow
/**
* The Linux and Android driver menus: the drivers each can pick from, the release downloads the
* last check found, and what each mode is set to. The launcher screen keeps one and hands its
* rows to the mode settings dialog.
*/
internal class DriverMenus(private val activity: Activity, private val ui: Handler) {
var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
var releaseStatus by mutableStateOf("Not checked yet - tap refresh to look for new drivers")
var releaseChecking by mutableStateOf(false)
var canRestoreBundled by mutableStateOf(false)
/** Asset name -> download percent, while it downloads. */
private val releaseProgress = HashMap<String, Int>()
var linuxSteam by mutableStateOf("")
var linuxDesktop by mutableStateOf("")
var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
var androidSelected by mutableStateOf("")
fun refreshDrivers() {
val lm = LinuxVulkanDriverManager(activity)
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
else DriverRow(
id, lm.getDriverName(id),
listOfNotNull(
lm.getDriverVersion(id).takeIf { it.isNotEmpty() },
lm.getMinGlibc(id).takeIf { it.isNotEmpty() }?.let { "glibc $it+" },
).joinToString(" · "),
true, origin(id),
)
}
linuxSteam = SessionPrefs.linuxDriver(activity, SessionService.MODE_STEAM)
linuxDesktop = SessionPrefs.linuxDriver(activity, SessionService.MODE_DESKTOP)
val td = TurnipDriver(activity)
val auto = td.autoId()
androidRows = buildList {
add(DriverRow(
TurnipDriver.AUTO, "Auto - picked by GPU",
if (auto == "system") "system Vulkan: no bundled build for this GPU" else "${td.displayName(auto)} (bundled)",
false,
))
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id)))
}
canRestoreBundled = td.hiddenBundled().isNotEmpty()
androidSelected = SessionPrefs.androidDriver(activity)
refreshReleaseRows()
}
/**
* Import off the main thread - a driver zip is a few MB and the glibc check reads the whole
* library - then say what happened. A refusal's message is the user-facing reason.
*/
fun importDriver(uri: Uri, linux: Boolean) {
val name = activity.displayNameOf(uri)
Thread({
val problem = try {
if (linux) LinuxVulkanDriverManager(activity).installDriver(uri, name)
else TurnipDriver(activity).installFromZip(uri, name)
null
} catch (e: IllegalArgumentException) {
e.message
} catch (e: Exception) {
Log.w(TAG, "driver import", e)
"Import failed: ${e.message}"
}
ui.post {
android.widget.Toast.makeText(
activity, problem ?: "Imported ${name ?: "driver"}",
if (problem != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
).show()
refreshDrivers()
}
}, "import-driver").start()
}
/**
* Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a
* session never starts on a driver that is gone; a release download is forgotten, so the menu
* offers it again.
*/
fun deleteDriver(id: String, linux: Boolean) {
if (linux) {
LinuxVulkanDriverManager(activity).removeDriver(id)
for (mode in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
if (SessionPrefs.linuxDriver(activity, mode) == id) SessionPrefs.setLinuxDriver(activity, mode, "")
}
} else {
val td = TurnipDriver(activity)
if (id in TurnipDriver.BUNDLED) td.hideBundled(id) else td.remove(id)
if (SessionPrefs.androidDriver(activity) == id) SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
}
TurnipReleases.forget(activity, id)
android.widget.Toast.makeText(activity, "Deleted ${id}", android.widget.Toast.LENGTH_SHORT).show()
refreshDrivers()
}
/** The download entries and the refresh line, from what the last check found. */
fun refreshReleaseRows() {
val check = TurnipReleases.cached(activity)
val lm = LinuxVulkanDriverManager(activity)
val td = TurnipDriver(activity)
fun rows(linux: Boolean) = check?.assets.orEmpty()
.filter { it.linux == linux }
.filter { a -> TurnipReleases.installedId(activity, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null }
.map { a ->
val mb = "%.1f MB".format(a.size / 1_048_576.0)
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
}
linuxDownloads = rows(linux = true)
androidDownloads = rows(linux = false)
if (!releaseChecking) releaseStatus = when (check) {
null -> "Not checked yet - tap refresh to look for new drivers"
else -> "Latest: " + check.latest.joinToString(" · ") { "${it.first} ${it.second}" } +
(if (check.failed.isEmpty()) "" else " · ${check.failed.joinToString()} unreachable") +
" · checked ${ago(check.checkedAt)}"
}
}
private fun ago(t: Long): String {
val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0)
return when {
m < 1 -> "just now"
m < 60 -> "$m min ago"
m < 48 * 60 -> "${m / 60} h ago"
else -> "${m / (24 * 60)} days ago"
}
}
/** Only when the user taps refresh: nothing goes online on its own. */
fun checkLatestTurnip() {
if (releaseChecking) return
releaseChecking = true
releaseStatus = "Checking Banners-Turnip and WinNative…"
Thread({
val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) {
Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
}
ui.post {
releaseChecking = false
refreshReleaseRows()
if (problem != null) releaseStatus = "Couldn't check: $problem"
}
}, "turnip-release-check").start()
}
/** Download one release driver and import it through the same importer a picked zip uses. */
fun downloadReleaseDriver(assetName: String) {
val asset = TurnipReleases.cached(activity)?.assets?.firstOrNull { it.name == assetName } ?: return
if (releaseProgress.containsKey(assetName)) return
releaseProgress[assetName] = 0
refreshReleaseRows()
Thread({
var file: java.io.File? = null
val problem = try {
file = TurnipReleases.download(activity, asset) { pct ->
ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() }
}
val uri = Uri.fromFile(file)
val id = if (asset.linux) LinuxVulkanDriverManager(activity).installDriver(uri, asset.name)
else TurnipDriver(activity).installFromZip(uri, asset.name)
TurnipReleases.recordDownload(activity, asset, id)
null
} catch (e: IllegalArgumentException) {
e.message
} catch (e: Exception) {
Log.w(TAG, "release driver download", e)
"Download failed: ${e.message}"
} finally {
file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) }
}
ui.post {
releaseProgress.remove(assetName)
android.widget.Toast.makeText(
activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu",
android.widget.Toast.LENGTH_LONG,
).show()
refreshDrivers()
}
}, "download-turnip").start()
}
private companion object {
const val TAG = "MainActivity"
}
}
internal fun Context.displayNameOf(uri: Uri): String? = if (uri.scheme == "file") uri.lastPathSegment else try {
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
} catch (e: Exception) {
null
}
@@ -97,13 +97,11 @@ object HomeApp {
val intent = Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(ComponentName(app.packageName, app.className))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (displayId == null) {
context.startActivity(intent)
return
}
// Keep the target app's task separate from DroidDeck. Without this, Android can put the
// app on top of the caller's task and move the entire task to the chosen display.
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
context.startActivity(intent, options.toBundle())
}
@@ -1,17 +1,21 @@
package com.droiddeck.launcher
import android.Manifest
import android.app.ActivityOptions
import android.content.Intent
import android.content.ClipData
import android.content.ClipboardManager
import java.io.File
import android.content.pm.PackageManager
import android.hardware.display.DisplayManager
import android.net.Uri
import android.provider.OpenableColumns
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Display
import android.view.KeyEvent
import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
@@ -20,11 +24,9 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.toArgb
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.gpu.LsfgNative
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.DesktopCatalog
@@ -34,17 +36,20 @@ import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.ui.PackageRow
import com.droiddeck.launcher.session.OfflineMode
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.ProtonPage
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.core.CpuCores
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
import com.droiddeck.launcher.core.WirelessAdbFix
import com.droiddeck.launcher.ui.CoreRow
import com.droiddeck.launcher.ui.PerformancePage
import com.droiddeck.launcher.ui.ModeSettingsPage
import com.droiddeck.launcher.ui.ModeSettings
import com.droiddeck.launcher.ui.ModeSettingsActions
import com.droiddeck.launcher.ui.DriverRow
import com.droiddeck.launcher.ui.ConfirmDialog
import com.droiddeck.launcher.ui.ControllerActions
import com.droiddeck.launcher.ui.ControllerMappingPage
@@ -72,9 +77,17 @@ import com.droiddeck.launcher.input.SecondScreenDisplays
*/
class MainActivity : ComponentActivity() {
private val ui = Handler(Looper.getMainLooper())
private val drivers = DriverMenus(this, ui)
private val components = ComponentsMenu(this, ui)
private val decky = DeckyMenu(this, ui)
private val protons = ProtonMenu(this, ui)
// The screen's state. Compose redraws whatever reads these when they change.
private var installed by mutableStateOf<String?>(null)
/** A session launch waiting on its button to fill the page (LaunchFlood). */
private var flood by mutableStateOf<PendingFlood?>(null)
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
private var ready by mutableStateOf(false)
private var available by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
private var busy by mutableStateOf(false)
@@ -89,13 +102,9 @@ class MainActivity : ComponentActivity() {
private var steamDeckMode by mutableStateOf(false)
private var showCredits by mutableStateOf(false)
private var showProtons by mutableStateOf(false)
private var deckyInstalled by mutableStateOf<String?>(null)
private var deckyReleases by mutableStateOf<List<DeckyManager.Release>>(emptyList())
private var deckyChecking by mutableStateOf(false)
private var deckyStage by mutableStateOf<String?>(null)
private var deckyPercent by mutableIntStateOf(-1)
private var deckySupervisor by mutableStateOf(false)
private var deckyReleaseRequest = 0
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
private var showComponents by mutableStateOf(false)
private var focusComponentsContent by mutableStateOf(true)
private var showMapping by mutableStateOf(false)
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
@@ -107,10 +116,6 @@ class MainActivity : ComponentActivity() {
private var desktopInstalled by mutableStateOf(false)
private var offlineAccount by mutableStateOf<String?>(null)
private var offline by mutableStateOf(false)
private var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
private var protonBusyId by mutableStateOf<String?>(null)
private var protonStage by mutableStateOf<String?>(null)
private var protonPercent by mutableIntStateOf(-1)
private var showPerformance by mutableStateOf(false)
private var clientOverride by mutableStateOf(false)
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
@@ -120,31 +125,24 @@ class MainActivity : ComponentActivity() {
private var noXalia by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var phantomWarning by mutableStateOf<String?>(null)
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false)
private var clientDirectAudio by mutableStateOf(false)
private var forceFullscreen by mutableStateOf(true)
private var launcherFullscreen by mutableStateOf(true)
private var mic by mutableStateOf(false)
private var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
private var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
private var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
private var releaseStatus by mutableStateOf("Not checked yet - tap refresh to look for new drivers")
private var releaseChecking by mutableStateOf(false)
private var canRestoreBundled by mutableStateOf(false)
/** Asset name -> download percent, while it downloads. */
private val releaseProgress = HashMap<String, Int>()
private var linuxSteam by mutableStateOf("")
private var linuxDesktop by mutableStateOf("")
private var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
private var androidSelected by mutableStateOf("")
// The app's own picker (files/), once per kind of pick: the two driver lists validate
// differently, and the reason a zip is refused names the list it belongs in.
private val pickComponent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importComponent(it) }
}
private val pickLinuxDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = true) }
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = true) }
}
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = false) }
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = false) }
}
private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
@@ -181,7 +179,8 @@ class MainActivity : ComponentActivity() {
private var customResolution by mutableStateOf<Pair<Int, Int>?>(null)
private var fexPreset by mutableStateOf("")
private var steamChannel by mutableStateOf("publicbeta")
private var theme by mutableStateOf("paper")
private var runSteamAtStartup by mutableStateOf(false)
private var theme by mutableStateOf("graphite")
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
private var hdrOn by mutableStateOf(false)
private var hdrReason by mutableStateOf<String?>(null)
@@ -221,7 +220,7 @@ class MainActivity : ComponentActivity() {
override fun startActivity(intent: Intent?) {
if (intent?.component?.className == SessionActivity::class.java.name) {
when {
protonBusyId != null || ProtonExtras.installInProgress -> {
protons.protonBusyId != null || ProtonExtras.installInProgress -> {
android.widget.Toast.makeText(this, "Wait for the compatibility tool install to finish", android.widget.Toast.LENGTH_SHORT).show()
return
}
@@ -231,15 +230,36 @@ class MainActivity : ComponentActivity() {
}
}
}
if (intent?.component?.className == SessionActivity::class.java.name) {
if (flood != null) return
// Started by a blue button: it floods the page first. A running session is re-joined
// as before, rising over the front end.
val from = com.droiddeck.launcher.ui.LaunchOrigin.take()
if (from != null && !SessionState.running && com.droiddeck.launcher.ui.Motion.scale != 0f) {
flood = PendingFlood(from, intent)
return
}
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
}
super.startActivity(intent)
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
}
/** The page is all blue: the session opens on the same blue, with no animation of its own. */
private fun launchFlooded(f: PendingFlood) {
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
super.startActivity(f.intent.putExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, signal.toArgb()))
overridePendingTransition(0, 0)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
theme = SessionPrefs.theme(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
applyLauncherFullscreen()
setContent {
DroidDeckTheme(theme) {
val sm = settingsMode
@@ -247,9 +267,11 @@ class MainActivity : ComponentActivity() {
sm != null -> { { ModeSettingsHost(sm) } }
showPerformance -> { { PerformanceHost() } }
showProtons -> { { ProtonHost() } }
showComponents -> { { ComponentsHost() } }
showMapping -> { { MappingHost() } }
else -> null
}
com.droiddeck.launcher.ui.FloodBehind({ floodProgress }) {
FrontEndScreen(
FrontEndState(
installed = installed, ready = ready, available = available?.version,
@@ -260,7 +282,7 @@ class MainActivity : ComponentActivity() {
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
frameGenEngine = FrameGen.engine(this), frameGenMultiplier = FrameGen.multiplier(this),
lsfgReady = LsfgNative.isInstalled(this),
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showMapping) "controller-mapping" else null,
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
theme = theme,
isHomeApp = homeAppSelected,
homeScreenEnabled = homeScreenEnabled,
@@ -277,19 +299,22 @@ class MainActivity : ComponentActivity() {
buildLabel = BuildConfig.BUILD_LABEL,
oscMode = oscMode,
controller = controllerSettings,
phantomProcessStatus = phantomProcessStatus,
showPhantomGate = showPhantomGate,
launcherFullscreen = launcherFullscreen,
),
FrontEndActions(
onPlay = { startSession(Intent(this, SessionActivity::class.java)) },
onPlay = { startSteamSession() },
// Steam's desktop client as a window on the desktop: under gamescope the
// client puts itself into Big Picture whatever it is started with.
onPlayDesktopUi = {
startSession(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"))
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
},
onSteamGame = { g ->
startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"))
startSession(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"), steamSession = true)
},
onDesktop = {
startSession(Intent(this, SessionActivity::class.java)
@@ -315,9 +340,14 @@ class MainActivity : ComponentActivity() {
frameGenLabel = FrameGen.label(this)
},
onProtons = { openProtons() },
onPerformance = { refreshCores(); showProtons = false; showMapping = false; showPerformance = true },
onComponents = { focusContent -> openComponents(focusContent) },
onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true },
onRoms = { showRoms = true },
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
onBrowseFiles = { dir ->
startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)
.putExtra(com.droiddeck.launcher.files.FileManagerActivity.EXTRA_START_DIR, dir.absolutePath))
},
onLogs = {
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
logsEnabled = SessionPrefs.logsEnabled(this)
@@ -336,8 +366,13 @@ class MainActivity : ComponentActivity() {
offline = OfflineMode.enabled(this)
},
onCredits = { showCredits = true },
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showMapping = false },
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false },
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
onLauncherFullscreen = { on ->
SessionPrefs.setLauncherFullscreen(this, on)
launcherFullscreen = on
applyLauncherFullscreen()
},
onHomeApp = { manageHomeApp() },
onHomeScreen = { on ->
HomeApp.setHomeScreenEnabled(this, on)
@@ -351,6 +386,50 @@ class MainActivity : ComponentActivity() {
onCheckLatestBuild = {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml")))
},
onRefreshPhantomStatus = { refreshPhantomStatus() },
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) },
onWirelessAdbPair = { host, port, code, complete ->
Thread({
val result = runCatching {
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
}
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging pairing failed" }
ui.post { complete(error) }
}, "wireless-adb-pair").start()
},
onFindWirelessAdbPort = { host, complete ->
Thread({
val port = WirelessAdbFix.findConnectPort(this@MainActivity, host)
ui.post { complete(port) }
}, "wireless-adb-discovery").start()
},
onWirelessAdbApply = { host, port, enabled, complete ->
Thread({
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging command failed" }
ui.post {
if (error == null) refreshPhantomStatus()
complete(error)
}
}, "wireless-adb-fix").start()
},
onSetPhantomProcessLimit = { enabled, complete ->
Thread({
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging is unavailable" }
ui.post {
if (error == null) refreshPhantomStatus()
complete(error)
}
}, "wireless-adb-setting").start()
},
onCopyPhantomCommand = { enabled ->
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
ClipData.newPlainText("DroidDeck child-process setting", PhantomProcessLimit.adbCommand(enabled)),
)
android.widget.Toast.makeText(this, "ADB command copied", android.widget.Toast.LENGTH_SHORT).show()
},
onDismissPhantomGate = { showPhantomGate = false },
controller = ControllerActions(
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() },
@@ -360,12 +439,13 @@ class MainActivity : ComponentActivity() {
onAdaptiveSticks = { on -> ControllerPrefs.setAdaptiveSticks(this, on); refreshController() },
onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) },
onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() },
onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showMapping = true },
onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = true },
onResetAll = { ControllerPrefs.resetAll(this); refreshController() },
),
),
page = page,
)
}
if (showRoms) RomsDialog(
path = romsDir,
onChoose = {
@@ -392,9 +472,12 @@ class MainActivity : ComponentActivity() {
onDismiss = { showRemove = false },
)
if (showCredits) CreditsDialog { showCredits = false }
flood?.let { f -> com.droiddeck.launcher.ui.LaunchFlood(f.from, onProgress = { floodProgress = it }) { launchFlooded(f) } }
}
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
// The session's logs land in Downloads so a failed run can be handed over as a folder
// rather than dug out of app-private storage. targetSdk 28 means the old permission still
// grants exactly that.
@@ -417,16 +500,73 @@ class MainActivity : ComponentActivity() {
}, "finish-abandoned").start()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
startSteamAtStartupIfEnabled()
}
private fun startSteamAtStartupIfEnabled() {
if (SessionPrefs.runSteamAtStartup(this) && !isFinishing && !isDestroyed) startSteamSession()
}
private fun startSteamSession() {
startSession(Intent(this, SessionActivity::class.java), steamSession = true)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) applyLauncherFullscreen()
}
private fun applyLauncherFullscreen() {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = if (launcherFullscreen) {
(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
} else {
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
}
}
/** On the Components page the pad's LB / RB step through FEX, DXVK and VKD3D-Proton, wrapping around. */
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
val all = ComponentsManager.COMPONENTS
val step = if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else all.size - 1
components.compComp = all[(all.indexOf(components.compComp).coerceAtLeast(0) + step) % all.size]
}
return true
}
return super.dispatchKeyEvent(event)
}
override fun onResume() {
super.onResume()
com.droiddeck.launcher.ui.Motion.refresh(this)
refreshPhantomStatus()
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
// session has just ended). Cheap when nothing is queued.
if (!SessionState.running) Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
if (applied.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
if (showComponents) components.refreshComponents()
}
}, "components-queue").start()
oscMode = SessionPrefs.oscMode(this)
refreshController()
refreshHomeAppState()
refreshSecondScreenDisplays()
refresh()
deckyInstalled = DeckyManager.installed(this)
decky.deckyInstalled = DeckyManager.installed(this)
DeckyManager.syncCefMarker(this)
deckySupervisor = DeckyManager.supervisorEnabled(this)
decky.deckySupervisor = DeckyManager.supervisorEnabled(this)
// Added games' art (a store lookup for what the folders lack) starts here, not only when
// the cog opens.
refreshAddedGames()
@@ -442,6 +582,10 @@ class MainActivity : ComponentActivity() {
override fun onStop() {
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
// The session covers the page by now; coming back finds it as it was.
flood = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
super.onStop()
}
@@ -492,40 +636,10 @@ class MainActivity : ComponentActivity() {
private fun openProtons() {
settingsMode = null
showPerformance = false
showComponents = false
showMapping = false
showProtons = true
refreshProtons()
}
private fun refreshDecky() {
val request = ++deckyReleaseRequest
deckyChecking = true
Thread({
val channels = runCatching { DeckyManager.releaseChannels(this) }
.getOrElse { DeckyManager.ReleaseChannels(emptyList(), emptyList()) }
ui.post {
if (request == deckyReleaseRequest) {
// Use the newest compatible stable build, or the newest compatible
// prerelease when the fork has not published a stable ARM64 asset.
deckyReleases = channels.stable.ifEmpty { channels.prerelease }
deckyChecking = false
}
}
}, "decky-releases").start()
}
private fun installDecky(release: DeckyManager.Release) {
if (deckyStage != null || SessionState.running) return
deckyStage = "Starting…"; deckyPercent = -1
Thread({
val problem = runCatching {
DeckyManager.install(this, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
}.getOrElse { error -> "Decky install failed: ${error.message ?: error.javaClass.simpleName}" }
ui.post {
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(this)
if (problem != null) android.widget.Toast.makeText(this, problem, android.widget.Toast.LENGTH_LONG).show()
}
}, "install-decky").start()
protons.refreshProtons()
}
private fun refreshController() {
@@ -543,57 +657,65 @@ class MainActivity : ComponentActivity() {
)
}
private fun openComponents(focusContent: Boolean = true) {
focusComponentsContent = focusContent
settingsMode = null
showPerformance = false
showProtons = false
showMapping = false
showComponents = true
components.refreshComponents(snapshotFirst = true)
}
private fun importComponent(uri: Uri) {
val name = displayNameOf(uri) ?: "imported.wcp"
components.componentAction("Importing") {
val tmp = File(cacheDir, "component-import.wcp")
contentResolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("cannot read the file")
try { "Imported ${ComponentsManager.importPackage(this, tmp, name).version}" } finally { tmp.delete() }
}
}
@Composable
private fun ProtonHost() {
ProtonPage(
rows = protonRows,
busyId = protonBusyId,
stage = protonStage,
percent = protonPercent,
runtimeReady = ready,
sessionRunning = SessionState.running,
onInstall = { id -> installProton(id) },
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; refreshProtons() },
onRemove = { id -> removeProton(id) },
onBack = { showProtons = false },
private fun ComponentsHost() {
ComponentsPage(
snapshot = components.compSnapshot,
catalog = components.compCatalog,
catalogAt = components.compCatalogAt,
protonId = components.compProton,
comp = components.compComp,
checking = components.compChecking,
busy = components.compBusy,
downloads = components.compDownloads,
requestInitialFocus = focusComponentsContent,
onProton = { components.compProton = it },
onComp = { components.compComp = it },
onSwap = { file -> components.compProton?.let { pid -> components.componentAction("Swapping") { ComponentsManager.swap(this, pid, file) } } },
onRestore = { version -> components.compProton?.let { pid -> components.componentAction("Restoring") { ComponentsManager.restore(this, pid, components.compComp, version) } } },
onCancelQueued = { components.compProton?.let { pid -> components.componentAction("Cancelling") { ComponentsManager.cancelQueued(this, pid, components.compComp); "The waiting swap was cancelled." } } },
onDeletePackage = { file -> components.componentAction("Deleting") { ComponentsManager.deletePackage(this, file) } },
onDeleteOriginal = { version -> components.compProton?.let { pid -> components.componentAction("Deleting") { ComponentsManager.deleteOriginal(this, pid, components.compComp, version) } } },
onDownload = { components.downloadComponent(it) },
onRefresh = { components.refreshComponentCatalog() },
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) },
onBack = { showComponents = false },
)
}
private fun installProton(id: String) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return
ProtonExtras.unqueue(this, tool)
protonBusyId = id
protonStage = "Starting…"
protonPercent = -1
Thread({
val problem = ProtonExtras.install(this, tool) { label, value ->
ui.post { protonStage = label; protonPercent = value }
}
ui.post {
protonBusyId = null
protonStage = null
protonPercent = -1
refreshProtons()
if (problem != null) android.widget.Toast.makeText(this, problem, android.widget.Toast.LENGTH_LONG).show()
}
}, "install-proton-$id").start()
}
private fun removeProton(id: String) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return
protonBusyId = id
protonStage = "Removing ${tool.name}…"
protonPercent = -1
Thread({
ProtonExtras.remove(this, tool)
ui.post {
protonBusyId = null
protonStage = null
refreshProtons()
}
}, "remove-proton-$id").start()
@Composable
private fun ProtonHost() {
ProtonPage(
rows = protons.protonRows,
busyId = protons.protonBusyId,
stage = protons.protonStage,
percent = protons.protonPercent,
runtimeReady = ready,
sessionRunning = SessionState.running,
onInstall = { id -> protons.installProton(id) },
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
onRemove = { id -> protons.removeProton(id) },
onBack = { showProtons = false },
)
}
private fun refreshPackages() {
@@ -644,9 +766,9 @@ class MainActivity : ComponentActivity() {
ModeSettings(
mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode,
hdr = hdrOn, hdrReason = hdrReason,
linuxRows = linuxRows,
linuxSelected = if (mode == SessionService.MODE_STEAM) linuxSteam else linuxDesktop,
androidRows = androidRows, androidSelected = androidSelected,
linuxRows = drivers.linuxRows,
linuxSelected = if (mode == SessionService.MODE_STEAM) drivers.linuxSteam else drivers.linuxDesktop,
androidRows = drivers.androidRows, androidSelected = drivers.androidSelected,
touchMode = touchMode,
suspendPolicy = suspendPolicy,
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
@@ -660,30 +782,31 @@ class MainActivity : ComponentActivity() {
storageOptions = storageOptions,
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
addedGamesArt = addedGamesArt,
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, releaseStatus = releaseStatus,
releaseChecking = releaseChecking, canRestoreBundled = canRestoreBundled,
deckyInstalled = if (mode == SessionService.MODE_STEAM) deckyInstalled else null,
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) deckyReleases.firstOrNull() else null,
deckyChecking = deckyChecking, deckyStage = deckyStage, deckyPercent = deckyPercent,
deckyEnabled = deckySupervisor, deckySessionRunning = SessionState.running,
linuxDownloads = drivers.linuxDownloads, androidDownloads = drivers.androidDownloads, releaseStatus = drivers.releaseStatus,
releaseChecking = drivers.releaseChecking, canRestoreBundled = drivers.canRestoreBundled,
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null,
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
),
ModeSettingsActions(
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size },
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); refreshDrivers() },
onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); drivers.refreshDrivers() },
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) },
onRemoveLinux = { id -> deleteDriver(id, linux = true) },
onRefreshReleases = { checkLatestTurnip() },
onDownloadDriver = { name -> downloadReleaseDriver(name) },
onRestoreBundled = { TurnipDriver(this).restoreBundled(); refreshDrivers() },
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); refreshDrivers() },
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
onRefreshReleases = { drivers.checkLatestTurnip() },
onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) },
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); drivers.refreshDrivers() },
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) },
onRemoveAndroid = { id -> deleteDriver(id, linux = false) },
onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
@@ -710,6 +833,10 @@ class MainActivity : ComponentActivity() {
},
onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id },
onRunSteamAtStartup = { on ->
SessionPrefs.setRunSteamAtStartup(this, on)
runSteamAtStartup = on
},
onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, "Choose a folder of your own games", addedGamesDirs.lastOrNull())) },
onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() },
onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() },
@@ -718,13 +845,13 @@ class MainActivity : ComponentActivity() {
pendingAddedGame = folder
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), "Choose the game's .exe", folder))
},
onDeckyInstall = { release -> installDecky(release) },
onDeckyCheck = { refreshDecky() },
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); deckySupervisor = enabled },
onDeckyInstall = { release -> decky.installDecky(release) },
onDeckyCheck = { decky.refreshDecky() },
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); decky.deckySupervisor = enabled },
onDeckyUninstall = {
DeckyManager.uninstall(this, wipeData = false)
deckyInstalled = null
deckySupervisor = false
decky.deckyInstalled = null
decky.deckySupervisor = false
},
onDismiss = { settingsMode = null },
),
@@ -781,12 +908,14 @@ class MainActivity : ComponentActivity() {
private fun openModeSettings(mode: String) {
showPerformance = false
showProtons = false
showComponents = false
showMapping = false
refreshDrivers()
drivers.refreshDrivers()
resolutionCap = SessionPrefs.resolutionCap(this, mode)
customResolution = SessionPrefs.customResolution(this, mode)
fexPreset = SessionPrefs.fexPreset(this)
steamChannel = SessionPrefs.steamChannel(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
addedGamesDirs = SessionPrefs.addedGamesDirs(this)
refreshAddedGames()
shapeMode = SessionPrefs.shapeMode(this)
@@ -804,9 +933,9 @@ class MainActivity : ComponentActivity() {
gameStorage = SessionPrefs.gameStorage(this)
storageOptions = GameStorage.options(this).map { it.label to it.path }
if (mode == SessionService.MODE_STEAM) {
deckyInstalled = DeckyManager.installed(this)
deckySupervisor = DeckyManager.supervisorEnabled(this)
refreshDecky()
decky.deckyInstalled = DeckyManager.installed(this)
decky.deckySupervisor = DeckyManager.supervisorEnabled(this)
decky.refreshDecky()
}
settingsMode = mode
}
@@ -824,178 +953,6 @@ class MainActivity : ComponentActivity() {
gameStorage = path
}
private fun refreshDrivers() {
val lm = LinuxVulkanDriverManager(this)
fun origin(id: String) = if (TurnipReleases.isDownloaded(this, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
linuxRows = LinuxVulkanDriver.optionValues(this).map { id ->
if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
else DriverRow(
id, lm.getDriverName(id),
listOfNotNull(
lm.getDriverVersion(id).takeIf { it.isNotEmpty() },
lm.getMinGlibc(id).takeIf { it.isNotEmpty() }?.let { "glibc $it+" },
).joinToString(" · "),
true, origin(id),
)
}
linuxSteam = SessionPrefs.linuxDriver(this, SessionService.MODE_STEAM)
linuxDesktop = SessionPrefs.linuxDriver(this, SessionService.MODE_DESKTOP)
val td = TurnipDriver(this)
val auto = td.autoId()
androidRows = buildList {
add(DriverRow(
TurnipDriver.AUTO, "Auto - picked by GPU",
if (auto == "system") "system Vulkan: no bundled build for this GPU" else "${td.displayName(auto)} (bundled)",
false,
))
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id)))
}
canRestoreBundled = td.hiddenBundled().isNotEmpty()
androidSelected = SessionPrefs.androidDriver(this)
refreshReleaseRows()
}
/**
* Import off the main thread - a driver zip is a few MB and the glibc check reads the whole
* library - then say what happened. A refusal's message is the user-facing reason.
*/
private fun importDriver(uri: Uri, linux: Boolean) {
val name = displayNameOf(uri)
Thread({
val problem = try {
if (linux) LinuxVulkanDriverManager(this).installDriver(uri, name)
else TurnipDriver(this).installFromZip(uri, name)
null
} catch (e: IllegalArgumentException) {
e.message
} catch (e: Exception) {
Log.w(TAG, "driver import", e)
"Import failed: ${e.message}"
}
ui.post {
android.widget.Toast.makeText(
this, problem ?: "Imported ${name ?: "driver"}",
if (problem != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
).show()
refreshDrivers()
}
}, "import-driver").start()
}
/**
* Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a
* session never starts on a driver that is gone; a release download is forgotten, so the menu
* offers it again.
*/
private fun deleteDriver(id: String, linux: Boolean) {
if (linux) {
LinuxVulkanDriverManager(this).removeDriver(id)
for (mode in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
if (SessionPrefs.linuxDriver(this, mode) == id) SessionPrefs.setLinuxDriver(this, mode, "")
}
} else {
val td = TurnipDriver(this)
if (id in TurnipDriver.BUNDLED) td.hideBundled(id) else td.remove(id)
if (SessionPrefs.androidDriver(this) == id) SessionPrefs.setAndroidDriver(this, TurnipDriver.AUTO)
}
TurnipReleases.forget(this, id)
android.widget.Toast.makeText(this, "Deleted ${id}", android.widget.Toast.LENGTH_SHORT).show()
refreshDrivers()
}
/** The download entries and the refresh line, from what the last check found. */
private fun refreshReleaseRows() {
val check = TurnipReleases.cached(this)
val lm = LinuxVulkanDriverManager(this)
val td = TurnipDriver(this)
fun rows(linux: Boolean) = check?.assets.orEmpty()
.filter { it.linux == linux }
.filter { a -> TurnipReleases.installedId(this, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null }
.map { a ->
val mb = "%.1f MB".format(a.size / 1_048_576.0)
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
}
linuxDownloads = rows(linux = true)
androidDownloads = rows(linux = false)
if (!releaseChecking) releaseStatus = when (check) {
null -> "Not checked yet - tap refresh to look for new drivers"
else -> "Latest: " + check.latest.joinToString(" · ") { "${it.first} ${it.second}" } +
(if (check.failed.isEmpty()) "" else " · ${check.failed.joinToString()} unreachable") +
" · checked ${ago(check.checkedAt)}"
}
}
private fun ago(t: Long): String {
val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0)
return when {
m < 1 -> "just now"
m < 60 -> "$m min ago"
m < 48 * 60 -> "${m / 60} h ago"
else -> "${m / (24 * 60)} days ago"
}
}
/** Only when the user taps refresh: nothing goes online on its own. */
private fun checkLatestTurnip() {
if (releaseChecking) return
releaseChecking = true
releaseStatus = "Checking Banners-Turnip and WinNative…"
Thread({
val problem = try { TurnipReleases.refresh(this); null } catch (e: Exception) {
Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
}
ui.post {
releaseChecking = false
refreshReleaseRows()
if (problem != null) releaseStatus = "Couldn't check: $problem"
}
}, "turnip-release-check").start()
}
/** Download one release driver and import it through the same importer a picked zip uses. */
private fun downloadReleaseDriver(assetName: String) {
val asset = TurnipReleases.cached(this)?.assets?.firstOrNull { it.name == assetName } ?: return
if (releaseProgress.containsKey(assetName)) return
releaseProgress[assetName] = 0
refreshReleaseRows()
Thread({
var file: java.io.File? = null
val problem = try {
file = TurnipReleases.download(this, asset) { pct ->
ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() }
}
val uri = Uri.fromFile(file)
val id = if (asset.linux) LinuxVulkanDriverManager(this).installDriver(uri, asset.name)
else TurnipDriver(this).installFromZip(uri, asset.name)
TurnipReleases.recordDownload(this, asset, id)
null
} catch (e: IllegalArgumentException) {
e.message
} catch (e: Exception) {
Log.w(TAG, "release driver download", e)
"Download failed: ${e.message}"
} finally {
file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) }
}
ui.post {
releaseProgress.remove(assetName)
android.widget.Toast.makeText(
this, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu",
android.widget.Toast.LENGTH_LONG,
).show()
refreshDrivers()
}
}, "download-turnip").start()
}
private fun displayNameOf(uri: Uri): String? = if (uri.scheme == "file") uri.lastPathSegment else try {
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
} catch (e: Exception) {
null
}
/** The two masks as the dialog shows them; an empty stored list shows as every core ticked. */
private fun refreshCores() {
clientOverride = SessionPrefs.clientCpusOverride(this)
@@ -1008,24 +965,11 @@ class MainActivity : ComponentActivity() {
zinkLazy = SessionPrefs.zinkLazy(this)
noXalia = SessionPrefs.noXalia(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
// Android 12 kills the children an app forks itself once there are more than a handful.
// A session is nothing but those, so where this is on the OS ends the session and no log
// of ours says why. We cannot change a secure setting from here - only say so.
phantomWarning = runCatching {
android.provider.Settings.Global.getString(contentResolver, "settings_enable_monitor_phantom_procs")
}.getOrNull().let { v ->
when (v?.lowercase()) {
"false", "0" -> null
else -> "Android 12 and later kill the extra processes an app starts for itself once there are more than a few, and a session is made of dozens: proot, gamescope, the client and its helpers, Wine. Where that is left on, the client dies with nothing in its log, because nothing in the session did it. Some phones have a \"restrict child processes\" switch in Developer options - turn it off. Otherwise, over adb:\n\n adb shell settings put global settings_enable_monitor_phantom_procs false\n\nThis phone " + (if (v == null) "has not been set either way, so the ROM's default applies." else "currently reports it as on.")
}
}
}
private fun refreshProtons() {
protonRows = ProtonExtras.tools.map { ProtonRow(it.id, it.name, ProtonExtras.installed(this, it), ProtonExtras.queued(this, it)) }
refreshPhantomStatus()
}
private fun refresh() {
if (!busy && LinuxRuntimeInstaller.isInstalling()) followInstall { LinuxRuntimeInstaller.attach(it) }
desktopInstalled = DesktopCatalog.desktopInstalled(this)
offlineAccount = OfflineMode.account(this)
offline = OfflineMode.enabled(this)
@@ -1042,7 +986,13 @@ class MainActivity : ComponentActivity() {
// The libraries, off the main thread: manifests and a folder scan.
Thread({
val games = if (ready) Library.steamGames(this) + com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art -> Library.SteamGame(g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId) }
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art ->
Library.SteamGame(
g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId,
hero = art.hero ?: art.header, gameFiles = g.folder,
protonPrefix = Library.protonPrefix(this, g.appId),
)
}
} else emptyList()
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
ui.post { steamGames = games; emulatorList = emus }
@@ -1075,24 +1025,64 @@ class MainActivity : ComponentActivity() {
}
/** Starts a session; with no runtime on a non-Adreno, the same warning Setup gives comes first, before any download. */
private fun startSession(intent: Intent) {
private fun startSession(intent: Intent, steamSession: Boolean = false) {
refreshPhantomStatus()
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
showPhantomGate = true
return
}
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
if (warn && available != null) showNonAdreno = available
else startActivity(intent)
}
private fun refreshPhantomStatus() {
phantomProcessStatus = PhantomProcessLimit.read(contentResolver)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
"${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.ADB_COMMAND}"
} else null
}
private fun openDeveloperOptions(displayId: Int?) {
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
if (displayId == null) startActivity(intent)
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
} catch (error: Exception) {
if (displayId != null) {
runCatching { startActivity(intent) }
android.widget.Toast.makeText(this, "Could not open Settings on the bottom screen; opened it on the main screen.", android.widget.Toast.LENGTH_LONG).show()
} else {
startActivity(Intent(android.provider.Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
android.widget.Toast.makeText(this, "Open Developer options in Settings", android.widget.Toast.LENGTH_LONG).show()
}
}
}
private fun install(release: LinuxRuntimeInstaller.Release) {
// The service keeps the process alive if the user switches away; this screen joins the
// same install (or starts it, if it gets there first) to show the progress.
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
followInstall { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
}
/**
* Shows an install's progress until it ends. [run] either starts one or joins the one already
* running (null: nothing was), which is how a launcher rebuilt mid-install picks it back up.
*/
private fun followInstall(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
busy = true
failed = false
stage = "Starting…"
percent = -1
Thread({
val ok = LinuxRuntimeInstaller.install(this, release) { s, p ->
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
ui.post { stage = s; percent = p }
}
})
ui.post {
busy = false
failed = !ok
if (ok != null) failed = !ok
refresh()
}
}, "install").start()
@@ -1108,5 +1098,6 @@ class MainActivity : ComponentActivity() {
private const val TAG = "MainActivity"
/** What the picker offers for a driver zip; some file apps label a zip as a plain stream. */
private val ZIP_EXT = listOf("zip")
private val WCP_EXT = listOf("wcp")
}
}
@@ -0,0 +1,62 @@
package com.droiddeck.launcher
import android.os.Handler
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
/**
* The optional ARM64 Protons (GE-Proton, proton-cachyos): the rows the page lists and an install or
* removal in progress. The launcher screen keeps one and shows it.
*/
internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
var protonBusyId by mutableStateOf<String?>(null)
var protonStage by mutableStateOf<String?>(null)
var protonPercent by mutableIntStateOf(-1)
fun installProton(id: String) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return
ProtonExtras.unqueue(activity, tool)
protonBusyId = id
protonStage = "Starting…"
protonPercent = -1
Thread({
val problem = ProtonExtras.install(activity, tool) { label, value ->
ui.post { protonStage = label; protonPercent = value }
}
ui.post {
protonBusyId = null
protonStage = null
protonPercent = -1
refreshProtons()
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
}
}, "install-proton-$id").start()
}
fun removeProton(id: String) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return
protonBusyId = id
protonStage = "Removing ${tool.name}…"
protonPercent = -1
Thread({
ProtonExtras.remove(activity, tool)
ui.post {
protonBusyId = null
protonStage = null
refreshProtons()
}
}, "remove-proton-$id").start()
}
fun refreshProtons() {
protonRows = ProtonExtras.tools.map { ProtonRow(it.id, it.name, ProtonExtras.installed(activity, it), ProtonExtras.queued(activity, it)) }
}
}
@@ -69,6 +69,8 @@ import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.DRAWER_PAGES
import kotlin.math.abs
/**
@@ -95,6 +97,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f))
private var cursorVisible by mutableStateOf(false)
/** The blue the front end flooded to on the way in; the loading screen opens on it (LaunchFlood). */
private var floodColor by mutableStateOf<Int?>(null)
private val cursorHide = Runnable { cursorVisible = false }
/** When the pad or the on-screen controls were last used (uptimeMillis); see [showCursor]. */
private var lastPadInputMs = 0L
@@ -140,6 +144,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// Compose reads these; the activity writes them.
private var drawerOpen by mutableStateOf(false)
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
private var drawerPage by mutableIntStateOf(0)
private var drawerControllerActive by mutableStateOf(false)
private var backActionsInverted by mutableStateOf(false)
@@ -228,12 +234,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
root.pointerIcon = noCursor
surfaceView.pointerIcon = noCursor
loading = LoadingState(this)
loading = LoadingState(this, steam = loadingMode() == SessionService.MODE_STEAM)
if (!SessionState.running) {
val needRuntime = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(this) == null
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
!com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this)
if (needRuntime || needDesktop) installThenStart(needRuntime, needDesktop)
val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM &&
com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
if (needRuntime || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton)
}
hud = PerfHud(this)
hud.onPresentingWindowChanged = {
@@ -246,121 +254,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
readPrefs()
// One Compose layer for every menu and overlay. Touches nothing in it consumes fall
// through to the pad and the game underneath.
sessionOverlay = ComposeView(this).apply {
isFocusable = true
isFocusableInTouchMode = true
setContent {
DroidDeckTheme {
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
if (hud.text.isNotEmpty()) HudText(hud.text)
if (loading.visible) LoadingOverlay(loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended)
// Opening the drawer takes the controller away from the game: release its pad.
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
if (drawerOpen) {
padBridge?.releaseAll()
androidx.compose.runtime.withFrameNanos { }
val requested = sessionOverlay.requestFocus()
Log.i(TAG, "drawer root focus requested=$requested focused=${sessionOverlay.hasFocus()}")
} else {
releaseDrawerDirection()
}
}
// The PC keyboard takes it too, for moving over the keys; the drawer opens over it.
androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) padBridge?.releaseAll() }
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
sendKey = { code, down -> if (CompositorHost.isStarted) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) },
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
onClose = { pcKeyboardOpen = false },
)
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM,
title = if (SessionState.mode == SessionService.MODE_RUN)
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "Game" else null,
isHomeApp = isHomeApp,
androidApps = androidApps,
hudOn = hudOn,
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier,
lsfgReady = LsfgNative.isInstalled(this@SessionActivity),
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
shapeMode = shapeMode, fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
onFrameGenPick = { engine, multiplier ->
FrameGen.set(this@SessionActivity, engine, multiplier)
readPrefs()
applyFrameGen()
},
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() },
onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
// The desktop with Steam's desktop client in it, in this session's place: the
// session ends with status 0 and onSessionEnded starts the relaunch (Stop's
// finish() would skip it).
onSwitchToDesktop = if (SessionState.mode == SessionService.MODE_STEAM) ({
drawerOpen = false
SessionState.relaunch = Intent(this@SessionActivity, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop")
SessionService.stop(this@SessionActivity)
}) else null,
backActionsInverted = backActionsInverted,
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
backActionsInverted = inverted
},
onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
onSuspendPolicy = { policy ->
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
suspendPolicy = policy
SessionService.suspendPolicyChanged(this@SessionActivity)
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = ::selectSecondScreenMode,
onSecondScreenDisplay = ::selectSecondScreenDisplay,
onLaunchAndroidApp = { app, displayId ->
drawerOpen = false
try {
HomeApp.launch(this@SessionActivity, app, displayId)
} catch (_: Exception) {
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show()
}
},
onBackground = { drawerOpen = false; moveTaskToBack(true) },
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
onClose = { drawerOpen = false },
))
if (SessionState.suspended) SessionPausedOverlay {
SessionService.resume(this@SessionActivity)
}
}
}
intent.getIntExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, 0).takeIf { it != 0 && loading.visible }?.let {
floodColor = it
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(it))
}
sessionOverlay = createSessionOverlay()
root.addView(sessionOverlay)
setContentView(root)
handleHomeGuideIntent(intent)
updateOnScreenControls()
WaylandCompositor.setFirstFrameListener {
SessionEvents.firstFrame()
runOnUiThread {
loading.visible = false
hud.start()
}
}
WaylandCompositor.setFirstFrameListener(firstFrameListener)
SessionEvents.markReadyIfPossible()
SessionState.endListener = endListener
// A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord.
@@ -369,6 +273,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun handleOnBackPressed() {
// The PC keyboard closes first (B on a controller), then Back is the drawer again.
when {
::loading.isInitialized && loading.ended -> finish()
drawerOpen -> drawerOpen = false
pcKeyboardOpen -> pcKeyboardOpen = false
else -> routeBackAction()
@@ -378,6 +283,130 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
watchSession()
}
/**
* One Compose layer for every menu and overlay. Touches nothing in it consumes fall through to
* the pad and the game underneath.
*/
private fun createSessionOverlay(): ComposeView = ComposeView(this).apply {
isFocusable = true
isFocusableInTouchMode = true
setContent {
DroidDeckTheme {
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
if (hud.text.isNotEmpty()) HudText(hud.text)
if (loading.visible) LoadingOverlay(
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
title = loadingTitle(), steam = loadingMode() == SessionService.MODE_STEAM,
// As the drawer's Stop does: the service stops, and a start still installing is cancelled.
onCancel = { SessionService.stop(this@SessionActivity); finish() },
endedDetail = loading.endedDetail,
onRetry = { retrySession() },
onShareLogs = { shareCurrentSessionLogs() },
onClose = { finish() },
flood = floodColor?.let { androidx.compose.ui.graphics.Color(it) },
onFlooded = {
floodColor = null
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
},
)
// Opening the drawer takes the controller away from the game: release its pad.
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
if (drawerOpen) {
padBridge?.releaseAll()
androidx.compose.runtime.withFrameNanos { }
val requested = sessionOverlay.requestFocus()
Log.i(TAG, "drawer root focus requested=$requested focused=${sessionOverlay.hasFocus()}")
} else {
releaseDrawerDirection()
}
}
// The PC keyboard takes it too, for moving over the keys; the drawer opens over it.
androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) padBridge?.releaseAll() }
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
sendKey = { code, down -> if (CompositorHost.isStarted) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) },
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
onClose = { pcKeyboardOpen = false },
)
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM,
title = if (SessionState.mode == SessionService.MODE_RUN)
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "Game" else null,
isHomeApp = isHomeApp,
androidApps = androidApps,
hudOn = hudOn,
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier,
lsfgReady = LsfgNative.isInstalled(this@SessionActivity),
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
shapeMode = shapeMode, fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
onFrameGenPick = { engine, multiplier ->
FrameGen.set(this@SessionActivity, engine, multiplier)
readPrefs()
applyFrameGen()
},
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() },
onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
// The desktop with Steam's desktop client in it, in this session's place: the
// session ends with status 0 and onSessionEnded starts the relaunch (Stop's
// finish() would skip it).
onSwitchToDesktop = if (SessionState.mode == SessionService.MODE_STEAM) ({
drawerOpen = false
SessionState.relaunch = Intent(this@SessionActivity, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop")
SessionService.stop(this@SessionActivity)
}) else null,
backActionsInverted = backActionsInverted,
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
backActionsInverted = inverted
},
onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
onSuspendPolicy = { policy ->
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
suspendPolicy = policy
SessionService.suspendPolicyChanged(this@SessionActivity)
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = ::selectSecondScreenMode,
onSecondScreenDisplay = ::selectSecondScreenDisplay,
onLaunchAndroidApp = { app, displayId ->
drawerOpen = false
try {
HomeApp.launch(this@SessionActivity, app, displayId)
} catch (_: Exception) {
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show()
}
},
onBackground = { drawerOpen = false; moveTaskToBack(true) },
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
onClose = { drawerOpen = false },
components = drawerComponents,
onComponentsRefresh = { refreshDrawerComponents() },
onComponentSwap = { pid, comp, value -> swapDrawerComponent(pid, comp, value) },
))
if (SessionState.suspended) SessionPausedOverlay(
title = pausedTitle(),
onResume = { SessionService.resume(this@SessionActivity) },
)
}
}
}
private fun refreshHomeApp() {
isHomeApp = HomeApp.isDefault(this)
androidApps = if (isHomeApp) HomeApp.launchableApps(this) else emptyList()
@@ -424,6 +453,62 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
}
/** Re-reads the Protons for the drawer's Components tab, first running swaps a closed game was holding back. */
private fun refreshDrawerComponents() {
Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
val snap = runCatching { ComponentsManager.snapshot(this) }.getOrNull()
uiHandler.post {
drawerComponents = snap
if (applied.isNotEmpty()) android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
}
}, "drawer-components").start()
}
private fun swapDrawerComponent(protonId: String, comp: String, value: String) {
Thread({
val message = runCatching {
val snap = ComponentsManager.snapshot(this)
val queued = snap.protons.firstOrNull { it.proton.id == protonId }?.components?.get(comp)?.queued
val active = snap.protons.firstOrNull { it.proton.id == protonId }?.components?.get(comp)?.activeFile
val build = snap.protons.firstOrNull { it.proton.id == protonId }?.proton?.version?.let(ComponentsManager::safeName)
val current = active ?: "orig:$build"
if (queued != null && value == current) {
// Picking what is already in place again cancels the swap waiting for the game.
ComponentsManager.cancelQueued(this, protonId, comp); "The waiting swap was cancelled."
} else if (value.startsWith("orig:")) ComponentsManager.restore(this, protonId, comp, value.removePrefix("orig:"))
else ComponentsManager.swap(this, protonId, value)
}.getOrElse { e -> "Swap failed: ${e.message ?: e.javaClass.simpleName}" }
uiHandler.post {
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
refreshDrawerComponents()
}
}, "drawer-components-swap").start()
}
/** The session this screen is bringing up: the live one when re-attached, else the intent's. */
private fun loadingMode(): String =
if (SessionState.running) SessionState.mode
else intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
private fun pausedTitle(): String = when (SessionState.mode) {
SessionService.MODE_DESKTOP -> "The desktop is paused"
SessionService.MODE_RUN -> (com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "The program") + " is paused"
else -> "Steam is paused"
}
private fun loadingTitle(): String = when (loadingMode()) {
SessionService.MODE_DESKTOP ->
if (!SessionState.running && intent.getStringExtra(SessionService.EXTRA_STEAM_UI) != null) "Starting Steam on the desktop"
else "Starting the desktop"
SessionService.MODE_RUN -> {
val program = if (SessionState.running) SessionState.program else intent.getStringExtra(SessionService.EXTRA_PROGRAM)
"Starting " + (com.droiddeck.launcher.frontend.Library.nameForProgram(program) ?: "the program")
}
else -> "Starting Steam"
}
private fun shareCurrentSessionLogs() {
val folder = SessionPaths.current()
if (folder == null || !folder.isDirectory) {
@@ -471,17 +556,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
* First Play (or Desktop) on a fresh install: the runtime, and for the desktop its package,
* are downloaded and unpacked here, on the loading screen's own line and bar, and the session
* starts when they are in. Nothing else changes.
*
* The first Steam session also gets Valve's ARM64 Proton here, before the client has ever
* started, so the compatibility tool is installed and the default at sign-in with no install
* dialog, download or client restart. Not being able to fetch it stops nothing: the session
* then asks the client for it after sign-in, as it always has.
*/
private fun installThenStart(runtime: Boolean, desktop: Boolean) {
private fun installThenStart(runtime: Boolean, desktop: Boolean, proton: Boolean = false) {
if (SessionState.stopRequested) return
installingRuntime = true
SessionState.installing = if (runtime) "runtime" else "desktop"
SessionState.installing = if (runtime) "runtime" else if (desktop) "desktop" else "proton"
SessionEvents.transition(
SessionPhase.INSTALLING_RUNTIME,
if (runtime) "runtime.installing" else "desktop.installing",
"${SessionState.installing}.installing",
mapOf("component" to SessionState.installing),
)
loading.step = if (runtime) "downloading the Linux runtime" else "downloading the desktop"
loading.step = if (runtime) "downloading the Linux runtime" else if (desktop) "downloading the desktop"
else "downloading Proton Experimental (ARM64)"
loading.percent = -1
Thread({
var failedComponent: String? = null
@@ -496,6 +587,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
problem = installDesktop()
if (problem == null) SessionEvents.record("desktop.ready") else failedComponent = "desktop"
}
if (problem == null && proton && !SessionState.stopRequested) {
SessionState.installing = "proton"
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "proton.installing", mapOf("component" to "proton"))
val protonProblem = installProton()
if (protonProblem == null) SessionEvents.record("proton.ready")
else SessionEvents.record("proton.skipped", mapOf("reason" to protonProblem))
}
uiHandler.post {
installingRuntime = false
SessionState.installing = null
@@ -511,6 +609,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionEvents.fail(code, problem)
collectStartArtifacts("session start failed")
loading.showEnded(problem)
focusEndedScreen()
return@post
}
loading.percent = -1
@@ -561,6 +660,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return problem?.let { "The desktop did not install ($it). Check the connection and press Desktop again." }
}
/** Null when the ARM64 Proton is in, else why not; the session goes on either way. */
private fun installProton(): String? {
uiHandler.post { loading.percent = -1; loading.step = "downloading Proton Experimental (ARM64)" }
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
val entry = catalog.fetch(catalog.STEAM_SEED_URL)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
?: return "catalog unreachable"
return catalog.install(this, entry, progressFor("Proton Experimental (ARM64)", entry.size / 1_000_000))
}
override fun surfaceCreated(holder: SurfaceHolder) {
if (installingRuntime || SessionState.stopRequested) return
if (!SessionState.running) {
@@ -791,19 +899,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun showEnded(status: Int, hint: String?) {
run {
if (status != 0) {
loading.showEnded(
"The session ended ($status)\n${SessionState.logFile?.path ?: "-"}" +
(if (hint != null) "\n\n$hint" else "")
)
// A moment on screen, so a failure is readable rather than a flash of black;
// longer when there is advice to read.
Handler(Looper.getMainLooper()).postDelayed({ finish() }, if (hint != null) 9000 else 4000)
} else {
finish()
}
if (status == 0) {
finish()
return
}
// It stays until the user leaves: a failure read against a timer is a failure not read.
loading.showEnded(
hint ?: "Steam stopped unexpectedly. Share the logs with a bug report, or try again.",
"Exit status $status · ${SessionState.logFile?.path ?: "no log"}",
)
focusEndedScreen()
}
/** The ended screen's buttons take the pad: it is no longer driving a game. */
private fun focusEndedScreen() {
drawerOpen = false
padBridge?.releaseAll()
uiHandler.post { sessionOverlay.requestFocus() }
}
/** The same start again, in a fresh activity: the ended one keeps no session to reuse. */
private fun retrySession() {
val again = Intent(intent)
finish()
startActivity(again)
}
/**
@@ -851,10 +970,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (drawerOpen && !drawerControllerActive) sessionOverlay.requestFocus()
drawerControllerActive = true
}
// While the session starts, B is the loading screen's Cancel, as its corner says.
if (fromController && event.keyCode == KeyEvent.KEYCODE_BUTTON_B && ::loading.isInitialized && loading.visible && !loading.ended && !drawerOpen) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
SessionService.stop(this)
finish()
}
return true
}
// The ended screen is a page of buttons: the pad drives them, and B leaves.
if (::loading.isInitialized && loading.ended) {
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) finish()
return true
}
return super.dispatchKeyEvent(event)
}
if (drawerOpen) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
drawerPage = (drawerPage + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else 2) % 3
drawerPage = (drawerPage + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else DRAWER_PAGES - 1) % DRAWER_PAGES
releaseDrawerDirection()
}
return true
@@ -1338,6 +1473,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onResume() {
super.onResume()
com.droiddeck.launcher.ui.Motion.refresh(this)
refreshHomeApp()
if (intent?.action == SessionService.ACTION_RESUME) {
intent.action = null
@@ -1352,6 +1488,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onPause() {
// Do not carry transient session UI across an app/display transition. In particular, the
// drawer's dim layer can otherwise remain over Steam when this activity returns.
drawerOpen = false
pcKeyboardOpen = false
(getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener)
releaseDrawerDirection()
// A button held when the app goes away would stay held in the ring for the whole session.
@@ -1391,6 +1531,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
/** Ours, so a finishing activity never unhooks the one that replaced it. */
private val endListener: (Int) -> Unit = { status -> onSessionEnded(status) }
private val firstFrameListener = Runnable {
SessionEvents.firstFrame()
runOnUiThread {
loading.visible = false
hud.start()
}
}
override fun onDestroy() {
// Deliberately does NOT end the session: this activity can be destroyed while the user is
@@ -1403,7 +1550,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (::hud.isInitialized) hud.stop()
padBridge?.stop()
if (SessionState.endListener === endListener) SessionState.endListener = null
WaylandCompositor.setFirstFrameListener(null)
WaylandCompositor.clearFirstFrameListener(firstFrameListener)
super.onDestroy()
}
@@ -0,0 +1,25 @@
package com.droiddeck.launcher.core;
import java.io.File;
import java.io.IOException;
/**
* Where an archive entry may land. An entry name ("../x", "/etc/x") or a symlink already written
* by an earlier entry can point outside the directory being filled; the canonical path follows
* both, so anything that does not resolve inside it is refused.
*/
public final class ArchivePaths {
private ArchivePaths() {}
/**
* The file for {@code name} under {@code destination}, or null when it would resolve outside
* it. The destination itself counts as inside (a "./" entry).
*/
public static File inside(File destination, String name) throws IOException {
String base = destination.getCanonicalPath();
File file = new File(destination, name);
String path = file.getCanonicalPath();
if (path.equals(base) || path.startsWith(base + File.separator)) return file;
return null;
}
}
@@ -5,7 +5,6 @@ import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.provider.Settings
import android.util.Log
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
@@ -162,21 +161,7 @@ object DeviceReport {
})
h("Android process limits")
// Android 12 kills "phantom" processes - the children an app forks itself rather than
// starting through the framework - once there are more than a handful of them. A session is
// nothing but those: proot, gamescope, Xwayland, the client, its helpers, Wine, FEX. Where
// this is left on, the OS kills the session and nothing in our logs says why, because
// nothing in the session did it. Some ROMs expose it in Developer options as a
// "restrict child processes" switch; otherwise it is
// adb shell settings put global settings_enable_monitor_phantom_procs false
val phantom = runCatching {
Settings.Global.getString(context.contentResolver, "settings_enable_monitor_phantom_procs")
}.getOrNull()
k("Phantom proc monitor", when (phantom?.lowercase()) {
"false", "0" -> "disabled (good - the OS will not kill the session's children)"
null, "" -> "not set (ROM default, usually ENABLED - see the note below)"
else -> "ENABLED (the OS may kill the session with no log; turn off \"restrict child processes\")"
})
k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context.contentResolver)))
h("Device switch files in Download")
for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver",
@@ -0,0 +1,36 @@
package com.droiddeck.launcher.core
import java.io.File
import java.security.MessageDigest
/** File checksums as lowercase hex, and GitHub's release-asset digests, in one place. */
object Hashes {
private val GITHUB_SHA256 = Regex("(?i)sha256:[0-9a-f]{64}")
@JvmStatic
fun sha256(file: File): String = hex(file, "SHA-256")
@JvmStatic
fun sha512(file: File): String = hex(file, "SHA-512")
/** True when [digest] is GitHub's asset digest form, "sha256:" and 64 hex digits. */
@JvmStatic
fun isGithubSha256(digest: String?): Boolean = digest != null && digest.matches(GITHUB_SHA256)
/** The hex of a GitHub asset digest ("sha256:<hex>"), or null when [digest] is not one. */
@JvmStatic
fun githubSha256(digest: String?): String? = digest?.takeIf { isGithubSha256(it) }?.substringAfter(':')
private fun hex(file: File, algorithm: String): String {
val digest = MessageDigest.getInstance(algorithm)
file.inputStream().buffered(1 shl 16).use { input ->
val buffer = ByteArray(1 shl 20)
while (true) {
val n = input.read(buffer)
if (n < 0) break
digest.update(buffer, 0, n)
}
}
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
}
}
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.core
import android.content.ContentResolver
import android.os.Build
import android.provider.Settings
/** Android's phantom process monitor can kill the many child processes used by a Steam session. */
enum class PhantomProcessStatus {
NOT_APPLICABLE,
DISABLED,
ENABLED,
UNSET,
UNREADABLE,
}
object PhantomProcessLimit {
const val ADB_COMMAND = "adb shell settings put global settings_enable_monitor_phantom_procs false"
const val SHELL_COMMAND = "settings put global settings_enable_monitor_phantom_procs false"
private const val SETTING = "settings_enable_monitor_phantom_procs"
fun adbCommand(enabled: Boolean): String =
"adb shell settings put global $SETTING ${if (enabled) "true" else "false"}"
fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
val global = try {
Settings.Global.getString(resolver, SETTING)
} catch (_: Exception) {
return PhantomProcessStatus.UNREADABLE
}
return status(global, systemProperty(OVERRIDE_PROPERTY))
}
/**
* The value Android itself acts on, in FeatureFlagUtils.isEnabled's order: the global setting
* when it is set, otherwise the feature-flag override property. Developer options' "Disable
* child process restrictions" writes only the property, so a device switched off there has no
* global setting at all and must not be reported as unset.
*/
fun status(global: String?, override: String?): PhantomProcessStatus {
val value = global?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
?: override?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
return when (value) {
"false", "0" -> PhantomProcessStatus.DISABLED
null -> PhantomProcessStatus.UNSET
else -> PhantomProcessStatus.ENABLED
}
}
private const val OVERRIDE_PROPERTY = "persist.sys.fflag.override.$SETTING"
private fun systemProperty(name: String): String? = try {
Class.forName("android.os.SystemProperties")
.getMethod("get", String::class.java)
.invoke(null, name) as? String
} catch (_: Exception) {
null
}
fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
fun title(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
PhantomProcessStatus.UNREADABLE -> "Child-process limit could not be checked"
PhantomProcessStatus.DISABLED -> "Child-process limit is off"
PhantomProcessStatus.NOT_APPLICABLE -> "Child-process limit not required"
}
fun instructions(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.UNSET -> "This setting is unset, so the ROM default applies and may enforce the limit. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not read the setting. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.DISABLED -> "Steam sessions can start."
PhantomProcessStatus.NOT_APPLICABLE -> "This Android version does not use this limit."
}
fun gateInstructions(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options."
PhantomProcessStatus.UNSET -> "The ROM default may enforce this limit. Explicitly turn off “Restrict child processes” in Developer options."
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not check this setting. Turn off “Restrict child processes” in Developer options."
else -> instructions(status)
}
fun reportValue(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)"
PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)"
PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12"
}
}
@@ -37,11 +37,10 @@ public final class TarZst {
destination.mkdirs();
try (InputStream in = new ZstdCompressorInputStream(new BufferedInputStream(source, 1 << 16));
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
String base = destination.getCanonicalPath() + File.separator;
TarArchiveEntry entry;
while ((entry = tar.getNextTarEntry()) != null) {
File file = new File(destination, entry.getName());
if (!file.getCanonicalPath().startsWith(base)) continue;
File file = ArchivePaths.inside(destination, entry.getName());
if (file == null) continue;
if (entry.isDirectory()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
@@ -0,0 +1,185 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import com.flyfishxu.kadb.Kadb
import com.flyfishxu.kadb.cert.KadbCert
import java.io.File
import java.net.InetAddress
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.ArrayDeque
/** A narrowly scoped Wireless debugging client for the child-process setting repair. */
object WirelessAdbFix {
private const val CERT_FILE = "wireless-adb-cert.pem"
private const val KEY_FILE = "wireless-adb-key.pem"
private const val HOST_FILE = "wireless-adb-host.txt"
private const val CONNECTION_FILE = "wireless-adb-connection.txt"
private data class SavedConnection(val host: String, val port: Int?)
@Synchronized
private fun loadOrCreateIdentity(context: Context) {
val directory = context.noBackupFilesDir
val cert = File(directory, CERT_FILE)
val key = File(directory, KEY_FILE)
if (cert.isFile && key.isFile) {
KadbCert.set(cert.readBytes(), key.readBytes())
return
}
val identity = KadbCert.get(notAfter = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650))
KadbCert.set(identity.first, identity.second)
writeAtomically(cert, identity.first)
writeAtomically(key, identity.second)
}
private fun writeAtomically(destination: File, contents: ByteArray) {
val temporary = File(destination.parentFile, "${destination.name}.tmp")
temporary.writeBytes(contents)
check(temporary.renameTo(destination)) { "Could not save Wireless debugging identity" }
}
suspend fun pair(context: Context, host: String, port: Int, pairingCode: String) {
loadOrCreateIdentity(context.applicationContext)
Kadb.pair(host, port, pairingCode, "DroidDeck")
writeAtomically(File(context.noBackupFilesDir, HOST_FILE), host.toByteArray())
writeAtomically(File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
}
private fun savedConnection(context: Context): SavedConnection? {
val directory = context.applicationContext.noBackupFilesDir
if (!File(directory, CERT_FILE).isFile || !File(directory, KEY_FILE).isFile) return null
val host = File(directory, HOST_FILE).takeIf(File::isFile)?.readText()?.trim()
?.takeIf(String::isNotEmpty) ?: return null
val lines = File(directory, CONNECTION_FILE).takeIf(File::isFile)?.readLines()
val port = lines?.takeIf { it.size == 2 && it[0] == host }
?.get(1)?.toIntOrNull()?.takeIf { it in 1..65535 }
return SavedConnection(host, port)
}
/** A saved pairing skips the PIN; an unknown connection port can be filled in from Settings. */
fun savedConnectionAddress(context: Context): String? = savedConnection(context)?.let { saved ->
val host = if (':' in saved.host) "[${saved.host}]" else saved.host
"$host:${saved.port ?: ""}"
}
private fun saveConnection(context: Context, host: String, port: Int) {
writeAtomically(
File(context.applicationContext.noBackupFilesDir, CONNECTION_FILE),
"$host\n$port".toByteArray(),
)
}
/** Finds this paired device's separate TLS connection port from Android's ADB mDNS record. */
fun findConnectPort(context: Context, pairedHost: String, timeoutSeconds: Long = 12): Int? {
val manager = context.applicationContext.getSystemService(Context.NSD_SERVICE) as NsdManager
val expectedAddress = runCatching { InetAddress.getByName(pairedHost).address }.getOrNull() ?: return null
val resolvedPort = AtomicInteger(-1)
val finished = AtomicBoolean(false)
val latch = CountDownLatch(1)
val queue = ArrayDeque<NsdServiceInfo>()
val seen = mutableSetOf<String>()
var resolving = false
val lock = Any()
lateinit var resolveNext: () -> Unit
resolveNext = {
val next = synchronized(lock) {
if (finished.get() || resolving || queue.isEmpty()) null
else queue.removeFirst().also { resolving = true }
}
if (next != null) {
val listener = object : NsdManager.ResolveListener {
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
synchronized(lock) { resolving = false }
resolveNext()
}
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
val address = serviceInfo.host?.address
if (address != null && address.contentEquals(expectedAddress) && finished.compareAndSet(false, true)) {
resolvedPort.set(serviceInfo.port)
latch.countDown()
} else {
synchronized(lock) { resolving = false }
resolveNext()
}
}
}
runCatching { manager.resolveService(next, listener) }.onFailure {
synchronized(lock) { resolving = false }
resolveNext()
}
}
}
val discoveryListener = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String) = Unit
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
if (serviceInfo.serviceType?.contains("_adb-tls-connect._tcp") == true) {
synchronized(lock) {
if (seen.add(serviceInfo.serviceName)) queue.addLast(serviceInfo)
}
resolveNext()
}
}
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
override fun onDiscoveryStopped(serviceType: String) { latch.countDown() }
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
}
try {
manager.discoverServices("_adb-tls-connect._tcp.", NsdManager.PROTOCOL_DNS_SD, discoveryListener)
latch.await(timeoutSeconds, TimeUnit.SECONDS)
} catch (_: Exception) {
return null
} finally {
runCatching { manager.stopServiceDiscovery(discoveryListener) }
}
return resolvedPort.get().takeIf { it in 1..65535 }
}
fun setChildProcessLimit(context: Context, host: String, port: Int, enabled: Boolean) {
loadOrCreateIdentity(context.applicationContext)
Kadb.create(host, port).use { adb ->
val value = if (enabled) "true" else "false"
val change = adb.shell("settings put global settings_enable_monitor_phantom_procs $value")
check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } }
val result = adb.shell("settings get global settings_enable_monitor_phantom_procs")
check(result.exitCode == 0 && result.output.trim() == value) {
"Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}"
}
}
saveConnection(context, host, port)
}
/** Tries the app's saved pairing without asking for a new pairing code. */
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
val appContext = context.applicationContext
val saved = savedConnection(appContext)
?: error("No Wireless debugging pairing is saved")
val cachedPort = saved.port
if (cachedPort != null) {
val cachedResult = runCatching {
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
}
if (cachedResult.isSuccess) return
val discoveredPort = findConnectPort(appContext, saved.host)
if (discoveredPort != null && discoveredPort != cachedPort) {
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
} else {
cachedResult.getOrThrow()
}
} else {
val discoveredPort = findConnectPort(appContext, saved.host)
?: error("Enter the current Wireless debugging IP address & Port")
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
}
}
}
@@ -249,7 +249,7 @@ fun CollapsibleRail(
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) {
Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp))
Spacer(Modifier.width(6.dp))
Text(link.label, fontSize = 11.sp)
Text(link.label, fontSize = 12.sp)
}
}
}
@@ -269,7 +269,7 @@ fun CollapsibleRail(
Text(
section.header,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
fontSize = 9.sp,
fontSize = 11.sp,
fontWeight = FontWeight.Bold,
letterSpacing = 0.6.sp,
modifier = Modifier.padding(start = 14.dp, top = 10.dp, bottom = 2.dp),
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.files
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import java.io.File
// Reading and setting a file's read-only and hidden attributes (the DOS attribute xattr).
// ── DOS file attributes (Read-only / Hidden) ──
// The in-container file manager (wfm.exe) exposes these in its Properties dialog; this mirrors the
// same two toggles for files browsed from the app side. No root - we only touch permission bits the
// app owns (container files) and the Wine DOS-attribute xattr.
// FILE_ATTRIBUTE_HIDDEN, as Wine encodes it in the user.DOSATTRIB extended attribute.
private const val FILE_ATTRIBUTE_HIDDEN = 0x2
private const val DOSATTRIB_XATTR = "user.DOSATTRIB"
// Snapshot of a file's two toggleable attributes. hiddenSupported is false when the underlying
// filesystem can't store the DOSATTRIB xattr (the FUSE /storage volumes) - the Hidden toggle is then
// disabled while Read-only keeps working.
internal data class FileAttrState(
val readOnly: Boolean,
val hidden: Boolean,
val hiddenSupported: Boolean,
)
// Wine (and Samba) store user.DOSATTRIB as an ASCII hex string ("0x22"), sometimes with trailing
// Samba fields after a separator. We only need the leading DOS-attribute hex, so read from the "0x"
// prefix and stop at the first non-hex character.
private fun parseDosAttrib(raw: ByteArray): Int {
val s = String(raw, Charsets.US_ASCII).trim()
val hex = if (s.startsWith("0x") || s.startsWith("0X")) s.substring(2) else s
val digits = hex.takeWhile { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }
return digits.toIntOrNull(16) ?: 0
}
// Read the current read-only + Wine-hidden state. Never throws: an xattr-unsupported filesystem
// comes back hiddenSupported=false (Hidden toggle disabled), Read-only always resolves.
internal fun readFileAttrs(file: File): FileAttrState {
val path = file.absolutePath
// Read-only reflects the OWNER write bit - that's what Wine maps to FILE_ATTRIBUTE_READONLY.
val readOnly = runCatching {
(android.system.Os.stat(path).st_mode and android.system.OsConstants.S_IWUSR) == 0
}.getOrDefault(!file.canWrite())
var hidden = false
var supported = true
try {
hidden = (parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR)) and FILE_ATTRIBUTE_HIDDEN) != 0
} catch (e: android.system.ErrnoException) {
// ENODATA: xattr namespace works, the attribute just isn't set yet -> still toggleable.
// ENOTSUP/EOPNOTSUPP/anything else: the fs can't store it -> disable the Hidden toggle.
supported = e.errno == android.system.OsConstants.ENODATA
} catch (e: Exception) {
supported = false
}
return FileAttrState(readOnly, hidden, supported)
}
// Toggle read-only by flipping the write bits, preserving every other permission bit. Setting
// read-only clears owner/group/other write (so Wine sees FILE_ATTRIBUTE_READONLY regardless of which
// write bit it checks); clearing it restores owner write. Falls back to File.setWritable if chmod is
// somehow refused. Returns true on success.
internal fun setReadOnly(file: File, readOnly: Boolean): Boolean = runCatching {
val path = file.absolutePath
val mode = android.system.Os.stat(path).st_mode
val writeBits = android.system.OsConstants.S_IWUSR or
android.system.OsConstants.S_IWGRP or android.system.OsConstants.S_IWOTH
val newMode = if (readOnly) mode and writeBits.inv()
else mode or android.system.OsConstants.S_IWUSR
android.system.Os.chmod(path, newMode)
true
}.getOrElse { file.setWritable(!readOnly, true) }
// Flip Wine's DOS hidden bit in user.DOSATTRIB, preserving the other DOS-attribute bits
// (archive/system/read-only) already encoded there, and synthesizing a minimal value when absent.
// Writes Wine's own "0x%x" format, which Wine reads back natively. Returns false when the fs can't
// store the xattr, so the caller can disable just the Hidden toggle.
internal fun setHidden(file: File, hidden: Boolean): Boolean = try {
val path = file.absolutePath
var attr = try {
parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR))
} catch (e: android.system.ErrnoException) {
if (e.errno == android.system.OsConstants.ENODATA) 0 else throw e
}
attr = if (hidden) attr or FILE_ATTRIBUTE_HIDDEN else attr and FILE_ATTRIBUTE_HIDDEN.inv()
val value = "0x%x".format(attr).toByteArray(Charsets.US_ASCII)
android.system.Os.setxattr(path, DOSATTRIB_XATTR, value, 0)
true
} catch (e: Exception) {
false
}
@@ -11,6 +11,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.droiddeck.launcher.ui.DroidDeckTheme
import java.io.File
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
class FileManagerActivity : ComponentActivity() {
@@ -19,10 +20,11 @@ class FileManagerActivity : ComponentActivity() {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
}
val initialDir = intent.getStringExtra(EXTRA_START_DIR)?.let(::File)
setContent {
DroidDeckTheme {
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
FileManagerScreen()
FileManagerScreen(initialDir = initialDir)
}
}
}
@@ -32,4 +34,8 @@ class FileManagerActivity : ComponentActivity() {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 1 && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) recreate()
}
companion object {
const val EXTRA_START_DIR = "com.droiddeck.launcher.files.START_DIR"
}
}
@@ -0,0 +1,599 @@
package com.droiddeck.launcher.files
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
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.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.FileCopy
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.InsertDriveFile
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.ContentCut
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material.icons.filled.PushPin
import androidx.compose.material.icons.filled.Storage
import androidx.compose.material.icons.filled.Image
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import coil.compose.AsyncImage
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
// The File Manager's rows, tiles, favourites and context menu.
// Semantic identity colours for the favourite-card drive badge. Intentionally NOT theme
// accent colours - they identify the storage source at a glance. Returns (background, foreground).
private fun badgeColors(loc: FavLocation): Pair<Color, Color> {
val white = Color(0xFFFFFFFF)
return when {
loc.storage == FavStorage.INTERNAL -> Color(0xFF2E5FB0) to white // blue
loc.storage == FavStorage.SD -> Color(0xFF2E7D32) to white // green
else -> Color(0xFF555555) to white // grey
}
}
// The context-menu item list shared by the list rows (FileItemRow) and the grid tiles
// (FileGridTile), so both open the identical menu. Gating (isDir/canRun/isInno/looksLikeArchive) is
// recomputed from [file] here - one source of truth for what each item shows. Every item dismisses
// the menu first, then runs its action.
@Composable
private fun FileContextMenuItems(
file: File,
isFavorite: Boolean,
onSelect: () -> Unit,
onRename: () -> Unit,
onCopy: () -> Unit,
onCut: () -> Unit,
onDelete: () -> Unit,
onToggleFavorite: () -> Unit,
onProperties: () -> Unit,
onDismissMenu: () -> Unit,
) {
val isDir = file.isDirectory
DropdownMenuItem(
text = { Text("Select") },
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onSelect() },
)
MenuItemDivider()
// Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config
// files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu.
DropdownMenuItem(
text = { Text("Properties") },
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onProperties() },
)
MenuItemDivider()
// Favorites are directories - only folders get the pin toggle.
if (isDir) {
DropdownMenuItem(
text = { Text(if (isFavorite) "Remove from Favorites" else "Add to Favorites") },
leadingIcon = {
Icon(
if (isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder,
null,
tint = MaterialTheme.colorScheme.primary,
)
},
onClick = { onToggleFavorite() },
)
MenuItemDivider()
}
DropdownMenuItem(
text = { Text("Rename") },
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onRename() },
)
MenuItemDivider()
DropdownMenuItem(
text = { Text("Copy") },
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onCopy() },
)
MenuItemDivider()
DropdownMenuItem(
text = { Text("Cut") },
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onCut() },
)
MenuItemDivider()
DropdownMenuItem(
text = { Text("Delete") },
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onDelete() },
)
}
@Composable
@OptIn(ExperimentalFoundationApi::class)
internal fun FileItemRow(
file: File,
showActions: Boolean = true,
compact: Boolean = false,
selectionMode: Boolean = false,
selected: Boolean = false,
onLongPress: () -> Unit = {},
onToggleSelect: () -> Unit = {},
onTap: () -> Unit,
onMenu: () -> Unit,
menuExpanded: Boolean,
onDismissMenu: () -> Unit,
onSelect: () -> Unit = {},
onCopy: () -> Unit,
onCut: () -> Unit,
onDelete: () -> Unit,
onRename: () -> Unit,
isFavorite: Boolean = false,
onToggleFavorite: () -> Unit = {},
onProperties: () -> Unit = {},
) {
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
val isDir = file.isDirectory
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
// wallpaper/icon). Coil sizes the decode to the 36dp slot and caches it, so scrolling stays smooth.
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
// For real PE executables, try to pull out the embedded application icon (async, off the main thread).
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
if (!isDir && file.name.lowercase().endsWith(".exe")) {
LaunchedEffect(file.absolutePath) {
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
if (bmp != null) exeIcon = bmp.asImageBitmap()
}
}
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.combinedClickable(
// In selection mode a tap toggles instead of opening, so you can rattle through a
// folder without long-pressing every single row.
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(
containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)
else MaterialTheme.colorScheme.surfaceContainer,
),
border = BorderStroke(
1.dp,
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
) {
if (selectionMode) {
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() })
Spacer(Modifier.width(4.dp))
}
when {
// Show the executable's own embedded icon when we managed to extract one.
exeIcon != null -> Image(
bitmap = exeIcon!!,
contentDescription = null,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
isExe -> Icon(
painter = painterResource(R.drawable.icon_menu_container),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
isDir -> Icon(
imageVector = Icons.Filled.Folder,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
// Real image preview. Falls back to the generic file icon while loading or on decode failure.
isImage -> AsyncImage(
model = file,
contentDescription = null,
contentScale = ContentScale.Crop,
placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile),
error = rememberVectorPainter(Icons.Filled.InsertDriveFile),
modifier = Modifier
.size(36.dp)
.clip(RoundedCornerShape(6.dp)),
)
else -> Icon(
imageVector = Icons.Filled.InsertDriveFile,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
}
Spacer(Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = buildString {
if (!isDir) append(FileOps.formatBytes(file.length())).append(" \u2022 ")
append(dateFormat.format(Date(file.lastModified())))
},
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
)
}
if (showActions) Box {
IconButton(onClick = onMenu) {
Icon(Icons.Filled.MoreVert, "Actions", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = onDismissMenu,
modifier = Modifier.outlinedMenuCard(),
) {
FileContextMenuItems(
file = file,
isFavorite = isFavorite,
onSelect = onSelect,
onRename = onRename,
onCopy = onCopy,
onCut = onCut,
onDelete = onDelete,
onToggleFavorite = onToggleFavorite,
onProperties = onProperties,
onDismissMenu = onDismissMenu,
)
}
}
}
}
}
// Dedicated Favorites list that replaces the file list while the star toggle is on.
// Reads the store keyed on [favTick] so it recomposes after any pin/unpin.
@Composable
internal fun FavoritesList(
currentDir: File,
favTick: Int,
onPinCurrent: () -> Unit,
onJump: (File) -> Unit,
onUnpin: (File) -> Unit,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val favorites = remember(favTick) {
FavoritesStore.list(context).map(::File).filter { it.exists() }
}
val currentAlreadyPinned = remember(favTick, currentDir.absolutePath) {
FavoritesStore.isFavorite(context, currentDir.absolutePath)
}
LazyColumn(modifier = modifier) {
item {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
) {
Text(
text = "Favorites",
color = MaterialTheme.colorScheme.onBackground,
fontSize = 15.sp,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.weight(1f),
)
TextButton(
onClick = onPinCurrent,
enabled = !currentAlreadyPinned,
) {
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(6.dp))
Text(
text = "Pin current folder",
color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp,
)
}
}
}
if (favorites.isEmpty()) {
item {
Box(
modifier = Modifier.fillParentMaxSize(),
contentAlignment = Alignment.Center,
) {
Text(
text = "No favorites yet - pin a folder with its ⋮ menu to jump back here fast.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 13.sp,
modifier = Modifier.padding(horizontal = 32.dp),
)
}
}
} else {
items(favorites, key = { it.absolutePath }) { file ->
val loc = remember(file.absolutePath) { describeLocation(file) }
FavoriteCard(
file = file,
loc = loc,
onJump = { onJump(file) },
onUnpin = { onUnpin(file) },
)
}
}
}
}
// A single favourite - matches the FileItemRow card style (surfaceContainer + outline +
// RoundedCornerShape(10.dp)). Shows the folder name, a coloured drive badge + origin text,
// and the full display path; tapping jumps into it, the filled star unpins.
@Composable
private fun FavoriteCard(
file: File,
loc: FavLocation,
onJump: () -> Unit,
onUnpin: () -> Unit,
) {
val (badgeBg, badgeFg) = badgeColors(loc)
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.clickable(onClick = onJump),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
) {
Icon(
imageVector = Icons.Filled.Folder,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(36.dp),
)
Spacer(Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(2.dp))
// Origin line: coloured drive badge + source description.
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = loc.driveLabel,
color = badgeFg,
fontSize = 11.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.clip(RoundedCornerShape(4.dp))
.background(badgeBg)
.padding(horizontal = 6.dp, vertical = 2.dp),
)
Spacer(Modifier.width(6.dp))
Text(
text = when (loc.storage) {
FavStorage.INTERNAL -> "Internal storage"
FavStorage.SD -> "SD card"
FavStorage.OTHER -> "Storage"
},
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
)
}
Spacer(Modifier.height(2.dp))
Text(
text = loc.displayPath,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
fontFamily = FontFamily.Monospace,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
IconButton(onClick = onUnpin) {
Icon(
Icons.Filled.Star,
contentDescription = "Remove from favorites",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(22.dp),
)
}
}
}
}
/**
* One entry in the File Manager's grid view: a big thumbnail with the name under it.
*
* Deliberately drops size and date - at this width they truncate to noise. The grid is for
* recognising things by sight (screenshots, covers, game folders); the list stays the view for
* reading details.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun FileGridTile(
file: File,
selectionMode: Boolean,
selected: Boolean,
onLongPress: () -> Unit,
onToggleSelect: () -> Unit,
onTap: () -> Unit,
onMenu: () -> Unit,
menuExpanded: Boolean = false,
onDismissMenu: () -> Unit = {},
isFavorite: Boolean = false,
onSelect: () -> Unit = {},
onRename: () -> Unit = {},
onCopy: () -> Unit = {},
onCut: () -> Unit = {},
onDelete: () -> Unit = {},
onToggleFavorite: () -> Unit = {},
onProperties: () -> Unit = {},
) {
val isDir = file.isDirectory
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
if (!isDir && file.name.lowercase().endsWith(".exe")) {
LaunchedEffect(file.absolutePath) {
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
if (bmp != null) exeIcon = bmp.asImageBitmap()
}
}
// The tile has no ⋮ button - long-press opens this menu, anchored to the Box around the Card.
Box {
Card(
modifier = Modifier
.padding(4.dp)
.combinedClickable(
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(
containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)
else MaterialTheme.colorScheme.surfaceContainer,
),
border = BorderStroke(
1.dp,
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
),
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth().padding(8.dp),
) {
Box(modifier = Modifier.size(56.dp), contentAlignment = Alignment.Center) {
when {
exeIcon != null -> Image(bitmap = exeIcon!!, contentDescription = null, modifier = Modifier.size(48.dp))
isDir -> Icon(
Icons.Filled.Folder, null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(48.dp),
)
isImage -> AsyncImage(
model = file,
contentDescription = null,
contentScale = ContentScale.Crop,
placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile),
error = rememberVectorPainter(Icons.Filled.InsertDriveFile),
modifier = Modifier.size(56.dp).clip(RoundedCornerShape(6.dp)),
)
else -> Icon(
Icons.Filled.InsertDriveFile, null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(44.dp),
)
}
if (selectionMode) {
androidx.compose.material3.Checkbox(
checked = selected,
onCheckedChange = { onToggleSelect() },
modifier = Modifier.align(Alignment.TopStart),
)
}
}
Spacer(Modifier.height(4.dp))
// Always reserve two lines (issue #475): a one-line name used to make its card shorter than
// its neighbours, so grid rows had ragged heights. Fixed min/max keeps every tile the same size.
Text(
file.name,
color = MaterialTheme.colorScheme.onSurface,
fontSize = 12.sp,
minLines = 2,
maxLines = 2,
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
overflow = TextOverflow.Ellipsis,
)
}
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = onDismissMenu,
modifier = Modifier.outlinedMenuCard(),
) {
FileContextMenuItems(
file = file,
isFavorite = isFavorite,
onSelect = onSelect,
onRename = onRename,
onCopy = onCopy,
onCut = onCut,
onDelete = onDelete,
onToggleFavorite = onToggleFavorite,
onProperties = onProperties,
onDismissMenu = onDismissMenu,
)
}
}
}
@@ -0,0 +1,101 @@
package com.droiddeck.launcher.files
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Storage
import androidx.compose.material.icons.filled.Image
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.text.style.TextOverflow
import java.io.File
// The File Manager's non-UI helpers: sorting, paths, conflict choices and favourite locations.
/*
* Bannerlator's File Manager (ui/screens/FileManagerScreen.kt), carried over whole: the same
* browsing, grid and list, sorting, search, multi-select, copy/cut/paste with conflicts and
* progress, rename, delete, new folder, properties, favourites and the locations rail, and the
* same pick modes. What this app has no use for is not here: running a file in a Wine container,
* adding it to a container's shortcuts, the Drive C: / Drive Z: locations and the archive
* unpacker that installs into a prefix. Everything else is line for line the same so a fix in
* either app carries to the other.
*/
/**
* What to do when a pasted item already exists at the destination.
*
* OVERWRITE and MERGE resolve to the same call - `copyWithProgress` recurses into an existing
* directory and truncates existing files - but they mean different things to the user, so both are
* offered and the wording is chosen per item type (files overwrite, folders merge).
*/
enum class ConflictChoice { OVERWRITE, MERGE, KEEP_BOTH, SKIP }
/**
* Shortens a path from the LEFT, keeping whole segments.
*
* Compose's TextOverflow can only ellipsise the tail, which for a path throws away the part that
* matters - `/storage/emulated/0/Games/Racing/Dir…` tells you nothing about where you are.
*/
internal fun elidePathStart(path: String, max: Int): String {
if (path.length <= max) return path
val parts = path.split('/').filter { it.isNotEmpty() }
val out = StringBuilder()
for (part in parts.asReversed()) {
if (out.length + part.length + 1 > max - 2) break
out.insert(0, "/$part")
}
return if (out.isEmpty()) "…" + path.takeLast(max - 1) else "…$out"
}
/** Folder-first ordering stays fixed across both sort directions. */
internal fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
val inner: Comparator<File> = when (sortBy) {
"date" -> compareBy { it.lastModified() }
// Directory length() is meaningless, so folders sort by name within the size ordering
// instead of pretending to have one.
"size" -> compareBy { if (it.isDirectory) -1L else it.length() }
else -> compareBy { it.name.lowercase() }
}
val directed = if (desc) inner.reversed() else inner
return compareBy<File> { if (it.isDirectory) 0 else 1 }.then(directed)
}
// Image extensions that get a real thumbnail (via Coil) instead of the generic file icon.
internal val IMAGE_THUMB_EXTS = setOf("jpg", "jpeg", "png", "webp", "bmp", "gif")
// True when [child] is [ancestor] itself or lives anywhere inside it.
internal fun isWithin(child: File, ancestor: File): Boolean {
val c = runCatching { child.canonicalPath }.getOrDefault(child.absolutePath)
val a = runCatching { ancestor.canonicalPath }.getOrDefault(ancestor.absolutePath)
return c == a || c.startsWith(a + File.separator)
}
// ── Favorites: origin resolution ──
enum class FavStorage { INTERNAL, SD, OTHER }
data class FavLocation(
val storage: FavStorage,
val driveLabel: String, // "Internal", "SD card", or "Storage"
val displayPath: String // the unix absolute path
)
// Resolve where [file] lives (storage source + a friendly label) by prefix-matching its path.
fun describeLocation(file: File): FavLocation {
val abs = file.absolutePath
val internal = "/storage/emulated/0"
if (abs == internal || abs.startsWith("$internal/")) {
return FavLocation(FavStorage.INTERNAL, "Internal", abs)
}
if (abs.startsWith("/storage/")) {
val name = abs.removePrefix("/storage/").substringBefore('/')
if (name.isNotEmpty() && name != "emulated" && name != "self") {
return FavLocation(FavStorage.SD, "SD card", abs)
}
}
return FavLocation(FavStorage.OTHER, "Storage", abs)
}
@@ -7,12 +7,7 @@ import androidx.compose.foundation.Image
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
@@ -21,7 +16,6 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
@@ -33,41 +27,25 @@ import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.ContentPaste
import androidx.compose.material.icons.filled.CreateNewFolder
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.FileCopy
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.InsertDriveFile
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.ContentCut
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.SdStorage
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Unarchive
import androidx.compose.material.icons.filled.ViewList
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material.icons.filled.PushPin
import androidx.compose.material.icons.filled.Storage
import androidx.compose.material.icons.filled.Smartphone
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.SportsEsports
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
@@ -95,217 +73,22 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import coil.compose.AsyncImage
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/*
* Bannerlator's File Manager (ui/screens/FileManagerScreen.kt), carried over whole: the same
* browsing, grid and list, sorting, search, multi-select, copy/cut/paste with conflicts and
* progress, rename, delete, new folder, properties, favourites and the locations rail, and the
* same pick modes. What this app has no use for is not here: running a file in a Wine container,
* adding it to a container's shortcuts, the Drive C: / Drive Z: locations and the archive
* unpacker that installs into a prefix. Everything else is line for line the same so a fix in
* either app carries to the other.
*/
/**
* What to do when a pasted item already exists at the destination.
*
* OVERWRITE and MERGE resolve to the same call - `copyWithProgress` recurses into an existing
* directory and truncates existing files - but they mean different things to the user, so both are
* offered and the wording is chosen per item type (files overwrite, folders merge).
*/
enum class ConflictChoice { OVERWRITE, MERGE, KEEP_BOTH, SKIP }
/**
* Shortens a path from the LEFT, keeping whole segments.
*
* Compose's TextOverflow can only ellipsise the tail, which for a path throws away the part that
* matters - `/storage/emulated/0/Games/Racing/Dir…` tells you nothing about where you are.
*/
private fun elidePathStart(path: String, max: Int): String {
if (path.length <= max) return path
val parts = path.split('/').filter { it.isNotEmpty() }
val out = StringBuilder()
for (part in parts.asReversed()) {
if (out.length + part.length + 1 > max - 2) break
out.insert(0, "/$part")
}
return if (out.isEmpty()) "…" + path.takeLast(max - 1) else "…$out"
}
/** Folder-first ordering stays fixed across both sort directions. */
private fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
val inner: Comparator<File> = when (sortBy) {
"date" -> compareBy { it.lastModified() }
// Directory length() is meaningless, so folders sort by name within the size ordering
// instead of pretending to have one.
"size" -> compareBy { if (it.isDirectory) -1L else it.length() }
else -> compareBy { it.name.lowercase() }
}
val directed = if (desc) inner.reversed() else inner
return compareBy<File> { if (it.isDirectory) 0 else 1 }.then(directed)
}
// Image extensions that get a real thumbnail (via Coil) instead of the generic file icon.
private val IMAGE_THUMB_EXTS = setOf("jpg", "jpeg", "png", "webp", "bmp", "gif")
// True when [child] is [ancestor] itself or lives anywhere inside it.
private fun isWithin(child: File, ancestor: File): Boolean {
val c = runCatching { child.canonicalPath }.getOrDefault(child.absolutePath)
val a = runCatching { ancestor.canonicalPath }.getOrDefault(ancestor.absolutePath)
return c == a || c.startsWith(a + File.separator)
}
// ── DOS file attributes (Read-only / Hidden) ──
// The in-container file manager (wfm.exe) exposes these in its Properties dialog; this mirrors the
// same two toggles for files browsed from the app side. No root - we only touch permission bits the
// app owns (container files) and the Wine DOS-attribute xattr.
// FILE_ATTRIBUTE_HIDDEN, as Wine encodes it in the user.DOSATTRIB extended attribute.
private const val FILE_ATTRIBUTE_HIDDEN = 0x2
private const val DOSATTRIB_XATTR = "user.DOSATTRIB"
// Snapshot of a file's two toggleable attributes. hiddenSupported is false when the underlying
// filesystem can't store the DOSATTRIB xattr (the FUSE /storage volumes) - the Hidden toggle is then
// disabled while Read-only keeps working.
private data class FileAttrState(
val readOnly: Boolean,
val hidden: Boolean,
val hiddenSupported: Boolean,
)
// Wine (and Samba) store user.DOSATTRIB as an ASCII hex string ("0x22"), sometimes with trailing
// Samba fields after a separator. We only need the leading DOS-attribute hex, so read from the "0x"
// prefix and stop at the first non-hex character.
private fun parseDosAttrib(raw: ByteArray): Int {
val s = String(raw, Charsets.US_ASCII).trim()
val hex = if (s.startsWith("0x") || s.startsWith("0X")) s.substring(2) else s
val digits = hex.takeWhile { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }
return digits.toIntOrNull(16) ?: 0
}
// Read the current read-only + Wine-hidden state. Never throws: an xattr-unsupported filesystem
// comes back hiddenSupported=false (Hidden toggle disabled), Read-only always resolves.
private fun readFileAttrs(file: File): FileAttrState {
val path = file.absolutePath
// Read-only reflects the OWNER write bit - that's what Wine maps to FILE_ATTRIBUTE_READONLY.
val readOnly = runCatching {
(android.system.Os.stat(path).st_mode and android.system.OsConstants.S_IWUSR) == 0
}.getOrDefault(!file.canWrite())
var hidden = false
var supported = true
try {
hidden = (parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR)) and FILE_ATTRIBUTE_HIDDEN) != 0
} catch (e: android.system.ErrnoException) {
// ENODATA: xattr namespace works, the attribute just isn't set yet -> still toggleable.
// ENOTSUP/EOPNOTSUPP/anything else: the fs can't store it -> disable the Hidden toggle.
supported = e.errno == android.system.OsConstants.ENODATA
} catch (e: Exception) {
supported = false
}
return FileAttrState(readOnly, hidden, supported)
}
// Toggle read-only by flipping the write bits, preserving every other permission bit. Setting
// read-only clears owner/group/other write (so Wine sees FILE_ATTRIBUTE_READONLY regardless of which
// write bit it checks); clearing it restores owner write. Falls back to File.setWritable if chmod is
// somehow refused. Returns true on success.
private fun setReadOnly(file: File, readOnly: Boolean): Boolean = runCatching {
val path = file.absolutePath
val mode = android.system.Os.stat(path).st_mode
val writeBits = android.system.OsConstants.S_IWUSR or
android.system.OsConstants.S_IWGRP or android.system.OsConstants.S_IWOTH
val newMode = if (readOnly) mode and writeBits.inv()
else mode or android.system.OsConstants.S_IWUSR
android.system.Os.chmod(path, newMode)
true
}.getOrElse { file.setWritable(!readOnly, true) }
// Flip Wine's DOS hidden bit in user.DOSATTRIB, preserving the other DOS-attribute bits
// (archive/system/read-only) already encoded there, and synthesizing a minimal value when absent.
// Writes Wine's own "0x%x" format, which Wine reads back natively. Returns false when the fs can't
// store the xattr, so the caller can disable just the Hidden toggle.
private fun setHidden(file: File, hidden: Boolean): Boolean = try {
val path = file.absolutePath
var attr = try {
parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR))
} catch (e: android.system.ErrnoException) {
if (e.errno == android.system.OsConstants.ENODATA) 0 else throw e
}
attr = if (hidden) attr or FILE_ATTRIBUTE_HIDDEN else attr and FILE_ATTRIBUTE_HIDDEN.inv()
val value = "0x%x".format(attr).toByteArray(Charsets.US_ASCII)
android.system.Os.setxattr(path, DOSATTRIB_XATTR, value, 0)
true
} catch (e: Exception) {
false
}
// ── Favorites: origin resolution ──
enum class FavStorage { INTERNAL, SD, OTHER }
data class FavLocation(
val storage: FavStorage,
val driveLabel: String, // "Internal", "SD card", or "Storage"
val displayPath: String // the unix absolute path
)
// Resolve where [file] lives (storage source + a friendly label) by prefix-matching its path.
fun describeLocation(file: File): FavLocation {
val abs = file.absolutePath
val internal = "/storage/emulated/0"
if (abs == internal || abs.startsWith("$internal/")) {
return FavLocation(FavStorage.INTERNAL, "Internal", abs)
}
if (abs.startsWith("/storage/")) {
val name = abs.removePrefix("/storage/").substringBefore('/')
if (name.isNotEmpty() && name != "emulated" && name != "self") {
return FavLocation(FavStorage.SD, "SD card", abs)
}
}
return FavLocation(FavStorage.OTHER, "Storage", abs)
}
// Semantic identity colours for the favourite-card drive badge. Intentionally NOT theme
// accent colours - they identify the storage source at a glance. Returns (background, foreground).
private fun badgeColors(loc: FavLocation): Pair<Color, Color> {
val white = Color(0xFFFFFFFF)
return when {
loc.storage == FavStorage.INTERNAL -> Color(0xFF2E5FB0) to white // blue
loc.storage == FavStorage.SD -> Color(0xFF2E7D32) to white // green
else -> Color(0xFF555555) to white // grey
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -1030,7 +813,7 @@ fun FileManagerScreen(
// when it doesn't fit we drop the /storage/emulated/0 prefix, not the tail.
text = elidePathStart(currentDir.absolutePath, 52),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 11.sp,
fontSize = 12.sp,
maxLines = 1,
// fill = true: the path takes all remaining width, so the free-space figure
// is pinned to the right edge instead of sliding around with the path length.
@@ -1040,7 +823,7 @@ fun FileManagerScreen(
Text(
"${FileOps.formatBytes(freeSpace)} free",
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 11.sp,
fontSize = 12.sp,
maxLines = 1,
)
}
@@ -1414,675 +1197,3 @@ fun FileManagerScreen(
} // end rail + content Row
}
}
// The context-menu item list shared by the list rows (FileItemRow) and the grid tiles
// (FileGridTile), so both open the identical menu. Gating (isDir/canRun/isInno/looksLikeArchive) is
// recomputed from [file] here - one source of truth for what each item shows. Every item dismisses
// the menu first, then runs its action.
@Composable
private fun FileContextMenuItems(
file: File,
isFavorite: Boolean,
onSelect: () -> Unit,
onRename: () -> Unit,
onCopy: () -> Unit,
onCut: () -> Unit,
onDelete: () -> Unit,
onToggleFavorite: () -> Unit,
onProperties: () -> Unit,
onDismissMenu: () -> Unit,
) {
val isDir = file.isDirectory
DropdownMenuItem(
text = { Text("Select") },
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onSelect() },
)
MenuItemDivider()
// Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config
// files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu.
DropdownMenuItem(
text = { Text("Properties") },
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onProperties() },
)
MenuItemDivider()
// Favorites are directories - only folders get the pin toggle.
if (isDir) {
DropdownMenuItem(
text = { Text(if (isFavorite) "Remove from Favorites" else "Add to Favorites") },
leadingIcon = {
Icon(
if (isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder,
null,
tint = MaterialTheme.colorScheme.primary,
)
},
onClick = { onToggleFavorite() },
)
MenuItemDivider()
}
DropdownMenuItem(
text = { Text("Rename") },
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onRename() },
)
MenuItemDivider()
DropdownMenuItem(
text = { Text("Copy") },
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onCopy() },
)
MenuItemDivider()
DropdownMenuItem(
text = { Text("Cut") },
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onCut() },
)
MenuItemDivider()
DropdownMenuItem(
text = { Text("Delete") },
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onDelete() },
)
}
@Composable
@OptIn(ExperimentalFoundationApi::class)
private fun FileItemRow(
file: File,
showActions: Boolean = true,
compact: Boolean = false,
selectionMode: Boolean = false,
selected: Boolean = false,
onLongPress: () -> Unit = {},
onToggleSelect: () -> Unit = {},
onTap: () -> Unit,
onMenu: () -> Unit,
menuExpanded: Boolean,
onDismissMenu: () -> Unit,
onSelect: () -> Unit = {},
onCopy: () -> Unit,
onCut: () -> Unit,
onDelete: () -> Unit,
onRename: () -> Unit,
isFavorite: Boolean = false,
onToggleFavorite: () -> Unit = {},
onProperties: () -> Unit = {},
) {
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
val isDir = file.isDirectory
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
// wallpaper/icon). Coil sizes the decode to the 36dp slot and caches it, so scrolling stays smooth.
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
// For real PE executables, try to pull out the embedded application icon (async, off the main thread).
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
if (!isDir && file.name.lowercase().endsWith(".exe")) {
LaunchedEffect(file.absolutePath) {
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
if (bmp != null) exeIcon = bmp.asImageBitmap()
}
}
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.combinedClickable(
// In selection mode a tap toggles instead of opening, so you can rattle through a
// folder without long-pressing every single row.
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(
containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)
else MaterialTheme.colorScheme.surfaceContainer,
),
border = BorderStroke(
1.dp,
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
) {
if (selectionMode) {
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() })
Spacer(Modifier.width(4.dp))
}
when {
// Show the executable's own embedded icon when we managed to extract one.
exeIcon != null -> Image(
bitmap = exeIcon!!,
contentDescription = null,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
isExe -> Icon(
painter = painterResource(R.drawable.icon_menu_container),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
isDir -> Icon(
imageVector = Icons.Filled.Folder,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
// Real image preview. Falls back to the generic file icon while loading or on decode failure.
isImage -> AsyncImage(
model = file,
contentDescription = null,
contentScale = ContentScale.Crop,
placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile),
error = rememberVectorPainter(Icons.Filled.InsertDriveFile),
modifier = Modifier
.size(36.dp)
.clip(RoundedCornerShape(6.dp)),
)
else -> Icon(
imageVector = Icons.Filled.InsertDriveFile,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
}
Spacer(Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = buildString {
if (!isDir) append(FileOps.formatBytes(file.length())).append(" \u2022 ")
append(dateFormat.format(Date(file.lastModified())))
},
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 11.sp,
)
}
if (showActions) Box {
IconButton(onClick = onMenu) {
Icon(Icons.Filled.MoreVert, "Actions", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = onDismissMenu,
modifier = Modifier.outlinedMenuCard(),
) {
FileContextMenuItems(
file = file,
isFavorite = isFavorite,
onSelect = onSelect,
onRename = onRename,
onCopy = onCopy,
onCut = onCut,
onDelete = onDelete,
onToggleFavorite = onToggleFavorite,
onProperties = onProperties,
onDismissMenu = onDismissMenu,
)
}
}
}
}
}
// Dedicated Favorites list that replaces the file list while the star toggle is on.
// Reads the store keyed on [favTick] so it recomposes after any pin/unpin.
@Composable
private fun FavoritesList(
currentDir: File,
favTick: Int,
onPinCurrent: () -> Unit,
onJump: (File) -> Unit,
onUnpin: (File) -> Unit,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val favorites = remember(favTick) {
FavoritesStore.list(context).map(::File).filter { it.exists() }
}
val currentAlreadyPinned = remember(favTick, currentDir.absolutePath) {
FavoritesStore.isFavorite(context, currentDir.absolutePath)
}
LazyColumn(modifier = modifier) {
item {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
) {
Text(
text = "Favorites",
color = MaterialTheme.colorScheme.onBackground,
fontSize = 15.sp,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.weight(1f),
)
TextButton(
onClick = onPinCurrent,
enabled = !currentAlreadyPinned,
) {
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(6.dp))
Text(
text = "Pin current folder",
color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp,
)
}
}
}
if (favorites.isEmpty()) {
item {
Box(
modifier = Modifier.fillParentMaxSize(),
contentAlignment = Alignment.Center,
) {
Text(
text = "No favorites yet - pin a folder with its ⋮ menu to jump back here fast.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 13.sp,
modifier = Modifier.padding(horizontal = 32.dp),
)
}
}
} else {
items(favorites, key = { it.absolutePath }) { file ->
val loc = remember(file.absolutePath) { describeLocation(file) }
FavoriteCard(
file = file,
loc = loc,
onJump = { onJump(file) },
onUnpin = { onUnpin(file) },
)
}
}
}
}
// A single favourite - matches the FileItemRow card style (surfaceContainer + outline +
// RoundedCornerShape(10.dp)). Shows the folder name, a coloured drive badge + origin text,
// and the full display path; tapping jumps into it, the filled star unpins.
@Composable
private fun FavoriteCard(
file: File,
loc: FavLocation,
onJump: () -> Unit,
onUnpin: () -> Unit,
) {
val (badgeBg, badgeFg) = badgeColors(loc)
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.clickable(onClick = onJump),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
) {
Icon(
imageVector = Icons.Filled.Folder,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(36.dp),
)
Spacer(Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(2.dp))
// Origin line: coloured drive badge + source description.
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = loc.driveLabel,
color = badgeFg,
fontSize = 9.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.clip(RoundedCornerShape(4.dp))
.background(badgeBg)
.padding(horizontal = 6.dp, vertical = 2.dp),
)
Spacer(Modifier.width(6.dp))
Text(
text = when (loc.storage) {
FavStorage.INTERNAL -> "Internal storage"
FavStorage.SD -> "SD card"
FavStorage.OTHER -> "Storage"
},
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 11.sp,
)
}
Spacer(Modifier.height(2.dp))
Text(
text = loc.displayPath,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 11.sp,
fontFamily = FontFamily.Monospace,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
IconButton(onClick = onUnpin) {
Icon(
Icons.Filled.Star,
contentDescription = "Remove from favorites",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(22.dp),
)
}
}
}
}
/**
* One entry in the File Manager's grid view: a big thumbnail with the name under it.
*
* Deliberately drops size and date - at this width they truncate to noise. The grid is for
* recognising things by sight (screenshots, covers, game folders); the list stays the view for
* reading details.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun FileGridTile(
file: File,
selectionMode: Boolean,
selected: Boolean,
onLongPress: () -> Unit,
onToggleSelect: () -> Unit,
onTap: () -> Unit,
onMenu: () -> Unit,
menuExpanded: Boolean = false,
onDismissMenu: () -> Unit = {},
isFavorite: Boolean = false,
onSelect: () -> Unit = {},
onRename: () -> Unit = {},
onCopy: () -> Unit = {},
onCut: () -> Unit = {},
onDelete: () -> Unit = {},
onToggleFavorite: () -> Unit = {},
onProperties: () -> Unit = {},
) {
val isDir = file.isDirectory
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
if (!isDir && file.name.lowercase().endsWith(".exe")) {
LaunchedEffect(file.absolutePath) {
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
if (bmp != null) exeIcon = bmp.asImageBitmap()
}
}
// The tile has no ⋮ button - long-press opens this menu, anchored to the Box around the Card.
Box {
Card(
modifier = Modifier
.padding(4.dp)
.combinedClickable(
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(
containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)
else MaterialTheme.colorScheme.surfaceContainer,
),
border = BorderStroke(
1.dp,
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
),
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth().padding(8.dp),
) {
Box(modifier = Modifier.size(56.dp), contentAlignment = Alignment.Center) {
when {
exeIcon != null -> Image(bitmap = exeIcon!!, contentDescription = null, modifier = Modifier.size(48.dp))
isDir -> Icon(
Icons.Filled.Folder, null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(48.dp),
)
isImage -> AsyncImage(
model = file,
contentDescription = null,
contentScale = ContentScale.Crop,
placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile),
error = rememberVectorPainter(Icons.Filled.InsertDriveFile),
modifier = Modifier.size(56.dp).clip(RoundedCornerShape(6.dp)),
)
else -> Icon(
Icons.Filled.InsertDriveFile, null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(44.dp),
)
}
if (selectionMode) {
androidx.compose.material3.Checkbox(
checked = selected,
onCheckedChange = { onToggleSelect() },
modifier = Modifier.align(Alignment.TopStart),
)
}
}
Spacer(Modifier.height(4.dp))
// Always reserve two lines (issue #475): a one-line name used to make its card shorter than
// its neighbours, so grid rows had ragged heights. Fixed min/max keeps every tile the same size.
Text(
file.name,
color = MaterialTheme.colorScheme.onSurface,
fontSize = 11.sp,
minLines = 2,
maxLines = 2,
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
overflow = TextOverflow.Ellipsis,
)
}
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = onDismissMenu,
modifier = Modifier.outlinedMenuCard(),
) {
FileContextMenuItems(
file = file,
isFavorite = isFavorite,
onSelect = onSelect,
onRename = onRename,
onCopy = onCopy,
onCut = onCut,
onDelete = onDelete,
onToggleFavorite = onToggleFavorite,
onProperties = onProperties,
onDismissMenu = onDismissMenu,
)
}
}
}
/**
* Properties sheet for a single file or folder: basic info plus the two Windows/Wine file attributes
* the in-container file manager (wfm.exe) also exposes - Read-only and Hidden. Each toggle applies
* immediately (off the main thread) and refreshes the listing via [onChanged].
*
* State is keyed on the file so it always reflects the entry it was opened for. On a filesystem that
* can't store Wine's DOSATTRIB xattr (the FUSE /storage volumes) only the Hidden toggle is disabled;
* Read-only keeps working everywhere.
*/
@Composable
private fun FilePropertiesDialog(
file: File,
onDismiss: () -> Unit,
onChanged: () -> Unit,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
var attrs by remember(file.absolutePath) { mutableStateOf<FileAttrState?>(null) }
// Guards against a second toggle landing while the first is still being applied off-thread.
var busy by remember(file.absolutePath) { mutableStateOf(false) }
LaunchedEffect(file.absolutePath) {
attrs = withContext(Dispatchers.IO) { readFileAttrs(file) }
}
OutlinedAlertDialog(
onDismissRequest = onDismiss,
title = { Text("Properties") },
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
// ── Basic info ──
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(6.dp))
PropertyLine("Location", file.parent ?: "-")
PropertyLine(
"Type",
if (file.isDirectory) "Folder"
else file.extension.uppercase().let { if (it.isBlank()) "File" else "$it file" },
)
if (!file.isDirectory) PropertyLine("Size", FileOps.formatBytes(file.length()))
PropertyLine("Modified", dateFormat.format(Date(file.lastModified())))
Spacer(Modifier.height(10.dp))
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
Spacer(Modifier.height(6.dp))
val state = attrs
// ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY).
AttributeToggleRow(
label = "Read-only",
description = "Stops games (and Wine) from overwriting or deleting this file.",
checked = state?.readOnly == true,
enabled = state != null && !busy,
onToggle = { want ->
busy = true
scope.launch {
val ok = withContext(Dispatchers.IO) { setReadOnly(file, want) }
busy = false
if (ok) {
attrs = attrs?.copy(readOnly = want)
onChanged()
} else {
Toast.makeText(context, "Couldn't change Read-only", Toast.LENGTH_SHORT).show()
}
}
},
)
Spacer(Modifier.height(2.dp))
// ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr.
val hiddenSupported = state?.hiddenSupported == true
AttributeToggleRow(
label = "Hidden",
description = if (state != null && !hiddenSupported)
"This storage can't store the hidden flag."
else "Marks the file hidden in Windows (Wine's hidden attribute).",
checked = state?.hidden == true,
enabled = state != null && hiddenSupported && !busy,
onToggle = { want ->
busy = true
scope.launch {
val ok = withContext(Dispatchers.IO) { setHidden(file, want) }
busy = false
if (ok) {
attrs = attrs?.copy(hidden = want)
onChanged()
} else {
// The write failed after all - disable the toggle rather than lie.
attrs = attrs?.copy(hiddenSupported = false)
Toast.makeText(context, "Couldn't change Hidden on this storage", Toast.LENGTH_SHORT).show()
}
}
},
)
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("Done") } },
)
}
// One "label: value" line in the Properties info block.
@Composable
private fun PropertyLine(label: String, value: String) {
Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
Text(
text = label,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
modifier = Modifier.width(76.dp),
)
Text(
text = value,
color = MaterialTheme.colorScheme.onSurface,
fontSize = 12.sp,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
}
}
// A labelled attribute switch with a one-line description, used by the Properties sheet.
@Composable
private fun AttributeToggleRow(
label: String,
description: String,
checked: Boolean,
enabled: Boolean,
onToggle: (Boolean) -> Unit,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = label,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
)
Text(
text = description,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 11.sp,
)
}
Spacer(Modifier.width(8.dp))
androidx.compose.material3.Switch(
checked = checked,
enabled = enabled,
onCheckedChange = onToggle,
)
}
}
@@ -0,0 +1,202 @@
package com.droiddeck.launcher.files
import android.widget.Toast
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
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.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
// The File Manager's properties dialog.
/**
* Properties sheet for a single file or folder: basic info plus the two Windows/Wine file attributes
* the in-container file manager (wfm.exe) also exposes - Read-only and Hidden. Each toggle applies
* immediately (off the main thread) and refreshes the listing via [onChanged].
*
* State is keyed on the file so it always reflects the entry it was opened for. On a filesystem that
* can't store Wine's DOSATTRIB xattr (the FUSE /storage volumes) only the Hidden toggle is disabled;
* Read-only keeps working everywhere.
*/
@Composable
internal fun FilePropertiesDialog(
file: File,
onDismiss: () -> Unit,
onChanged: () -> Unit,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
var attrs by remember(file.absolutePath) { mutableStateOf<FileAttrState?>(null) }
// Guards against a second toggle landing while the first is still being applied off-thread.
var busy by remember(file.absolutePath) { mutableStateOf(false) }
LaunchedEffect(file.absolutePath) {
attrs = withContext(Dispatchers.IO) { readFileAttrs(file) }
}
OutlinedAlertDialog(
onDismissRequest = onDismiss,
title = { Text("Properties") },
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
// ── Basic info ──
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(6.dp))
PropertyLine("Location", file.parent ?: "-")
PropertyLine(
"Type",
if (file.isDirectory) "Folder"
else file.extension.uppercase().let { if (it.isBlank()) "File" else "$it file" },
)
if (!file.isDirectory) PropertyLine("Size", FileOps.formatBytes(file.length()))
PropertyLine("Modified", dateFormat.format(Date(file.lastModified())))
Spacer(Modifier.height(10.dp))
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
Spacer(Modifier.height(6.dp))
val state = attrs
// ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY).
AttributeToggleRow(
label = "Read-only",
description = "Stops games (and Wine) from overwriting or deleting this file.",
checked = state?.readOnly == true,
enabled = state != null && !busy,
onToggle = { want ->
busy = true
scope.launch {
val ok = withContext(Dispatchers.IO) { setReadOnly(file, want) }
busy = false
if (ok) {
attrs = attrs?.copy(readOnly = want)
onChanged()
} else {
Toast.makeText(context, "Couldn't change Read-only", Toast.LENGTH_SHORT).show()
}
}
},
)
Spacer(Modifier.height(2.dp))
// ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr.
val hiddenSupported = state?.hiddenSupported == true
AttributeToggleRow(
label = "Hidden",
description = if (state != null && !hiddenSupported)
"This storage can't store the hidden flag."
else "Marks the file hidden in Windows (Wine's hidden attribute).",
checked = state?.hidden == true,
enabled = state != null && hiddenSupported && !busy,
onToggle = { want ->
busy = true
scope.launch {
val ok = withContext(Dispatchers.IO) { setHidden(file, want) }
busy = false
if (ok) {
attrs = attrs?.copy(hidden = want)
onChanged()
} else {
// The write failed after all - disable the toggle rather than lie.
attrs = attrs?.copy(hiddenSupported = false)
Toast.makeText(context, "Couldn't change Hidden on this storage", Toast.LENGTH_SHORT).show()
}
}
},
)
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("Done") } },
)
}
// One "label: value" line in the Properties info block.
@Composable
private fun PropertyLine(label: String, value: String) {
Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
Text(
text = label,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
modifier = Modifier.width(76.dp),
)
Text(
text = value,
color = MaterialTheme.colorScheme.onSurface,
fontSize = 12.sp,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
}
}
// A labelled attribute switch with a one-line description, used by the Properties sheet.
@Composable
private fun AttributeToggleRow(
label: String,
description: String,
checked: Boolean,
enabled: Boolean,
onToggle: (Boolean) -> Unit,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = label,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
)
Text(
text = description,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
)
}
Spacer(Modifier.width(8.dp))
androidx.compose.material3.Switch(
checked = checked,
enabled = enabled,
onCheckedChange = onToggle,
)
}
}
@@ -14,7 +14,15 @@ import java.io.File
*/
object Library {
/** [gameId] is what steam://rungameid/ takes: the appid for a Steam title, the shortcut id for an added game. */
class SteamGame(val appId: Int, val name: String, val art: File?, val library: String, val gameId: Long = appId.toLong())
/**
* [art] is the portrait capsule; [hero] the wide banner Steam shows above a game's page, when
* the client has cached one. [lastPlayed] is Steam's own "LastPlayed" (unix seconds), 0 = never.
*/
class SteamGame(
val appId: Int, val name: String, val art: File?, val library: String, val gameId: Long = appId.toLong(),
val hero: File? = null, val lastPlayed: Long = 0L,
val gameFiles: File? = null, val protonPrefix: File? = null,
)
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
/** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */
@@ -55,16 +63,35 @@ object Library {
4690330, // Legacy Steam Runtime
)
private val STEAM_CAPSULES = listOf("library_capsule.jpg", "library_600x900.jpg")
private val STEAM_HEROES = listOf("library_hero.jpg")
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
private val LAST_PLAYED = Regex("^\\s*\"LastPlayed\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
private val INSTALL_DIR = Regex("^\\s*\"installdir\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
/** Steam's library roots visible to this launcher: its private default plus the selected library. */
private fun steamLibraries(context: Context): List<Pair<File, String>> {
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
return listOfNotNull(
root to "internal",
GameStorage.effective(context)?.let { File(it.path) to it.label },
)
}
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
fun protonPrefix(context: Context, appId: Long, preferredLibrary: File? = null): File? {
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first })
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
return roots.asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
.firstOrNull { it.isDirectory }
}
fun steamGames(context: Context): List<SteamGame> {
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
val cache = File(root, "appcache/librarycache")
val libraries = listOfNotNull(
root to "internal",
GameStorage.effective(context)?.let { File(it.path) to it.label },
)
val libraries = steamLibraries(context)
val out = LinkedHashMap<Int, SteamGame>()
for ((library, label) in libraries) {
val steamapps = File(library, "steamapps")
@@ -77,19 +104,31 @@ object Library {
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
// StateFlags 4 = fully installed; anything else is downloading, updating or broken.
if (name.isEmpty() || flags and 4 == 0) return@forEach
val art = steamCapsule(cache, appId)
out[appId] = SteamGame(appId, name, art, label)
val art = steamCacheImage(cache, appId, STEAM_CAPSULES)
val hero = steamCacheImage(cache, appId, STEAM_HEROES)
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
// App manifests are Valve KeyValues (VDF) files. installdir is one folder
// below steamapps/common; only expose it when the directory exists and the
// manifest value cannot escape that directory.
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
out[appId] = SteamGame(
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
gameFiles = gameFiles,
protonPrefix = protonPrefix(context, appId.toLong(), library),
)
}
}
return out.values.toList()
}
/** Steam stores current library capsules inside hash-named folders under the app's cache dir. */
private fun steamCapsule(cache: File, appId: Int): File? {
/** Steam stores current library art inside hash-named folders under the app's cache dir. */
private 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 STEAM_CAPSULES.asSequence()
return names.asSequence()
.flatMap { name -> dirs.asSequence().map { File(it, name) } }
.firstOrNull { it.isFile && it.length() > 0L }
}
@@ -278,7 +317,9 @@ object Library {
"-C", "Dolphin.General.HotkeysRequireFocus=False", "-C", "Dolphin.Input.BackgroundInput=True",
"-e", guestPath,
)
"cemu" -> listOf("-g", guestPath)
// Full screen (LaunchSettings.cpp -f); the settings seed keeps the Getting Started
// dialog away (bannerlator-pad-defaults).
"cemu" -> listOf("-f", "-g", guestPath)
// Full screen (CLI.cpp --fullscreen); the guide button leaves it for melonDS's menus and
// comes back (HK_FullscreenToggle, bannerlator-pad-defaults).
"melonds" -> listOf("-f", guestPath)
@@ -40,9 +40,11 @@ object FrameGen {
}
/** "Off", "Win-FG 2×", "LSFG 3×" - for the main screen. */
fun label(context: Context): String = when (engine(context)) {
ENGINE_WINFG -> "Win-FG ${multiplier(context)}×"
ENGINE_LSFG -> "LSFG ${multiplier(context)}×"
fun label(context: Context): String = label(engine(context), multiplier(context))
fun label(engine: String, multiplier: Int): String = when (engine) {
ENGINE_WINFG -> "Win-FG $multiplier×"
ENGINE_LSFG -> "LSFG $multiplier×"
else -> "Off"
}
@@ -82,47 +84,5 @@ object FrameGen {
return problem
}
/**
* Off, or an engine at 2x/3x/4x; saved on pick, then [onChanged]. The LSFG rows are greyed
* and unpickable until Lossless Scaling is installed in the Steam client - the engine cannot
* run without its DLL, so offering it would only produce a setting that silently does nothing.
*/
fun showPicker(activity: android.app.Activity, onChanged: () -> Unit) {
val lsfgReady = LsfgNative.isInstalled(activity)
val lsfgNote = if (lsfgReady) "" else " - install Lossless Scaling in Steam"
val choices = listOf("Off",
"Win-FG 2×", "Win-FG 3×", "Win-FG 4×",
"LSFG 2×$lsfgNote", "LSFG 3×$lsfgNote", "LSFG 4×$lsfgNote")
val current = when (engine(activity)) {
ENGINE_WINFG -> multiplier(activity) - 1
ENGINE_LSFG -> if (lsfgReady) multiplier(activity) + 2 else 0
else -> 0
}
val adapter = object : android.widget.ArrayAdapter<String>(
activity, android.R.layout.simple_list_item_single_choice, choices) {
override fun isEnabled(position: Int) = lsfgReady || position < 4
override fun areAllItemsEnabled() = lsfgReady
override fun getView(position: Int, convertView: android.view.View?, parent: android.view.ViewGroup): android.view.View {
val view = super.getView(position, convertView, parent)
view.isEnabled = isEnabled(position)
view.alpha = if (isEnabled(position)) 1f else 0.38f
return view
}
}
android.app.AlertDialog.Builder(activity)
.setTitle(com.droiddeck.launcher.R.string.frame_gen_title)
.setSingleChoiceItems(adapter, current) { dialog, which ->
when (which) {
0 -> set(activity, ENGINE_OFF, 2)
in 1..3 -> set(activity, ENGINE_WINFG, which + 1)
else -> set(activity, ENGINE_LSFG, which - 2)
}
dialog.dismiss()
onChanged()
}
.setNeutralButton(android.R.string.ok, null)
.show()
}
private const val TAG = "FrameGen"
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.gpu
import com.droiddeck.launcher.core.Hashes
import android.content.Context
import com.droiddeck.launcher.core.FileUtils
import org.json.JSONArray
@@ -27,7 +28,9 @@ object TurnipReleases {
private const val KEY_DOWNLOADS = "downloads"
/** [label] names the variant for the menu: the GPUs it is for, and a build flavour. */
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String)
/** [sha256] is the release asset's digest from GitHub; empty for a list cached before it was kept. */
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String,
val sha256: String = "")
/** [latest] = each source's newest release tag, for the refresh line. */
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
@@ -89,11 +92,13 @@ object TurnipReleases {
val a = list.getJSONObject(j)
val name = a.getString("name")
val (linux, label) = src.classify(name, tag) ?: continue
// Only assets GitHub has a sha256 for are offered: the download is checked against it.
val sha = Hashes.githubSha256(a.optString("digest")) ?: continue
// Newest first: the first release carrying a variant is the one offered.
if (!seen.add("$linux|$label")) continue
assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name)
.put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))
.put("linux", linux).put("label", label))
.put("linux", linux).put("label", label).put("sha256", sha))
}
}
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
@@ -131,7 +136,7 @@ object TurnipReleases {
for (i in 0 until list.length()) {
val a = list.getJSONObject(i)
out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"),
a.optLong("size"), a.getBoolean("linux"), a.getString("label")))
a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", "")))
}
val latest = ArrayList<Pair<String, String>>()
val l = json.optJSONArray("latest") ?: JSONArray()
@@ -167,6 +172,7 @@ object TurnipReleases {
/** Download an asset into the cache; the caller imports it and deletes the file. */
fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File {
if (asset.sha256.isEmpty()) throw IOException("This driver list predates checksums - refresh it and try again")
val target = File(context.cacheDir, asset.name)
val c = URL(asset.url).openConnection() as HttpURLConnection
c.connectTimeout = 15_000
@@ -191,6 +197,9 @@ object TurnipReleases {
}
}
}
if (!asset.sha256.equals(Hashes.sha256(target), ignoreCase = true)) {
throw IOException("Checksum mismatch - the download was discarded")
}
return target
} catch (e: Exception) {
FileUtils.delete(target)
@@ -25,6 +25,7 @@ import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.onSignal
import com.droiddeck.launcher.ui.LocalPalette
class ControllerEditorActivity : ComponentActivity() {
@@ -47,7 +48,7 @@ class ControllerEditorActivity : ComponentActivity() {
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.9f), RoundedCornerShape(50))
.padding(start = 14.dp, end = 5.dp, top = 5.dp, bottom = 5.dp),
) {
Text("Drag to move", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(end = 4.dp))
Text("Drag to move", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(end = 4.dp))
EditorButton("Reset", false) { controls.resetLayout() }
EditorButton("Cancel", false) { finish() }
EditorButton("Save", true) {
@@ -67,7 +68,7 @@ class ControllerEditorActivity : ComponentActivity() {
val pal = LocalPalette.current
Text(
label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
color = if (primary) Color.White else MaterialTheme.colorScheme.onBackground,
color = if (primary) pal.onSignal else MaterialTheme.colorScheme.onBackground,
modifier = Modifier.clip(RoundedCornerShape(50))
.background(if (primary) pal.signal else Color.White.copy(alpha = 0.06f))
.clickable(onClick = onClick)
@@ -1,12 +1,11 @@
package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.core.Hashes
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.session.SessionState
import java.io.File
import java.io.FileInputStream
import java.security.MessageDigest
import org.json.JSONArray
/** Optional Decky Loader installation for the ARM64 Linux guest. */
@@ -84,7 +83,7 @@ object DeckyManager {
val n = it.optString("name")
(n == "$name.sha256" || n == "$name.sha256sum" || n == "$name.sha256.txt") && it.optString("browser_download_url").startsWith("https://")
}?.optString("browser_download_url")?.takeIf { it.startsWith("https://") }
val digest = binary.optString("digest").takeIf { it.matches(Regex("(?i)sha256:[0-9a-f]{64}")) }
val digest = binary.optString("digest").takeIf { Hashes.isGithubSha256(it) }
if (digest == null && checksum == null) continue
val size = binary.optLong("size", 0)
if (size <= 0) continue
@@ -109,7 +108,7 @@ object DeckyManager {
Regex("(?i)\\b[0-9a-f]{64}\\b").find(checksumBody)?.value
} ?: run { temp.delete(); return "Release checksum is missing" }
if (!expected.matches(Regex("(?i)[0-9a-f]{64}"))) { temp.delete(); return "Release checksum is invalid" }
if (!expected.equals(sha256(temp), true)) { temp.delete(); return "Decky Loader checksum mismatch" }
if (!expected.equals(Hashes.sha256(temp), true)) { temp.delete(); return "Decky Loader checksum mismatch" }
if (!validElf(temp, release.machine)) { temp.delete(); return "Release asset is not a compatible 64-bit Linux executable" }
if (SessionState.running) { temp.delete(); return "A session started during the download; stop it before installing Decky Loader" }
if (!temp.setExecutable(true, false)) { temp.delete(); return "Could not mark PluginLoader executable" }
@@ -148,15 +147,6 @@ object DeckyManager {
if (wipeData) File(root, "root/homebrew").deleteRecursively()
}
private fun sha256(file: File): String {
val digest = MessageDigest.getInstance("SHA-256")
FileInputStream(file).buffered().use { input ->
val buffer = ByteArray(1024 * 1024)
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
}
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 255) }
}
private fun validElf(file: File, machine: Int): Boolean = runCatching {
file.inputStream().use { input ->
val h = ByteArray(20)
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.core.Hashes
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.Downloader
@@ -18,6 +19,12 @@ import java.io.File
object DesktopCatalog {
private const val TAG = "DesktopCatalog"
const val CATALOG_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/desktop.json"
/**
* Valve's Proton Experimental (ARM64) with its appmanifest, laid out as the client keeps it.
* In a catalog of its own so it never shows among the packages a user picks from.
*/
const val STEAM_SEED_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/steam-seed.json"
const val PROTON_SEED_ID = "proton-arm64"
class Entry(
val id: String, val name: String, val tier: Int, val version: String, val kind: String,
@@ -26,8 +33,8 @@ object DesktopCatalog {
val icon: String, val category: String,
)
fun fetch(): List<Entry>? {
val body = Downloader.downloadString(CATALOG_URL) ?: return null
fun fetch(url: String = CATALOG_URL): List<Entry>? {
val body = Downloader.downloadString(url) ?: return null
return try {
val json = JSONObject(body)
val arr = json.getJSONArray("packages")
@@ -57,6 +64,15 @@ object DesktopCatalog {
fun installed(context: Context, id: String): String? =
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
/**
* True until the ARM64 Proton has been placed once. Its appmanifest counts too, so an install
* the client fetched itself is never overwritten; after the first placement the client owns it
* and updates it like any other app, and a user who removes it is not given it back.
*/
fun protonSeedNeeded(context: Context): Boolean =
installed(context, PROTON_SEED_ID) == null &&
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
// labwc comes with the hosted desktop package itself (its launcher is staged by the app at
// every session, so it cannot tell whether the package is there); SessionFiles uses the same test.
fun desktopInstalled(context: Context): Boolean =
@@ -66,6 +82,8 @@ object DesktopCatalog {
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val root = LinuxRuntime.rootDir(context)
if (!root.isDirectory) return "The Linux runtime is not installed"
// Every catalog row carries a sha256; one without is refused rather than trusted.
if (entry.sha256.isEmpty()) return "The catalog has no checksum for ${entry.name}"
val download = File(context.cacheDir, "pkg-${entry.id}.download")
try {
listener?.onProgress("Downloading ${entry.name}", 0)
@@ -73,11 +91,9 @@ object DesktopCatalog {
listener?.onProgress("Downloading ${entry.name}", if (f < 0) -1 else Math.round(f * 100f))
}
if (!ok) return "Download failed"
if (entry.sha256.isNotEmpty()) {
listener?.onProgress("Verifying", -1)
val actual = LinuxRuntimeInstaller.sha256(download)
if (!entry.sha256.equals(actual, ignoreCase = true)) return "Checksum mismatch - nothing was changed"
}
listener?.onProgress("Verifying", -1)
val actual = Hashes.sha256(download)
if (!entry.sha256.equals(actual, ignoreCase = true)) return "Checksum mismatch - nothing was changed"
listener?.onProgress("Installing ${entry.name}", -1)
when (entry.kind) {
"appimage" -> {
@@ -4,7 +4,9 @@ import android.content.Context;
import android.util.Log;
import com.droiddeck.launcher.core.ArchivePaths;
import com.droiddeck.launcher.core.Downloader;
import com.droiddeck.launcher.core.Hashes;
import com.droiddeck.launcher.core.FileUtils;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
@@ -23,7 +25,8 @@ import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
/**
* Downloads and unpacks the Linux runtime rootfs into {@code files/linuxfs}. It is opt-in: nothing
@@ -52,7 +55,7 @@ public final class LinuxRuntimeInstaller {
public final String sha256;
public final long size;
Release(String version, String url, String sha256, long size) {
public Release(String version, String url, String sha256, long size) {
this.version = version;
this.url = url;
this.sha256 = sha256;
@@ -60,6 +63,23 @@ public final class LinuxRuntimeInstaller {
}
}
/**
* One install per process. The launcher and the session screen can both start one, and a
* launcher rebuilt mid-install (a pad plugged in, dark mode switched) forgets it had: a second
* install would share the first one's archive and staging directory and wreck both.
*/
private static final class Job {
final CopyOnWriteArrayList<ProgressListener> listeners = new CopyOnWriteArrayList<>();
final CountDownLatch done = new CountDownLatch(1);
volatile String stage = "Starting\u2026";
volatile int percent = -1;
volatile boolean ok;
}
private static final Object JOB_LOCK = new Object();
private static Job running;
private static boolean removing;
private LinuxRuntimeInstaller() {}
/** The build currently unpacked, or null when the runtime is not installed. */
@@ -104,6 +124,66 @@ public final class LinuxRuntimeInstaller {
* not. An update therefore keeps Steam, the login and the installed games.
*/
public static boolean install(Context context, Release release, ProgressListener listener) {
Job job;
boolean owner;
synchronized (JOB_LOCK) {
if (removing) return false;
owner = running == null;
if (owner) running = new Job();
job = running;
if (listener != null) job.listeners.add(listener);
}
if (!owner) return join(job, listener);
try {
job.ok = installOnce(context.getApplicationContext(), release, (stage, percent) -> {
job.stage = stage;
job.percent = percent;
for (ProgressListener l : job.listeners) l.onProgress(stage, percent);
});
return job.ok;
} finally {
synchronized (JOB_LOCK) {
running = null;
}
job.done.countDown();
}
}
/** True while an install is running in this process, whoever started it. */
public static boolean isInstalling() {
synchronized (JOB_LOCK) {
return running != null;
}
}
/**
* Follows the install already running, for a screen that was rebuilt mid-install. Blocks until
* it ends and returns its result, or returns null at once when nothing is installing.
*/
public static Boolean attach(ProgressListener listener) {
Job job;
synchronized (JOB_LOCK) {
job = running;
if (job == null) return null;
if (listener != null) job.listeners.add(listener);
}
return join(job, listener);
}
private static boolean join(Job job, ProgressListener listener) {
try {
if (listener != null) listener.onProgress(job.stage, job.percent);
job.done.await();
return job.ok;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} finally {
if (listener != null) job.listeners.remove(listener);
}
}
private static boolean installOnce(Context context, Release release, ProgressListener listener) {
File archive = new File(context.getCacheDir(), "linuxfs.tar.zst");
try {
if (listener != null) listener.onProgress("Downloading", 0);
@@ -120,7 +200,7 @@ public final class LinuxRuntimeInstaller {
}
if (listener != null) listener.onProgress("Verifying", -1);
String actual = sha256(archive);
String actual = Hashes.sha256(archive);
if (!release.sha256.equalsIgnoreCase(actual)) {
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
return false;
@@ -130,6 +210,8 @@ public final class LinuxRuntimeInstaller {
// runtime that isInstalled() would happily launch.
File root = LinuxRuntime.rootDir(context);
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
recoverInterruptedSwap(root, staging, old);
FileUtils.delete(staging);
if (!staging.mkdirs()) return false;
if (listener != null) listener.onProgress("Extracting", -1);
@@ -139,7 +221,6 @@ public final class LinuxRuntimeInstaller {
}
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
FileUtils.delete(old);
if (root.isDirectory() && !root.renameTo(old)) {
FileUtils.delete(staging);
@@ -164,6 +245,8 @@ public final class LinuxRuntimeInstaller {
}
if (!staging.renameTo(root)) {
File keptTo = new File(staging, USER_DATA);
if (keptTo.isDirectory() && old.isDirectory()) keptTo.renameTo(new File(old, USER_DATA));
if (old.isDirectory()) old.renameTo(root);
return false;
}
@@ -177,8 +260,38 @@ public final class LinuxRuntimeInstaller {
}
}
public static void uninstall(Context context) {
FileUtils.delete(LinuxRuntime.rootDir(context));
private static void recoverInterruptedSwap(File root, File staging, File old) {
File target = root.isDirectory() ? root : old;
File stagedHome = new File(staging, USER_DATA);
File home = new File(target, USER_DATA);
if (target.isDirectory() && stagedHome.isDirectory() && (!home.exists() || isEmptyDir(home))) {
FileUtils.delete(home);
if (stagedHome.renameTo(home)) Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update");
}
if (!root.isDirectory() && old.isDirectory() && old.renameTo(root)) {
Log.w(TAG, "restored the previous runtime after an interrupted update");
}
}
private static boolean isEmptyDir(File dir) {
String[] names = dir.list();
return dir.isDirectory() && names != null && names.length == 0;
}
/** Removes the runtime; returns false without touching it while an install is running. */
public static boolean uninstall(Context context) {
synchronized (JOB_LOCK) {
if (running != null || removing) return false;
removing = true;
}
try {
FileUtils.delete(LinuxRuntime.rootDir(context));
return true;
} finally {
synchronized (JOB_LOCK) {
removing = false;
}
}
}
/**
@@ -193,12 +306,10 @@ public final class LinuxRuntimeInstaller {
new BufferedInputStream(new FileInputStream(archive), 1 << 16));
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
TarArchiveEntry entry;
String base = destination.getCanonicalPath() + File.separator;
while ((entry = tar.getNextTarEntry()) != null) {
File file = new File(destination, entry.getName());
// Refuse anything that would land outside the runtime directory.
if (!(file.getCanonicalPath() + (entry.isDirectory() ? File.separator : "")).startsWith(base)
&& !file.getCanonicalPath().equals(destination.getCanonicalPath())) {
File file = ArchivePaths.inside(destination, entry.getName());
if (file == null) {
Log.w(TAG, "skipping entry outside the rootfs: " + entry.getName());
continue;
}
@@ -215,7 +326,13 @@ public final class LinuxRuntimeInstaller {
} else if (entry.isLink()) {
// A hard link to an earlier entry. Link where the filesystem allows it and
// fall back to a copy, which costs space but always works.
File target = new File(destination, entry.getLinkName());
// The target is checked too: a link to "../../shared_prefs/x" would pull a
// file from outside the rootfs into it.
File target = ArchivePaths.inside(destination, entry.getLinkName());
if (target == null) {
Log.w(TAG, "skipping hard link outside the rootfs: " + entry.getLinkName());
continue;
}
file.delete();
try {
Files.createLink(file.toPath(), target.toPath());
@@ -244,16 +361,4 @@ public final class LinuxRuntimeInstaller {
return false;
}
}
public static String sha256(File file) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
try (InputStream in = new BufferedInputStream(new FileInputStream(file), 1 << 16)) {
byte[] buffer = new byte[1 << 16];
int read;
while ((read = in.read(buffer)) != -1) digest.update(buffer, 0, read);
}
StringBuilder sb = new StringBuilder();
for (byte b : digest.digest()) sb.append(String.format("%02x", b));
return sb.toString();
}
}
@@ -0,0 +1,100 @@
package com.droiddeck.launcher.runtime
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.droiddeck.launcher.MainActivity
import com.droiddeck.launcher.R
/**
* Keeps the process in the foreground while the Linux runtime downloads and unpacks. The runtime
* is several hundred megabytes; without a foreground service Android may kill the app the moment
* the user switches away, and the install starts over from the resumable part file.
*
* The install itself is [LinuxRuntimeInstaller.install], which runs one job per process: the
* screen that asked for it joins the same job to show progress, so it does not matter which of the
* two gets there first.
*/
class RuntimeInstallService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val release = intent?.let(::releaseFrom)
startForeground(NOTIFICATION_ID, notification("Starting…", -1))
if (release == null) {
stopSelf(startId)
return START_NOT_STICKY
}
Thread({
val manager = getSystemService(NotificationManager::class.java)
var shown = Int.MIN_VALUE
LinuxRuntimeInstaller.install(applicationContext, release) { stage, percent ->
// Every percent at most once: a notification per read would flood the system.
if (percent != shown) {
shown = percent
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
}
}
@Suppress("DEPRECATION")
stopForeground(true)
stopSelf(startId)
}, "runtime-install").start()
return START_NOT_STICKY
}
private fun notification(stage: String, percent: Int): Notification {
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Runtime install",
NotificationManager.IMPORTANCE_LOW).apply {
description = "Shows while the Linux runtime downloads and installs"
setShowBadge(false)
setSound(null, null)
enableVibration(false)
})
val open = PendingIntent.getActivity(this, 0,
Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE)
return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle("Installing the Linux runtime")
.setContentText(stage)
.setProgress(100, percent.coerceIn(0, 100), percent < 0)
.setContentIntent(open)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setShowWhen(false)
.build()
}
companion object {
private const val CHANNEL_ID = "runtime-install"
private const val NOTIFICATION_ID = 2
private const val EXTRA_VERSION = "version"
private const val EXTRA_URL = "url"
private const val EXTRA_SHA256 = "sha256"
private const val EXTRA_SIZE = "size"
/** Starts the install of [release] in the foreground; a running install is joined instead. */
fun start(context: Context, release: LinuxRuntimeInstaller.Release) {
val intent = Intent(context, RuntimeInstallService::class.java)
.putExtra(EXTRA_VERSION, release.version)
.putExtra(EXTRA_URL, release.url)
.putExtra(EXTRA_SHA256, release.sha256)
.putExtra(EXTRA_SIZE, release.size)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
}
private fun releaseFrom(intent: Intent): LinuxRuntimeInstaller.Release? {
val version = intent.getStringExtra(EXTRA_VERSION) ?: return null
val url = intent.getStringExtra(EXTRA_URL) ?: return null
val sha256 = intent.getStringExtra(EXTRA_SHA256) ?: return null
return LinuxRuntimeInstaller.Release(version, url, sha256, intent.getLongExtra(EXTRA_SIZE, 0L))
}
}
}
@@ -0,0 +1,656 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.Hashes
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdInputStream
import com.github.luben.zstd.ZstdOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
/**
* FEX, DXVK and VKD3D-Proton per Proton, for the Linux Steam client.
*
* Every Proton the client runs games with keeps its own copy of these three inside its tree. This
* lists them, stores packages (.wcp: tar + zstd with a profile.json) downloaded from the Nightlies
* "-Linux" releases or imported, swaps one into a Proton, keeps the Proton's shipped files as
* "original bundles" - one per Proton build, so a Steam update adds a new one instead of replacing
* the last - restores those, and deletes stored packages.
*
* Where a Proton reads each component (its own `proton` script, ARM64 host):
* DXVK files/lib/wine/dxvk/{aarch64,i386}-windows -> the prefix's system32 / syswow64
* VKD3D files/lib/wine/vkd3d-proton/{aarch64,i386}-windows -> the same, on every launch
* FEX files/lib/wine/aarch64-windows/lib{arm64ec,wow64}fex.dll
* files/lib/wine/aarch64-unix/lib{arm64ec,wow64}fex.so (FEX 2607 and newer)
* Proton copies DXVK and VKD3D into the prefix on every normal launch, so a swap applies the next
* time a game starts. A swap into a Proton a running game is using waits until that game exits.
*
* Same formats and data layout as the Decky "Components Manager" plugin, whose data is taken over
* once on first use.
*/
object ComponentsManager {
private const val TAG = "Components"
private const val NIGHTLIES = "The412Banner/Nightlies"
/** Release tag -> component. Only the Linux repacks: the Android releases carry bionic unixlibs. */
private val RELEASES = linkedMapOf(
"FexCore-Linux" to "fex",
"Dxvk-Linux" to "dxvk",
"Dxvk-arm64ec-Linux" to "dxvk",
"Dxvk-gplasync-Linux" to "dxvk",
"Vkd3d-proton-Linux" to "vkd3d",
)
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
private const val WINE = "files/lib/wine"
private val FEX_FILES = listOf(
"$WINE/aarch64-windows/libarm64ecfex.dll",
"$WINE/aarch64-windows/libwow64fex.dll",
"$WINE/aarch64-unix/libarm64ecfex.so",
"$WINE/aarch64-unix/libwow64fex.so",
)
private val COMP_DIR = mapOf("dxvk" to "$WINE/dxvk", "vkd3d" to "$WINE/vkd3d-proton")
/** The folders a Proton reads on ARM64. */
private val PE_ARCHES = listOf("aarch64-windows", "i386-windows")
/**
* The DLLs that ARE the component. A swap clears exactly these before unpacking, so no file of
* the previous version is left mixed in; anything else a Proton keeps beside them - GE's
* openvr_api_dxvk.dll, which its launcher copies into every prefix and aborts without - stays.
*/
private val COMP_DLLS = mapOf(
"dxvk" to setOf("d3d8.dll", "d3d9.dll", "d3d10.dll", "d3d10_1.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll"),
"vkd3d" to setOf("d3d12.dll", "d3d12core.dll"),
)
private const val PLUGIN_DATA = "root/homebrew/data/decky-components-manager"
data class Proton(val id: String, val name: String, val dir: File, val guestPath: String, val version: String, val valve: Boolean)
data class Component(val detected: String, val detail: String, val inUse: String, val activeFile: String?, val queued: String?)
data class Original(val comp: String, val protonVersion: String, val label: String, val size: Long)
data class Package(val file: String, val comp: String, val version: String, val description: String, val size: Long)
data class CatalogItem(val file: String, val comp: String, val release: String, val url: String, val size: Long, val digest: String)
data class ProtonView(
val proton: Proton, val components: Map<String, Component>, val originals: List<Original>, val inUseByGame: Boolean,
/** When a launch last had to put this Proton's chosen files back (epoch seconds), or 0. */
val reappliedAt: Long = 0,
)
data class Snapshot(val protons: List<ProtonView>, val packages: List<Package>)
data class Catalog(val items: List<CatalogItem>, val fetchedAt: Long)
private val lock = Any()
// ------------------------------------------------------------------ paths
private fun root(context: Context) = LinuxRuntime.rootDir(context)
private fun steam(context: Context) = File(root(context), "root/.local/share/Steam")
private fun host(context: Context, guest: String) = File(root(context), guest.removePrefix("/"))
private fun dataDir(context: Context) = File(context.filesDir, "components").apply { mkdirs() }
private fun packagesDir(context: Context) = File(dataDir(context), "packages").apply { mkdirs() }
private fun originalsDir(context: Context) = File(dataDir(context), "originals").apply { mkdirs() }
private fun stateFile(context: Context) = File(dataDir(context), "state.json")
private fun catalogFile(context: Context) = File(dataDir(context), "catalog.json")
/**
* Inside the Linux runtime, read by the Proton launch wrappers (bannerlator-steam-compat's
* bl_components) before every game launch: desired.tsv + an unpacked copy of each package in use.
*/
private const val LAUNCH_DIR = "root/.local/share/bannerlator-components"
private fun launchDir(context: Context) = File(root(context), LAUNCH_DIR)
fun safeName(s: String): String = s.replace(Regex("[^A-Za-z0-9._+-]+"), "_").trim('_').ifEmpty { "unnamed" }
// ------------------------------------------------------------------ state
private fun loadState(context: Context): JSONObject =
runCatching { JSONObject(stateFile(context).readText()) }.getOrElse { JSONObject() }.apply {
if (!has("active")) put("active", JSONObject())
if (!has("queued")) put("queued", JSONObject())
}
private fun saveState(context: Context, state: JSONObject) {
val f = stateFile(context)
val tmp = File(f.parentFile, f.name + ".tmp")
tmp.writeText(state.toString(2))
tmp.renameTo(f)
// Every change of choice reaches the launch wrappers at once.
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
}
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
/** Takes over the Decky plugin's packages, originals and swap records, once. */
private fun migratePlugin(context: Context) {
val marker = File(dataDir(context), ".plugin-imported")
if (marker.isFile) return
val plugin = File(root(context), PLUGIN_DATA)
if (plugin.isDirectory) {
runCatching {
File(plugin, "packages").listFiles()?.forEach { f ->
if (f.isFile && f.name.endsWith(".wcp")) {
val dst = File(packagesDir(context), f.name)
if (!dst.exists()) f.copyTo(dst)
}
}
val originals = File(plugin, "originals")
if (originals.isDirectory) originals.copyRecursively(originalsDir(context), overwrite = false)
val ps = File(plugin, "state.json")
if (ps.isFile && !stateFile(context).isFile) ps.copyTo(stateFile(context))
Log.i(TAG, "took over the Decky plugin's data from $plugin")
}.onFailure { Log.w(TAG, "plugin data import", it) }
}
marker.writeText("1\n")
}
// ------------------------------------------------------------------ Protons
private fun libraryRoots(context: Context): List<File> {
val roots = mutableListOf(steam(context))
val vdf = File(steam(context), "steamapps/libraryfolders.vdf")
runCatching {
Regex("\"path\"\\s+\"([^\"]+)\"").findAll(vdf.readText()).forEach {
val h = host(context, it.groupValues[1])
if (roots.none { r -> r.canonicalPath == h.canonicalPath }) roots.add(h)
}
}
return roots
}
private fun displayName(dir: File): String = runCatching {
Regex("\"display_name\"\\s+\"([^\"]+)\"").find(File(dir, "compatibilitytool.vdf").readText())?.groupValues?.get(1)
}.getOrNull() ?: dir.name
private fun protonVersion(dir: File): String = runCatching {
val parts = File(dir, "version").useLines { it.firstOrNull() ?: "" }.trim().split(Regex("\\s+"))
if (parts.size > 1) parts[1] else parts.firstOrNull()?.ifEmpty { null } ?: "unknown"
}.getOrDefault("unknown")
/** Every Proton tree with a Wine inside. Launch wrappers pointing at another Proton are left out. */
fun protons(context: Context): List<Proton> {
val found = LinkedHashMap<String, Proton>()
val bases = listOf(File(steam(context), "compatibilitytools.d") to false) +
libraryRoots(context).map { File(it, "steamapps/common") to true }
// Not canonical: /data/user/0 is a link to /data/data on many devices, and the guest path is
// what is left after removing the rootfs prefix exactly as the paths were built.
val rootPath = root(context).absolutePath.trimEnd('/')
for ((base, valve) in bases) {
val entries = base.listFiles()?.sortedBy { it.name } ?: continue
for (dir in entries) {
if (!File(dir, WINE).isDirectory || !File(dir, "proton").isFile) continue
val real = runCatching { dir.canonicalPath }.getOrDefault(dir.path)
if (found.containsKey(real)) continue
val guest = if (dir.absolutePath.startsWith(rootPath)) dir.absolutePath.removePrefix(rootPath) else dir.absolutePath
found[real] = Proton(safeName(dir.name), displayName(dir), dir, guest, protonVersion(dir), valve)
}
}
return found.values.toList()
}
private fun proton(context: Context, id: String) = protons(context).firstOrNull { it.id == id }
?: throw IllegalStateException("No Proton with id $id")
/**
* Is anything running on this Proton right now - a game, or the client's own start-up runs,
* whose Wine processes can outlive them? Swaps wait while it is. Read from the command lines.
*/
fun inUse(proton: Proton): Boolean = anyProcess(proton) { needle, text -> text.contains(needle + "proton ") || text.contains(needle + "files/bin") }
/**
* Is a game running on this Proton? Only a launch runs proton with the verb waitforexitandrun
* (Proton's own script stays up until the game exits); the client's start-up runs do not.
*/
fun gameRunning(proton: Proton): Boolean = anyProcess(proton) { needle, text -> text.contains(needle + "proton waitforexitandrun") }
private fun anyProcess(proton: Proton, match: (String, String) -> Boolean): Boolean {
val needle = proton.guestPath.trimEnd('/') + "/"
val procs = File("/proc").listFiles() ?: return false
for (p in procs) {
if (!p.name.all(Char::isDigit)) continue
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
if (cmd.isEmpty()) continue
if (match(needle, String(cmd).replace('\u0000', ' '))) return true
}
return false
}
// ------------------------------------------------------------------ component files
private fun readVersionFile(f: File): String = runCatching {
val text = f.readText().trim()
Regex("\\(([^)]+)\\)").find(text)?.groupValues?.get(1) ?: text.split(Regex("\\s+")).last()
}.getOrDefault("")
private fun fexVersion(dir: File): String {
val dll = File(dir, FEX_FILES[0])
if (!dll.isFile) return ""
val text = runCatching { String(dll.readBytes(), Charsets.ISO_8859_1) }.getOrDefault("")
return Regex("FEX-\\d{4}(?:\\.\\d+)?(?:-\\d+-g[0-9a-f]{6,})?").findAll(text).map { it.value }.maxByOrNull { it.length }
?: "FEX (build without a version name)"
}
private fun compFiles(dir: File, comp: String): List<String> {
if (comp == "fex") return FEX_FILES.filter { File(dir, it).isFile }
val base = File(dir, COMP_DIR.getValue(comp))
return base.walkTopDown().filter { it.isFile }.map { it.relativeTo(dir).path }.sorted().toList()
}
private fun owned(comp: String, rel: String) = comp == "fex" || PE_ARCHES.any { "/$it/" in rel }
private fun fingerprint(dir: File, comp: String): Map<String, String> =
compFiles(dir, comp).filter { owned(comp, it) }.associateWith { Hashes.sha256(File(dir, it)) }
// ------------------------------------------------------------------ packages
private fun normalize(name: String) = name.removePrefix("./").trimStart('/')
private inline fun <T> readWcp(f: File, block: (TarArchiveInputStream) -> T): T =
TarArchiveInputStream(ZstdInputStream(BufferedInputStream(FileInputStream(f), 1 shl 16))).use(block)
private fun readProfile(f: File): JSONObject = readWcp(f) { tar ->
while (true) {
val e = tar.nextTarEntry ?: break
if (!e.isDirectory && normalize(e.name) == "profile.json") return@readWcp JSONObject(tar.readBytes().decodeToString())
}
throw IllegalArgumentException("no profile.json in ${f.name}")
}
private fun packageInfo(f: File): Package {
val prof = readProfile(f)
val comp = TYPES[prof.optString("type")] ?: throw IllegalArgumentException("${f.name} is not a Linux component package (type ${prof.optString("type")})")
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
}
fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
?.filter { it.isFile && it.name.endsWith(".wcp") }?.sortedBy { it.name }
?.mapNotNull { f -> runCatching { packageInfo(f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
?: emptyList()
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
private fun installFiles(context: Context, dir: File, comp: String, wcp: File): Map<String, String> {
val staged = File(dataDir(context), "staging-${System.nanoTime()}")
try {
readWcp(wcp) { tar ->
while (true) {
val e = tar.nextTarEntry ?: break
val rel = normalize(e.name)
if (e.isDirectory || !rel.startsWith("files/")) continue
require(rel.split('/').none { it == ".." }) { "unsafe path $rel" }
val out = File(staged, rel)
out.parentFile?.mkdirs()
FileOutputStream(out).use { tar.copyTo(it) }
}
}
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
COMP_DIR[comp]?.let { compDir ->
for (arch in PE_ARCHES) {
val target = File(dir, "$compDir/$arch")
if (!File(staged, "$compDir/$arch").isDirectory || !target.isDirectory) continue
target.listFiles()?.filter { it.name.lowercase() in COMP_DLLS.getValue(comp) }?.forEach { it.delete() }
}
}
val hashes = LinkedHashMap<String, String>()
File(staged, "files").walkTopDown().filter { it.isFile }.forEach { src ->
val rel = src.relativeTo(staged).path
val dst = File(dir, rel)
dst.parentFile?.mkdirs()
val tmp = File(dst.parentFile, dst.name + ".dcm-new")
src.copyTo(tmp, overwrite = true)
if (rel.endsWith(".so")) tmp.setExecutable(true, false)
tmp.setReadable(true, false)
if (!tmp.renameTo(dst)) { dst.delete(); check(tmp.renameTo(dst)) { "could not place $rel" } }
hashes[rel] = Hashes.sha256(dst)
}
return hashes
} finally {
staged.deleteRecursively()
}
}
private fun writeWcp(dest: File, profile: JSONObject, dir: File, rels: List<String>) {
val tmp = File(dest.parentFile, dest.name + ".part")
TarArchiveOutputStream(ZstdOutputStream(BufferedOutputStream(FileOutputStream(tmp), 1 shl 16), 9)).use { tar ->
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX)
val bytes = profile.toString(2).toByteArray()
tar.putArchiveEntry(TarArchiveEntry("./profile.json").apply { size = bytes.size.toLong() })
tar.write(bytes); tar.closeArchiveEntry()
for (rel in rels) {
val f = File(dir, rel)
tar.putArchiveEntry(TarArchiveEntry(f, "./$rel"))
FileInputStream(f).use { it.copyTo(tar) }
tar.closeArchiveEntry()
}
}
tmp.renameTo(dest)
}
// ------------------------------------------------------------------ originals
private fun originalFile(context: Context, p: Proton, comp: String) =
File(originalsDir(context), "${p.id}/${safeName(p.version)}/$comp.wcp").apply { parentFile?.mkdirs() }
fun originals(context: Context, protonId: String): List<Original> {
val base = File(originalsDir(context), protonId)
val versions = base.listFiles()?.filter { it.isDirectory }?.sortedByDescending { it.lastModified() } ?: return emptyList()
return versions.flatMap { v ->
COMPONENTS.mapNotNull { comp ->
val f = File(v, "$comp.wcp")
if (!f.isFile) null else Original(comp, v.name, runCatching { readProfile(f).optString("description") }.getOrDefault(""), f.length())
}
}
}
/**
* Saves a Proton's shipped files for this component before they are first replaced in this
* Proton build. A build already swapped into is not saved again: its files are ours.
*/
private fun ensureOriginal(context: Context, p: Proton, comp: String, state: JSONObject) {
val dest = originalFile(context, p, comp)
if (dest.isFile) return
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
if (active != null && active.optString("protonVersion") == p.version) return
val rels = compFiles(p.dir, comp)
if (rels.isEmpty()) return
val current = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
val profile = JSONObject()
.put("type", TYPE_OF.getValue(comp))
.put("versionName", "original-${p.version}")
.put("versionCode", 0)
.put("description", "Original · ${p.name} · ${p.version} · ${LABEL.getValue(comp)} $current".trim())
.put("files", JSONArray(rels.map { JSONObject().put("source", it).put("target", "\${proton}/$it") }))
writeWcp(dest, profile, p.dir, rels)
Log.i(TAG, "saved original $comp of ${p.name} ${p.version}")
}
/** Saves the originals of every Proton build not seen yet (first open, and after a Steam update). */
fun snapshotAll(context: Context) = synchronized(lock) {
migratePlugin(context)
val state = loadState(context)
for (p in protons(context)) for (comp in COMPONENTS) {
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
}
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
}
// ------------------------------------------------------------------ view
fun snapshot(context: Context): Snapshot = synchronized(lock) {
migratePlugin(context)
val state = loadState(context)
val reapplied = HashMap<String, Long>()
runCatching {
File(launchDir(context), "reapplied.log").forEachLine { line ->
val parts = line.split('\t')
if (parts.size >= 2) parts[0].toLongOrNull()?.let { reapplied[parts[1]] = maxOf(reapplied[parts[1]] ?: 0, it) }
}
}
val views = protons(context).map { p ->
val comps = COMPONENTS.associateWith { comp ->
val detected = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
val detail = if (comp == "fex") (if (File(p.dir, FEX_FILES[2]).isFile) "with Linux helpers" else "DLLs only") else ""
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
val inUseLabel = when {
active == null -> "Original"
active.optString("protonVersion") != p.version -> "Original (Proton updated since the last swap)"
else -> {
val want = active.optJSONObject("files") ?: JSONObject()
val fp = fingerprint(p.dir, comp)
if (want.keys().asSequence().all { fp[it] == want.optString(it) }) active.optString("label", active.optString("file"))
else "Changed outside Components"
}
}
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
Component(
detected.ifEmpty { "not present" }, detail, inUseLabel,
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
q?.optString("label"),
)
}
ProtonView(p, comps, originals(context, p.id), gameRunning(p), reapplied[p.dir.name] ?: 0)
}
Snapshot(views, packages(context))
}
// ------------------------------------------------------------------ launch-time enforcement
/**
* Writes what each Proton should be using for the launch wrappers: desired.tsv, one line per
* file (tool dir, Proton build, component, file, sha256, source copy), and an unpacked copy of
* every package or older-build original in use to copy from. Rebuilt whole after every change, so
* a restored or deleted choice simply stops being enforced. The Proton's own current-build
* originals are not listed: the wrappers also give Steam's probe runs their own prefix, which is
* what overwrote files in the first place.
*/
private fun syncLaunchState(context: Context, state: JSONObject) {
val dir = launchDir(context)
val store = File(dir, "store").apply { mkdirs() }
val all = protons(context)
val lines = StringBuilder()
val keep = HashSet<String>()
val active = state.sub("active")
for (pid in active.keys()) {
val p = all.firstOrNull { it.id == pid } ?: continue
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) {
val a = comps.optJSONObject(comp) ?: continue
if (a.optString("protonVersion") != p.version) continue
val file = a.optString("file")
val (key, wcp) = if (file.startsWith("original ")) {
val v = file.removePrefix("original ")
"original-$pid-${safeName(v)}-$comp" to File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp")
} else safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
if (!wcp.isFile) continue
val unpacked = File(store, key)
if (!File(unpacked, ".complete").isFile) {
unpacked.deleteRecursively()
readWcp(wcp) { tar ->
while (true) {
val e = tar.nextTarEntry ?: break
val rel = normalize(e.name)
if (e.isDirectory || !rel.startsWith("files/") || rel.split('/').any { it == ".." }) continue
val out = File(unpacked, rel)
out.parentFile?.mkdirs()
FileOutputStream(out).use { tar.copyTo(it) }
}
}
File(unpacked, ".complete").writeText("1\n")
}
keep += key
val files = a.optJSONObject("files") ?: continue
for (rel in files.keys()) {
val src = File(unpacked, rel)
if (!src.isFile) continue
val guestSrc = "/" + src.absolutePath.removePrefix(root(context).absolutePath.trimEnd('/')).trimStart('/')
lines.append(p.dir.name).append('\t').append(p.version).append('\t').append(comp).append('\t')
.append(rel).append('\t').append(files.optString(rel)).append('\t').append(guestSrc).append('\n')
}
}
}
store.listFiles()?.filter { it.isDirectory && it.name !in keep }?.forEach { it.deleteRecursively() }
val list = File(dir, "desired.tsv")
val tmp = File(dir, "desired.tsv.tmp")
tmp.writeText(lines.toString())
tmp.renameTo(list)
}
// ------------------------------------------------------------------ actions
/** Applies a package now, or queues it when a game is running on that Proton. Returns what happened. */
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
val p = proton(context, protonId)
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(wcp)
val state = loadState(context)
if (inUse(p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
saveState(context, state)
return "${LABEL[info.comp]} ${info.version} goes into ${p.name} when the game running on it closes."
}
applyPackage(context, p, info, wcp, state)
state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
saveState(context, state)
"${LABEL[info.comp]} ${info.version} is now in ${p.name}. It applies the next time a game starts."
}
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
ensureOriginal(context, p, info.comp, state)
val hashes = installFiles(context, p.dir, info.comp, wcp)
state.sub("active").sub(p.id).put(info.comp, JSONObject()
.put("file", wcp.name).put("label", info.version).put("protonVersion", p.version)
.put("files", JSONObject(hashes.filterKeys { owned(info.comp, it) } as Map<*, *>))
.put("at", System.currentTimeMillis() / 1000))
Log.i(TAG, "swapped ${info.comp} ${info.version} into ${p.name} ${p.version}")
}
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
val p = proton(context, protonId)
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(wcp.isFile) { "That original bundle is not stored" }
val state = loadState(context)
if (inUse(p)) {
state.sub("queued").sub(p.id).put(comp, JSONObject().put("kind", "original").put("protonVersion", protonVersion).put("label", "Original $protonVersion"))
saveState(context, state)
return "${LABEL[comp]} of ${p.name} goes back to its original when the game running on it closes."
}
applyOriginal(context, p, comp, protonVersion, wcp, state)
state.sub("queued").optJSONObject(p.id)?.remove(comp)
saveState(context, state)
"${LABEL[comp]} of ${p.name} restored from its $protonVersion original."
}
private fun applyOriginal(context: Context, p: Proton, comp: String, protonVersion: String, wcp: File, state: JSONObject) {
val current = protonVersion == safeName(p.version)
if (!current) ensureOriginal(context, p, comp, state)
installFiles(context, p.dir, comp, wcp)
val active = state.sub("active").sub(p.id)
if (current) active.remove(comp)
else active.put(comp, JSONObject().put("file", "original $protonVersion").put("label", "Original from $protonVersion")
.put("protonVersion", p.version).put("files", JSONObject(fingerprint(p.dir, comp) as Map<*, *>)).put("at", System.currentTimeMillis() / 1000))
}
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
fun applyQueued(context: Context): List<String> = synchronized(lock) {
val state = loadState(context)
val queued = state.sub("queued")
if (queued.length() == 0) return emptyList()
val done = mutableListOf<String>()
val all = protons(context)
for (pid in queued.keys().asSequence().toList()) {
val p = all.firstOrNull { it.id == pid } ?: run { queued.remove(pid); null } ?: continue
if (inUse(p)) continue
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val q = comps.optJSONObject(comp) ?: continue
runCatching {
if (q.optString("kind") == "original") {
val v = q.optString("protonVersion")
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
} else {
val wcp = File(packagesDir(context), q.optString("file"))
applyPackage(context, p, packageInfo(wcp), wcp, state)
}
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
comps.remove(comp)
}
if (comps.length() == 0) queued.remove(pid)
}
saveState(context, state)
done
}
fun cancelQueued(context: Context, protonId: String, comp: String) = synchronized(lock) {
val state = loadState(context)
state.sub("queued").optJSONObject(protonId)?.remove(comp)
saveState(context, state)
}
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val active = state.sub("active")
for (pid in active.keys()) {
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { "$name is in use in $pid. Swap that Proton to something else first." }
}
val f = File(packagesDir(context), name)
check(f.isFile) { "$name is not stored" }
f.delete()
"Deleted $name."
}
fun deleteOriginal(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
val p = proton(context, protonId)
check(safeName(p.version) != protonVersion) { "The installed build's original is kept: it is the way back." }
val f = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(f.isFile) { "Not stored" }
f.delete()
f.parentFile?.takeIf { it.listFiles().isNullOrEmpty() }?.delete()
"Deleted the $protonVersion original of ${LABEL[comp]}."
}
/** Imports a -linux .wcp from anywhere the app can read (the file picker hands over a copy). */
fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) {
val info = packageInfo(source)
val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" })
source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest)
info.copy(file = dest.name)
}
// ------------------------------------------------------------------ catalog
/** The Nightlies listing: cached on disk, fetched again only when [force] (the refresh button). */
fun catalog(context: Context, force: Boolean): Catalog {
val cache = catalogFile(context)
if (!force && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) }
if (!force) return Catalog(emptyList(), 0)
val items = JSONArray()
for ((tag, comp) in RELEASES) {
val body = Downloader.downloadString("https://api.github.com/repos/$NIGHTLIES/releases/tags/$tag") ?: continue
val assets = runCatching { JSONObject(body).optJSONArray("assets") }.getOrNull() ?: continue
for (i in 0 until assets.length()) {
val a = assets.getJSONObject(i)
val name = a.optString("name")
if (!name.endsWith(".wcp")) continue
// Only packages GitHub has a sha256 for are offered: the download is checked against it.
if (!Hashes.isGithubSha256(a.optString("digest"))) continue
items.put(JSONObject().put("file", name).put("comp", comp).put("release", tag)
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
}
}
val out = JSONObject().put("items", items).put("fetchedAt", System.currentTimeMillis() / 1000)
val tmp = File(cache.parentFile, cache.name + ".tmp")
tmp.writeText(out.toString()); tmp.renameTo(cache)
return parseCatalog(out)
}
private fun parseCatalog(o: JSONObject): Catalog {
val arr = o.optJSONArray("items") ?: JSONArray()
val items = (0 until arr.length()).map { arr.getJSONObject(it) }.map {
CatalogItem(it.optString("file"), it.optString("comp"), it.optString("release"), it.optString("url"), it.optLong("size"), it.optString("digest"))
}.sortedWith(compareBy({ it.comp }, { it.release }, { it.file }))
return Catalog(items, o.optLong("fetchedAt"))
}
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { "Downloads come only from the Nightlies releases" }
require(Hashes.isGithubSha256(item.digest)) { "This package list predates checksums - refresh it and try again" }
val dest = File(packagesDir(context), safeName(item.file))
val part = File(dest.parentFile, dest.name + ".part")
part.delete()
check(Downloader.downloadFile(item.url, part, false) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { "Download failed" }
if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error("Checksum mismatch") }
val info = runCatching { packageInfo(part) }.getOrElse { part.delete(); throw it }
synchronized(lock) { part.renameTo(dest) }
return info.copy(file = dest.name)
}
}
@@ -17,15 +17,20 @@ import java.nio.charset.StandardCharsets
* progress, and lifting that out is the difference between "starting the Steam client" for three
* minutes and a percentage that moves.
*/
class LoadingState(context: Context) {
class LoadingState(context: Context, steam: Boolean = true) {
var visible by mutableStateOf(true)
var step by mutableStateOf("Starting the session…")
var percent by mutableIntStateOf(-1)
var elapsed by mutableStateOf("")
var hint by mutableStateOf("")
var ended by mutableStateOf(false)
/** The technical side of an ended session (exit status, log path), under the advice in [step]. */
var endedDetail by mutableStateOf<String?>(null)
private val hints = context.resources.getStringArray(com.droiddeck.launcher.R.array.loading_hints)
// The desktop and the emulators get their own: the Steam ones talk about Steam.
private val hints = context.resources.getStringArray(
if (steam) com.droiddeck.launcher.R.array.loading_hints else com.droiddeck.launcher.R.array.loading_hints_desktop,
)
private val startedAt = SystemClock.elapsedRealtime()
/** Once a second: the clock and the hint. */
@@ -35,10 +40,11 @@ class LoadingState(context: Context) {
hint = hints[((seconds / 8) % hints.size).toInt()]
}
fun showEnded(message: String) {
fun showEnded(message: String, detail: String? = null) {
visible = true
ended = true
step = message
endedDetail = detail
}
/** Re-reads the end of the log and updates the line and the bar. */
@@ -81,7 +81,7 @@ class PerfHud(context: Context) {
fun stop() {
running = false
WaylandCompositor.setGameListener(null)
WaylandCompositor.clearGameListener(listener)
text = ""
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.Hashes
import android.content.Context
import android.os.StatFs
import android.util.Log
@@ -7,7 +8,6 @@ import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.security.MessageDigest
import org.json.JSONArray
/** Immediate download and installation of the optional ARM64 Proton builds. */
@@ -21,7 +21,9 @@ object ProtonExtras {
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
private data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long)
/** [sha256] from GitHub's asset digest; [sha512] the URL of a checksum file published beside it. */
private data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null)
val tools = listOf(
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
@@ -99,14 +101,24 @@ object ProtonExtras {
return "Download was incomplete; the partial file is kept for a resumable retry"
}
asset.sha512?.let { checksumUrl ->
onProgress("Verifying download", -1)
val checksumText = Downloader.downloadString(checksumUrl)
val expected = checksumText?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
if (expected != null && !expected.equals(sha512(archive), ignoreCase = true)) {
archive.delete()
return "Checksum mismatch; the download was deleted"
// One checksum has to be found and has to match: GitHub's sha256 digest, else the
// release's own sha512 file. A download neither vouches for is not installed.
onProgress("Verifying download", -1)
val verified = when {
asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true)
asset.sha512 != null -> {
val expected = Downloader.downloadString(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
?: return "Could not read the release checksum; try again"
expected.equals(Hashes.sha512(archive), ignoreCase = true)
}
else -> {
archive.delete()
return "${tool.name} ${asset.tag} publishes no checksum; nothing was installed"
}
}
if (!verified) {
archive.delete()
return "Checksum mismatch; the download was deleted"
}
if (SessionState.running) return "A session started during the download; stop it before installing compatibility tools"
@@ -170,6 +182,7 @@ object ProtonExtras {
release.optString("tag_name"), name,
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
archive.optLong("size", 0L),
Hashes.githubSha256(archive.optString("digest")),
)
}
null
@@ -179,19 +192,6 @@ object ProtonExtras {
}
}
private fun sha512(file: File): String {
val digest = MessageDigest.getInstance("SHA-512")
file.inputStream().buffered().use { input ->
val buffer = ByteArray(4 * 1024 * 1024)
while (true) {
val read = input.read(buffer)
if (read < 0) break
digest.update(buffer, 0, read)
}
}
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
}
private fun requestLines(context: Context): List<String> =
FileUtils.readString(requests(context))?.lines()?.filter { it.isNotBlank() } ?: emptyList()
}
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.session
import android.app.ActivityManager
import android.content.Context
import android.util.Log
import android.widget.Toast
/**
* Other apps on the device that sign into the user's Steam account with their own client. Steam
@@ -34,31 +33,21 @@ object RivalClients {
fun name(pkg: String): String = if (pkg == "com.xiaoji.egggame") "GameHub" else pkg
/**
* Stop the installed rivals' background processes before the client starts, and say so. A
* rival in the foreground survives this, so the wording covers that case too. Call on the main
* thread; the Toast is shown from here.
* Stop the installed rivals' background processes before the client starts. A rival in the
* foreground survives this. The activity service call and its log messages are unchanged.
*/
fun stopBeforeSession(context: Context) {
val rivals = installed(context)
if (rivals.isEmpty()) return
val who = name(rivals[0])
Log.w(TAG, "competing Steam client installed: $rivals")
var asked = false
try {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
if (am != null) {
for (pkg in rivals) am.killBackgroundProcesses(pkg)
asked = true
Log.i(TAG, "asked Android to stop background processes of $rivals")
}
} catch (t: Throwable) {
Log.w(TAG, "could not stop competing Steam clients", t)
}
Toast.makeText(
context,
if (asked) "Closed $who in the background - it signs into your Steam account."
else "If $who is open, close it first - it signs into your Steam account and will sign this client out.",
Toast.LENGTH_LONG,
).show()
}
}
@@ -148,8 +148,161 @@ object SessionFiles {
staged.delete()
Log.e(TAG, "could not write ld.so.preload")
}
val startupMovieDir = File(root, "root/.local/share/Steam/config/uioverrides/movies")
// Steam looks up these conventional names in its user override directory. Keep both
// variants populated because the startup movie name differs across Steam clients.
val bigPictureMovieInstalled = stageStartupMovie(
context,
startupMovieDir,
"bigpicture_startup.webm",
)
stageStartupMovie(context, startupMovieDir, "steam_os_startup.webm")
if (bigPictureMovieInstalled) {
ensureStartupMovieDefault(File(root, "root/.local/share/Steam/config/config.vdf"))
}
}
private fun stageStartupMovie(context: Context, directory: File, name: String): Boolean {
val movie = File(directory, name)
val staged = File(directory, "$name.staged")
var installed = false
try {
directory.mkdirs()
context.assets.open("steam-startup/droiddeck-startup.webm").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setReadable(true, false) && staged.renameTo(movie)
} catch (e: Exception) {
Log.w(TAG, "could not stage Steam startup movie $name", e)
} finally {
if (!installed) staged.delete()
}
if (!installed) Log.e(TAG, "Steam startup movie $name NOT staged")
return installed
}
private data class VdfBlock(val keyStart: Int, val open: Int, val close: Int)
private fun ensureStartupMovieDefault(config: File) {
val path = "/uioverrides/movies/bigpicture_startup.webm"
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config for startup movie", it)
return
} else ""
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val movie = findObject(text, "StartupMovie", 0, text.length)
if (movie != null) {
val block = text.substring(movie.keyStart, movie.close + 1)
val selectedId = scalar(block, "MovieID")
val selectedPath = scalar(block, "LocalPath")
if (selectedPath == path) {
Log.i(TAG, "Steam startup movie is set to DroidDeck")
return
}
val legacyDefault = selectedId == "0" && selectedPath == legacyPath
val hasExplicitSelection =
(!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()
if (!legacyDefault && hasExplicitSelection) {
Log.i(TAG, "Steam startup movie selection preserved")
return
}
val updated = setScalar(block, "MovieID", "0", newline)
.let { setScalar(it, "LocalPath", path, newline) }
text = text.replaceRange(movie.keyStart, movie.close + 1, updated)
} else {
val steam = findSteamBlock(text)
if (steam == null) {
if (text.isNotBlank()) {
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
return
}
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
val section = startupMovieSection("\t\t\t\t", path, newline)
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
val section = startupMovieSection(indent + "\t", path, newline)
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
}
}
val staged = File(config.parentFile, config.name + ".staged")
try {
config.parentFile?.mkdirs()
staged.writeText(text)
if (!staged.renameTo(config)) {
staged.delete()
Log.e(TAG, "could not write Steam startup movie selection")
} else {
Log.i(TAG, "Steam startup movie default selected")
}
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write Steam startup movie selection", e)
}
}
private fun findSteamBlock(text: String): VdfBlock? {
val install = findObject(text, "InstallConfigStore", 0, text.length) ?: return null
val software = findObject(text, "Software", install.open + 1, install.close) ?: return null
val valve = findObject(text, "Valve", software.open + 1, software.close) ?: return null
return findObject(text, "Steam", valve.open + 1, valve.close)
}
private fun findObject(text: String, key: String, start: Int, end: Int): VdfBlock? {
val pattern = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]*(?:\\r?\\n[\\t ]*)?\\{")
val match = pattern.find(text, start)?.takeIf { it.range.first < end && it.range.last < end } ?: return null
val open = text.indexOf('{', match.range.first).takeIf { it < end } ?: return null
var depth = 0
var quoted = false
var escaped = false
for (index in open until end) {
val char = text[index]
if (quoted) {
if (escaped) escaped = false
else if (char == '\\') escaped = true
else if (char == '\"') quoted = false
} else {
when (char) {
'\"' -> quoted = true
'{' -> depth++
'}' -> {
depth--
if (depth == 0) return VdfBlock(match.range.first, open, index)
}
}
}
}
return null
}
private fun scalar(block: String, key: String): String? {
val pattern = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]+\"([^\"\\r\\n]*)\"")
return pattern.find(block)?.groupValues?.get(1)
}
private fun setScalar(block: String, key: String, value: String, newline: String): String {
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*)$")
val match = pattern.find(block)
if (match != null) return block.replaceRange(match.range, match.groupValues[1] + "\"" + value + "\"" + match.groupValues[2])
val close = block.lastIndexOf('}')
if (close < 0) return block
val lineStart = block.lastIndexOf('\n', close).let { if (it < 0) 0 else it + 1 }
val indent = block.substring(lineStart, close).takeWhile { it == '\t' || it == ' ' } + "\t"
val entry = indent + "\"" + key + "\"\t\t\"" + value + "\"" + newline
return block.substring(0, lineStart) + entry + block.substring(lineStart)
}
private fun startupMovieSection(indent: String, path: String, newline: String): String = listOf(
indent + "\"StartupMovie\"",
indent + "{",
indent + "\t\"MovieID\"\t\t\"0\"",
indent + "\t\"LocalPath\"\t\t\"" + path + "\"",
indent + "}",
).joinToString(newline)
/**
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
* folder rather than dug out of app-private storage - but the session script redirects its own
@@ -21,6 +21,13 @@ object SessionPrefs {
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
/** Whether the launcher hides Android's status and navigation bars. */
fun launcherFullscreen(context: Context): Boolean = prefs(context).getBoolean("launcherFullscreen", true)
fun setLauncherFullscreen(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("launcherFullscreen", on).apply()
}
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean("hud", true)
fun setHudEnabled(context: Context, on: Boolean) {
@@ -306,6 +313,13 @@ object SessionPrefs {
prefs(context).edit().putString("steamChannel", id).apply()
}
/** Whether opening DroidDeck starts a Steam session instead of showing the front end. */
fun runSteamAtStartup(context: Context): Boolean = prefs(context).getBoolean("runSteamAtStartup", false)
fun setRunSteamAtStartup(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("runSteamAtStartup", on).apply()
}
/**
* The folders of the user's own Windows games (one game per subfolder), any number of them
* from anywhere on the device. The single folder an earlier build kept is carried in.
@@ -336,8 +350,8 @@ object SessionPrefs {
prefs(context).edit().putString("addedExe:$folderPath", path).apply()
}
/** The app's colour theme (ui/Themes ids); Paper on black unless chosen otherwise. */
fun theme(context: Context): String = prefs(context).getString("theme", "paper") ?: "paper"
/** The app's colour theme (ui/Themes ids); Graphite unless chosen otherwise. */
fun theme(context: Context): String = prefs(context).getString("theme", "graphite") ?: "graphite"
fun setTheme(context: Context, id: String) {
prefs(context).edit().putString("theme", id).apply()
@@ -57,6 +57,7 @@ import java.util.Locale
*/
class SessionService : Service() {
private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>()
private val stopLock = Any()
private var wakeLock: PowerManager.WakeLock? = null
private var wifiLock: WifiManager.WifiLock? = null
private var sessionPid = -1
@@ -84,7 +85,7 @@ class SessionService : Service() {
}
}
/** Counts sessions this service has started; a process exit from an earlier one is ignored. */
private var sessionGen = 0
@Volatile private var sessionGen = 0
override fun onCreate() {
super.onCreate()
@@ -263,150 +264,17 @@ class SessionService : Service() {
killStragglers()
SessionFiles.stage(this, root)
// One folder per session, claimed by whoever started first - the activity starts the
// compositor before this service runs - so the compositor's log lands in the same place.
val sessionDir = SessionPaths.beginOrCurrent(this)
val sessionDir = openSessionFolder()
val sessionLog = File(sessionDir, "session.log")
SessionState.logFile = sessionLog
SessionState.logDirectory = sessionDir
SessionState.sessionId = sessionDir.name
SessionState.eventsFile = File(sessionDir, "events.jsonl")
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
// Written first, so a session that dies in its first second still says what it ran on.
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
// Everything the app decides from here on - the driver it chose, the audio line, a rival
// client stopped, the exit status - reaches logcat and nowhere a user can get at. Mirror it.
SessionLogCapture.start(File(sessionDir, "app.log"))
val size = SessionState.outputSize
val guest = ArrayList<String>()
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("HOME=/root")
guest.add("USER=root")
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
guest.add("TERM=xterm-256color")
guest.add("LANG=C.UTF-8")
// Without this the session is UTC: the client's clock, its logs and every timestamp in a
// session bundle sit hours off the device's. Bannerlator carries the same line.
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
// Steam's CEF needs GL and the rootfs ships no native GL driver: route it through Zink.
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
// An imported glibc Turnip for this mode, when the user chose one: the session script checks
// the manifest and its library from inside and points the loader at it with VK_DRIVER_FILES,
// so the runtime's own driver above stays untouched and is what a bad import falls back to.
// A program from the rail is one of the desktop's emulators, so it draws with the desktop's
// Linux driver, not the Steam session's: the driver's shader cache is keyed on the driver
// build, and with two drivers every emulator compiled its shaders twice - once per way of
// starting it (RPCS3's 6650 interpreter variants on each first boot).
val driverMode = if (SessionState.mode == MODE_RUN) MODE_DESKTOP else SessionPrefs.prefMode(SessionState.mode)
val linuxDriverId = SessionPrefs.linuxDriver(this, driverMode)
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
// Downloads holds the value verbatim ("sysmem", "sysmem,deck_emu"); with nothing there, an
// imported driver from the A710/A720/A722 legs gets "sysmem" on its own, which is what both
// its authors advise for those GPUs and what nothing else in the list needs.
tuDebug(linuxDriverId)?.let { guest.add("TU_DEBUG=$it") }
// Zink renders the client's UI (Chromium -> ANGLE -> Zink -> Turnip). Lazy descriptors is
// the mode Zink recommends where the driver has no descriptor buffer, and what Ludashi ships
// by default for its Zink path; a switch here because on one Fold the menus run at 14 fps.
if (SessionPrefs.zinkLazy(this)) guest.add("ZINK_DESCRIPTORS=lazy")
// The rest of the client-interface switches (SessionPrefs): GL marshalled off the calling
// thread, no GL error checks, and the client run as SteamOS runs it (the script reads
// BL_STEAMDECK; it is the one that builds the command line).
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
// The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the
// same set-up as a Steam session: it gets what the client and its games are started with.
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
if (SessionState.mode == MODE_STEAM) {
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
SessionPrefs.writeForceFullscreenFlag(this)
}
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
// XALIA_SUPPORTED_ONLY itself otherwise). Off by default: xalia is Valve's, and on a device
// whose seccomp answers its syscalls normally there is no reason to take it away.
if (SessionPrefs.noXalia(this)) guest.add("PROTON_USE_XALIA=0")
// The FEXCore preset for the x86 games the client launches: its FEX_* variables go in
// here, before the script, so every game process inherits them from the client. The
// default preset sets nothing, which is what every session ran on before.
if (steamHere) {
val preset = SessionPrefs.fexPreset(this)
val vars = com.droiddeck.launcher.core.FexPreset.env(preset)
vars.forEach { guest.add(it) }
if (vars.isNotEmpty()) Log.i(TAG, "fex preset $preset: ${vars.joinToString(" ")}")
}
// Anything else, for a device that cannot be reached with a debugger: Downloads/droiddeck-env
// holds KEY=VALUE lines that go into the session's environment as written, after ours, so a
// line here wins. Zink and Turnip tunables (ZINK_DESCRIPTORS=lazy, MESA_*), gamescope's,
// the client's - whatever the experiment needs, without a build per attempt.
extraEnv().forEach { guest.add(it) }
// Core masks, Bannerlator's two (cfca3912). The client's is sent whenever the override is
// on, even naming every core: it exists to undo the pin Steam applies to its own interface
// renderer, and the scheduler's default is exactly what that pin takes away. A game's is
// sent only when it is a real restriction - a game has no pin of its own to undo.
if (steamHere && SessionPrefs.clientCpusOverride(this)) {
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
}
// The game cores also pin the desktop and a program from the rail; without a choice the
// session script picks every core but the slowest cluster for those (program_cores).
CpuCores.restrictionOrEmpty(SessionPrefs.gameCpus(this))
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
addClientEnvironment(guest, runtimeDir, steamHere)
// PulseAudio always: the client is a native Linux program and has no other way to make a
// sound - its menus, its music and its voice chat all go through here. DirectAudio is not
// an alternative to it on this path: it replaces the audio driver INSIDE Wine, so it
// changes what games do and leaves the client alone. The microphone is its own opt-in on
// top, and the helper only opens an input stream when asked - so a user who wants game
// sound but no recording gets exactly that, and Android's recording indicator stays off.
val wantsDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.directAudio(this)
val wantsMic = SessionPrefs.micEnabled(this) &&
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
// Both paths sit under the app's files directory, which the session binds at its own path,
// so the same string is valid on both sides and nothing has to be translated.
val audioDir = File(filesDir, "directaudio").apply { mkdirs() }
val relaySocket = File(audioDir, "relay.sock")
val micFifo = if (wantsMic) File(audioDir, "mic.fifo") else null
val audioLog = File(sessionDir, "audio.log")
val pulse = PulseAudioComponent(this, micFifo?.absolutePath)
// With DirectAudio on, the client's own sound goes through the relay too: the daemon
// fills the relay's ring and the relay, outside proot, drives the device.
// The client's own sound: the classic AAudio sink unless the user chose the relay.
val clientDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.clientDirectAudio(this)
if (clientDirectAudio) pulse.setRelaySocket(relaySocket.absolutePath)
pulse.setLogFile(audioLog)
pulse.attach(this)
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
components.add(pulse)
if (wantsDirectAudio || wantsMic || clientDirectAudio) {
// After the daemon in the list, so it can wait for the pipe the daemon makes.
val relay = DirectAudioRelayComponent(relaySocket, micFifo)
relay.setLogFile(audioLog)
relay.attach(this)
components.add(relay)
}
if (wantsDirectAudio) {
// Read by the Proton wrappers, which point Wine at the driver and name it in the
// prefix. Absent, they take an early return and the game uses Proton's own audio - so
// this variable is the whole of the selection.
guest.add("BL_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR)
guest.add("BANNER_AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
}
Log.i(TAG, "audio: client " + (if (clientDirectAudio) "DirectAudio" else "classic AAudio sink") + (if (wantsDirectAudio) " + DirectAudio for games" else "")
+ (if (wantsMic) " + microphone" else "") +
(if (SessionPrefs.micEnabled(this) && !wantsMic) " (microphone wanted but RECORD_AUDIO not granted)" else ""))
val pulse = startAudio(guest, sessionDir)
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
@@ -424,28 +292,7 @@ class SessionService : Service() {
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
if (controllersOn) {
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path)
val rings = FakeInputWriter.getRingEnv(fakeInputDir)
if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings")
// SDL and Steam key their mapping database on bus+vendor+product: only a known
// identity gets the standard layout without the user configuring the pad by hand.
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
guest.add("FAKE_EVDEV_VIBRATION=1")
// Steam Input's virtual-gamepad identity is for games the client starts, which are
// meant to see that pad. Everywhere else (the desktop, a program from the rail) it
// hides the pad: SDL ignores a Steam virtual gamepad unless it runs under Steam, so
// every SDL emulator came up with no controller. There it is a plain Xbox 360 pad.
if (SessionState.mode == MODE_STEAM) guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
guest.add("SDL_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_JOYSTICK_HIDAPI=0")
if (File(Environment.getExternalStorageDirectory(), PAD_LOG_SWITCH).exists()) {
guest.add("FAKE_EVDEV_LOG=1")
}
SessionState.fakeInputDir = fakeInputDir
}
if (controllersOn) addControllerEnvironment(guest, fakeInputDir)
// The desktop is wlroots (labwc). Stock wlroots allocates through gbm on a real DRM render
// node, and ours is a KGSL stand-in - labwc died at "unable to create allocator" - so the
// default is pixman (software, shm), where a Vulkan program cannot draw at all; those run
@@ -506,6 +353,282 @@ class SessionService : Service() {
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
FileUtils.clear(File(cacheDir, "shm"))
val binds = sessionBinds(controllersOn, fakeInputDir)
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
)
val hostEnv = HostEnvironment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
hostEnv["PROOT_TMP_DIR"] = cacheDir.path
// proot links against a libtalloc beside it, and Android's linker does not search an
// executable's own directory: unnamed, the process dies before it starts and says so only
// in `logcat -b crash`.
// proot reads this itself, so it belongs in proot's own environment rather than the guest's.
if (SessionPrefs.prootNoSeccomp(this)) {
hostEnv["PROOT_NO_SECCOMP"] = "1"
Log.i(TAG, "proot: seccomp acceleration off by request")
}
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
val terminalCommand = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
)
val terminalHostEnvironment = LinkedHashMap(System.getenv())
hostEnv.asArray().forEach { entry ->
val separator = entry.indexOf('=')
if (separator > 0) terminalHostEnvironment[entry.substring(0, separator)] = entry.substring(separator + 1)
}
if (gen == sessionGen && SessionState.running) {
SessionTerminal.prepare(terminalCommand, terminalHostEnvironment.map { (key, value) -> "$key=$value" }.toTypedArray(), root, gen)
}
// Whether the client signs in to Valve or starts offline: read once, while it starts, and
// rewritten by the client when it exits, so it is set again here at every session start.
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) OfflineMode.apply(this, root)
val networkLink = LinuxNetworkLinkComponent(this, root)
networkLink.attach(this)
networkLink.publish()
components.add(networkLink)
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while it was starting; not launching it")
if (gen == sessionGen) components.clear()
return
}
components.forEach { it.start() }
val line = command.joinToString(" ") {
it.replace("\\", "\\\\").replace(" ", "\\ ")
}
watchLaunchRequests(sessionRoot)
// One session replacing another (the desktop's Steam launchers): the old proot is killed
// by the teardown a second after the new one has started, and its exit used to arrive
// here as "session ended: 137" and end the NEW session. An exit belongs to the session
// that started it.
val pid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
}
Log.i(TAG, "session ended: $status")
stopSession(status ?: -1)
}, null)
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while its guest was starting; taking it down")
if (gen == sessionGen) {
launchWatcher?.stopWatching()
launchWatcher = null
components.reversed().forEach { runCatching { it.stop() } }
components.clear()
}
if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start()
return
}
sessionPid = pid
if (pid > 1) {
SessionEvents.guestStarted(pid)
} else {
SessionEvents.record("guest.start_failed", mapOf("pid" to pid))
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", pid)
stopSession(-1)
return
}
if (gen == sessionGen && SessionState.running) {
suspendController = SessionSuspendController(
sessionRoot = { sessionPid },
helperRoots = { components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } },
suspendAudio = {
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
},
resumeAudio = {
if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink")
},
)
mainHandler.post { updateSuspendPolicy() }
}
}
/** The session's own log folder, opened and filled with what is known before anything starts. */
private fun openSessionFolder(): File {
// One folder per session, claimed by whoever started first - the activity starts the
// compositor before this service runs - so the compositor's log lands in the same place.
val sessionDir = SessionPaths.beginOrCurrent(this)
val sessionLog = File(sessionDir, "session.log")
SessionState.logFile = sessionLog
SessionState.logDirectory = sessionDir
SessionState.sessionId = sessionDir.name
SessionState.eventsFile = File(sessionDir, "events.jsonl")
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
// Written first, so a session that dies in its first second still says what it ran on.
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
// Everything the app decides from here on - the driver it chose, the audio line, a rival
// client stopped, the exit status - reaches logcat and nowhere a user can get at. Mirror it.
SessionLogCapture.start(File(sessionDir, "app.log"))
return sessionDir
}
/** The guest's base environment: paths, the display, the GL/Vulkan stack and the client's switches. */
private fun addClientEnvironment(guest: MutableList<String>, runtimeDir: File, steamHere: Boolean) {
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("HOME=/root")
guest.add("USER=root")
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
guest.add("TERM=xterm-256color")
guest.add("LANG=C.UTF-8")
// Without this the session is UTC: the client's clock, its logs and every timestamp in a
// session bundle sit hours off the device's. Bannerlator carries the same line.
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
// Steam's CEF needs GL and the rootfs ships no native GL driver: route it through Zink.
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
// An imported glibc Turnip for this mode, when the user chose one: the session script checks
// the manifest and its library from inside and points the loader at it with VK_DRIVER_FILES,
// so the runtime's own driver above stays untouched and is what a bad import falls back to.
// A program from the rail is one of the desktop's emulators, so it draws with the desktop's
// Linux driver, not the Steam session's: the driver's shader cache is keyed on the driver
// build, and with two drivers every emulator compiled its shaders twice - once per way of
// starting it (RPCS3's 6650 interpreter variants on each first boot).
val driverMode = if (SessionState.mode == MODE_RUN) MODE_DESKTOP else SessionPrefs.prefMode(SessionState.mode)
val linuxDriverId = SessionPrefs.linuxDriver(this, driverMode)
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
// Downloads holds the value verbatim ("sysmem", "sysmem,deck_emu"); with nothing there, an
// imported driver from the A710/A720/A722 legs gets "sysmem" on its own, which is what both
// its authors advise for those GPUs and what nothing else in the list needs.
tuDebug(linuxDriverId)?.let { guest.add("TU_DEBUG=$it") }
// Zink renders the client's UI (Chromium -> ANGLE -> Zink -> Turnip). Lazy descriptors is
// the mode Zink recommends where the driver has no descriptor buffer, and what Ludashi ships
// by default for its Zink path; a switch here because on one Fold the menus run at 14 fps.
if (SessionPrefs.zinkLazy(this)) guest.add("ZINK_DESCRIPTORS=lazy")
// The rest of the client-interface switches (SessionPrefs): GL marshalled off the calling
// thread, no GL error checks, and the client run as SteamOS runs it (the script reads
// BL_STEAMDECK; it is the one that builds the command line).
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
if (SessionState.mode == MODE_STEAM) {
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
SessionPrefs.writeForceFullscreenFlag(this)
}
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
// XALIA_SUPPORTED_ONLY itself otherwise). Off by default: xalia is Valve's, and on a device
// whose seccomp answers its syscalls normally there is no reason to take it away.
if (SessionPrefs.noXalia(this)) guest.add("PROTON_USE_XALIA=0")
// The FEXCore preset for the x86 games the client launches: its FEX_* variables go in
// here, before the script, so every game process inherits them from the client. The
// default preset sets nothing, which is what every session ran on before.
if (steamHere) {
val preset = SessionPrefs.fexPreset(this)
val vars = com.droiddeck.launcher.core.FexPreset.env(preset)
vars.forEach { guest.add(it) }
if (vars.isNotEmpty()) Log.i(TAG, "fex preset $preset: ${vars.joinToString(" ")}")
}
// Anything else, for a device that cannot be reached with a debugger: Downloads/droiddeck-env
// holds KEY=VALUE lines that go into the session's environment as written, after ours, so a
// line here wins. Zink and Turnip tunables (ZINK_DESCRIPTORS=lazy, MESA_*), gamescope's,
// the client's - whatever the experiment needs, without a build per attempt.
extraEnv().forEach { guest.add(it) }
// Core masks, Bannerlator's two (cfca3912). The client's is sent whenever the override is
// on, even naming every core: it exists to undo the pin Steam applies to its own interface
// renderer, and the scheduler's default is exactly what that pin takes away. A game's is
// sent only when it is a real restriction - a game has no pin of its own to undo.
if (steamHere && SessionPrefs.clientCpusOverride(this)) {
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
}
// The game cores also pin the desktop and a program from the rail; without a choice the
// session script picks every core but the slowest cluster for those (program_cores).
CpuCores.restrictionOrEmpty(SessionPrefs.gameCpus(this))
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
}
/** PulseAudio, and the DirectAudio relay when a path needs it; returns the daemon for suspend and resume. */
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
// PulseAudio always: the client is a native Linux program and has no other way to make a
// sound - its menus, its music and its voice chat all go through here. DirectAudio is not
// an alternative to it on this path: it replaces the audio driver INSIDE Wine, so it
// changes what games do and leaves the client alone. The microphone is its own opt-in on
// top, and the helper only opens an input stream when asked - so a user who wants game
// sound but no recording gets exactly that, and Android's recording indicator stays off.
val wantsDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.directAudio(this)
val wantsMic = SessionPrefs.micEnabled(this) &&
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
// Both paths sit under the app's files directory, which the session binds at its own path,
// so the same string is valid on both sides and nothing has to be translated.
val audioDir = File(filesDir, "directaudio").apply { mkdirs() }
val relaySocket = File(audioDir, "relay.sock")
val micFifo = if (wantsMic) File(audioDir, "mic.fifo") else null
val audioLog = File(sessionDir, "audio.log")
val pulse = PulseAudioComponent(this, micFifo?.absolutePath)
// With DirectAudio on, the client's own sound goes through the relay too: the daemon
// fills the relay's ring and the relay, outside proot, drives the device.
// The client's own sound: the classic AAudio sink unless the user chose the relay.
val clientDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.clientDirectAudio(this)
if (clientDirectAudio) pulse.setRelaySocket(relaySocket.absolutePath)
pulse.setLogFile(audioLog)
pulse.attach(this)
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
components.add(pulse)
if (wantsDirectAudio || wantsMic || clientDirectAudio) {
// After the daemon in the list, so it can wait for the pipe the daemon makes.
val relay = DirectAudioRelayComponent(relaySocket, micFifo)
relay.setLogFile(audioLog)
relay.attach(this)
components.add(relay)
}
if (wantsDirectAudio) {
// Read by the Proton wrappers, which point Wine at the driver and name it in the
// prefix. Absent, they take an early return and the game uses Proton's own audio - so
// this variable is the whole of the selection.
guest.add("BL_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR)
guest.add("BANNER_AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
}
Log.i(TAG, "audio: client " + (if (clientDirectAudio) "DirectAudio" else "classic AAudio sink") + (if (wantsDirectAudio) " + DirectAudio for games" else "")
+ (if (wantsMic) " + microphone" else "") +
(if (SessionPrefs.micEnabled(this) && !wantsMic) " (microphone wanted but RECORD_AUDIO not granted)" else ""))
return pulse
}
/** The fake evdev pads: the ring files the app writes and the identity SDL and Steam see. */
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File) {
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path)
val rings = FakeInputWriter.getRingEnv(fakeInputDir)
if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings")
// SDL and Steam key their mapping database on bus+vendor+product: only a known
// identity gets the standard layout without the user configuring the pad by hand.
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
guest.add("FAKE_EVDEV_VIBRATION=1")
// Steam Input's virtual-gamepad identity is for games the client starts, which are
// meant to see that pad. Everywhere else (the desktop, a program from the rail) it
// hides the pad: SDL ignores a Steam virtual gamepad unless it runs under Steam, so
// every SDL emulator came up with no controller. There it is a plain Xbox 360 pad.
if (SessionState.mode == MODE_STEAM) guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
guest.add("SDL_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1")
guest.add("SDL_JOYSTICK_HIDAPI=0")
if (File(Environment.getExternalStorageDirectory(), PAD_LOG_SWITCH).exists()) {
guest.add("FAKE_EVDEV_LOG=1")
}
SessionState.fakeInputDir = fakeInputDir
}
/** What proot binds into the guest: the pads, the battery, storage, the game library, added games and ROMs. */
private fun sessionBinds(controllersOn: Boolean, fakeInputDir: File): ArrayList<String> {
val binds = ArrayList<String>()
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
// The client's battery readout (the Quick Access Menu, the top bar) reads
@@ -563,85 +686,7 @@ class SessionService : Service() {
} else if (roms != null) {
Log.w(TAG, "roms: $roms is not a readable folder; /root/ROMs not offered this session")
}
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
)
val hostEnv = HostEnvironment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
hostEnv["PROOT_TMP_DIR"] = cacheDir.path
// proot links against a libtalloc beside it, and Android's linker does not search an
// executable's own directory: unnamed, the process dies before it starts and says so only
// in `logcat -b crash`.
// proot reads this itself, so it belongs in proot's own environment rather than the guest's.
if (SessionPrefs.prootNoSeccomp(this)) {
hostEnv["PROOT_NO_SECCOMP"] = "1"
Log.i(TAG, "proot: seccomp acceleration off by request")
}
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
val terminalCommand = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
)
val terminalHostEnvironment = LinkedHashMap(System.getenv())
hostEnv.asArray().forEach { entry ->
val separator = entry.indexOf('=')
if (separator > 0) terminalHostEnvironment[entry.substring(0, separator)] = entry.substring(separator + 1)
}
if (gen == sessionGen && SessionState.running) {
SessionTerminal.prepare(terminalCommand, terminalHostEnvironment.map { (key, value) -> "$key=$value" }.toTypedArray(), root, gen)
}
// Whether the client signs in to Valve or starts offline: read once, while it starts, and
// rewritten by the client when it exits, so it is set again here at every session start.
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) OfflineMode.apply(this, root)
val networkLink = LinuxNetworkLinkComponent(this, root)
networkLink.attach(this)
networkLink.publish()
components.add(networkLink)
components.forEach { it.start() }
val line = command.joinToString(" ") {
it.replace("\\", "\\\\").replace(" ", "\\ ")
}
watchLaunchRequests(sessionRoot)
// One session replacing another (the desktop's Steam launchers): the old proot is killed
// by the teardown a second after the new one has started, and its exit used to arrive
// here as "session ended: 137" and end the NEW session. An exit belongs to the session
// that started it.
sessionPid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
}
Log.i(TAG, "session ended: $status")
stopSession(status ?: -1)
}, null)
Log.i(TAG, "session pid $sessionPid, log ${sessionLog.path}")
if (gen == sessionGen && SessionState.running && sessionPid > 1) {
SessionEvents.guestStarted(sessionPid)
} else if (gen == sessionGen && SessionState.running) {
SessionEvents.record("guest.start_failed", mapOf("pid" to sessionPid))
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", sessionPid)
stopSession(-1)
return
}
if (gen == sessionGen && SessionState.running) {
suspendController = SessionSuspendController(
sessionRoot = { sessionPid },
helperRoots = { components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } },
suspendAudio = {
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
},
resumeAudio = {
if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink")
},
)
mainHandler.post { updateSuspendPolicy() }
}
return binds
}
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
@@ -714,6 +759,30 @@ class SessionService : Service() {
* behind, still holding the Wayland socket and the audio server the next session needs. They
* are our uid, so they are ours to kill.
*/
/**
* Every process of ours still running a program out of the Linux runtime once proot is gone.
* proot's --kill-on-exit and the tree sweep only reach what proot still traces; a tracee it
* lost - an Xwayland that aborted from one thread and then looped on a syscall proot's own
* seccomp filter, with no tracer left, answers ENOSYS - survives both, reparented to init,
* and wrote 9 GB of one line into the session log before anything killed it.
*/
private fun killGuestLeftovers() {
val me = android.os.Process.myPid()
val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/"
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
var killed = 0
for (proc in procs) {
val pid = proc.name.toIntOrNull() ?: continue
if (pid == me) continue
// Another uid's exe is not ours to read; a process already gone has none.
val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue }
if (!exe.startsWith(rootfs)) continue
android.os.Process.killProcess(pid)
killed++
}
if (killed > 0) Log.w(TAG, "killed $killed guest process(es) proot no longer tracked")
}
private fun killStragglers() {
val me = android.os.Process.myPid()
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
@@ -826,8 +895,12 @@ class SessionService : Service() {
}
}
private fun finishSessionStop(status: Int) {
private fun finishSessionStop(status: Int, stoppedGen: Int) {
mainHandler.post {
if (stoppedGen != sessionGen || SessionState.running) {
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
return@post
}
SessionState.suspended = false
SessionState.guestPid = -1
releaseLocks()
@@ -846,8 +919,11 @@ class SessionService : Service() {
}
private fun stopSession(status: Int) {
if (!SessionState.running) return
SessionState.running = false
synchronized(stopLock) {
if (!SessionState.running) return
SessionState.running = false
}
val stoppedGen = sessionGen
SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
@@ -890,10 +966,11 @@ class SessionService : Service() {
Thread({
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
finishSessionStop(status)
killGuestLeftovers()
finishSessionStop(status, stoppedGen)
}, "session-teardown").start()
} else {
finishSessionStop(status)
finishSessionStop(status, stoppedGen)
}
}
if (prootPid > 1) acquireLocks()
@@ -1075,6 +1152,10 @@ class SessionService : Service() {
}
fun stop(context: Context) {
if (!SessionState.running) {
SessionState.stopRequested = true
return
}
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
}
@@ -0,0 +1,434 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.ComponentsManager.CatalogItem
import com.droiddeck.launcher.session.ComponentsManager.Snapshot
import java.text.DateFormat
import java.util.Date
/** One installed row: a Proton's original bundle (one per Proton build) or a stored package. */
private class InstalledItem(
val name: String, val detail: String, val tag: String,
val selected: Boolean, val removable: Boolean,
/** Stored package file, or null for an original. */
val file: String?,
/** The Proton build an original belongs to. */
val protonVersion: String?,
)
private val GOLD = Color(0xFFF2C66D)
private val ROW_SHAPE = RoundedCornerShape(10.dp)
/**
* FEX, DXVK and VKD3D-Proton per Proton, as a full page opened from the rail's "Components" entry.
* A title row with the Nightlies refresh, then the Proton and the component (LB / RB turn it), what
* is in use, and the installed packages beside the ones on the Nightlies - stacked when the page is
* narrow. Tapping an installed row swaps it in; the refresh button is the only thing that goes online.
*/
@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
@Composable
fun ComponentsPage(
snapshot: Snapshot?,
catalog: List<CatalogItem>,
catalogAt: Long,
protonId: String?,
comp: String,
checking: Boolean,
busy: String?,
downloads: Map<String, Int>,
onProton: (String) -> Unit,
onComp: (String) -> Unit,
onSwap: (String) -> Unit,
onRestore: (String) -> Unit,
onCancelQueued: () -> Unit,
onDeletePackage: (String) -> Unit,
onDeleteOriginal: (String) -> Unit,
onDownload: (CatalogItem) -> Unit,
onRefresh: () -> Unit,
onImport: () -> Unit,
onBack: () -> Unit,
requestInitialFocus: Boolean = true,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
BackHandler(onBack = onBack)
var confirm by remember { mutableStateOf<Pair<String, () -> Unit>?>(null) }
var confirmTitle by remember { mutableStateOf("") }
var about by remember { mutableStateOf(false) }
var protonMenu by remember { mutableStateOf(false) }
fun ask(title: String, body: String, action: () -> Unit) { confirmTitle = title; confirm = body to action }
val views = snapshot?.protons ?: emptyList()
val view = views.firstOrNull { it.proton.id == protonId } ?: views.firstOrNull()
val label = ComponentsManager.LABEL[comp] ?: comp
val checked = if (catalogAt > 0) DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(catalogAt * 1000)) else "never"
val nightlies = if (busy != null) "$busy…" else "Nightlies checked $checked"
Column(Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
// ---- title, and the one thing that goes online -----------------------------------------
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
Text(
"Components", fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground,
maxLines = 1, modifier = Modifier.weight(1f),
)
if (!narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
ToolIcon(Icons.Outlined.Info, "About Components") { about = true }
ToolIcon(Icons.Outlined.Refresh, "Check the Nightlies for new packages", busy = checking, enabled = !checking, onClick = onRefresh)
}
if (narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
// ---- which Proton, which component ------------------------------------------------------
val comps = ComponentsManager.COMPONENTS
androidx.compose.foundation.layout.FlowRow(
horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
) {
if (view != null) Box {
ValueChip(view.proton.name, protonMenu, modifier = Modifier.widthIn(max = 300.dp).heightIn(min = 44.dp)) { protonMenu = !protonMenu }
AnchoredMenu(protonMenu, onDismiss = { protonMenu = false }, title = "Proton",
note = "Valve's own Proton is replaced when Steam updates it; its originals are kept per build.") { first ->
views.forEachIndexed { i, v ->
val swaps = v.components.values.count { it.activeFile != null }
MenuItem(
v.proton.name, checked = v.proton.id == view.proton.id,
detail = v.proton.version + (if (swaps > 0) " · $swaps swapped" else " · all original") + (if (v.inUseByGame) " · game running" else ""),
focusRequester = if (i == 0) first else null,
) { onProton(v.proton.id); protonMenu = false }
}
}
}
TabStrip(comps.map { ComponentsManager.LABEL.getValue(it) }, comps.indexOf(comp).coerceAtLeast(0), { onComp(comps[it]) })
}
// ---- what is in use -----------------------------------------------------------------------
if (view != null) {
val st = view.components.getValue(comp)
val fixedAt = if (view.reappliedAt > 0) " · re-applied at launch " + DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(view.reappliedAt * 1000)) else ""
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(top = 12.dp).clip(RoundedCornerShape(12.dp)).background(colors.surface)
.border(1.dp, pal.line, RoundedCornerShape(12.dp)).padding(horizontal = 14.dp, vertical = 8.dp).heightIn(min = 28.dp),
) {
Box(Modifier.size(8.dp).background(if (st.queued != null) Color(0xFFFFB86B) else pal.good, CircleShape))
Text(
(if (st.queued != null) "Next: ${st.queued} · after the game closes" else "$label in use: ${st.inUse}") + fixedAt,
fontSize = 14.sp, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
)
if (st.queued != null) FocusText("Cancel", pal.signal, onClick = onCancelQueued)
else if (!narrow) Text(
if (view.inUseByGame) "Waits until the game closes" else "Changes apply the next time a game starts",
fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1,
)
}
}
// ---- the lists ------------------------------------------------------------------------------
when {
snapshot == null -> Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp)) {
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(12.dp))
Text("Reading the Protons…", fontSize = 14.sp, color = colors.onSurfaceVariant)
}
view == null -> Text(
"No Proton is installed in the Linux runtime yet. Start the Steam client once so it downloads its ARM64 Proton, or add GE-Proton / CachyOS from Setup.",
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 16.dp),
)
else -> {
val p = view.proton
val st = view.components.getValue(comp)
val build = ComponentsManager.safeName(p.version)
val originals = view.originals.filter { it.comp == comp }
val stored = snapshot.packages.filter { it.comp == comp }
val activeIsOriginal = st.activeFile == null
val rows = originals.map { o ->
val isCurrent = o.protonVersion == build
InstalledItem(
"Original · ${o.protonVersion}",
o.label.substringAfterLast(" · ", "").ifEmpty { o.label } + if (isCurrent) " · this build" else " · earlier build",
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + stored.map { s ->
InstalledItem(s.version, String.format("%.1f MB", s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
}
val storedNames = snapshot.packages.map { it.file }.toSet()
val available = catalog.filter { it.comp == comp && ComponentsManager.safeName(it.file) !in storedNames }
val first = remember { FocusRequester() }
LaunchedEffect(p.id, comp, requestInitialFocus) {
if (requestInitialFocus) runCatching { first.requestFocus() }
}
val installed: @Composable () -> Unit = {
SettingsGroup("Installed · ${rows.size}") {
if (rows.isEmpty()) Text(
"Nothing stored for $label yet. This Proton's own files are saved as its original when the page opens.",
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
)
rows.forEachIndexed { i, item ->
InstalledLine(
item, modifier = if (i == 0) Modifier.focusRequester(first) else Modifier,
onSelect = {
if (item.selected) return@InstalledLine
val waits = if (view.inUseByGame) " A game is running on this Proton, so it waits until the game closes." else " It applies the next time a game starts."
if (item.file != null) ask("Swap $label?", "Put ${item.name} into ${p.name}? Its shipped files stay saved as an original bundle.$waits") { onSwap(item.file) }
else ask("Restore $label?", "Put the ${item.protonVersion} original back into ${p.name}?$waits") { onRestore(item.protonVersion!!) }
},
onDelete = {
if (item.file != null) ask("Delete ${item.name}?", "Its package file is removed from the app. You can download it again any time.") { onDeletePackage(item.file) }
else ask("Delete this original?", "The ${item.protonVersion} original of $label belongs to an earlier build of ${p.name}. The installed build's original is always kept.") { onDeleteOriginal(item.protonVersion!!) }
},
)
}
}
}
val nightly: @Composable () -> Unit = {
SettingsGroup("On the Nightlies · ${available.size}") {
if (available.isEmpty()) Text(
if (catalogAt == 0L) "Refresh to list the packages on the Nightlies." else "Nothing new since the last check.",
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
)
available.forEach { d -> AvailableLine(d, downloads[d.file], enabled = busy == null) { onDownload(d) } }
}
}
Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
if (narrow) { installed(); nightly() }
else Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.Top) {
Column(Modifier.weight(1f)) { installed() }
Column(Modifier.weight(1f)) { nightly() }
}
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 14.dp)) {
SmallButton("Import .wcp", onClick = onImport)
if (!activeIsOriginal && originals.any { it.protonVersion == build }) FocusText("Restore this Proton's original", pal.signal) {
ask("Restore $label?", "Put ${p.name}'s original $label back?") { onRestore(build) }
}
}
}
}
}
}
if (about) AlertDialog(
onDismissRequest = { about = false },
title = { Text("Components") },
text = {
Text(
"FEX, DXVK and VKD3D-Proton for each Proton the Steam client runs games with.\n\n" +
"Tap an installed row to swap it in; it applies the next time a game starts. If a game is running on that Proton, the swap waits until it closes.\n\n" +
"Your choices are also checked right before every game launch: if anything changed a Proton's files (Steam's start-up tests, for one), they are put back first, and the page says \"re-applied at launch\".\n\n" +
"Each Proton build's own files are kept as its original, so a Steam update never loses them. Packages come from the Nightlies \"-Linux\" releases (refresh) or Import .wcp.",
fontSize = 14.sp,
)
},
confirmButton = { FocusText("OK", pal.signal) { about = false } },
)
confirm?.let { (body, action) ->
AlertDialog(
onDismissRequest = { confirm = null },
title = { Text(confirmTitle) },
text = { Text(body, fontSize = 14.sp) },
// Opens on Cancel, so a stray A press on a controller never swaps or deletes anything.
confirmButton = {
val del = confirmTitle.startsWith("Delete")
FocusText(if (del) "Delete" else if (confirmTitle.startsWith("Restore")) "Restore" else "Swap", if (del) colors.error else pal.signal) { confirm = null; action() }
},
dismissButton = {
val cancelFocus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { cancelFocus.requestFocus() } }
FocusText("Cancel", colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
},
)
}
}
@Composable
private fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(40.dp).clip(RoundedCornerShape(12.dp))
.background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line2, RoundedCornerShape(12.dp))
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick),
) {
if (busy) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
else Icon(icon, contentDescription = description, tint = colors.onBackground, modifier = Modifier.size(20.dp))
}
}
/**
* A small button. Resting: grey outline (blue text when [accent]). Focused or hovered: a solid blue
* fill with an outline in the text colour - unmistakable in a column of identical buttons.
*/
@Composable
private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean = false, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = (src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value) && enabled
Box(
contentAlignment = Alignment.Center,
modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp))
.background(if (hot) pal.signal else colors.surfaceVariant)
.border(2.dp, if (hot) colors.onBackground else pal.line2, RoundedCornerShape(10.dp))
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
Text(
text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1,
color = if (!enabled) colors.onSurfaceVariant else if (hot) pal.onSignal else if (accent) pal.signal else colors.onBackground,
)
}
}
@Composable
private fun Tag(text: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val (fg, bg) = when (text) {
"ORIGINAL" -> GOLD to Color(0x22F2C66D)
"IN USE" -> pal.onSignal to pal.signal
"NEW" -> pal.good to Color(0x224CD37F)
else -> colors.onSurfaceVariant to Color.White.copy(alpha = 0.07f)
}
Text(
text.lowercase().replaceFirstChar { it.uppercase() }, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = fg, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(bg).padding(horizontal = 7.dp, vertical = 1.dp),
)
}
@Composable
private fun InstalledLine(item: InstalledItem, modifier: Modifier = Modifier, onSelect: () -> Unit, onDelete: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
.background(if (hot) pal.signal.copy(alpha = 0.14f) else if (item.selected) pal.signal.copy(alpha = 0.07f) else Color.Transparent),
) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.weight(1f).heightIn(min = 56.dp).then(modifier)
.border(2.dp, if (hot) pal.signal else Color.Transparent, ROW_SHAPE)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect)
.controllerConfirm(onClick = onSelect)
.padding(start = 14.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).border(2.dp, if (item.selected) pal.signal else colors.onSurfaceVariant, CircleShape)) {
if (item.selected) Box(Modifier.size(9.dp).background(pal.signal, CircleShape))
}
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
item.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (item.selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
)
Tag(item.tag)
}
Text(item.detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 2.dp))
}
if (item.selected) Tag("IN USE")
}
// The trash column is always there (empty when the row can't be deleted) so rows line up.
if (!item.removable) Spacer(Modifier.padding(end = 6.dp).size(40.dp))
else {
val delSrc = remember { MutableInteractionSource() }
val delHot = delSrc.collectIsFocusedAsState().value || delSrc.collectIsHoveredAsState().value
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(end = 6.dp).size(40.dp).clip(ROW_SHAPE)
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
.border(2.dp, if (delHot) colors.error else Color.Transparent, ROW_SHAPE)
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete)
.controllerConfirm(onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = "Delete ${item.name}", tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
@Composable
private fun AvailableLine(d: CatalogItem, progress: Int?, enabled: Boolean, onDownload: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(start = 14.dp, end = 10.dp, top = 8.dp, bottom = 8.dp),
) {
Column(Modifier.weight(1f)) {
Text(d.file.removeSuffix(".wcp"), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
"${d.release} · " + String.format("%.1f MB", d.size / 1048576.0), fontSize = 13.sp, color = colors.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 2.dp),
)
}
if (progress == null) SmallButton("Download", enabled = enabled, accent = true, onClick = onDownload)
else Column(horizontalAlignment = Alignment.End, modifier = Modifier.width(96.dp)) {
Text(if (progress < 0) "…" else "$progress%", fontSize = 13.sp, color = colors.onSurfaceVariant)
Spacer(Modifier.height(4.dp))
if (progress < 0) LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
else LinearProgressIndicator(progress = { progress / 100f }, modifier = Modifier.fillMaxWidth())
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
@@ -41,12 +41,12 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
oscMode, note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc,
)
val tintOpen = host.open == "controller-tint"
SettingsRow("Colour", "Tint of the on-screen buttons", highlighted = tintOpen) {
SettingsRow("Color", "Tint of the on-screen buttons", highlighted = tintOpen) {
Box {
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second ?: "Custom", tintOpen) {
host.open = if (tintOpen) null else "controller-tint"
}
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = "Colour") { firstItemFocus ->
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = "Color") { firstItemFocus ->
ControllerPrefs.tints.forEachIndexed { index, (color, name) ->
MenuItem(name, checked = c.tint == color, leading = { Swatch(color) }, focusRequester = if (index == 0) firstItemFocus else null) {
a.onTint(color)
@@ -59,7 +59,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
ChoiceRow(host, "controller-opacity", "Opacity", null, ControllerPrefs.opacities.map { it to "$it%" }, c.opacity, onPick = a.onOpacity)
ChoiceRow(host, "controller-size", "Button size", "100% keeps the standard size", ControllerPrefs.sizes.map { it to "$it%" }, c.size, onPick = a.onSize)
ToggleRow(host, "controller-stick-click", "Stick click", "Double-tap a stick and hold for L3 or R3", c.stickClick, onChange = a.onStickClick)
ToggleRow(host, "controller-adaptive", "Adaptive sticks", "A stick centres where your thumb lands and returns home when you let go", c.adaptiveSticks, onChange = a.onAdaptiveSticks)
ToggleRow(host, "controller-adaptive", "Adaptive sticks", "A stick centers where your thumb lands and returns home when you let go", c.adaptiveSticks, onChange = a.onAdaptiveSticks)
SettingsRow("Layout", if (c.customLayout) "Custom positions saved" else "Placed for this screen's size and your grip") {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SecondaryButton("Edit") { a.onEditLayout() }
@@ -68,7 +68,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
}
val remapped = c.mapping.count { (id, target) -> id != target }
ActionRow("Button mapping", if (remapped == 0) "Every button sends its own input" else "$remapped of ${c.mapping.size} buttons remapped", "Configure", a.onMapping)
ActionRow("Reset controller", "Restore the default colour, opacity, size, stick behaviour, mapping and layout", "Reset", a.onResetAll)
ActionRow("Reset controller", "Restore the default color, opacity, size, stick behavior, mapping and layout", "Reset", a.onResetAll)
}
@Composable
@@ -194,12 +194,12 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
color = if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
)
if (row.tag.isNotEmpty()) Text(
row.tag, fontSize = 9.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = colors.onSurfaceVariant,
row.tag, fontSize = 11.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(start = 8.dp).clip(RoundedCornerShape(5.dp)).background(Color.White.copy(alpha = 0.07f))
.padding(horizontal = 6.dp, vertical = 2.dp),
)
}
if (row.detail.isNotEmpty()) Text(row.detail, fontSize = 11.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
if (row.detail.isNotEmpty()) Text(row.detail, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
}
}
if (row.removable) {
@@ -221,7 +221,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
/** A text button that shows where controller focus is: an outline in its own colour. */
@Composable
private fun FocusText(text: String, color: Color, modifier: Modifier = Modifier, onClick: () -> Unit) {
internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier, onClick: () -> Unit) {
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val shape = RoundedCornerShape(8.dp)
@@ -0,0 +1,22 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.Composable
import com.droiddeck.launcher.gpu.FrameGen
/**
* The frame generation picker, anchored to whatever opened it (host key "fg"). One copy for Setup,
* a game's launch settings and the session drawer, so they say the same thing.
*/
@Composable
internal fun FrameGenMenu(
host: MenuHost, engine: String, multiplier: Int, lsfgReady: Boolean,
onPick: (engine: String, multiplier: Int) -> Unit,
) {
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
val need = if (lsfgReady) null else "Needs Lossless Scaling installed in Steam"
fun pick(e: String, m: Int) { onPick(e, m); host.open = null }
MenuItem("Off", checked = engine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { pick(FrameGen.ENGINE_OFF, 2) }
for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_WINFG, m), checked = engine == FrameGen.ENGINE_WINFG && multiplier == m) { pick(FrameGen.ENGINE_WINFG, m) }
for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_LSFG, m), checked = engine == FrameGen.ENGINE_LSFG && multiplier == m, enabled = lsfgReady, detail = need) { pick(FrameGen.ENGINE_LSFG, m) }
}
}
@@ -0,0 +1,186 @@
package com.droiddeck.launcher.ui
import android.graphics.Bitmap
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
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
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.runtime.key
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.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 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.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
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 androidx.compose.ui.zIndex
import coil.compose.AsyncImage
import java.io.File
// Cover art: posters, the art grid and its tiles.
internal class Tile(
val title: String, val sub: String?, val art: File?, val key: String,
val iconRes: Int? = null, val dim: Boolean = false, val iconBitmap: Bitmap? = null,
val showFooter: Boolean = true,
val onClick: () -> Unit,
)
@Composable
internal fun Poster(art: File?, name: String, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
val t = remember { Animatable(0f) }
LaunchedEffect(Unit) { t.animateTo(1f, Motion.sp(0.6f, Spring.StiffnessLow)) }
Box(
modifier = modifier.padding(start = 16.dp).aspectRatio(2f / 3f)
.graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 16.dp.toPx(); rotationZ = (1f - t.value) * 2f; scaleX = 0.94f + 0.06f * t.value; scaleY = scaleX; shadowElevation = 22.dp.toPx(); shape = Shape12; clip = false }
.clip(Shape12).background(artBrush(hueOf(name))),
) {
if (art != null) CoverImage(art, Modifier.fillMaxSize())
else Text(name, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.align(Alignment.BottomStart).padding(8.dp), maxLines = 3, overflow = TextOverflow.Ellipsis)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun ArtGrid(tiles: List<Tile>, wide: Boolean = false) {
val square = tiles.isNotEmpty() && tiles.all { it.art == null && (it.iconRes != null || it.iconBitmap != null) }
// Big enough to recognise a game by its art and read its name under it; icon tiles are squares.
val minSize = if (square) 76.dp else if (wide) 120.dp else 96.dp
val gap = 12.dp
// Laid out whole, not lazily: the pad's focus search only finds tiles that exist, and a lazy
// grid composes only the rows on screen, so a press towards the next row bounced back among
// the visible tiles. A few hundred tiles lay out fine; the page's scroll follows the focused one.
BoxWithConstraints(modifier = Modifier.fillMaxWidth()) {
val avail = maxWidth - 8.dp
val cols = ((avail + gap) / (minSize + gap)).toInt().coerceAtLeast(1)
val tileWidth = (avail - gap * (cols - 1)) / cols
Column(modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 14.dp, start = 4.dp, end = 4.dp)) {
for (row in tiles.chunked(cols)) {
Row(horizontalArrangement = Arrangement.spacedBy(gap), modifier = Modifier.fillMaxWidth().padding(bottom = gap)) {
for (t in row) key(t.key) {
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val track = Modifier.paneItem("tile:" + t.key).then(if (t === tiles.first()) Modifier.firstTile() else Modifier)
Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot, track) }
}
}
}
}
}
}
@Composable
private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableInteractionSource, hot: Boolean, track: Modifier) {
val colors = MaterialTheme.colorScheme
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.97f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "tileScale")
val lift by animateFloatAsState(if (hot) -5f else 0f, Motion.sp(0.6f), label = "tileLift")
val elev by animateFloatAsState(if (hot) 18f else 2f, Motion.tw(300), label = "tileElev")
val pal = LocalPalette.current
val ring by animateColorAsState(if (hot) pal.signal else Color.Transparent, Motion.tw(220), label = "tileRing")
Column(
modifier = track
.graphicsLayer { scaleX = scale; scaleY = scale; translationY = lift.dp.toPx(); shadowElevation = elev.dp.toPx(); shape = Shape12; clip = false; ambientShadowColor = if (hot) pal.signal else Color.Black; spotShadowColor = if (hot) pal.signal else Color.Black; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, 0.9f) }
.clip(Shape12)
.background(colors.surface)
.border(2.5.dp, ring, Shape12)
.alpha(if (t.dim && !hot) 0.55f else 1f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = t.onClick),
) {
Box(modifier = Modifier.fillMaxWidth().shine(hot)) {
Art(t.art, t.iconRes, t.title, Modifier.fillMaxWidth(), wide, t.iconBitmap)
}
if (t.showFooter) {
Column(modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp)) {
Text(t.title, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (t.sub != null) Text(t.sub, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
/**
* Art for a portrait (2:3) tile. Box art fills it; wide art - a PS3 disc's ICON0, a game's header -
* is shown whole over a blurred, darkened copy of itself instead of losing its sides to the crop.
*/
@Composable
private fun CoverImage(art: File, modifier: Modifier) {
var wideArt by remember(art) { mutableStateOf(false) }
Box(modifier) {
if (wideArt) {
AsyncImage(
model = art, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.2f; scaleY = 1.2f }.blur(14.dp),
)
Spacer(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.45f)))
}
AsyncImage(
model = art, contentDescription = null,
contentScale = if (wideArt) ContentScale.Fit else ContentScale.Crop,
onSuccess = { state ->
val size = state.painter.intrinsicSize
if (size.width > size.height * 1.1f) wideArt = true
},
modifier = Modifier.fillMaxSize(),
)
}
}
@Composable
private fun Art(art: File?, iconRes: Int?, label: String, modifier: Modifier, wide: Boolean = false, iconBitmap: Bitmap? = null) {
val colors = MaterialTheme.colorScheme
val ratio = if (art == null && (iconRes != null || iconBitmap != null)) 1f else if (wide) 16f / 9f else 2f / 3f
Box(modifier = modifier.aspectRatio(ratio).background(if (art == null && iconRes == null && iconBitmap == null) artBrush(hueOf(label)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surface)))) {
when {
art != null -> if (wide) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
else CoverImage(art, Modifier.fillMaxSize())
iconRes != null -> Image(painterResource(iconRes), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(if (wide) 10.dp else 8.dp))
iconBitmap != null -> Image(bitmap = iconBitmap.asImageBitmap(), contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(8.dp))
else -> {
Spacer(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Color.Transparent, 0.45f to Color.Transparent, 1f to Color.Black.copy(alpha = 0.55f))))
Text(label, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color.White.copy(alpha = 0.92f), modifier = Modifier.align(Alignment.BottomStart).padding(6.dp), maxLines = 3, overflow = TextOverflow.Ellipsis)
}
}
}
}
@@ -0,0 +1,409 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.CompositionLocalProvider
import android.os.Build
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Image
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
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.runtime.key
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
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.DesktopWindows
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.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.geometry.Offset
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.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.Role
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.HomeApp
import com.droiddeck.launcher.frontend.Library
import java.io.File
// The front end's right-hand pane and the page it shows: backdrop, desktop card and emulators.
@Composable
internal fun Pane(
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
) {
BoxWithConstraints(modifier = modifier) {
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
val backdropArt: File? = when {
s.pageKey != null && page != null -> null
selected.startsWith("app:") -> s.steamGames.firstOrNull { "app:${it.appId}" == selected }?.art
selected == "games" -> s.steamGames.maxByOrNull { it.lastPlayed }?.art
selected.startsWith("rom:") -> romFor(s, selected)?.second?.art
else -> null
}
Backdrop(backdropArt)
AnimatedContent(
// Picking another game changes the detail beside the list, not the whole page.
targetState = if (page != null && s.pageKey != null) s.pageKey else if (selected.startsWith("app:")) "games" else selected,
transitionSpec = {
(fadeIn(Motion.tw(300, 80)) + slideInVertically(Motion.tw(420, 80)) { it / 24 })
.togetherWith(fadeOut(Motion.tw(170)) + slideOutVertically(Motion.tw(170)) { -it / 40 })
.apply { targetContentZIndex = 1f }
},
label = "pane",
) { key ->
if (page != null && key == s.pageKey) page()
else Content(s, if (key == "games") selected else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb)
}
}
}
}
@Composable
private fun Backdrop(art: File?) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Crossfade(targetState = art, animationSpec = Motion.tw(700), label = "backdrop") { a ->
// A game's own art, blurred, where it has some; otherwise the plain ground with one quiet
// glow of the theme's signal colour - a colour per title hash read as noise.
if (a != null && Build.VERSION.SDK_INT >= 31) {
Box(modifier = Modifier.fillMaxSize().alpha(0.26f).blur(70.dp)) {
AsyncImage(model = a, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.5f; scaleY = 1.5f })
}
} else {
Box(modifier = Modifier.fillMaxSize().background(Brush.radialGradient(listOf(pal.signal.copy(alpha = 0.07f), Color.Transparent), center = Offset.Zero, radius = 1400f)))
}
}
Spacer(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color.Transparent, colors.background.copy(alpha = 0.35f)))))
}
private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, Library.Rom>? {
val parts = selected.split(":")
val e = s.emulators.firstOrNull { it.id == parts.getOrNull(1) } ?: return null
val g = e.games.getOrNull(parts.getOrNull(2)?.toIntOrNull() ?: -1) ?: return null
return e to g
}
@Composable
private fun Content(
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
val narrow = LocalNarrowPane.current
val padH = if (narrow) 16.dp else 22.dp
val padV = if (narrow) 12.dp else 18.dp
// Setup scrolls inside itself, under its tabs.
if (selected == "setup") {
Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) {
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
}
return
}
// Steam is a full-bleed wall of the library with Play over it.
if (selected == "steam") {
SteamHome(s, a, modifier)
return
}
// The Games tab lays out its own list and detail.
if (selected == "games" || selected.startsWith("app:")) {
GamesPage(s, a, selected, onSelect, modifier)
return
}
// Every other page scrolls as one - header, hero and grid - so a short screen reaches the grid
// instead of showing a sliver of it under a fixed hero. A focused tile scrolls itself into view.
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
when {
selected == "android-apps" && s.isHomeApp -> {
Rise(0) { PageHeader("Android apps") { Chip("${s.androidApps.size} apps", ok = false) } }
if (s.androidApps.isEmpty()) Rise(3) { Note("No launchable Android apps found.") }
else Rise(3, Modifier.fillMaxWidth()) {
ArtGrid(s.androidApps.map { app ->
Tile(
app.label,
null,
null,
"android:${app.packageName}",
onClick = { onAndroidAppClick(app) },
iconBitmap = app.icon,
)
})
}
}
selected == "desktop" -> {
val installed = s.emulators.filter { it.installed }
val available = s.emulators.filter { !it.installed }
Rise(0) {
PageHeader("Desktop") {
if (s.desktopInstalled) Chip("● Desktop installed", ok = true) else Chip("Installs on first open", ok = false)
}
}
Rise(2) { DesktopCard(s, a) }
if (installed.isNotEmpty()) {
Rise(3) { SectionTitle("Emulators", "${installed.size} installed") }
Rise(4) { EmulatorGrid(installed, first = true, onSelect = onSelect) }
}
if (available.isNotEmpty()) {
Rise(5) { SectionTitle("Available to install", available.size.toString()) }
Rise(6) { EmulatorGrid(available, first = installed.isEmpty(), onSelect = onSelect) }
}
}
selected.startsWith("emu:") -> {
val e = s.emulators.firstOrNull { "emu:${it.id}" == selected }
if (e == null) Note("Not installed.") else {
val pkgId = Library.packageId(e.id)
val pkg = pkgId?.let { id -> s.packages?.firstOrNull { it.id == id } }
Rise(0) {
BackLink("Desktop") { onSelect("desktop") }
}
Rise(1) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.padding(top = 12.dp, bottom = 12.dp),
) {
Image(painterResource(e.iconRes), null, modifier = Modifier.size(52.dp))
Column {
Text(e.name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text(
e.system.replaceFirstChar { it.uppercase() } + if (e.installed) "" else " · not installed",
fontSize = 14.sp, color = colors.onSurfaceVariant,
)
}
}
}
if (e.installed) {
Rise(3) {
Actions {
PrimaryButton("Open ${e.name}", enabled = !s.busy, main = true) { a.onEmulator(e) }
BusyChip(s)
SecondaryButton("ROMs folder", onClick = a.onRoms)
if (pkg != null) SecondaryButton(
if (pkg.kind == "appimage") "Remove" else "Hide",
enabled = s.packageBusyId == null && !s.sessionRunning,
) { a.onRemovePackage(pkg.id) }
}
}
Rise(4) { SectionTitle("Games", e.games.size.toString()) }
if (e.games.isEmpty()) Rise(5) {
Note(
if (s.romsDir == null) "Choose a ROMs folder."
else if (e.id == "retroarch") "Browse to /root/ROMs in RetroArch."
else "Add ${e.system} games to ROMs/${e.system.substringBefore(' ')}.",
)
}
else Rise(5, Modifier.fillMaxWidth()) {
ArtGrid(e.games.mapIndexed { index, g -> Tile(g.name, if (g.art != null) "installed" else g.hostPath.extension.uppercase().ifEmpty { "folder" }, g.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") } }, wide = e.games.none { it.art != null })
}
} else {
if (pkg != null) Rise(2) {
Actions {
PrimaryButton(
if (s.packageBusyId == pkg.id) "Installing…" else "Install ${e.name}",
enabled = s.packageBusyId == null && s.ready && !s.packageCatalogLoading && !s.sessionRunning,
) { a.onInstallPackage(pkg.id) }
if (s.sessionRunning) ActionChip("Stop session to install", ok = false)
else if (!s.ready) ActionChip("Runtime required", ok = false)
}
}
Rise(3) {
Box(Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 8.dp)) {
Note(when {
s.packageCatalogLoading -> "Loading install details…"
pkg == null -> "Install details are unavailable right now. Try again when the package catalog is reachable."
!s.ready -> "Install the Linux runtime from Setup before installing desktop apps."
s.sessionRunning -> "Stop the active session before installing desktop apps."
pkg.notes.isNotBlank() -> pkg.notes
else -> "Install ${e.name} into the Linux desktop runtime."
})
}
}
if (s.packageBusyId == pkg?.id) Rise(4) {
val stage = s.packageStage
Text(
if (stage != null && s.packagePercent >= 0) "$stage · ${s.packagePercent}%" else stage ?: "Starting…",
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 6.dp),
)
if (s.packagePercent >= 0) LinearProgressIndicator(progress = { s.packagePercent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
}
if (pkg?.kind == "tar") Rise(5) { Note("Hiding this package takes it off Desktop; its files stay in the Linux runtime.") }
}
}
}
selected.startsWith("rom:") -> {
val pair = romFor(s, selected)
if (pair == null) Note("That game is gone from the ROMs folder.") else {
val (e, g) = pair
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
BackLink(e.name) { onSelect("emu:${e.id}") }
Eyebrow("Desktop · ${e.system}")
}
}
Rise(1) { Title(g.name) }
Rise(2) {
Row {
Column(modifier = Modifier.weight(1f)) {
Text(g.guestPath, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.clip(RoundedCornerShape(8.dp)).background(colors.surface).padding(horizontal = 10.dp, vertical = 6.dp))
Spacer(Modifier.height(14.dp))
Actions {
Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp))
PrimaryButton("Launch in ${e.name}", enabled = !s.busy, main = true) { a.onRom(g) }
if (s.busy) BusyChip(s) else ActionChip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false)
}
}
if (g.art != null && !narrow) Poster(g.art, g.name, Modifier.width(detailPosterWidth))
}
}
val others = e.games.filter { it !== g }
if (others.isNotEmpty()) {
Rise(3) { SectionTitle("Also in ${e.name}", null) }
Rise(4, Modifier.fillMaxWidth()) {
ArtGrid(others.map { x ->
val index = e.games.indexOf(x)
Tile(x.name, if (x.art != null) "installed" else x.hostPath.extension.uppercase().ifEmpty { "folder" }, x.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") }
}, wide = others.none { it.art != null })
}
}
}
}
else -> Note("That page is gone. Pick a section on the left.")
}
}
}
/** The Linux desktop itself, above the emulators that run in it. */
@Composable
private fun DesktopCard(s: FrontEndState, a: FrontEndActions) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val actions: @Composable () -> Unit = {
Actions {
// Enabled without a runtime or the desktop: the session's loading screen installs them first.
PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, main = true, onClick = a.onDesktop)
Cog(onClick = a.onDesktopSettings)
BusyChip(s)
}
}
Column(
verticalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(16.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(52.dp).clip(Shape14).background(colors.surfaceVariant).border(1.dp, pal.line2, Shape14),
) { Icon(Icons.Outlined.DesktopWindows, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(26.dp)) }
Column(modifier = Modifier.weight(1f)) {
Text("Linux desktop", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text("LXQt, Firefox and your emulators", fontSize = 14.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
if (!narrow) actions()
}
if (narrow) actions()
}
}
/** Emulators as wide tiles - three across, or a list on a narrow page. */
@Composable
private fun EmulatorGrid(emulators: List<Library.Emulator>, first: Boolean, onSelect: (String) -> Unit) {
val columns = if (LocalNarrowPane.current) 1 else 3
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) {
emulators.chunked(columns).forEachIndexed { r, row ->
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
row.forEachIndexed { i, e ->
key(e.id) {
EmulatorTile(e, Modifier.weight(1f).fillMaxHeight(), isFirst = first && r == 0 && i == 0) { onSelect("emu:${e.id}") }
}
}
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
}
}
/**
* One emulator: its icon, system and games. One not yet installed says so in words and keeps full
* contrast - dimming it read as disabled rather than one press from installing.
*/
@Composable
private fun EmulatorTile(e: Library.Emulator, modifier: Modifier, isFirst: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.97f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "emuScale")
val system = e.system.replaceFirstChar { it.uppercase() }
val detail = if (e.installed && e.id != "retroarch") "$system · ${e.games.size} game${if (e.games.size == 1) "" else "s"}" else system
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = modifier.paneItem("tile:emu:${e.id}").then(if (isFirst) Modifier.firstTile() else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(Shape14)
.background(if (hot) pal.signal.copy(alpha = 0.10f) else if (e.installed) colors.surface else Color.Transparent)
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, Shape14)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.padding(horizontal = 12.dp, vertical = 10.dp),
) {
Image(painterResource(e.iconRes), contentDescription = null, modifier = Modifier.size(if (e.installed) 44.dp else 36.dp))
Column(modifier = Modifier.weight(1f)) {
Text(e.name, fontSize = if (e.installed) 15.sp else 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(detail, fontSize = if (e.installed) 13.sp else 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (!e.installed) Text(
"Install", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal,
modifier = Modifier.clip(RoundedCornerShape(8.dp)).border(1.dp, pal.line2, RoundedCornerShape(8.dp)).padding(horizontal = 10.dp, vertical = 6.dp),
)
}
}
@@ -0,0 +1,271 @@
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.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.key
import androidx.compose.foundation.layout.Column
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.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.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
// The Games page: the list, the hero for the selected game and its labels.
/**
* The Games tab: installed Steam games down the left, most recently played first, and the one
* picked beside them - its banner, Launch and the launch settings. One game skips the list.
*/
@Composable
internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, onSelect: (String) -> Unit, modifier: Modifier) {
val games = remember(s.steamGames) { s.steamGames.sortedByDescending { it.lastPlayed } }
val narrow = LocalNarrowPane.current
val current = games.firstOrNull { "app:${it.appId}" == selected } ?: games.firstOrNull()
if (current == null) {
Column(modifier = modifier.padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
Rise(0) { PageHeader("Games") }
Rise(1) { Note("Games you install in Steam show up here. Open Steam, install one, and it appears after the session.") }
Rise(2) {
Actions { PrimaryButton("Play Steam", enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp), onClick = a.onPlay) }
}
}
return
}
val host = rememberMenuHost()
if (games.size == 1) {
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
Rise(0) {
Row(verticalAlignment = Alignment.Bottom) {
GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp)) {
GameHeroCopy(current, if (narrow) 28.sp else 38.sp)
GameActions(current, s, a)
}
if (!narrow) Poster(current.art, current.name, Modifier.width(168.dp))
}
}
Rise(1) { SectionTitle("Launch settings", null) }
Rise(2) { LaunchSettings(s, a, host) }
}
return
}
val pal = LocalPalette.current
Row(modifier = modifier) {
GameList(games, current, onSelect = { onSelect("app:${it.appId}") }, onLaunch = { a.onSteamGame(it) },
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)) {
GameHeroCopy(current, if (narrow) 24.sp else 32.sp)
GameActions(current, s, a)
}
SectionTitle("Launch settings", null)
LaunchSettings(s, a, host)
}
}
}
@Composable
private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions) {
Actions {
PrimaryButton("Launch", enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(g) }
g.gameFiles?.takeIf { it.isDirectory }?.let { dir ->
SecondaryButton("Game files", compact = true) { a.onBrowseFiles(dir) }
}
g.protonPrefix?.takeIf { it.isDirectory }?.let { dir ->
SecondaryButton("Proton prefix", compact = true) { a.onBrowseFiles(dir) }
}
BusyChip(s)
}
}
/** When it was last played (or where it is, if never) over its name, then room for Launch. */
@Composable
private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
Text(
(lastPlayedText(g.lastPlayed) ?: libraryLabel(g.library)).uppercase(),
fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = LocalPalette.current.signal,
maxLines = 1, overflow = TextOverflow.Ellipsis,
)
Text(
g.name, fontSize = titleSize, lineHeight = titleSize * 1.15f, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(8.dp))
}
@Composable
private fun GameList(
games: List<Library.SteamGame>, current: Library.SteamGame,
onSelect: (Library.SteamGame) -> Unit, onLaunch: (Library.SteamGame) -> Unit, modifier: Modifier,
) {
val colors = MaterialTheme.colorScheme
// Laid out whole, as the art grid is: the pad's focus search only finds rows that exist.
Column(
verticalArrangement = Arrangement.spacedBy(2.dp),
modifier = modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 10.dp, top = 16.dp, bottom = 16.dp),
) {
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 6.dp, bottom = 10.dp)) {
Text("Games", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
Text(games.size.toString(), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 3.dp))
}
for (g in games) key(g.appId) {
GameRow(g, g.appId == current.appId, onSelect = { onSelect(g) }, onLaunch = { onLaunch(g) })
}
}
}
/** One game in the list. Moving onto it with the pad shows it; A launches it, a tap only shows it. */
@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)
.border(2.dp, if (selected || focused) pal.signal else Color.Transparent, Shape12)
.hoverable(src).clickable(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)
Text(
lastPlayedText(g.lastPlayed)?.removePrefix("Last played ")?.replaceFirstChar { it.uppercase() } ?: "Never played",
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
}
}
/** A page's title, with room at its right for a status chip. */
@Composable
internal fun PageHeader(title: String, trailing: @Composable RowScope.() -> Unit = {}) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp),
) {
Text(
title, fontSize = if (LocalNarrowPane.current) 22.sp else 26.sp, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground, maxLines = 1,
)
trailing()
}
}
/** Why a launch button is greyed out: the runtime is being worked on. Nothing when it is not. */
@Composable
internal fun BusyChip(s: FrontEndState) {
if (s.busy) ActionChip(if (s.percent >= 0) "Runtime busy · ${s.percent}%" else "Runtime busy", ok = false)
}
/** Whether Steam can start, said where Play is rather than only in Setup. */
@Composable
internal fun RuntimeChip(s: FrontEndState) = when {
s.busy -> Chip(if (s.percent >= 0) "${s.stage} · ${s.percent}%" else s.stage, ok = false)
!s.ready -> Chip("Runtime installs on first Play", ok = false)
s.available != null && s.available != s.installed -> Chip("Runtime update available", ok = false)
else -> Chip("● Runtime ready", ok = true)
}
/** "Last played 3 days ago" from Steam's unix seconds; null for a game never played. */
private fun lastPlayedText(lastPlayed: Long): String? {
if (lastPlayed <= 0L) return null
val span = android.text.format.DateUtils.getRelativeTimeSpanString(
lastPlayed * 1000L, System.currentTimeMillis(), android.text.format.DateUtils.MINUTE_IN_MILLIS,
).toString()
return "Last played " + span.replaceFirstChar { it.lowercase() }
}
private fun libraryLabel(library: String): String = when (library) {
"internal" -> "Internal storage"
"added" -> "Added game"
else -> library
}
/**
* A game's wide banner: Steam's hero art where the client cached one, else its capsule blurred to
* fill the width. The copy sits bottom-left over a scrim of the ground colour so it always reads;
* the art takes the banner's size, so a banner given a minimum height grows to fit its copy.
*/
@Composable
private fun GameHero(g: Library.SteamGame, modifier: Modifier, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
Box(modifier = modifier.clip(Shape16).background(artBrush(hueOf(g.name)))) {
val image = g.hero ?: g.art
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,
)
}
}
@@ -0,0 +1,261 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.focus.focusRequester
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Image
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
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
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.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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material.icons.outlined.VideoLibrary
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.layout.widthIn
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.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
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 com.droiddeck.launcher.R
import com.droiddeck.launcher.core.PhantomProcessLimit
// The front end's side rail: the page list, the resume entry and the controller hints under it.
/** What the pad's face buttons do here, along the bottom edge as on a console. */
@Composable
internal fun ControllerHints(select: String = "Select", tabs: Boolean = false) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(modifier = Modifier.fillMaxWidth()) {
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(18.dp, Alignment.End),
modifier = Modifier.fillMaxWidth().height(34.dp).background(colors.surface).padding(horizontal = 20.dp),
) {
if (tabs) HintGlyph("LB RB", "Tabs")
HintGlyph("A", select)
HintGlyph("B", "Back")
}
}
}
@Composable
private fun HintGlyph(button: String, action: String) {
val colors = MaterialTheme.colorScheme
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
// Face buttons are round; bumpers are a wider keycap.
val shape = if (button.length == 1) CircleShape else RoundedCornerShape(6.dp)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.height(20.dp).widthIn(min = 20.dp).clip(shape).background(colors.onBackground).padding(horizontal = if (button.length == 1) 0.dp else 6.dp),
) {
Text(button, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.background)
}
Text(action, fontSize = 13.sp, color = colors.onSurfaceVariant)
}
}
internal val AttentionAmber = Color(0xFFFFB547)
/**
* The launcher's sections, always on screen down the left edge: the app is landscape-only, so the
* width a hamburger menu would save is better spent keeping every section one press away.
*/
@Composable
internal fun SideRail(
s: FrontEndState, selected: String,
onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit, a: FrontEndActions, modifier: Modifier,
) {
val colors = MaterialTheme.colorScheme
val compact = LocalConfiguration.current.screenHeightDp < 420
// Under 600dp wide (4:3 and square screens) the labels would cost a fifth of the width.
val iconOnly = isNarrowScreen()
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
) {
Image(painterResource(R.drawable.logo), contentDescription = "DroidDeck", modifier = Modifier.size(if (compact) 28.dp else 34.dp))
Spacer(Modifier.height(if (compact) 6.dp else 12.dp))
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()),
) {
RailItem("Steam", Icons.Outlined.SportsEsports, "steam", selected == "steam", compact, iconOnly, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
// Always there, so the items below it never move; an empty library says how to fill it.
RailItem("Games", Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, onFocus = { onFocusSelect("games") }) { onSelect("games") }
RailItem("Desktop", Icons.Outlined.DesktopWindows, "desktop", selected == "desktop", compact, iconOnly, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
RailItem("Components", Icons.Outlined.Layers, "components", selected == "components", compact, iconOnly, onFocus = { onFocusSelect("components") }) { onSelect("components") }
// Home mode's extra section goes last, so it shifts nothing above it.
if (s.isHomeApp) RailItem("Apps", Icons.Outlined.Apps, "android-apps", selected == "android-apps", compact, iconOnly, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
RailItem("Setup", Icons.Outlined.Tune, "setup", selected == "setup", compact, iconOnly, badge = setupNeedsAttention, onFocus = { onFocusSelect("setup") }) { onSelect("setup") }
}
AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(bottom = 8.dp)) {
val barWidth = if (iconOnly) 44.dp else 60.dp
if (s.percent >= 0) LinearProgressIndicator(progress = { s.percent / 100f }, modifier = Modifier.width(barWidth))
else LinearProgressIndicator(modifier = Modifier.width(barWidth))
Text(if (s.percent >= 0) "${s.percent}%" else if (iconOnly) "…" else "Working", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))
}
}
var lastRunning by remember { mutableStateOf("") }
if (s.running != null) lastRunning = s.running
AnimatedVisibility(
s.running != null,
enter = expandVertically(Motion.sp(0.75f)) + fadeIn(Motion.tw(300)),
exit = shrinkVertically(Motion.tw(220)) + fadeOut(Motion.tw(180)),
) { ResumeRailItem(lastRunning, compact, iconOnly, a.onResume) }
}
}
@Composable
private fun RailItem(
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean,
badge: Boolean = false, onFocus: () -> Unit = {}, onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val frontFocus = LocalFrontFocus.current
val src = remember { MutableInteractionSource() }
val focused by src.collectIsFocusedAsState()
val hovered by src.collectIsHoveredAsState()
val pressed by src.collectIsPressedAsState()
if (frontFocus != null) LaunchedEffect(focused) {
if (focused) {
frontFocus.focusedRail = key
onFocus()
}
else if (frontFocus.focusedRail == key) frontFocus.focusedRail = null
}
val fg by animateColorAsState(
if (current) pal.signal else if (focused || hovered) colors.onBackground else colors.onSurfaceVariant,
Motion.tw(220), label = "railFg",
)
val fill by animateColorAsState(
if (current) pal.signal.copy(alpha = 0.14f) else if (focused || hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent,
Motion.tw(220), label = "railFill",
)
val ring by animateColorAsState(if (focused) pal.signal else Color.Transparent, Motion.tw(180), label = "railRing")
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "railScale")
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.railFor(key)) else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale }
.size(width = if (iconOnly) 52.dp else 80.dp, height = if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
.clip(Shape14)
.background(fill)
.border(2.dp, ring, Shape14)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.then(if (iconOnly) Modifier.semantics { contentDescription = label } else Modifier),
) {
if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp))
else Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) {
Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (compact) 20.dp else 22.dp))
Text(label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = fg, maxLines = 1, softWrap = false)
}
if (badge) Box(
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 7.dp else 8.dp, end = if (iconOnly) 9.dp else 18.dp)
.size(8.dp).clip(CircleShape).background(AttentionAmber),
)
}
}
/** The running session, one press from anywhere in the launcher. */
@Composable
private fun ResumeRailItem(name: String, compact: Boolean, iconOnly: Boolean, onResume: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val focused by src.collectIsFocusedAsState()
val hovered by src.collectIsHoveredAsState()
val pulse = rememberInfiniteTransition(label = "pulse")
val ringScale by pulse.animateFloat(0.4f, 1.6f, infiniteRepeatable(tween(Motion.ms(1600).coerceAtLeast(1), easing = Motion.Ease), RepeatMode.Restart), label = "ring")
// Animations off: the live dot alone, no pulsing ring.
val still = Motion.scale == 0f
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(3.dp),
modifier = Modifier
.padding(top = 6.dp)
.width(if (iconOnly) 52.dp else 80.dp)
.clip(Shape14)
.background(pal.good.copy(alpha = if (focused || hovered) 0.20f else 0.12f))
.border(2.dp, if (focused) pal.signal else Color.Transparent, Shape14)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onResume)
.semantics { contentDescription = "Resume $name" }
.padding(vertical = if (iconOnly) 15.dp else if (compact) 6.dp else 9.dp, horizontal = 4.dp),
) {
Box(modifier = Modifier.size(14.dp), contentAlignment = Alignment.Center) {
if (!still) Box(modifier = Modifier.size(14.dp).graphicsLayer { scaleX = ringScale; scaleY = ringScale; alpha = (1.6f - ringScale) / 1.2f }.border(1.5.dp, pal.good, CircleShape))
Box(modifier = Modifier.size(7.dp).clip(CircleShape).background(pal.good))
}
// Icons only: the live dot alone says something is running; its description says what.
if (!iconOnly) {
Text("Resume", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, softWrap = false)
Text(name, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,434 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.FocusRequester
import android.os.Build
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
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
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.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.PriorityHigh
import androidx.compose.material.icons.outlined.Extension
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.VideogameAsset
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import kotlinx.coroutines.flow.first
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
import com.droiddeck.launcher.session.SessionPrefs
// The Setup page: runtime and device checks, tools, frame generation and launch settings.
private enum class CheckState { OK, WARN, BUSY }
/** One requirement in Setup's system check: a status mark, what it is, and at most one action. */
@Composable
private fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val tint = when (state) {
CheckState.OK -> pal.good
CheckState.WARN -> AttentionAmber
CheckState.BUSY -> pal.signal
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxWidth()
.background(if (state == CheckState.WARN) AttentionAmber.copy(alpha = 0.07f) else Color.Transparent)
.heightIn(min = 60.dp)
.padding(horizontal = 14.dp, vertical = 10.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(28.dp).clip(CircleShape).background(tint.copy(alpha = 0.16f))) {
Icon(
when (state) {
CheckState.OK -> Icons.Filled.Check
CheckState.WARN -> Icons.Filled.PriorityHigh
CheckState.BUSY -> Icons.Filled.Refresh
},
contentDescription = when (state) {
CheckState.OK -> "Done"
CheckState.WARN -> "Needs attention"
CheckState.BUSY -> "Working"
},
tint = tint, modifier = Modifier.size(16.dp),
)
}
Column(modifier = Modifier.weight(1f)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
if (detail != null) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
if (action != null) action()
}
if (divider) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
@Composable
internal fun SetupPanel(
s: FrontEndState,
a: FrontEndActions,
onOpenDeveloperOptions: () -> Unit,
onRequestWirelessAdb: (Boolean) -> Unit,
) {
val host = rememberMenuHost()
var processLimitBusy by remember { mutableStateOf(false) }
var processLimitMessage by remember { mutableStateOf<String?>(null) }
val setProcessLimit: (Boolean) -> Unit = { enabled ->
processLimitBusy = true
processLimitMessage = null
a.onSetPhantomProcessLimit(enabled) { error ->
processLimitBusy = false
if (error == null) {
a.onRefreshPhantomStatus()
} else {
processLimitMessage = "Check the Wireless debugging IP address & Port, or pair again if Android removed this device."
onRequestWirelessAdb(enabled)
}
}
}
val runtime = when {
s.busy -> "Working…"
!s.ready -> "Install"
s.available != null && s.available != s.installed -> "Update"
else -> "Manage"
}
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val gpuOk = remember { DeviceSupport.adreno() }
val gpuName = remember { DeviceSupport.gpuName() }
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val signedIn = s.offlineAccount != null
var showLimitDetails by rememberSaveable { mutableStateOf(false) }
val checks = 4
val readyCount = listOf(gpuOk, s.ready && !s.busy, !limitBlocks, signedIn).count { it }
// Five tabs instead of one long scroll; LB and RB turn them from anywhere on the page.
val tabs = listOf("Overview", "Controller", "Session", "Launcher", "About")
var tab by rememberSaveable { mutableStateOf(0) }
val tabFocus = remember { List(tabs.size) { FocusRequester() } }
var tabTurned by remember { mutableStateOf(false) }
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true }
val inputModeManager = LocalInputModeManager.current
// The control a controller was on went with the old tab: it lands on the new tab itself.
LaunchedEffect(tab) {
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
androidx.compose.runtime.withFrameNanos { }
runCatching { tabFocus[tab].requestFocus() }
}
}
Rise(0, Modifier.fillMaxSize()) {
Column(
modifier = Modifier.fillMaxSize().bumpers(
onPrevious = { pick((tab + tabs.size - 1) % tabs.size) },
onNext = { pick((tab + 1) % tabs.size) },
),
) {
PageHeader("Setup") {
Chip(if (readyCount == checks) "● All set" else "$readyCount of $checks ready", ok = readyCount == checks)
}
TabStrip(tabs, tab, pick, Modifier.padding(bottom = 4.dp), tabFocus)
Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
when (tab) {
0 -> {
SectionTitle("System check", null)
// What Steam needs, one row each: green when done, one button when not. The
// process-limit controls only open under their row.
Column(modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
CheckRow(
if (gpuOk) CheckState.OK else CheckState.WARN,
if (gpuOk) "Device supported" else "GPU not supported",
if (gpuOk) gpuName else "Steam draws with an Adreno driver; $gpuName may show a black screen",
)
CheckRow(
when { s.busy -> CheckState.BUSY; !s.ready -> CheckState.WARN; else -> CheckState.OK },
"Linux runtime",
when {
s.busy -> if (s.percent >= 0) "${s.stage} · ${s.percent}%" else s.stage
!s.ready -> "Not installed · about 3 GB, installed on the first Play"
s.available != null && s.available != s.installed -> "${s.installed ?: "Installed"} · update available"
else -> "${s.installed ?: "Installed"} · up to date"
},
) { SecondaryButton(runtime, enabled = !s.busy, compact = true, onClick = a.onRuntime) }
CheckRow(
if (limitBlocks) CheckState.WARN else CheckState.OK,
"Child-process limit",
when (s.phantomProcessStatus) {
PhantomProcessStatus.ENABLED -> "On · Android may close Steam. Turning it off takes a minute"
PhantomProcessStatus.UNSET -> "Not set · the ROM default may close Steam. Turning it off takes a minute"
PhantomProcessStatus.UNREADABLE -> "Could not be checked · turning it off takes a minute"
else -> PhantomProcessLimit.title(s.phantomProcessStatus)
},
) {
if (limitBlocks) PrimaryButton(if (showLimitDetails) "Hide" else "Fix it", compact = true) { showLimitDetails = !showLimitDetails }
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
SecondaryButton(if (showLimitDetails) "Hide" else "Details", compact = true) { showLimitDetails = !showLimitDetails }
}
}
AnimatedVisibility(showLimitDetails, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
// One sentence and at most three buttons. The computer route and its
// raw command live on the full page Wireless debugging opens.
Column(modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, top = 4.dp, bottom = 10.dp)) {
Text(
if (limitBlocks) PhantomProcessLimit.gateInstructions(s.phantomProcessStatus)
else PhantomProcessLimit.instructions(s.phantomProcessStatus),
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
)
Actions {
if (limitBlocks) {
PrimaryButton("Developer options", compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton("Use Wireless debugging", compact = true, enabled = !processLimitBusy) { setProcessLimit(false) }
SecondaryButton("Check again", compact = true, onClick = a.onRefreshPhantomStatus)
} else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
SecondaryButton("Turn limit on", compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
}
}
if (processLimitBusy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp))
processLimitMessage?.let { Text(it, fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp)) }
}
}
CheckRow(
if (signedIn) CheckState.OK else CheckState.WARN,
"Steam account",
s.offlineAccount?.let { if (s.offline) "Signed in as $it · offline mode" else "Signed in as $it" } ?: "Press Play and sign in to Steam",
divider = false,
)
}
SectionTitle("Tools", null)
ToolGrid(s, a)
}
1 -> {
val controller = s.controller
if (controller != null && a.controller != null) SettingsGroup("Controller") {
ControllerRows(host, s.oscMode, controller, a.controller)
}
if (s.controller == null || a.controller == null) Note("Controller settings are unavailable.")
}
2 -> {
SettingsGroup("Session") {
ChoiceRow(
host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted),
listOf(
false to SessionPrefs.BACK_MENU_THEN_QAM,
true to SessionPrefs.BACK_QAM_THEN_MENU,
), s.backActionsInverted, onPick = a.onBackActionsInverted,
)
SettingsRow("Frame generation", "Select the frame generation mode") {
Box {
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
FrameGenMenu(s, a, host)
}
}
ToggleRow(host, "logs", "Session logs", "Saved after each session", s.logsEnabled) { a.onLogs() }
ActionRow("Latest session logs", "Send them with a bug report", "Share logs", a.onShareLogs)
ToggleRow(
host, "offline", "Offline mode",
s.offlineAccount?.let { "Signed in as $it" } ?: "Sign in to Steam first",
s.offline, enabled = s.offlineAccount != null,
) { a.onOffline() }
}
}
3 -> {
SettingsGroup("Launcher") {
SettingsRow("Theme", "Choose the launcher appearance") {
Box {
ValueChip(Themes.byId(s.theme).label, host.open == "theme") { host.open = if (host.open == "theme") null else "theme" }
AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = "Theme") { firstItemFocus ->
Themes.all.forEachIndexed { index, theme ->
MenuItem(theme.label, checked = s.theme == theme.id, focusRequester = if (index == 0) firstItemFocus else null) {
a.onTheme(theme.id)
host.open = null
}
}
}
}
}
ToggleRow(
host, "home-screen", "Use as a Home screen",
if (s.homeScreenEnabled) "DroidDeck can be the phone's Home app" else "Off: DroidDeck is never offered as a Home app",
s.homeScreenEnabled,
) { a.onHomeScreen(it) }
ToggleRow(
host, "launcher-fullscreen", "Fullscreen",
if (s.launcherFullscreen) "Hide the Android status and navigation bars" else "Show the Android status and navigation bars",
s.launcherFullscreen,
) { a.onLauncherFullscreen(it) }
if (s.homeScreenEnabled) {
ActionRow("Default Home app", s.defaultHomeLabel ?: "Choose a Home app", "Choose", a.onHomeApp)
}
}
}
else -> {
SettingsGroup("About") {
ActionRow("Build", s.buildLabel, "Check for newer", a.onCheckLatestBuild)
ActionRow("Credits", "The people and projects DroidDeck builds on", "View", a.onCredits)
}
}
}
}
}
}
}
/** The launcher's own tools as cards: four across, two by two on a narrow page. */
@Composable
private fun ToolGrid(s: FrontEndState, a: FrontEndActions) {
val columns = if (LocalNarrowPane.current) 2 else 4
val tools = listOf(
ToolSpec(Icons.Outlined.Folder, "Files", "Browse and manage files", a.onFiles),
ToolSpec(Icons.Outlined.Extension, "Proton versions", "Install ARM64 Proton builds", a.onProtons),
ToolSpec(Icons.Outlined.Speed, "Performance", "CPU core assignment", a.onPerformance),
ToolSpec(Icons.Outlined.VideogameAsset, "ROMs folder", s.romsDir ?: "Choose where emulator games are stored", a.onRoms),
)
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
for (row in tools.chunked(columns)) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
for (t in row) ToolCard(t, Modifier.weight(1f).fillMaxHeight())
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
}
}
private class ToolSpec(val icon: ImageVector, val title: String, val detail: String, val onClick: () -> Unit)
@Composable
private fun ToolCard(t: ToolSpec, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.97f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "toolScale")
Column(
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = modifier.paneItem("tool:${t.title}")
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(Shape14)
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, Shape14)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = t.onClick)
.controllerConfirm(onClick = t.onClick)
.padding(horizontal = 14.dp, vertical = 12.dp),
) {
Icon(t.icon, contentDescription = null, tint = if (hot) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
Text(t.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(t.detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
@Composable
private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
FrameGenMenu(host, s.frameGenEngine, s.frameGenMultiplier, s.lsfgReady, a.onFrameGenPick)
}
/**
* What shapes a launch, beside the game rather than three screens away in Setup. They are the
* app-wide settings - each card opens the same page or menu Setup does.
*/
@Composable
internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
// Three across, two on a narrow page; each row's cards share one height.
val columns = if (LocalNarrowPane.current) 2 else 3
val controller = a.controller
val cards = buildList<@Composable (Modifier) -> Unit> {
add { m -> SettingCard("Components", "FEX, DXVK, VKD3D", "card:components", m) { a.onComponents(true) } }
add { m ->
Box(m) {
SettingCard("Frame generation", s.frameGenLabel, "card:fg", Modifier.fillMaxSize()) {
host.open = if (host.open == "fg") null else "fg"
}
FrameGenMenu(s, a, host)
}
}
if (controller != null) add { m -> SettingCard("Controls", "Button mapping", "card:controls", m, controller.onMapping) }
}
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
for (row in cards.chunked(columns)) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
for (card in row) card(Modifier.weight(1f).fillMaxHeight())
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
}
}
@Composable
private fun SettingCard(label: String, value: String, id: String, modifier: Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.97f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "cardScale")
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(220), label = "cardEdge")
Column(
verticalArrangement = Arrangement.spacedBy(3.dp),
modifier = modifier.paneItem(id)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(Shape14)
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.border(if (hot) 2.dp else 1.dp, edge, Shape14)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 12.dp),
) {
Text(label, fontSize = 13.sp, color = if (hot) pal.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(value, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@@ -0,0 +1,237 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import android.provider.Settings
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
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.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
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.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.ChevronLeft
import androidx.compose.ui.graphics.vector.ImageVector
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.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.semantics.Role
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
// Small building blocks shared by the front end's pages: text styles, chips and buttons.
internal val Shape14 = RoundedCornerShape(14.dp)
@Composable
internal fun Eyebrow(t: String) {
val pal = LocalPalette.current
val rule = remember { Animatable(0f) }
LaunchedEffect(Unit) { rule.animateTo(1f, Motion.tw(600, 120)) }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Box(modifier = Modifier.width(18.dp).height(1.5.dp).graphicsLayer { scaleX = rule.value; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0f, 0.5f) }.background(pal.signal))
Text(t.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = pal.signal)
}
}
@Composable internal fun Title(t: String) = Text(t, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(top = 4.dp, bottom = 4.dp))
@Composable internal fun Lede(t: String) = Text(t, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 12.dp))
@Composable
internal fun SectionTitle(t: String, detail: String?) {
val colors = MaterialTheme.colorScheme
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 8.dp)) {
Text(t.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant)
if (detail != null) Text(detail, fontSize = 12.sp, color = colors.onBackground)
Box(modifier = Modifier.weight(1f).height(1.dp).background(LocalPalette.current.line))
}
}
@Composable internal fun Note(t: String) = Text(t, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.fillMaxWidth().clip(Shape12).background(MaterialTheme.colorScheme.surface).border(1.dp, LocalPalette.current.line2, Shape12).padding(12.dp))
/** A page's buttons: they wrap onto a second line rather than run off a narrow page. */
@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun Actions(content: @Composable () -> Unit) = FlowRow(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) { content() }
/** A status chip in a row of buttons, centred on their height. */
@Composable
internal fun ActionChip(t: String, ok: Boolean) = Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok) }
internal val Shape16 = RoundedCornerShape(16.dp)
/** One level up, as Back and B do: a real button, big enough to hit ([compact]: for the tightest layouts). */
@Composable
internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(22.dp)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.paneItem("back:$label").heightIn(min = if (compact) 44.dp else 48.dp)
.clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.04f))
.border(2.dp, if (hot) pal.signal else Color.Transparent, shape)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(start = 8.dp, end = 16.dp),
) {
Icon(Icons.Filled.ChevronLeft, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(22.dp))
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@Composable
internal fun Chip(t: String, ok: Boolean) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Text(
t, fontSize = 12.sp, color = if (ok) pal.good else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.clip(RoundedCornerShape(99.dp)).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, RoundedCornerShape(99.dp)).padding(horizontal = 9.dp, vertical = 4.dp),
)
}
@Composable
internal fun rememberHot(src: MutableInteractionSource): Boolean = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
@Composable
internal fun PrimaryButton(
text: String,
enabled: Boolean = true,
main: Boolean = false,
compact: Boolean = false,
modifier: Modifier = Modifier,
/** The Steam tab's own Play: bigger than any other button on a page. */
large: Boolean = false,
icon: ImageVector? = null,
onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
// The page's main button is where the pane is entered from the rail.
val frontFocus = if (main) LocalFrontFocus.current else null
if (frontFocus != null) DisposableEffect(Unit) {
frontFocus.primaryAttached++
onDispose { frontFocus.primaryAttached-- }
}
val track = (if (frontFocus == null) Modifier.paneItem("btn:$text") else Modifier).downToFirstTile()
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) && enabled
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "btnScale")
val lift by animateFloatAsState(if (hot) 14f else 6f, Motion.tw(300), label = "btnLift")
// Where it sits, so a session it starts can grow out of it (LaunchFlood).
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier.then(track)
.onGloballyPositioned { placed[0] = it }
// 48dp to touch on a handheld; compact rows keep 44.
.heightIn(min = if (compact) 44.dp else 48.dp)
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.primary).onFocusChanged { if (it.isFocused) frontFocus.last = FrontFocus.PRIMARY } else Modifier)
.graphicsLayer { alpha = if (LaunchOrigin.flooding === placed) 0f else 1f; scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
.clip(Shape12)
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
.shine(hot, 0.45f)
// The grow and shine alone barely show on the light fill: outline it when a
// controller is on it, as the other controls are.
.border(2.dp, if (hot) pal.signal else Color.Transparent, Shape12)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled) {
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
onClick()
}
.padding(
start = if (large) 20.dp else if (compact) 10.dp else if (icon != null) 14.dp else 18.dp,
end = if (large) 26.dp else if (compact) 10.dp else 18.dp,
top = if (large) 16.dp else if (compact) 7.dp else 11.dp,
bottom = if (large) 16.dp else if (compact) 7.dp else 11.dp,
),
) {
val fg = if (enabled) colors.onPrimary else colors.onSurfaceVariant
if (icon != null) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (large) 20.dp else 17.dp))
Text(
text, fontSize = if (large) 17.sp else if (compact) 12.sp else 15.sp,
fontWeight = if (large) FontWeight.Bold else FontWeight.SemiBold, letterSpacing = 0.5.sp, color = fg, maxLines = 1,
)
}
}
@Composable
internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boolean = false, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) && enabled
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "secScale")
val pal = LocalPalette.current
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "secEdge")
val fill by animateColorAsState(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f), Motion.tw(250), label = "secFill")
Box(
contentAlignment = Alignment.Center,
modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = if (compact) 10.dp else 16.dp, vertical = if (compact) 7.dp else 11.dp),
) { Text(text, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) }
}
@Composable
internal fun Cog(size: androidx.compose.ui.unit.Dp = 48.dp, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val rot by animateFloatAsState(if (hot) 90f else 0f, Motion.sp(0.55f), label = "cog")
val pal = LocalPalette.current
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "cogEdge")
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("cog").downToFirstTile().size(size).clip(if (size > 48.dp) Shape14 else Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, if (size > 48.dp) Shape14 else Shape12)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick),
) { Icon(Icons.Filled.Settings, "Settings", tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(if (size > 48.dp) 20.dp else 18.dp).rotate(rot)) }
}
@@ -0,0 +1,174 @@
package com.droiddeck.launcher.ui
import android.os.SystemClock
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import kotlin.math.hypot
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.delay
import kotlinx.coroutines.coroutineScope
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.runtime.snapshotFlow
import androidx.compose.animation.core.spring
// Starting a session from a blue button: the button grows until the page is its blue, and the
// loading screen opens on that blue and gathers it into the ball of the throbber.
/** Carries the flood's colour to the session, which opens on it. */
const val EXTRA_FLOOD = "com.droiddeck.launcher.FLOOD"
/** Where the last pressed blue button sat, so a session started by it can grow out of it. */
internal object LaunchOrigin {
private var bounds: Rect? = null
private var button: Any? = null
private var at = 0L
/** The button a flood is growing out of: it steps aside so only the flood shows. */
var flooding by mutableStateOf<Any?>(null)
fun mark(r: Rect, key: Any) {
bounds = r
button = key
at = SystemClock.uptimeMillis()
}
/** The button behind a launch starting now, if one was pressed just before; it hides for the flood. */
fun take(): Rect? {
val b = bounds?.takeIf { SystemClock.uptimeMillis() - at < 1_500 }
if (b != null) flooding = button
bounds = null
button = null
return b
}
}
/** The page a flood grows over, sinking back a touch as it is covered; [progress] is the flood's. */
@Composable
internal fun FloodBehind(progress: () -> Float, content: @Composable () -> Unit) {
Box(Modifier.fillMaxSize().graphicsLayer { val k = sinkScale(progress()); scaleX = k; scaleY = k }) { content() }
}
private fun sinkScale(progress: Float) = 1f - 0.04f * progress
private val Gather = CubicBezierEasing(0.6f, 0f, 0.15f, 1f)
/**
* The pressed button, [from] in root px, stretching out to cover the page. Each edge rides its own
* loose spring: the ones with furthest to go set off first and quickest, the ones near the page's
* edge lag and then snap after them, so it pulls like something elastic rather than zooming. It
* goes blobby in flight, its gradient settles into the flat blue of the ball, and [onProgress]
* (0 to 1) lets the page behind sink a little. Calls [onCovered] once nothing but blue shows.
* Swallows touches while it runs.
*/
@Composable
internal fun LaunchFlood(from: Rect, onProgress: (Float) -> Unit, onCovered: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
// Left, top, right, bottom: 0 on the button, 1 on the page's edge. Springs overshoot past the
// edge, off the page, so the wobble is felt in the pull and never seen as a shrink.
val edges = remember { List(4) { Animatable(0f) } }
val covered by rememberUpdatedState(onCovered)
val progress by rememberUpdatedState(onProgress)
var page by remember { mutableStateOf(Size.Zero) }
LaunchedEffect(page != Size.Zero) {
if (page == Size.Zero) return@LaunchedEffect
val travel = listOf(from.left, from.top, page.width - from.right, page.height - from.bottom).map { it.coerceAtLeast(0f) }
val far = travel.max().coerceAtLeast(1f)
coroutineScope {
val runs = edges.mapIndexed { i, edge ->
val lead = travel[i] / far
launch {
delay(Motion.ms((180 * (1f - lead)).toInt()).toLong())
edge.animateTo(1f, spring(dampingRatio = 0.48f, stiffness = lerp(110f, 190f, lead))) {
progress(edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f)
}
}
}
// Covered once every edge has reached the page's, the first time round.
snapshotFlow { edges.all { it.value >= 0.995f } }.first { it }
covered()
runs.forEach { it.join() }
}
}
Canvas(Modifier.fillMaxSize().onSizeChanged { page = Size(it.width.toFloat(), it.height.toFloat()) }.pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) {
val (l, t, r, b) = edges.map { it.value }
val mean = edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f
// The button sinks with the page behind (FloodBehind), so the flood leaves from where it is now.
val k = sinkScale(mean)
val cx = size.width / 2f
val cy = size.height / 2f
val left = lerp(cx + (from.left - cx) * k, 0f, l)
val top = lerp(cy + (from.top - cy) * k, 0f, t)
val right = lerp(cx + (from.right - cx) * k, size.width, r)
val bottom = lerp(cy + (from.bottom - cy) * k, size.height, b)
val w = (right - left).coerceAtLeast(0f)
val h = (bottom - top).coerceAtLeast(0f)
// A button's corners at rest, a blob in flight, square once it fills the page.
val blob = kotlin.math.sin(Math.PI * mean).toFloat().coerceAtLeast(0f)
val corner = lerp(12.dp.toPx() * (1f - mean), minOf(w, h) * 0.42f, blob)
// The button's gradient gives way to the ball's flat blue in the first half.
val mix = (mean * 2f).coerceAtMost(1f)
drawRoundRect(
Brush.linearGradient(
listOf(lerp(colors.primary, pal.signal, mix), lerp(pal.primary2, pal.signal, mix)),
start = Offset(left, top), end = Offset(right, bottom),
),
topLeft = Offset(left, top), size = Size(w, h), cornerRadius = CornerRadius(corner),
)
}
}
/**
* The session's first frames: the page in [flood], drawing in to a circle over [ball] (centre and
* radius in root px, once the throbber is laid out) that lands the size of it. Calls [onLanded] then.
*/
@Composable
internal fun FloodGather(flood: Color, ball: Pair<Offset, Float>?, onLanded: () -> Unit) {
val gather = remember { Animatable(0f) }
var started by remember { mutableStateOf(false) }
val landed by rememberUpdatedState(onLanded)
LaunchedEffect(ball != null) {
if (ball == null || started) return@LaunchedEffect
started = true
// A beat of plain blue first, so the change of screen does not read as a cut.
delay(Motion.ms(90).toLong())
gather.animateTo(1f, tween(Motion.ms(640).coerceAtLeast(1), easing = Gather))
landed()
}
Canvas(Modifier.fillMaxSize().pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) {
val b = ball
if (b == null) {
drawRect(flood)
return@Canvas
}
val (c, r) = b
val far = maxOf(hypot(c.x, c.y), hypot(size.width - c.x, c.y), hypot(c.x, size.height - c.y), hypot(size.width - c.x, size.height - c.y))
drawCircle(flood, radius = lerp(far, r, gather.value), center = c)
}
}
@@ -0,0 +1,20 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
// Sizes that decide how the launcher reflows on 4:3 and square screens (480x360 or 480x480 dp) as
// well as on the 16:9 ones it was first laid out for.
/** A page narrower than this reflows: settings rows stack, grids drop columns, posters go. */
val NarrowPaneWidth = 520.dp
/** Whether the page being drawn is narrow - the pane beside the rail on a 4:3 or square screen. */
val LocalNarrowPane = compositionLocalOf { false }
/** Too narrow a screen for a labelled rail: the rail shows icons only. */
@Composable
internal fun isNarrowScreen(): Boolean = LocalConfiguration.current.screenWidthDp < 600
@@ -66,6 +66,8 @@ class ModeSettings(
val forceFullscreen: Boolean? = null,
/** Steam only: the client branch forced on the command line. */
val steamChannel: String? = null,
/** Steam only: start a Steam session when DroidDeck opens. */
val runSteamAtStartup: Boolean = false,
/** Steam only: the user's chosen Games folders; null outside Steam. */
val addedGamesDirs: List<String>? = null,
val addedGames: List<AddedGameRow> = emptyList(),
@@ -119,6 +121,7 @@ class ModeSettingsActions(
val onFexPreset: (String) -> Unit = {},
val onForceFullscreen: (Boolean) -> Unit = {},
val onSteamChannel: (String) -> Unit = {},
val onRunSteamAtStartup: (Boolean) -> Unit = {},
val onPickAddedGamesDir: () -> Unit = {},
val onForgetAddedGamesDir: (path: String) -> Unit = {},
val onAddedGamesArt: (Boolean) -> Unit = {},
@@ -273,6 +276,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
onPick = a.onSuspendPolicy,
)
}
if (steam) SettingsGroup("Startup") {
ToggleRow(
host, "steam-startup", "Run Steam when DroidDeck starts",
"Open the Steam session when you launch DroidDeck.",
s.runSteamAtStartup, onChange = a.onRunSteamAtStartup,
)
}
if (steam) SettingsGroup("Decky") {
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
s.deckyInstalled != s.deckyLatestRelease.tag
@@ -0,0 +1,183 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
@Composable
fun PhantomProcessGatePage(
status: PhantomProcessStatus,
onDismiss: () -> Unit,
onOpenDeveloperOptions: () -> Unit,
onSetUpWirelessAdb: () -> Unit,
) {
BackHandler(onBack = onDismiss)
BoxWithConstraints(Modifier.fillMaxWidth()) {
val compact = maxWidth < 620.dp && maxHeight < 500.dp
SettingsPage(
host = rememberMenuHost(),
title = if (compact) "Steam paused" else "Steam cannot start yet",
eyebrow = "Steam",
lede = if (compact) compactStatus(status) else "${PhantomProcessLimit.title(status)} · checking again every two seconds",
onBack = onDismiss,
// Scrolls, so the larger text never pushes the ADB command off a short screen.
scrollContent = true,
compactLayout = compact,
) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 620.dp
Column(
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
when {
compact -> CompactGateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
wide -> Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth()) {
Column(Modifier.weight(1f)) {
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
}
Column(Modifier.weight(1f)) { AdbFallback() }
}
else -> {
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
AdbFallback()
}
}
}
}
}
}
}
private fun compactStatus(status: PhantomProcessStatus): String {
val state = when (status) {
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
PhantomProcessStatus.UNREADABLE -> "Child-process limit is unreadable"
else -> PhantomProcessLimit.title(status)
}
return "$state · retrying every 2 sec"
}
@Composable
private fun CompactGateInstructions(
status: PhantomProcessStatus,
onOpenDeveloperOptions: () -> Unit,
onSetUpWirelessAdb: () -> Unit,
) {
SettingsGroup("1 · Developer options", compact = true) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 7.dp),
verticalArrangement = Arrangement.spacedBy(5.dp),
) {
Text(
PhantomProcessLimit.gateInstructions(status),
style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton("Use Wireless debugging", compact = true, onClick = onSetUpWirelessAdb)
}
}
}
SettingsGroup("3 · Computer ADB last resort", compact = true) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp),
verticalArrangement = Arrangement.spacedBy(3.dp),
) {
Text(
"If the setting is missing and Wireless debugging is unavailable, run this from a computer:",
style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
PhantomProcessLimit.ADB_COMMAND,
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
private fun GateInstructions(
status: PhantomProcessStatus,
onOpenDeveloperOptions: () -> Unit,
onSetUpWirelessAdb: () -> Unit,
) {
SettingsGroup("1 · Developer options first") {
Column(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
PhantomProcessLimit.gateInstructions(status),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions)
SecondaryButton("Use Wireless debugging", onClick = onSetUpWirelessAdb)
}
}
}
@Composable
private fun AdbFallback() {
SettingsGroup("3 · Computer ADB last resort") {
Column(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
"Use this only if Developer options has no setting and Wireless debugging is unavailable. Connect this device to a computer with ADB and run:",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
Text(
PhantomProcessLimit.ADB_COMMAND,
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
fun DeveloperDisplayChoiceDialog(
displays: List<Pair<Int, String>>,
onMainScreen: () -> Unit,
onSecondaryScreen: (Int) -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Open Developer options") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
Text("Choose which display to open Android Settings on.")
TextButton(modifier = Modifier.fillMaxWidth(), onClick = onMainScreen) { Text("Main screen") }
displays.forEach { (id, label) ->
TextButton(modifier = Modifier.fillMaxWidth(), onClick = { onSecondaryScreen(id) }) { Text(label) }
}
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@@ -33,7 +33,7 @@ fun ProtonPage(
val colors = MaterialTheme.colorScheme
SettingsPage(
host,
title = "Compatibility tools",
title = "Proton versions",
eyebrow = "Setup",
lede = "Download and install an ARM64 Proton build now, then select it per game in Steam > Properties > Compatibility.",
onBack = onBack,
@@ -70,7 +70,7 @@ fun ProtonPage(
if (busyId == row.id) Column(modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 10.dp)) {
Text(
if (stage != null && percent >= 0) "$stage · $percent%" else stage ?: "Starting…",
fontSize = 11.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 5.dp),
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 5.dp),
)
if (percent >= 0) LinearProgressIndicator(progress = { percent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
@@ -0,0 +1,313 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.runtime.produceState
import androidx.compose.runtime.key
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.runtime.remember
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import com.droiddeck.launcher.frontend.Library
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.material.icons.Icons
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.icons.filled.Pause
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.Icon
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.border
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
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
// The session's loading screen, its paused screen and the HUD text style.
@Composable
fun HudText(text: String) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) {
Text(
text,
fontFamily = FontFamily.Monospace,
fontSize = 12.sp,
color = Color.White,
modifier = Modifier
.padding(12.dp)
.background(Color(0x8C000000))
.padding(horizontal = 8.dp, vertical = 3.dp),
)
}
}
/** One line of the loading screen's checklist; [detail] is what it says while it is the one running. */
private class LoadStage(val label: String, val detail: String)
private fun loadStages(steam: Boolean): List<LoadStage> = if (steam) listOf(
LoadStage("Linux runtime", "Getting the Linux runtime ready"),
LoadStage("Session", "Starting the display and audio"),
LoadStage("Steam client", "Checking the Steam client and its compatibility tools"),
LoadStage("Opening Steam", "Waiting for Steam's first frame"),
) else listOf(
LoadStage("Linux runtime", "Getting the Linux runtime ready"),
LoadStage("Desktop", "Getting the desktop ready"),
LoadStage("Opening", "Waiting for the first frame"),
)
/**
* The checklist stage a loading line belongs to, -1 when it says nothing about the stage. The lines
* are the session script's "== STEP" milestones and the installer's own progress; they arrive in
* order, and the screen never steps back.
*/
private fun stageOf(step: String, steam: Boolean): Int {
val t = step.lowercase()
return when {
"linux runtime" in t -> 0
"starting the session" in t -> 1
!steam && "desktop" in t -> 1
steam && "starting the steam client" in t -> 3
steam && ("steam" in t || "client" in t || "proton" in t || "library" in t || "compatibility" in t) -> 2
else -> -1
}
}
/** Download and install lines are worth reading as they are; the script's own notes are not. */
private fun readableStep(step: String): Boolean {
val t = step.lowercase()
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
}
@Composable
fun LoadingOverlay(
step: String, percent: Int, elapsed: String, hint: String, ended: Boolean,
title: String = "Starting Steam", steam: Boolean = true, onCancel: (() -> Unit)? = null,
/** An ended session's exit status and log path, shown small under the advice. */
endedDetail: String? = null,
onRetry: (() -> Unit)? = null,
onShareLogs: (() -> Unit)? = null,
onClose: (() -> Unit)? = null,
/** The blue the page opens on when a button flooded to it, gathered into the throbber's ball. */
flood: Color? = null,
onFlooded: () -> Unit = {},
) {
val colors = MaterialTheme.colorScheme
var ball by remember { mutableStateOf<Pair<Offset, Float>?>(null) }
val stages = remember(steam) { loadStages(steam) }
var reached by remember { mutableStateOf(0) }
LaunchedEffect(step, steam) {
val at = stageOf(step, steam)
if (at > reached) reached = at
}
val active = reached.coerceAtMost(stages.lastIndex)
val detail = if (percent >= 0 || readableStep(step)) step.replaceFirstChar { it.uppercase() } else stages[active].detail
val context = LocalContext.current
// The Steam tab's wall behind it, dimmed and slowed: starting Steam reads as the same place settling in.
val games by produceState(emptyList<Library.SteamGame>()) {
value = withContext(Dispatchers.IO) { runCatching { Library.steamGames(context).sortedByDescending { it.lastPlayed } }.getOrDefault(emptyList()) }
}
Box(
modifier = Modifier
.fillMaxSize()
.background(colors.background)
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {},
) {
CapsuleWall(games, driftMs = 65_000, modifier = Modifier.alpha(0.3f))
Box(
Modifier.fillMaxSize().drawBehind {
drawRect(
Brush.radialGradient(
0f to colors.background.copy(alpha = 0.94f),
0.6f to colors.background.copy(alpha = 0.72f),
1f to colors.background.copy(alpha = 0.55f),
center = Offset(size.width / 2f, size.height * 0.46f), radius = maxOf(size.width, size.height) * 0.55f,
),
)
},
)
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.7f to Color.Transparent, 1f to colors.background.copy(alpha = 0.95f))))
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.align(Alignment.Center).verticalScroll(rememberScrollState()).padding(horizontal = 32.dp, vertical = 24.dp),
) {
// Held on the plain D while the flood gathers, and started fresh when it lands.
key(flood == null) {
LogoThrobber(
Modifier.width(if (ended) 88.dp else 110.dp).onGloballyPositioned { ball = throbberBall(it.boundsInRoot()) },
running = !ended && flood == null,
)
}
Spacer(Modifier.height(30.dp))
Text(
if (ended) "The session ended" else title, fontSize = 20.sp, fontWeight = FontWeight.SemiBold,
color = colors.onBackground, textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis,
)
Text(
if (ended) step else detail, fontSize = 14.sp, lineHeight = 20.sp, color = colors.onSurfaceVariant, textAlign = TextAlign.Center,
maxLines = if (ended) 12 else 2, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 6.dp).widthIn(max = 520.dp),
)
if (!ended) LoadSegments(stages.size, active, percent, Modifier.padding(top = 18.dp))
if (ended && endedDetail != null) Text(
endedDetail, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant.copy(alpha = 0.8f),
textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 12.dp).widthIn(max = 520.dp),
)
if (ended) EndedActions(onRetry, onShareLogs, onClose)
}
if (!ended && hint.isNotEmpty()) Text(
hint, fontSize = 13.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant.copy(alpha = 0.8f), textAlign = TextAlign.Center,
maxLines = 3, overflow = TextOverflow.Ellipsis,
modifier = Modifier.align(Alignment.BottomCenter).padding(start = 120.dp, end = 120.dp, bottom = 28.dp),
)
if (!ended && onCancel != null) CancelHint(onCancel, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 16.dp))
if (flood != null) FloodGather(flood, ball, onFlooded)
}
}
/** What to do about an ended session: nothing leaves on a timer, and the pad starts on Try again. */
@Composable
private fun EndedActions(onRetry: (() -> Unit)?, onShareLogs: (() -> Unit)?, onClose: (() -> Unit)?) {
val first = remember { FocusRequester() }
LaunchedEffect(Unit) {
androidx.compose.runtime.withFrameNanos { }
runCatching { first.requestFocus() }
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(top = 22.dp)) {
var firstUsed = false
fun claim(): Modifier = if (firstUsed) Modifier else { firstUsed = true; Modifier.focusRequester(first) }
if (onRetry != null) PrimaryButton("Try again", modifier = claim(), onClick = onRetry)
if (onShareLogs != null) SecondaryButton("Share logs", modifier = claim(), onClick = onShareLogs)
if (onClose != null) SecondaryButton("Back", modifier = claim(), onClick = onClose)
}
}
/** One segment per stage: done ones filled, the current one filling (or running, with no percent). */
@Composable
private fun LoadSegments(count: Int, active: Int, percent: Int, modifier: Modifier = Modifier) {
val pal = LocalPalette.current
val track = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.12f)
val run = rememberInfiniteTransition(label = "segment")
.animateFloat(-0.4f, 1f, infiniteRepeatable(tween(Motion.ms(1300).coerceAtLeast(1), easing = FastOutSlowInEasing)), label = "run")
val still = Motion.scale == 0f
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = modifier.semantics { contentDescription = "Step ${active + 1} of $count" },
) {
repeat(count) { i ->
Box(
Modifier.width(44.dp).height(3.dp).clip(RoundedCornerShape(2.dp))
.background(if (i < active) pal.signal else track)
.drawBehind {
if (i != active) return@drawBehind
if (percent >= 0) drawRect(pal.signal, size = Size(size.width * percent.coerceIn(0, 100) / 100f, size.height))
else if (still) drawRect(pal.signal.copy(alpha = 0.5f))
else drawRect(pal.signal, topLeft = Offset(size.width * run.value, 0f), size = Size(size.width * 0.4f, size.height))
},
)
}
}
}
/** Cancel as the pad's B, in the corner; a tap works too. */
@Composable
private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
val src = remember { MutableInteractionSource() }
val hot = src.collectIsHoveredAsState().value || src.collectIsFocusedAsState().value
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(22.dp))
.background(if (hot) colors.onBackground.copy(alpha = 0.08f) else Color.Transparent)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onCancel)
.padding(horizontal = 12.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).clip(CircleShape).background(colors.onBackground)) {
Text("B", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.background)
}
Text("Cancel", fontSize = 13.sp, color = colors.onSurfaceVariant)
}
}
/** A session paused in the background, ready to pick up where it left off. */
@Composable
fun SessionPausedOverlay(title: String = "Steam is paused", onResume: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val interactionSource = remember { MutableInteractionSource() }
val resumeFocus = remember { FocusRequester() }
LaunchedEffect(Unit) {
androidx.compose.runtime.withFrameNanos { }
runCatching { resumeFocus.requestFocus() }
}
Box(
modifier = Modifier
.fillMaxSize()
.background(pal.background.copy(alpha = 0.94f))
.clickable(interactionSource = interactionSource, indication = null) {},
contentAlignment = Alignment.Center,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.widthIn(max = 440.dp).padding(32.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.padding(bottom = 6.dp).size(64.dp).border(2.dp, pal.line2, CircleShape)) {
Icon(Icons.Filled.Pause, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(30.dp))
}
Text(title, fontSize = 28.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center)
PrimaryButton(
"Resume",
modifier = Modifier.padding(top = 14.dp).focusRequester(resumeFocus).controllerConfirm(onClick = onResume),
onClick = onResume,
)
}
}
}
@@ -1,5 +1,21 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.draw.alpha
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.offset
import androidx.compose.material.icons.Icons
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.outlined.PowerSettingsNew
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material3.Icon
import androidx.compose.ui.draw.clipToBounds
import android.view.Display
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
@@ -22,10 +38,8 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.AlertDialog
@@ -38,12 +52,8 @@ import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.HomeApp
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
@@ -55,11 +65,11 @@ import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -82,16 +92,21 @@ import androidx.compose.ui.text.style.TextOverflow
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenMode
import kotlinx.coroutines.flow.collect
private val drawerPageTitles = listOf("Now", "Controls", "Session")
private val drawerPageEntries = listOf("hud", "touch", "suspend")
private val drawerPageTitles = listOf("Display", "Controls", "Components", "Settings")
/** One icon per drawer page, in page order (QAM-style tabs). */
private val drawerPageIcons = listOf(Icons.Outlined.DesktopWindows, Icons.Outlined.SportsEsports, Icons.Outlined.Layers, Icons.Outlined.Settings)
private val drawerPageEntries = listOf("hud", "touch", "cmp-proton", "suspend")
private class DrawerFocus {
private val requesters = HashMap<String, FocusRequester>()
private val last = arrayOfNulls<String>(3)
private val last = arrayOfNulls<String>(DRAWER_PAGES)
var focused by mutableStateOf<String?>(null)
private set
@@ -109,79 +124,6 @@ private class DrawerFocus {
fun forget(page: Int) { last[page] = null }
}
@Composable
fun HudText(text: String) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) {
Text(
text,
fontFamily = FontFamily.Monospace,
fontSize = 12.sp,
color = Color.White,
modifier = Modifier
.padding(12.dp)
.background(Color(0x8C000000))
.padding(horizontal = 8.dp, vertical = 3.dp),
)
}
}
@Composable
fun LoadingOverlay(step: String, percent: Int, elapsed: String, hint: String, ended: Boolean) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = androidx.compose.foundation.layout.Arrangement.Center,
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
.clickable(interactionSource = MutableInteractionSource(), indication = null) {}
.padding(32.dp),
) {
Image(painterResource(R.drawable.logo), contentDescription = null, modifier = Modifier.size(64.dp))
Spacer(Modifier.height(14.dp))
Text(if (ended) "The session ended" else "Steam is loading", color = Color.White, fontSize = 17.sp)
Text(step, color = Color(0xFFB8C4D0), fontSize = 13.sp, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 6.dp))
if (!ended) {
Spacer(Modifier.height(14.dp))
if (percent >= 0) LinearProgressIndicator(progress = { percent / 100f }, modifier = Modifier.width(220.dp))
else LinearProgressIndicator(modifier = Modifier.width(220.dp))
Text(elapsed, color = Color(0xFF667788), fontSize = 11.sp, modifier = Modifier.padding(top = 8.dp))
Text(
hint, color = Color(0xFF667788), fontSize = 11.sp, textAlign = TextAlign.Center,
modifier = Modifier.padding(top = 18.dp).widthIn(max = 360.dp),
)
}
}
}
@Composable
fun SessionPausedOverlay(onResume: () -> Unit) {
val interactionSource = remember { MutableInteractionSource() }
val resumeFocus = remember { FocusRequester() }
LaunchedEffect(Unit) {
androidx.compose.runtime.withFrameNanos { }
runCatching { resumeFocus.requestFocus() }
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color(0xF20B0D10))
.clickable(interactionSource = interactionSource, indication = null) {},
contentAlignment = Alignment.Center,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(32.dp),
) {
OutlinedButton(
onClick = onResume,
modifier = Modifier.focusRequester(resumeFocus).controllerConfirm(onClick = onResume),
) {
Text("Resume session")
}
}
}
}
/** Everything the drawer shows and does. */
class DrawerActions(
val steam: Boolean,
@@ -229,6 +171,12 @@ class DrawerActions(
val onShareLogs: () -> Unit,
val onStop: () -> Unit,
val onClose: () -> Unit,
/** Components tab: every Proton with what it uses; null until first read. */
val components: ComponentsManager.Snapshot? = null,
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
val onComponentsRefresh: () -> Unit = {},
/** Swaps [value] ("orig:<build>" or a stored package file) into a Proton's component. */
val onComponentSwap: (protonId: String, comp: String, value: String) -> Unit = { _, _, _ -> },
)
@OptIn(ExperimentalComposeUiApi::class)
@@ -240,7 +188,7 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
var androidAppsExpanded by rememberSaveable { mutableStateOf(false) }
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
var confirmStop by remember { mutableStateOf(false) }
val pageScroll = remember { List(3) { ScrollState(0) } }
val pageScroll = remember { List(DRAWER_PAGES) { ScrollState(0) } }
val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil")
val focus = remember { DrawerFocus() }
val inputModeManager = LocalInputModeManager.current
@@ -250,6 +198,7 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
}
BackHandler(enabled = open && confirmStop) { confirmStop = false }
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
LaunchedEffect(open, page) { if (open && page == DRAWER_PAGE_COMPONENTS) a.onComponentsRefresh() }
LaunchedEffect(open, controllerActive) {
if (open && !controllerActive) focusManager.clearFocus(force = true)
}
@@ -274,7 +223,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
modifier = Modifier.fillMaxSize().graphicsLayer { alpha = veil }.background(Color(0x8A000000))
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() },
)
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
// A 4:3 or near-square screen (under 440dp tall) gets one-line shortcuts and a shorter tab row,
// so the settings keep most of the height; a narrow one keeps some of the game in view.
val short = maxHeight < 440.dp
val sheetWidth = minOf(360.dp, maxWidth * 0.92f)
AnimatedVisibility(
open,
enter = slideInHorizontally(Motion.sp(0.8f, Spring.StiffnessLow)) { it } + fadeIn(Motion.tw(220)),
@@ -283,30 +236,22 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
Column(
modifier = Modifier
.fillMaxHeight()
.width(340.dp)
.width(sheetWidth)
.background(pal.background.copy(alpha = 0.97f))
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
.focusGroup()
.controllerBack {
if (host.open != null) host.open = null else a.onClose()
}
.padding(horizontal = 14.dp, vertical = 16.dp),
.padding(if (short) 12.dp else 16.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 4.dp, bottom = 6.dp)) {
Box(modifier = Modifier.size(10.dp).clip(CircleShape).background(Brush.linearGradient(listOf(colors.primary, pal.primary2))))
Spacer(Modifier.width(10.dp))
Text(a.title ?: if (a.steam) "Steam" else "Desktop", fontSize = 17.sp, fontWeight = FontWeight.Bold,
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().heightIn(min = if (short) 40.dp else 44.dp)) {
Text(a.title ?: if (a.steam) "Steam" else "Desktop", fontSize = if (short) 18.sp else 20.sp, fontWeight = FontWeight.Bold,
color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
ShareSessionLogsButton(modifier = focus.track(page, "share-logs")) {
host.open = null
a.onShareLogs()
}
Spacer(Modifier.width(8.dp))
StopSessionButton(modifier = focus.track(page, "stop")) { host.open = null; confirmStop = true }
}
if (a.onSteamMenu != null && a.onQam != null) {
val qamInteraction = remember { MutableInteractionSource() }
val qamHot = qamInteraction.collectIsFocusedAsState().value || qamInteraction.collectIsHoveredAsState().value
var qamStartedOnPress by remember { mutableStateOf(false) }
LaunchedEffect(qamInteraction) {
qamInteraction.interactions.collect { interaction ->
@@ -319,59 +264,29 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
}
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().padding(bottom = 12.dp),
modifier = Modifier.fillMaxWidth().padding(top = if (short) 8.dp else 12.dp),
) {
val steamSrc = remember { MutableInteractionSource() }
val steamHot = steamSrc.collectIsFocusedAsState().value || steamSrc.collectIsHoveredAsState().value
OutlinedButton(
onClick = { host.open = null; a.onSteamMenu.invoke() },
interactionSource = steamSrc,
modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "steam")).controllerConfirm {
host.open = null
a.onSteamMenu.invoke()
},
shape = RoundedCornerShape(12.dp),
border = BorderStroke(if (steamHot) 2.dp else 1.dp, if (steamHot) pal.signal else colors.outline),
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (steamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
) {
Text("STEAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
QuickAction("Steam menu", Icons.Outlined.Menu, Modifier.weight(1f).then(focus.track(page, "steam")), compact = short) {
host.open = null
a.onSteamMenu.invoke()
}
OutlinedButton(
onClick = {
host.open = null
if (!qamStartedOnPress) a.onQam.invoke()
qamStartedOnPress = false
},
QuickAction(
"Quick access", Icons.Outlined.MoreHoriz,
Modifier.weight(1f).then(focus.track(page, "qam")).semantics { contentDescription = "Open Quick Access Menu" },
compact = short,
interactionSource = qamInteraction,
modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "qam"))
.semantics { contentDescription = "Open Quick Access Menu" }.controllerConfirm {
host.open = null
a.onQam.invoke()
},
shape = RoundedCornerShape(12.dp),
border = BorderStroke(if (qamHot) 2.dp else 1.dp, if (qamHot) pal.signal else colors.outline),
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (qamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
onConfirm = { host.open = null; a.onQam.invoke() },
) {
Text("QAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
host.open = null
if (!qamStartedOnPress) a.onQam.invoke()
qamStartedOnPress = false
}
// Big Picture's own "Switch to Desktop" waits on SteamOS Manager for ever
// here; this does the switch without the client.
if (a.onSwitchToDesktop != null) {
val deskSrc = remember { MutableInteractionSource() }
val deskHot = deskSrc.collectIsFocusedAsState().value || deskSrc.collectIsHoveredAsState().value
OutlinedButton(
onClick = { host.open = null; a.onSwitchToDesktop.invoke() },
interactionSource = deskSrc,
modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "desktop"))
.semantics { contentDescription = "Switch to Desktop" }.controllerConfirm {
host.open = null
a.onSwitchToDesktop.invoke()
},
shape = RoundedCornerShape(12.dp),
border = BorderStroke(if (deskHot) 2.dp else 1.dp, if (deskHot) pal.signal else colors.outline),
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (deskHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
) {
Text("DESKTOP", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
QuickAction("Desktop", Icons.Outlined.DesktopWindows, Modifier.weight(1f).then(focus.track(page, "desktop")), compact = short) {
host.open = null
a.onSwitchToDesktop.invoke()
}
}
}
@@ -379,47 +294,21 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
modifier = Modifier.fillMaxWidth().padding(top = if (short) 6.dp else 12.dp),
) {
DrawerOutlineButton("LB ‹", modifier = Modifier.height(48.dp).then(focus.track(page, "prev"))) {
host.open = null; onPageChange((page + 2) % 3)
DrawerBumper("LB", "Previous page", modifier = focus.track(page, "prev")) {
host.open = null; onPageChange((page + DRAWER_PAGES - 1) % DRAWER_PAGES)
}
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f),
) {
drawerPageTitles.forEachIndexed { index, title ->
val dotSource = remember { MutableInteractionSource() }
val dotFocused = dotSource.collectIsFocusedAsState().value
val select = { host.open = null; onPageChange(index) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(38.dp)
.semantics { contentDescription = "$title page" }
.hoverable(dotSource)
.clickable(interactionSource = dotSource, indication = LocalIndication.current, onClick = select)
.controllerConfirm(onClick = select),
) {
Box(
Modifier.size(if (index == page) 16.dp else 10.dp)
.clip(CircleShape)
.background(if (index == page) pal.signal else colors.onSurfaceVariant)
.border(if (dotFocused) 2.dp else 0.dp, colors.onBackground, CircleShape),
)
}
}
}
DrawerOutlineButton("› RB", modifier = Modifier.height(48.dp).then(focus.track(page, "next"))) {
host.open = null; onPageChange((page + 1) % 3)
DrawerPageTabs(page = page, compact = short, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
DrawerBumper("RB", "Next page", modifier = focus.track(page, "next")) {
host.open = null; onPageChange((page + 1) % DRAWER_PAGES)
}
}
Column(
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll[page]),
) {
) { CompositionLocalProvider(LocalChipMinWidth provides 120.dp) {
when (page) {
0 -> SettingsGroup("Now") {
0 -> SettingsGroup("Display") {
ToggleRow(host, "hud", "Performance HUD", null, a.hudOn,
chipModifier = focus.track(page, "hud"), onChange = a.onHud)
if (a.fillScreen != null) ToggleRow(
@@ -427,23 +316,15 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen,
)
val fgOpen = host.open == "fg"
val fgLabel = when (a.frameGenEngine) {
FrameGen.ENGINE_WINFG -> "Win-FG ${a.frameGenMultiplier}×"
FrameGen.ENGINE_LSFG -> "LSFG ${a.frameGenMultiplier}×"
else -> "Off"
}
val fgLabel = FrameGen.label(a.frameGenEngine, a.frameGenMultiplier)
SettingsRow("Frame generation", null, highlighted = fgOpen) {
Box {
ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" }
AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
val need = if (a.lsfgReady) null else "Requires Lossless Scaling"
MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
}
FrameGenMenu(host, a.frameGenEngine, a.frameGenMultiplier, a.lsfgReady, a.onFrameGenPick)
}
}
}
DRAWER_PAGE_COMPONENTS -> ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
1 -> {
SettingsGroup("Controls") {
ChoiceRow(host, "touch", "Touch", null,
@@ -459,16 +340,16 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
}
SettingsGroup("Keyboard") {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) {
DrawerOutlineButton("Hardware", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "hardware"))) {
DrawerOutlineButton("PC keyboard", modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "hardware"))) {
host.open = null; a.onHardwareKeyboard()
}
DrawerOutlineButton("Android", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "android"))) {
DrawerOutlineButton("Android", modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "android"))) {
host.open = null; a.onKeyboard()
}
}
}
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
ChoiceRow(host, "second-screen-mode", "Controls", null,
ChoiceRow(host, "second-screen-mode", "Shows", null,
listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL).map { it to it.label },
a.secondScreenMode, chipModifier = focus.track(page, "second-screen-mode"), onPick = a.onSecondScreenMode)
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", "Display", null,
@@ -528,13 +409,21 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
FexPreset.all.map { it.id to it.label }, a.fexPreset,
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
}
SettingsGroup("Support") {
SettingsRow("Session logs", "Send this session's logs with a bug report") {
DrawerOutlineButton("Share logs", modifier = focus.track(page, "share-logs")) {
host.open = null
a.onShareLogs()
}
}
}
Spacer(Modifier.height(18.dp))
if (!a.isHomeApp) DrawerOutlineButton("Background", modifier = focus.track(page, "background")) {
host.open = null; a.onBackground()
}
}
}
}
} }
}
}
}
@@ -608,32 +497,271 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill")
Box(
contentAlignment = Alignment.Center,
modifier = modifier.size(42.dp).semantics { contentDescription = "Stop session" }
.clip(RoundedCornerShape(12.dp)).background(fill).border(1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.5f), RoundedCornerShape(12.dp))
val shape = RoundedCornerShape(20.dp)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = "Stop session" }
.clip(shape).background(fill).border(if (hot) 2.dp else 1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.55f), shape)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick),
) { Text("×", fontSize = 25.sp, fontWeight = FontWeight.Medium, color = colors.error) }
.controllerConfirm(onClick = onClick)
.padding(start = 12.dp, end = 14.dp),
) {
Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp))
Text("Stop", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error)
}
}
/** One of the sheet's shortcuts into Steam: an icon over its name, the whole tile the target. */
@Composable
private fun ShareSessionLogsButton(modifier: Modifier = Modifier, onClick: () -> Unit) {
private fun QuickAction(
label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, modifier: Modifier,
compact: Boolean = false,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
onConfirm: (() -> Unit)? = null,
onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val hot = interactionSource.collectIsFocusedAsState().value || interactionSource.collectIsHoveredAsState().value
val shape = RoundedCornerShape(12.dp)
val tile = modifier.height(if (compact) 44.dp else 64.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, shape)
.hoverable(interactionSource)
.clickable(interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onConfirm ?: onClick)
.padding(horizontal = 6.dp)
val content: @Composable () -> Unit = {
Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(20.dp))
Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (compact) Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally), modifier = tile,
) { content() }
else Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(5.dp, Alignment.CenterVertically), modifier = tile,
) { content() }
}
/** A bumper as a keycap, 44dp to touch; LB / RB on the pad turn the page too. */
@Composable
private fun DrawerBumper(label: String, description: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val ring = RoundedCornerShape(10.dp)
val cap = RoundedCornerShape(7.dp)
Box(
contentAlignment = Alignment.Center,
modifier = modifier.widthIn(min = 88.dp).height(42.dp)
.semantics { contentDescription = "Send current session logs" }
.clip(RoundedCornerShape(12.dp))
.background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.border(1.dp, if (hot) pal.signal else colors.outline.copy(alpha = 0.5f), RoundedCornerShape(12.dp))
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick),
modifier = modifier.size(44.dp).clip(ring)
.border(2.dp, if (hot) pal.signal else Color.Transparent, ring)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = description },
) {
Text("send logs", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
color = if (hot) pal.signal else colors.onSurfaceVariant, maxLines = 1)
Text(
label, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = if (hot) colors.onBackground else colors.onSurfaceVariant,
modifier = Modifier.clip(cap).background(colors.surfaceVariant).border(1.dp, pal.line2, cap).padding(horizontal = 6.dp, vertical = 3.dp),
)
}
}
/**
* The drawer's page tabs, QAM-style: one icon per page standing in a line in page order. The
* selected one steps forward - full size, bright, a soft glow - while the others step back to
* half size and fade, and the whole line leans a little toward the selection. LB / RB still turn
* the page (the buttons beside it and the pad's bumpers); a tab can be tapped or picked with the
* pad like the dots it replaces.
*/
@Composable
private fun DrawerPageTabs(page: Int, modifier: Modifier = Modifier, compact: Boolean = false, onSelect: (Int) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val count = drawerPageIcons.size
val middle = (count - 1) / 2f
val motion = tween<Float>(durationMillis = 340, easing = FastOutSlowInEasing)
androidx.compose.foundation.layout.BoxWithConstraints(
contentAlignment = Alignment.Center,
modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds(),
) {
val tab = if (compact) 40f else 56f
// Fit the line to the room between LB and RB. Worst case is an end tab selected: full size
// ([tab] dp) and pushed outward by the lean, which scales with the spacing. So
// (count-1) * spacing * (1 + lean/64) + 56 <= width
// - never more than the mock's 64 dp, never tighter than 32 dp.
val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(32f, DRAWER_TAB_SPACING_DP)
val leanStep = DRAWER_TAB_LEAN_DP * spacing / DRAWER_TAB_SPACING_DP
val lean by animateFloatAsState(-(page - middle) * leanStep, motion, label = "tabLean")
drawerPageIcons.forEachIndexed { index, icon ->
val selected = index == page
val source = remember { MutableInteractionSource() }
val focused = source.collectIsFocusedAsState().value
val scale by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_SCALE, motion, label = "tabScale")
val alpha by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_ALPHA, motion, label = "tabAlpha")
val glow by animateFloatAsState(if (selected) 1f else 0f, motion, label = "tabGlow")
val tint by animateColorAsState(if (selected) colors.onBackground else colors.onSurfaceVariant, tween(340), label = "tabTint")
val select = { onSelect(index) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.offset(x = ((index - middle) * spacing + lean).dp)
.size(tab.dp)
.graphicsLayer { scaleX = scale; scaleY = scale; this.alpha = alpha }
.clip(RoundedCornerShape(16.dp))
.background(
Brush.radialGradient(
listOf(pal.signal.copy(alpha = 0.34f * glow), pal.signal.copy(alpha = 0.10f * glow), Color.Transparent),
),
)
.border(if (focused) 2.dp else 0.dp, if (focused) colors.onBackground else Color.Transparent, RoundedCornerShape(16.dp))
.semantics { contentDescription = "${drawerPageTitles[index]} page" }
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, onClick = select)
.controllerConfirm(onClick = select),
) {
Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(if (compact) 22.dp else 30.dp))
}
}
}
}
/** Display, Controls, Components, Settings. */
const val DRAWER_PAGES = 4
private const val DRAWER_PAGE_COMPONENTS = 2
/**
* The drawer's Components tab: quick swaps between what is already installed, per Proton. A swap
* into the Proton a running game uses waits until that game closes; downloading, importing and
* deleting stay on the Components page in the app.
*/
@Composable
private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val snap = a.components
if (snap == null) {
SettingsGroup("Components") {
Text("Reading the Protons…", fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(14.dp))
}
return
}
val running = snap.protons.filter { it.inUseByGame }
var pick by rememberSaveable { mutableStateOf<String?>(null) }
val view = snap.protons.firstOrNull { it.proton.id == pick } ?: running.firstOrNull() ?: snap.protons.firstOrNull()
// Focusable, so the pad can climb from the Proton box up to it and the page scrolls it into view.
SettingsGroup("Running now") {
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value
val pal = LocalPalette.current
Column(
modifier = Modifier.fillMaxWidth().then(track("cmp-running"))
.focusable(interactionSource = src)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.padding(horizontal = 14.dp, vertical = 11.dp),
) {
if (running.isEmpty()) {
Text("No game is running on a Proton", fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text("Changes apply the next time a game starts.", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
} else for (r in running) {
Text(r.proton.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
for (comp in ComponentsManager.COMPONENTS) {
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
Text(ComponentsManager.LABEL.getValue(comp), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(96.dp))
Text(r.components.getValue(comp).inUse, fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
}
if (view == null) {
SettingsGroup("Components") {
Text("No Proton is installed yet.", fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(14.dp))
}
return
}
val p = view.proton
SettingsGroup("Components") {
DrawerStackedChoice(
host, "cmp-proton", "Proton",
listOfNotNull(
p.version,
"game running".takeIf { view.inUseByGame },
view.reappliedAt.takeIf { it > 0 }?.let { "re-applied at launch " + java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(it * 1000)) },
).joinToString(" · "),
snap.protons.map { it.proton.id to it.proton.name }, p.id,
chipModifier = track("cmp-proton"), onPick = { pick = it },
)
val build = ComponentsManager.safeName(p.version)
for (comp in ComponentsManager.COMPONENTS) {
val st = view.components.getValue(comp)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) "Original" else "Original · ${it.protonVersion}") } +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (options.isEmpty()) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
DrawerStackedChoice(
host, "cmp-$comp", ComponentsManager.LABEL.getValue(comp),
// The box already shows the choice: only say more when there is more to say.
st.queued?.let { "Next: $it · after the game closes" } ?: st.inUse.takeIf { it != shown },
options, current,
note = if (view.inUseByGame) "A game is running on this Proton: the change waits until it closes." else "Applies the next time a game starts.",
chipModifier = track("cmp-$comp"),
onPick = { v -> if (v != current || st.queued != null) a.onComponentSwap(p.id, comp, v) },
)
}
}
Text(
"Downloads, importing and deleting are on the Components page in the app.",
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
)
}
/**
* A choice for the drawer's narrow column: label, then the box across the full width, then the
* detail underneath - so a long Proton or package name never squeezes the text beside it.
*/
@Composable
private fun <T> DrawerStackedChoice(
host: MenuHost, key: String, label: String, hint: String?,
options: List<Pair<T, String>>, selected: T, note: String? = null,
chipModifier: Modifier = Modifier, onPick: (T) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val open = host.open == key
Column(
modifier = Modifier.fillMaxWidth()
.background(if (open) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
.padding(horizontal = 14.dp, vertical = 10.dp),
) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Box(modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, modifier = chipModifier.fillMaxWidth()) {
host.open = if (open) null else key
}
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
options.forEachIndexed { index, (value, text) ->
MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) {
onPick(value)
host.open = null
}
}
}
}
if (hint != null) Text(hint, fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 5.dp))
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
/** The tab row's measure, from the approved mock: side tabs at half size, a little faded. */
private const val DRAWER_TAB_SPACING_DP = 64f
private const val DRAWER_TAB_LEAN_DP = 12f
private const val DRAWER_TAB_SIDE_SCALE = 0.5f
private const val DRAWER_TAB_SIDE_ALPHA = 0.7f
@@ -14,6 +14,14 @@ import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.size
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.semantics.semantics
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
@@ -96,6 +104,85 @@ internal fun Modifier.controllerBack(onBack: () -> Unit): Modifier = onPreviewKe
}
}
/** LB and RB turn a page's tabs; the keys are taken whenever focus is anywhere inside [this]. */
internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = onPreviewKeyEvent { event ->
val keyEvent = event.nativeKeyEvent
val previous = keyEvent.keyCode == KeyEvent.KEYCODE_BUTTON_L1
if (!previous && keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_R1) {
false
} else {
if (keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) { if (previous) onPrevious() else onNext() }
true
}
}
/**
* A page's tabs with the pad's bumpers drawn beside them. The host turns them with LB/RB (see
* [bumpers]); the keycaps are for touch and stay out of the d-pad's path. The row scrolls sideways
* when a narrow page cannot fit every tab.
*/
@Composable
internal fun TabStrip(
tabs: List<String>, selected: Int, onSelect: (Int) -> Unit,
modifier: Modifier = Modifier, focusRequesters: List<FocusRequester>? = null,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(12.dp)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier) {
BumperKey("LB", "Previous tab") { onSelect((selected + tabs.size - 1) % tabs.size) }
Row(
modifier = Modifier.weight(1f, fill = false).clip(shape).background(colors.surfaceVariant).border(1.dp, pal.line2, shape)
.horizontalScroll(rememberScrollState()).padding(3.dp),
) {
tabs.forEachIndexed { i, label ->
val on = i == selected
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val pick = { onSelect(i) }
val tabShape = RoundedCornerShape(9.dp)
Text(
label, fontSize = 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1,
color = if (on) pal.onSignal else if (hot) colors.onBackground else colors.onSurfaceVariant,
modifier = Modifier
.then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier)
.clip(tabShape)
.background(if (on) pal.signal else if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.border(2.dp, if (!hot) Color.Transparent else if (on) colors.onBackground else pal.signal, tabShape)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 16.dp, vertical = 12.dp),
)
}
}
BumperKey("RB", "Next tab") { onSelect((selected + 1) % tabs.size) }
}
}
/** A bumper drawn as a keycap, 44dp to touch; the pad presses the real one. */
@Composable
private fun BumperKey(label: String, description: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val cap = RoundedCornerShape(7.dp)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(44.dp)
.focusProperties { canFocus = false }
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, role = Role.Button, onClick = onClick)
.semantics { contentDescription = description },
) {
Text(
label, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant,
modifier = Modifier.clip(cap).background(colors.surfaceVariant).border(1.dp, pal.line2, cap)
.padding(horizontal = 6.dp, vertical = 3.dp),
)
}
}
/** The narrowest a setting's value box gets; the session menu's sheet sets it lower. */
val LocalChipMinWidth = androidx.compose.runtime.compositionLocalOf { 150.dp }
class MenuHost {
var open by mutableStateOf<String?>(null)
}
@@ -154,14 +241,14 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no
.padding(6.dp),
) {
if (title != null) Text(
title.uppercase(), fontSize = 10.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant,
title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 6.dp),
)
Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content(firstItemFocus) }
if (note != null) {
Spacer(Modifier.height(4.dp))
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Text(note, fontSize = 11.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp))
Text(note, fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp))
}
}
}
@@ -198,7 +285,7 @@ fun MenuItem(
}
Column(modifier = Modifier.weight(1f)) {
Text(label, fontSize = 13.5.sp, color = if (checked) pal.signal else colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (detail != null) Text(detail, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (detail != null) Text(detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
if (trailing != null) { Spacer(Modifier.width(8.dp)); trailing() }
}
@@ -215,7 +302,8 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween,
modifier = modifier
.widthIn(min = 150.dp)
.widthIn(min = LocalChipMinWidth.current)
.heightIn(min = 44.dp)
.clip(RoundedCornerShape(10.dp))
.background(colors.surfaceVariant)
.border(1.dp, edge, RoundedCornerShape(10.dp))
@@ -235,11 +323,15 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
}
@Composable
fun SettingsGroup(title: String, content: @Composable ColumnScope.() -> Unit) {
fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 6.dp)) {
Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(if (compact) 6.dp else 10.dp),
modifier = Modifier.fillMaxWidth().padding(top = if (compact) 4.dp else 16.dp, bottom = if (compact) 3.dp else 6.dp),
) {
Text(title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant)
Box(modifier = Modifier.weight(1f).height(1.dp).background(pal.line))
}
Column(modifier = Modifier.fillMaxWidth().clip(GroupShape).background(colors.surface).border(1.dp, pal.line, GroupShape)) { content() }
@@ -250,13 +342,20 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, cont
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val bg by animateColorAsState(if (highlighted) pal.signal.copy(alpha = 0.10f) else Color.Transparent, Motion.tw(200), label = "rowBg")
Row(
// A narrow page stacks the control under its label, so neither squeezes the other.
if (LocalNarrowPane.current) Column(
modifier = Modifier.fillMaxWidth().background(bg).padding(start = 14.dp, end = 14.dp, top = 11.dp, bottom = 12.dp),
) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
if (hint != null) Text(hint, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
Box(Modifier.padding(top = 8.dp)) { control() }
} else Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp),
) {
Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
if (hint != null) Text(hint, fontSize = 11.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
if (hint != null) Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
}
control()
}
@@ -289,7 +388,46 @@ fun <T> ChoiceRow(
@Composable
fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked: Boolean, enabled: Boolean = true, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) =
ChoiceRow(host, key, label, hint, listOf(true to "On", false to "Off"), checked, enabled, chipModifier = chipModifier, onPick = onChange)
SettingsRow(label, hint) {
ToggleSwitch(checked, enabled, label, chipModifier) { host.open = null; onChange(it) }
}
/** An on/off switch: one tap or one A press flips it, where a menu of On and Off took three. */
@Composable
fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = null, modifier: Modifier = Modifier, onChange: (Boolean) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val track by animateColorAsState(if (checked) pal.signal else colors.surfaceVariant, Motion.tw(180), label = "switchTrack")
val edge by animateColorAsState(if (hot) pal.signal else if (checked) pal.signal else pal.line2, Motion.tw(180), label = "switchEdge")
val knob by animateFloatAsState(if (checked) 1f else 0f, Motion.sp(0.7f), label = "switchKnob")
val flip = { onChange(!checked) }
val shape = RoundedCornerShape(99.dp)
// 48dp tall to touch; the visible track sits inside it.
Box(
contentAlignment = Alignment.Center,
modifier = modifier
.heightIn(min = 48.dp).widthIn(min = 64.dp)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src)
.clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.Switch, onClick = flip)
.controllerConfirm(enabled = enabled, onClick = flip)
.semantics { stateDescription = if (checked) "On" else "Off"; if (label != null) contentDescription = label },
) {
Box(
Modifier.size(width = 52.dp, height = 30.dp).clip(shape).background(track)
.border(if (hot) 2.dp else 1.dp, if (hot && checked) colors.onBackground else edge, shape),
) {
Box(
Modifier.padding(4.dp).size(22.dp)
.graphicsLayer { translationX = knob * 22.dp.toPx() }
.clip(CircleShape)
.background(if (checked) pal.onSignal else colors.onSurfaceVariant),
)
}
}
}
@Composable
fun MultiRow(
@@ -332,40 +470,88 @@ fun SettingsPage(
action: (@Composable () -> Unit)? = null,
/** Pass one held above the page to keep its scroll position across a page opened over it. */
scroll: androidx.compose.foundation.ScrollState? = null,
scrollContent: Boolean = true,
compactLayout: Boolean = false,
content: @Composable ColumnScope.() -> Unit,
) {
val scrollState = scroll ?: rememberScrollState()
val colors = MaterialTheme.colorScheme
val dim by animateFloatAsState(if (host.open != null) 0.6f else 1f, Motion.tw(220), label = "pageDim")
Column(modifier = Modifier.fillMaxSize().padding(horizontal = 22.dp, vertical = 18.dp)) {
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically) {
// Outlined when a controller's focus is on it, like every other control here.
val backSrc = remember { MutableInteractionSource() }
val backHot = backSrc.collectIsFocusedAsState().value || backSrc.collectIsHoveredAsState().value
Text(
"‹ Back", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
color = if (backHot) LocalPalette.current.signal else colors.onSurfaceVariant,
modifier = Modifier.clip(RoundedCornerShape(8.dp))
.border(2.dp, if (backHot) LocalPalette.current.signal else Color.Transparent, RoundedCornerShape(8.dp))
.hoverable(backSrc).clickable(interactionSource = backSrc, indication = null, onClick = onBack)
.padding(horizontal = 6.dp, vertical = 4.dp),
)
if (eyebrow != null) {
Spacer(Modifier.width(10.dp))
Eyebrow(eyebrow)
val narrow = LocalNarrowPane.current && !compactLayout
Column(
modifier = Modifier.fillMaxSize().padding(
horizontal = if (compactLayout) 14.dp else if (narrow) 16.dp else 22.dp,
vertical = if (compactLayout) 6.dp else if (narrow) 12.dp else 18.dp,
),
verticalArrangement = Arrangement.spacedBy(if (compactLayout) 2.dp else 0.dp),
) {
if (narrow) {
// Back and the title share one line: a 4:3 screen has no height to spare.
Rise(0) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.padding(bottom = 6.dp),
) {
BackLink("Back", compact = true, onClick = onBack)
Text(
title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
)
if (action != null) action()
}
}
if (lede != null) Rise(1) { Lede(lede) }
} else {
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically) {
BackLink("Back", compact = compactLayout, onClick = onBack)
if (eyebrow != null) {
Spacer(Modifier.width(10.dp))
Eyebrow(eyebrow)
}
}
}
Rise(1) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.weight(1f)) {
if (compactLayout) {
Text(
title,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
color = colors.onBackground,
modifier = Modifier.padding(vertical = 2.dp),
)
} else {
Title(title)
}
}
if (action != null) action()
}
}
if (lede != null) Rise(2) {
if (compactLayout) {
Text(
lede,
fontSize = 12.sp,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(bottom = 3.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
} else {
Lede(lede)
}
}
}
Rise(1) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.weight(1f)) { Title(title) }
if (action != null) action()
}
}
if (lede != null) Rise(2) { Lede(lede) }
Rise(3, Modifier.weight(1f).fillMaxWidth()) {
Column(modifier = Modifier.fillMaxSize().graphicsLayer { alpha = dim }.verticalScroll(scrollState).padding(bottom = 24.dp)) { content() }
Column(
modifier = Modifier
.fillMaxSize()
.graphicsLayer { alpha = dim }
.then(if (scrollContent) Modifier.verticalScroll(scrollState) else Modifier)
.padding(bottom = if (compactLayout) 0.dp else 24.dp),
) { content() }
}
}
}
@@ -0,0 +1,231 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.runtime.State
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
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.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.draw.drawBehind
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.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.frontend.Library
/** From this many games the Steam tab is a wall; fewer would only repeat the same covers. */
private const val WALL_MIN_GAMES = 4
/**
* The Steam tab: the library as a slowly drifting, tilted wall of capsules (a few games instead
* lean on their own; none, a wall of empty ones), and over it Steam and the one thing to do here -
* Play. Everything about a single game lives on the Games tab.
*/
@Composable
internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
val games = remember(s.steamGames) { s.steamGames.sortedByDescending { it.lastPlayed } }
val narrow = LocalNarrowPane.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Box(modifier = modifier.fillMaxSize().clipToBounds()) {
if (games.size in 1 until WALL_MIN_GAMES) CapsuleFan(games)
else {
if (games.isEmpty()) Box(
Modifier.fillMaxSize().drawBehind {
drawRect(
Brush.radialGradient(
listOf(pal.signal.copy(alpha = 0.12f), Color.Transparent),
center = Offset(size.width * 0.72f, size.height * 0.42f), radius = 380.dp.toPx(),
),
)
},
)
CapsuleWall(games)
// The wall fades out behind the words, and toward the bottom where the buttons sit.
Box(
Modifier.fillMaxSize().background(
Brush.horizontalGradient(
0f to colors.background.copy(alpha = 0.97f),
0.34f to colors.background.copy(alpha = 0.86f),
0.68f to colors.background.copy(alpha = 0.25f),
1f to colors.background.copy(alpha = 0.1f),
),
),
)
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.55f to Color.Transparent, 1f to colors.background.copy(alpha = 0.9f))))
}
Column(
modifier = Modifier.align(Alignment.BottomStart)
.padding(start = if (narrow) 20.dp else 44.dp, bottom = if (narrow) 20.dp else 44.dp, end = 20.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Text(
"Steam", fontSize = if (narrow) 34.sp else 44.sp, lineHeight = if (narrow) 40.sp else 50.sp,
fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1,
)
// Said only when something stands between Play and Steam; a ready runtime needs no words.
if (s.busy || !s.ready || (s.available != null && s.available != s.installed)) RuntimeChip(s)
}
Spacer(Modifier.height(18.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
// Enabled without a runtime: the session's loading screen installs it first.
PrimaryButton("Play Steam", enabled = !s.busy, main = true, large = true, icon = Icons.Filled.PlayArrow, onClick = a.onPlay)
Cog(size = 54.dp, onClick = a.onSteamSettings)
}
}
}
}
/**
* Columns of capsules tilted a few degrees, alternate columns drifting up and down. Each column
* holds its run of covers twice and moves by exactly one run, so the loop has no seam. An empty
* library draws the same wall in blank capsules, slower.
*/
@Composable
internal fun CapsuleWall(
games: List<Library.SteamGame>,
driftMs: Int = if (games.isEmpty()) 75_000 else 40_000,
modifier: Modifier = Modifier,
) {
val capW = 112.dp
val capH = 168.dp
val gap = 14.dp
val transition = rememberInfiniteTransition(label = "wall")
val drift = transition.animateFloat(
0f, 1f,
infiniteRepeatable(tween(driftMs, easing = LinearEasing)),
label = "drift",
)
// Animations off in the system settings: a still wall.
val still = Motion.scale == 0f
BoxWithConstraints(modifier.fillMaxSize()) {
// Centred on the page and big enough that, once tilted, it still covers every corner.
val tilt = Math.toRadians(13.0)
val cos = kotlin.math.cos(tilt).toFloat()
val sin = kotlin.math.sin(tilt).toFloat()
val wallW = (maxWidth * cos + maxHeight * sin) * 1.1f
val wallH = maxOf(maxHeight * 2.4f, (maxWidth * sin + maxHeight * cos) * 1.1f)
val columns = ((wallW + gap) / (capW + gap)).toInt() + 1
val perRun = ((wallH + gap) / (capH + gap)).toInt() + 1
val run = (capH + gap) * perRun
Row(
horizontalArrangement = Arrangement.spacedBy(gap),
modifier = Modifier
.wrapContentSize(Alignment.TopStart, unbounded = true)
.offset(x = -(wallW - maxWidth) / 2, y = -(wallH - maxHeight) / 2)
.requiredSize(wallW, wallH)
.graphicsLayer { rotationZ = -13f },
) {
repeat(columns) { c ->
Column(
verticalArrangement = Arrangement.spacedBy(gap),
modifier = Modifier.wrapContentHeight(Alignment.Top, unbounded = true).graphicsLayer {
val shift = if (still) 0f else run.toPx() * drift.value
translationY = if (c % 2 == 0) -shift else shift - run.toPx()
},
) {
repeat(perRun * 2) { i ->
val g = if (games.isEmpty()) null else games[(c * 5 + (i % perRun) * 3) % games.size]
Capsule(g, RoundedCornerShape(10.dp), Modifier.size(capW, capH))
}
}
}
}
}
}
/** One to three games, each a large capsule leaning on the others and floating a little. */
@Composable
private fun CapsuleFan(games: List<Library.SteamGame>) {
val pal = LocalPalette.current
val transition = rememberInfiniteTransition(label = "fan")
val floats = listOf(9_000, 11_000, 13_000).map { ms ->
transition.animateFloat(0f, 1f, infiniteRepeatable(tween(ms, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "float")
}
val still = Motion.scale == 0f
// Where each sits (share of the page), its height (share of the page's) and its lean; front first.
val slots = listOf(
FanSlot(0.54f, 0.14f, 0.62f, -9f),
FanSlot(0.70f, 0.24f, 0.56f, 5f),
FanSlot(0.40f, 0.30f, 0.50f, -17f),
)
BoxWithConstraints(
Modifier.fillMaxSize().drawBehind {
drawRect(
Brush.radialGradient(
listOf(pal.signal.copy(alpha = 0.14f), Color.Transparent),
center = Offset(size.width * 0.68f, size.height * 0.45f), radius = size.height * 0.6f,
),
)
},
) {
for (i in games.indices.reversed()) {
val slot = slots[i]
val h = maxHeight * slot.height
val v: State<Float> = floats[i]
Capsule(
games[i], RoundedCornerShape(14.dp),
Modifier
.offset(x = maxWidth * slot.x, y = maxHeight * slot.y)
.size(h * 2f / 3f, h)
.graphicsLayer {
val t = if (still) 0f else v.value
rotationZ = slot.lean + 2f * t
translationY = -12.dp.toPx() * t
shadowElevation = 24.dp.toPx()
shape = RoundedCornerShape(14.dp)
clip = false
},
)
}
}
}
private class FanSlot(val x: Float, val y: Float, val height: Float, val lean: Float)
/** A game's portrait capsule, or a blank one standing in for a game yet to be installed. */
@Composable
private fun Capsule(g: Library.SteamGame?, shape: RoundedCornerShape, modifier: Modifier) {
val pal = LocalPalette.current
if (g == null) {
Box(modifier.clip(shape).background(Brush.linearGradient(listOf(pal.surface, pal.background))).border(1.dp, pal.line, shape))
return
}
Box(modifier.clip(shape).background(artBrush(hueOf(g.name)))) {
if (g.art != null) AsyncImage(model = g.art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
}
}
@@ -6,6 +6,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.platform.LocalContext
import com.droiddeck.launcher.session.SessionPrefs
@@ -18,11 +19,19 @@ class Palette(
)
object Themes {
const val GRAPHITE = "graphite"
const val PAPER = "paper"
const val ICON_BLUE = "blue"
const val ELECTRIC = "electric"
val all: List<Palette> = listOf(
Palette(
GRAPHITE, "Graphite", "Graphite surfaces, with the logo's own orb blue for everything selected, focused or pressed.",
background = Color(0xFF0A0B0D), surface = Color(0xFF121417), surfaceVariant = Color(0xFF1A1D22), line = Color(0xFF262A31), line2 = Color(0xFF343A43),
onBackground = Color(0xFFF2F4F7), onSurfaceVariant = Color(0xFF9AA3AF),
primary = Color(0xFF1A9FFF), primary2 = Color(0xFF1487DB), onPrimary = Color(0xFF03111F), signal = Color(0xFF1A9FFF),
good = Color(0xFF4CD37F),
),
Palette(
PAPER, "Paper on black", "White is the primary, the icon's blue is the signal for rules, rings and dots.",
background = Color(0xFF000000), surface = Color(0xFF0F0F10), surfaceVariant = Color(0xFF191A1C), line = Color(0xFF262729), line2 = Color(0xFF343638),
@@ -49,7 +58,13 @@ object Themes {
fun byId(id: String): Palette = all.firstOrNull { it.id == id } ?: all[0]
}
val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.PAPER) }
val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.GRAPHITE) }
/**
* Text and icons drawn on a [Palette.signal] fill: near-black where the blue is light enough that
* white would not read (Graphite's #1A9FFF gives white 2.8:1), white where it is deep.
*/
val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03111F) else Color.White
@Composable
fun DroidDeckTheme(theme: String? = null, content: @Composable () -> Unit) {
@@ -0,0 +1,171 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.rotate
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
/**
* The DroidDeck mark as the loading indicator. Every loop the D's square half bends into an arc,
* the ring they make turns once around the ball, and the half straightens back into the D.
*/
@Composable
internal fun LogoThrobber(modifier: Modifier = Modifier, running: Boolean = true) {
val ink = MaterialTheme.colorScheme.onBackground
val ball = LocalPalette.current.signal
val loop = rememberInfiniteTransition(label = "throbber")
.animateFloat(0f, 1f, infiniteRepeatable(tween(LOOP_MS, easing = LinearEasing)), label = "loop")
// Animations off in the system settings, or nothing running: the plain D.
val still = !running || Motion.scale == 0f
val left = remember { Path() }
val right = remember { Path() }
Canvas(modifier.aspectRatio(LogoShape.WIDTH / LogoShape.HEIGHT)) {
val p = if (still) 0f else loop.value
val bend = when {
p < 0.10f -> 0f
p < 0.24f -> Settle.transform((p - 0.10f) / 0.14f)
p < 0.76f -> 1f
p < 0.90f -> 1f - Settle.transform((p - 0.76f) / 0.14f)
else -> 0f
}
val turn = if (p < 0.16f || p > 0.84f) 0f else Turn.transform((p - 0.16f) / 0.68f) * 360f
val ballScale = when {
p < 0.12f -> 1f
p < 0.30f -> 1f - 0.2f * Settle.transform((p - 0.12f) / 0.18f)
p < 0.70f -> 0.8f
p < 0.88f -> 0.8f + 0.2f * Settle.transform((p - 0.70f) / 0.18f)
else -> 1f
}
val s = size.width / LogoShape.WIDTH
fun px(x: Float, y: Float) = Offset((x - LogoShape.LEFT) * s, y * s)
val centre = px(LogoShape.CX, LogoShape.CY)
LogoShape.left(left, bend, ::px)
LogoShape.right(right, ::px)
rotate(turn, centre) {
drawPath(left, ink)
drawPath(right, ink)
}
drawCircle(ball, radius = LogoShape.BALL * s * ballScale, center = centre)
}
}
/** The ball of a throbber laid out in [bounds]: its centre and its radius, at rest. */
internal fun throbberBall(bounds: androidx.compose.ui.geometry.Rect): Pair<Offset, Float> {
val s = bounds.width / LogoShape.WIDTH
return Offset(bounds.left + (LogoShape.CX - LogoShape.LEFT) * s, bounds.top + LogoShape.CY * s) to LogoShape.BALL * s
}
private const val LOOP_MS = 1900
private val Settle = CubicBezierEasing(0.5f, 0f, 0.3f, 1f)
private val Turn = CubicBezierEasing(0.65f, 0f, 0.35f, 1f)
/**
* The logo's geometry in its SVG's own units (viewBox -55.98 0 239.92 223.72): a D of a square
* left side and a round right side, cut by a ring around the ball and split top and bottom.
* The left half is sampled along rays from the centre so it can bend, point for point, into the
* mirror of the right half's arc.
*/
private object LogoShape {
const val LEFT = -55.98f
const val WIDTH = 239.92f
const val HEIGHT = 223.72f
const val CX = 63.98f
const val CY = 111.86f
const val BALL = 55.98f
private const val OUTER = 111.86f
private const val INNER = 71.81f
private const val SQUARE_X = -31.98f
private const val SPLIT_LEFT = 56.055f
private const val SPLIT_RIGHT = 71.885f
private class Pt(val x: Float, val y: Float)
private fun at(a: Double, r: Float) = Pt((CX + r * cos(a)).toFloat(), (CY + r * sin(a)).toFloat())
private fun angle(x: Float, y: Float) = atan2((y - CY).toDouble(), (x - CX).toDouble())
// Angles taken the long way round, through the left: from about -94 degrees down to -266.
private fun leftward(a: Double) = if (a < 0) a else a - 2 * Math.PI
private val rays: List<Double> = run {
val top = angle(SPLIT_LEFT, 0f)
val topCorner = angle(SQUARE_X, 0f)
val bottomCorner = leftward(angle(SQUARE_X, HEIGHT))
val bottom = leftward(angle(SPLIT_LEFT, HEIGHT))
// The corners are rays of their own, so the square half keeps sharp corners.
fun span(a: Double, b: Double, n: Int) = List(n) { i -> a + (b - a) * i / (n - 1) }
span(top, topCorner, 9).dropLast(1) + span(topCorner, bottomCorner, 25).dropLast(1) + span(bottomCorner, bottom, 9)
}
private val square: List<Pt> = rays.map { a ->
val c = cos(a)
val sn = sin(a)
val hits = buildList {
if (c < -1e-9) add((SQUARE_X - CX) / c)
if (sn < -1e-9) add((0f - CY) / sn)
if (sn > 1e-9) add((HEIGHT - CY) / sn)
}
val t = hits.minOrNull() ?: 0.0
Pt((CX + t * c).toFloat(), (CY + t * sn).toFloat())
}.toMutableList().also { it[0] = Pt(SPLIT_LEFT, 0f); it[it.lastIndex] = Pt(SPLIT_LEFT, HEIGHT) }
private val arc: List<Pt> = rays.map { at(it, OUTER) }.toMutableList().also {
val dy = sqrt(OUTER * OUTER - (SPLIT_LEFT - CX) * (SPLIT_LEFT - CX))
it[0] = Pt(SPLIT_LEFT, CY - dy)
it[it.lastIndex] = Pt(SPLIT_LEFT, CY + dy)
}
private val leftInner: List<Pt> = run {
val dx = (SPLIT_LEFT - CX).toDouble()
val dy = sqrt(INNER * INNER - dx * dx)
val from = atan2(dy, dx)
val to = atan2(-dy, dx) + 2 * Math.PI
List(rays.size) { i -> at(from + (to - from) * i / (rays.size - 1), INNER) }
}
private val rightHalf: List<Pt> = run {
val dx = (SPLIT_RIGHT - CX).toDouble()
val oy = sqrt(OUTER * OUTER - dx * dx)
val iy = sqrt(INNER * INNER - dx * dx)
val outerFrom = atan2(-oy, dx)
val outerTo = atan2(oy, dx)
val innerFrom = atan2(iy, dx)
val innerTo = atan2(-iy, dx)
List(40) { i -> at(outerFrom + (outerTo - outerFrom) * i / 39, OUTER) } +
List(40) { i -> at(innerFrom + (innerTo - innerFrom) * i / 39, INNER) }
}
/** The left half, [bend] of the way from the square D side (0) to the arc (1). */
fun left(path: Path, bend: Float, px: (Float, Float) -> Offset) {
path.reset()
square.forEachIndexed { i, q ->
val r = arc[i]
val o = px(q.x + (r.x - q.x) * bend, q.y + (r.y - q.y) * bend)
if (i == 0) path.moveTo(o.x, o.y) else path.lineTo(o.x, o.y)
}
for (q in leftInner) px(q.x, q.y).let { path.lineTo(it.x, it.y) }
path.close()
}
fun right(path: Path, px: (Float, Float) -> Offset) {
path.reset()
rightHalf.forEachIndexed { i, q ->
val o = px(q.x, q.y)
if (i == 0) path.moveTo(o.x, o.y) else path.lineTo(o.x, o.y)
}
path.close()
}
}
@@ -0,0 +1,538 @@
package com.droiddeck.launcher.ui
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusManager
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.WirelessAdbFix
import kotlin.math.min
import kotlin.math.roundToInt
@Composable
fun WirelessAdbFixPage(
onBack: () -> Unit,
desiredEnabled: Boolean,
onOpenDeveloperOptions: () -> Unit,
onPair: (String, Int, String, (String?) -> Unit) -> Unit,
onFindConnectPort: (String, (Int?) -> Unit) -> Unit,
onApply: (String, Int, Boolean, (String?) -> Unit) -> Unit,
) {
val context = LocalContext.current
val savedAddress = remember { WirelessAdbFix.savedConnectionAddress(context) }
var step by rememberSaveable { mutableStateOf(if (savedAddress == null) 0 else 1) }
var pairingAddress by rememberSaveable { mutableStateOf("") }
var connectionAddress by rememberSaveable { mutableStateOf(savedAddress.orEmpty()) }
var pairingCode by rememberSaveable { mutableStateOf("") }
var busy by remember { mutableStateOf(false) }
var editing by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
var messageIsError by remember { mutableStateOf(false) }
val focusManager = LocalFocusManager.current
val keyboardController = LocalSoftwareKeyboardController.current
val pairingEndpoint = parseAdbAddress(pairingAddress)
val pairNow: () -> Unit = {
parseAdbAddress(pairingAddress)?.let { endpoint ->
keyboardController?.hide()
focusManager.clearFocus()
busy = true
editing = false
message = null
messageIsError = false
onPair(endpoint.host, endpoint.port, pairingCode) { error ->
pairingCode = ""
if (error != null) {
busy = false
message = error
messageIsError = true
} else {
step = 1
busy = true
message = "Paired. Finding the Wireless debugging port…"
onFindConnectPort(endpoint.host) { discoveredPort ->
if (discoveredPort == null) {
connectionAddress = formatAddressHost(endpoint.host) + ":"
busy = false
message = "Paired. Enter the port from Settings."
} else {
connectionAddress = formatAdbAddress(endpoint.host, discoveredPort)
message = "Device found. Applying the setting…"
onApply(endpoint.host, discoveredPort, desiredEnabled) { applyError ->
busy = false
if (applyError == null) {
step = 2
message = null
} else {
message = "Could not apply automatically. Check the address below and retry. $applyError"
messageIsError = true
}
}
}
}
}
}
}
}
val applyAddress: () -> Unit = {
parseAdbAddress(connectionAddress)?.let { endpoint ->
keyboardController?.hide()
focusManager.clearFocus()
busy = true
editing = false
message = null
messageIsError = false
onApply(endpoint.host, endpoint.port, desiredEnabled) { error ->
busy = false
if (error == null) {
step = 2
message = null
} else {
message = error
messageIsError = true
}
}
}
}
val pairAgain: () -> Unit = {
step = 0
pairingAddress = ""
pairingCode = ""
message = null
messageIsError = false
}
BackHandler { if (!busy) onBack() }
BoxWithConstraints(Modifier.fillMaxSize()) {
val compactSplit = maxWidth < 620.dp && maxHeight < 500.dp
val form: @Composable () -> Unit = {
WirelessStepForm(
step = step,
pairingAddress = pairingAddress,
onPairingAddressChange = { pairingAddress = it },
pairingCode = pairingCode,
onPairingCodeChange = { pairingCode = it.filter(Char::isDigit).take(6) },
connectionAddress = connectionAddress,
onConnectionAddressChange = { connectionAddress = it },
busy = busy,
message = message,
messageIsError = messageIsError,
compact = compactSplit,
editing = editing,
onEditingChanged = { editing = it },
focusManager = focusManager,
desiredEnabled = desiredEnabled,
canPair = pairingEndpoint != null && pairingCode.length == 6,
onPair = pairNow,
onApply = applyAddress,
onPairAgain = pairAgain,
)
}
SettingsPage(
host = rememberMenuHost(),
title = when {
compactSplit && step < 2 -> "Wireless debugging"
step == 2 -> "Child-process limit updated"
else -> "Change the child-process limit"
},
eyebrow = "Setup",
lede = when {
compactSplit && step == 0 -> "If the option is missing, pair over Wireless debugging."
compactSplit && step == 1 -> "Paired. Check IP address & Port in Wireless debugging."
compactSplit -> "The child-process limit was updated."
step == 0 -> "Use step 2 if Developer options has no child-process setting. In Android Settings, open Developer options → Wireless debugging → Pair device with pairing code."
step == 1 -> "Paired. Use the address below; update it from Wireless debugging → IP address & Port if needed."
else -> "The child-process limit was updated over Wireless debugging."
},
onBack = { if (!busy) onBack() },
action = if (compactSplit && step < 2) {
{ SecondaryButton("Developer options", compact = true, enabled = !busy, onClick = onOpenDeveloperOptions) }
} else null,
scrollContent = !compactSplit,
compactLayout = compactSplit,
) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 620.dp
if (step == 2) {
Column(
modifier = Modifier.widthIn(max = 680.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
SettingsGroup("Child-process limit", compact = compactSplit) {
Text(
"Android confirmed the limit is ${if (desiredEnabled) "on" else "off"}.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(14.dp),
)
}
PrimaryButton("Done", enabled = !busy, onClick = onBack)
}
} else if (compactSplit) {
Column(
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
form()
if (!editing) CompactComputerFallback(desiredEnabled)
}
} else {
val routes: @Composable () -> Unit = {
FallbackOrder(desiredEnabled, busy, onOpenDeveloperOptions)
}
if (wide) {
Row(
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(14.dp),
verticalAlignment = Alignment.Top,
) {
Column(Modifier.weight(1f)) { routes() }
Column(Modifier.weight(1f)) { form() }
}
} else {
Column(
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
routes()
form()
}
}
}
}
}
}
}
@Composable
private fun WirelessStepForm(
step: Int,
pairingAddress: String,
onPairingAddressChange: (String) -> Unit,
pairingCode: String,
onPairingCodeChange: (String) -> Unit,
connectionAddress: String,
onConnectionAddressChange: (String) -> Unit,
busy: Boolean,
message: String?,
messageIsError: Boolean,
compact: Boolean,
editing: Boolean,
onEditingChanged: (Boolean) -> Unit,
focusManager: FocusManager,
desiredEnabled: Boolean,
canPair: Boolean,
onPair: () -> Unit,
onApply: () -> Unit,
onPairAgain: () -> Unit,
) {
if (step == 0) {
SettingsGroup("2 · Pair Wireless debugging", compact = compact) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
) {
AdbTextField(
value = pairingAddress,
onValueChange = onPairingAddressChange,
label = "Pairing pop-up IP address & Port",
placeholder = "192.168.1.42:37123",
keyboardType = KeyboardType.Ascii,
imeAction = ImeAction.Next,
compact = compact,
onFocusChange = onEditingChanged,
onNext = { focusManager.moveFocus(FocusDirection.Next) },
)
Row(
verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth(),
) {
AdbTextField(
value = pairingCode,
onValueChange = onPairingCodeChange,
label = "Pairing code (PIN)",
placeholder = "6 digits",
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done,
compact = compact,
onFocusChange = onEditingChanged,
onDone = {
focusManager.clearFocus()
},
modifier = Modifier.weight(1f),
)
PrimaryButton("Pair", compact = compact, enabled = !busy && canPair, onClick = onPair)
}
StatusMessage(busy, message, isError = messageIsError)
}
}
} else {
SettingsGroup("2 · Apply over Wireless debugging", compact = compact) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
) {
AdbTextField(
value = connectionAddress,
onValueChange = onConnectionAddressChange,
label = "Connection IP address & Port",
placeholder = "192.168.1.42:45678",
keyboardType = KeyboardType.Ascii,
imeAction = ImeAction.Done,
compact = compact,
onFocusChange = onEditingChanged,
onDone = { focusManager.clearFocus() },
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth(),
) {
StatusMessage(busy, message, Modifier.weight(1f), isError = messageIsError)
SecondaryButton("Pair again", compact = compact, enabled = !busy, onClick = onPairAgain)
PrimaryButton(
if (desiredEnabled) "Turn limit on" else "Turn limit off",
compact = compact,
enabled = !busy && parseAdbAddress(connectionAddress) != null,
onClick = onApply,
)
}
}
}
}
}
@Composable
private fun AdbTextField(
value: String,
onValueChange: (String) -> Unit,
label: String,
keyboardType: KeyboardType,
imeAction: ImeAction,
modifier: Modifier = Modifier,
placeholder: String? = null,
compact: Boolean = false,
onFocusChange: (Boolean) -> Unit = {},
onNext: (() -> Unit)? = null,
onDone: (() -> Unit)? = null,
) {
val context = LocalContext.current
val palette = LocalPalette.current
val onValueChangeLatest = rememberUpdatedState(onValueChange)
val onNextLatest = rememberUpdatedState(onNext)
val onDoneLatest = rememberUpdatedState(onDone)
val onFocusChangeLatest = rememberUpdatedState(onFocusChange)
var focused by remember { mutableStateOf(false) }
val shape = RoundedCornerShape(8.dp)
val inputHeight = if (compact) 44.dp else 52.dp
val colors = MaterialTheme.colorScheme
Column(modifier = modifier.fillMaxWidth()) {
Text(
label,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Medium,
color = colors.onSurfaceVariant,
maxLines = 1,
)
Box(
modifier = Modifier
.fillMaxWidth()
.height(inputHeight)
.background(colors.surfaceVariant, shape)
.border(1.dp, if (focused) palette.signal else palette.line2, shape)
.padding(horizontal = 10.dp),
contentAlignment = Alignment.CenterStart,
) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { viewContext ->
EditText(viewContext).apply {
isSingleLine = true
setHorizontallyScrolling(true)
background = null
setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0)
setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f)
setTextColor(colors.onBackground.toArgb())
setHintTextColor(colors.onSurfaceVariant.toArgb())
contentDescription = label
inputType = if (keyboardType == KeyboardType.Number) {
InputType.TYPE_CLASS_NUMBER
} else {
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
}
imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI
hint = placeholder
setOnEditorActionListener { _, actionId, event ->
val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER
when {
imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> {
onNextLatest.value?.invoke()
true
}
imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> {
onDoneLatest.value?.invoke()
true
}
else -> false
}
}
setOnFocusChangeListener { _, hasFocus ->
focused = hasFocus
onFocusChangeLatest.value(hasFocus)
}
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(s: Editable?) {
onValueChangeLatest.value(s?.toString().orEmpty())
}
})
}
},
update = { editText ->
editText.setTextColor(colors.onBackground.toArgb())
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
editText.hint = placeholder
editText.contentDescription = label
if (editText.text.toString() != value) {
val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length
editText.setText(value)
editText.setSelection(min(cursor, value.length))
}
},
)
}
}
}
@Composable
private fun FallbackOrder(
desiredEnabled: Boolean,
busy: Boolean,
onOpenDeveloperOptions: () -> Unit,
) {
SettingsGroup("Other ways to change it") {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text("1 · Developer options (try first)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
Text("Set “Restrict child processes” ${if (desiredEnabled) "on" else "off"}.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
SecondaryButton("Open Developer options", enabled = !busy, onClick = onOpenDeveloperOptions)
Text("3 · Computer ADB (last resort)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
Text("Only if Wireless debugging is unavailable.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(
PhantomProcessLimit.adbCommand(desiredEnabled),
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
private fun CompactComputerFallback(desiredEnabled: Boolean) {
SettingsGroup("3 · Computer ADB last resort", compact = true) {
Text(
PhantomProcessLimit.adbCommand(desiredEnabled),
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace),
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp),
)
}
}
@Composable
private fun StatusMessage(busy: Boolean, message: String?, modifier: Modifier = Modifier, isError: Boolean = false) {
if (busy) {
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
Text(message ?: "Working…", style = MaterialTheme.typography.bodySmall)
}
} else {
message?.let {
Text(
it,
modifier = modifier,
style = MaterialTheme.typography.bodySmall,
color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
private data class AdbEndpoint(val host: String, val port: Int)
private fun parseAdbAddress(value: String): AdbEndpoint? {
val address = value.trim()
val host: String
val portText: String
if (address.startsWith("[")) {
val closingBracket = address.indexOf(']')
if (closingBracket <= 1 || address.getOrNull(closingBracket + 1) != ':') return null
host = address.substring(1, closingBracket)
if (':' !in host) return null
portText = address.substring(closingBracket + 2)
} else {
val colon = address.lastIndexOf(':')
if (colon <= 0 || address.indexOf(':') != colon) return null
host = address.substring(0, colon)
portText = address.substring(colon + 1)
}
if (host.isBlank() || host.any(Char::isWhitespace)) return null
val port = portText.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null
return AdbEndpoint(host, port)
}
private fun formatAddressHost(host: String): String = if (':' in host) "[$host]" else host
private fun formatAdbAddress(host: String, port: Int): String = "${formatAddressHost(host)}:$port"
private fun imeActionFlag(action: ImeAction): Int = when (action) {
ImeAction.Next -> EditorInfo.IME_ACTION_NEXT
ImeAction.Done -> EditorInfo.IME_ACTION_DONE
ImeAction.Go -> EditorInfo.IME_ACTION_GO
ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH
else -> EditorInfo.IME_ACTION_UNSPECIFIED
}
@@ -24,7 +24,7 @@ class HdrProbe(
) {
/** Why HDR cannot be offered, or null when it can. */
val reason: String? = when {
Build.VERSION.SDK_INT < 29 -> "needs Android 10 or newer (display layers with a colour space)"
Build.VERSION.SDK_INT < 29 -> "needs Android 10 or newer (display layers with a color space)"
!hdr10 -> if (formats.isEmpty()) "this display reports no HDR support" else "this display supports $formats, not HDR10"
else -> null
}
@@ -26,6 +26,10 @@ public final class WaylandCompositor {
* listener must marshal to the UI thread itself. */
public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; }
public static synchronized void clearFirstFrameListener(Runnable r) {
if (firstFrameListener == r) firstFrameListener = null;
}
/** Invoked from native (banner_on_first_frame) on the first present. */
@SuppressWarnings("unused")
static void onFirstFramePresented() {
@@ -52,6 +56,10 @@ public final class WaylandCompositor {
public static void setGameListener(GameListener l) { gameListener = l; }
public static synchronized void clearGameListener(GameListener l) {
if (gameListener == l) gameListener = null;
}
/** Invoked from native (banner_on_game_surface). */
@SuppressWarnings("unused")
static void onGameSurface(String window, String gpuName) {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 367 B

After

Width:  |  Height:  |  Size: 924 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 233 B

After

Width:  |  Height:  |  Size: 530 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 508 B

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 897 B

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

After

Width:  |  Height:  |  Size: 11 KiB

+6
View File
@@ -6,6 +6,12 @@
<item>By default, leaving the app pauses Steam; it picks up where it left off when you come back.</item>
<item>Your controller appears as an Xbox 360 pad. Otherwise, use the on-screen controls.</item>
</string-array>
<string-array name="loading_hints_desktop">
<item>First run sets up the desktop. This may take a few minutes.</item>
<item>By default, leaving the app pauses the session; it picks up where it left off when you come back.</item>
<item>Touch works as a touchpad: drag to move the pointer, tap to click.</item>
<item>Your controller appears as an Xbox 360 pad. Otherwise, use the on-screen controls.</item>
</string-array>
<string name="session_channel">Session</string>
<string name="session_channel_description">Shows while a Steam or desktop session is open</string>
<string name="session_notification">Steam is running</string>
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.core
import java.io.File
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
class ArchivePathsTest {
private lateinit var root: File
private lateinit var dest: File
@Before fun setUp() {
root = Files.createTempDirectory("archive-paths").toFile()
dest = File(root, "dest").apply { mkdirs() }
}
@After fun tearDown() {
root.deleteRecursively()
}
@Test fun plainEntryLandsInside() {
assertEquals(File(dest, "usr/bin/sh").canonicalPath, ArchivePaths.inside(dest, "usr/bin/sh")!!.canonicalPath)
}
@Test fun dotEntryIsTheDestination() {
assertEquals(dest.canonicalPath, ArchivePaths.inside(dest, "./")!!.canonicalPath)
}
@Test fun parentTraversalIsRefused() {
assertNull(ArchivePaths.inside(dest, "../escape"))
assertNull(ArchivePaths.inside(dest, "usr/../../escape"))
}
@Test fun siblingWithSharedPrefixIsRefused() {
File(root, "dest-other").mkdirs()
assertNull(ArchivePaths.inside(dest, "../dest-other/x"))
}
@Test fun symlinkOutOfTheTreeIsRefused() {
Files.createSymbolicLink(File(dest, "link").toPath(), root.toPath())
assertNull(ArchivePaths.inside(dest, "link/escape"))
}
}
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.core
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class HashesTest {
private fun file(text: String): File =
Files.createTempFile("hashes", ".bin").toFile().apply { writeText(text); deleteOnExit() }
@Test fun sha256OfKnownInput() {
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", Hashes.sha256(file("abc")))
}
@Test fun sha512OfKnownInput() {
assertEquals(
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" +
"2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
Hashes.sha512(file("abc")),
)
}
@Test fun githubDigestIsRecognised() {
val hex = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
assertTrue(Hashes.isGithubSha256("sha256:$hex"))
assertEquals(hex, Hashes.githubSha256("sha256:$hex"))
assertEquals(hex.uppercase(), Hashes.githubSha256("SHA256:${hex.uppercase()}"))
}
@Test fun anythingElseIsNotADigest() {
assertFalse(Hashes.isGithubSha256(null))
assertFalse(Hashes.isGithubSha256(""))
assertFalse(Hashes.isGithubSha256("sha256:abc"))
assertFalse(Hashes.isGithubSha256("sha512:" + "0".repeat(64)))
assertNull(Hashes.githubSha256("md5:0123"))
}
}
@@ -0,0 +1,58 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class LogRedactorTest {
@Test fun labelledJwtIsRedacted() {
val out = LogRedactor.redact("Using JWT 25484942796017334")
assertFalse(out.contains("25484942796017334"))
assertTrue(out.contains("<redacted:jwt>"))
}
@Test fun secretPairKeepsItsKey() {
val out = LogRedactor.redact("GET /x?sessionid=abcdef123456 200")
assertFalse(out.contains("abcdef123456"))
assertTrue(out.contains("sessionid="))
}
@Test fun plainKeyValueSurvives() {
assertEquals("language key=english", LogRedactor.redact("language key=english"))
}
@Test fun steamIdIsMaskedNotDeleted() {
assertEquals("user 76561********1234", LogRedactor.redact("user 76561198012341234"))
}
@Test fun webApiKeyIsRedactedButDepotChunkIsKept() {
val key = "0123456789abcdef0123456789abcdef"
val chunk = "0123456789abcdef0123456789abcdef01234567"
assertFalse(LogRedactor.redact("key $key").contains(key))
assertTrue(LogRedactor.redact("chunk $chunk").contains(chunk))
}
@Test fun emailIsRedacted() {
assertEquals("login <redacted:email> ok", LogRedactor.redact("login someone@example.com ok"))
}
@Test fun clockTimeIsNotAnAddress() {
val line = "[2026-09-27 10:03:05] Startup"
assertEquals(line, LogRedactor.redact(line))
}
@Test fun redactingTwiceChangesNothing() {
val lines = listOf(
"Using JWT 25484942796017334",
"token=abcdefghijklmnop sessionid=qrstuvwxyz123",
"user 76561198012341234 [U:1:52075506]",
"external address 2607:f8b0:4005:80a::200e",
"OnLoginStateChange someaccount 2 1 0 0",
)
for (line in lines) {
val once = LogRedactor.redact(line)
assertEquals(once, LogRedactor.redact(once))
}
}
}
@@ -0,0 +1,29 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Test
class PhantomProcessLimitTest {
@Test
fun developerOptionsToggleAloneCountsAsOff() {
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.status(null, "false"))
}
@Test
fun globalSettingWinsOverTheProperty() {
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.status("false", "true"))
assertEquals(PhantomProcessStatus.ENABLED, PhantomProcessLimit.status("true", "false"))
}
@Test
fun emptyGlobalFallsThroughToTheProperty() {
assertEquals(PhantomProcessStatus.ENABLED, PhantomProcessLimit.status("", "true"))
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.status(" ", "0"))
}
@Test
fun neitherSetIsUnset() {
assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status(null, null))
assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status("", ""))
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
# DroidDeck mark
`droiddeck-mark.svg` is the editable source for the split-D mark. The blue orb is `#1A9FFF`; its halo and the two separator bars are transparent cutouts. The bars are centered on x=63.97, the endpoint of the curved half in the original Steam Deck symbol, and use the halo's 15.83-unit thickness. The mark is optically centered in its view box with a small rightward offset to balance its asymmetric silhouette.
`droiddeck-mark.svg` is the editable source for the white split-D mark. The blue orb is `#1A9FFF`; its halo and the two separator bars are transparent cutouts. The bars are centered on x=63.97, the endpoint of the curved half in the original Steam Deck symbol, and use the halo's 15.83-unit thickness. The mark is optically centered in its view box with a small rightward offset to balance its asymmetric silhouette. Place it on black when a background is needed.
Android currently consumes raster resources for the launcher layers and the Compose logo. The `mipmap-*/ic_launcher_foreground.png` files are density-sized exports of the SVG, with the mark kept inside the adaptive icon safe area. The matching backgrounds are white. `drawable-nodpi/logo.png` composes the same mark on a white circular badge for use on the app's dark surfaces.
Android currently consumes raster resources for the launcher layers and the Compose logo. The `mipmap-*/ic_launcher_foreground.png` files are density-sized exports of the SVG, with the mark kept inside the adaptive icon safe area. The matching backgrounds are black. `drawable-nodpi/logo.png` composes the same mark on a black circular badge.
+71
View File
@@ -0,0 +1,71 @@
# DroidDeck boot animation
This source accompanies the single Steam startup movie bundled by the app:
`app/src/main/assets/steam-startup/droiddeck-startup.webm` (1280×720 at 30 fps, pitch black background, VP8 video
with Opus audio). `droiddeck-boot.html` is the editable animation; the scripts and WAV below
render the animation at the bundled playback profile. No alternate MP4 or WebM exports are kept in the repository.
From the repository root, render the movie with:
python3 artwork/boot-animation-source/render.py 1280 720 30 app/src/main/assets/steam-startup/droiddeck-startup.webm dark
The bundled profile reduces decoded pixels per second by 78% compared with 1080p/60.
VP8 also lowers software decode cost while Steam is starting. Keep the bundled movie at
720p/30; higher-resolution exports are intended for sharing.
The app stages that file into Steam's `config/uioverrides/movies` folder before each session. If
Steam still has its built-in startup movie selected, DroidDeck sets this movie as the device's
startup default before Steam starts. A custom startup movie the user selected later is preserved.
To regenerate the soundtrack, run these commands from this directory:
python3 events.py
python3 sound.py
The animation and audio are both procedurally generated; the included WAV is the soundtrack used
for the bundled render.
`droiddeck-boot.html` holds the whole animation. Every frame is a pure function of time, so the
preview page and the video render draw exactly the same thing. Open it in a browser to scrub, slow
it down or step frame by frame (arrow keys).
## Re-render the video
pip install playwright && playwright install chromium # ffmpeg with libvpx also required
python3 render.py 1280 720 30 droiddeck-boot-1280x720.webm
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.mp4 # .mp4 = H.264 for sharing
python3 render.py 1280 720 30 droiddeck-boot-dark-1280x720.webm dark # dark version
Each frame gets real motion blur (180° shutter, adaptive sub-frames). Output is VP8 for .webm or H.264 for .mp4, both BT.709,
so the orb stays #1A9FFF after compression.
## Sound
Every sound is synthesized in `sound.py` (no samples) and placed on the exact physics events the
animation reports, so hits stay frame-accurate even after you change the timing. Key: D major.
python3 events.py # export impact times, rocking, piece speeds from the animation
python3 sound.py # -> droiddeck-boot-sound.wav (-18 LUFS, -1 dBFS peak)
python3 embed_sound.py # put it in the preview page
python3 render.py ... # muxes the wav in automatically (Opus in .webm, AAC in .mp4)
The soundtrack is built from the final chord. Each piece lands on one of its notes as a soft, muted
tone (legs D, ball A with a quieter echo, bowl F#), the wobble and jump play in silence, and the
lock lands with the same soft voice and plays all the notes together. Tweak the cue sheet in `sound.py`: the `tock(...)` calls under
`# 1. the stack`, the chord list under `# 4. lock`, and the room reverb mix (`.14 * wet`).
## Where to tweak
- Timing of the drops: `archDrop`, `ballDrop`, `domeDrop` (start time, height, bounciness `e`).
- The balancing act: `SWAY` keyframes (time, lean). Bigger values = bigger wobble. The bowl leads,
the ball chases it (`sway(t - .12)`), the legs follow (`sway(t - .10)`).
- The catch-hop on the big wobble: `HOP` (start time, duration, sideways distance, height).
- Crouch before the jump: `crouchA/B/D`.
- Jump and lock-in: `FL` (rise time, apex height, lock time, how far pieces spread).
- Colors for each version (pieces, background, shadows, lock glow): `THEMES` (light, dark).
- Total length: `DUR`.
## Install as the Steam startup movie
Put the .webm in `~/.steam/root/config/uioverrides/movies/`, then pick it in
Steam > Settings > Customization > Startup Movie.
@@ -0,0 +1,700 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>DroidDeck boot animation</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap" rel="stylesheet">
<style>
:root{
box-sizing:border-box;
padding-top:env(safe-area-inset-top,0px);
padding-bottom:env(safe-area-inset-bottom,0px);
--page:#E2E8EE; --panel:#F3F6F9; --ink:#131a21; --muted:#56636F; --line:rgba(19,26,33,.12);
--track:rgba(19,26,33,.14); --accent:#1A9FFF; --accent-ink:#0B6FC2; --stage-edge:rgba(19,26,33,.10);
--font:"Sora", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
--code:ui-monospace, "SF Mono", Menlo, Consolas, monospace;
}
@media (prefers-color-scheme: dark){
:root:not([data-theme="light"]){
--page:#0D1319; --panel:#151D25; --ink:#DCE5ED; --muted:#8A98A6; --line:rgba(220,229,237,.12);
--track:rgba(220,229,237,.16); --accent-ink:#5CB8FF; --stage-edge:rgba(0,0,0,.5);
}
}
:root[data-theme="dark"]{
--page:#0D1319; --panel:#151D25; --ink:#DCE5ED; --muted:#8A98A6; --line:rgba(220,229,237,.12);
--track:rgba(220,229,237,.16); --accent-ink:#5CB8FF; --stage-edge:rgba(0,0,0,.5);
}
*,*::before,*::after{box-sizing:inherit}
html{scroll-padding-top:env(safe-area-inset-top,0px)}
body{margin:0;background:var(--page);color:var(--ink);font-family:var(--font);font-size:15px;line-height:1.55;-webkit-font-smoothing:antialiased}
main{max-width:980px;margin:0 auto;padding:28px 20px 40px}
header{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:18px}
h1{font-size:1.35rem;font-weight:600;letter-spacing:-.01em;margin:0}
.meta{color:var(--muted);font-size:.9rem;margin:0}
.stage{position:relative;width:100%;aspect-ratio:16/10;border-radius:14px;overflow:hidden;background:#D6E1EA;box-shadow:0 0 0 1px var(--stage-edge),0 18px 50px -24px rgba(10,20,30,.45)}
.stage canvas{display:block;width:100%;height:100%;cursor:pointer}
.stage.dark{background:#000}
.stage.dark .hint{color:#C9D3DD}
.head-l{display:flex;align-items:baseline;gap:14px;flex-wrap:wrap}
.version{display:inline-flex;border-radius:999px;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:3px}
.version button{border:0;background:none;border-radius:999px;padding:5px 14px;font-size:.85rem;cursor:pointer;color:var(--muted)}
.version button[aria-pressed="true"]{background:var(--ink);color:var(--page)}
.version button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
.stage .hint{position:absolute;inset:auto 0 14px 0;text-align:center;font-size:.85rem;color:#2c3a47;opacity:0;transition:opacity .25s}
.stage.ended .hint{opacity:.75}
.controls{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:14px;margin-top:16px}
button{font:inherit;color:inherit}
.play{display:inline-flex;align-items:center;gap:8px;border:0;background:var(--accent);color:#fff;border-radius:999px;padding:9px 16px 9px 12px;font-weight:600;font-size:.9rem;cursor:pointer}
.play svg{width:18px;height:18px}
.play:hover{filter:brightness(1.06)}
.play:focus-visible,.speed button:focus-visible,.beat:focus-visible,input[type=range]:focus-visible,.fs:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
.scrub{position:relative;padding-bottom:22px}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:28px;background:transparent;margin:0;cursor:pointer}
input[type=range]::-webkit-slider-runnable-track{height:4px;border-radius:4px;background:linear-gradient(to right,var(--accent) var(--p,0%),var(--track) var(--p,0%))}
input[type=range]::-moz-range-track{height:4px;border-radius:4px;background:linear-gradient(to right,var(--accent) var(--p,0%),var(--track) var(--p,0%))}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;border-radius:50%;background:var(--ink);margin-top:-6px;border:3px solid var(--page)}
input[type=range]::-moz-range-thumb{width:12px;height:12px;border-radius:50%;background:var(--ink);border:3px solid var(--page)}
.beats{position:absolute;left:8px;right:8px;bottom:0;height:20px}
.beat{position:absolute;transform:translateX(-50%);border:0;background:none;padding:0 2px;font-size:.74rem;color:var(--muted);cursor:pointer;white-space:nowrap}
.beat:first-child{transform:translateX(-4px)}
.beat:first-child::before{left:4px}
.beat::before{content:"";position:absolute;left:50%;top:-9px;width:1px;height:6px;background:var(--muted);opacity:.6}
.beat:hover,.beat.on{color:var(--ink)}
.right{display:flex;align-items:center;gap:10px}
.time{font-variant-numeric:tabular-nums;font-size:.85rem;color:var(--muted);min-width:78px;text-align:right}
.speed{display:inline-flex;border-radius:999px;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:3px}
.speed button{border:0;background:none;border-radius:999px;padding:4px 10px;font-size:.8rem;cursor:pointer;color:var(--muted)}
.speed button[aria-pressed="true"]{background:var(--ink);color:var(--page)}
.snd{display:inline-flex;align-items:center;gap:6px;border:0;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);border-radius:999px;height:32px;padding:0 12px 0 9px;font-size:.8rem;cursor:pointer;color:var(--ink)}
.snd svg{width:18px;height:18px}
.snd[aria-pressed="true"]{background:var(--accent);color:#fff;box-shadow:none}
.snd:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
.fs{border:0;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);border-radius:999px;width:32px;height:32px;display:grid;place-items:center;cursor:pointer;color:var(--ink)}
.fs svg{width:16px;height:16px}
.install{margin-top:34px;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:28px;border-top:1px solid var(--line);padding-top:24px}
.install h2{font-size:1rem;font-weight:600;margin:0 0 8px}
.install p,.install ol{margin:0;color:var(--muted);font-size:.9rem;max-width:62ch}
.install ol{padding-left:1.2em}
.install li+li{margin-top:6px}
code{font-family:var(--code);font-size:.84em;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:1px 6px;border-radius:6px;color:var(--ink);overflow-wrap:anywhere}
@media (max-width:640px){
main{padding:18px 14px 32px}
.controls{grid-template-columns:auto 1fr;row-gap:6px}
.right{grid-column:1 / -1;justify-content:space-between}
.install{grid-template-columns:1fr}
.beat{font-size:.68rem}
.snd span{display:none}
.snd{padding:0 8px}
.right{gap:8px}
}
body.render{background:#000;margin:0}
body.render main{display:none}
</style>
</head>
<body>
<main>
<header>
<div class="head-l">
<h1>DroidDeck boot animation</h1>
<p class="meta" id="meta">6.3 s at 60 fps, with sound</p>
</div>
<div class="version" role="group" aria-label="Version">
<button data-v="light" aria-pressed="true">Light</button>
<button data-v="dark" aria-pressed="false">Dark</button>
</div>
</header>
<div class="stage" id="stage">
<canvas id="cv" aria-label="DroidDeck boot animation: three logo pieces stack into a little droid balancing a bowl on its head, then jump and lock into the DroidDeck mark"></canvas>
<div class="hint" id="hint">Tap to replay</div>
</div>
<div class="controls">
<button class="play" id="play" aria-label="Pause">
<svg viewBox="0 0 24 24" aria-hidden="true"><path id="playIcon" fill="currentColor" d="M7 5h4v14H7zM13 5h4v14h-4z"/></svg>
<span id="playLabel">Pause</span>
</button>
<div class="scrub">
<input type="range" id="scrub" min="0" max="1000" step="1" value="0" aria-label="Timeline">
<div class="beats" id="beats"></div>
</div>
<div class="right">
<span class="time" id="time">0.00 / 6.30</span>
<div class="speed" role="group" aria-label="Playback speed">
<button data-s="1" aria-pressed="true">1×</button>
<button data-s="0.5" aria-pressed="false">½×</button>
<button data-s="0.25" aria-pressed="false">¼×</button>
</div>
<button class="snd" id="snd" aria-pressed="false" aria-label="Sound">
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M3 9.5h4l5-4.2v13.4l-5-4.2H3z"/><path id="sndMark" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M16 9.5l5 5M21 9.5l-5 5"/></svg>
<span>Sound</span>
</button>
<button class="fs" id="fs" aria-label="Full screen" hidden>
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>
</button>
</div>
</div>
<section class="install">
<div>
<h2>Use it as the Steam startup movie</h2>
<ol>
<li>Put the <code>.webm</code> file in <code>~/.steam/<wbr>root/<wbr>config/<wbr>uioverrides/<wbr>movies/</code>. Create the folders if they don’t exist.</li>
<li>In Steam, open Settings &gt; Customization &gt; Startup Movie and pick it.</li>
</ol>
</div>
<div>
<h2>Which file to ship</h2>
<p>Ship the dark version if your Steam UI is dark: it hands off to the library without a bright flash. The 1280×800 cut matches Steam Deck and is the safe default. The 1920×1080 cut is sharper on phones and TVs. Steam needs the <code>.webm</code>; the <code>.mp4</code> files are for sharing. Everything is drawn and synthesized in code, so the included scripts can output any other size.</p>
</div>
</section>
</main>
<script>
/* =====================================================================
DroidDeck boot animation engine
Every frame is a pure function of time t, so the live preview and the
offline video render draw exactly the same thing.
Units: logo units from droiddeck-mark.svg. World origin = frame centre,
y points down. The frame is always 690 units tall.
===================================================================== */
const DD = (() => {
'use strict';
const deg = Math.PI / 180;
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
const eio = t => { t = clamp(t); return t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; };
const eInQ = t => { t = clamp(t); return t * t; };
const eOutC = t => { t = clamp(t); return 1 - Math.pow(1 - t, 3); };
// ---- 2D affine helpers. m = [a,b,c,d,e,f] (canvas setTransform order)
const mul = (m, n) => [
m[0]*n[0] + m[2]*n[1], m[1]*n[0] + m[3]*n[1],
m[0]*n[2] + m[2]*n[3], m[1]*n[2] + m[3]*n[3],
m[0]*n[4] + m[2]*n[5] + m[4], m[1]*n[4] + m[3]*n[5] + m[5]];
const T = (x, y) => [1, 0, 0, 1, x, y];
const R = a => { const c = Math.cos(a), s = Math.sin(a); return [c, s, -s, c, 0, 0]; };
const S = (x, y) => [x, 0, 0, y, 0, 0];
const chain = (...ms) => ms.reduce(mul);
const ap = (m, p) => ({ x: m[0]*p.x + m[2]*p.y + m[4], y: m[1]*p.x + m[3]*p.y + m[5] });
const rv = (a, x, y) => { const c = Math.cos(a), s = Math.sin(a); return { x: c*x - s*y, y: s*x + c*y }; };
// ---- Geometry straight from the SVG
const G = { L: -31.98, B: 223.72, slotL: 56.055, slotR: 71.885, cy: 111.86,
dcx: 63.97, dR: 111.86, hcx: 63.98, hR: 71.81, ocx: 63.98, oR: 55.98 };
const ORB = '#1A9FFF';
const THEMES = {
light: { ink: '#1b1b1b', bg: ['#EDF3F8', '#DCE6EE', '#B6C7D6'], shadow: '22,40,58', shadowK: 1, ringA: 1, ringGlow: 0, glow: 0, noise: 3 },
// Keep the shipped Steam render black between and around the animated pieces.
dark: { ink: '#FFFFFF', bg: ['#000000', '#000000', '#000000'], shadow: '0,0,0', shadowK: 2.3, ringA: 1.5, ringGlow: 14, glow: .34, noise: 0 },
};
let TH = THEMES.light, THN = 'light';
const setTheme = n => { THN = THEMES[n] ? n : 'light'; TH = THEMES[THN]; };
const ORB_C = { x: G.ocx, y: G.cy };
function archPath() { // left piece: the "bridge"
const p = new Path2D();
const dx = G.slotL - G.hcx, hy = Math.sqrt(G.hR*G.hR - dx*dx);
p.moveTo(G.L, 0); p.lineTo(G.slotL, 0); p.lineTo(G.slotL, G.cy - hy);
p.arc(G.hcx, G.cy, G.hR, Math.atan2(-hy, dx), Math.atan2(hy, dx), true);
p.lineTo(G.slotL, G.B); p.lineTo(G.L, G.B); p.closePath();
return p;
}
function domePath() { // right piece: the curve of the D
const dxo = G.slotR - G.dcx, hyo = Math.sqrt(G.dR*G.dR - dxo*dxo);
const dxi = G.slotR - G.hcx, hyi = Math.sqrt(G.hR*G.hR - dxi*dxi);
const p = new Path2D();
p.moveTo(G.slotR, G.cy - hyo);
p.arc(G.dcx, G.cy, G.dR, Math.atan2(-hyo, dxo), Math.atan2(hyo, dxo), false);
p.lineTo(G.slotR, G.cy + hyi);
p.arc(G.hcx, G.cy, G.hR, Math.atan2(hyi, dxi), Math.atan2(-hyi, dxi), true);
p.closePath();
return p;
}
function orbPath() { const p = new Path2D(); p.arc(G.ocx, G.cy, G.oR, 0, Math.PI*2); return p; }
const PATH = { arch: archPath(), dome: domePath(), orb: orbPath() };
// centroids (numerical, symmetric in y)
function centroid(path, x0, x1) {
const c = document.createElement('canvas').getContext('2d');
let n = 0, sx = 0;
for (let x = x0; x <= x1; x += .5) for (let y = 0; y <= G.B; y += .5)
if (c.isPointInPath(path, x, y)) { n++; sx += x; }
return { x: sx / n, y: G.cy };
}
const CEN = { arch: centroid(PATH.arch, G.L, G.slotL), dome: centroid(PATH.dome, G.slotR, 176) };
// anchors: the point of each piece that touches whatever it stands on
const ANC = { arch: { x: G.slotL, y: G.cy }, ball: { x: G.ocx, y: G.cy + G.oR }, dome: { x: G.hcx + G.hR, y: G.cy } };
const HA = G.slotL - G.L; // arch height when standing (88.035)
const WA = G.cy; // arch half width (111.86)
const FOOT_HALF = (G.cy - (G.cy - Math.sqrt(G.hR*G.hR - (G.slotL-G.hcx)**2))) ; // unused helper
const FEET = [{ x: G.slotL, y: 20.24 }, { x: G.slotL, y: G.B - 20.24 }]; // foot centres (piece coords)
// ---- Scene constants
const VIEW_H = 690; // world units visible vertically
const FLOOR = 150;
const GRAV = 6500;
const DUR = 6.30;
const T_L = 4.00; // lift-off
// ------------------------------------------------------------------
// Drops: exact ballistic bounces (height above whatever you land on)
// ------------------------------------------------------------------
function drop(o) {
const g = GRAV, segs = [], impacts = [];
let t = o.t0, v = o.v0;
let tau = (-v + Math.sqrt(v*v + 2*g*o.h0)) / g;
segs.push({ ts: t, te: t + tau, h0: o.h0, vu: -v });
t += tau; v = v + g*tau; impacts.push({ t, v });
for (;;) {
const vu = o.e * v; if (vu < o.minV) break;
const d = 2*vu / g; segs.push({ ts: t, te: t + d, h0: 0, vu });
t += d; v = vu; impacts.push({ t, v });
}
const rest = t;
const seg = tt => { for (const s of segs) if (tt < s.te) return s; return null; };
return {
o, impacts, rest, land: impacts[0].t,
h(tt) { if (tt <= o.t0) return o.h0; const s = seg(tt); if (!s) return 0; const u = tt - s.ts; return Math.max(0, s.h0 + s.vu*u - .5*g*u*u); },
v(tt) { if (tt <= o.t0 || tt >= rest) return 0; const s = seg(tt); return s ? s.vu - g*(tt - s.ts) : 0; },
air(tt) { return tt > o.t0 && tt < rest; }
};
}
const archDrop = drop({ t0: 0.10, h0: 520, v0: 250, e: 0.20, minV: 300 });
const ballDrop = drop({ t0: 0.50, h0: 440, v0: 250, e: 0.45, minV: 170 });
const domeDrop = drop({ t0: 1.15, h0: 330, v0: 250, e: 0.24, minV: 250 });
// ------------------------------------------------------------------
// The balancing act: one master sway curve, everything else follows it
// through springs so the parts lag, overshoot and settle on their own.
// ------------------------------------------------------------------
const SWAY = [[1.60, 0], [1.90, .42], [2.24, -.70], [2.62, .95], [2.82, 1.10],
[3.08, -.44], [3.30, .16], [3.50, 0]];
function sway(t) {
if (t <= SWAY[0][0] || t >= SWAY[SWAY.length-1][0]) return 0;
for (let i = 0; i < SWAY.length - 1; i++) {
const [ta, va] = SWAY[i], [tb, vb] = SWAY[i+1];
if (t < tb) { const p = (t - ta)/(tb - ta); return va + (vb - va)*(.5 - .5*Math.cos(Math.PI*p)); }
}
return 0;
}
// legs hop sideways to get back under the bowl on the big wobble
const HOP = { t: 2.70, d: .19, dx: 26, h: 16 };
const hopX = t => HOP.dx*eio((t - HOP.t)/HOP.d);
const hopH = t => (t > HOP.t && t < HOP.t + HOP.d) ? HOP.h*Math.sin(Math.PI*(t - HOP.t)/HOP.d) : 0;
// crouch before the jump (added straight onto squash)
function crouch(t, amt, a, b, hold) {
if (t < a || t >= T_L) return 0;
if (t < b) return amt * eio((t - a)/(b - a));
if (t < hold) return amt;
return amt * (1 - eInQ((t - hold)/(T_L - hold)));
}
const crouchA = t => crouch(t, .17, 3.56, 3.84, 3.91);
const crouchB = t => crouch(t, .12, 3.60, 3.86, 3.91);
const crouchD = t => crouch(t, .09, 3.64, 3.88, 3.91);
const PHI_FALL = 5*deg, PSI_FALL = -6*deg, U0 = 12;
const ROLL = G.oR/G.dR; // bowl radius is 2x the ball: it turns 1.5x as it rolls
const DT = 1/1200, N = Math.ceil((DUR + .2)/DT);
const SIG = { phi: new Float32Array(N), u: new Float32Array(N), psi: new Float32Array(N),
qA: new Float32Array(N), qB: new Float32Array(N), qD: new Float32Array(N) };
function peakFactor(w, z) { // peak of a unit-velocity kick
const wd = w*Math.sqrt(1 - z*z), ts = Math.atan(wd/(z*w))/wd;
return Math.exp(-z*w*ts)*Math.sin(wd*ts)/wd;
}
const SPR = { A: [40, .32], B: [34, .28], D: [36, .34] };
const kick = (k, peak) => peak / peakFactor(SPR[k][0], SPR[k][1]);
(function simulate() {
const K = [];
const v1a = archDrop.impacts[0].v, v1b = ballDrop.impacts[0].v, v1d = domeDrop.impacts[0].v;
archDrop.impacts.forEach(i => K.push({ t: i.t, k: 'A', dv: kick('A', .13 * i.v/v1a) }));
ballDrop.impacts.forEach(i => { const r = i.v/v1b;
K.push({ t: i.t, k: 'B', dv: kick('B', .24*r) }); K.push({ t: i.t, k: 'A', dv: kick('A', .06*r) });
K.push({ t: i.t, k: 'phi', dv: .55*r }); });
domeDrop.impacts.forEach(i => { const r = i.v/v1d;
K.push({ t: i.t, k: 'D', dv: kick('D', .11*r) }); K.push({ t: i.t, k: 'B', dv: kick('B', .17*r) });
K.push({ t: i.t, k: 'A', dv: kick('A', .07*r) }); });
K.push({ t: HOP.t + HOP.d, k: 'A', dv: kick('A', .07) }); K.push({ t: HOP.t + HOP.d, k: 'B', dv: kick('B', .06) });
K.push({ t: HOP.t + HOP.d, k: 'D', dv: kick('D', .04) });
K.sort((a, b) => a.t - b.t);
let phi = PHI_FALL, phiV = 0, phiA = 0, u = U0, uV = 0, psi = PSI_FALL, psiV = 0;
const q = { A: [0, 0], B: [0, 0], D: [0, 0] };
let ki = 0, crossings = 0, lastSign = 1;
for (let i = 0; i < N; i++) {
const t = i*DT;
while (ki < K.length && K[ki].t <= t) {
const k = K[ki++];
if (k.k === 'phi') phiV += k.dv; else q[k.k][1] += k.dv;
}
const s = sway(t);
// arch rocking on its feet
if (t < archDrop.land) { phi = PHI_FALL; phiV = 0; phiA = 0; }
else {
const w = 20, z = .38, tgt = 5.6*deg*sway(t - .10);
phiA = -w*w*(phi - tgt) - 2*z*w*phiV; phiV += phiA*DT; phi += phiV*DT;
const sg = Math.sign(phi) || lastSign;
if (sg !== lastSign && crossings < 2 && t < 1.0) { q.A[1] += kick('A', .035); crossings++; }
lastSign = sg;
}
// ball rolling along the arch top
if (t < ballDrop.rest) { u = U0; uV = 0; }
else { const w = 13, z = .5, tgt = 24*sway(t - .12); const a = -w*w*(u - tgt) - 2*z*w*uV; uV += a*DT; u += uV*DT; }
// dome: floppy hat with inertia (it lags the body)
if (t < domeDrop.land) { psi = PSI_FALL; psiV = 0; }
else { const w = 13, z = .22, tgt = 11*deg*s; const a = -w*w*(psi - tgt) - 2*z*w*psiV - .6*phiA; psiV += a*DT; psi += psiV*DT; }
// squash springs; falling pieces stretch along their velocity
const tgA = archDrop.air(t) ? -Math.min(.12, Math.abs(archDrop.v(t))*4.6e-5) : 0;
const tgB = ballDrop.air(t) ? -Math.min(.14, Math.abs(ballDrop.v(t))*6.5e-5) : 0;
const tgD = domeDrop.air(t) ? -Math.min(.10, Math.abs(domeDrop.v(t))*4.0e-5) : 0;
for (const [k, tg] of [['A', tgA], ['B', tgB], ['D', tgD]]) {
const [w, z] = SPR[k]; const st = q[k];
const a = -w*w*(st[0] - tg) - 2*z*w*st[1]; st[1] += a*DT; st[0] += st[1]*DT;
}
SIG.phi[i] = phi; SIG.u[i] = u; SIG.psi[i] = psi;
SIG.qA[i] = q.A[0]; SIG.qB[i] = q.B[0]; SIG.qD[i] = q.D[0];
}
})();
const sig = (name, t) => {
const x = clamp(t/DT, 0, N - 1.001), i = Math.floor(x), f = x - i, a = SIG[name];
return a[i] + (a[i+1] - a[i])*f;
};
// ------------------------------------------------------------------
// Standing pose: a kinematic chain floor → arch → ball → dome
// ------------------------------------------------------------------
function standPose(t) {
const hA = archDrop.h(t) + hopH(t), hx = hopX(t), phi = sig('phi', t), u = sig('u', t), psi = sig('psi', t);
const qA = sig('qA', t) + crouchA(t), qB = sig('qB', t) + crouchB(t), qD = sig('qD', t) + crouchD(t);
const hB = ballDrop.h(t), hD = domeDrop.h(t);
const sxA = 1 + .55*qA, syA = 1 - qA;
const side = phi >= 0 ? 1 : -1; // rock on the outer corner of one foot
const piv = { x: hx + side*WA*sxA, y: FLOOR - hA };
const off = rv(phi, -side*WA*sxA, 0);
const A = { x: piv.x + off.x, y: piv.y + off.y };
const mA = chain(T(A.x, A.y), R(phi), S(sxA, syA), R(90*deg), T(-ANC.arch.x, -ANC.arch.y));
const top = rv(phi, u, -HA*syA);
const cB = { x: A.x + top.x, y: A.y + top.y - hB };
const sxB = 1 + .8*qB, syB = 1 - qB;
const mB = chain(T(cB.x, cB.y), R(phi), S(sxB, syB), T(-ANC.ball.x, -ANC.ball.y));
const bc = rv(phi, 0, -G.oR*syB), O = { x: cB.x + bc.x, y: cB.y + bc.y };
// bowl: outer curve resting on the ball, rolling without slipping
const ang = phi + psi, dd = rv(ang, 0, -G.oR*syB);
const cD = { x: O.x + dd.x, y: O.y + dd.y - hD };
const sxD = 1 + .6*qD, syD = 1 - qD;
const mD = chain(T(cD.x, cD.y), R(ang), S(sxD, syD), T(0, -G.dR), R(psi*ROLL), R(90*deg), T(-G.dcx, -G.cy));
return { arch: mA, ball: mB, dome: mD, O, hA };
}
// ------------------------------------------------------------------
// Flight: lift-off, unfold around the orb, magnetic clack, hover settle
// ------------------------------------------------------------------
const FL = { TR: .34, APEX: -108, TC: .44, X: 48, ROT: .40 };
const H0 = (() => {
const p = standPose(T_L), O = p.O, h = { O };
for (const k of ['arch', 'dome']) {
const c = ap(p[k], CEN[k]), m = p[k];
const fin = { x: CEN[k].x - ORB_C.x, y: 0 };
h[k] = { a0: Math.atan2(c.y - O.y, c.x - O.x), r0: Math.hypot(c.x - O.x, c.y - O.y),
th0: Math.atan2(m[1], m[0]), aF: k === 'arch' ? Math.PI : 0, rF: Math.abs(fin.x) };
}
return h;
})();
const damp = (s, w, z) => { const wd = w*Math.sqrt(1 - z*z); return Math.exp(-z*w*s)*Math.sin(wd*s)/wd; };
const fromRest = (x0, s, w, z) => { const wd = w*Math.sqrt(1 - z*z);
return Math.exp(-z*w*s)*(x0*Math.cos(wd*s) + (z*w*x0/wd)*Math.sin(wd*s)); };
function flightPose(t) {
const tau = t - T_L, sC = tau - FL.TC;
const done = tau > 1.7;
let Oy = tau < FL.TR ? H0.O.y + (FL.APEX - H0.O.y)*(1 - (1 - tau/FL.TR)**2)
: fromRest(FL.APEX, tau - FL.TR, 9.5, .75);
let Ox = H0.O.x*(1 - eio(tau/.4));
if (done) { Ox = 0; Oy = 0; }
const O = { x: Ox, y: Oy };
const st = -Math.sin(Math.PI*clamp(tau/.30))*.085; // stretch on the way up
const gs = sC > 0 && !done ? 1 + .05*Math.exp(-6*sC)*Math.sin(20*sC) : 1;
const G_ = chain(T(O.x, O.y), S(gs, gs), T(-O.x, -O.y));
const piece = (k, jsign, kq) => {
const h = H0[k];
const a = h.a0 + (h.aF - h.a0)*eio(tau/FL.ROT);
let r = h.rF + (h.r0 - h.rF)*(1 - smooth(0, .30, tau));
r += FL.X*smooth(0, .22, tau)*(1 - eInQ((tau - .30)/(FL.TC - .30)));
if (sC > 0 && !done) r += 3.6*Math.exp(-14*sC)*Math.abs(Math.sin(38*sC)); // hard stop, tiny rebound
let th = h.th0 + (0 - h.th0)*eio((tau - .02)/FL.ROT);
if (done) { r = h.rF; th = 0; }
const q = st*kq, c = CEN[k];
const C = { x: O.x + r*Math.cos(done ? h.aF : a), y: O.y + r*Math.sin(done ? h.aF : a) };
return mul(G_, chain(T(C.x, C.y), S(1 + .6*q, 1 - q), R(th), T(-c.x, -c.y)));
};
const qb = st*1.1;
const ball = mul(G_, chain(T(O.x, O.y), S(1 + .8*qb, 1 - qb), T(-ORB_C.x, -ORB_C.y)));
return { arch: piece('arch', 1, .8), dome: piece('dome', -1, .8), ball, O, tau };
}
function pose(t) {
t = clamp(t, 0, DUR);
const p = t < T_L ? standPose(t) : flightPose(t);
// contact shadows
const fade = t < T_L ? 1 : 1 - smooth(0, .2, t - T_L);
const sh = [];
if (fade > 0) {
let lowest = Infinity, cx = 0;
for (const f of FEET) {
const w = ap(p.arch, f), hf = Math.max(0, FLOOR - w.y);
lowest = Math.min(lowest, hf); cx += w.x/2;
sh.push({ x: w.x, rx: 30 + hf*.35, ry: 5.5 + hf*.05, a: .34*Math.exp(-hf/22)*fade });
}
sh.unshift({ x: cx, rx: 150 + lowest*.35, ry: 15 + lowest*.03, a: .17*Math.exp(-lowest/210)*fade });
}
p.shadows = sh;
// shock ring when the pieces lock
const sC = t - (T_L + FL.TC);
p.sC = sC;
p.ring = sC > 0 && sC < .8 ? { O: p.O, r: 118 + 210*eOutC(sC/.8), a: .34*(1 - sC/.8)**2, w: 4*(1 - .7*sC/.8) } : null;
return p;
}
// ------------------------------------------------------------------
// Drawing
// ------------------------------------------------------------------
function makeBG(W, H, noise) {
const c = document.createElement('canvas'); c.width = W; c.height = H;
const g = c.getContext('2d');
const cx = W/2, cy = H*.47, R = Math.hypot(W, H)*.6;
const gr = g.createRadialGradient(cx, cy, 0, cx, cy, R);
gr.addColorStop(0, TH.bg[0]); gr.addColorStop(.42, TH.bg[1]); gr.addColorStop(1, TH.bg[2]);
g.fillStyle = gr; g.fillRect(0, 0, W, H);
if (noise) { // static dither: kills banding in the video
const id = g.getImageData(0, 0, W, H), d = id.data; let s = 1337;
for (let i = 0; i < d.length; i += 4) {
s = (s*1664525 + 1013904223) >>> 0; const n = ((s >>> 24)/255 - .5)*noise;
d[i] += n; d[i+1] += n; d[i+2] += n;
}
g.putImageData(id, 0, 0);
}
return c;
}
function draw(ctx, W, H, t, bg) {
const px = H/VIEW_H, base = [px, 0, 0, px, W/2, H/2];
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.drawImage(bg, 0, 0, W, H);
const p = pose(t);
for (const s of p.shadows) {
if (s.a < .003) continue;
ctx.setTransform(...mul(base, [s.rx, 0, 0, s.ry, s.x, FLOOR]));
const g = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
const a = Math.min(.9, s.a*TH.shadowK), c = TH.shadow;
g.addColorStop(0, `rgba(${c},${a})`); g.addColorStop(.55, `rgba(${c},${a*.45})`); g.addColorStop(1, `rgba(${c},0)`);
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(0, 0, 1, 0, Math.PI*2); ctx.fill();
}
if (p.ring) {
ctx.setTransform(...base);
ctx.strokeStyle = `rgba(26,159,255,${Math.min(1, p.ring.a*TH.ringA)})`; ctx.lineWidth = p.ring.w;
if (TH.ringGlow) { ctx.shadowColor = `rgba(26,159,255,${Math.min(1, p.ring.a*2)})`; ctx.shadowBlur = TH.ringGlow*px; }
ctx.beginPath(); ctx.arc(p.ring.O.x, p.ring.O.y, p.ring.r, 0, Math.PI*2); ctx.stroke();
ctx.shadowBlur = 0; ctx.shadowColor = 'transparent';
}
if (TH.glow && p.sC > 0 && p.sC < 1.4) { // dark only: the orb flashes on at lock, light leaks through the halo gap
const ga = TH.glow*Math.min(1, p.sC/.03)*Math.exp(-p.sC/.32)*(1 - smooth(1.0, 1.4, p.sC));
ctx.setTransform(...base);
const g = ctx.createRadialGradient(p.O.x, p.O.y, G.oR*.9, p.O.x, p.O.y, G.oR*2.6);
g.addColorStop(0, `rgba(26,159,255,${ga})`); g.addColorStop(.35, `rgba(26,159,255,${ga*.45})`); g.addColorStop(1, 'rgba(26,159,255,0)');
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(p.O.x, p.O.y, G.oR*2.6, 0, Math.PI*2); ctx.fill();
}
ctx.fillStyle = TH.ink;
ctx.setTransform(...mul(base, p.arch)); ctx.fill(PATH.arch);
ctx.setTransform(...mul(base, p.dome)); ctx.fill(PATH.dome);
ctx.fillStyle = ORB;
ctx.setTransform(...mul(base, p.ball)); ctx.fill(PATH.orb);
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
// how far (px) things move during an exposure: drives motion-blur sample count
const PROBE = { arch: [{x:G.L,y:0},{x:G.L,y:G.B},{x:G.slotL,y:0},{x:G.slotL,y:G.B}],
dome: [{x:G.slotR,y:0},{x:G.slotR,y:G.B},{x:176,y:G.cy}],
ball: [{x:G.ocx-G.oR,y:G.cy},{x:G.ocx+G.oR,y:G.cy},{x:G.ocx,y:G.cy-G.oR},{x:G.ocx,y:G.cy+G.oR}] };
function motionPx(t0, t1, H) {
const a = pose(t0), b = pose(t1), px = H/VIEW_H; let m = 0;
for (const k of ['arch', 'dome', 'ball']) for (const q of PROBE[k]) {
const p0 = ap(a[k], q), p1 = ap(b[k], q); m = Math.max(m, Math.hypot(p1.x - p0.x, p1.y - p0.y));
}
if (b.ring) m = Math.max(m, Math.abs(b.ring.r - (a.ring ? a.ring.r : 116)));
return m*px;
}
// Offline render with real motion blur (180° shutter, adaptive samples)
let RC = null;
function renderFrame(i, fps = 60, shutter = .5) {
const cv = document.getElementById('cv'), W = cv.width, H = cv.height;
if (!RC || RC.W !== W || RC.H !== H || RC.theme !== THN) {
const ctx = cv.getContext('2d', { willReadFrequently: true });
RC = { W, H, theme: THN, ctx, bg: makeBG(W, H, TH.noise), acc: new Uint16Array(W*H*4) };
}
const t = i/fps, ex = shutter/fps;
const t0 = Math.max(0, t - ex/2), t1 = Math.min(DUR, t + ex/2);
const n = Math.max(1, Math.min(48, Math.ceil(motionPx(t0, t1, H)/.45)));
if (n === 1) { draw(RC.ctx, W, H, t, RC.bg); }
else {
const acc = RC.acc; acc.fill(0);
for (let k = 0; k < n; k++) {
draw(RC.ctx, W, H, t0 + (k + .5)/n*(t1 - t0), RC.bg);
const d = RC.ctx.getImageData(0, 0, W, H).data;
for (let j = 0; j < d.length; j++) acc[j] += d[j];
}
const out = RC.ctx.createImageData(W, H), o = out.data;
for (let j = 0; j < o.length; j++) o[j] = (acc[j] + (n >> 1))/n;
RC.ctx.putImageData(out, 0, 0);
}
return { url: cv.toDataURL('image/png'), samples: n };
}
return { DUR, T_L, HOP, setTheme, get theme() { return THN; }, draw, makeBG, renderFrame, pose, sig, sway, drops: { archDrop, ballDrop, domeDrop },
BEATS: [['Drop', .10], ['Wobble', 1.60], ['Jump', 3.56], ['Lock', T_L + FL.TC]],
frameCount: fps => Math.round(DUR*fps) + 1, CEN, H0 };
})();
/* =====================================================================
Preview player (or bare canvas when ?render=1)
===================================================================== */
(() => {
const qs = new URLSearchParams(location.search);
const cv = document.getElementById('cv');
if (qs.get('render')) {
document.body.classList.add('render');
DD.setTheme(qs.get('theme') || 'light');
document.body.appendChild(cv);
cv.width = +qs.get('w') || 1280; cv.height = +qs.get('h') || 800;
cv.style.width = cv.width + 'px'; cv.style.height = cv.height + 'px';
return;
}
const stage = document.getElementById('stage'), ctx = cv.getContext('2d');
const scrub = document.getElementById('scrub'), timeEl = document.getElementById('time');
const playBtn = document.getElementById('play'), playIcon = document.getElementById('playIcon'), playLabel = document.getElementById('playLabel');
const beatsEl = document.getElementById('beats'), fsBtn = document.getElementById('fs');
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
const sndBtn = document.getElementById('snd'), sndMark = document.getElementById('sndMark'), hint = document.getElementById('hint');
let W = 0, H = 0, bg = null, t = reduce ? DD.DUR : 0, playing = !reduce, speed = 1, last = 0, raf = 0;
// Soundtrack through Web Audio. When it's playing, the audio clock drives the picture.
const Sound = (() => {
let ctx = null, buf = null, src = null, on = false, pending = null, t0 = 0, c0 = 0, rate = 1;
const bytes = () => { const b = atob(DD_SOUND), u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u.buffer; };
async function ensure() { // call from a tap: browsers only allow sound after one
if (!ctx) { const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return false; ctx = new AC(); }
if (ctx.state !== 'running') { try { await ctx.resume(); } catch (e) {} }
if (!buf) { pending = pending || new Promise((ok, no) => ctx.decodeAudioData(bytes(), ok, no));
try { buf = await pending; } catch (e) { pending = null; return false; } }
return ctx.state === 'running';
}
function stop() { if (src) { try { src.stop(); } catch (e) {} src.disconnect(); src = null; } }
function start(at, r) {
stop(); if (!on || !buf || !ctx || ctx.state !== 'running' || at >= buf.duration) return;
src = ctx.createBufferSource(); src.buffer = buf; src.playbackRate.value = r; src.connect(ctx.destination);
c0 = ctx.currentTime; t0 = at; rate = r; src.start(c0, at);
}
function clock() { return src ? t0 + Math.max(0, ctx.currentTime - c0 - (ctx.outputLatency || 0))*rate : null; }
return { ensure, start, stop, clock, get on() { return on; }, set on(v) { on = v; if (!v) stop(); } };
})();
// version: remembered per viewer, otherwise follows the system theme
let ver = null; try { ver = localStorage.getItem('dd-version'); } catch (e) {}
if (ver !== 'light' && ver !== 'dark') ver = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
function setVersion(v) {
ver = v; DD.setTheme(v); stage.classList.toggle('dark', v === 'dark');
document.querySelectorAll('.version button').forEach(b => b.setAttribute('aria-pressed', b.dataset.v === v));
if (W) bg = DD.makeBG(W, H, 0);
try { localStorage.setItem('dd-version', v); } catch (e) {}
}
document.querySelectorAll('.version button').forEach(b => b.onclick = () => { setVersion(b.dataset.v); render(); });
setVersion(ver);
function size() {
const r = stage.getBoundingClientRect(), dpr = Math.min(window.devicePixelRatio || 1, 2.5);
const w = Math.round(r.width*dpr), h = Math.round(r.height*dpr);
if (w !== W || h !== H) { W = cv.width = w; H = cv.height = h; bg = DD.makeBG(W, H, 0); }
render();
}
const ICON = { pause: 'M7 5h4v14H7zM13 5h4v14h-4z', play: 'M8 5.5v13l11-6.5z', replay: 'M12 5a7 7 0 1 1-6.6 4.7l1.9.6A5 5 0 1 0 12 7v3L7.5 6 12 2z' };
function ui() {
const ended = t >= DD.DUR - 1e-6;
const mode = playing ? 'pause' : ended ? 'replay' : 'play';
playIcon.setAttribute('d', ICON[mode]);
playLabel.textContent = mode === 'pause' ? 'Pause' : mode === 'replay' ? 'Replay' : 'Play';
playBtn.setAttribute('aria-label', playLabel.textContent);
stage.classList.toggle('ended', ended && !playing);
hint.textContent = Sound.on ? 'Tap to replay' : 'Turn on Sound to hear it';
sndBtn.setAttribute('aria-pressed', Sound.on);
sndMark.setAttribute('d', Sound.on ? 'M15.5 9.2a4 4 0 0 1 0 5.6M18.3 6.6a7.6 7.6 0 0 1 0 10.8' : 'M16 9.5l5 5M21 9.5l-5 5');
const p = t/DD.DUR; scrub.value = Math.round(p*1000); scrub.style.setProperty('--p', (p*100) + '%');
timeEl.textContent = `${t.toFixed(2)} / ${DD.DUR.toFixed(2)}`;
let cur = -1; DD.BEATS.forEach((b, i) => { if (t >= b[1]) cur = i; });
[...beatsEl.children].forEach((el, i) => el.classList.toggle('on', i === cur));
}
function render() { if (bg) DD.draw(ctx, W, H, t, bg); ui(); }
function loop(now) {
raf = 0;
if (playing) {
const heard = Sound.clock();
if (heard !== null) t = Math.min(DD.DUR, heard);
else t = Math.min(DD.DUR, t + Math.min(.05, (now - last)/1000)*speed);
if (t >= DD.DUR) playing = false;
}
last = now; render();
if (playing) raf = requestAnimationFrame(loop);
}
function play() {
if (t >= DD.DUR - 1e-6) t = 0;
playing = true; Sound.start(t, speed); last = performance.now();
if (!raf) raf = requestAnimationFrame(loop);
}
function pause() { playing = false; Sound.stop(); render(); }
sndBtn.onclick = async () => {
if (Sound.on) { Sound.on = false; ui(); return; }
Sound.on = true; ui();
if (!(await Sound.ensure())) { Sound.on = false; ui(); return; }
t = 0; play(); // replay from the top so it's heard in sync
};
playBtn.onclick = () => playing ? pause() : play();
cv.onclick = () => playing ? pause() : play();
scrub.oninput = () => { playing = false; Sound.stop(); t = scrub.value/1000*DD.DUR; render(); };
document.querySelectorAll('.speed button').forEach(b => b.onclick = () => {
speed = +b.dataset.s; document.querySelectorAll('.speed button').forEach(x => x.setAttribute('aria-pressed', x === b));
if (playing) Sound.start(t, speed);
});
DD.BEATS.forEach(([name, bt]) => {
const b = document.createElement('button'); b.className = 'beat'; b.textContent = name;
b.style.left = (bt/DD.DUR*100) + '%'; b.onclick = () => { t = bt; play(); };
beatsEl.appendChild(b);
});
addEventListener('keydown', e => {
if (e.target.closest('input,button') && e.key !== ' ') return;
if (e.key === ' ') { e.preventDefault(); playing ? pause() : play(); }
else if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
e.preventDefault(); playing = false; Sound.stop(); t = Math.max(0, Math.min(DD.DUR, t + (e.key === 'ArrowRight' ? 1 : -1)/60)); render();
}
});
if (stage.requestFullscreen) {
fsBtn.hidden = false;
fsBtn.onclick = () => document.fullscreenElement ? document.exitFullscreen() : stage.requestFullscreen().catch(() => {});
}
new ResizeObserver(size).observe(stage);
addEventListener('resize', size);
size();
if (playing) play();
})();
</script>
<script id="dd-sound">/* soundtrack: MP3, base64. Rebuild with embed_sound.py */
const DD_SOUND = /*SOUND*/"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYwLjE2LjEwMAAAAAAAAAAAAAAA//uUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAEJAAGPAAADBggLDhATFhgaHR8iJScqLS8yNDY5Oz5BQ0ZJS01QUlVYWl1gYmVnaWxucXR2eXx+gIOFiIuNkJOVmJqcn6Gkp6msr7Gztri7vsDDxsjLzc/S1Nfa3N/i5Obp6+7x8/b5+/4AAAAATGF2YzYwLjMxAAAAAAAAAAAAAAAAJAXgAAAAAAABjwC+eaeUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//uUZAAP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAETEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xLine truncated
</script>
</body>
</html>
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""Embed droiddeck-boot-sound.wav into droiddeck-boot.html (MP3, base64) for the preview page."""
import base64, re, subprocess
from pathlib import Path
here = Path(__file__).parent
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(here / "droiddeck-boot-sound.wav"),
"-c:a", "libmp3lame", "-b:a", "128k", str(here / "_snd.mp3")], check=True)
b64 = base64.b64encode((here / "_snd.mp3").read_bytes()).decode(); (here / "_snd.mp3").unlink()
html = (here / "droiddeck-boot.html").read_text()
html = re.sub(r'/\*SOUND\*/".*?"/\*END\*/', lambda m: f'/*SOUND*/"{b64}"/*END*/', html, flags=re.S)
(here / "droiddeck-boot.html").write_text(html)
print(f"embedded {len(b64)/1024:.0f} KB of sound")
+20
View File
@@ -0,0 +1,20 @@
import json
from pathlib import Path
from playwright.sync_api import sync_playwright
JS = """(() => {
const d = DD.drops, c = (m, q) => ({x: m[0]*q.x + m[2]*q.y + m[4], y: m[1]*q.x + m[3]*q.y + m[5]});
const ev = {DUR: DD.DUR, T_L: DD.T_L, LOCK: DD.BEATS[3][1], HOP: DD.HOP,
drops: Object.fromEntries(['archDrop','ballDrop','domeDrop'].map(k => [k, {t0: d[k].o.t0, impacts: d[k].impacts}]))};
const tr = {t:[], phi:[], u:[], psi:[], ax:[], ay:[], bx:[], by:[], dx:[], dy:[]}, dt = 1/1200;
for (let i = 0; i*dt <= DD.DUR + 1e-9; i++) { const t = i*dt, p = DD.pose(t);
const a = c(p.arch, DD.CEN.arch), b = c(p.ball, {x: 63.98, y: 111.86}), q = c(p.dome, DD.CEN.dome);
tr.t.push(t); tr.phi.push(DD.sig('phi', t)); tr.u.push(DD.sig('u', t)); tr.psi.push(DD.sig('psi', t));
tr.ax.push(a.x); tr.ay.push(a.y); tr.bx.push(b.x); tr.by.push(b.y); tr.dx.push(q.x); tr.dy.push(q.y); }
ev.tr = tr; return ev; })()"""
with sync_playwright() as p:
b = p.chromium.launch(); pg = b.new_page()
pg.goto(Path(__file__).with_name('droiddeck-boot.html').resolve().as_uri() + '?render=1&w=320&h=200')
pg.wait_for_function("typeof DD !== 'undefined'", timeout=15000)
ev = pg.evaluate(JS); b.close()
json.dump(ev, open('events.json', 'w'))
print({k: v for k, v in ev.items() if k != 'tr'})
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Render the DroidDeck boot animation to .webm (Steam) or .mp4 (H.264).
Usage: python3 render.py [WIDTH] [HEIGHT] [FPS] [OUT] [light|dark]
python3 render.py 1280 720 30 droiddeck-boot.webm
python3 render.py 1920 1080 60 droiddeck-boot.mp4
python3 render.py 1280 720 30 droiddeck-boot-dark.webm dark
Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx.
The animation is drawn by droiddeck-boot.html (same folder); each frame gets real
motion blur (180-degree shutter, up to 48 sub-frames when things move fast).
"""
import base64, os, shutil, subprocess, sys, tempfile, time
from pathlib import Path
from playwright.sync_api import sync_playwright
W = int(sys.argv[1]) if len(sys.argv) > 1 else 1280
H = int(sys.argv[2]) if len(sys.argv) > 2 else 720
FPS = int(sys.argv[3]) if len(sys.argv) > 3 else 30
OUT = sys.argv[4] if len(sys.argv) > 4 else f"droiddeck-boot-{W}x{H}.webm"
THEME = sys.argv[5] if len(sys.argv) > 5 else "light" # light | dark
ONLY = [int(x) for x in os.environ.get("FRAMES", "").split(",") if x] # debug: render some frames only
html = Path(__file__).with_name("droiddeck-boot.html").resolve()
tmp = Path(os.environ["FRAMEDIR"]) if os.environ.get("FRAMEDIR") else Path(tempfile.mkdtemp(prefix="ddframes_"))
tmp.mkdir(parents=True, exist_ok=True) # FRAMEDIR=... makes a long render resumable
t0 = time.time()
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(viewport={"width": W, "height": H})
page.goto(f"{html.as_uri()}?render=1&w={W}&h={H}&theme={THEME}")
page.wait_for_function("typeof DD !== 'undefined'", timeout=30000)
n = page.evaluate(f"DD.frameCount({FPS})")
frames = ONLY or range(n)
for i in frames:
if (tmp / f"f{i:05d}.png").exists() and not ONLY:
continue
r = page.evaluate(f"DD.renderFrame({i}, {FPS})")
(tmp / f"f{i:05d}.png").write_bytes(base64.b64decode(r["url"].split(",", 1)[1]))
if i % 30 == 0 or ONLY:
print(f"frame {i+1}/{n} blur samples {r['samples']:>2} {time.time()-t0:5.1f}s", flush=True)
browser.close()
if ONLY:
print("frames left in", tmp); sys.exit(0)
COLOR = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv"]
SOUND = Path(__file__).with_name("droiddeck-boot-sound.wav") # made by sound.py; muxed in if present
cmd = ["ffmpeg", "-y", "-loglevel", "error", "-framerate", str(FPS), "-i", str(tmp / "f%05d.png")]
if SOUND.exists():
cmd += ["-i", str(SOUND), "-map", "0:v", "-map", "1:a"]
cmd += ["-c:a", "aac", "-b:a", "192k"] if OUT.lower().endswith(".mp4") else ["-c:a", "libopus", "-b:a", "160k"]
cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int,format=yuv420p"]
if OUT.lower().endswith(".mp4"): # H.264 for sharing, previews and anything that won't play webm
cmd += ["-c:v", "libx264", "-preset", "slow", "-crf", "15", "-profile:v", "high", "-tune", "animation",
"-g", str(FPS * 2), "-movflags", "+faststart"]
else: # VP8 keeps software decoding inexpensive during Steam startup
cmd += ["-c:v", "libvpx", "-b:v", "2M", "-crf", "10", "-deadline", "good", "-cpu-used", "2",
"-g", str(FPS * 2)]
cmd += COLOR + ([] if SOUND.exists() else ["-an"]) + [OUT]
subprocess.run(cmd, check=True)
if not os.environ.get("FRAMEDIR"):
shutil.rmtree(tmp)
print(f"wrote {OUT} ({os.path.getsize(OUT)/1e6:.2f} MB) in {time.time()-t0:.0f}s")
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env python3
"""DroidDeck boot animation: procedural sound design.
Every sound is synthesized (no samples) and placed on the exact physics events the animation
engine reports (events.json, exported by events.py). Key: D major.
legs (arch) lands on a muted D
ball lands on A, the second bounce a quieter echo
bowl lands on F#
balancing silence
jump silence
lock a soft landing in the same voice, then all those notes together as the D chord
Usage: python3 sound.py [events.json] [out.wav]
"""
import json, sys
import numpy as np
from scipy import signal
SR = 48000
FPS = 60
ev = json.load(open(sys.argv[1] if len(sys.argv) > 1 else 'events.json'))
OUT = sys.argv[2] if len(sys.argv) > 2 else 'droiddeck-boot-sound.wav'
FRAMES = round(ev['DUR'] * FPS) + 1
N = int(np.ceil(FRAMES / FPS * SR)) # exactly the video length
rng = np.random.default_rng(20260925)
# note frequencies
def hz(n): return 440.0 * 2 ** ((n - 69) / 12)
D2 = 440.0 * 2 ** ((38 - 69) / 12)
D3, A3, D4, E4, Fs4, A4, B4, Cs5, D5, E5, Fs5, A5, D6 = [hz(n) for n in (50, 57, 62, 64, 66, 69, 71, 73, 74, 76, 78, 81, 86)]
# ------------------------------------------------------------------ building blocks
def tt(dur): return np.arange(int(dur * SR)) / SR
def edge(x, a_ms=1.0, r_ms=4.0):
"""Click-free start and end."""
na, nr = max(1, int(a_ms * SR / 1000)), max(1, int(r_ms * SR / 1000))
x[:na] *= np.sin(np.linspace(0, np.pi / 2, na)) ** 2
x[-nr:] *= np.cos(np.linspace(0, np.pi / 2, nr)) ** 2
return x
def bp(x, lo, hi, order=2):
return signal.sosfilt(signal.butter(order, [lo, min(hi, SR * .45)], 'bandpass', fs=SR, output='sos'), x)
def lp(x, f, order=2): return signal.sosfilt(signal.butter(order, f, 'lowpass', fs=SR, output='sos'), x)
def hp(x, f, order=2): return signal.sosfilt(signal.butter(order, f, 'highpass', fs=SR, output='sos'), x)
def modal(freqs, decays, amps, dur):
t = tt(dur); y = np.zeros_like(t)
for f, d, a in zip(freqs, decays, amps):
if f < SR * .45: y += a * np.sin(2 * np.pi * f * t) * np.exp(-t / d)
return y
def glide(f0, f1, tau, dur):
"""Sine whose pitch moves exponentially from f0 to f1."""
t = tt(dur); f = f1 + (f0 - f1) * np.exp(-t / tau)
return np.sin(2 * np.pi * np.cumsum(f) / SR)
def noise_burst(dur, lo, hi, tau):
t = tt(dur); return bp(rng.standard_normal(len(t)), lo, hi) * np.exp(-t / tau)
def pan(x, p):
p = np.clip(p, -1, 1); a = (p + 1) * np.pi / 4
return np.stack([x * np.cos(a), x * np.sin(a)])
MIX = np.zeros((2, N))
def put(t0, st, gain=1.0):
i = int(round(t0 * SR))
if i >= N: return
j = min(N, i + st.shape[1]); MIX[:, i:j] += gain * st[:, :j - i]
# ------------------------------------------------------------------ instruments
def wood(amp, f0=520, size=1.0, thump=0.0, dur=.35):
"""Hard wood / toy-block clack. thump adds body for heavy landings."""
r = [1, 1.93, 2.81, 4.13, 5.62]
y = modal([f0 * k for k in r], [s * size for s in (.055, .034, .022, .014, .009)], [1, .55, .42, .26, .16], dur)
y += .7 * noise_burst(dur, 1400, 7500, .0035)
if thump: y += thump * glide(118, 52, .035, dur) * np.exp(-tt(dur) / .075)
return edge(y * amp)
def bonk(amp, f):
"""Hollow rubber ball on a board: round pitched body, soft click, tiny board knock."""
d = .42; t = tt(d)
y = glide(f * 1.28, f, .018, d) * np.exp(-t / (.09 + .05 * amp))
y += .22 * glide(f * 2.45, f * 2.3, .02, d) * np.exp(-t / .035)
y += .55 * glide(95, 60, .03, d) * np.exp(-t / .045)
y += .22 * noise_burst(d, 1800, 5000, .002)
y += .25 * wood(1, f0=640, size=.6, dur=d)
return edge(y * amp, a_ms=.6)
def bowl_ring(amp, f=A4, dur=2.4, dscale=1.0):
"""Struck metal bowl: inharmonic partials, each split in two for the slow beating shimmer."""
t = tt(dur); y = np.zeros_like(t)
for k, dec, a, beat in zip((1, 2.71, 5.12, 8.21), tuple(d * dscale for d in (1.25, .62, .3, .15)), (1, .45, .24, .12), (.9, 1.7, 2.6, 3.1)):
for s in (-1, 1):
y += .5 * a * np.sin(2 * np.pi * (f * k + s * beat / 2) * t + (s > 0) * .8) * np.exp(-t / dec)
return edge(y * amp, a_ms=.8, r_ms=30)
def clonk(amp, ring):
d = .5; t = tt(d)
y = .8 * glide(160, 92, .03, d) * np.exp(-t / .06) + .45 * wood(1, f0=880, size=.7, dur=d)
return edge(y * amp), bowl_ring(ring)
def marimba(f, amp, damp=1.0):
d = 1.2; t = tt(d)
tau = .55 * (440 / f) ** .5 * damp
y = modal([f, f * 3.93, f * 9.2], [tau, tau * .22, .03], [1, .32, .07], d)
y += .05 * lp(rng.standard_normal(len(t)), 2500) * np.exp(-t / .002)
return edge(y * amp, a_ms=1.5, r_ms=40)
def svf_whoosh(env, fc, q=.9):
"""Noise through a band-pass whose centre follows fc(t): air moving past a spinning piece."""
x = rng.standard_normal(len(env)); y = np.zeros_like(x); ic1 = ic2 = 0.0
for i in range(len(x)):
g = np.tan(np.pi * min(fc[i], SR * .45) / SR); k = 1 / q
a1 = 1 / (1 + g * (g + k)); a2 = g * a1; a3 = g * a2
v3 = x[i] - ic2; v1 = a1 * ic1 + a2 * v3; v2 = ic2 + a2 * ic1 + a3 * v3
ic1 = 2 * v1 - ic1; ic2 = 2 * v2 - ic2; y[i] = v1
return y * env
def epiano(f, amp, dur=2.8, decay=1.5):
"""FM electric piano: bright tine at the strike that mellows as the index falls."""
t = tt(dur)
idx = 1.7 * np.exp(-t / .22) + .22
y = np.sin(2 * np.pi * f * t + idx * np.sin(2 * np.pi * f * t))
y += .18 * np.sin(2 * np.pi * f * t + .9 * np.exp(-t / .012) * np.sin(2 * np.pi * 14 * f * t)) * np.exp(-t / .05)
return edge(y * np.exp(-t / decay) * amp, a_ms=3, r_ms=60)
def tock(f, amp, decay=.42, sub=0.0):
"""A landing as a muted note in the chord's own FM e-piano voice: felt contact, no pitch bend."""
d = 1.5; t = tt(d)
idx = 1.3 * np.exp(-t / .07) + .18
y = np.sin(2 * np.pi * f * t + idx * np.sin(2 * np.pi * f * t)) * np.exp(-t / decay)
y = lp(y, 2600)
y += .30 * lp(rng.standard_normal(len(t)), 1600) * np.exp(-t / .0016)
if sub: y += sub * np.sin(2 * np.pi * D2 * t) * np.exp(-t / .075)
return edge(y * amp, a_ms=1.5, r_ms=80)
def bell(f, amp, dur=1.6):
t = tt(dur)
y = np.sin(2 * np.pi * f * t + 1.1 * np.exp(-t / .3) * np.sin(2 * np.pi * 3.5 * f * t)) * np.exp(-t / .7)
return edge(y * amp, a_ms=2, r_ms=40)
# ------------------------------------------------------------------ tracks from the engine
tr = {k: np.array(v) for k, v in ev['tr'].items()}
TT = tr['t']; dT = TT[1] - TT[0]
def at(name, t): return np.interp(t, TT, tr[name])
def speed(xk, yk):
return np.hypot(np.gradient(tr[xk], dT), np.gradient(tr[yk], dT))
X2PAN = 1 / 330 # world units to stereo pan
drops = ev['drops']; T_L = ev['T_L']; LOCK = ev['LOCK']; HOP = ev['HOP']
events_log = []
def log(t, what): events_log.append((round(t, 3), what))
# ------------------------------------------------------------------ cue sheet
# Kept deliberately sparse: one sound per story beat, with silence between them.
tsamp = np.arange(N) / SR
# 1. the stack: each piece lands on a muted note of the final chord (D, A, A-echo, F#);
# the lock then plays them all together
ai = drops['archDrop']['impacts']
put(ai[0]['t'], pan(tock(D3, .40, decay=.5, sub=.8), .1)); log(ai[0]['t'], 'legs land: D')
bi = drops['ballDrop']['impacts']
for k, imp in enumerate(bi[:2]):
a = .32 * (imp['v'] / bi[0]['v']) ** .9
put(imp['t'], pan(tock(A3, a, decay=.36, sub=.3 * a / .32), 0)); log(imp['t'], f'ball: A {a:.2f}')
di = drops['domeDrop']['impacts']
put(di[0]['t'], pan(tock(Fs4, .28, decay=.45, sub=.45), -.05)); log(di[0]['t'], 'bowl lands: F#')
# 2-3. the balancing act and the jump play in silence: the stack and the lock carry it
# 4. lock: one snap, then a four-note chord that rings out
put(LOCK, pan(tock(D3, .24, decay=.28, sub=.8), 0)); log(LOCK, 'lock: soft landing in the stack voice')
for f, a, p, off in ((D3, .24, -.1, 0), (A3, .28, .2, .02), (D4, .30, -.2, .04), (Fs4, .26, .15, .06)):
put(LOCK + .018 + off, pan(epiano(f, a, decay=1.3 if f < 300 else 1.1), p))
log(LOCK + .018, 'D chord')
# ------------------------------------------------------------------ room, master
def room_ir(dur=1.1, rt60=.75):
t = tt(dur); tau = rt60 / 6.9; irs = []
for ch in range(2):
n = rng.standard_normal(len(t))
ir = lp(n, 7000) * np.exp(-t / (tau * .6)) * .5 + lp(n, 2200) * np.exp(-t / tau)
ir[:int(.011 * SR)] = 0 # pre-delay
for d_ms, g in ((13, .5), (19, .35), (27, .3), (38, .2)):
ir[int((d_ms + ch * 1.3) * SR / 1000)] += g
irs.append(ir / np.sqrt(np.sum(ir ** 2)))
return irs
irs = room_ir()
wet = np.stack([signal.fftconvolve(MIX[ch], irs[ch])[:N] for ch in range(2)])
out = MIX + .14 * wet
out = hp(out, 28)
fade = np.ones(N); nf = int(.45 * SR); fade[-nf:] = np.cos(np.linspace(0, np.pi / 2, nf)) ** 2
out *= fade
# gentle peak control: soft-knee compress only the loudest transients, then normalise
pk = np.max(np.abs(out)); x = out / pk
knee = .5; ax = np.abs(x); over = ax > knee
x[over] = np.sign(x[over]) * (knee + (1 - knee) * np.tanh((ax[over] - knee) / (1 - knee)))
L0, L1 = int((LOCK + .06) * SR), int((LOCK + .76) * SR)
body_rms = np.sqrt(np.mean(x[:, L0:L1].mean(0) ** 2))
out = x * (10 ** (-14.9 / 20) / body_rms) # chord body held at the level the team liked (-14.9 dB RMS)
assert np.max(np.abs(out)) < 10 ** (-1 / 20), 'would clip'
import wave
pcm = (np.clip(out.T, -1, 1) * 32767).astype('<i2')
with wave.open(OUT, 'wb') as w:
w.setnchannels(2); w.setsampwidth(2); w.setframerate(SR); w.writeframes(pcm.tobytes())
json.dump(sorted(events_log), open('sound_events.json', 'w'), indent=0)
print(f'wrote {OUT}: {N / SR:.3f}s, {len(events_log)} cues')
for t, w_ in sorted(events_log): print(f' {t:6.3f} {w_}')
+16
View File
@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="360" viewBox="0 0 1280 360" role="img" aria-labelledby="t" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYTpjNDEzNmY0YS0xYWE5LTQ4MzEtYTgwNS1iOGJkYTkzOWM3OWMAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaOdgBuqxauxA5Ft/U5O/L/0AAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDo2YTI3MjgxMC1iYjQ3LTQyZmItOWE4ZC1kOGJhM2QxOTg2MzJscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNo7FQMclkxxkOM9r48dH+p5QAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggoYQr3GKI/CBS/tjJfXabQnWGTIXEWN2Q4HY/bRZcAd2kZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaCmdTerrFFCgrujAStdxo3AAAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRNAAAAAAAAAAAAAAAAAGRoYXNoWCDdCEqOYsAzpUmsE8GjJyHfVbPv34OtUVI9Zxt08oNaTWRuYW1lbmp1bWJmIG1hbmlmZXN0amV4Y2x1c2lvbnOBomVzdGFydBi3Zmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOmM0MTM2ZjRhLTFhYTktNDgzMS1hODA1LWI4YmRhOTM5Yzc5Yy9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOjVkZjQ2ZTE0LTQzNjQtNGZmZC1hMWVhLTBlNmQ3M2NjMmM0ZXJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCChhCvcYoj8IFL+2Ml9dptCdYZMhcRY3ZDgdj9tFlwB3aJjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFggEranykZZVM3ediUytxX7Gk1wpijJyo8W1hbSxY8qGHSiY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFggd9tQukbXKUDL9GyrZINf6cuup075WZSflrCFunu5uDB0Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALine truncated
<title id="t">DroidDeck</title>
<defs>
<radialGradient id="bg" cx="0.36" cy="0.46" r="0.95" gradientTransform="translate(0.36 0.46) scale(0.48 1) translate(-0.36 -0.46)">
<stop offset="0" stop-color="#1B222B"/><stop offset="0.42" stop-color="#0F1419"/><stop offset="1" stop-color="#05070A"/></radialGradient>
<radialGradient id="glow"><stop offset="0.35" stop-color="#1A9FFF" stop-opacity="0.17"/><stop offset="1" stop-color="#1A9FFF" stop-opacity="0"/></radialGradient>
<clipPath id="card"><rect width="1280" height="360" rx="26"/></clipPath>
</defs>
<g clip-path="url(#card)">
<rect width="1280" height="360" fill="url(#bg)"/>
<circle cx="289.75" cy="182.36" r="155.76" fill="none" stroke="#1A9FFF" stroke-opacity="0.091" stroke-width="12"/><circle cx="289.75" cy="182.36" r="155.76" fill="none" stroke="#1A9FFF" stroke-opacity="0.260" stroke-width="2.4"/><circle cx="289.75" cy="182.36" r="241.9" fill="none" stroke="#1A9FFF" stroke-opacity="0.052" stroke-width="9.5"/><circle cx="289.75" cy="182.36" r="241.9" fill="none" stroke="#1A9FFF" stroke-opacity="0.150" stroke-width="1.9"/><circle cx="289.75" cy="182.36" r="348.1" fill="none" stroke="#1A9FFF" stroke-opacity="0.028" stroke-width="7"/><circle cx="289.75" cy="182.36" r="348.1" fill="none" stroke="#1A9FFF" stroke-opacity="0.080" stroke-width="1.4"/><circle cx="289.75" cy="182.36" r="123.9" fill="url(#glow)"/>
<g transform="translate(239.135 123.36) scale(0.527445) translate(31.98 0)"><path fill="#FFFFFF" d="M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z"/><path fill="#FFFFFF" d="M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"/><circle fill="#1A9FFF" cx="63.98" cy="111.86" r="55.98"/></g><path fill="#FFFFFF" d="M361.45 241.36V160.13H387.02V241.36ZM387.02 196.73 376.32 188.38Q379.5 174.17 387.02 166.31Q394.54 158.46 407.91 158.46Q413.76 158.46 418.19 160.21Q422.62 161.97 425.96 165.65L410.75 184.87Q409.08 183.03 406.57 182.03Q404.07 181.02 400.89 181.02Q394.54 181.02 390.78 184.95Q387.02 188.88 387.02 196.73ZM467.91 243.2Q455.38 243.2 445.27 237.6Q435.15 232 429.3 222.31Q423.45 212.61 423.45 200.58Q423.45 188.54 429.3 179.02Q435.15 169.49 445.18 163.89Q455.21 158.29 467.91 158.29Q480.62 158.29 490.64 163.81Q500.67 169.32 506.52 178.93Q512.37 188.54 512.37 200.58Q512.37 212.61 506.52 222.31Q500.67 232 490.64 237.6Q480.62 243.2 467.91 243.2ZM467.91 219.97Q473.43 219.97 477.61 217.54Q481.79 215.12 484.04 210.69Q486.3 206.26 486.3 200.58Q486.3 194.9 483.96 190.63Q481.62 186.37 477.52 183.95Q473.43 181.52 467.91 181.52Q462.56 181.52 458.39 183.95Q454.21 186.37 451.87 190.72Q449.53 195.06 449.53 200.75Q449.53 206.26 451.87 210.69Q454.21 215.12 458.39 217.54Q462.56 219.97 467.91 219.97ZM523.4 241.36V160.13H548.98V241.36ZM536.27 148.93Q530.26 148.93 526.33 144.84Q522.4 140.74 522.4 134.89Q522.4 128.88 526.33 124.86Q530.26 120.85 536.27 120.85Q542.29 120.85 546.13 124.86Q549.98 128.88 549.98 134.89Q549.98 140.74 546.13 144.84Q542.29 148.93 536.27 148.93ZM599.95 243.03Q588.42 243.03 579.48 237.52Q570.54 232 565.44 222.47Q560.34 212.95 560.34 200.75Q560.34 188.54 565.44 179.02Q570.54 169.49 579.48 163.97Q588.42 158.46 599.95 158.46Q608.31 158.46 615.08 161.63Q621.85 164.81 626.28 170.41Q630.71 176.01 631.21 183.2V217.46Q630.71 224.65 626.36 230.41Q622.02 236.18 615.16 239.61Q608.31 243.03 599.95 243.03ZM604.47 219.97Q609.98 219.97 613.99 217.54Q618 215.12 620.34 210.77Q622.68 206.43 622.68 200.75Q622.68 195.06 620.43 190.8Q618.17 186.54 614.08 184.03Q609.98 181.52 604.63 181.52Q599.28 181.52 595.19 184.03Q591.09 186.54 588.67 190.88Q586.25 195.23 586.25 200.75Q586.25 206.26 588.59 210.61Q590.93 214.95 595.11 217.46Q599.28 219.97 604.47 219.97ZM646.75 241.36H621.68V219.46L625.53 199.74L621.18 180.02V120.02H646.75ZM683.19 241.36V218.29H712.44Q723.13 218.29 731.16 214.03Q739.18 209.77 743.53 201.58Q747.87 193.39 747.87 182.19Q747.87 170.99 743.44 162.97Q739.01 154.95 731.07 150.6Q723.13 146.26 712.44 146.26H682.35V123.36H712.77Q726.14 123.36 737.42 127.62Q748.71 131.88 757.15 139.82Q765.59 147.76 770.18 158.54Q774.78 169.32 774.78 182.36Q774.78 195.23 770.18 206.09Q765.59 216.96 757.23 224.81Q748.87 232.67 737.59 237.01Q726.31 241.36 713.11 241.36ZM665.47 241.36V123.36H691.71V241.36ZM827.6 243.2Q814.39 243.2 804.11 237.77Q793.83 232.33 787.98 222.64Q782.13 212.95 782.13 200.75Q782.13 188.54 787.9 178.93Q793.67 169.32 803.53 163.81Q813.39 158.29 825.76 158.29Q837.79 158.29 846.98 163.47Q856.18 168.65 861.44 177.85Q866.71 187.04 866.71 198.91Q866.71 201.08 866.46 203.5Q866.21 205.93 865.54 209.1L795.51 209.27V191.72L854.67 191.55L843.64 198.91Q843.47 191.89 841.47 187.29Q839.46 182.69 835.54 180.27Q831.61 177.85 825.92 177.85Q819.91 177.85 815.48 180.61Q811.05 183.36 808.63 188.38Q806.2 193.39 806.2 200.58Q806.2 207.77 808.79 212.86Q811.38 217.96 816.15 220.72Q820.91 223.48 827.43 223.48Q833.45 223.48 838.29 221.39Q843.14 219.3 846.82 215.12L860.86 229.16Q854.84 236.18 846.32 239.69Q837.79 243.2 827.6 243.2ZM916.68 243.2Q904.15 243.2 893.95 237.68Q883.75 232.17 877.9 222.47Q872.05 212.78 872.05 200.75Q872.05 188.54 877.99 178.93Q883.92 169.32 894.12 163.81Q904.31 158.29 917.02 158.29Q926.54 158.29 934.48 161.55Q942.42 164.81 948.6 171.33L932.22 187.71Q929.38 184.53 925.62 183.03Q921.86 181.52 917.02 181.52Q911.5 181.52 907.24 183.95Q902.98 186.37 900.55 190.63Q898.13 194.9 898.13 200.58Q898.13 206.26 900.55 210.61Q902.98 214.95 907.32 217.46Q911.67 219.97 917.02 219.97Q922.03 219.97 925.96 218.21Q929.88 216.46 932.73 213.28L948.94 229.66Q942.59 236.35 934.56 239.77Q926.54 243.2 916.68 243.2ZM1010.61 241.36 982.2 199.24 1010.45 160.13H1039.03L1004.93 204.09L1005.77 193.56L1040.7 241.36ZM958.63 241.36V120.02H984.21V241.36Z"/>
</g>
<rect x="0.5" y="0.5" width="1279" height="359" rx="25.5" fill="none" stroke="rgba(255,255,255,0.07)"/>
</svg>

After

Width:  |  Height:  |  Size: 13 KiB

+16
View File
@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="360" viewBox="0 0 1280 360" role="img" aria-labelledby="t" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYTozODE2MThiZi02NDJmLTQ2MjYtODBmOS0zODNkMTg1MTg1YzYAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaNJTd2RbvEwJ3CejXuiiUa8AAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDpiZWIyNDdlNC0zMGYzLTQwNTMtOGRiMy02YjM5ZDFiMDE5MjVscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNoH5LUfnG8pzZTvyp93dxAjAAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggp0bIyQE4HprwqtllS1/PuFew+dPPCPuezvtPD9UACASkZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaCjAw2/dKHURaCMsIpPL4O0AAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRNAAAAAAAAAAAAAAAAAGRoYXNoWCCEQ7KUH92rkmFULm/paDTTakKh2Kq0tGvmqok6E4sdumRuYW1lbmp1bWJmIG1hbmlmZXN0amV4Y2x1c2lvbnOBomVzdGFydBi3Zmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOjM4MTYxOGJmLTY0MmYtNDYyNi04MGY5LTM4M2QxODUxODVjNi9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOjM4NDAyMDFkLWVjMTEtNGExYS1iYWU3LTFjYzgzNzUwMzY5YnJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCCnRsjJATgemvCq2WVLX8+4V7D5088I+57O+08P1QAIBKJjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFggg3t3BJoakmzmieZvRQ5KFPJxvI/zSgQVZG0rhdu4JumiY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFggZjySb2zXGJyOOu+/uDpQ8CRteSnMgEk64l3gBu0UM5t0Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALine truncated
<title id="t">DroidDeck</title>
<defs>
<radialGradient id="bg" cx="0.36" cy="0.46" r="0.95" gradientTransform="translate(0.36 0.46) scale(0.48 1) translate(-0.36 -0.46)">
<stop offset="0" stop-color="#F4F8FB"/><stop offset="0.42" stop-color="#E4ECF2"/><stop offset="1" stop-color="#CAD7E2"/></radialGradient>
<radialGradient id="glow"><stop offset="0.35" stop-color="#1A9FFF" stop-opacity="0.0"/><stop offset="1" stop-color="#1A9FFF" stop-opacity="0"/></radialGradient>
<clipPath id="card"><rect width="1280" height="360" rx="26"/></clipPath>
</defs>
<g clip-path="url(#card)">
<rect width="1280" height="360" fill="url(#bg)"/>
<circle cx="289.75" cy="182.36" r="155.76" fill="none" stroke="#1A9FFF" stroke-opacity="0.300" stroke-width="2.4"/><circle cx="289.75" cy="182.36" r="241.9" fill="none" stroke="#1A9FFF" stroke-opacity="0.170" stroke-width="1.9"/><circle cx="289.75" cy="182.36" r="348.1" fill="none" stroke="#1A9FFF" stroke-opacity="0.090" stroke-width="1.4"/>
<g transform="translate(239.135 123.36) scale(0.527445) translate(31.98 0)"><path fill="#1B1B1B" d="M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z"/><path fill="#1B1B1B" d="M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"/><circle fill="#1A9FFF" cx="63.98" cy="111.86" r="55.98"/></g><path fill="#1B1B1B" d="M361.45 241.36V160.13H387.02V241.36ZM387.02 196.73 376.32 188.38Q379.5 174.17 387.02 166.31Q394.54 158.46 407.91 158.46Q413.76 158.46 418.19 160.21Q422.62 161.97 425.96 165.65L410.75 184.87Q409.08 183.03 406.57 182.03Q404.07 181.02 400.89 181.02Q394.54 181.02 390.78 184.95Q387.02 188.88 387.02 196.73ZM467.91 243.2Q455.38 243.2 445.27 237.6Q435.15 232 429.3 222.31Q423.45 212.61 423.45 200.58Q423.45 188.54 429.3 179.02Q435.15 169.49 445.18 163.89Q455.21 158.29 467.91 158.29Q480.62 158.29 490.64 163.81Q500.67 169.32 506.52 178.93Q512.37 188.54 512.37 200.58Q512.37 212.61 506.52 222.31Q500.67 232 490.64 237.6Q480.62 243.2 467.91 243.2ZM467.91 219.97Q473.43 219.97 477.61 217.54Q481.79 215.12 484.04 210.69Q486.3 206.26 486.3 200.58Q486.3 194.9 483.96 190.63Q481.62 186.37 477.52 183.95Q473.43 181.52 467.91 181.52Q462.56 181.52 458.39 183.95Q454.21 186.37 451.87 190.72Q449.53 195.06 449.53 200.75Q449.53 206.26 451.87 210.69Q454.21 215.12 458.39 217.54Q462.56 219.97 467.91 219.97ZM523.4 241.36V160.13H548.98V241.36ZM536.27 148.93Q530.26 148.93 526.33 144.84Q522.4 140.74 522.4 134.89Q522.4 128.88 526.33 124.86Q530.26 120.85 536.27 120.85Q542.29 120.85 546.13 124.86Q549.98 128.88 549.98 134.89Q549.98 140.74 546.13 144.84Q542.29 148.93 536.27 148.93ZM599.95 243.03Q588.42 243.03 579.48 237.52Q570.54 232 565.44 222.47Q560.34 212.95 560.34 200.75Q560.34 188.54 565.44 179.02Q570.54 169.49 579.48 163.97Q588.42 158.46 599.95 158.46Q608.31 158.46 615.08 161.63Q621.85 164.81 626.28 170.41Q630.71 176.01 631.21 183.2V217.46Q630.71 224.65 626.36 230.41Q622.02 236.18 615.16 239.61Q608.31 243.03 599.95 243.03ZM604.47 219.97Q609.98 219.97 613.99 217.54Q618 215.12 620.34 210.77Q622.68 206.43 622.68 200.75Q622.68 195.06 620.43 190.8Q618.17 186.54 614.08 184.03Q609.98 181.52 604.63 181.52Q599.28 181.52 595.19 184.03Q591.09 186.54 588.67 190.88Q586.25 195.23 586.25 200.75Q586.25 206.26 588.59 210.61Q590.93 214.95 595.11 217.46Q599.28 219.97 604.47 219.97ZM646.75 241.36H621.68V219.46L625.53 199.74L621.18 180.02V120.02H646.75ZM683.19 241.36V218.29H712.44Q723.13 218.29 731.16 214.03Q739.18 209.77 743.53 201.58Q747.87 193.39 747.87 182.19Q747.87 170.99 743.44 162.97Q739.01 154.95 731.07 150.6Q723.13 146.26 712.44 146.26H682.35V123.36H712.77Q726.14 123.36 737.42 127.62Q748.71 131.88 757.15 139.82Q765.59 147.76 770.18 158.54Q774.78 169.32 774.78 182.36Q774.78 195.23 770.18 206.09Q765.59 216.96 757.23 224.81Q748.87 232.67 737.59 237.01Q726.31 241.36 713.11 241.36ZM665.47 241.36V123.36H691.71V241.36ZM827.6 243.2Q814.39 243.2 804.11 237.77Q793.83 232.33 787.98 222.64Q782.13 212.95 782.13 200.75Q782.13 188.54 787.9 178.93Q793.67 169.32 803.53 163.81Q813.39 158.29 825.76 158.29Q837.79 158.29 846.98 163.47Q856.18 168.65 861.44 177.85Q866.71 187.04 866.71 198.91Q866.71 201.08 866.46 203.5Q866.21 205.93 865.54 209.1L795.51 209.27V191.72L854.67 191.55L843.64 198.91Q843.47 191.89 841.47 187.29Q839.46 182.69 835.54 180.27Q831.61 177.85 825.92 177.85Q819.91 177.85 815.48 180.61Q811.05 183.36 808.63 188.38Q806.2 193.39 806.2 200.58Q806.2 207.77 808.79 212.86Q811.38 217.96 816.15 220.72Q820.91 223.48 827.43 223.48Q833.45 223.48 838.29 221.39Q843.14 219.3 846.82 215.12L860.86 229.16Q854.84 236.18 846.32 239.69Q837.79 243.2 827.6 243.2ZM916.68 243.2Q904.15 243.2 893.95 237.68Q883.75 232.17 877.9 222.47Q872.05 212.78 872.05 200.75Q872.05 188.54 877.99 178.93Q883.92 169.32 894.12 163.81Q904.31 158.29 917.02 158.29Q926.54 158.29 934.48 161.55Q942.42 164.81 948.6 171.33L932.22 187.71Q929.38 184.53 925.62 183.03Q921.86 181.52 917.02 181.52Q911.5 181.52 907.24 183.95Q902.98 186.37 900.55 190.63Q898.13 194.9 898.13 200.58Q898.13 206.26 900.55 210.61Q902.98 214.95 907.32 217.46Q911.67 219.97 917.02 219.97Q922.03 219.97 925.96 218.21Q929.88 216.46 932.73 213.28L948.94 229.66Q942.59 236.35 934.56 239.77Q926.54 243.2 916.68 243.2ZM1010.61 241.36 982.2 199.24 1010.45 160.13H1039.03L1004.93 204.09L1005.77 193.56L1040.7 241.36ZM958.63 241.36V120.02H984.21V241.36Z"/>
</g>
<rect x="0.5" y="0.5" width="1279" height="359" rx="25.5" fill="none" stroke="rgba(19,26,33,0.08)"/>
</svg>

After

Width:  |  Height:  |  Size: 13 KiB

+1 -1
View File
@@ -8,6 +8,6 @@
<rect x="56.055" y="178.72" width="15.83" height="45" fill="#000"/>
</mask>
</defs>
<path fill="#1b1b1b" mask="url(#negative-space)" d="M-31.98 0H63.97c61.84 0 111.96 50.08 111.96 111.86S125.81 223.72 63.97 223.72H-31.98V0Z"/>
<path fill="#FFFFFF" mask="url(#negative-space)" d="M-31.98 0H63.97c61.84 0 111.96 50.08 111.96 111.86S125.81 223.72 63.97 223.72H-31.98V0Z"/>
<circle cx="63.98" cy="111.86" r="55.98" fill="#1A9FFF"/>
</svg>

Before

Width:  |  Height:  |  Size: 826 B

After

Width:  |  Height:  |  Size: 826 B

Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff. Show more