Compare commits

...
Author SHA1 Message Date
The412Banner 1acbdec6c1 fix(desktop): strictly confined snaps get the mounts their layout declares 2026-11-24 21:43:33 +00:00
Kurt Himebauch 7c8f5c2707 fix(ui): changing the language restarts the launcher instead of leaving it frozen (#3163)
* fix(ui): changing the language restarts the launcher instead of leaving it frozen

* fix(ui): a launcher restart no longer starts the startup session

* fix(ui): a stopping launcher no longer clears the hooks its replacement set

* fix(ui): a launcher restart keeps a pending session switch

* fix(ui): a launcher restart hands its state over in-process, not through intent extras
2026-11-24 16:26:55 -05:00
MaxsTechReview 14b130500f fix(desktop): a program started through a directory link knows its real path (#3158)
* fix(desktop): a program started through a directory link knows its real path

* fix(desktop): a missing or non-directory component still fails the lookup
2026-11-24 16:23:06 -05:00
MaxsTechReview afe81ea69f fix(fex): x86-64 DwarFS AppImages start and GLib programs reach D-Bus (#3162)
* fix(fex): a program run from a descriptor keeps its argv[0] and an absolute /proc/self/exe

* fix(fex): 64-bit programs send their socket credentials through the hook

D-Bus clients fill SCM_CREDENTIALS with getuid(), which is 0 under the guest. FEX sent x86-64 sendmsg straight to the kernel, which refused the fake root uid with EPERM, so GLib programs lost the session bus and every portal. sendmsg, recvmsg and getsockopt now go through libc like the identity calls, so the hook puts in the real ids and shows the peer as root.
2026-11-24 16:21:40 -05:00
MaxsTechReview 5ca0575e67 fix(gog): resolve exact-path depot overlays before validation (#2720) 2026-11-24 16:18:24 -05:00
Kurt Himebauch 9e405ec92c fix(game-env): run Hades II at D3D12 feature level 12_2 (#2855) 2026-11-24 16:18:20 -05:00
TapuukandTapuuk 8f0e124b5d fix(runtime): fetch the KDE language-pack index directly from GitHub (#2845)
The index carries the sha256 of every language pack, so loading it through a download mirror let the mirror pick both the hash and the pack that gets extracted into the Linux runtime. The index now always comes straight from GitHub; pack bodies can still use mirrors since their hash is trusted.

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
2026-11-24 16:18:15 -05:00
xlulx 31c475d5e1 fix(session): run game thread hints on the SM8750P Snapdragon 8 Elite (#2914)
* fix: run game thread hints on the SM8750P Snapdragon 8 Elite

* fix: gate game thread hints on the SoC model SocNames resolves

* fix: skip unknown SoC model properties
2026-11-24 16:18:10 -05:00
MaxsTechReview 46206b3e16 fix(desktop): links read into a buffer sized from lstat show their guest target (#3157)
* fix(desktop): links read into a buffer sized from lstat show their guest target

lstat reports the guest length of a link stored with a rootfs target, and dpkg's
update-alternatives then reads it with exactly that many bytes. readlink filled the
buffer with the start of the host path, which could no longer be mapped back, so
every alternative looked dangling ("current alternative /data/dat is unknown").
The whole target is read first, mapped, then copied into the caller's buffer.

* fix(desktop): a zero-sized readlink buffer still fails with EINVAL

* test(desktop): read errno before printing the zero-size readlink result
2026-11-24 16:18:05 -05:00
4399db4716 fix(loading): show the arm64 Steam client's update progress in every language (#2651)
* fix(loading): show the arm64 Steam client's update progress in every language

The arm64 bootstrapper writes its progress straight into session.log in the
client's language and with thousands separators, e.g.
"正在下载更新 (已下载 184,557,共 573,070 KB)" or
"Downloading update (184,557 of 573,070 KB)". UPDATE_PROGRESS only matched the
forwarded x86-64 form without separators, so the loading screen stayed on
"Waiting for Steam's first frame" with no percentage for the whole ~570 MB
first update. Users took that for a hang and cancelled; after two starts the
installer's repair wiped the partial download, so it started over each time.

Accept separators, and fall back to the bootstrapper's language-independent
"Set percent complete: N" line.

* chore: drop the added comment

* fix(loading): a zero or post-extract percent line no longer reads as a download

* fix(loading): an unknown percent ends the earlier download percent

* fix(session): ignore out-of-range percents and clear a percent after an unknown one

---------

Co-authored-by: guohaomin1995-dev <321670510+guohaomin1995-dev@users.noreply.github.com>
Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-24 16:17:17 -05:00
informalTechCode ee6cf20ae4 fix(glasses): correct One Pro+ tracking and enable verified controls (#2680)
* fix(glasses): correct One Pro+ tracking and enable verified controls

* fix(i18n): translate current XREAL family guidance
2026-11-24 16:17:12 -05:00
Moroni Granja 2a51b044c5 fix: a Steam target whose file is gone goes back to the app's exe (#2411)
* fix: a Steam target whose file is gone goes back to the app's exe

A shortcut Target edited in Steam is kept across the client's restart on
purpose, but it was kept even after the file it names disappeared. When the
app's own exe already equalled the recorded proposal, nothing replaced the dead
target: Steam started `System/launcher.exe`, Wine answered
`err:steam:run_process Failed to create process ...: 2`, and the game never ran
(#694, after #1644 and #2022 removed the two real causes).

The merge now treats a target that is not a file as no edit at all and writes
the listing's exe and StartIn. The check runs in the guest, where the shortcut's
paths live.

Fixes #694

* fix: keep a Steam target whose card is not mounted

- The app recreates /mnt/droiddeck-sd and /mnt/bannerlator-sd before binding the card, so the
  mountpoint outlives a removed card. A target directly under one had an existing parent, so
  the missing-file repair overwrote the edited Exe and Start In and kept them overwritten.
- The repair now needs the target's storage to be there: a card mountpoint that lists nothing
  is a card that is not in the device, and the edit is kept for when it returns. Extra Steam
  libraries under /mnt/droiddeck-lib/<id> get the same check.
- test_a_steam_target_under_a_bare_card_mountpoint_is_kept fails without the check and asserts
  both fields; test_a_steam_target_under_a_mounted_card_goes_back_to_the_apps keeps the repair.

* fix: repair a Steam target removed with its folder

- A missing target is gone when its storage is mounted and either its folder is still
  there or it lives in a tree the app always has (internal store installs, the internal
  Steam library). An update that removes the whole game folder now repairs the shortcut.
- Store volumes and added game folders are removable mounts too: /mnt/droiddeck-stores/<id>
  and /root/Games/<name> are checked for content before a target under them is treated as
  gone, so an unplugged volume keeps the edited Exe and Start In.
- Tests: internal folder removed repairs both fields; a bare store mountpoint and a card
  mountpoint keep both; a mounted card still repairs. 84 tests pass.

* fix: classify a Steam target by its resolved path

- A target such as /root/Games/Stores/../../../mnt/droiddeck-sd/Other.exe matched the
  internal prefix and was repaired while the card was out. internal_target and
  removable_mount now normalize the path before choosing the storage class, so the
  decision follows the file the target resolves to; the kept text is unchanged.
- test_a_steam_target_is_classified_by_its_resolved_path fails before the normalization
  (the edit is replaced) and keeps both fields after it. 85 tests pass.
2026-11-24 16:17:04 -05:00
Shawn Montgomery ab023667a0 fix(xbox): a bundle's own packaging files don't stop the legacy install (#3003)
Halo Wars: Definitive Edition's EAppx bundle leaves AppxBlockmap.xml at
the top of the game folder, and its one package folder has its own, so
hoist refused the install with "Extraction would overwrite ...". The
files a package container carries about itself (AppxBlockMap.xml,
AppxSignature.p7x, [Content_Types].xml, AppxMetadata) now replace the
bundle's copies, found by name regardless of letter casing. A game file
in the way still stops a fresh install.
2026-11-24 16:17:00 -05:00
JM LamboandJacob Lambert 0a27c8bb98 fix(desktop): Firefox renders in software on the system PowerVR driver (#2839)
* fix(desktop): Firefox draws on the system PowerVR driver

Under the nested KWin on the system PowerVR driver, Firefox's Wayland window
stops updating partway through drawing and repaints only where the pointer
moves. Through Xwayland it draws normally, so Desktop runs Firefox on X11 on
that path.

* fix(desktop): Firefox renders in software on the system PowerVR driver

The Xwayland workaround only worked because Firefox fell back to software
WebRender there. The breakage follows hardware WebRender on zink, not the
Wayland window: with MOZ_ACCELERATED=0 Firefox draws correctly on Wayland,
so it keeps native Wayland features such as fractional scaling.

---------

Co-authored-by: Jacob Lambert <183008808+JMLambo@users.noreply.github.com>
2026-11-24 16:16:55 -05:00
Kurt Himebauch bcd4e0d99f fix(agent): the setup install retries on transient source errors and no longer accepts a held-back package (#2904) 2026-11-24 16:16:50 -05:00
xlulx 86ea861818 fix(frontend): turn on native DirectX shader compilers for Warband, Don't Starve Together and EU4 (#2998)
* fix: turn on d3dx9 and D3DCompiler 42 for Mount & Blade Warband

Warband compiles its postFX effects at launch through d3dx9_42. With Wine's
built-in d3dcompiler_42 the launch stops on an error dialog (E5017 'Write pass
assignments', then E5033 'Unknown target profile __fx_2_0__'). The native
d3dx9 and D3DCompiler 42 components fix it, but nothing picked them: Steam's
list for the game does not name them and the folder scan only recommends d3dx9.

* fix: turn on D3DCompiler 43 for Don't Starve Together

Don't Starve Together renders through its bundled ANGLE, which compiles
vs_3_0/ps_3_0 shaders with d3dcompiler_43. With Wine's built-in compiler
the bytecode trips DXVK's SM3 parser (`m_info.kind == OperandKind::eSrcReg`
in sm3_parser.h), the render thread stops after "Renderer initialize: Okay"
and the game sits on a black screen. The native D3DCompiler 43 component
fixes it, but Steam's list for the game does not name it.

* fix: turn on D3DCompiler 43 for Europa Universalis IV

EU4 builds its map effects at launch through native d3dx9_43, which compiles
them with d3dcompiler_43. Wine's built-in d3dcompiler_43 fails the terrain,
border, map name and bloom shaders with E5005 ('No compatible 2 parameter
declaration for GetFoWColor'), so the map draws black and province names show
as white blocks. Steam's list for the game names only d3dx9; turning on the
native D3DCompiler 43 component as well fixes the map.

* test: keep one per-game redist test, the one that also covers Steam's d3dx9 pick

The Warband and Don't Starve Together tests only restated their SCRIPTED rows;
Skyrim's test already covers how SCRIPTED picks are added.
2026-11-24 16:16:45 -05:00
Dennis ZabolotnyandDennis Zabolotny 76e0460064 fix(storage): warn when game storage is formatted as FAT32 (#2883)
* fix(storage): warn when game storage is formatted as FAT32

FAT32 cannot hold files over 4 GB, so Steam games with larger files fail to install and Steam reports 'Not enough disk space'. Warn when such a card is chosen as game storage.

* fix(storage): translate the FAT32 warning into Russian

* fix(storage): warn about FAT32 for Automatic, extra libraries and store folders

Show the FAT32 note in the Second library menu while the effective card is FAT32, so the default Automatic choice is covered, and warn when an additional Steam library or a store install folder is added.

* fix(storage): shorten the FAT32 warning and warn on reselecting a saved folder

* fix(storage): warn for the resolved store target and keep the SD note

---------

Co-authored-by: Dennis Zabolotny <15849186+zdennisz@users.noreply.github.com>
2026-11-24 16:16:40 -05:00
Ouse 64647e0d99 fix(input): normalize hardware Escape before Back handlers (#2976) 2026-11-24 16:16:35 -05:00
MaxsTechReview 8bb1895702 fix(gog): skip saves GOG Cloud marks deleted (#3025)
* fix(gog): skip saves GOG Cloud marks deleted

GOG keeps a deleted cloud save in the listing as an empty gzip object
(hash aadd86936a80ee8a369579c3926f1b3c). The listing was read as plain
names without hashes, so every deleted save was downloaded again as an
empty file. Ask for the JSON listing, keep each object's hash, treat
deletion markers as absent, and only send a marked save back once it
changed locally. Local files are never removed.

* docs: credit gogdl and Lutris for the GOG cloud deletion marker
2026-11-24 16:16:31 -05:00
LarzVader ae47876386 fix(venus): Zink draws on Mali-G610 when the depth test is off (#3102)
With depthTestEnable off, Vulkan ignores depthCompareOp. The Mali-G610 driver behind Venus
(Nothing Phone (2a), Dimensity 7200 Pro) applies it anyway, even without a depth attachment.
Zink leaves the op at VK_COMPARE_OP_NEVER whenever GL has the depth test off, so every fragment
Zink draws is thrown away: clears and copies work, draws never show. This is the black Steam UI
when it renders through Zink and the black picture of OpenGL games such as Stardew Valley. DXVK
sets ALWAYS in the same case, which is why D3D games drew.

The layer now hands the driver ALWAYS while the depth test is off:
- vkCmdSetDepthTestEnable and vkCmdSetDepthCompareOp keep the state per command buffer, which
  vkBeginCommandBuffer clears. While the test is off the driver gets ALWAYS; turning it on again
  restores the application's op.
- A pipeline with the depth test off and neither state dynamic is created with ALWAYS.

It is on for every device with gaps. ALWAYS for a disabled depth test changes nothing on a driver
that follows the spec.
2026-11-24 16:16:26 -05:00
LarzVader 6e252ea3ad fix(venus): destroying a null handle no longer grows the Mali layer's maps (#3101)
The handle maps use key 0 for an empty slot. vkDestroyBuffer, vkFreeMemory and the other destroy
calls accept VK_NULL_HANDLE, and map_remove(0) matched the first empty slot it reached, so every
such call lowered count without removing anything. Once count wrapped below zero, every map_put
saw a full table and doubled it, and each rehash took twice as long as the one before.

Steam's web helper frees null buffers about 50,000 times in a few minutes. On a Mali-G610 its UI
stalled periodically for 0.2 s, 0.37 s, 0.75 s, 1.5 s and then 3 s, and the buffer map reported a
count of 4294967295.

map_get, map_put and map_remove now ignore key 0. On a Nothing Phone (2a) running 0.7.1 with this
change, the buffer map stayed at 256 slots after 115,000 frees and the stalls were gone.
2026-11-24 16:16:19 -05:00
MaxsTechReview 1f82db66ac fix(desktop): flatpaks that point Vulkan at their GL extension still get the session's driver (#3159) 2026-11-24 15:33:53 -05:00
MaxsTechReview fbeefc9c9a fix(desktop): programs started by name run scripts without a shebang line (#3155) 2026-11-24 15:33:49 -05:00
Kurt Himebauch 2e3b69e9ff perf(steam): setup applies Steam's client update so the first launch has nothing to unpack (#3152)
* perf(steam): setup applies Steam's client update itself so the first launch has nothing to unpack

The setup already downloads every package of Steam's client update. droiddeck-steam-preapply now extracts them and writes the .installed and .manifest records the way Steam's updater does, so the first launch verifies and starts instead of unpacking for about half a minute and restarting. When it cannot, the packages stay and Steam updates itself as before.

* perf(setup): the Steam stage skips the plain packages it just applied, and Proton's install trusts the prefetch's checksum

With the whole client update applied from the cached packages, the separate 362 MB plain-package install is redundant: the cache pass applies the update and finishes the install, and the plain install stays as the fallback. DroidDeck Proton's archive was hashed twice more at install time after the prefetch had already verified it; the install now reuses that result while the file is unchanged.

* fix(steam): a failed or cancelled apply leaves nothing stale, extraction stays inside the Steam root, and a cache failure still installs

A failed apply removes its record and the cache marker so the next run retries; cancelling stops the helper; entries that leave the Steam root, directly or through a symlink, are refused; the plain install still runs when the cache pass fails; Proton's install reuses the prefetch's verification only for the same digest.

* fix(steam): a cancelled apply clears the cache marker too
2026-11-24 15:18:41 -05:00
Kurt Himebauch 9db80cebd9 chore: add EnzoDLofi to trusted-test-builds.txt (#3156) 2026-11-24 14:26:23 -05:00
LunaDL f920aad104 Feat: toggle to show hud only in a game (#2970)
* Add HUD visibility toggle for active games

* Add HUD visibility translations for all languages

* Fix HUD game visibility and Turkish strings

* Support compositor-only HUD game detection

* Fix HUD activity reconciliation and Steam focus

* Clear stale Gamescope focus metadata

* Clear stale Steam focus when metadata is unavailable

* Prevent HUD flicker on metadata read failures

* Prevent HUD visibility flicker

* Fix HUD visibility during compositor activity

* Fix HUD visibility during compositor activity

* Prevent Steam SHM frames activating HUD

* Fix HUD activity detection when Steam is focused

* Remove HUD detection comments

* Fix HUD game activity detection

* Fix HUD compositor activity detection

* Use Gamescope frames for HUD activity detection

* Restore fullscreen SHM frame statistics callback

* Restore fullscreen SHM frame statistics callback

* Fix HUD SHM frame reporting

* Prevent Steam focus from activating game-only HUD

* Fix SHM frame freshness guard and test harness

* Used suggestion code from rabbit

* Ignore Steam UI frames for game-only HUD

* Keep default HUD stats updating over Steam UI

* Isolate Steam fallback frame statistics

* Isolate Steam fallback frame statistics

* Trigger HUD APK build
2026-11-24 14:19:42 -05:00
MaxsTechReview e709e1c454 fix(desktop): Go programs see the session's identity and paths (#3154)
* fix(desktop): Go programs see the session's identity and paths

Static Go programs now get the session's root identity from getuid and its
relatives, and set*id calls succeed, as C and x86 programs already do. The
added code also takes over Go's second raw system call function (and its
golang.org/x/sys copy), which getuid goes through.

Go programs that link the C library (snapd, gocryptfs, ipp-usb) get the same
code: their Go note is found past the other notes, and the code fits before
a data segment that does not start on a page boundary. snap now reaches the
session's snapd and installs snaps.

* fix(desktop): read every Go note and retry Go programs after a failed scan
2026-11-24 14:07:01 -05:00
The412Bannerandmaxjivi05 5f8655b13e fix(flatpak): find sandbox sources named by their kernel path when the session runs without proot (#3059)
Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-24 11:39:52 -05:00
MaxsTechReview c298da6f60 fix(nativeguest): keep loader paths out of guest environment (#3147)
* fix(nativeguest): keep loader paths out of guest environment

* fix(nativeguest): preserve caller library search paths

* fix(nativeguest): preserve empty caller library path components
2026-11-24 10:30:54 -05:00
Kurt Himebauch caf16c8aa5 fix(steam): a failed package claim fails the install (#3149)
run_parallel is called in an || list, which switches set -e off inside it and inside its workers, so a failed claim left the worker's index empty and the worker exited successfully with packages unclaimed. The worker now checks the claim itself and marks the run failed, and claim_next uses the same flock command as the unpack lock.
2026-11-24 10:15:38 -05:00
Kurt Himebauch c1dd542f97 fix(steam): the parallel installer claims packages under a flock (#3145)
The parallel workers claimed packages with mkdir, which is not atomic in the app's guest shell: two workers sometimes took the same package and about 3 installs in 8 failed on a device. Claims now come from a counter under a flock, and a counter that cannot be read or written fails the worker.
2026-11-24 09:51:16 -05:00
The412Bannerandmaxjivi05 cf44aaed14 fix(appimage): catalog AppImages start without proot (#3077)
* fix(appimage): catalog AppImages start without proot

* fix(appimage): cache cleanup does not follow symlinked entries

* fix(appimage): keep unpacked copies in use and track subsecond changes

* fix(appimage): extract native images through an open descriptor

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-24 09:37:09 -05:00
Kurt Himebauch 39debda0b0 fix(onboarding): a smoother first run, from the child-process setting to the Steam sign-in (#3114)
The child-process fix always uses the guided pairing flow, Finish setup opens the setting directly and queues the Steam launch, the Play button carries the first-run progress, the setup bar weighs each download by its real size, and the Steam client packages download over four connections and unpack one at a time under a flock.
2026-11-24 08:56:08 -05:00
Kurt Himebauch 46ec222fa5 fix(ui): apps launched to either screen open where you chose (#3093) 2026-11-24 08:11:13 -05:00
Kurt Himebauch e2d87c5083 feat(tools): pre_pr.sh runs the CI checks the fast loop skips, for what the branch changes (#3119)
* feat(tools): pre_pr.sh runs the CI checks the fast loop skips, for what the branch changes

* fix(tools): pre_pr.sh checks authorship with no file changes and skips deleted tests

* docs(agents): pre_pr.sh picks tests by name

* docs(agents): pre_pr.sh compiles and lints only for app changes
2026-11-24 04:45:54 -05:00
Kurt Himebauch 1534cf1c93 fix(ci): cache the Windows launcher services so hosted runners finish within the job limit (#3139)
* fix(ci): cache the Windows launcher services so hosted runners finish within the job limit

* fix(ci): save each launcher build as soon as it finishes, and install both linkers for Rockstar
2026-11-24 04:08:14 -05:00
Kurt Himebauch 627344ea30 fix(ci): Robolectric's jar cache restores on every runner (#3134) 2026-11-24 02:49:49 -05:00
MaxsTechReview 7905e2f8ba fix(ui): Stores is back on the bar by default (#3115)
The tab layout from #2798 moved Stores into More for anyone who never
arranged their tabs, so the Battle.net and Epic launchers on the Stores page
looked gone after updating from Stable. A layout someone saved is kept.
2026-11-24 01:24:39 -05:00
MaxsTechReview f6c6e73a6b Native hook: start a program again through /proc/self/exe as itself (#3120)
* Native hook: start a program again through /proc/self/exe as itself

A program that execs /proc/self/exe (Chromium's network and utility
services, Electron apps) reached the kernel link, which names ld.so, so
the child was started without ld.so and saw libddexec as its own
program. Chromium then looked for its ICU data beside libddexec and the
network service crashed in a loop.

The exec path now resolves /proc/self/exe to the program the hook knows
it runs, so it is routed like any other guest program, and readlink of
the exe link names a program from a bind by its guest path.

* fix(hook): keep the host path of a running program a nested bind shadows
2026-11-24 01:06:17 -05:00
Kurt Himebauch 309893b722 fix(ci): cache Robolectric's Android jars so Maven Central 429s stop failing unit tests (#3127) 2026-11-24 00:46:03 -05:00
Kurt Himebauch 9b800ceb5e feat(build): build_local.sh reuses main CI's prepared components when this tree would prepare the same (#3118)
* feat(build): build_local.sh reuses main CI's prepared components when this tree would prepare the same

* docs(agents): build_local.sh reuses CI's prepared components

* fix(build): reuse only this repository's main artifacts, keyed by artifact id

* fix(build): CI reuse verifies before replacing, and declines other NDKs, PulseAudio sources, unregistered inputs and edited submodules

* fix(build): CI reuse also declines a VK_INCLUDE override

* fix(build): CI reuse also declines a custom build image
2026-11-24 00:21:26 -05:00
MaxsTechReview a03ec8eb57 Session preload: leave programs a Chromium app starts from its own folder alone (#3121)
The browser flags were added to every program beside chrome-sandbox
that had no --type switch. Chrome's crash handler is such a program, so
it was started with --no-sandbox, rejected it and exited. A Chromium app
that starts a program from its own folder already passes that program
the arguments it needs, so those programs are left unchanged. Another
Chromium app started from it still gets the flags.
2026-11-24 00:12:02 -05:00
MaxsTechReview e349d2544e fix(nativeguest): a script interpreter reached through a bind runs as a guest program (#3112)
* fix(nativeguest): a script interpreter reached through a bind runs as a guest program

A Flatpak runtime binds its own /usr outside the sandbox root, so the hook
took #!/usr/bin/bash there for an Android program and handed it to the
kernel, which failed with "bad interpreter". An interpreter whose guest
path is a bind now starts like any guest program.

* Native hook: keep Android interpreters a bind reaches on the host

* Native hook: match the root of an interpreter on a folder boundary
2026-11-23 23:42:04 -05:00
MaxsTechReview 5f2699e56b fix(fex): x86 programs see the session's identity from getuid and its relatives (#3104)
* fix(fex): x86 programs see the session's identity from getuid and its relatives

* fix(hook): getresuid and getresgid keep EFAULT for a missing pointer

* fix(hook): getresuid and getresgid return EFAULT for any pointer the kernel cannot write

* fix(hook): getgroups returns EFAULT for a list the kernel cannot write
2026-11-23 23:41:42 -05:00
MaxsTechReview cd87718ac2 fix(hook): named semaphores live where the session maps /dev/shm (#3110)
* fix(hook): named semaphores live where the session maps /dev/shm

* fix(hook): a semaphore opened twice is one mapping, mapped before its name is published

* fix(nativeguest): a fork while another thread opens a semaphore leaves the child a usable registry

* Native hook: register the semaphore fork handlers at load
2026-11-23 22:53:19 -05:00
Kurt Himebauch f9304f41c7 fix(ci): remove the three main unit test flakes (#3117)
* fix(test): ProtonMenuAutoTest no longer fetches Proton releases from GitHub

aCachedCheckUpdatesOnlyInstalledFamiliesAndReplacesOlderDroidDeckProton left experimentalRefresh at its default, which downloads the release list with 10 s connect and 15 s read timeouts, so a slow or rate-limited network blew the test's 5 s wait.

* fix(test): a background-thread error no longer halts the unit test JVM

Every Robolectric test runs App.onCreate, which chains CrashHandler onto the default uncaught-exception handler. A plain JVM has none, so the first test's handler halts with exit 2 on any later uncaught error, and the chain grows by one layer per test. A Robolectric lifecycle plugin now resets the default handler to a printing one before each test.
2026-11-23 22:09:28 -05:00
Kurt Himebauch 95aab3703f fix(build): helper script edits no longer invalidate the prepared runtime, and every build uses CI's NDK (#3116)
* fix(build): helper script edits no longer invalidate the prepared runtime, and every build uses CI's NDK

* docs(agents): helper script edits no longer need build_local.sh
2026-11-23 21:55:27 -05:00
Kurt Himebauch fcaaf4dde0 docs(agents): hints for the build loop, worktrees, device control and CI failures (#3113)
* docs(agents): hints for the build loop, worktrees, device control and CI failures

* docs(agents): run the tests that cover changed code
2026-11-23 21:36:14 -05:00
MaxsTechReview d967dd03a3 fix(desktop): Electron and Chromium apps start however they are launched (#3106)
* fix(desktop): Electron and Chromium apps start however they are launched

The session preload only added --no-sandbox when the program path itself
sat beside chrome-sandbox, so a PATH link such as /usr/bin/vesktop was
missed and the app aborted on the setuid sandbox. It now resolves the
path and also checks the parent folder, and adds --ozone-platform=x11
when an X display is set, since Wayland cannot open the GPU stand-in.

The desktop menu overrides that added the same flags are removed: they
covered only menu launches made after the desktop started, and the
preload now covers every launch. Stale overrides are cleaned up by the
existing marker check.

* fix(preload): execvp checks the program found on PATH for the Chromium flags

* fix(preload): the PATH lookup prefers the program execvp would run
2026-11-23 21:23:56 -05:00
MaxsTechReview 366afa6b73 fix(desktop): an arm64 AppImage started directly runs like one opened from the file manager (#3108)
* fix(desktop): an arm64 AppImage started directly runs like one opened from the file manager

Without proot a guest program starts through the dynamic loader, which
refuses the nonzero ABI version byte that marks every type 2 AppImage,
so running an arm64 AppImage from a terminal or from a menu entry that
names the image failed with "ELF file ABI version invalid". The preload
already hands foreign programs to droiddeck-open; AppImages now go there
too, where they are unpacked and started as the file manager does.

* fix(desktop): hand off only AppImages that carry a filesystem, never a bare runtime
2026-11-23 21:17:17 -05:00
MaxsTechReview 5cb8e7fdf3 fix(hook): /dev/fd in a forked process names that process's own descriptors (#3105)
* fix(hook): /dev/fd in a forked process names that process's own descriptors

The /dev/fd and /dev/std* binds point at /proc/self/fd. Their sources were
resolved with realpath when the binds were loaded, which turned /proc/self
into the loading process's pid. A child that forks without exec, such as a
bash subshell running cat < <(...), then opened its parent's descriptors
and failed with ENOENT. Sources under /proc keep their own path.

* fix(hook): keep canonical bind sources for /proc paths that name no process

* fix(hook): only /proc bind sources that name a process keep their form
2026-11-23 21:17:13 -05:00
MaxsTechReview 8ee80aa20f fix(appimage): arm64 programs use the session's GL libraries over bundled copies (#3103) 2026-11-23 20:02:13 -05:00
MaxsTechReview 78f942313d fix(fex): x86 programs no longer see the host's arm64 preload libraries (#3098)
* fix(fex): x86 programs no longer see the host's arm64 preload libraries

* test(fex): build the x86 preload fixtures with an x86-64 compiler
2026-11-23 20:02:08 -05:00
MaxsTechReview 8576652fb6 fix(fex): thunk libOpenGL with the host GL library (#3099)
* fix(fex): x86 programs that use libOpenGL load again

* fix(fex): thunk libOpenGL with the host GL library
2026-11-23 19:09:23 -05:00
MaxsTechReviewandmaxjivi05 f539660650 fix(nativeguest): keep parent lookups inside the guest root (#3094)
* fix(nativeguest): keep the parent of the guest root inside the rootfs

* fix(nativeguest): keep every .. walk inside the guest root and its mounts

Absolute paths that climb above /, relative paths from the working
directory or any descriptor, and paths that climb out of a mount were
resolved by the kernel from the rootfs folder or the mount's real place,
so /.., chdir("..") from / and fstatat(fd, "../..") listed the app's
files folder. The walk is now resolved in the guest's view first.

* fix(nativeguest): .. from a linked mount ancestor follows the real directory

---------

Co-authored-by: maxjivi05 <6025299+maxjivi05@users.noreply.github.com>
2026-11-23 18:55:37 -05:00
MaxsTechReview ba3f840b8d fix(fex): x86 programs reach Unix sockets inside the rootfs (#3097)
* fix(fex): x86 programs reach Unix sockets inside the rootfs

* fix(nativeguest): bind uses only the socket path length the caller gives
2026-11-23 18:48:52 -05:00
MaxsTechReview ec31c9e2b6 fix(nativeguest): load glibc locales and iconv modules without proot (#3096)
* fix(nativeguest): load glibc locales and iconv modules without proot

glibc opens its locale files and gconv modules with its own internal
open(), which the hook never sees, so every program ran in the C locale
and iconv knew only built-in charsets: Qt warned it could not switch to
UTF-8, setlocale() failed for C.UTF-8 and the app's language, and
iconv -t latin1 was unsupported. The hook now points LOCPATH and
GCONV_PATH at the rootfs; droiddeck-fex keeps x86 guests on their own
gconv modules.

* test(nativeguest): the locale default test ignores the developer's own paths
2026-11-23 18:36:48 -05:00
Kurt Himebauch 59e98afae7 feat(onboarding): background first-run downloads, one setup card, no wait for Steam (#3091)
* feat(onboarding): one setup card, Steam client and Proton downloaded in the background, no component toast

* feat(onboarding): an optional Bluetooth controllers row in the setup card asks for the permission up front

* feat(onboarding): prefetch Steam's whole package cache, one foreground notification, child-process setup while downloads run

* test(steam): the cache pass keeps packages under Steam's names and is not repeated

* feat(onboarding): unpack the whole Steam client ahead of time and record it as installed, downloads no longer wait for a cool device

* feat(onboarding): setup progress on the Steam home page, Bluetooth asked only from the setup card, Steam unpacks its own files

* fix(onboarding): review fixes: removal does not report setup progress, cancel stops the whole prefetch, cache files are verified, no resume toast

* fix(onboarding): a cancelled prefetch is never a setup failure

* fix(onboarding): the Steam fact is updated atomically

* feat(onboarding): Bluetooth controllers moves into the Steam integration list
2026-11-23 17:31:24 -05:00
Kurt Himebauch 15b1e196af fix(remote-play): the decoder reports a changed stream size, so fullscreen streams are not cropped to a corner (#3095)
* fix(remote-play): the decoder reports a changed stream size, so fullscreen streams are not cropped to a corner

* fix(remote-play): capture buffers are sized for large streams up front and a size change reopens only the app decoder

* fix(remote-play): reject out-of-range scaling deltas and an SPS that ends before its frame flag
2026-11-23 17:31:13 -05:00
MaxsTechReview b0a8c0898e ci: keep unit-test scratch out of the runner's shared /tmp (#3083)
* ci: keep unit-test scratch out of the runner's shared /tmp

Test JVMs now write temp files under the test task's build folder,
which checkout wipes on every job, so a killed run no longer leaves
Robolectric and JUnit folders behind in /tmp.

Self-hosted runners also clear stale test folders they own in /tmp,
drop the regenerable Gradle build cache when the workspace has under
20 GB free, and log disk use so a full disk is visible in the job.

* test(agent): size check no longer depends on the temp path's length

A symlink's own size is the length of its target path, so the old
100-byte bound failed once the temp dir moved under the build folder.

* ci: never remove a mount point while clearing runner scratch

* ci: keep a scratch folder that anything inside it touched recently

* ci: keep a scratch folder the freshness scan could not read
2026-11-23 15:24:05 -05:00
Kurt Himebauch e3b1b60914 feat(steam): first-run defaults for big art and the bouncing logo screensaver (#3087)
* feat(steam): first-run defaults for big art on Library home and the bouncing logo screensaver

* fix(steam): seeded keys land in the root store when nested stores close on its last line
2026-11-23 14:16:51 -05:00
Kurt Himebauch 86ad1544a6 feat(ui): a More tab in the session menu for rarely used pages (#3084)
* feat(ui): a More tab in the session menu keeps the pages you use least, and holds the way to arrange them

* fix(ui): bumpers walk only the strip, and back leaves a page kept inside More

* feat(ui): a Back to More row at the top of pages kept inside More

* refactor(ui): the arrange pages editor reuses the Edit tabs More divider

* feat(ui): the Session page can be kept inside More

* fix(ui): the on-screen bumpers step across the strip like the physical ones
2026-11-23 14:08:17 -05:00
Kurt Himebauch db80e7592a tools: quick_deploy skips lint vital (#3085) 2026-11-23 13:34:27 -05:00
MaxsTechReview 6ecc5a22d3 fix(addons): CurseForge connects once, reuses its game instance and skips rescans after its own changes (#3081)
* fix(addons): CurseForge connects once, reuses its game instance and skips rescans after its own changes

* fix(addons): a settled list is dropped by a refresh, a later change or a newer change

* fix(curseforge): publish the report under the same lock as the turn check

An older change could report its list after a newer one had already
reported, so the fallback marks could miss add-ons the newer change
installed.
2026-11-23 13:33:29 -05:00
Kurt Himebauch 963af6df8e fix(ui): Reset tabs popover takes controller focus in the Edit tabs sheet (#3082) 2026-11-23 13:32:39 -05:00
The412Banner f683e97172 fix(xbox): read a GameCore package from its config beside the generated AppxManifest (#3029) 2026-11-23 13:28:33 -05:00
Kurt Himebauch 5df25c77ca feat(ui): resize the session menu by its edge, and set dual screen from the menu (#3080)
* feat(ui): resize the session menu by its edge handle, and set dual screen to auto, on or off from the menu

* fix(ui): the session menu resize handle follows the finger across several moves per frame

* fix(ui): the closed agent menu button has no gap inside its outline

* feat(ui): the session menu's resize handle hovers just past its left edge

* fix(session): turning dual screen on from the menu moves the menu itself to the second screen

* fix(ui): keep the menu width bounds current and restore a pinned second-screen menu after backgrounding
2026-11-23 12:49:10 -05:00
Tushar Gandhe 3502b43cea fix(ui): the controller focus ring follows each corner of the focused shape (#3036) 2026-11-23 12:07:14 -05:00
Kurt Himebauch 4b8c3b158d fix(ui): compact chat in the session drawer stays usable on short or narrow panels (#3078) 2026-11-23 11:33:13 -05:00
MaxsTechReview 2151db3883 fix(battlenet): offer World of Warcraft: Forever in the store (#3075)
Forever has its own launch code and installs headlessly through its
product code like the other titles, but the store hid it. It is now
listed and hidden once installed.
2026-11-23 11:11:15 -05:00
MaxsTechReview 823f70320f fix(nativeguest): x86-64 path calls, SIGSYS handlers and re-execs stay inside the rootfs hook (#3074)
* fix(nativeguest): x86-64 path system calls and SIGSYS handlers stay inside the rootfs hook

FEX passed most guest path system calls to the kernel with an inline svc, so the
native path hook never mapped them, and it mirrored guest SIGSYS handlers with a
raw rt_sigaction that replaced the hook's own handler, after which the next
blocked system call killed the program. Path calls now go through libc's
syscall(), which the hook maps (guarded until the hook is initialised so an early
allocator cannot deadlock), and a SIGSYS handler set through syscall() is
recorded and chained like one set through sigaction().

* fix(ddexec): a program that re-execs itself keeps the rootfs hook

A re-exec through /proc/self/exe starts the program through the guest
ld.so again but left out the hook, so the child saw host paths. Steam's
reaper then recorded host install folders, and Battle.net games moved to
a mapped drive the Library could not resolve. The re-exec now preloads
the hook of the root the same way the first start does.
2026-11-23 11:11:10 -05:00
The412Bannerandmaxjivi05 bf7f7ecda7 fix(nativeguest): a spawned "ld.so --list PROGRAM" loads the program from the rootfs (#3054)
* fix(nativeguest): a spawned "ld.so --list PROGRAM" loads the program from the rootfs

* fix(nativeguest): keep the existing ld.so start comments

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-23 10:40:16 -05:00
MaxsTechReview 3b8b14b06c fix(session): FEX and AppImage extraction no longer hang at start-up (#3070)
The clock pause preload opened its control file on the first monotonic
clock read. A program whose allocator reads the clock while holding its
own lock, as FEX does while it starts, re-entered that allocator through
the open wrappers and deadlocked. The control file is now opened only in
the preload's constructor, so a clock read never opens a file.
2026-11-23 10:27:47 -05:00
DantalianandDantalian a305a91c66 feat(files): add a plain text editor to the file manager (#2980)
* feat(files): add a plain text editor to the file manager

* fix(files): address CodeRabbit review on the text editor

- compose the editor instead of the toolbar so EXIT can't bypass the
  unsaved-changes guard
- read through a capped stream, keep undecodable files read-only, and
  preserve POSIX permissions via staging-file rename with no direct-write
  fallback
- serialize saves, keep dirty consistent across concurrent edits, reset
  match index on text change, fix empty-state counter and read-only
  replace buttons
- scroll match into view horizontally; ignore cursor-only edits for dirty
- add tests for literal U+FFFD files and the capped reader

* fix(files): treat rename failure as save error and follow symbolic links

* test(files): assert the resolved save target without canonicalizing it

---------

Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
2026-11-23 10:16:39 -05:00
Kurt Himebauch 3e558ab33e feat(ui): Decky and Boot movies get their own tabs, with a Decky plugin store (#3068) 2026-11-23 09:59:58 -05:00
Kurt Himebauch d5b9cf5b41 feat(ui): the Updates icon shows the build you're on (#3064) 2026-11-23 09:18:06 -05:00
MaxsTechReview 2478c44948 fix(fex): free host signal state when a guest leaves its handler (#3052)
* fix(fex): free host signal state when a guest leaves its handler

FEX keeps each signal's host context on the host stack and frees it only
on rt_sigreturn. A guest that leaves its handler another way (siglongjmp,
or CoreCLR resuming a catch after a NullReferenceException) left about
2 KB of host stack and one SignalHandlerRefCounter count behind. Some
3500 such exceptions on one thread overran the guard-less 8 MB host
stack, and the CurseForge agent died with "Internal CLR error.
(0x80131506)" and "Stack overflow occurred on the same thread again!"
at the start of its second addon scan.

0009 chains each thread's signal frames with the guest frame range and
alternate stack they used. A signal that arrives in JIT code at the host
level of the newest frame, after the guest stack pointer has left that
frame, drops the left frames and stores its context where the newest
live frame (or the dispatcher entry) left the host stack. rt_sigreturn
pops its frame and any newer ones it skips; thread stop clears the
chain. Signals inside system calls or thunk callbacks are left alone.
This follows the approach suggested in FEX-Emu/FEX#2487.

0008 now restores InSyscallInfo only for signals that interrupted JIT
code, the only case that saves it. Restoring 0 for a signal that
interrupted a system call cleared the mark while the call was still
running; an itimer loop around time() crashed in 15 of 15 runs.

Pocket FIT Elite: siglongjmp out of a SIGSEGV handler died after about
3500 iterations under FEX-2611.1 with and without 0008 and finishes
200000 with 0009; the new probe (350000 escapes on and off the alternate
stack, mixed with returning handlers and nested handlers) finishes under
0009 and crashes before 2000 iterations without it. The 0008 probe
still reports no stale registers.

* test(fex): check every delivery hunk of the 0009 patch

* fix(fex): reset the host stack when a system call ends a block

* fix(fex): thunk calls mark the guest state as spilled

* fix(fex): signal returns apply the handler's register changes

* docs(fex): describe patches 0010 to 0012 and credit the upstream fix

* test(fex): require AVX2 for the ymm probe and keep vdso canaries live
2026-11-23 07:20:33 -05:00
MaxsTechReview 6400a9ef09 fix(addons): uninstall addons the manager has not listed yet (#3060)
A row shown as installed by its toc project id before the manager's first
report had nothing to delete when the manager did not list the project, and
the dialog reported success. The dialog now falls back to the folders whose
toc names the project, deletes them through the existing addon delete, and
shows the delete error when no folder matches.
2026-11-23 06:47:25 -05:00
MaxsTechReview c78adda7ca fix(addons): show installed addons as installed while the manager rescans (#3057)
* fix(addons): show installed addons as installed while the manager rescans

Opening the download dialog starts a fresh scan of the addon manager's
installed projects, and every row showed Install until it answered
(about 20 s). Rows now start from the manager's last report, kept only
for projects whose folders are all still on disk, and its new report
takes over, Update state included.

* fix(addons): match installed addons by their toc project id before the first report

Before the addon manager has reported at all, a search row whose project id
matches an installed addon's X-Curse-Project-ID shows as installed. Placeholder
ids are ignored and the manager's report always takes over.

* fix(addons): read toc fields from flavour tocs and keep known state when a scan fails

An addon whose main toc is a stub keeps its version and project id in the
flavour tocs, so missing fields are now filled from the next toc in order.
A failed manager scan now falls back to the last known installed state
instead of clearing it.
2026-11-23 05:57:05 -05:00
MaxsTechReview 43b17483fb fix(addons): read only the needed .toc fields instead of the whole file (#3056)
Some addons keep their data as metadata lines in the .toc (one has a
57 MB .toc with 400k "## X-..." lines). Opening the Addons tab read the
whole file into one string and kept every metadata line in a map, so each
opening allocated 220-270 MB for a moment and could push the app past its
heap limit. Stream the .toc line by line, keep only Version and
X-WoWI-ID, and stop once both are found.
2026-11-23 04:00:04 -05:00
MaxsTechReview 84c877813f fix(addons): CurseForge rows follow CurseForge's own installed list (#3042)
* fix(addons): CurseForge rows follow CurseForge's own installed list

The CurseForge source reads installed state and available updates from
CurseForge's installed projects after asking it to rescan the game
instance, so addons removed from disk show Install again and out of date
ones show Update, which updates through CurseForge. Deleting an addon
from the addon list uninstalls it through CurseForge when CurseForge
manages it, so its list and the files stay in step.

* Delete addons through CurseForge only while it is already linked

* Link CurseForge on the Addons tab and give its rows Update and Uninstall

* Match WoWInterface addons to the AddOns folders on disk

The WoWInterface source now reads each addon's folder list and marks it
installed when every folder is on disk, whichever source installed it.
Deletes from that source go through CurseForge while it is linked.

* Fix Compose tests hanging after a dropped UI dispatch and stop CurseForge on tab dispose

A non-Compose test that runs the real App after a Compose test in the same
Robolectric sandbox leaves AndroidUiDispatcher flagged as scheduled while its
looper message is dropped by the sandbox reset, so global snapshot changes are
never applied and every later Compose test times out waiting for idle. The
shared compose rule now detects that state and re-arms the dispatcher.

CurseLink.close runs the stop on a job owned by the link, so the tab test can
join it and prove no CurseForge work remains after the tab is disposed.

* Match add-on folders by case, offer only real updates, settle deletes on disk

A delete that CurseForge finished before its link dropped now counts as
done when the folder is already gone. Managed uninstalls only consider
projects whose folders are all present, and folder names resolve
case-insensitively everywhere. Update is offered only for a newer
version, falling back to the source's current file when versions do not
compare. The test compose rule also re-posts a dropped frame dispatch.
2026-11-23 03:15:53 -05:00
Kurt Himebauch f43cc43d05 fix(ui): the empty Steam page's ball bounces edge to edge, and the logo traces in around it on the slam (#3050) 2026-11-22 23:27:28 -05:00
Kurt Himebauch 101139ec99 feat(runtime): run the Linux side without proot by default (#3041) 2026-11-22 21:44:14 -05:00
MaxsTechReview 527cb85867 fix(fex): signal return restores syscall state; CurseForge runs headless (#3040)
* fix(fex): signal return restores the interrupted syscall state

A guest rt_sigreturn goes through FEX's syscall stub, which marks every
static register as spilled. Returning to unchanged JIT code skipped the
stub's reset, so later asynchronous signals skipped the register spill
and guest handlers read stale registers. CoreCLR's GC suspension reads
and redirects that context, which made x86-64 .NET programs fail with
random access violations. Restore the value saved at signal entry.

* fix(addons): run CurseForge headless from the addon browser, without a session

- The CurseForge source starts the app in its own headless gamescope
  (droiddeck-headless, shared with the Battle.net Agent) instead of a hidden
  session: no SessionService, compositor output or ImageReader.
- The helper's start keeps running until the app exits, so the app lives
  for as long as the addon browser holds that guest command; closing the
  dialog asks the app to quit, stops its process group and cancels the
  command, which ends the app, its gamescope and the guest.
- An app the user already has open is reported busy and left alone.
- Removes BackgroundSession and the CompositorHost start path it shared with
  SessionActivity, with their tests.

* fix(addons): bind each CurseForge stop to its launch and keep the inspector URL out of logs

A stop now only acts on the launch that registered it, so a late stop
from a closed browser cannot end a newer launch, and the browser stops
once. Command logs redact the inspector URL. The signal probe reports a
sender thread that cannot start, sets ECX before the measured region and
its test accepts a valid overshoot of the target count.

* fix(fex): unblock the probe signal before sampling
2026-11-22 20:40:30 -05:00
DeathKhan 6ef8e2274e fix(ui): focused cards keep their solid ground under the highlight tint (#2909) 2026-11-22 17:11:29 -05:00
Kurt Himebauch 00525cde15 fix(session): picking a bottom-screen mode clears the menu restore left by a teardown (#3007) 2026-11-22 17:07:23 -05:00
MaxsTechReview 210c127446 feat(addons): add a CurseForge source to the addon browser (#3028)
* feat(addons): add a CurseForge source to the addon browser

Search and install CurseForge addons from the Download addons window by
driving the installed CurseForge app in the background: it starts minimized
on the session's X display with its inspector bound to 127.0.0.1, and the
window's own renderer services handle game detection, search, install and
shutdown. Sign-in stays inside the CurseForge app.

The Install buttons in the addon list now size to their label, so the label
is centered and the button matches the other compact buttons.

* fix(curseforge): secret inspector URL, hold mode and serialised starts

- Start CurseForge with its Node inspector on 127.0.0.1:0 and publish only
  the UUID websocket URL, kept in the 0700 state directory, so no fixed
  unauthenticated debug port is exposed.
- The agent evaluates through that URL instead of a fixed port.
- Add a hold mode that runs as a session program and stops the app on
  exit, and a lock so hold and start never launch twice.

* feat(addons): run CurseForge in a hidden session when none is running

- Opening the CurseForge source with no session starts one headlessly
  (offscreen compositor output, shared start path with SessionActivity via
  CompositorHost) running the CurseForge hold helper; leaving the dialog
  stops the app and that session. A session the user already had is
  reused and left running.
- Drop the "start a session" notice from every locale.
- Addon browser link: cleanup shares the link's lock off the UI thread,
  stops the app at once on close, refuses work after close and stops a
  launch that finishes after close.
- CurseForgeApp.start stops the app before every failed return.
- instanceFor returns no instance when the populated list has no match.

* Harden headless CurseForge session and helper lifecycle

Scope the hidden session to its id, roll back partial starts, release the
offscreen reader once the session ends, re-acquire the inspector when its
endpoint goes away, bound DevTools calls by one deadline, key the installed
snapshot by target, track the helper launch by pid start time and directory,
fail on lock errors, and update the HDR gate test to its new location.

* Map DevTools send failures and recheck the hidden session id

* fix(addons): bind the hidden session to the id it claims at launch

* Keep the CurseForge helper quiet when no launch is recorded
2026-11-22 17:02:35 -05:00
Tushar Gandhe 234e40157e feat(launcher): LT and RT step between the main tabs from anywhere in the launcher (#3035)
* feat(launcher): LT and RT step between the main tabs from anywhere in the launcher

LT and RT move to the previous and next main tab on every layout. The activity handles them before any page sees the key, so a focused control, an embedded Android view such as the terminal, or nothing being focused no longer swallows them; dialogs and popups keep their own keys. Pads that report the triggers only as axes, like the Xbox Wireless Controller, get an L2/R2 press when a trigger passes 60% of its travel; pads that send their own trigger keys are left alone.

* fix(launcher): trigger tab steps tick, drop a pending press on focus loss, and move once per pull

Controller haptics now ticks for L2 and R2. A synthetic trigger press waiting its 40 ms is cancelled when the launcher loses window focus or is destroyed, so a dialog that opens in between keeps the page behind it. Each pull is tracked: when a synthetic press has gone out, the pad's own trigger key for the same pull is swallowed instead of stepping a second tab.
2026-11-22 16:59:01 -05:00
Tushar Gandhe c3809c0a75 fix(ui): keep the Agent composer above the keyboard and release search fields on tap (#2852)
* fix(agent): keep the composer above the keyboard outside fullscreen

* fix(ui): release a search field when another control is tapped

* fix(ui): release the add-on search field in its dialog, and let a reopened search take focus

* fix(ui): a drag that returns to where it began does not release the search field
2026-11-22 16:58:57 -05:00
Tushar Gandhe 71b7b6efad fix(library): put the store accounts button on the right of the source chips, as on other pages (#2929) 2026-11-22 16:58:53 -05:00
Tushar Gandhe a0e7c1715a fix(ui): smaller game page link pills with a gap between rows (#2973) 2026-11-22 16:58:49 -05:00
MaxsTechReview 2c2d55058e fix(preload): open synthesized socket tables when the fd reopen is denied (#3034) 2026-11-22 16:20:34 -05:00
MaxsTechReview 7f61e514e6 chore: pin gamescope to the release with the opacity focus fix (#3031) 2026-11-22 14:27:08 -05:00
MaxsTechReview b891019b87 fix(steam-x64): keep the session's GL thunk for the x86 web helper (#3027)
* fix(steam-x64): keep the session's GL thunk for the x86 web helper

FEX's global AppConfig for steamwebhelper turns the GL thunk off and is
read after FEX_THUNKCONFIG, so the x86 helper used the rootfs's x86 Mesa.
Steam's browser compositor creates its window through SDL3 and GLX in
the helper's browser process, x86 Mesa faulted in driCreateNewScreen3
(SIGSEGV) about 11 s after each start, and the client restarted the
helper every 12 s.

For every global FEX AppConfig that turns off a thunk the session uses,
the launcher writes a local AppConfig with the session's thunk set. It
leaves local files with other content alone and removes its own files
when the client runs in software.

* fix(steam-x64): write FEX AppConfig overrides atomically

* fix(steam-x64): stage AppConfig overrides in a unique temporary file

* fix(steam-x64): publish AppConfig overrides without replacing a newer file
2026-11-22 14:16:34 -05:00
MaxsTechReview 1a29c65d4f fix(gamescope): choose focus again when a window's opacity crosses zero (#3030)
A window is a focus candidate only while _NET_WM_WINDOW_OPACITY is above
zero, but a change of that property never re-ran focus selection. A
layered window that maps fully transparent and fades in was skipped at
map time and stayed skipped once opaque, so a nested desktop session
hid its gamescope window and the game ran with nothing on screen.
2026-11-22 13:47:22 -05:00
MaxsTechReview ff5e4c7ac7 fix(preload): accept NETLINK_ROUTE multicast subscriptions (#3015)
* fix(preload): accept NETLINK_ROUTE multicast subscriptions

Programs that watch for network changes bind their route socket with
multicast groups or join them with NETLINK_ADD_MEMBERSHIP. The emulated
socket refused both with EACCES, and .NET's NetworkChange treats that as
fatal: CurseForge's Mods Agent failed to initialise with "Permission
denied" from NetworkChange.CreateSocket(), so the app never loaded its
library.

Real Linux lets unprivileged sockets join rtnetlink groups. Accept the
groups at bind and through ADD/DROP_MEMBERSHIP, report them from
getsockname(), and keep queries on the same socket working. No change
events are generated yet; queries still return the current snapshot.

* fix(preload): keep netlink group membership in the shared socket state

Memberships now live in the peer metadata the kernel holds for the socket, next to the port and cap ack, so they survive exec and a change made by one process after fork is seen by every process holding the socket.

* fix(session): answer denied /proc/net socket tables

Android's SELinux policy denies app processes every file under /proc/net.
.NET lists TCP listeners from /proc/net/tcp and tcp6 before it binds a
server port, so the CurseForge Mods Agent failed on every port with
"An error was encountered while querying information from the operating
system" on stock firmware. Denied tcp, tcp6, udp and udp6 reads now get a
header-only table, through open and openat as well as fopen, the same way
the route and interface tables already are.

* fix(session): keep synthesized socket tables read-only and file-only

Reopen the populated table read-only instead of duplicating its writable
descriptor, and leave O_DIRECTORY opens with their original failure.
2026-11-22 13:37:44 -05:00
MaxsTechReview 2d38f11b36 Build FEX's latest release, point releases included (#3026)
The FEX build pinned FEX-2610 and its tag checks only accepted four
digits, so FEX-2611.1 was never picked up. The build now takes the
latest release tag, and Fixed-upstream compares the four-digit release.
CMake 4.5 rejects DEPENDS in install(CODE), which stopped host thunk
builds; patch 0007 drops it.
2026-11-22 13:03:43 -05:00
MaxsTechReview fd2e1652ad fix(fex): invalidate translated code written through a later writable alias (#3020)
* fix(fex): invalidate translated code written through a later writable alias

x86-64 CoreCLR maps its W^X memfd writable after the executable view was
translated. Under SMCChecks=mtrack the new alias was never write-protected,
so writes through it did not invalidate stale translations. Protect the
overlapping part of an executable alias on mmap and mprotect.

* fix(fex): protect every writable alias in one mprotect range and build fmt without modules

* fix(fex): build without C++ module scanning or import std
2026-11-22 12:22:11 -05:00
Tushar Gandhe c6b6e7362e fix(ui): game page main action above its box, and tabs that scroll and slide (#2994) 2026-11-22 11:31:46 -05:00
MaxsTechReview cb7edbefd2 fix(input): show the main screen layout editor first, like the second screen (#3019)
The Screen visibility group sat above the Layout group on the Main screen page, so in landscape its description pushed Edit on screen below the fold and the page looked like it had no editor. The Layout group now comes first on both screens.
2026-11-22 10:56:03 -05:00
Kurt Himebauch a9b5994a91 fix(library): drop the card's bottom gradient when it has no text to show (#3017) 2026-11-22 10:52:25 -05:00
MaxsTechReview 42f25c2a6c fix(input): controls edited in portrait keep their places in the panel below the game (#3013)
* fix(input): controls edited in portrait keep their places in the panel below the game

The panel below the game in portrait always regenerated the stock
layout, so positions saved from the Controls editor were dropped and
only the button styling carried over. The panel now orients to the
portrait frame and fits the edited controls into the panel at their
saved proportions; untouched stock layouts keep the generated panel.

* Keep the Deck panel's trackpads and fitted sizes for edited portrait controls
2026-11-22 09:51:32 -05:00
MaxsTechReview 501debc7f6 fix(game-env): Dragon's Dogma 2 starts with its Wine detection off (#3011)
Dragon's Dogma 2 checks for Wine and takes a path that does not start.
Launches of Steam app 2054970 now append the game's own
/WineDetectionEnabled:False switch at launch time. Steam's stored Launch
Options are untouched, and a /WineDetectionEnabled: value the user already
passes keeps priority and is not repeated.
2026-11-22 09:31:40 -05:00
Tushar Gandhe 1f70d43fe2 feat(ui): a Launcher setting turns page swipes off, and edge swipes in landscape leave the page alone (#2924) 2026-11-22 07:26:39 -05:00
Tamim Kabir a8d03d687f fix(input): SDL 3 games no longer crash on the virtual pads' udev devices (#2915) 2026-11-22 02:43:32 -05:00
Kurt Himebauch 9cfab884d5 feat(session): the DroidDeck menu is a bottom-screen mode, and the controller stays with the game (#3001) 2026-11-22 00:16:49 -05:00
FX1922 aefa5a3c0d feat(session): split the display resolution into landscape and portrait (#2990)
## Summary

Splits the session resolution setting into two: **Landscape resolution**
and **Portrait resolution**. Each has the same options as the old
Resolution row, plus a Follow option so one orientation can mirror the
other.

## Why

A single resolution has to serve both orientations. Presets and Match
screen flip automatically in portrait, but a custom size is used exactly
as typed, so a landscape size in a portrait session is wrong. Users who
play in both orientations couldn't pick a good size for each.

## Behavior

- The Display tab shows **Landscape resolution** and, underneath it,
**Portrait resolution**. Both offer the full existing list: presets,
Match screen, Follow screen, scaled follow options and Custom.
- Each row has an extra option at the top. **Follow portrait** (on the
landscape row) and **Follow landscape** (on the portrait row) use the
other orientation's choice, so someone can set one resolution and let
the other mirror it. The label shows the size it resolves to.
- A session picks the landscape or portrait choice from its orientation.
This uses the same orientation check as the output size, so the
unfolded-controls layout still counts as landscape.
- Custom WxH sizes are flipped to match the target orientation when
followed, e.g. portrait following 1280x720 uses 720x1280.
- If both rows would follow each other, the other row is set to the
concrete size it currently resolves to, so there is never a loop and
nothing visibly changes.
- The glasses output keeps using the landscape resolution.
- Applies to the Steam and Desktop Display tabs, which share the same
row.

## Compatibility

- The existing saved choice (`displayResolution.<mode>`) is now the
landscape resolution, so existing users keep their setting.
- The portrait choice is stored as `displayResolution.portrait.<mode>`
and defaults to Follow landscape, so portrait sessions behave as before
until it is changed. The settings reset covers it through the existing
`displayResolution.` prefix.
- One visible difference: a typed landscape custom size, used as typed
in portrait before, now flips to portrait while portrait follows
landscape.

## Known limitation

"Follow screen" is still decided once when the session starts, not on
every rotation. Re-evaluating it on rotation could make the window
orientation flip repeatedly when no orientation is pinned.

## Changes

- `SessionDisplay`: `LINK_LANDSCAPE` / `LINK_PORTRAIT`, `isLink`,
`orientCustom`, `effectiveChoice`
- `SessionPrefs`: `resolutionStored` (raw value per orientation),
`resolutionChoice(..., portrait)`, `setResolutionChoice(..., portrait)`
with the loop guard, `resolutionChosen(..., portrait)`
- `SessionActivity`: `portraitOutput()` drives the output size,
follow-screen choice and follow scale; the Match-screen default for
programs that draw at the panel size checks the matching orientation
- `ResolutionRow`, `ModeSettingsDialog`, `FrontEndActivity`: two rows,
the Follow option, state and actions
- `DeviceReport`: logs landscape and portrait separately
- Strings: `display_resolution_landscape`,
`display_resolution_portrait`, `display_follow_landscape`,
`display_follow_portrait` in all 33 locales; the unused
`display_resolution` is removed
- Tests: `PortraitResolutionTest`

## Testing

- Unit tests added for the preference logic, follow resolution, loop
guard and reset.
2026-11-22 08:03:03 +03:00
MaxsTechReview 6de3c59d7c fix(venus): lower the guest's SPIR-V to 1.3 for the phone's shader compiler (#2587)
* fix(venus): lower the guest's SPIR-V to 1.3 for the phone's shader compiler

* fix(venus): lower SPIR-V to 1.3 for Mali drivers

* fix(venus): keep the SPIR-V cap valid and scoped to active layers

Cap inline compute pipeline code too, leave the shader hooks off when
the layer is turned off, strip clip and cull distances only where they
are emulated, and leave modules alone whose capabilities, decorations or
OpSelect results need a newer version or an undeclared extension.

* fix(venus): keep application pipeline chains read-only and check non-semantic imports

Inline stage code is handed to the driver through a copy of the stage's
pNext chain instead of being written into the application's create info,
pipeline hooks return VK_ERROR_OUT_OF_HOST_MEMORY when their allocations
fail, and a NonSemantic import is only lowered to SPIR-V 1.3 when the
module declares SPV_KHR_non_semantic_info.

* fix(venus): preserve valid pipeline and shader behavior

* fix(venus): lower compatible read-only shader parameters

* fix(venus): install SPIR-V 1.3 lowering hooks on Vulkan 1.2+ devices or emulated gaps
2026-11-21 23:52:56 -05:00
MaxsTechReview bc11653c15 fix(steam): start the web helper when Android refuses CPU pinning on every GPU (#2819) 2026-11-21 23:52:53 -05:00
MaxsTechReview d6496b2f96 feat(addons): install the CurseForge app and update addons per game (#2986)
* feat(addons): install the CurseForge app and update addons per game

The Addons tab installs the official CurseForge Linux app from its own
update feed, checks it against the feed's SHA-512, shows its version,
offers updates and removes it with the components delete button.

Installed addons show their .toc version and are checked against
WoWInterface by X-WoWI-ID or the recorded source of addons installed
from the Download window; Update replaces them in place.

The CurseForge web search chip is replaced by the app.

* fix(addons): address review on update ordering, flavor filter, origins lock and failed checks

* fix(addons): compact scrollable addon browser with list rows

* fix(addons): compare release times as instants and replace the sources file atomically

* fix(addons): open the addon browser at the top of the list

* Keep the addon browser's search focus and installed version in sync

* Track the search field's own focus in the addon browser

* Key the installed addon version by install target

* Install rar and 7z addon archives
2026-11-21 23:47:58 -05:00
MaxsTechReview 3577073ab9 fix(input): move and resize the on-screen D-pad as one control, per-control button size and sizes above 100% (#2996)
* fix(input): move and resize the D-pad as one control, per-control button size and sizes above 100%

* fix(input): controller art for copied layouts, keep the minimum size when shrinking the D-pad

Copies and per-game versions of the on-screen gamepad now draw the same controller art and placement as the original, and resizing the D-pad from a corner or the per-control slider keeps every arrow at a usable size.

* Keep other controls' moves when undoing a repeated resize
2026-11-21 23:47:35 -05:00
Kurt Himebauch a2587f4f20 fix(display): preserve padded layer buffer layouts (#2985)
* fix(display): preserve padded layer buffer layouts

* fix(display): fall back when layer allocation fails

* fix(display): write linear targets at their row pitch
2026-11-21 23:40:11 -05:00
Kurt Himebauch b2687701c1 build: run the local macOS build natively, with no emulation (#2999)
build: make the local macOS build run natively, with no emulation

On an arm64 Mac the x86/i386 session preloads were built in a linux/amd64
container under emulation, and the Rockstar launcher failed to link against
Homebrew's SJLJ i686 mingw. Both now build on the host's own architecture.

- build_local.sh: on arm64 build the x86 preloads in a native arm64 Debian
  bullseye container with the x86_64/i686 cross toolchains (glibc 2.31, as
  before); x86 hosts keep the native gcc-multilib path.
- build-x86-preloads.sh: X86_CROSS=1 selects the cross toolchains.
- rockstar-launcher/build-container.sh: build the launcher in a native
  Ubuntu container with a DWARF2 mingw, used on macOS only.
- vr/build.sh: stop aborting silently when ANDROID_NDK_HOME names an NDK
  that is not installed.
- build_local.sh: expand the empty stores_check array safely on bash 3.2 so
  the script reaches its signing step.
2026-11-21 22:51:27 -05:00
MaxsTechReviewandKurt Himebauch 378175c6ac feat(input): controller-specific on-screen controls with editor, rotation and tablet fixes (#2988)
* feat(input): restore controller-specific overlay designs

* fix(input): restore portrait controller layouts

* fix(input): fix duplicates, rotation and tablet placement in the controller overlays

- Hide the below-game controls while the layout editor is open, and give the
  editor the same cutout insets and optional Steam controls as the game view,
  so the editor never shows a second copy of a control.
- Keep a separate portrait frame for layouts edited in portrait. A layout
  edited in one orientation keeps the stock kit positions in the other instead
  of being stretched across.
- Anchor the overlay to the bottom of the screen and cap the portrait panel's
  physical size, so tablets keep the controls in the lower half.
- Put L2/L1 and R1/R2 side by side in every kit.
- List deleted stock controls in the editor's Add dialog so they can be
  restored, and keep removed rear buttons and trackpads removed.

* fix(input): scale edited overlay layouts around the controller artwork positions

* fix(input): keep stock landscape controls, color setting, keyboard action and displayed frame edits consistent

* fix(input): draw the layout editor with the kit artwork at the size it will be saved

The editor placed its controls in onSizeChanged, which runs during layout, so
the preview canvas was rebuilt or remeasured too late: new controls were laid
out at 0x0 and existing ones kept stale sizes, losing the kit D-pad artwork.
Placement now happens in onMeasure, before the canvas measures its children.

The editor preview used the saved button size instead of the slider value, so
the slider showed a different layout from the one Done saved.

D-pad pieces that joined or left the kit cross were never redrawn, so moving
one piece hid all four.

* fix(input): keep portrait rear buttons and trackpads where they were saved

A portrait save stores the rear buttons and trackpads only in the rotated
frame, but loading that frame only moved controls that already existed in the
main frame, so they were regenerated at the screen edges.

* fix(input): adopt the displayed portrait frame for layouts edited only in landscape

Button size and reset positions now switch to the frame on screen whenever the edited layout's
orientation differs from the editor, not only when a rotated frame exists, so a portrait change
is saved as the portrait frame instead of overwriting the landscape edits. The tools panel stays
open while that happens.

* fix(input): keep a separate button size for the rotated frame

* fix(input): take the shown frame's button size whenever editing switches orientation

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-21 20:11:21 -05:00
MaxsTechReview 183cbd9351 fix(preload): start apps that check for a single thread and stop the first-call allocation hang (#2995)
* fix(preload): look up the native glibc symbol version first so wrapped calls never allocate

On x86 the first dlvsym lookup asked for GLIBC_2.17, which only exists on arm64. The failed lookup makes glibc allocate, which deadlocks when the first wrapped call happens inside a program's own allocator setup. Each architecture now asks for its base version first.

* fix(zram): start the page-out worker per request instead of keeping a thread in every process

Every process that loaded the session preload carried a resident zr-worker thread from its constructor on. Programs that check they are single-threaded before forking or before unshare(CLONE_NEWUSER) failed, for example Chromium's zygote, which could not start its GPU process.

The signal handler now starts the worker with a raw clone on a stack the preload maps itself. The worker makes only raw system calls and exits when no request is left, so starting it from the handler is safe and idle processes stay single-threaded. When the worker cannot be started, the process trims inline in small steps as before.

* fix(preload): start the page-out worker with the same clone flags as a thread

Programs that filter clone to the flag set threads use, as browser
sandboxes do, now accept the worker. The kernel clears the stack-busy
word and wakes waiters when the worker exits.

* fix(preload): page out inline in single-threaded and self-sandboxed processes

A process with one thread may be about to check that it is single-threaded
before fork or unshare, and a process that added a seccomp filter after it
started may trap system calls into its own handler. Neither gets a worker
thread now; both trim inline in small steps as before.

* fix(preload): check the signalled thread's own seccomp filters before starting the worker

Read Seccomp_filters from /proc/thread-self/status so a thread that installed its own filter
without TSYNC trims inline instead of calling clone under that filter, and fall back to the
inline path when the signal mask cannot be changed.

* test(preload): start parked threads with SIGURG already blocked

* test(preload): count only page-out workers when checking for leftover threads
2026-11-21 20:11:18 -05:00
Kurt Himebauch 6af598b25e feat(launcher): tick haptics for controller navigation (#2993)
* feat(launcher): tick haptics for controller navigation, off for touch

* docs: regenerate settings map for controller haptics

* fix(launcher): tick for hat and stick navigation, which arrive as joystick-source keys

* fix(launcher): tick before the Components tab consumes L1/R1
2026-11-21 16:31:58 -05:00
FX192 86226910c3 Correct the tall-aspect game height expectation in the test 2026-11-22 00:09:51 +03:00
FX192 0399c3e510 Use the portrait resolution in the controls-below layout and size the game area to the output aspect 2026-11-21 23:50:19 +03:00
MaxsTechReview 088c8ff1cf fix(battlenet): follow the selected FEX instead of pinning an old build (#2987)
* fix(battlenet): follow the selected FEX instead of pinning a d2rfix build

The Battle.net prefix forced the newest FEXCore d2rfix package from the Nightlies listing, which stopped updating. Its fixes are in the bundled and nightly FEX, so the prefix now uses whatever FEX is selected. Existing d2rfix selections for the Battle.net profile are cleared once; any other choice is kept. The DXVK memory cap and Start without Steam defaults are now applied when a session starts.

* fix(battlenet): import the legacy plugin state before unpinning the Battle.net FEX
2026-11-21 15:31:18 -05:00
Kurt Himebauch 31dd8f9987 feat(session): arrange and hide in-session menu pages, round pinned end-session button (#2989)
* feat(session): arrange and hide the in-session menu pages

* fix(session): the end-session button is a true circle pinned to the right of the menu header

* fix(session): arrange-pages drag reads the current list; reset reloads the page layout even if the activity was recreated

* fix(session): Back leaves Arrange pages first; UI zoo previews don't save page layout

* fix(session): Back on a grabbed page row restores its order before anything else
2026-11-21 15:25:45 -05:00
FX192 567181d05f fix(session): let the portrait custom resolution dialog accept tall sizes 2026-11-21 22:56:29 +03:00
FX192 a9054aac3f fix(session): address review on the landscape and portrait resolution split
Accept generated portrait sizes on reload, use the right orientation and output target when deciding follow screen, show the real size behind each Follow option, treat a saved portrait Desktop resolution as chosen, and update the orientation hint in every locale.
2026-11-21 22:46:45 +03:00
FX192 50dace9958 feat(session): split the display resolution into landscape and portrait
Landscape and Portrait resolution rows with the same options, each with a Follow option so one can mirror the other. Existing choices stay as the landscape resolution and portrait follows landscape by default, so nothing changes until portrait is set.
2026-11-21 22:21:08 +03:00
403 changed files with 22506 additions and 5132 deletions

No files matched your search

+1
View File
@@ -6,3 +6,4 @@ KeegantheVeganat0r
kingokksa
ovurrsl
KeegantheVeganat0r
EnzoDLofi
+4 -1
View File
@@ -29,11 +29,14 @@ jobs:
persist-credentials: false
- name: Build in Arch Linux ARM
env:
GH_TOKEN: ${{ github.token }}
FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }}
FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }}
run: |
set -euo pipefail
docker run --rm -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
FEX_VERSION=$(gh api repos/FEX-Emu/FEX/releases/latest --jq .tag_name)
echo "Building $FEX_VERSION, FEX's latest release"
docker run --rm -e FEX_VERSION="$FEX_VERSION" -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
sudo chown -R "$(id -u):$(id -g)" .
- uses: actions/upload-artifact@v4
with:
+75
View File
@@ -164,6 +164,9 @@ jobs:
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Clear scratch earlier runs left behind
if: runner.environment == 'self-hosted'
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
- name: Merge the pinned APK base
if: github.event_name == 'pull_request'
env:
@@ -367,6 +370,10 @@ jobs:
persist-credentials: false
submodules: recursive
- name: Clear scratch earlier runs left behind
if: runner.environment == 'self-hosted'
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
- name: Check human authorship
env:
EVENT_NAME: ${{ github.event_name }}
@@ -565,23 +572,65 @@ jobs:
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
# A hosted runner needs over 20 minutes per launcher; rebuild only when its sources change, and save each
# build as soon as it finishes so a later timeout cannot discard it.
- name: Restore the Ubisoft launcher build
id: ubisoft-cache
uses: actions/cache/restore@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
key: ubisoft-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/ubisoft-launcher/src/**', 'tools/ubisoft-launcher/Cargo.toml', 'tools/ubisoft-launcher/Cargo.lock', 'tools/ubisoft-launcher/build.sh', 'tools/ubisoft-launcher/build.rs', 'tools/ubisoft-launcher/.cargo/**') }}
- name: Ubisoft launcher service (x86_64-pc-windows-gnu)
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
run: |
set -euo pipefail
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
bash tools/ubisoft-launcher/build.sh
- name: Save the Ubisoft launcher build
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
key: ${{ steps.ubisoft-cache.outputs.cache-primary-key }}
- name: Restore the Rockstar launcher build
id: rockstar-cache
uses: actions/cache/restore@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
key: rockstar-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/rockstar-launcher/src/**', 'tools/rockstar-launcher/Cargo.toml', 'tools/rockstar-launcher/Cargo.lock', 'tools/rockstar-launcher/build.sh', 'tools/rockstar-launcher/build.rs', 'tools/rockstar-launcher/.cargo/**') }}
- name: Rockstar launcher service (32-bit and 64-bit)
if: steps.rockstar-cache.outputs.cache-hit != 'true'
run: |
set -euo pipefail
command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; }
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
bash tools/rockstar-launcher/build.sh
- name: Save the Rockstar launcher build
if: steps.rockstar-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
key: ${{ steps.rockstar-cache.outputs.cache-primary-key }}
- name: Restore the Epic launcher build
id: epic-cache
uses: actions/cache/restore@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
key: epic-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/epic-launcher/src/**', 'tools/epic-launcher/Cargo.toml', 'tools/epic-launcher/Cargo.lock', 'tools/epic-launcher/build.sh', 'tools/epic-launcher/build.rs', 'tools/epic-launcher/.cargo/**') }}
- name: Epic Games Launcher parent stand-in (x86_64-pc-windows-gnu)
if: steps.epic-cache.outputs.cache-hit != 'true'
run: |
set -euo pipefail
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
bash tools/epic-launcher/build.sh
- name: Save the Epic launcher build
if: steps.epic-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
key: ${{ steps.epic-cache.outputs.cache-primary-key }}
- uses: actions/download-artifact@v4
with:
@@ -685,6 +734,32 @@ jobs:
if-no-files-found: ignore
overwrite: true
- name: Resolve the Robolectric version
id: robolectric
run: |
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
# The cache path sits beside the workspace because runner homes are at different depths from it, and
# actions/cache stores paths relative to the workspace. Runners that keep their own ~/.m2 skip the cache.
- name: Place Robolectric's Android jars beside the workspace
id: robolectric-jars
run: |
set -euo pipefail
jars="$GITHUB_WORKSPACE/../robolectric-jars"
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
echo "cache=false" >> "$GITHUB_OUTPUT"
else
mkdir -p "$jars" "$(dirname "$m2")"
ln -sfn "$(cd "$jars" && pwd)" "$m2"
echo "cache=true" >> "$GITHUB_OUTPUT"
fi
- name: Cache Robolectric's Android jars
if: steps.robolectric-jars.outputs.cache == 'true'
uses: actions/cache@v4
with:
path: ../robolectric-jars
key: robolectric-android-all-v2-${{ steps.robolectric.outputs.version }}
- name: Unit tests
id: unit-tests
env:
+36 -1
View File
@@ -2,7 +2,42 @@
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
# Working on the device
# Building and testing
- For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step.
- `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`.
- Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout.
- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally.
- Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '<class>'` and `python3 -m unittest discover -s tools/tests -p 'test_<area>*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI.
- For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape.
- After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`.
- Compile errors in code you didn't touch, after switching branches, are usually stale incremental state. Rebuild once before you change anything.
# Worktrees and shared machines
- After `git worktree add`, run `git submodule update --init --recursive`. Without it, `buildVkBridgeServer` fails on missing `external/MaliBridge`. Do not commit the `tools/syncthing/syncthing-android` pointer the build dirties.
- Other agents may be building on the same machine. Never run `./gradlew --stop` or kill Gradle/Kotlin daemons you did not start. If you need isolation, use `GRADLE_USER_HOME=<own dir> GRADLE_RO_DEP_CACHE=$HOME/.gradle/caches`.
# Driving the app and device
- Do it yourself with `tools/droiddeckctl` (see `docs/agent-control.md`) instead of asking the user: `cdp eval` for Steam's UI (`SteamClient.Apps.TerminateApp('<appid>', false)` quits a game, including on a Remote Play host), `input`, `quit`, `displays`, `screenshot --display <id>`.
- A stream has started only when the session state reads `Streaming`. `SteamClient.Apps.StreamGame` alone can leave Steam on its menu, so open the game page and press Stream.
- Test controller navigation with `tools/droiddeckctl input gamepad ...`, a real uinput pad. `adb shell input keyevent DPAD_*` does not arrive as a joystick event and hides d-pad/stick bugs.
- A release-signed build installs over a release-signed install with `adb install -r`. Don't back up, uninstall or clear data to update. Scope `pm` and permission resets to `com.droiddeck.launcher`, never the whole device.
# CI
- Before pushing a PR, run `tools/pre_pr.sh`. It checks authorship and the merge onto `main`, then, when app sources change, compiles and runs lint as CI does. It picks tests by name: `<File>*Test` for changed Kotlin files, and `tools/tests` modules that mention a changed path. Add any other tests that cover your change, and leave the full suites to CI.
- CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge.
- Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors.
- Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them.
- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs/<job-id>/logs`, or `gh run download <run> -n unit-test-results`. Don't call a failure a runner problem until you have read it.
- Only these are known flakes worth a `gh run rerun <run> --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real.
- A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`.
# Agents running on the device (DroidDeck's in-app agent)
These apply only where `dd-lab-build` exists. Agents on a dev host use `tools/quick_deploy.sh` instead.
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
+3 -3
View File
@@ -70,7 +70,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source.
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
@@ -91,7 +91,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
<details>
<summary><b>Stores</b></summary>
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send.
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send. Deleted GOG cloud saves are recognised by the empty-gzip deletion hash gogdl and Lutris skip.
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
- The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268).
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
@@ -99,7 +99,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
- The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code.
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. Installed addons show their `.toc` version and `X-WoWI-ID`, and are checked against that list for updates, as [WowUp](https://github.com/WowUp/WowUp) does. The Addons tab installs the official [CurseForge](https://www.curseforge.com/download/app) Linux app from CurseForge's own update feed (downloaded at install time and checked against its SHA-512, not included), which keeps its own sign-in.
- The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
+8 -6
View File
@@ -125,7 +125,8 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
android {
namespace 'com.droiddeck.launcher'
compileSdk 34
ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
ndkVersion project.findProperty('ndkVersion') ?: providers.fileContents(rootProject.layout.projectDirectory.file('tools/ci/toolchains.env'))
.asText.get().readLines().find { it.startsWith('CI_ANDROID_NDK_VERSION=') }.split('=', 2)[1].trim()
defaultConfig {
applicationId "com.droiddeck.launcher"
@@ -232,6 +233,9 @@ android {
}
maxHeapSize = '2g'
maxParallelForks = 2
def jvmTemp = new File(temporaryDir, 'jvm')
systemProperty 'java.io.tmpdir', jvmTemp.absolutePath
doFirst { jvmTemp.mkdirs() }
def logTarget = providers.systemProperty('robolectric.logging').orNull
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
}
@@ -261,11 +265,9 @@ if (vitureSdkDir) {
tasks.named('preBuild').configure { dependsOn(stageVitureNotices) }
}
def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
from(rootProject.file('tools/linuxfs/overlay')) {
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
}
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
def stageSessionScripts = tasks.register('stageSessionScripts', Exec) {
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage'
}
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
@@ -15,6 +15,7 @@ private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Li
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
@DroidDeckPreviews @Composable private fun SteamEmptyPreview() = Launcher("steam", games = emptyList())
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
@@ -61,7 +61,7 @@ internal val sampleActions: FrontEndActions = FrontEndActions(
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> },
onSetPhantomProcessLimit = { _, _ -> },
)
/** The in-game menu's actions with settled sample values; its switches do nothing. */
+1
View File
@@ -232,6 +232,7 @@
android:exported="false"
android:screenOrientation="user"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:windowSoftInputMode="adjustResize"
android:theme="@style/AppTheme" />
<activity
+128 -24
View File
@@ -21,6 +21,7 @@
#define SYS_munmap 215
#define SYS_mmap 222
#define SYS_mprotect 226
#define SYS_getpid 172
#define AT_FDCWD_ (-100)
#define O_RDONLY_ 0
@@ -52,6 +53,21 @@ static size_t slen(const char *s) {
return n;
}
static int seq(const char *a, const char *b) {
while (*a && *a == *b) a++, b++;
return *a == *b;
}
static const char *env_get(char **envp, const char *name) {
size_t n = slen(name);
for (; *envp; envp++) {
size_t i = 0;
while (i < n && (*envp)[i] == name[i]) i++;
if (i == n && (*envp)[n] == '=') return *envp + n + 1;
}
return 0;
}
static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); }
static void out_num(long v) {
@@ -112,19 +128,43 @@ static int prot_of(uint32_t flags) {
static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); }
static void load(const char *path, struct image *im, uintptr_t page) {
static void read_interp(int fd, const Elf64_Phdr *ph, int phnum, char *interp, size_t size, const char *path) {
interp[0] = 0;
for (int i = 0; i < phnum; i++) {
if (ph[i].p_type != PT_INTERP) continue;
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= size) die("bad PT_INTERP", path, 0);
if (xpread(fd, interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
die("truncated PT_INTERP", path, 0);
interp[ph[i].p_filesz] = 0;
}
}
static int read_headers(const char *path, Elf64_Ehdr *eh, Elf64_Phdr *ph) {
int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0);
if (fd < 0) die("cannot open", path, fd);
Elf64_Ehdr eh;
if (xpread(fd, &eh, sizeof(eh), 0) != (long)sizeof(eh)) die("not an ELF file", path, 0);
if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || eh.e_ident[EI_MAG2] != ELFMAG2 ||
eh.e_ident[EI_MAG3] != ELFMAG3 || eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_AARCH64 ||
(eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || eh.e_phentsize != sizeof(Elf64_Phdr) ||
eh.e_phnum == 0 || eh.e_phnum > MAX_PHDRS)
if (xpread(fd, eh, sizeof(*eh), 0) != (long)sizeof(*eh)) die("not an ELF file", path, 0);
if (eh->e_ident[EI_MAG0] != ELFMAG0 || eh->e_ident[EI_MAG1] != ELFMAG1 || eh->e_ident[EI_MAG2] != ELFMAG2 ||
eh->e_ident[EI_MAG3] != ELFMAG3 || eh->e_ident[EI_CLASS] != ELFCLASS64 || eh->e_machine != EM_AARCH64 ||
(eh->e_type != ET_EXEC && eh->e_type != ET_DYN) || eh->e_phentsize != sizeof(Elf64_Phdr) ||
eh->e_phnum == 0 || eh->e_phnum > MAX_PHDRS)
die("not a 64-bit ARM ELF program", path, 0);
long size = (long)eh->e_phnum * (long)sizeof(Elf64_Phdr);
if (xpread(fd, ph, (size_t)size, (long)eh->e_phoff) != size) die("truncated program headers", path, 0);
return fd;
}
static void interp_of(const char *path, char *interp, size_t size) {
Elf64_Ehdr eh;
Elf64_Phdr ph[MAX_PHDRS];
long size = (long)eh.e_phnum * (long)sizeof(Elf64_Phdr);
if (xpread(fd, ph, (size_t)size, (long)eh.e_phoff) != size) die("truncated program headers", path, 0);
int fd = read_headers(path, &eh, ph);
read_interp(fd, ph, eh.e_phnum, interp, size, path);
sys6(SYS_close, fd, 0, 0, 0, 0, 0);
}
static void load(const char *path, struct image *im, uintptr_t page) {
Elf64_Ehdr eh;
Elf64_Phdr ph[MAX_PHDRS];
int fd = read_headers(path, &eh, ph);
uintptr_t lo = UINTPTR_MAX, hi = 0;
for (int i = 0; i < eh.e_phnum; i++) {
@@ -173,16 +213,9 @@ static void load(const char *path, struct image *im, uintptr_t page) {
im->phnum = eh.e_phnum;
im->phent = eh.e_phentsize;
im->phdr = 0;
im->interp[0] = 0;
for (int i = 0; i < eh.e_phnum; i++) {
read_interp(fd, ph, eh.e_phnum, im->interp, sizeof(im->interp), path);
for (int i = 0; i < eh.e_phnum; i++)
if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr;
if (ph[i].p_type == PT_INTERP) {
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= sizeof(im->interp)) die("bad PT_INTERP", path, 0);
if (xpread(fd, im->interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
die("truncated PT_INTERP", path, 0);
im->interp[ph[i].p_filesz] = 0;
}
}
if (!im->phdr) {
for (int i = 0; i < eh.e_phnum; i++) {
Elf64_Phdr *p = &ph[i];
@@ -202,6 +235,36 @@ static unsigned long auxv_get(const uintptr_t *auxv, unsigned long type, unsigne
return fallback;
}
static int is_self_exe(const char *execfn) {
if (!execfn) return 0;
if (seq(execfn, "/proc/self/exe") || seq(execfn, "/proc/thread-self/exe")) return 1;
const char *p = "/proc/";
while (*p && *p == *execfn) p++, execfn++;
if (*p) return 0;
char num[24];
int i = (int)sizeof(num) - 1;
num[i] = 0;
unsigned long pid = (unsigned long)sys6(SYS_getpid, 0, 0, 0, 0, 0, 0);
do {
num[--i] = (char)('0' + pid % 10);
pid /= 10;
} while (pid && i > 0);
const char *d = num + i;
while (*d && *d == *execfn) d++, execfn++;
return !*d && seq(execfn, "/exe");
}
static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) {
const char *root = env_get(envp, "DDNATV_ROOT");
if (!root || interp[0] != '/') return interp;
size_t a = slen(root), b = slen(interp);
if (a + b + 1 > size) return interp;
for (size_t i = 0; i < a; i++) buf[i] = root[i];
for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i];
if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp;
return buf;
}
__attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
long argc = (long)sp[0];
char **argv = (char **)(sp + 1);
@@ -211,25 +274,66 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1);
long naux = 0;
while (auxv[naux * 2] != AT_NULL) naux++;
if (argc < 3) die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0));
const char *path;
char **args = argv + 2;
long nargs = argc - 2;
char interp_buf[4096];
char hook_buf[4096];
if (reexec) {
path = env_get(envp, "DDNATV_REAL_EXE");
if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0);
args = argv;
nargs = argc;
const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH");
char prog_interp[256];
interp_of(path, prog_interp, sizeof(prog_interp));
if (prog_interp[0] && lib_path && lib_path[0]) {
const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf));
const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
long n = argc > 1 ? argc - 1 : 0;
char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *));
long k = 0;
v[k++] = (char *)ld_so;
if (hook == (const char *)hook_buf) {
v[k++] = (char *)"--preload";
v[k++] = (char *)hook;
}
v[k++] = (char *)"--library-path";
v[k++] = (char *)lib_path;
v[k++] = (char *)"--argv0";
v[k++] = argc > 0 ? argv[0] : (char *)path;
v[k++] = (char *)path;
for (long i = 0; i < n; i++) v[k++] = argv[1 + i];
v[k] = 0;
args = v;
nargs = k;
path = ld_so;
}
} else if (argc < 3) {
die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
} else {
path = argv[1];
}
uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096);
const char *path = argv[1];
struct image prog, interp;
load(path, &prog, page);
int has_interp = prog.interp[0] != 0;
if (has_interp) load(prog.interp, &interp, page);
if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page);
// The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one.
// The strings stay where the kernel put them.
static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN};
long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0]));
long new_argc = argc - 2;
long new_argc = nargs;
long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2;
uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp;
uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
uintptr_t *w = nsp;
*w++ = (uintptr_t)new_argc;
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2];
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i];
*w++ = 0;
for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i];
*w++ = 0;
+14 -3
View File
@@ -737,6 +737,11 @@ static void describe(const struct surface *s, char *out, size_t size) {
else snprintf(out, size, "window %#x (%s)", w->hwnd, prog);
}
static int is_steam_client_surface(const struct surface *s) {
const char *name = client_name(wl_resource_get_client(s->resource));
return strcmp(name, "steam") == 0 || strstr(name, "steamwebhelper") != NULL;
}
static struct surface *toplevel_by_hwnd(uint32_t hwnd) {
struct surface *s;
wl_list_for_each(s, &g_toplevels, toplevel_link)
@@ -894,6 +899,7 @@ int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
static uint64_t g_game_frames;
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
extern void droiddeck_on_game_frame(void);
extern void droiddeck_on_compositor_frame(void);
extern void droiddeck_on_content_rate(int fps);
static int64_t g_cadence_ns;
static int64_t g_cadence_frames;
@@ -949,9 +955,10 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
g_hud_shm = s;
g_hud_shm_ns = now;
g_hud_new = 1;
droiddeck_on_game_frame();
}
}
if (s == g_hud_shm && (!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL))
droiddeck_on_compositor_frame();
}
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
@@ -1025,7 +1032,8 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
droiddeck_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)",
name, b->width, b->height, (unsigned long long)b->modifier);
}
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
if (s != g_hud_surface && !is_steam_client_surface(s) &&
(b->img || ahb_swapchain_has_ahb(b)) &&
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) ||
(announced_now && !below_surface(g_hud_surface, s) &&
(int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
@@ -1050,9 +1058,12 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
: "the compositor's driver could NOT import it (nothing can show it)");
s->hdr_fmt_logged = b->format;
}
if (s == g_hud_surface) {
if (s == g_hud_surface && !is_steam_client_surface(s)) {
g_hud_alive_ns = now_ns();
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; note_game_frame_gap(); droiddeck_on_game_frame(); }
} else if (is_steam_client_surface(s) && !repeat &&
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL)) {
droiddeck_on_compositor_frame();
}
}
+6 -2
View File
@@ -518,6 +518,10 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
img = vkp_image_import_dmabuf(nh->data[0], fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888, mod, w, h,
got.stride * 4, 0, 1);
path = "dma-buf (QTI handle)";
if (!img && mod == MOD_LINEAR && vkp_can_import_ahb()) {
img = vkp_image_import_ahb(ahb, info, sizeof(info));
if (img) { mod = SC_MOD_GRALLOC; path = "AHardwareBuffer"; }
}
} else {
if (tier == TIER_UBWC) {
char hd[256];
@@ -941,7 +945,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return 0; }
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, r, color, 0) != 0) return -1;
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8);
@@ -1150,7 +1154,7 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl
if (sw <= 0 || sh <= 0) return -1;
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return 0; }
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
if (!l->first_logged) {
@@ -24,6 +24,12 @@ static inline uint32_t vkp_linear_dmabuf_texel_bytes(VkFormat fmt) {
return fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? 8u : 4u;
}
static inline int vkp_padded_linear_target_needs_layout(int drm_modifiers, uint64_t modifier, VkFormat fmt,
int w, uint32_t stride, uint32_t offset) {
return !drm_modifiers && modifier == 0 &&
(offset != 0 || (uint64_t)stride != (uint64_t)w * vkp_linear_dmabuf_texel_bytes(fmt));
}
static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, uint32_t stride, uint32_t offset,
VkBufferImageCopy *copy) {
const uint32_t texel = vkp_linear_dmabuf_texel_bytes(fmt);
@@ -39,11 +45,11 @@ static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, ui
}
static inline VkBufferMemoryBarrier vkp_linear_dmabuf_ownership(VkBuffer buffer, uint32_t queue_family,
int acquire) {
VkAccessFlags access, int acquire) {
return (VkBufferMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
.srcAccessMask = acquire ? 0 : VK_ACCESS_TRANSFER_READ_BIT,
.dstAccessMask = acquire ? VK_ACCESS_TRANSFER_READ_BIT : 0,
.srcAccessMask = acquire ? 0 : access,
.dstAccessMask = acquire ? access : 0,
.srcQueueFamilyIndex = acquire ? VK_QUEUE_FAMILY_FOREIGN_EXT : queue_family,
.dstQueueFamilyIndex = acquire ? queue_family : VK_QUEUE_FAMILY_FOREIGN_EXT,
.buffer = buffer,
+1 -1
View File
@@ -22,7 +22,7 @@
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) X(CmdCopyImageToBuffer) \
X(CreateBuffer) X(DestroyBuffer) X(GetBufferMemoryRequirements) X(BindBufferMemory) \
X(CmdCopyBufferToImage) \
\
+72 -49
View File
@@ -1123,7 +1123,7 @@ static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_
static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img) {
if (!img || !img->linear_buf) return;
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, 1);
VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 1);
VkImageMemoryBarrier write = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -1132,7 +1132,7 @@ static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
0, NULL, 1, &acquire, 1, &write);
g_vk.CmdCopyBufferToImage(cmd, img->linear_buf, img->image, VK_IMAGE_LAYOUT_GENERAL, 1, &img->linear_copy);
VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, 0);
VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 0);
VkImageMemoryBarrier read = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -1259,7 +1259,8 @@ static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferIma
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
VkBufferCreateInfo bci = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = &ext, .size = size,
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE};
.usage = img->blit_dst ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE};
VkResult r = g_vk.CreateBuffer(g_dev, &bci, NULL, &img->linear_buf);
if (r != VK_SUCCESS) goto fail;
uint32_t allowed = 0xffffffff;
@@ -1312,8 +1313,8 @@ static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferIma
img->in_general = 1;
return 0;
fail:
LOGE("dmabuf: reading the linear %dx%d buffer at its row pitch failed (%s); importing it as an image",
img->w, img->h, vk_result_name(r));
LOGE("dmabuf: %s the linear %dx%d buffer at its row pitch failed (%s)",
img->blit_dst ? "writing" : "reading", img->w, img->h, vk_result_name(r));
if (dupfd >= 0) close(dupfd);
destroy_image_objects(img);
return -1;
@@ -1324,15 +1325,20 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
if (dev_init() != 0) return NULL;
const VkFormat format = drm_to_vk(drm_format);
const int padded_target = as_blit_dst &&
vkp_padded_linear_target_needs_layout(g_drm_modifiers, modifier, format, w, stride, offset);
if (padded_target && !g_vk.CmdCopyImageToBuffer) return NULL;
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0;
img->fmt = drm_to_vk(drm_format);
const int through_buffer = vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst);
img->fmt = format;
const int through_buffer = padded_target || vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst);
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
const int modifier_sampled = !as_blit_dst && g_drm_modifiers && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
modifier_importable(img->fmt, modifier, sampled_usage);
img->sampled = through_buffer ? optimal_sampled(img->fmt) : modifier_sampled;
img->sampled = !as_blit_dst && (through_buffer ? optimal_sampled(img->fmt) : modifier_sampled);
/* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
* or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
{
@@ -1358,7 +1364,12 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
if (through_buffer) {
VkBufferImageCopy linear_copy;
const VkDeviceSize linear_size = vkp_linear_dmabuf_copy(img->fmt, w, h, stride, offset, &linear_copy);
if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) return img;
if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) {
if (padded_target) droiddeck_log("gpu", "linear layer target %dx%d writes at pitch %u via DMA-BUF",
w, h, stride);
return img;
}
if (padded_target) { free(img); return NULL; }
img->sampled = modifier_sampled;
}
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
@@ -2522,6 +2533,48 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
return 1;
}
static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_layout, struct vkp_image *dst,
const VkImageBlit *blit, VkFilter filter) {
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
const VkImageMemoryBarrier acquire = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &acquire);
g_vk.CmdBlitImage(cmd, src, src_layout, dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
if (dst->staged) {
const VkImageMemoryBarrier read = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = dst->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &read);
const VkBufferMemoryBarrier write = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 1);
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 1, &write, 0, NULL);
VkBufferImageCopy copy = dst->linear_copy;
copy.imageExtent.width = (uint32_t)blit->dstOffsets[1].x;
copy.imageExtent.height = (uint32_t)blit->dstOffsets[1].y;
g_vk.CmdCopyImageToBuffer(cmd, dst->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->linear_buf, 1, &copy);
const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 0);
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 1, &release, 0, NULL);
return;
}
const VkImageMemoryBarrier release = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &release);
}
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
@@ -2540,41 +2593,28 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 2, acq);
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
g_vk.CmdBlitImage(g_cmd, src->image,
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &rel);
g_vk.EndCommandBuffer(g_cmd);
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
@@ -2890,31 +2930,14 @@ static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp
}
const int gpu_wait = take_wait_fd(wait_fd);
if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; }
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
for (int i = 0; i < n; i++) {
struct vkp_image *dst = dsts[i];
VkImageMemoryBarrier acq = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range,
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &acq);
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}};
g_vk.CmdBlitImage(cmd, srcs[i], src_layout, dst->image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
(g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &rel);
blit_to_layer(cmd, srcs[i], src_layout, dst, &blit,
(g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
}
g_vk.EndCommandBuffer(cmd);
@@ -63,6 +63,7 @@ static jclass g_compositor_cls;
static jmethodID g_on_first_frame;
static jmethodID g_on_game_surface;
static jmethodID g_on_game_frame;
static jmethodID g_on_compositor_frame;
static jmethodID g_on_game_program;
static jmethodID g_on_pointer_lock;
static jmethodID g_on_clipboard;
@@ -84,6 +85,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
g_on_game_surface = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameSurface",
"(Ljava/lang/String;Ljava/lang/String;)V");
g_on_game_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameFrame", "()V");
g_on_compositor_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onCompositorFrame", "()V");
g_on_game_program = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameProgram",
"(ILjava/lang/String;)V");
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; }
@@ -154,6 +156,13 @@ void droiddeck_on_game_frame(void) {
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
}
void droiddeck_on_compositor_frame(void) {
JNIEnv *env;
if (!g_compositor_cls || !g_on_compositor_frame || !(env = thread_env())) return;
(*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_compositor_frame);
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
}
void droiddeck_on_refresh_target(int refresh, int frame_rate) {
JNIEnv *env;
if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return;
@@ -21,6 +21,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
@@ -46,6 +47,7 @@ class App : Application() {
com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this)
com.droiddeck.launcher.agent.AgentHost.refresh(this)
com.droiddeck.launcher.ui.NavTabs.load(this)
com.droiddeck.launcher.ui.DrawerPages.load(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
checkAgain = null
checkComponentUpdates(again)
}
if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; "))
refreshComponents()
}
}, "component-updates").start()
@@ -6,6 +6,7 @@ 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.runtime.DeckyStore
import com.droiddeck.launcher.session.SessionState
import java.io.File
@@ -21,6 +22,59 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
var deckySupervisor by mutableStateOf(false)
var deckyPendingZip by mutableStateOf<File?>(null)
var deckyReleaseRequest = 0
var deckyPlugins by mutableStateOf<List<DeckyStore.Installed>>(emptyList())
var deckyStore by mutableStateOf<List<DeckyStore.Plugin>?>(null)
var deckyStoreFailed by mutableStateOf(false)
private var storeRequest = 0
fun refreshPlugins() {
Thread({
val found = DeckyStore.installed(activity)
ui.post { deckyPlugins = found }
}, "decky-plugins").start()
}
fun refreshStore() {
val request = ++storeRequest
deckyStore = null; deckyStoreFailed = false
Thread({
val listing = DeckyStore.fetch()
ui.post {
if (request != storeRequest) return@post
deckyStore = listing.orEmpty(); deckyStoreFailed = listing == null
}
}, "decky-store").start()
}
fun installStorePlugin(plugin: DeckyStore.Plugin) {
val version = plugin.latest ?: return
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1
Thread({
val problem = runCatching {
DeckyStore.install(activity, plugin, version) { label, value ->
val binary = DeckyManager.downloadingBinary
ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary }
}
}.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) }
ui.post {
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.decky_plugin_installed), android.widget.Toast.LENGTH_LONG).show()
refreshPlugins()
}
}, "install-decky-store").start()
}
fun removePlugin(plugin: DeckyStore.Installed) {
if (deckyStage != null || SessionState.running) return
Thread({
val problem = DeckyStore.remove(activity, plugin)
ui.post {
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
refreshPlugins()
}
}, "remove-decky-plugin").start()
}
fun refreshDecky() {
val request = ++deckyReleaseRequest
@@ -90,6 +144,7 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
val message = problem ?: activity.getString(R.string.decky_plugin_installed)
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
refreshPlugins()
}
}, "import-decky-plugin").start()
}
@@ -17,8 +17,11 @@ import android.os.Looper
import android.util.Log
import android.view.Display
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import android.widget.EditText
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
@@ -184,7 +187,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(false)
private var nativeUserland by mutableStateOf(true)
private var cursorComposite by mutableStateOf(false)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
@@ -199,6 +202,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM)
private var launcherFullscreen by mutableStateOf(true)
private var controllerHaptics by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
private var downloadPrefix by mutableStateOf("")
@@ -250,6 +254,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
refreshWifiDiscovery()
}
private val bluetoothPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (!granted && !shouldShowRequestPermissionRationale(android.Manifest.permission.BLUETOOTH_CONNECT)) {
integrationSettings(SteamIntegration.appInfo(this))
}
integrationState = readIntegration()
}
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
com.droiddeck.launcher.handtracking.HandTracking.refreshPermission(this)
}
@@ -371,6 +381,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SteamIntegration.Feature.SHORTCUTS -> {
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
}
SteamIntegration.Feature.BLUETOOTH -> {
if (SteamIntegration.bluetoothAllowed(this)) integrationSettings(SteamIntegration.appInfo(this))
else bluetoothPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT)
}
}
}
@@ -529,7 +543,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
saveAction(getString(R.string.main_addons_importing, name)) {
if (SessionState.running) return@saveAction getString(R.string.main_addons_close_session)
val imported = try {
com.droiddeck.launcher.runtime.WowAddons.import(zip, target)
com.droiddeck.launcher.runtime.WowAddons.import(zip, target, context = this@FrontEndActivity)
} catch (_: com.droiddeck.launcher.runtime.WowAddons.TooLarge) {
return@saveAction getString(R.string.main_addons_too_large, zip.name)
}
@@ -538,7 +552,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
val downloads = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_addons_pick_zip, name), downloads))
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip", "rar", "7z"), getString(R.string.main_addons_pick_zip, name), downloads))
}
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
@@ -585,6 +599,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
private var settingsMode by mutableStateOf<String?>(null)
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
private var resolutionPortrait by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE)
private var fexPreset by mutableStateOf("")
private var forceSsbs by mutableStateOf(false)
private var steamClientArch by mutableStateOf("arm64")
@@ -622,6 +637,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
private var storageDiagnostics by mutableStateOf(false)
private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList())
private var storageFat32 by mutableStateOf(false)
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
}
@@ -637,6 +653,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun addSteamLibrary(path: String) {
Thread({
val result = SteamLibraries.add(this, path)
val fat32 = result is SteamLibraries.AddResult.Added && GameStorage.isFat32(result.entry.path)
ui.post {
steamLibraries = SteamLibraries.list(this)
refreshFoundSteamLibraries()
@@ -647,6 +664,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
result is SteamLibraries.AddResult.Added && result.entry.path != path ->
android.widget.Toast.makeText(this, getString(R.string.libraries_used_inner, result.entry.label), android.widget.Toast.LENGTH_LONG).show()
}
if (fat32) android.widget.Toast.makeText(this, R.string.main_storage_fat32, android.widget.Toast.LENGTH_LONG).show()
}
}, "steam-library-add").start()
}
@@ -702,6 +720,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
private var ownScreen by mutableStateOf<SecondScreenDisplay?>(null)
private var dualDisplayId by mutableStateOf(-1)
private var dualScreenDevice by mutableStateOf(false)
private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
@@ -904,19 +923,31 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
LauncherIcon.set(this, style)
launcherIcon = LauncherIcon.current(this)
if (launcherIcon == before) return false
restartLauncher()
return true
}
// recreate() leaves this activity's window drawing nothing and ignoring input on some devices (#2668).
private fun restartLauncher() {
LauncherHandoff.put(Bundle().also(::saveLauncherState))
switchPoll?.let { ui.removeCallbacks(it) }
switchPoll = null
switchingTo = null
queuedLaunch.clear()
cancelCompatLaunch()
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(LauncherIcon.activity(this))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher"))
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher")
.putExtra(EXTRA_RESTARTED, true))
finishAndRemoveTask()
return true
}
private fun readGameIntent(request: Intent) {
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
request.data?.takeIf { it.scheme == "droiddeck" && it.host == "settings" }?.let { uri ->
val section = uri.pathSegments.firstOrNull()
navRequest = if (section in setOf("storage", "sync", "downloads")) section
navRequest = if (section in setOf("storage", "sync", "downloads", "decky", "boot-movies")) section
else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key
request.data = null
gameLinkReading = false
@@ -1238,9 +1269,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
super.onCreate(savedInstanceState)
drivers.restartBlocked = ::runtimeChangesBlocked
drivers.loadTpUbwcMode()
pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
val handoff = if (savedInstanceState == null && intent.getBooleanExtra(EXTRA_RESTARTED, false)) LauncherHandoff.take() else null
val saved = savedInstanceState ?: handoff
pendingSessionLogExport = saved?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
queuedLaunch.restore(
saved?.let { androidx.core.os.BundleCompat.getParcelable(it, STATE_PENDING_GATE_LAUNCH, Intent::class.java) },
saved?.getLong(STATE_PENDING_GATE_LAUNCH_AT, 0L) ?: 0L, System.currentTimeMillis(),
)
homeChoiceOpen = saved?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
gameSpaceOffered = saved?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
if (savedInstanceState == null) readIntegrationIntent(intent)
val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS)
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED)
@@ -1264,6 +1301,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
requestedOrientation = launcherOrientation
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
controllerHaptics = SessionPrefs.controllerHaptics(this)
downloadSource = DownloadSource.mode(this)
downloadMirror = DownloadSource.mirror(this)
downloadPrefix = DownloadSource.custom(this)
@@ -1339,6 +1377,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
integrationFocus = integrationFocus,
androidApps = androidApps,
secondScreenDisplays = secondScreenDisplays,
ownScreen = ownScreen,
dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
dualScreenDevice = dualScreenDevice,
dualScreenMode = dualScreenMode,
@@ -1363,6 +1402,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherOrientation = launcherOrientation,
homePage = homePage,
launcherFullscreen = launcherFullscreen,
controllerHaptics = controllerHaptics,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
downloadPrefix = downloadPrefix,
@@ -1385,6 +1425,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
),
FrontEndActions(
onPlay = { playSteam() },
onQueuePlaySteam = {
queuedLaunch.queue(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, false), System.currentTimeMillis())
},
onPlaySteamVr = { playSteamVr() },
onSteamUrl = { url ->
if (!SessionState.running) startSession(
@@ -1524,7 +1567,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onAddonImport = { sg, target -> importAddons(sg.name, target) },
onAddonDelete = { target, name ->
saveAction(getString(R.string.main_addons_deleting, name)) {
com.droiddeck.launcher.runtime.WowAddons.delete(target, name)
com.droiddeck.launcher.ui.deleteAddon(this, target, name)
getString(R.string.main_addons_deleted, name)
}
},
@@ -1659,7 +1702,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onLanguage = { tag ->
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) {
com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag)
recreate()
restartLauncher()
}
},
onAppScale = { percent ->
@@ -1679,6 +1722,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value)
homePage = value
},
onControllerHaptics = { on -> SessionPrefs.setControllerHaptics(this, on); controllerHaptics = on },
onLauncherFullscreen = { on ->
SessionPrefs.setLauncherFullscreen(this, on)
launcherFullscreen = on
@@ -1755,31 +1799,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
},
onRefreshPhantomStatus = { refreshPhantomStatus() },
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) },
onWirelessAdbPair = { host, port, code, complete ->
Thread({
val result = runCatching {
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@FrontEndActivity, host, port, code) }
}
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_pair_failed) }
ui.post { complete(error) }
}, "wireless-adb-pair").start()
},
onFindWirelessAdbPort = { host, complete ->
Thread({
val port = WirelessAdbFix.findConnectPort(this@FrontEndActivity, host)
ui.post { complete(port) }
}, "wireless-adb-discovery").start()
},
onWirelessAdbApply = { host, port, enabled, complete ->
Thread({
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@FrontEndActivity, host, port, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_command_failed) }
ui.post {
if (error == null) refreshPhantomStatus()
complete(error)
}
}, "wireless-adb-fix").start()
},
onSetPhantomProcessLimit = { enabled, complete ->
Thread({
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@FrontEndActivity, enabled) }
@@ -1796,18 +1815,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
)
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
},
onDismissPhantomGate = { showPhantomGate = false },
onDismissPhantomGate = { queuedLaunch.clear(); showPhantomGate = false },
onShowPhantomGate = {
refreshPhantomStatus()
showPhantomGate = true
},
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
onStartWirelessAdbPairing = { enabled -> WirelessAdbPairingService.start(this, enabled) },
onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) },
onOpenNotificationSettings = {
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
},
onEnsureNotifications = { done -> ensureNotifications(done) },
updates = updates.actions(),
controller = ControllerActions(
onMapping = { showPerformance = false; showComponents = false; showMapping = true },
@@ -1903,10 +1918,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
!SessionPrefs.allFilesAsked(this)
if (savedInstanceState == null) {
if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) }
} else {
restoreCompatLaunch(savedInstanceState)
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
}
saved?.let { state ->
restoreCompatLaunch(state)
pendingSwitch = savedIntent(state, KEY_PENDING_SWITCH)
savedIntent(state, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, state.getLong(KEY_SWITCH_DEADLINE)) }
}
val wanted = ArrayList<String>()
@@ -1959,8 +1975,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var soundtrackLaunch = false
// A restarted launcher starts before the old one stops, so each clears the hooks only if they are still its own.
private val libraryHook: () -> Unit = { refreshAddedGames(); refresh() }
private val battleNetHook: (List<String>) -> Unit = { args -> openBattleNet(args) }
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
if (soundtrackLaunch) return
if (soundtrackLaunch || intent.getBooleanExtra(EXTRA_RESTARTED, false)) return
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
if (isFinishing || isDestroyed) return
when (SessionPrefs.startupSession(this)) {
@@ -1987,7 +2007,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
private fun startSteamSession(steamVr: Boolean = false) {
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true)
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true, queueIfBlocked = !steamVr)
}
@Suppress("OVERRIDE_DEPRECATION")
@@ -2008,6 +2028,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) triggerKeys.cancel()
if (hasFocus) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
applyLauncherFullscreen()
@@ -2037,6 +2058,36 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private var touchDownX = 0f
private var touchDownY = 0f
private var touchDragged = false
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
com.droiddeck.launcher.ui.ScreenTaps.count++
touchDownX = event.rawX
touchDownY = event.rawY
touchDragged = false
}
// A drag that wanders back to where it began is still a drag, not a tap.
MotionEvent.ACTION_MOVE -> if (!touchDragged &&
kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > ViewConfiguration.get(this).scaledTouchSlop
) touchDragged = true
MotionEvent.ACTION_CANCEL -> touchDragged = true
}
val handled = super.dispatchTouchEvent(event)
if (event.actionMasked == MotionEvent.ACTION_UP) leaveTextFieldOnOutsideTap(event)
return handled
}
private fun leaveTextFieldOnOutsideTap(event: MotionEvent) {
val field = currentFocus as? EditText ?: return
val slop = ViewConfiguration.get(this).scaledTouchSlop
if (touchDragged || kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > slop) return
com.droiddeck.launcher.ui.releaseTextField(field, IntArray(2).also(field::getLocationOnScreen), event.rawX, event.rawY)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
if (compatLaunch != null) {
@@ -2047,6 +2098,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
}
if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true
val tabStep = com.droiddeck.launcher.ui.dualPageStep(event)
val tabs = com.droiddeck.launcher.ui.MainTabSteps.handler
if (tabStep != null && tabs != null) {
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep)
return true
}
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
@@ -2063,9 +2123,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) }
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
if (compatLaunch != null && !compatLaunch!!.loading.ended &&
com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
triggerKeys.onMotion(event)
return super.dispatchGenericMotionEvent(event)
}
@@ -2092,8 +2155,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
refreshWifiDiscovery()
com.droiddeck.launcher.stores.StoresState.refresh(this)
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) }
com.droiddeck.launcher.stores.StoresState.libraryListener = libraryHook
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = battleNetHook
com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
@@ -2115,9 +2178,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!OfflineMode.enabled(this)) {
val updated = runCatching { ComponentUpdater.ensure(this, force = false) }
.onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList())
if (updated.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
}
if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; "))
}
ui.post {
componentsQueueBusy = false
@@ -2166,9 +2227,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
saveLauncherState(outState)
}
private fun saveLauncherState(outState: Bundle) {
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
queuedLaunch.launch?.let {
outState.putParcelable(STATE_PENDING_GATE_LAUNCH, it)
outState.putLong(STATE_PENDING_GATE_LAUNCH_AT, queuedLaunch.queuedAt)
}
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
@@ -2195,6 +2264,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
override fun onDestroy() {
// The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too.
queuedLaunchRunner.destroy()
triggerKeys.cancel()
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
@@ -2215,8 +2287,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
HomeWidgets.stopListening(this)
ui.removeCallbacks(mediaRefresh)
com.droiddeck.launcher.stores.StoresState.libraryListener = null
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
if (com.droiddeck.launcher.stores.StoresState.libraryListener === libraryHook) com.droiddeck.launcher.stores.StoresState.libraryListener = null
if (com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener === battleNetHook) com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener)
@@ -2256,6 +2328,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId
dualScreenMode = SessionPrefs.dualScreenMode(this)
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
ownScreen = ownDisplayId.takeIf { it != Display.DEFAULT_DISPLAY }?.let { id ->
displayManager.getDisplay(id)?.takeIf { it.isValid }?.let { SecondScreenDisplay(id, "${it.name} · ${it.mode.physicalWidth}×${it.mode.physicalHeight}") }
}
dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
dualScreenSessions = SessionPrefs.dualScreenSessionMode(this)
dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
@@ -2276,17 +2351,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
try {
HomeApp.launch(this, app, displayId)
} catch (_: Exception) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
val message = when {
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
val open = {
try {
HomeApp.launch(this, app, displayId)
} catch (_: Exception) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
val message = when {
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
}
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
}
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
}
if (displayId != null && displayId == com.droiddeck.launcher.ui.DualScreenPanel.shownOn) {
com.droiddeck.launcher.ui.DualScreenPanel.makeRoomForApp(this, displayId, open)
} else {
open()
}
}
@@ -2588,7 +2670,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (settingsMode != mode) return
com.droiddeck.launcher.ui.ModeSheetRows(
ModeSettings(
mode = mode, resolution = resolution,
mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
@@ -2612,6 +2694,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
mic = if (mode == SessionService.MODE_STEAM) mic else null,
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
storageOptions = storageOptions,
storageFat32 = storageFat32,
steamLibraries = steamLibraries,
foundSteamLibraries = foundSteamLibraries,
allFilesAccessMissing = allFilesAccessMissing,
@@ -2638,12 +2721,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
deckyDownloadingBinary = decky.deckyDownloadingBinary,
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
deckyPlugins = decky.deckyPlugins, deckyStore = decky.deckyStore, deckyStoreFailed = decky.deckyStoreFailed,
),
ModeSettingsActions(
onIntegration = ::configureIntegration,
onIntegrationAppInfo = ::openAppInfo,
onIntegrationLocation = ::openWifiDiscoverySettings,
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); loadResolutions(mode) },
onResolutionPortrait = { value -> SessionPrefs.setResolutionChoice(this, mode, value, portrait = true); loadResolutions(mode) },
onHdr = { on -> com.droiddeck.launcher.session.SessionHdr.set(this, mode, on); hdrOn = on },
onZeroCopy = { on ->
SessionPrefs.setZeroCopy(this, mode, on); zeroCopyOn = on
@@ -2747,6 +2832,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
decky.deckyInstalled = null
decky.deckySupervisor = false
},
onDeckyStoreRefresh = { decky.refreshStore() },
onDeckyStoreInstall = { plugin -> decky.installStorePlugin(plugin) },
onDeckyRemove = { plugin -> decky.removePlugin(plugin) },
onPickDeckyPluginZip = {
pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip)))
},
@@ -2976,11 +3064,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}, "shader-precache").start()
}
private fun loadResolutions(mode: String) {
val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this)
resolution = SessionPrefs.resolutionStored(this, mode, panel, false)
resolutionPortrait = SessionPrefs.resolutionStored(this, mode, panel, true)
}
private fun loadModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
loadResolutions(mode)
fexPreset = SessionPrefs.fexPreset(this)
forceSsbs = SessionPrefs.forceSsbs(this)
fastSync = SessionPrefs.fastSync(this)
@@ -3023,14 +3117,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
Thread({
drivers.refreshDrivers()
val storage = GameStorage.options(this)
val fat32 = GameStorage.effective(this)?.path?.let(GameStorage::isFat32) == true
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this)
ui.post {
storageOptions = storage
storageFat32 = fat32
if (mode == SessionService.MODE_STEAM) {
decky.deckyInstalled = deckyInstalled
decky.deckySupervisor = deckySupervisor
decky.refreshDecky()
decky.refreshPlugins()
}
fetchAddedGameArt()
}
@@ -3047,6 +3144,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
SessionPrefs.setGameStorage(this, path, label)
gameStorage = path
storageFat32 = GameStorage.effective(this)?.path?.let(GameStorage::isFat32) == true
if (storageFat32) android.widget.Toast.makeText(this, R.string.main_storage_fat32, android.widget.Toast.LENGTH_LONG).show()
checkUsbLink()
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
}
@@ -3145,6 +3244,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
ui.post { autoUpdateRuntime() }
Thread({ com.droiddeck.launcher.session.Onboarding.recheck(this) }, "onboarding-recheck").start()
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
@@ -3270,7 +3370,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
install(release)
}
private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean {
private fun startSession(intent: Intent, steamSession: Boolean = false, queueIfBlocked: Boolean = false): Boolean {
if (busy || LinuxRuntimeInstaller.isBusy()) return false
if (SessionState.installing != null && !SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
@@ -3282,6 +3382,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
refreshPhantomStatus()
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis())
showPhantomGate = true
return false
}
@@ -3291,8 +3392,64 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
return true
}
private var notificationsDone: ((Boolean) -> Unit)? = null
private fun ensureNotifications(done: (Boolean) -> Unit) {
if (WirelessAdbPairingService.notificationsEnabled(this)) {
done(true)
return
}
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
notificationsDone = done
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATIONS)
return
}
openNotificationSettings()
done(false)
}
private fun openNotificationSettings() {
android.widget.Toast.makeText(this, R.string.gate_notifications_toast, android.widget.Toast.LENGTH_LONG).show()
val appAllowed = getSystemService(android.app.NotificationManager::class.java)?.areNotificationsEnabled() != false
val intent = if (appAllowed && WirelessAdbPairingService.channelBlocked(this)) {
Intent(android.provider.Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_CHANNEL_ID, WirelessAdbPairingService.channelId())
} else {
Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
}
startActivity(intent.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != REQUEST_NOTIFICATIONS) return
val done = notificationsDone ?: return
notificationsDone = null
val granted = WirelessAdbPairingService.notificationsEnabled(this)
if (!granted) openNotificationSettings()
done(granted)
}
private val queuedLaunch = com.droiddeck.launcher.session.QueuedLaunch<Intent>(GATE_LAUNCH_MS)
private val queuedLaunchRunner = com.droiddeck.launcher.session.QueuedLaunchRunner(
queue = queuedLaunch,
now = System::currentTimeMillis,
blocked = { PhantomProcessLimit.blocksSteam(phantomProcessStatus) },
busy = ::steamStartBusy,
schedule = { delay, task -> if (delay <= 0L) ui.post(task) else ui.postDelayed(task, delay) },
unschedule = ui::removeCallbacks,
start = { launch -> startSession(launch, steamSession = true, queueIfBlocked = true) },
retryMs = GATE_LAUNCH_RETRY_MS,
)
/** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, or a storage cleanup. */
private fun steamStartBusy(): Boolean = busy || LinuxRuntimeInstaller.isBusy() || com.droiddeck.launcher.session.Onboarding.settling() ||
(SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning
private fun refreshPhantomStatus() {
phantomProcessStatus = PhantomProcessLimit.read(this)
if (queuedLaunch.launch != null && !PhantomProcessLimit.blocksSteam(phantomProcessStatus)) showPhantomGate = false
queuedLaunchRunner.poke()
adbPaired = WirelessAdbFix.hasSavedPairing(this)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
getString(
@@ -3304,7 +3461,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun openDeveloperOptions(displayId: Int?) {
val highlight = if (PhantomProcessLimit.hasDeveloperToggle() &&
WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) null else "toggle_adb_wireless"
WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) "disable_phantom_process_monitor" else "toggle_adb_wireless"
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) }
@@ -3343,13 +3500,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
Thread({
val ok = com.droiddeck.launcher.session.SettingsReset.resetAll(this, gameProfiles, scopes)
ui.post {
com.droiddeck.launcher.ui.DrawerPages.load(applicationContext)
if (isDestroyed) return@post
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.NavTabs.load(this)
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
if (!switchLauncherIcon(LauncherIcon.DARK)) restartLauncher()
}
}, "reset-settings").start()
}
@@ -3365,18 +3523,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun install(release: LinuxRuntimeInstaller.Release) {
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
}
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
private fun followRuntimeOperation(onboarding: Boolean = false, run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
busy = true
failed = false
stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
percent = -1
Thread({
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
if (onboarding) com.droiddeck.launcher.session.Onboarding.report(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, s, p)
ui.post { stage = s; percent = p }
})
if (onboarding) {
if (ok == false) com.droiddeck.launcher.session.Onboarding.fail(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, LinuxRuntimeInstaller.removalError() ?: "")
else com.droiddeck.launcher.session.Onboarding.finish(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME)
}
com.droiddeck.launcher.session.Onboarding.recheck(this)
ui.post {
busy = false
if (ok != null) failed = !ok
@@ -3385,7 +3549,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
refresh()
com.droiddeck.launcher.agent.AgentHost.refresh(this)
if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates()
if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() }
}
}, "runtime-operation").start()
}
@@ -3396,9 +3560,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this)
if (release.version == installed) return
if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) ||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.unfavourable(this))) return
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(this))) return
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself")
if (installed == null) protons.prefetchOwn()
install(release)
}
}
@@ -3415,7 +3580,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
companion object {
private const val REQUEST_NOTIFICATIONS = 7103
private const val EXTRA_RESTARTED = "com.droiddeck.launcher.extra.RESTARTED"
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
private const val STATE_PENDING_GATE_LAUNCH = "pending_gate_launch"
private const val STATE_PENDING_GATE_LAUNCH_AT = "pending_gate_launch_at"
private const val GATE_LAUNCH_MS = 15 * 60_000L
private const val GATE_LAUNCH_RETRY_MS = 2_000L
private const val KEY_PENDING_SESSION_LOG_EXPORT = "pending_session_log_export"
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
private const val TAG = "MainActivity"
@@ -118,12 +118,18 @@ object HomeWidgets {
if (live.size != parsed.size) save(context)
}
private val listeners: MutableSet<Any> = java.util.Collections.newSetFromMap(java.util.IdentityHashMap())
fun startListening(context: Context) {
listeners.add(context)
load(context)
runCatching { host(context).startListening() }
}
// A restarted launcher starts before the old one stops; the host keeps listening until the last owner stops.
fun stopListening(context: Context) {
listeners.remove(context)
if (listeners.isNotEmpty()) return
runCatching { host(context).stopListening() }
}
@@ -0,0 +1,27 @@
package com.droiddeck.launcher
import android.os.Bundle
import android.os.SystemClock
/**
* State a restarting launcher passes to its replacement inside this process. Intent extras are not used
* because FrontEndActivity is exported and any app could fill them.
*/
internal object LauncherHandoff {
private const val LIFETIME_MS = 10_000L
private var state: Bundle? = null
private var at = 0L
@Synchronized
fun put(carried: Bundle) {
state = carried
at = SystemClock.elapsedRealtime()
}
@Synchronized
fun take(): Bundle? {
val carried = state
state = null
return carried?.takeIf { SystemClock.elapsedRealtime() - at <= LIFETIME_MS }
}
}
@@ -93,6 +93,14 @@ class PairingGuideActivity : ComponentActivity() {
launchPending = true
}
override fun onDestroy() {
super.onDestroy()
val stage = WirelessAdbPairingService.stage.value
if (isFinishing && (stage is WirelessAdbPairingService.Stage.Waiting || stage is WirelessAdbPairingService.Stage.CodeNeeded)) {
WirelessAdbPairingService.cancel(this)
}
}
override fun onResume() {
super.onResume()
if (!launchPending) return
@@ -8,7 +8,9 @@ import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.Onboarding
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.SteamClientPrefetch
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SessionPhase
@@ -60,10 +62,15 @@ internal class ProtonMenu(
Thread({
val problem = runCatching {
installer(tool) { label, value ->
if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value)
ui.post { protonStage = label; protonPercent = value }
}
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
if (tool.id == ProtonExtras.OWN) {
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
}
ui.post {
protonProblem = problem
protonBusyId = null
@@ -170,16 +177,46 @@ internal class ProtonMenu(
Operation.checking.set(false)
}
ensureAutoUpdates()
ensureSteamClient()
}
if (!published) Operation.checking.set(false)
}, "proton-updates").start()
}
/** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */
fun prefetchOwn() {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() ||
ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return
Thread({
val problem = runCatching {
ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) }
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
ui.post { ensureAutoUpdates() }
}, "proton-prefetch").start()
}
/** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */
fun ensureSteamClient() {
if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) ||
!AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return
SteamClientPrefetch.start(
activity,
{ mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) },
activity.getString(R.string.onboarding_steam_failed),
)
}
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return
val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty()
if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
protonBusyId = ProtonExtras.OWN
protonProblem = null
@@ -154,6 +154,8 @@ import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.LatestRequestCoordinator
import com.droiddeck.launcher.ui.SessionDrawerPage
import com.droiddeck.launcher.ui.sessionDrawerPages
import com.droiddeck.launcher.ui.strip
import com.droiddeck.launcher.ui.tabFor
import com.droiddeck.launcher.ui.step
import kotlin.math.abs
@@ -244,9 +246,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun key(code: Int, down: Boolean) { heldKeys.set(4, code, down) }
override fun button(code: Int, down: Boolean) { heldButtons.set(4, code, down) }
override fun pointer(dx: Float, dy: Float) {
if (Looper.myLooper() == Looper.getMainLooper()) moveInputPointer(dx, dy)
else uiHandler.post {
if (resumed && !SessionState.suspended && !pipUi && !drawerOpen && !inputSettingsOpen)
if (Looper.myLooper() == Looper.getMainLooper()) {
if (!menuOwnsController) moveInputPointer(dx, dy)
} else uiHandler.post {
if (resumed && !SessionState.suspended && !pipUi && !menuOwnsController && !inputSettingsOpen)
moveInputPointer(dx, dy)
}
}
@@ -545,6 +548,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
drawerOpenState = value
if (!value && drawerDocked) closeDockedMenu()
}
private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController)
private val dockedTouchOnly: Boolean get() = drawerOpen && drawerDocked && !dockedMenuController
private val menuOwnsController: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuOwnsController(drawerOpen, drawerDocked, dockedMenuController)
private var quitFrom by mutableStateOf<androidx.compose.ui.geometry.Rect?>(null)
private var quitFlooded = false
private var leaving by mutableStateOf(false)
@@ -588,6 +594,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
private var drawerControllerActive by mutableStateOf(false)
private var backHold by mutableStateOf(true)
private var dockedMenuController by mutableStateOf(false)
private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var dualScreenSessionMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
private var backActionsInverted by mutableStateOf(false)
private var backDoubleTapMs by mutableStateOf(500)
private var lowLatency by mutableStateOf(true)
@@ -838,10 +847,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
SessionState.secondScreenAutoOpened = false
SessionState.bottomMenu = false
SessionState.secondScreenProvisional = false
SessionState.secondScreenAutomatic = false
SessionState.gameOnBottom = false
gameOnBottom = false
SessionState.gameOnBottom = SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED
gameOnBottom = SessionState.gameOnBottom
}
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
@@ -926,11 +936,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
!SessionPrefs.bluetoothAsked(this)) {
SessionPrefs.setBluetoothAsked(this)
requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH)
}
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
@Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
@@ -1109,6 +1114,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
when {
::loading.isInitialized && loading.ended -> finish()
inputSettingsOpen -> inputSettingsOpen = false
dockedTouchOnly -> routeBackAction()
drawerOpen -> drawerOpen = false
achievementsOpen -> closeAchievements()
pcKeyboardOpen -> pcKeyboardOpen = false
@@ -1137,6 +1143,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
val uiPointer = appUiOwnsPointer()
val cursorHidden = cursorHiddenByUi()
androidx.compose.runtime.SideEffect {
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
@@ -1187,7 +1194,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
} else {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
CursorOverlay({ cursorPos }, cursorVisible && (!uiPointer || onlyPcKeyboardOpen()) && !bottomOutputActive,
CursorOverlay({ cursorPos }, cursorVisible && (!cursorHidden || onlyPcKeyboardOpen()) && !bottomOutputActive,
resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity)
@@ -1304,9 +1311,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
}
}
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
LaunchedEffect(drawerOpen, menuOwnsController, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
updateOnScreenControls()
padBridge?.setInputEnabled(resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
padBridge?.setInputEnabled(resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended) {
backQamInput.cancel()
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
@@ -1358,13 +1365,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onDismiss = { gestureSettingsOpen = false },
onSaved = { gestureSettingsOpen = false; refreshGestureConfig() },
)
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
androidx.compose.runtime.LaunchedEffect(drawerOpen, menuOwnsController) {
if (drawerOpen) {
syncLossless()
releasePads()
androidx.compose.runtime.withFrameNanos { }
val requested = focusDrawer()
Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked")
if (menuOwnsController) {
releasePads()
androidx.compose.runtime.withFrameNanos { }
val requested = focusDrawer()
Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked")
} else {
releaseDrawerDirection()
}
} else {
releaseDrawerDirection()
}
@@ -1423,7 +1434,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (!SessionState.manualPause && !SessionState.suspended) pauseAnimated = false
}
SessionPausedOverlay(
suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed || SessionState.manualPause),
suspended = (SessionState.suspended || SessionState.manualPause) && (!autoResume || SessionState.resumeFailed || SessionState.manualPause),
engaged = SessionState.resumeRequested || SessionState.resuming,
failures = SessionState.resumeFailures,
frame = pausedFrame,
@@ -1522,6 +1533,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
secondScreenNone = !bottomOutputActive && !dockDrawer(),
dualScreenMode = dualScreenSessionMode,
onDualScreenMode = ::chooseDualScreenSessionMode,
gameOnBottom = bottomOutputActive,
gameSwapAvailable = bottomSwapAvailable,
gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay)
@@ -1532,6 +1545,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onHudOnlyDuringGame = { on ->
SessionPrefs.setHudOnlyDuringGame(this@SessionActivity, on)
hud.refresh()
},
onGpuClockPin = { on ->
SessionPrefs.setGpuClockPin(this@SessionActivity, on)
gpuClockPin = on
@@ -1752,6 +1769,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id))
padType = id
onScreenControls?.reload()
applyUnfoldedControls()
unfoldedPanel?.reload()
bottomInputControls?.reload()
},
backHold = backHold,
@@ -1759,6 +1778,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionPrefs.setBackHold(this@SessionActivity, on)
backHold = on
},
dockedMenuController = dockedMenuController,
onDockedMenuController = { on ->
SessionPrefs.setDockedMenuController(this@SessionActivity, on)
dockedMenuController = on
if (!on && drawerDocked) drawerControllerActive = false
},
backActionsInverted = backActionsInverted,
backDoubleTapMs = backDoubleTapMs,
onBackDoubleTapMs = { ms ->
@@ -1827,6 +1852,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
setRelativeMouse(mode)
},
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSelectMenuMode = ::pickMenuMode,
onSecondScreenMode = { mode ->
if (docked) drawerOpen = false
pickSecondScreenMode(mode)
@@ -1850,6 +1876,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pipAutoEnter = pipAutoEnter,
onPip = { pip.enter() },
onPause = ::pauseNow,
paused = SessionState.suspended || SessionState.manualPause,
onResume = { SessionService.resume(this@SessionActivity) },
orientation = sessionOrientation,
onOrientation = { value ->
SessionPrefs.setOrientation(this@SessionActivity, value)
sessionOrientation = value
applyFollowOrientation(resources.configuration)
},
onPipAutoEnter = { on ->
SessionPrefs.setPipAutoEnter(this@SessionActivity, on)
pipAutoEnter = on
@@ -1947,7 +1981,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun sendSteamGuide() {
drawerOpen = false
if (!dockedTouchOnly) drawerOpen = false
padBridge?.triggerSteamMenu()
}
@@ -1994,7 +2028,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun triggerSteamQam() {
drawerOpen = false
if (!dockedTouchOnly) drawerOpen = false
padBridge?.triggerQam()
}
@@ -2083,7 +2117,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun performBackAction(double: Boolean) {
val isSteam = SessionState.mode == SessionService.MODE_STEAM
val opensQam = isSteam && (double xor backActionsInverted)
if (opensQam) triggerSteamQam() else drawerOpen = !drawerOpen
if (opensQam) triggerSteamQam() else if (!dockedTouchOnly) drawerOpen = !drawerOpen
}
private fun handleHomeGuideIntent(incoming: Intent?) {
@@ -2627,6 +2661,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
oscRearButtons = SessionPrefs.oscRearButtons(this)
oscTrackpads = SessionPrefs.oscTrackpads(this)
backHold = SessionPrefs.backHold(this)
dockedMenuController = SessionPrefs.dockedMenuController(this)
sessionOrientation = SessionPrefs.orientation(this)
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
@@ -2956,16 +2993,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
WaylandCompositor.nativeResizeOutput(size.first, size.second)
}
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
private fun followScale(): Float {
val mode = displayMode()
val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait())
return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f
}
private fun followChoice(): Boolean {
val mode = displayMode()
return com.droiddeck.launcher.session.SessionDisplay.isFollow(
SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)))
SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait()))
}
private fun applyFollowOrientation(config: android.content.res.Configuration) {
@@ -3031,17 +3070,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun displayMode(): String = SessionPrefs.displayMode(this,
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted()
private fun outputSize(): Pair<Int, Int> =
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
resolutionChoice(), SessionPrefs.portrait(this) && !controlsBelowWanted())
resolutionChoice(), portraitOutput())
private fun resolutionChoice(): String {
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String {
val mode = displayMode()
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode, portrait))
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), portrait)
}
private fun refreshHz(): Float = refreshHz(null)
@@ -3511,13 +3552,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event)
if (normalized === event) return dispatchSessionKeyEvent(event)
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}")
}
return dispatchSessionKeyEvent(normalized)
}
private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
val steamVolume =
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!pipUi && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
!gestureSettingsOpen && !inputSettingsOpen && !appTextFocus && window.decorView.hasWindowFocus()
if (steamVolume) {
val audio = getSystemService(android.media.AudioManager::class.java)
@@ -3531,13 +3581,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (penStream.holdsKey(event) || (penSettings.mode != SessionPrefs.PEN_TOUCH && PenStream.isPenKey(event))) return penStream.onKey(event)
if (appTextFocus) return super.dispatchKeyEvent(event)
if (!pipUi) {
if (physicalInputBindings?.onKey(event, resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
if (physicalInputBindings?.onKey(event, resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true
if (physicalShortcuts.onKey(
event,
enabled = resumed && SessionState.running && !SessionState.suspended &&
!(drawerOpen && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) &&
!(drawerOpen && PhysicalShortcuts.isDrawerNavigationKey(event)) &&
!(menuOwnsController && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) &&
!(menuOwnsController && PhysicalShortcuts.isDrawerNavigationKey(event)) &&
(event.deviceId to event.keyCode) !in resumeKeysDown &&
!(::loading.isInitialized && (loading.visible || loading.ended)) &&
!pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen,
@@ -3545,12 +3595,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
) { action ->
pendingBackAction?.let(uiHandler::removeCallbacks)
pendingBackAction = null
drawerControllerActive = true
if (!dockedMenuIdle) drawerControllerActive = true
Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}")
when (action) {
PhysicalShortcuts.Action.STEAM -> sendSteamGuide()
PhysicalShortcuts.Action.QAM -> triggerSteamQam()
PhysicalShortcuts.Action.DROIDDECK -> drawerOpen = !drawerOpen
PhysicalShortcuts.Action.DROIDDECK -> if (!dockedTouchOnly) drawerOpen = !drawerOpen
}
}) return true
}
@@ -3576,7 +3626,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
if (mouseBackHandled) return true
val backToQam = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
val backToQam = !pipUi && !appTextFocus && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
!SessionState.suspended && padBridge?.canHoldQam() == true
@@ -3589,12 +3639,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad)
val fromController = PadBridge.isControllerKeyEvent(event)
if (fromController && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
padBridge?.setInputEnabled(false)
padBridge?.onKeyEvent(event)
}
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
if (drawerOpen && !drawerControllerActive) focusDrawer()
if (fromController && event.action == KeyEvent.ACTION_DOWN && !dockedMenuIdle) {
if (menuOwnsController && !drawerControllerActive) focusDrawer()
drawerControllerActive = true
}
if (fromController && event.keyCode == KeyEvent.KEYCODE_BUTTON_B && ::loading.isInitialized && loading.visible && !loading.ended && !drawerOpen) {
@@ -3613,7 +3663,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
val drawerShortcutKey = event.deviceId to event.keyCode
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) &&
((drawerOpen && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) {
((menuOwnsController && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) {
if (event.action == KeyEvent.ACTION_DOWN) {
drawerShortcutKeysDown.add(drawerShortcutKey)
if (event.repeatCount == 0) {
@@ -3625,11 +3675,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
return true
}
if (drawerOpen) {
if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
drawerPage = sessionDrawerPages(glasses.present)
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
val pages = sessionDrawerPages(glasses.present)
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection()
}
return true
@@ -3695,11 +3746,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (pipUi) return true
notePress(event)
if (PadBridge.isControllerMotionEvent(event) && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
if (PadBridge.isControllerMotionEvent(event) && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
padBridge?.setInputEnabled(false)
padBridge?.onMotionEvent(event)
}
if (drawerOpen && PadBridge.isControllerMotionEvent(event)) {
if (menuOwnsController && PadBridge.isControllerMotionEvent(event)) {
if (!drawerControllerActive) focusDrawer()
drawerControllerActive = true
if (event.actionMasked == MotionEvent.ACTION_MOVE &&
@@ -3876,6 +3927,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun closeDockedMenu() {
SessionState.bottomMenu = false
drawerDocked = false
val presentation = secondScreenPresentation ?: return
presentation.showMenu(false)
@@ -4301,7 +4353,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
?: if (SessionState.gameOnBottom) bottomGameDisplay()?.displayId else null
SessionState.secondScreenAutoOpened = true
if (gameDisplay != null && gameDisplay != target.displayId && secondScreenDisplays.any { it.id == gameDisplay }) {
panelMode(openingPanel())
panelMode(openingSurface())
} else {
val selectionChanged = selectedSecondScreenDisplay != target.displayId
selectedSecondScreenDisplay = target.displayId
@@ -4320,14 +4372,69 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun openingPanel() = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this, desktopSession), SessionState.deckPad,
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available(), desktopSession)
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available())
private fun openingSurface() = openingPanel().takeIf { it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD
private fun menuShownOnBottom() = drawerDocked && (drawerOpen || drawerPinned)
private fun pinDockedMenu() {
if (!dockDrawer()) return
drawerLayerOpen = false
if (!openDockedMenu()) return
drawerDocked = true
drawerOpenState = false
drawerPinned = true
updateKeyboardRoute()
}
private fun showMenuMode() {
dualControlsProvisional = false
selectSecondScreenMode(secondScreenMode.takeIf { it != SecondScreenMode.NONE } ?: SecondScreenMode.KEYBOARD_TRACKPAD)
if (secondScreenMode != SecondScreenMode.NONE) pinDockedMenu()
}
private fun pickMenuMode() {
typingReturnMode = null
automaticPanel = false
SessionPrefs.setSecondScreenPanel(this, desktopSession, SecondScreenMode.MENU.id)
drawerOpen = true
}
private fun settleDualScreenControls() {
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
dualControlsProvisional = false
if (secondScreenMode == SecondScreenMode.NONE) return
val wanted = openingPanel()
if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
if (wanted == SecondScreenMode.MENU) {
if (!menuShownOnBottom()) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
} else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
}
private fun chooseDualScreenSessionMode(mode: String) {
if (mode !in com.droiddeck.launcher.input.DualScreen.modes || mode == dualScreenSessionMode) return
SessionPrefs.setDualScreenSessionMode(this, mode)
dualScreenSessionMode = mode
SessionState.secondScreenAutoOpened = false
val menuOnBottom = drawerDocked
val menuOnTop = drawerOpenState && !drawerDocked
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED) {
putGameOnBottom(true)
} else if (gameOnBottom && mode != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
putGameOnBottom(false)
}
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
if (gameOnBottom) putGameOnBottom(false)
if (secondScreenMode != SecondScreenMode.NONE || menuOnBottom) closeSecondScreen(reset = true)
if (menuOnBottom) drawerOpen = true
} else if (menuOnTop) {
// The menu moves to the second screen as the menu itself, not as one of the control panels.
SessionState.secondScreenAutoOpened = true
refreshSecondScreenDisplays()
pinDockedMenu()
return
}
refreshSecondScreenDisplays()
}
private fun selectSecondScreenDisplay(displayId: Int) {
@@ -4348,6 +4455,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
closeSecondScreen(reset = true)
return
}
if (mode == SecondScreenMode.MENU) {
showMenuMode()
return
}
if (secondScreenDisplays.isEmpty()) {
panelMode(SecondScreenMode.NONE)
return
@@ -4364,7 +4475,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun showSecondScreen(requested: SecondScreenMode) {
if (pipUi || !started) return
val mode = if (requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) openingPanel() else requested
val mode = when {
requested == SecondScreenMode.MENU ->
secondScreenMode.takeIf { it != SecondScreenMode.NONE && it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD
requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> openingSurface()
else -> requested
}
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
closeSecondScreen(reset = false)
@@ -4401,6 +4517,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun pickSecondScreenMode(mode: SecondScreenMode) {
typingReturnMode = null
automaticPanel = false
SessionState.bottomMenu = false
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
selectSecondScreenMode(mode)
}
@@ -4408,7 +4525,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun bottomScreenPicker(mode: SecondScreenMode) = com.droiddeck.launcher.ui.ScreenPicker(
com.droiddeck.launcher.ui.secondScreenModes(false, SessionState.deckPad, bottomPages().isNotEmpty(),
com.droiddeck.launcher.session.BottomDesktop.available()),
mode, ::pickSecondScreenMode, onMenu = { drawerOpen = true },
mode, ::pickSecondScreenMode, onMenu = ::pickMenuMode,
)
private fun secondScreenPresentation(target: Display) = SecondScreenPresentation(
@@ -4620,7 +4737,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let {
it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()
} ?: 0
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow)
val outputAspect = if (!wanted || SessionState.followScreen) 0f
else outputSize().let { it.first.toFloat() / it.second.coerceAtLeast(1) }
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, outputAspect)
else FrameLayout.LayoutParams.MATCH_PARENT
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
if (params.height != gameHeight) {
@@ -4629,7 +4748,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
else "unfolded controls: game full screen")
}
val portrait = !com.droiddeck.launcher.session.SessionDisplay.foldable(this)
val dock = if (SessionState.deckPad) com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD])
val kit = com.droiddeck.launcher.input.PadKit.forOverlay(this, primaryInputLayout)
val dock = if (SessionState.deckPad && kit?.steam != false)
com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD])
else com.droiddeck.launcher.input.OnScreenLayout.Dock(portrait, false)
var panel = unfoldedPanel
if (panel != null && (!wanted || panel.dock != dock)) {
@@ -4830,6 +4951,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun dropDockedDrawer() {
if (drawerDocked && (drawerOpenState || drawerPinned)) SessionState.bottomMenu = true
drawerPinned = false
if (!drawerDocked) return
drawerDocked = false
@@ -4848,6 +4970,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (reset) {
panelMode(SecondScreenMode.NONE)
automaticPanel = false
SessionState.bottomMenu = false
}
}
@@ -5400,8 +5523,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun onlyPcKeyboardOpen(): Boolean =
pcKeyboardOpen && !drawerOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !glassesOutputActive && !touchEditorOpen && !wowChatOnTop
private fun appUiOwnsPointer(): Boolean =
drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop
private fun otherUiOwnsPointer(): Boolean =
pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop
private fun appUiOwnsPointer(): Boolean = drawerOpen || otherUiOwnsPointer()
/** A touch-only docked menu leaves the game cursor alone, so controller pointer moves stay visible. */
private fun cursorHiddenByUi(): Boolean = menuOwnsController || otherUiOwnsPointer()
private fun applyPlatformPointer(shown: Boolean) {
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
@@ -5510,6 +5638,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
.takeIf { it.isFile }
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM)
unfoldedColumn?.let { column ->
val shown = if (inputSettingsOpen) View.INVISIBLE else View.VISIBLE
if (column.visibility != shown) { unfoldedPanel?.releaseAll(); unfoldedDeckSurface?.releaseInputs(); column.visibility = shown }
}
val controls = onScreenControls ?: return
fun showPinned() {
controls.setPinnedOnly(true)
@@ -5675,31 +5807,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldKeys.set(owner, code, down)
}
private fun capturePausedFrame(manual: Boolean = false) {
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) return
private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) {
fun skipped(reason: String) {
if (manual) SessionEvents.record("pause.frame_skipped", mapOf("reason" to reason))
onDone()
}
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) {
return skipped("state running=${SessionState.running} pip=$pipUi glasses=$glassesOutputActive bottom=$bottomOutputActive")
}
if (SessionState.suspended && pausedFrame != null) return
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return
if (surfaceView.holder.surface?.isValid != true) return
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return skipped("policy")
if (surfaceView.holder.surface?.isValid != true) return skipped("surface invalid")
val width = surfaceView.width
val height = surfaceView.height
if (width <= 0 || height <= 0) return
if (width <= 0 || height <= 0) return skipped("size ${width}x$height")
val scale = minOf(1f, PAUSED_FRAME_MAX_EDGE / maxOf(width, height).toFloat())
val bitmap = try {
android.graphics.Bitmap.createBitmap(
maxOf(1, (width * scale).toInt()), maxOf(1, (height * scale).toInt()), android.graphics.Bitmap.Config.ARGB_8888,
)
} catch (_: OutOfMemoryError) {
return
return skipped("oom")
}
val surfaceAt = IntArray(2).also { surfaceView.getLocationInWindow(it) }
val overlayAt = IntArray(2).also { sessionOverlay.getLocationInWindow(it) }
val left = surfaceAt[0] - overlayAt[0]
val top = surfaceAt[1] - overlayAt[1]
val bounds = android.graphics.Rect(left, top, left + width, top + height)
val requestedAt = SystemClock.elapsedRealtime()
withPictureFrame { done ->
try {
android.view.PixelCopy.request(surfaceView, bitmap, { result ->
done()
onDone()
if (manual) SessionEvents.record("pause.frame_copy", mapOf(
"result" to result, "ms" to SystemClock.elapsedRealtime() - requestedAt,
"zeroCopy" to SessionPrefs.zeroCopy(this, SessionState.mode), "size" to "${width}x$height",
"lit" to (result == android.view.PixelCopy.SUCCESS && bitmapHasPicture(bitmap)),
))
if (result == android.view.PixelCopy.SUCCESS && !isDestroyed) {
pausedFrame = com.droiddeck.launcher.ui.PausedFrame(bitmap.asImageBitmap(), bounds)
pausedFrameWanted = false
@@ -5710,6 +5855,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} catch (_: IllegalArgumentException) {
done()
bitmap.recycle()
skipped("copy rejected")
}
}
}
@@ -5717,12 +5863,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun pauseNow() {
if (!SessionState.running || SessionState.suspended) return
pauseAnimated = true
drawerOpen = false
if (!dockedTouchOnly) drawerOpen = false
pausedFrame = null
capturePausedFrame(manual = true)
if (zeroCopyActive()) {
WaylandCompositor.nativeSetZeroCopy(false)
val restore = java.util.concurrent.atomic.AtomicBoolean(false)
val back = { if (restore.compareAndSet(false, true)) WaylandCompositor.nativeSetZeroCopy(true) }
uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS)
uiHandler.postDelayed({ back() }, ZERO_COPY_RESTORE_MS)
} else {
capturePausedFrame(manual = true)
}
SessionService.pause(this)
}
private fun zeroCopyActive(): Boolean =
CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy(this, SessionState.mode)
private fun bitmapHasPicture(bitmap: android.graphics.Bitmap): Boolean {
val w = bitmap.width
val h = bitmap.height
if (w <= 0 || h <= 0) return false
var lit = 0
for (i in 0 until 64) {
val c = bitmap.getPixel((w * (i % 8 + 1)) / 9, (h * (i / 8 + 1)) / 9)
if (android.graphics.Color.red(c) + android.graphics.Color.green(c) + android.graphics.Color.blue(c) > 24) lit++
}
return lit >= 3
}
private fun requestPausedFrame() {
if (pausedFrame != null) return
pausedFrameWanted = true
@@ -5826,8 +5995,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
reconcileDock(shownOnDisplayId)
settleDualScreenControls()
refreshSecondScreenDisplays()
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
else openDualScreenControls()
if (secondScreenMode != SecondScreenMode.NONE) {
if (secondScreenPresentation == null) showSecondScreen(secondScreenMode)
if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu()
SessionState.bottomMenu = false
} else {
if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu()
SessionState.bottomMenu = false
if (!menuShownOnBottom()) openDualScreenControls()
}
startedScreens++
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
Glasses.rescan()
@@ -5978,7 +6154,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldKeys.clear()
heldButtons.clear()
if (!screenOff) {
val menuUp = menuShownOnBottom()
drawerOpen = false
if (menuUp) SessionState.bottomMenu = true
pcKeyboardOpen = false
achievementsOpen = false
}
@@ -6750,6 +6928,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private const val LEAVE_TIMEOUT_MS = 1_500L
private const val TEXT_FIELD_TAP_MS = 1_000L
private const val PAUSED_FRAME_MAX_EDGE = 1920f
private const val ZERO_COPY_SETTLE_MS = 150L
private const val ZERO_COPY_RESTORE_MS = 1200L
private const val BFI_PICTURE_SETTLE_MS = 50L
private const val PAUSED_FRAME_REDRAW_MS = 150L
private const val BOTTOM_RECOVERY_MS = 1_000L
@@ -143,9 +143,9 @@ object AgentSetup {
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
"apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " +
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " +
"for i in 1 2 3; do apt update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
"for i in 1 2 3; do apt -o APT::Update::Error-Mode=any update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
"apt -f install -y --fix-missing; " +
"apt install -y --fix-missing --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
"apt install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
}
Step.SIGN_IN -> harness.signIn
Step.GITHUB -> listOf("dd-gh-login")
@@ -53,6 +53,13 @@ object AppUiPrefs {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply()
}
fun pageSwipe(context: Context): Boolean =
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("page-swipe", true)
fun setPageSwipe(context: Context, on: Boolean) {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("page-swipe", on).apply()
}
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
fun scale(context: Context): Int = normalizeScale(
@@ -207,9 +207,11 @@ object DeviceReport {
k("refresh_rate_mode", runCatching { Settings.Secure.getString(context.contentResolver, "refresh_rate_mode") }.getOrNull() ?: "not set")
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context)
for ((label, mode) in listOf("Resolution (Steam)" to SessionService.MODE_STEAM, "Resolution (Desktop)" to SessionService.MODE_DESKTOP)) {
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize)
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice)
k(label, "$choice (${size.first}x${size.second})")
for ((suffix, portrait) in listOf("landscape" to false, "portrait" to true)) {
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize, portrait)
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice, portrait)
k("$label $suffix", "$choice (${size.first}x${size.second})")
}
}
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
@@ -16,7 +16,7 @@ object SteamIntegration {
const val EXTRA_FEATURE = "integration_feature"
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
private const val SHORTCUTS_ASSET = "shortcuts.apk"
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH }
data class State(
val wifi: Boolean = false,
@@ -28,6 +28,7 @@ object SteamIntegration {
val shortcuts: Boolean = false,
val shortcutsRestricted: Boolean = false,
val shortcutsTried: Boolean = false,
val bluetooth: Boolean = false,
val suggested: Boolean = true,
)
@@ -39,9 +40,16 @@ object SteamIntegration {
home = HomeApp.isDefault(context),
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
shortcutsRestricted = restrictedSettings(context),
bluetooth = bluetoothAllowed(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
)
fun bluetoothAllowed(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S ||
context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
private fun restrictedSettings(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
val mode = runCatching {
@@ -38,6 +38,8 @@ class WirelessAdbPairingService : Service() {
private var pairingHost: String? = null
private var pairingPort: Int? = null
@Volatile private var working = false
@Volatile private var limitEnabled = false
@Volatile private var session = 0
private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) }
override fun onBind(intent: Intent?): IBinder? = null
@@ -50,12 +52,15 @@ class WirelessAdbPairingService : Service() {
onCode(code)
}
ACTION_CANCEL -> finish(Stage.Idle)
else -> begin()
else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true)
}
return START_NOT_STICKY
}
private fun begin() {
private fun begin(enableLimit: Boolean) {
if (working) return
session++
limitEnabled = enableLimit
pairingHost = null
pairingPort = null
working = false
@@ -68,12 +73,13 @@ class WirelessAdbPairingService : Service() {
private fun startDiscovery() {
stopDiscovery()
val owner = session
val manager = getSystemService(Context.NSD_SERVICE) as NsdManager
val listener = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String) = Unit
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return
runCatching { manager.resolveService(serviceInfo, resolveListener()) }
runCatching { manager.resolveService(serviceInfo, resolveListener(owner)) }
}
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
override fun onDiscoveryStopped(serviceType: String) = Unit
@@ -87,18 +93,20 @@ class WirelessAdbPairingService : Service() {
.onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) }
}
private fun resolveListener() = object : NsdManager.ResolveListener {
private fun resolveListener(owner: Int): NsdManager.ResolveListener {
return object : NsdManager.ResolveListener {
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
val address = serviceInfo.host ?: return
if (!WirelessAdbFix.isLocalAddress(address)) return
main.post {
if (working || current.value == Stage.Done) return@post
if (owner != session || working || current.value == Stage.Done) return@post
pairingHost = address.hostAddress
pairingPort = serviceInfo.port
if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded())
}
}
}
}
private fun onCode(code: String) {
@@ -114,29 +122,34 @@ class WirelessAdbPairingService : Service() {
return
}
working = true
val owner = session
val enable = limitEnabled
show(Stage.Working(getString(R.string.adbpair_pairing)))
Thread({
val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
if (paired.isFailure) {
main.post {
working = false
if (owner != session) return@post
pairingPort = null
show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected)))
}
return@Thread
}
main.post {
if (owner != session) return@post
stopDiscovery()
show(Stage.Working(getString(R.string.adbpair_connecting)))
}
val result = runCatching {
val connectPort = WirelessAdbFix.localConnectPort(this)
?: error(getString(R.string.adbpair_port_not_found))
main.post { show(Stage.Working(getString(R.string.adbpair_applying))) }
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
main.post { if (owner == session) show(Stage.Working(getString(R.string.adbpair_applying))) }
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, enable)
}
main.post {
working = false
if (owner != session) return@post
finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_command_failed)) } ?: Stage.Done)
}
}, "wireless-adb-pairing").start()
@@ -148,6 +161,7 @@ class WirelessAdbPairingService : Service() {
}
private fun finish(stage: Stage) {
session++
main.removeCallbacks(timeout)
stopDiscovery()
publish(stage)
@@ -248,6 +262,7 @@ class WirelessAdbPairingService : Service() {
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
private const val KEY_CODE = "code"
private const val EXTRA_ENABLE_LIMIT = "enable_limit"
private const val TIMEOUT_MS = 5 * 60_000L
private val current = MutableStateFlow<Stage>(Stage.Idle)
@@ -255,10 +270,10 @@ class WirelessAdbPairingService : Service() {
private fun publish(stage: Stage) { current.value = stage }
fun start(context: Context) {
fun start(context: Context, enableLimit: Boolean = false) {
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
publish(Stage.Waiting)
val intent = Intent(context, WirelessAdbPairingService::class.java)
val intent = Intent(context, WirelessAdbPairingService::class.java).putExtra(EXTRA_ENABLE_LIMIT, enableLimit)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
}
@@ -271,6 +286,12 @@ class WirelessAdbPairingService : Service() {
}
fun notificationsEnabled(context: Context): Boolean =
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false && !channelBlocked(context)
/** The code is typed into a notification on this channel; a channel the user switched off leaves pairing with nothing to type into. */
fun channelBlocked(context: Context): Boolean =
context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
fun channelId(): String = CHANNEL_ID
}
}
@@ -28,6 +28,7 @@ import androidx.compose.material.icons.filled.ArrowUpward
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.FileOpen
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.InsertDriveFile
@@ -101,8 +102,18 @@ private fun FileContextMenuItems(
onToggleFavorite: () -> Unit,
onProperties: () -> Unit,
onDismissMenu: () -> Unit,
onOpen: () -> Unit,
) {
val isDir = file.isDirectory
if (!isDir) {
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_edit_open)) },
leadingIcon = { Icon(Icons.Filled.FileOpen, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onOpen() },
modifier = Modifier.focusGlide(),
)
MenuItemDivider()
}
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_select)) },
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
@@ -180,6 +191,7 @@ internal fun FileItemRow(
onCut: () -> Unit,
onDelete: () -> Unit,
onRename: () -> Unit,
onOpen: () -> Unit = {},
isFavorite: Boolean = false,
onToggleFavorite: () -> Unit = {},
onProperties: () -> Unit = {},
@@ -291,6 +303,7 @@ internal fun FileItemRow(
file = file,
isFavorite = isFavorite,
onSelect = onSelect,
onOpen = onOpen,
onRename = onRename,
onCopy = onCopy,
onCut = onCut,
@@ -517,6 +530,7 @@ internal fun FileGridTile(
isFavorite: Boolean = false,
onSelect: () -> Unit = {},
onRename: () -> Unit = {},
onOpen: () -> Unit = {},
onCopy: () -> Unit = {},
onCut: () -> Unit = {},
onDelete: () -> Unit = {},
@@ -605,6 +619,7 @@ internal fun FileGridTile(
file = file,
isFavorite = isFavorite,
onSelect = onSelect,
onOpen = onOpen,
onRename = onRename,
onCopy = onCopy,
onCut = onCut,
@@ -191,6 +191,7 @@ fun FileManagerScreen(
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
var showNewFolderDialog by remember { mutableStateOf(false) }
var renameTarget by remember { mutableStateOf<File?>(null) }
var editingTarget by remember { mutableStateOf<File?>(null) }
var propertiesTarget by remember { mutableStateOf<File?>(null) }
var isOperationRunning by remember { mutableStateOf(false) }
var operationLabel by remember { mutableStateOf("") }
@@ -294,7 +295,7 @@ fun FileManagerScreen(
if (isOperationActive()) pendingNavigation = action else navigate(action)
}
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) {
requestNavigation(FileManagerNavigation.BACK)
}
@@ -696,6 +697,14 @@ fun FileManagerScreen(
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
Column(modifier = Modifier.fillMaxSize()) {
editingTarget?.let { target ->
TextEditorScreen(
file = target,
onExit = { editingTarget = null },
modifier = Modifier.fillMaxSize(),
)
return@Column
}
if (pickMode && !pickerTitle.isNullOrEmpty()) {
Text(
text = pickerTitle,
@@ -1194,6 +1203,8 @@ fun FileManagerScreen(
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
onPick?.invoke(file)
}
} else {
editingTarget = file
}
},
onMenu = { showMenuFor = file },
@@ -1205,6 +1216,7 @@ fun FileManagerScreen(
selectedPaths = selectedPaths + file.absolutePath
showMenuFor = null
},
onOpen = { editingTarget = file; showMenuFor = null },
onRename = { renameTarget = file; showMenuFor = null },
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
@@ -1273,6 +1285,8 @@ fun FileManagerScreen(
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
onPick?.invoke(file)
}
} else {
editingTarget = file
}
},
onMenu = { showMenuFor = file },
@@ -1286,6 +1300,7 @@ fun FileManagerScreen(
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
onDelete = { selectedEntry = file; showMenuFor = null },
onOpen = { editingTarget = file; showMenuFor = null },
onRename = { renameTarget = file; showMenuFor = null },
isFavorite = isFav,
onToggleFavorite = {
@@ -0,0 +1,726 @@
package com.droiddeck.launcher.files
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Save
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
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.mutableIntStateOf
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.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
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.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
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.R
import com.droiddeck.launcher.ui.focusGlide
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.charset.CharacterCodingException
import java.nio.charset.Charset
import java.nio.charset.CodingErrorAction
import java.nio.file.Files
import kotlin.math.roundToInt
internal const val EDITOR_FONT_SIZE_SP = 13
internal const val EDITOR_LINE_HEIGHT_SP = 18
internal const val EDITOR_TAB_WIDTH = 4
internal const val EDITOR_MAX_OPEN_BYTES = 4L * 1024 * 1024
internal const val EDITOR_MAX_EDIT_BYTES = 512L * 1024
internal enum class EditorCharset(val label: String, private val charsetName: String) {
UTF8("UTF-8", "UTF-8"),
GB18030("GB18030", "GB18030"),
;
val charset: Charset get() = Charset.forName(charsetName)
}
internal enum class EditorLock { NONE, BINARY, TOO_LARGE, PERMISSION, LOSSY }
internal enum class EditorLoadState { LOADING, READY, TOO_LARGE, UNREADABLE }
internal data class DecodedEditorText(val text: String, val charset: EditorCharset, val lossy: Boolean)
internal fun editorIsBinary(bytes: ByteArray, sample: Int = 8192): Boolean {
val limit = minOf(bytes.size, sample)
for (i in 0 until limit) if (bytes[i].toInt() == 0) return true
return false
}
private fun strictDecode(bytes: ByteArray, charset: Charset): String? = try {
charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString()
} catch (e: CharacterCodingException) {
null
}
internal fun decodeEditorText(bytes: ByteArray): DecodedEditorText {
strictDecode(bytes, Charsets.UTF_8)?.let { return DecodedEditorText(it, EditorCharset.UTF8, false) }
strictDecode(bytes, EditorCharset.GB18030.charset)?.let { return DecodedEditorText(it, EditorCharset.GB18030, false) }
return DecodedEditorText(String(bytes, Charsets.UTF_8), EditorCharset.UTF8, true)
}
internal fun resolveEditorSaveTarget(file: File): File {
val isLink = runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false)
if (!isLink) return file
// rename(2) replaces the link itself, so stage next to and rename onto the real target
return runCatching { file.canonicalFile }.getOrDefault(file)
}
internal fun readCapped(input: InputStream, limit: Long): ByteArray? {
val out = ByteArrayOutputStream()
val buffer = ByteArray(64 * 1024)
var total = 0L
while (true) {
val n = input.read(buffer)
if (n < 0) return out.toByteArray()
total += n
if (total > limit) return null
out.write(buffer, 0, n)
}
}
internal fun expandEditorTabs(text: String, width: Int = EDITOR_TAB_WIDTH): String {
if (text.indexOf('\t') < 0) return text
val out = StringBuilder(text.length)
var column = 0
for (c in text) {
when (c) {
'\n' -> {
out.append(c)
column = 0
}
'\t' -> {
val pad = width - (column % width)
repeat(pad) { out.append(' ') }
column += pad
}
else -> {
out.append(c)
column++
}
}
}
return out.toString()
}
internal fun lineCountOf(text: String): Int {
var lines = 1
for (i in text.indices) if (text[i] == '\n') lines++
return lines
}
internal fun lineIndexOfOffset(text: String, offset: Int): Int {
val end = offset.coerceIn(0, text.length)
var line = 0
var i = 0
while (i < end) {
if (text[i] == '\n') line++
i++
}
return line
}
internal fun columnOfOffset(text: String, offset: Int): Int {
val end = offset.coerceIn(0, text.length)
var start = end
while (start > 0 && text[start - 1] != '\n') start--
return end - start + 1
}
internal fun findEditorMatches(
text: String,
query: String,
matchCase: Boolean = false,
limit: Int = 10000,
): List<IntRange> {
if (query.isEmpty()) return emptyList()
val out = ArrayList<IntRange>()
var at = 0
while (out.size < limit) {
val found = text.indexOf(query, at, ignoreCase = !matchCase)
if (found < 0) break
out.add(found until found + query.length)
at = found + query.length
}
return out
}
internal fun replaceEditorMatches(text: String, matches: List<IntRange>, replacement: String): String {
if (matches.isEmpty()) return text
val out = StringBuilder(text.length)
var cursor = 0
for (m in matches) {
if (m.first < cursor || m.last >= text.length) continue
out.append(text, cursor, m.first).append(replacement)
cursor = m.last + 1
}
out.append(text, cursor, text.length)
return out.toString()
}
@Composable
internal fun TextEditorScreen(
file: File,
onExit: () -> Unit,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val density = LocalDensity.current
var text by remember { mutableStateOf("") }
var selection by remember { mutableStateOf(TextRange.Zero) }
var composing by remember { mutableStateOf<TextRange?>(null) }
var loadState by remember { mutableStateOf(EditorLoadState.LOADING) }
var lock by remember { mutableStateOf(EditorLock.NONE) }
var charset by remember { mutableStateOf(EditorCharset.UTF8) }
var dirty by remember { mutableStateOf(false) }
var saving by remember { mutableStateOf(false) }
var showDiscard by remember { mutableStateOf(false) }
var showSearch by remember { mutableStateOf(false) }
var query by remember { mutableStateOf("") }
var replacement by remember { mutableStateOf("") }
var matchCase by remember { mutableStateOf(false) }
var matchIndex by remember { mutableIntStateOf(0) }
val scrollState = rememberScrollState()
val textHorizontalState = rememberScrollState()
var viewportHeight by remember { mutableIntStateOf(0) }
var viewportWidth by remember { mutableIntStateOf(0) }
val lineHeightDp = with(density) { EDITOR_LINE_HEIGHT_SP.sp.toDp() }
val lineHeightPx = with(density) { lineHeightDp.toPx() }
val totalLines = remember(text) { lineCountOf(text) }
val cursorLine = lineIndexOfOffset(text, selection.end)
val cursorColumn = columnOfOffset(text, selection.end)
val matches = remember(text, query, matchCase) { findEditorMatches(text, query, matchCase) }
val readOnly = lock != EditorLock.NONE
val bodyStyle = TextStyle(
fontFamily = FontFamily.Monospace,
fontSize = EDITOR_FONT_SIZE_SP.sp,
lineHeight = EDITOR_LINE_HEIGHT_SP.sp,
color = MaterialTheme.colorScheme.onBackground,
)
val textMeasurer = rememberTextMeasurer()
val charWidthPx = remember(bodyStyle) { textMeasurer.measure(text = "0", style = bodyStyle).size.width.toFloat() }
LaunchedEffect(file) {
loadState = EditorLoadState.LOADING
val size = withContext(Dispatchers.IO) { file.length() }
if (size > EDITOR_MAX_OPEN_BYTES) {
loadState = EditorLoadState.TOO_LARGE
return@LaunchedEffect
}
val read = withContext(Dispatchers.IO) {
runCatching { file.inputStream().use { readCapped(it, EDITOR_MAX_OPEN_BYTES) } }
}
val bytes = read.getOrNull()
if (bytes == null) {
loadState = if (read.isFailure) EditorLoadState.UNREADABLE else EditorLoadState.TOO_LARGE
return@LaunchedEffect
}
val decoded = decodeEditorText(bytes)
text = expandEditorTabs(decoded.text)
charset = decoded.charset
lock = when {
editorIsBinary(bytes) -> EditorLock.BINARY
decoded.lossy -> EditorLock.LOSSY
bytes.size > EDITOR_MAX_EDIT_BYTES -> EditorLock.TOO_LARGE
!file.canWrite() -> EditorLock.PERMISSION
else -> EditorLock.NONE
}
selection = TextRange.Zero
loadState = EditorLoadState.READY
}
suspend fun revealLine(line: Int) {
val current = scrollState.value
val top = line * lineHeightPx
val target = when {
top < current -> top
top + lineHeightPx > current + viewportHeight -> top + lineHeightPx - viewportHeight
else -> return
}
val clamped = target.roundToInt().coerceIn(0, scrollState.maxValue)
if (clamped != current) scrollState.scrollTo(clamped)
}
LaunchedEffect(text, selection.end, viewportHeight, viewportWidth) {
if (loadState != EditorLoadState.READY) return@LaunchedEffect
revealLine(lineIndexOfOffset(text, selection.end))
if (viewportWidth > 0 && charWidthPx > 0) {
val x = (columnOfOffset(text, selection.end) - 1) * charWidthPx
val current = textHorizontalState.value
val target = when {
x < current -> x
x + charWidthPx > current + viewportWidth -> x + charWidthPx - viewportWidth
else -> null
}
if (target != null) {
val clamped = target.roundToInt().coerceIn(0, textHorizontalState.maxValue)
if (clamped != current) textHorizontalState.scrollTo(clamped)
}
}
}
LaunchedEffect(query, matchCase) {
if (query.isEmpty()) return@LaunchedEffect
matchIndex = 0
val first = matches.firstOrNull() ?: return@LaunchedEffect
selection = TextRange(first.first, first.last + 1)
composing = TextRange.Zero
}
LaunchedEffect(text) { matchIndex = 0 }
fun gotoMatch(delta: Int) {
if (matches.isEmpty()) return
matchIndex = Math.floorMod(matchIndex + delta, matches.size)
val m = matches[matchIndex]
selection = TextRange(m.first, m.last + 1)
composing = TextRange.Zero
}
fun replaceCurrent() {
if (readOnly) return
val m = matches.getOrNull(matchIndex) ?: return
text = text.replaceRange(m.first, m.last + 1, replacement)
dirty = true
matchIndex = 0
selection = TextRange(m.first + replacement.length)
composing = TextRange.Zero
}
fun replaceAll() {
if (readOnly || matches.isEmpty()) return
val all = findEditorMatches(text, query, matchCase, limit = Int.MAX_VALUE)
text = replaceEditorMatches(text, all, replacement)
dirty = true
matchIndex = 0
selection = TextRange.Zero
composing = TextRange.Zero
}
fun save() {
if (readOnly || saving || loadState != EditorLoadState.READY) return
val snapshot = text
val bytes = snapshot.toByteArray(charset.charset)
saving = true
scope.launch {
val ok = withContext(Dispatchers.IO) {
runCatching {
val target = resolveEditorSaveTarget(file)
val parent = target.parentFile
if (parent == null) {
target.writeBytes(bytes)
} else {
val tmp = File.createTempFile(".${target.name}.", ".droiddeck-tmp", parent)
try {
tmp.writeBytes(bytes)
runCatching {
Files.setPosixFilePermissions(tmp.toPath(), Files.getPosixFilePermissions(target.toPath()))
}
if (!tmp.renameTo(target)) error("rename to ${target.name} failed")
} finally {
tmp.delete()
}
}
}.isSuccess
}
saving = false
if (ok) {
if (text == snapshot) dirty = false
} else {
Toast.makeText(context, context.getString(R.string.fm_edit_save_failed, file.name), Toast.LENGTH_SHORT).show()
}
}
}
fun tryExit() {
if (saving) return
if (dirty && !readOnly) showDiscard = true else onExit()
}
BackHandler { tryExit() }
if (showDiscard) {
OutlinedAlertDialog(
onDismissRequest = { showDiscard = false },
title = { Text(stringResource(R.string.fm_edit_discard_title)) },
text = { Text(stringResource(R.string.fm_edit_discard_text, file.name)) },
confirmButton = {
TextButton(onClick = onExit, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.fm_edit_discard))
}
},
dismissButton = {
TextButton(onClick = { showDiscard = false }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.common_cancel))
}
},
)
}
Column(
modifier = modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainer)
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
IconButton(onClick = { tryExit() }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
Icons.Filled.ArrowBack,
stringResource(R.string.fm_back),
tint = MaterialTheme.colorScheme.primary,
)
}
Column(modifier = Modifier.weight(1f).padding(horizontal = 4.dp)) {
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (dirty) {
Text(
text = "\u2022 " + stringResource(R.string.fm_edit_modified),
color = MaterialTheme.colorScheme.primary,
fontSize = 11.sp,
maxLines = 1,
)
}
}
if (loadState == EditorLoadState.READY && lock != EditorLock.NONE) {
Text(
text = stringResource(
if (lock == EditorLock.BINARY) R.string.fm_edit_binary else R.string.fm_edit_read_only,
),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 10.sp,
maxLines = 1,
modifier = Modifier
.background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.small)
.padding(horizontal = 6.dp, vertical = 2.dp),
)
Spacer(Modifier.width(6.dp))
}
IconButton(
onClick = { showSearch = !showSearch },
enabled = loadState == EditorLoadState.READY,
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.Search,
stringResource(R.string.fm_edit_find),
tint = if (showSearch) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(
onClick = { save() },
enabled = loadState == EditorLoadState.READY && !readOnly && dirty && !saving,
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.Save,
stringResource(R.string.fm_edit_save),
tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (showSearch && loadState == EditorLoadState.READY) {
Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainer)) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp, top = 4.dp),
) {
OutlinedTextField(
value = query,
onValueChange = { query = it; matchIndex = 0 },
singleLine = true,
placeholder = { Text(stringResource(R.string.fm_edit_find), fontSize = 13.sp) },
textStyle = MaterialTheme.typography.bodySmall,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { gotoMatch(1) }),
modifier = Modifier.weight(1f).focusGlide(),
)
Text(
text = if (matches.isEmpty()) "0/${matches.size}" else "${matchIndex.coerceAtMost(matches.size - 1) + 1}/${matches.size}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 6.dp).widthIn(min = 44.dp, max = 80.dp),
)
IconButton(
onClick = { gotoMatch(-1) },
enabled = matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.KeyboardArrowUp,
stringResource(R.string.fm_edit_find_previous),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
}
IconButton(
onClick = { gotoMatch(1) },
enabled = matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.KeyboardArrowDown,
stringResource(R.string.fm_edit_find_next),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
}
TextButton(onClick = { matchCase = !matchCase }, modifier = Modifier.focusGlide(CircleShape)) {
Text(
text = "Aa",
color = if (matchCase) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 13.sp,
)
}
IconButton(onClick = { showSearch = false }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
Icons.Filled.Close,
stringResource(R.string.common_cancel),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 2.dp, end = 4.dp, bottom = 2.dp),
) {
OutlinedTextField(
value = replacement,
onValueChange = { replacement = it },
singleLine = true,
placeholder = { Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) },
textStyle = MaterialTheme.typography.bodySmall,
modifier = Modifier.weight(1f).focusGlide(),
)
TextButton(
onClick = { replaceCurrent() },
enabled = !readOnly && matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp)
}
TextButton(
onClick = { replaceAll() },
enabled = !readOnly && matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Text(stringResource(R.string.fm_edit_replace_all), fontSize = 13.sp)
}
}
}
}
Box(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.onSizeChanged { viewportHeight = it.height },
) {
when (loadState) {
EditorLoadState.LOADING -> CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center),
)
EditorLoadState.TOO_LARGE, EditorLoadState.UNREADABLE -> Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.align(Alignment.Center).padding(24.dp),
) {
Text(
text = stringResource(
if (loadState == EditorLoadState.TOO_LARGE) R.string.fm_edit_too_large
else R.string.fm_edit_open_failed,
if (loadState == EditorLoadState.TOO_LARGE) FileOps.formatBytes(context, file.length())
else file.name,
),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 14.sp,
textAlign = TextAlign.Center,
)
}
EditorLoadState.READY -> Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(scrollState),
) {
Row(modifier = Modifier.fillMaxWidth().height(lineHeightDp * totalLines.toFloat())) {
LineNumbers(
scrollState = scrollState,
viewportHeight = viewportHeight,
lineHeightDp = lineHeightDp,
lineHeightPx = lineHeightPx,
totalLines = totalLines,
cursorLine = cursorLine,
style = bodyStyle,
mutedColor = MaterialTheme.colorScheme.onSurfaceVariant,
cursorColor = MaterialTheme.colorScheme.primary,
)
Box(modifier = Modifier.weight(1f).onSizeChanged { viewportWidth = it.width }.horizontalScroll(textHorizontalState)) {
BasicTextField(
value = TextFieldValue(text = text, selection = selection, composition = composing),
onValueChange = { next ->
val changed = next.text != text
text = next.text
selection = next.selection
composing = next.composition
if (changed) dirty = true
},
readOnly = readOnly,
textStyle = bodyStyle,
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
capitalization = KeyboardCapitalization.None,
),
modifier = Modifier.fillMaxHeight().focusGlide(),
)
}
}
}
}
}
if (loadState == EditorLoadState.READY) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
) {
Text(
text = stringResource(R.string.fm_edit_position, cursorLine + 1, cursorColumn),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
)
Spacer(Modifier.weight(1f))
Text(
text = charset.label + " \u2022 " + FileOps.formatBytes(context, file.length()),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
)
}
}
}
}
@Composable
private fun LineNumbers(
scrollState: ScrollState,
viewportHeight: Int,
lineHeightDp: Dp,
lineHeightPx: Float,
totalLines: Int,
cursorLine: Int,
style: TextStyle,
mutedColor: Color,
cursorColor: Color,
modifier: Modifier = Modifier,
) {
val firstLine = (scrollState.value / lineHeightPx).toInt().coerceIn(0, totalLines - 1)
val lastLine = ((scrollState.value + viewportHeight) / lineHeightPx)
.toInt()
.coerceIn(firstLine, totalLines - 1)
Column(
horizontalAlignment = Alignment.End,
modifier = modifier
.width(IntrinsicSize.Min)
.padding(top = lineHeightDp * firstLine.toFloat()),
) {
for (line in firstLine..lastLine) {
Text(
text = (line + 1).toString(),
color = if (line == cursorLine) cursorColor else mutedColor,
textAlign = TextAlign.End,
maxLines = 1,
style = style,
modifier = Modifier.fillMaxWidth().height(lineHeightDp),
)
}
}
}
@@ -47,6 +47,7 @@ object AutoComponents {
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
@VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) }
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
@VisibleForTesting @Volatile internal var runNow = false
@@ -533,6 +534,10 @@ object AutoComponents {
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
fun powerSaveOrMetered(context: Context): Boolean =
context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true ||
context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
fun constrained(context: Context): Boolean {
val power = context.getSystemService(PowerManager::class.java)
if (power?.isPowerSaveMode == true) return true
@@ -20,6 +20,12 @@ object SteamRedists {
val SCRIPTED = mapOf(
72850 to listOf("xact" to "DirectX XACT audio"),
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
// Warband compiles its postFX .fx effects at launch through d3dx9_42; Wine's own d3dcompiler_42 stops with E5017/E5033 on fx_2_0.
48700 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_42" to "D3DCompiler 42"),
// DST's bundled ANGLE compiles SM3 shaders through d3dcompiler_43; DXVK's SM3 parser asserts on what Wine's own one emits.
322330 to listOf("d3dcompiler_43" to "D3DCompiler 43"),
// EU4 builds its map effects through native d3dx9_43, which calls d3dcompiler_43; Wine's own one fails them with E5005, so the map draws black.
236850 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_43" to "D3DCompiler 43"),
)
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
@@ -45,9 +45,8 @@ internal class XrealLink internal constructor(
if (msgId == VitureProtocol.MSG_GET_IMU) return true
val valid = when (msgId) {
VitureProtocol.MSG_GET_DISPLAY -> true
VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ
else value in 2..5 || value == XrealModel.NATIVE_60HZ
VitureProtocol.MSG_BRIGHTNESS -> !model.stereoOnlyControl && value in 0..9
VitureProtocol.MSG_DISPLAY -> model.supportsDisplayMode(value)
VitureProtocol.MSG_BRIGHTNESS -> model.hardwareControls && value in 0..model.brightnessMax
VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1
else -> false
}
@@ -64,12 +63,12 @@ internal class XrealLink internal constructor(
channels = connector.connect()
connection.set(channels)
if (!running) break
val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl)
val control = XrealControl(channels, model = model)
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
val current = channels
reports = Thread({
try {
var filter = XrealOrientationFilter(model.flipsYz)
var filter = XrealOrientationFilter(model)
var wasTracking = false
var lastSensor = System.nanoTime()
while (running && connection.get() === current) {
@@ -78,7 +77,7 @@ internal class XrealLink internal constructor(
if (sample != null) {
lastSensor = System.nanoTime()
val enabled = tracking
if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz)
if (enabled && !wasTracking) filter = XrealOrientationFilter(model)
wasTracking = enabled
if (enabled) filter.update(sample)?.let {
if (running && ready && tracking && connection.get() === current)
@@ -155,8 +154,9 @@ internal class XrealLink internal constructor(
internal class XrealControl(
private val channels: XrealChannels,
private val settleDelayMs: Long = 150,
private val stereoOnly: Boolean = false,
private val model: XrealModel = XrealModel.ONE_S,
) {
private val stereoOnly get() = model.stereoOnlyControl
private var transaction = 0
private fun exchange(command: Int, value: Int? = null): ByteArray {
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
@@ -172,7 +172,7 @@ internal class XrealControl(
fun display(): Int {
if (stereoOnly) return stereoDisplay()
val reply = exchange(XrealProtocol.GET_DISPLAY)
return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ }
return XrealProtocol.numeric(reply)?.takeIf(model::supportsDisplayMode)
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
}
private fun stereoDisplay(): Int {
@@ -187,6 +187,7 @@ internal class XrealControl(
}
}
fun changeDisplay(mode: Int): Int {
require(model.supportsDisplayMode(mode))
val stereo = mode == 5
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
val current = awaitDisplay { (it == 5) == stereo }
@@ -4,6 +4,7 @@ internal class XrealModel private constructor(
override val name: String,
val family: Family,
override val diagonalFovDeg: Float,
private val native60Hz: Int = NATIVE_60HZ,
) : GlassesModel {
enum class Family {
ONE_S,
@@ -14,23 +15,25 @@ internal class XrealModel private constructor(
override val controllable = true
override val brightnessMax = 9
override val volumeMax = 0
override val hasSunblock get() = family == Family.ONE_S
override val hardwareControls get() = family == Family.ONE_S
override val hasSunblock get() = !stereoOnlyControl
override val hardwareControls get() = !stereoOnlyControl
override val sbs90 = false
override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60)
override val rates2d get() = if (stereoOnlyControl) listOf(60) else super.rates2d
// Only the 1S has been exercised with SET_DISPLAY; the Aura is known to reboot on an unexpected index.
val stereoOnlyControl get() = family != Family.ONE_S
val stereoOnlyControl get() = family != Family.ONE_S && this !== ONE_PRO_PLUS
internal fun supportsDisplayMode(mode: Int) = if (stereoOnlyControl) mode == 5 || mode == native60Hz
else mode in 3..5 || mode == native60Hz || (this === ONE_S && mode == 2)
// The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it.
val flipsYz get() = family != Family.AURA
override fun mode(hz: Int, sbs: Boolean) = when {
sbs -> 5
stereoOnlyControl -> NATIVE_60HZ
stereoOnlyControl -> native60Hz
hz >= 120 -> 4
hz >= 90 -> 3
else -> NATIVE_60HZ
else -> native60Hz
}
override fun modeForStep(step: Int): Int? = null
@@ -44,7 +47,7 @@ internal class XrealModel private constructor(
val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f)
val ONE = XrealModel("XREAL One", Family.ONE, 50f)
val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f)
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f)
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f, 9)
val AURA = XrealModel("XREAL Aura", Family.AURA, 70f)
// The odd product ids one below these are the glasses' recovery mode.
@@ -2,13 +2,18 @@ package com.droiddeck.launcher.glasses
import kotlin.math.abs
internal class XrealOrientationFilter(private val flipYz: Boolean = true) {
internal class XrealOrientationFilter(private val model: XrealModel = XrealModel.ONE_S) {
private val fusion = ImuFusion()
private val sensorToDisplay = if (model === XrealModel.ONE_PRO_PLUS)
Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.toRadians(35.0).toFloat()) else null
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
sample.accel.headAxes(), sample.gyro.headAxes())
private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this
private fun Vec3.headAxes(): Vec3 {
val display = sensorToDisplay?.rotate(this) ?: this
return if (model.flipsYz) Vec3(display.x, -display.y, -display.z) else display
}
}
internal class ImuFusion {
@@ -7,7 +7,8 @@ object SocNames {
"SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870",
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
"SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5",
"SM8750" to "Snapdragon 8 Elite", "SM8750P" to "Snapdragon 8 Elite",
"SM8850" to "Snapdragon 8 Elite Gen 5",
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
"SM6375" to "Snapdragon 695",
@@ -23,7 +24,8 @@ object SocNames {
val sdk = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it != Build.UNKNOWN }.orEmpty() else ""
return listOf(prop("ro.soc.model"), prop("ro.vendor.qti.soc_model"), sdk, prop("ro.fota.platform"))
.map { it.trim() }
.firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
.firstOrNull { it.isNotEmpty() && !it.equals(Build.UNKNOWN, ignoreCase = true) && !Regex("(?i)^msm_\\d").containsMatchIn(it) }
.orEmpty()
}
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
@@ -44,6 +44,35 @@ class DroidDeckHudHost(context: Context) {
private var protonPid = 0
private var proton = ""
@Volatile private var lastWindow: String? = null
@Volatile private var lastCompositorFrameNanos = 0L
@Volatile private var lastVisibilityGameActive = false
private var candidateGameActive = false
private var candidateGameActiveSinceNs = 0L
private var stableGameActive = false
private fun isGameActive(): Boolean {
val now = System.nanoTime()
val compositorLive = lastCompositorFrameNanos > 0L &&
now - lastCompositorFrameNanos <= 1_000_000_000L
val detected = if (feed.live) {
feed.steamFocusKnown && !feed.steamFocused
} else {
compositorLive
}
if (detected != candidateGameActive) {
candidateGameActive = detected
candidateGameActiveSinceNs = now
}
if (detected != stableGameActive &&
now - candidateGameActiveSinceNs >= GAME_ACTIVITY_STABLE_NS
) {
stableGameActive = detected
}
return stableGameActive
}
var onPresentingWindowChanged: (() -> Unit)? = null
@@ -66,6 +95,12 @@ class DroidDeckHudHost(context: Context) {
}
override fun onGameFrame() {
if (feed.live && (!feed.steamFocusKnown || feed.steamFocused)) return
lastCompositorFrameNanos = System.nanoTime()
feed.onCompositorFrame(lastCompositorFrameNanos)
}
override fun onCompositorFrame() {
feed.onCompositorFrame(System.nanoTime())
}
}
@@ -73,7 +108,9 @@ class DroidDeckHudHost(context: Context) {
private val frameCallback = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
if (!running || !polling) return
reconcileGameActivity()
if (feed.poll(System.nanoTime())) view?.onFrames()
reconcileGameActivity()
Choreographer.getInstance().postFrameCallback(this)
}
}
@@ -151,7 +188,7 @@ class DroidDeckHudHost(context: Context) {
fun refresh() {
applyConfig()
if (!enabled) stop() else if (!running) start()
if (!enabled) stop() else if (!running) start() else applyShown()
}
fun start() {
@@ -181,14 +218,26 @@ class DroidDeckHudHost(context: Context) {
applyShown()
}
private fun reconcileGameActivity() {
if (!SessionPrefs.hudOnlyDuringGame(context)) {
lastVisibilityGameActive = isGameActive()
return
}
if (isGameActive() != lastVisibilityGameActive) applyShown()
}
private fun applyShown() {
if (!running) return
val show = !hidden && !backgrounded
val onlyDuringGame = SessionPrefs.hudOnlyDuringGame(context)
val gameActive = isGameActive()
val show = !hidden && !backgrounded && (!onlyDuringGame || gameActive)
view?.visibility = if (show) View.VISIBLE else View.GONE
showing = show
if (show != polling) {
polling = show
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
lastVisibilityGameActive = gameActive
val shouldPoll = !hidden && !backgrounded && (show || onlyDuringGame)
if (shouldPoll != polling) {
polling = shouldPoll
if (shouldPoll) Choreographer.getInstance().postFrameCallback(frameCallback)
else Choreographer.getInstance().removeFrameCallback(frameCallback)
}
}
@@ -532,6 +581,7 @@ class DroidDeckHudHost(context: Context) {
}
companion object {
private const val GAME_ACTIVITY_STABLE_NS = 350_000_000L
private const val DOCK_OVERHANG = 0.4f
private const val PREVIEW_FROM = 0.55f
private const val STRIP_PULL_ACROSS_DP = 360f
@@ -183,6 +183,8 @@ internal class GameFrameFeed(
private set
@Volatile var steamFocused = false
private set
@Volatile var steamFocusKnown = false
private set
@Volatile var pid = 0
private set
@Volatile var outputWidth = 0
@@ -198,10 +200,16 @@ internal class GameFrameFeed(
val compositorAdded = compositorFrames != seenCompositorFrames
seenCompositorFrames = compositorFrames
if (handle == 0L) {
if (nowNs < nextOpenNs) return compositorAdded
if (nowNs < nextOpenNs) {
return compositorAdded
}
nextOpenNs = nowNs + REOPEN_NS
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
if (handle == 0L) return compositorAdded
if (handle == 0L) {
return compositorAdded
}
HudFrames.nativePoll(handle, frametimes, times)
}
val n = HudFrames.nativePoll(handle, frametimes, times)
@@ -219,6 +227,7 @@ internal class GameFrameFeed(
fromGamescope = false
}
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
if (nowNs - lastInfoNs >= INFO_NS) {
lastInfoNs = nowNs
readInfo()
@@ -250,6 +259,7 @@ internal class GameFrameFeed(
}
fun close() {
fromGamescope = false
if (handle != 0L) HudFrames.nativeClose(handle)
handle = 0L
}
@@ -265,6 +275,7 @@ internal class GameFrameFeed(
outputHeight = info[2]
refreshMilliHz = info[3]
steamFocused = info[4] != 0
steamFocusKnown = true
engine = engineLabel(name)
}
@@ -0,0 +1,182 @@
package com.droiddeck.launcher.input
import android.graphics.Rect
import android.util.DisplayMetrics
import kotlin.math.max
import kotlin.math.min
internal class ControllerOverlayGeometry(
width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float,
) {
private val w = width.toFloat()
private val h = height.toFloat()
private val density = metrics.density
private val dpi = metrics.ydpi.takeIf { it in metrics.densityDpi * .6f..metrics.densityDpi * 1.6f }
?: metrics.densityDpi.toFloat()
private val fit = minOf(
min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)),
(w - safe.left - safe.right).coerceAtLeast(1f) / 1200f,
(h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f,
)
private val unit = fit * min(scale, 1f)
private val size = fit * scale
private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float {
val low = start + value * unit
val high = extent - end - (reference - value) * unit
return when {
value < reference / 3f -> low
value > reference * 2f / 3f -> high
else -> (extent / 2f + (value - reference / 2f) * unit).coerceIn(low, max(low, high))
}
}
private fun x(ref: Float) = anchor(ref, 1600f, w, safe.left, safe.right)
private fun y(ref: Float) = max(safe.top + ref * unit, h - safe.bottom - (900f - ref) * unit)
fun place(elements: List<InputSurfaceElement>, kit: PadKit, rearButtons: Boolean, trackpads: Boolean): List<InputSurfaceElement> {
if (!kit.steam) return placeStandardPad(elements, kit)
val leftEdge = safe.left + 52f * density
val middle = (w + safe.left - safe.right) / 2f
val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
val row = fitRow(listOfNotNull(keyboard,
Box(max(x(370f), leftEdge + 66f * size), y(852f), 66f, 30f),
Box(middle - 140f * unit, y(850f), 46f, 26f),
Box(middle + 140f * unit, y(850f), 46f, 26f),
Box(x(1230f), y(852f), 66f, 30f)), leftEdge)
val (guide, select, start, qam) = row.takeLast(4)
val positions = shoulders() + face(1375f, 345f, 96f) + mapOf(
InputControl.UP to Box(x(220f), y(345f) - 102.5f * size, 55.5f, 47.5f),
InputControl.RIGHT to Box(x(220f) + 102.5f * size, y(345f), 47.5f, 55.5f),
InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * size, 55.5f, 47.5f),
InputControl.LEFT to Box(x(220f) - 102.5f * size, y(345f), 47.5f, 55.5f),
InputControl.LS to Box(x(290f), y(640f), 96f),
InputControl.RS to Box(x(1310f), y(640f), 96f),
InputControl.SELECT to select,
InputControl.START to start,
InputControl.GUIDE to guide,
InputControl.QAM to qam,
)
val rear = mapOf(
InputControl.L4 to Box(x(30f), y(470f), 30f, 58f),
InputControl.L5 to Box(x(30f), y(590f), 30f, 58f),
InputControl.R4 to Box(x(1570f), y(470f), 30f, 58f),
InputControl.R5 to Box(x(1570f), y(590f), 30f, 58f),
)
val pads = mapOf(
InputControl.LEFT_PAD to Box(x(470f), y(360f), 88f),
InputControl.RIGHT_PAD to Box(x(1130f), y(360f), 88f),
)
val optional = rear.filterKeys { rearButtons } + pads.filterKeys { trackpads }
val placed = elements.mapNotNull { element ->
when {
element.id == KEYBOARD -> row.first().place(element)
element.id != "legacy:${element.control.id}" -> element
element.control in rear || element.control in pads -> optional[element.control]?.place(element)
else -> positions[element.control]?.place(element) ?: element
}
}
val chosen = placed.filter { it.id == "legacy:${it.control.id}" }.map { it.control }
return placed + optional.mapNotNull { (control, box) ->
if (chosen.any { if (control in rear) it in rear else it in pads }) null else box.place(InputSurfaceElement(control,
0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad))
}
}
private fun placeStandardPad(elements: List<InputSurfaceElement>, kit: PadKit): List<InputSurfaceElement> {
val leftEdge = safe.left + 52f * density
val middle = (w + safe.left - safe.right) / 2f
val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
val controls = if (kit.playStation) listOf(
InputControl.QAM to Box(x(220f), y(848f), 46f),
InputControl.SELECT to Box(middle - 160f * unit, y(850f), 50f, 30f),
InputControl.GUIDE to Box(middle, y(850f), 46f),
InputControl.START to Box(middle + 160f * unit, y(850f), 50f, 30f),
) else listOf(
InputControl.QAM to Box(x(220f), y(848f), 46f),
InputControl.SELECT to Box(middle - 110f * unit, y(850f), 38f),
InputControl.GUIDE to Box(middle, y(850f), 46f),
InputControl.START to Box(middle + 110f * unit, y(850f), 38f),
)
val row = fitRow(listOfNotNull(keyboard) + controls.map { it.second }, leftEdge)
val positions = controls.map { it.first }.zip(row.takeLast(controls.size)).toMap() + shoulders() +
if (kit.playStation) {
face(1350f, 395f, 96f) + dpad(250f, 395f, 125f, kit.dpad) + mapOf(
InputControl.LS to Box(x(565f), y(690f), 100f),
InputControl.RS to Box(x(1035f), y(690f), 100f),
InputControl.L3 to Box(x(565f) - 135f * size, y(690f) - 100f * size, 42f),
InputControl.R3 to Box(x(1035f) + 135f * size, y(690f) - 100f * size, 42f),
)
} else {
face(1375f, 400f, 94f) + dpad(470f, 675f, 118f, kit.dpad) + mapOf(
InputControl.LS to Box(x(235f), y(400f), 104f),
InputControl.RS to Box(x(1130f), y(690f), 104f),
InputControl.L3 to Box(x(235f) + 150f * size, y(400f) - 110f * size, 42f),
InputControl.R3 to Box(x(1130f) + 160f * size, y(690f) + 100f * size, 42f),
)
}
return elements.map { element ->
when (element.id) {
KEYBOARD -> row.first().place(element)
"legacy:${element.control.id}" -> positions[element.control]?.place(element) ?: element
else -> element
}
}
}
private fun shoulders() = mapOf(
InputControl.LT to Box(x(120f), y(96f), 80f, 34f),
InputControl.LB to Box(x(310f), y(96f), 80f, 34f),
InputControl.RB to Box(x(1290f), y(96f), 80f, 34f),
InputControl.RT to Box(x(1480f), y(96f), 80f, 34f),
)
private fun face(cx: Float, cy: Float, offset: Float) = mapOf(
InputControl.Y to Box(x(cx), y(cy) - offset * size, 58f),
InputControl.X to Box(x(cx) - offset * size, y(cy), 58f),
InputControl.B to Box(x(cx) + offset * size, y(cy), 58f),
InputControl.A to Box(x(cx), y(cy) + offset * size, 58f),
)
private fun dpad(cx: Float, cy: Float, radius: Float, style: DpadStyle): Map<InputControl, Box> {
val inner = radius * if (style == DpadStyle.DISC) .25f else .14f
val depth = (radius - inner) / 2f
val offset = (radius - depth) * size
val side = radius * .25f
return mapOf(
InputControl.UP to Box(x(cx), y(cy) - offset, side, depth),
InputControl.RIGHT to Box(x(cx) + offset, y(cy), depth, side),
InputControl.DOWN to Box(x(cx), y(cy) + offset, side, depth),
InputControl.LEFT to Box(x(cx) - offset, y(cy), depth, side),
)
}
private fun fitRow(row: List<Box>, start: Float): List<Box> {
val end = w - safe.right
val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density)
var edge = start - gap
val pushed = row.map { box -> box.at(max(box.cx, edge + gap + box.width / 2f)).also { edge = it.cx + it.width / 2f } }
edge = end + gap
return pushed.asReversed().map { box -> box.at(min(box.cx, edge - gap - box.width / 2f)).also { edge = it.cx - it.width / 2f } }.asReversed()
}
private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) {
val width get() = max(hw * 2f * size, w * .03f)
fun at(cx: Float) = Box(cx, cy, hw, hh)
fun place(element: InputSurfaceElement): InputSurfaceElement {
val height = max(hh * 2f * size, h * .03f)
return element.copy(
x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w,
y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h,
width = width / w, height = height / h,
).bounded()
}
}
private companion object {
const val KEYBOARD = "builtin:keyboard"
}
}
@@ -0,0 +1,127 @@
package com.droiddeck.launcher.input
import android.graphics.Rect
import com.droiddeck.launcher.input.GamepadGeometry.Box
import kotlin.math.min
internal class ControllerPortraitGeometry(
private val width: Float,
private val height: Float,
private val safe: Rect,
private val density: Float,
) {
fun place(
elements: List<InputSurfaceElement>, kit: PadKit, docked: Boolean, scale: Float,
rearButtons: Boolean, trackpads: Boolean,
): List<InputSurfaceElement> {
val w = width - safe.left - safe.right
val h = height - safe.top - safe.bottom
if (w <= 0 || h <= 0) return elements
val presented = elements.toMutableList()
val buttons = mutableMapOf<String, Box>()
val rear = presented.filter { it.control in REAR && isStock(it) }
val pads = presented.filter { it.control.isTrackpad && isStock(it) }
if (!docked && kit.steam) {
if (!rearButtons) presented.removeAll(rear) else if (rear.isEmpty()) REAR.forEach { addOptional(presented, it) }
if (!trackpads) presented.removeAll(pads) else if (pads.isEmpty()) {
addOptional(presented, InputControl.LEFT_PAD)
addOptional(presented, InputControl.RIGHT_PAD)
}
}
fun put(control: InputControl, box: Box) { buttons["legacy:${control.id}"] = box }
val reserve = if (docked) 0f else min(60f * density, h * .15f)
val panel = if (docked) h else min(minOf(h * .60f, w * 1.15f, PANEL_DP * density) * scale, h - reserve)
val top = height - safe.bottom - reserve - panel
val unit = min(density, min(w / 275f, panel / 300f))
val pad = 8f * unit
val gap = 8f * unit
val buttonHeight = 44f * unit
val shoulders = if (docked) listOf(InputControl.LT, InputControl.LB, InputControl.SELECT, InputControl.START, InputControl.RB, InputControl.RT)
else listOf(InputControl.LT, InputControl.LB, InputControl.RB, InputControl.RT)
fun row(controls: List<InputControl>, y: Float, rowHeight: Float, spacing: Float) {
val cell = (w - 2f * pad - (controls.size - 1) * spacing) / controls.size
controls.forEachIndexed { index, control ->
put(control, Box(safe.left + pad + cell / 2f + index * (cell + spacing), y, cell, rowHeight))
}
}
row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit)
var bodyTop = top + pad + buttonHeight + gap
if (presented.any { it.control in REAR && isStock(it) }) {
val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight)
row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap)
bodyTop += rearHeight + gap
}
val floor = height - safe.bottom - reserve - pad
val bodyHeight = floor - bodyTop - gap
if (bodyHeight <= 0f) return elements
val hasLeftPad = presented.any { it.control == InputControl.LEFT_PAD && isStock(it) }
val hasRightPad = presented.any { it.control == InputControl.RIGHT_PAD && isStock(it) }
val hasLeftStick = presented.any { it.control == InputControl.LS && isStock(it) }
val hasRightStick = presented.any { it.control == InputControl.RS && isStock(it) }
val four = hasLeftPad && hasLeftStick || hasRightPad && hasRightStick
val main = min(w * .46f, bodyHeight * .53f)
val second = min(w * .42f, bodyHeight - main)
val mainY = floor - main / 2f
val secondY = bodyTop + second / 2f
val left = safe.left + w * .25f
val right = safe.left + w * .75f
if (four) {
val col = (w - 2f * pad - 3f * gap) / 4f
val stick = min(col, main)
put(InputControl.LEFT_PAD, Box(safe.left + pad + col * .5f, mainY, col, main))
put(InputControl.LS, Box(safe.left + pad + col * 1.5f + gap, mainY, stick, stick))
put(InputControl.RS, Box(safe.left + w - pad - col * 1.5f - gap, mainY, stick, stick))
put(InputControl.RIGHT_PAD, Box(safe.left + w - pad - col * .5f, mainY, col, main))
} else {
put(if (hasLeftPad) InputControl.LEFT_PAD else InputControl.LS, Box(left, mainY, main, main))
put(if (hasRightPad) InputControl.RIGHT_PAD else InputControl.RS, Box(right, mainY, main, main))
}
val radius = second / 2f
val armWidth = radius * if (kit.dpad == DpadStyle.CROSS) .37f else .25f
val inner = if (kit.dpad == DpadStyle.ARROWS) radius * .14f else armWidth
val depth = radius - inner
val distance = (radius + inner) / 2f
put(InputControl.UP, Box(left, secondY - distance, armWidth * 2f, depth))
put(InputControl.RIGHT, Box(left + distance, secondY, depth, armWidth * 2f))
put(InputControl.DOWN, Box(left, secondY + distance, armWidth * 2f, depth))
put(InputControl.LEFT, Box(left - distance, secondY, depth, armWidth * 2f))
val face = second * .34f
val spread = second * .30f
put(InputControl.Y, Box(right, secondY - spread, face, face))
put(InputControl.X, Box(right - spread, secondY, face, face))
put(InputControl.B, Box(right + spread, secondY, face, face))
put(InputControl.A, Box(right, secondY + spread, face, face))
if (!docked) {
val ids = listOf(KEYBOARD, "legacy:guide", "legacy:select", "legacy:start", "legacy:qam")
.filter { id -> presented.any { it.id == id } }
val inset = min(52f * density, w * .17f)
val rowWidth = (w - inset - pad - gap * (ids.size - 1)) / ids.size.coerceAtLeast(1)
val rowHeight = min(reserve * .8f, 44f * unit)
ids.forEachIndexed { i, id ->
val center = safe.left + inset + rowWidth / 2f + i * (rowWidth + gap)
buttons[id] = Box(center, height - safe.bottom - reserve / 2f, rowWidth, rowHeight)
}
}
return presented.map { element ->
val box = buttons[element.id]
if (box == null) element else element.copy(
x = box.left / width, y = box.top / height, width = box.width / width, height = box.height / height,
).bounded()
}
}
private fun isStock(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}"
private fun addOptional(elements: MutableList<InputSurfaceElement>, control: InputControl) {
if (elements.none { it.control == control && isStock(it) }) {
elements += InputSurfaceElement(control, 0f, 0f, 0f, 0f, floating = false,
buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad)
}
}
private companion object {
const val KEYBOARD = "builtin:keyboard"
const val PANEL_DP = 504f
val REAR = listOf(InputControl.L4, InputControl.L5, InputControl.R5, InputControl.R4)
}
}
@@ -14,7 +14,8 @@ object DualScreen {
const val MODE_AUTO = "auto"
const val MODE_ON = "on"
const val MODE_OFF = "off"
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
const val MODE_SWAPPED = "swapped"
val modes = listOf(MODE_AUTO, MODE_ON, MODE_SWAPPED, MODE_OFF)
private const val TYPE_INTERNAL = 1
private const val TYPE_EXTERNAL = 2
private val knownModels = setOf("retroid pocket duo", "ayn thor")
@@ -23,6 +24,14 @@ object DualScreen {
@Volatile private var takenDisplays: Set<Int> = emptySet()
private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
fun menuOwnsController(open: Boolean, docked: Boolean, optIn: Boolean): Boolean = open && (!docked || optIn)
fun menuReturnsOnStart(selected: SecondScreenMode, menuWasShown: Boolean, menuUp: Boolean): Boolean =
!menuUp && (selected == SecondScreenMode.MENU || menuWasShown)
fun menuIdleOnBottom(open: Boolean, docked: Boolean, pinned: Boolean, optIn: Boolean): Boolean =
docked && (open || pinned) && !menuOwnsController(open, docked, optIn)
fun yieldsBottom(model: String): Boolean = model.trim().lowercase().let { m -> knownModels.any(m::startsWith) }
fun taken(displayId: Int): Boolean = displayId in takenDisplays
@@ -91,7 +100,7 @@ object DualScreen {
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
when (mode) {
MODE_OFF -> null
MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
MODE_ON, MODE_SWAPPED -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
else -> if (dockedToDisplay(displayManager, primaryDisplayId)) null else builtInDisplay(displayManager, primaryDisplayId)
}?.takeUnless { taken(it.displayId) }
@@ -27,8 +27,9 @@ internal class FloatingSteamOverlay(width: Int, height: Int, safe: Rect, density
val lowered = if (lowerShortcuts) lower(visible) else visible
if (rearButtons != true && trackpads != true) return lowered
val placed = lowered.toMutableList()
val chosen = lowered.filter(::isStock).map { it.control }
fun add(control: InputControl, x: Float, y: List<Float>, widthDp: Int, heightDp: Int, shape: InputButtonShape) {
if (placed.any { it.id == "legacy:${control.id}" }) return
if (chosen.any { if (control in rear) it in rear else it.isTrackpad }) return
val element = InputSurfaceElement(control, 0f, 0f, (widthDp * dp / w).coerceAtLeast(.03f),
(heightDp * dp / h).coerceAtLeast(.03f), floating = false, buttonShape = shape, showLabel = !control.isTrackpad)
findSpace(element, x, y, placed)?.let(placed::add)
@@ -3,6 +3,12 @@ package com.droiddeck.launcher.input
import android.view.KeyEvent
object GuestKeys {
fun normalizeKeyboardEscape(event: KeyEvent): KeyEvent {
if (!isKeyboardEscape(event.keyCode, event.scanCode)) return event
return KeyEvent(event.downTime, event.eventTime, event.action, KeyEvent.KEYCODE_ESCAPE,
event.repeatCount, event.metaState, event.deviceId, event.scanCode, event.flags, event.source)
}
/** Sends [event] as evdev presses, with Shift around characters typed by a keyboard that has no Shift key; false when it has no evdev code. */
fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean {
val down = event.action == KeyEvent.ACTION_DOWN
@@ -324,15 +324,27 @@ object InputLibraries {
layout.copy(screen = screen)
})
private fun encodeElements(list: List<InputSurfaceElement>) = JSONArray().also { elements ->
for (e in list) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
}
private fun decodeElements(array: JSONArray) = array.objects(64).map { e ->
InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
}
internal fun encode(library: InputLibrary): String {
val layouts = JSONArray()
for (layout in library.layouts) {
val elements = JSONArray()
for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
val encoded = JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", encodeElements(layout.elements))
if (layout.rotated.isNotEmpty()) encoded.put("rotated", encodeElements(layout.rotated)).put("rotatedAspect", layout.rotatedAspect.toDouble()).put("rotatedScale", layout.rotatedScale.toDouble())
layouts.put(encoded
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
}
@@ -371,13 +383,7 @@ object InputLibraries {
require(version in 2..VERSION || restore)
val generated = mutableSetOf<String>()
val layouts = doc.getJSONArray("layouts").objects(256).map { layout ->
val stored = layout.getJSONArray("elements").objects(64).map { e ->
InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
}
val stored = decodeElements(layout.getJSONArray("elements"))
val id = layout.getString("id")
val origin = layout.optionalString("origin")
val followsGamepad = restore && !layout.optBoolean("kitless") &&
@@ -388,7 +394,8 @@ object InputLibraries {
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin,
layout.optDouble("scale", 1.0).toFloat())
layout.optDouble("scale", 1.0).toFloat(), layout.optJSONArray("rotated")?.let(::decodeElements).orEmpty(),
layout.optDouble("rotatedAspect", 0.0).toFloat(), layout.optDouble("rotatedScale", layout.optDouble("scale", 1.0)).toFloat())
}
val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
@@ -22,8 +22,12 @@ data class SavedInputLayout(
val aspect: Float = 0f,
val origin: String? = null,
val scale: Float = 1f,
val rotated: List<InputSurfaceElement> = emptyList(),
val rotatedAspect: Float = 0f,
val rotatedScale: Float = 1f,
) {
val editable get() = template == InputLayoutTemplate.CUSTOM
val overlay get() = (origin ?: id).let { it == InputLibraries.OVERLAY || it.startsWith("migrated.layout.") }
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
fun withQuickButton(button: InputCommand, shown: Boolean) =
copy(style = style.copy(hidden = if (shown) style.hidden - button else style.hidden + button))
@@ -249,6 +253,8 @@ data class InputLibrary(
for (layout in layouts) {
require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS })
require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f)
require(layout.rotated.isEmpty() || layout.rotatedAspect.isFinite() && layout.rotatedAspect in .05f..20f && layout.rotatedScale.isFinite() && layout.rotatedScale in .5f..2f)
require(layout.rotated.size <= 64 && layout.rotated.all { r -> listOf(r.x, r.y, r.width, r.height).all { it.isFinite() } })
require(layout.scale.isFinite() && layout.scale in .5f..2f)
inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id })
for (e in layout.elements) {
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.input
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import kotlin.math.max
import kotlin.math.min
enum class InputElementKind(val control: InputControl) {
BUTTON(InputControl.A), STICK(InputControl.LS), TRACKPAD(InputControl.LEFT_PAD),
@@ -63,6 +65,27 @@ internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceE
width = w, height = h).bounded()
}
internal val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
internal val InputSurfaceElement.dpadPiece get() = id == "legacy:${control.id}" && control in DPAD
internal fun List<InputSurfaceElement>.groupOf(e: InputSurfaceElement) = if (e.dpadPiece) filter { it.dpadPiece } else listOf(e)
internal fun List<InputSurfaceElement>.frame(): InputSurfaceElement {
val left = minOf { it.x }; val top = minOf { it.y }
return first().copy(x = left, y = top, width = maxOf { it.x + it.width } - left, height = maxOf { it.y + it.height } - top)
}
internal fun List<InputSurfaceElement>.resizedAroundCentre(factor: Float): List<InputSurfaceElement> {
if (isEmpty()) return this
val f = frame()
val k = factor.coerceIn(.03f / minOf { min(it.width, it.height) }, 1f / max(f.width, f.height))
val w = f.width * k; val h = f.height * k
val left = (f.x + f.width / 2 - w / 2).coerceIn(0f, 1f - w)
val top = (f.y + f.height / 2 - h / 2).coerceIn(0f, 1f - h)
return map { it.copy(x = left + (it.x - f.x) * k, y = top + (it.y - f.y) * k, width = it.width * k, height = it.height * k).bounded() }
}
internal fun List<InputSurfaceElement>.withPositionsOf(defaults: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = defaults.associateBy { it.id }
return map { e -> byId[e.id]?.let { d -> e.copy(x = d.x, y = d.y, width = d.width, height = d.height).bounded() } ?: e }
@@ -197,19 +197,8 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> {
val before = from.elements().associateBy { it.id }
val after = elements().associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val w = (a.width * e.width / b.width).coerceIn(.03f, 1f)
val h = (a.height * e.height / b.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> =
rescaleBetween(stored, from.elements(), elements())
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
val inset = dp(BUTTONS_ONLY_INSET_DP)
@@ -345,7 +334,6 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
const val STICK_REACH = 1.25f
const val LEGACY_DPAD_RADIUS_DP = 26f
const val LEGACY_DPAD_OFFSET_DP = 52f
val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
const val KEYBOARD_ID = "builtin:keyboard"
const val KEYBOARD_RADIUS_DP = 18f
const val KEYBOARD_X_DP = 90f
@@ -360,3 +348,22 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
}
}
internal fun rescaleBetween(stored: List<InputSurfaceElement>, from: List<InputSurfaceElement>, to: List<InputSurfaceElement>,
sizeFrom: List<InputSurfaceElement> = from, sizeTo: List<InputSurfaceElement> = to): List<InputSurfaceElement> {
val before = from.associateBy { it.id }
val after = to.associateBy { it.id }
val smaller = sizeFrom.associateBy { it.id }
val larger = sizeTo.associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val sb = smaller[e.id] ?: b
val sa = larger[e.id] ?: a
val w = (sa.width * e.width / sb.width).coerceIn(.03f, 1f)
val h = (sa.height * e.height / sb.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
@@ -14,9 +14,6 @@ import android.view.View
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.ui.InputSurfaceView
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
@@ -75,15 +72,15 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
render()
}
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean,
val kit: PadKit?, val optional: Pair<Boolean?, Boolean?>)
private fun placed(): List<InputSurfaceElement> {
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
val optional = OnScreenLayout.optionalControls(context)
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly, PadKit.forOverlay(context, layout), optional)
return placements.getOrPut(key) {
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock,
rearButtons = SessionPrefs.oscRearButtons(context).takeIf { steam },
trackpads = SessionPrefs.oscTrackpads(context).takeIf { steam })
rearButtons = optional.first, trackpads = optional.second)
}
}
@@ -100,9 +97,9 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
private fun refreshAppearance() {
val style = layout?.style ?: InputSurfaceStyle()
val deck = dock == null && OnScreenLayout.usesSteamDeckButtons(context, layout)
surface.updateStyle(style, steamDeckButtons = deck)
quickToggle.tint = style.tint.takeUnless { deck }
val artwork = PadKit.forOverlay(context, layout)
surface.updateStyle(style, artwork)
quickToggle.tint = style.tint.takeUnless { artwork != null }
quickToggle.alpha = style.opacity / 100f
quickToggle.invalidate()
}
@@ -136,7 +133,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
params.bottomMargin = bottom
quickToggle.layoutParams = params
}
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
val fresh = OnScreenLayout.safeInsets(insets, dock != null)
if (fresh != safe) {
safe.set(fresh)
render()
@@ -3,17 +3,16 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
object OnScreenLayout {
internal fun usesSteamDeckButtons(context: Context, layout: SavedInputLayout?) =
layout?.id == InputLibraries.OVERLAY && SessionPrefs.steamController(context) == SessionPrefs.CONTROLLER_DECK
internal fun supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) =
layout?.id == InputLibraries.OVERLAY &&
layout?.overlay == true &&
(controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM)
data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) {
@@ -31,41 +30,96 @@ object OnScreenLayout {
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
private val REAR = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
private val BAR = setOf(InputControl.GUIDE, InputControl.QAM)
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
trackpads: Boolean? = null): List<InputSurfaceElement> {
val stored = layout?.elements ?: return emptyList()
if (width <= 0 || height <= 0) return stored
if (saved == null) return emptyList()
if (width <= 0 || height <= 0) return saved.elements
val layout = oriented(saved, dock?.portrait ?: (height > width))
val stored = layout.elements
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
val (reference, generated) = reference(context, layout, width, height)
val (reference, matched) = reference(context, layout, width, height)
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
if (dock?.portrait == true && !dock.grips && !matched && layout.aspect > 0f && layout.aspect < 1f && stored.any(::isGamepad))
return cluster(stored.filterNot { it.alwaysShown || isGamepad(it) && (it.id == KEYBOARD_ID || it.control in BAR) }, layout.aspect, width, height, safe)
val generated = matched || PadKit.forOverlay(context, layout) != null && stored.any(::isGamepad) &&
(dock != null || height > width && layout.aspect >= 1f || height <= width && layout.aspect > 0f && layout.aspect < 1f)
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
val placed = when {
val regenerated = when {
gamepad.isEmpty() -> emptyList()
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
else -> generator.regenerate(gamepad)
}
val placed = regenerated + gamepad.filter { g -> dock == null && optional(g) && regenerated.none { it.id == g.id } }
val byId = (placed + others).associateBy { it.id }
val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
if (dock != null || !supportsFloatingSteamControls(SessionPrefs.steamController(context), layout)) return ordered
if (generated && width >= height && usesSteamDeckButtons(context, layout) &&
val kit = PadKit.forOverlay(context, layout) ?: return ordered
if (generated &&
ControllerPrefs.layout(context, reference.first.toInt(), reference.second.toInt()).isEmpty() &&
ControllerPrefs.layout(context, width, height).isEmpty()) {
return SteamDeckOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale)
.place(ordered, rearButtons == true, trackpads == true)
if (dock != null || height > width) {
return ControllerPortraitGeometry(width.toFloat(), height.toFloat(), safe, context.resources.displayMetrics.density)
.place(ordered, kit, dock != null, layout.scale, rearButtons == true, trackpads == true)
}
return ControllerOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale)
.place(ordered, kit, rearButtons == true, trackpads == true)
}
if (dock != null || !kit.steam) return ordered
return FloatingSteamOverlay(width, height, safe, context.resources.displayMetrics.density)
.place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads)
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect())
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout = oriented(layout, height > width)
private fun oriented(layout: SavedInputLayout, portrait: Boolean): SavedInputLayout {
if (layout.rotated.isEmpty() || layout.aspect <= 0f || (layout.aspect < 1f) == portrait || (layout.rotatedAspect < 1f) != portrait) return layout
val rotated = layout.rotated.associateBy { it.id }
return layout.copy(elements = layout.elements.map { e -> rotated[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } ?: e } +
layout.rotated.filter { r -> optional(r) && layout.elements.none { it.id == r.id } },
aspect = layout.rotatedAspect, scale = layout.rotatedScale, rotated = emptyList(), rotatedAspect = 0f, rotatedScale = 1f)
}
fun withFrame(context: Context, saved: SavedInputLayout, elements: List<InputSurfaceElement>, aspect: Float, scale: Float = saved.scale): SavedInputLayout {
val (_, metrics) = InputLibraries.primaryDisplay(context)
val generated = generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels) != null
val portraitMain = saved.aspect > 0f && saved.aspect < 1f
if (aspect <= 0f || aspect >= 1f || portraitMain && !generated) {
val rotated = if (aspect >= 1f && portraitMain && !generated) Triple(saved.elements, saved.aspect, saved.scale) else Triple(saved.rotated, saved.rotatedAspect, saved.rotatedScale)
return saved.copy(elements = elements, aspect = aspect, scale = scale, rotated = rotated.first,
rotatedAspect = if (rotated.first.isEmpty()) 0f else rotated.second, rotatedScale = if (rotated.first.isEmpty()) 1f else rotated.third)
}
val main = if (portraitMain) 1f / saved.aspect else saved.aspect.takeIf { it > 0f } ?: (1f / aspect)
val ids = elements.associateBy { it.id }
val kept = saved.elements.mapNotNull { e -> ids[e.id]?.copy(x = e.x, y = e.y, width = e.width, height = e.height) }
val added = fit(elements.filter { d -> !optional(d) && saved.elements.none { it.id == d.id } }, aspect, 1f, (main * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
return saved.copy(elements = kept + added, aspect = main, rotated = elements, rotatedAspect = aspect, rotatedScale = scale)
}
fun optionalControls(context: Context): Pair<Boolean?, Boolean?> {
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
return SessionPrefs.oscRearButtons(context).takeIf { steam } to SessionPrefs.oscTrackpads(context).takeIf { steam }
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false, safe: Rect = Rect()): List<InputSurfaceElement> {
val (rear, pads) = optionalControls(context)
return elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, safe,
rearButtons = rear, trackpads = pads)
}
fun editorFrame(layout: SavedInputLayout, displayed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = displayed.associateBy { it.id }
return layout.elements.map { byId[it.id] ?: it }
return layout.elements.map { byId[it.id] ?: it } + displayed.filter { d ->
optional(d) && layout.elements.none { it.id == d.id }
}
}
fun safeInsets(insets: android.view.WindowInsets?, docked: Boolean): Rect {
val cutout = if (android.os.Build.VERSION.SDK_INT >= 28) insets?.displayCutout else null
return Rect(cutout?.safeInsetLeft ?: 0, if (docked) 0 else cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
}
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
@@ -81,6 +135,23 @@ object OnScreenLayout {
}
}
private fun cluster(elements: List<InputSurfaceElement>, aspect: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
if (elements.isEmpty()) return elements
val left = elements.minOf { it.x } * aspect
val top = elements.minOf { it.y }
val spanX = (elements.maxOf { it.x + it.width } * aspect - left).coerceAtLeast(.0001f)
val spanY = (elements.maxOf { it.y + it.height } - top).coerceAtLeast(.0001f)
val w = (width - safe.left - safe.right).toFloat().coerceAtLeast(1f)
val h = (height - safe.top - safe.bottom).toFloat().coerceAtLeast(1f)
val scale = minOf(w / aspect, w / spanX, h / spanY)
val originX = safe.left + (w - spanX * scale) / 2f - left * scale
val originY = safe.top + (h - spanY * scale) / 2f - top * scale
return elements.map { e ->
e.copy(x = (originX + e.x * aspect * scale) / width, y = (originY + e.y * scale) / height,
width = e.width * aspect * scale / width, height = e.height * scale / height)
}
}
private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float {
val centre = start + size / 2f
val scaled = size * reference * scale
@@ -91,6 +162,8 @@ object OnScreenLayout {
}
}
private fun optional(e: InputSurfaceElement) = e.id == "legacy:${e.control.id}" && (e.control.isTrackpad || e.control in REAR)
private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
@@ -104,7 +177,7 @@ object OnScreenLayout {
if (gamepad.any { it.id.startsWith("legacy:") }) {
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f }
val aspectSize = layout.aspect.takeIf { layout.overlay && it > 0f }
?.let { (it * height).roundToInt().coerceAtLeast(1) to height }
for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) {
val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale)
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
internal enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS }
internal enum class DpadStyle { CROSS, DISC, ARROWS }
internal enum class StickCap { RINGED, DISHED, KNURLED }
internal enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) {
STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true),
DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED),
DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED);
val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER
val playStation get() = this == DUALSHOCK || this == DUALSENSE
fun label(control: InputControl): String = when (control) {
InputControl.LB -> if (xbox) "LB" else "L1"
InputControl.RB -> if (xbox) "RB" else "R1"
InputControl.LT -> if (xbox) "LT" else "L2"
InputControl.RT -> if (xbox) "RT" else "R2"
else -> control.label
}
/** What the player calls [control] on this controller. */
fun name(control: InputControl): String = if (!playStation) label(control) else when (control) {
InputControl.A -> "Cross"
InputControl.B -> "Circle"
InputControl.X -> "Square"
InputControl.Y -> "Triangle"
else -> label(control)
}
fun native(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" && element.icon == 0 &&
(element.name == element.control.label || element.name == name(element.control))
fun artwork(element: InputSurfaceElement) = element.image.isEmpty() && element.showLabel &&
(native(element) || element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD)
companion object {
fun forOverlay(context: Context, layout: SavedInputLayout?): PadKit? =
if (layout?.overlay != true) null else when (SessionPrefs.steamController(context)) {
SessionPrefs.CONTROLLER_DECK -> STEAM_DECK
SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER
SessionPrefs.CONTROLLER_XBOX360 -> XBOX
SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK
SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE
else -> null
}
}
}
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.session.SessionPrefs
enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindings: String? = null) {
NONE("none", R.string.second_mode_none),
MENU("menu", R.string.touch_droiddeck_menu),
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad, InputStockLayouts.TRACKPAD),
TERMINAL("terminal", R.string.second_mode_terminal),
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls, InputStockLayouts.DECK),
@@ -21,19 +22,12 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
fun panel(context: Context): String? = if (this == DECK_CONTROLS) SessionPrefs.deckPanel(context).bindings else bindings
companion object {
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false, desktopSession: Boolean = false): SecondScreenMode {
/** The mode the bottom screen opens in: the one picked last if it is still available, else the DroidDeck menu. */
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false): SecondScreenMode =
entries.firstOrNull {
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard) &&
(it != DESKTOP || bottomDesktop)
}?.let { return it }
val picked = entries.any { it != NONE && it.id == remembered }
return when {
desktopSession -> KEYBOARD_TRACKPAD
deckPad -> DECK_CONTROLS
dashboard && !picked -> DASHBOARD
else -> KEYBOARD_TRACKPAD
}
}
} ?: MENU
}
}
@@ -1,116 +0,0 @@
package com.droiddeck.launcher.input
import android.graphics.Rect
import android.util.DisplayMetrics
import kotlin.math.max
import kotlin.math.min
internal class SteamDeckOverlayGeometry(
width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float,
) {
private val w = width.toFloat()
private val h = height.toFloat()
private val density = metrics.density
private val dpi = metrics.ydpi.takeIf { it in metrics.densityDpi * .6f..metrics.densityDpi * 1.6f }
?: metrics.densityDpi.toFloat()
private val unit = minOf(
min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)) * scale,
(w - safe.left - safe.right).coerceAtLeast(1f) / 1200f,
(h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f,
)
private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float {
val low = start + value * unit
val high = extent - end - (reference - value) * unit
return when {
value < reference / 3f -> low
value > reference * 2f / 3f -> high
else -> (extent / 2f + (value - reference / 2f) * unit).coerceIn(low, max(low, high))
}
}
fun place(elements: List<InputSurfaceElement>, rearButtons: Boolean, trackpads: Boolean): List<InputSurfaceElement> {
val x = { ref: Float -> anchor(ref, 1600f, w, safe.left, safe.right) }
val y = { ref: Float -> anchor(ref, 900f, h, safe.top, safe.bottom) }
val leftEdge = safe.left + 52f * density
val middle = (w + safe.left - safe.right) / 2f
val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
val row = fitRow(listOfNotNull(keyboard,
Box(max(x(370f), leftEdge + 66f * unit), y(852f), 66f, 30f),
Box(middle - 140f * unit, y(850f), 46f, 26f),
Box(middle + 140f * unit, y(850f), 46f, 26f),
Box(x(1230f), y(852f), 66f, 30f)), leftEdge)
val (guide, select, start, qam) = row.takeLast(4)
val positions = mapOf(
InputControl.LT to Box(x(140f), y(66f), 88f, 34f),
InputControl.LB to Box(x(140f), y(148f), 88f, 30f),
InputControl.RT to Box(x(1460f), y(66f), 88f, 34f),
InputControl.RB to Box(x(1460f), y(148f), 88f, 30f),
InputControl.Y to Box(x(1375f), y(345f) - 96f * unit, 58f),
InputControl.X to Box(x(1375f) - 96f * unit, y(345f), 58f),
InputControl.B to Box(x(1375f) + 96f * unit, y(345f), 58f),
InputControl.A to Box(x(1375f), y(345f) + 96f * unit, 58f),
InputControl.UP to Box(x(220f), y(345f) - 102.5f * unit, 55.5f, 47.5f),
InputControl.RIGHT to Box(x(220f) + 102.5f * unit, y(345f), 47.5f, 55.5f),
InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * unit, 55.5f, 47.5f),
InputControl.LEFT to Box(x(220f) - 102.5f * unit, y(345f), 47.5f, 55.5f),
InputControl.LS to Box(x(290f), y(640f), 96f),
InputControl.RS to Box(x(1310f), y(640f), 96f),
InputControl.SELECT to select,
InputControl.START to start,
InputControl.GUIDE to guide,
InputControl.QAM to qam,
)
val rear = mapOf(
InputControl.L4 to Box(x(30f), y(470f), 30f, 58f),
InputControl.L5 to Box(x(30f), y(590f), 30f, 58f),
InputControl.R4 to Box(x(1570f), y(470f), 30f, 58f),
InputControl.R5 to Box(x(1570f), y(590f), 30f, 58f),
)
val pads = mapOf(
InputControl.LEFT_PAD to Box(x(470f), y(360f), 88f),
InputControl.RIGHT_PAD to Box(x(1130f), y(360f), 88f),
)
val optional = rear.filterKeys { rearButtons } + pads.filterKeys { trackpads }
val placed = elements.mapNotNull { element ->
when {
element.id == KEYBOARD -> row.first().place(element)
element.id != "legacy:${element.control.id}" -> element
element.control in rear || element.control in pads -> optional[element.control]?.place(element)
else -> positions[element.control]?.place(element) ?: element
}
}
return placed + optional.mapNotNull { (control, box) ->
if (placed.any { it.id == "legacy:${control.id}" }) null else box.place(InputSurfaceElement(control,
0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad))
}
}
private fun fitRow(row: List<Box>, start: Float): List<Box> {
val end = w - safe.right
val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density)
var edge = start - gap
val pushed = row.map { box -> box.at(max(box.cx, edge + gap + box.width / 2f)).also { edge = it.cx + it.width / 2f } }
edge = end + gap
return pushed.asReversed().map { box -> box.at(min(box.cx, edge - gap - box.width / 2f)).also { edge = it.cx - it.width / 2f } }.asReversed()
}
private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) {
val width get() = max(hw * 2f * unit, w * .03f)
fun at(cx: Float) = Box(cx, cy, hw, hh)
fun place(element: InputSurfaceElement): InputSurfaceElement {
val height = max(hh * 2f * unit, h * .03f)
return element.copy(
x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w,
y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h,
width = width / w, height = height / h,
).bounded()
}
}
private companion object {
const val KEYBOARD = "builtin:keyboard"
}
}
@@ -0,0 +1,81 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
internal class TriggerKeys(private val dispatch: (KeyEvent) -> Unit) {
private class Pull {
val held = BooleanArray(2)
val sent = BooleanArray(2)
}
private val handler = Handler(Looper.getMainLooper())
private val keyed = HashSet<Int>()
private val pulls = HashMap<Int, Pull>()
var synthesizing = false
private set
/** True when this real trigger key belongs to a pull that already went out as a synthetic press. */
fun nativeKey(event: KeyEvent): Boolean {
val i = index(event.keyCode) ?: return false
keyed += event.deviceId
val pull = pulls[event.deviceId] ?: return false
if (!pull.sent[i]) return false
if (event.action == KeyEvent.ACTION_UP) pull.sent[i] = false
return true
}
fun onMotion(event: MotionEvent) {
if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) return
val device = event.deviceId
if (device in keyed) return
val pull = pulls.getOrPut(device) { Pull() }
update(pull, 0, maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)), event)
update(pull, 1, maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)), event)
}
fun cancel() {
handler.removeCallbacksAndMessages(null)
pulls.clear()
}
private fun update(pull: Pull, i: Int, value: Float, event: MotionEvent) {
if (!pull.held[i] && value >= PRESS) {
pull.held[i] = true
pull.sent[i] = false
val device = event.deviceId
val source = event.source
// A pad that also sends trigger keys delivers them close to the axis; waiting lets that key win.
handler.postDelayed({
if (device !in keyed && pulls[device] === pull) {
pull.sent[i] = true
press(CODES[i], device, source)
}
}, KEY_WAIT_MS)
} else if (pull.held[i] && value <= RELEASE) pull.held[i] = false
}
private fun press(code: Int, device: Int, source: Int) {
val now = SystemClock.uptimeMillis()
synthesizing = true
try {
dispatch(KeyEvent(now, now, KeyEvent.ACTION_DOWN, code, 0, 0, device, 0, 0, source))
dispatch(KeyEvent(now, now, KeyEvent.ACTION_UP, code, 0, 0, device, 0, 0, source))
} finally {
synthesizing = false
}
}
private fun index(code: Int): Int? = CODES.indexOf(code).takeIf { it >= 0 }
private companion object {
val CODES = intArrayOf(KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2)
const val PRESS = 0.6f
const val RELEASE = 0.3f
const val KEY_WAIT_MS = 40L
}
}
@@ -12,9 +12,6 @@ object BattleNet {
const val APP_ID = 2596113170L
const val FEX_REQUEST = "battlenet-fex.request"
const val FEX_RESULT = "battlenet-fex.result"
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null, val flavor: String? = null)
@@ -59,7 +56,7 @@ object BattleNet {
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
)
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" }
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
@@ -162,8 +159,6 @@ object BattleNet {
source = com.droiddeck.launcher.stores.Store.BATTLENET.id,
)
fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"]
internal fun title(uid: String): Title? {
val id = uid.lowercase()
TITLES.firstOrNull { it.uid == id }?.let { return it }
@@ -391,54 +386,6 @@ object BattleNet {
Log.i(TAG, "removed")
}
private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""")
private const val LISTING_MAX_AGE = 6 * 3600L
private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b ->
for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i])
if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second)
}
internal fun d2rfix(file: String): Pair<List<Long>, Long>? {
val m = D2RFIX.matchEntire(file) ?: return null
val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
return version to (m.groupValues[2].toLongOrNull() ?: return null)
}
internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? =
items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } }
.maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first
fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items }
@Synchronized
internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String {
val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing")
val file = ComponentsManager.safeName(item.file)
if (ComponentsManager.packages(context).none { it.file == file }) {
Log.i(TAG, "downloading ${item.file}")
ComponentsManager.download(context, item) {}
}
val scope = APP_ID.toString()
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
ComponentsManager.setGameComponent(context, scope, "fex", file)
Log.i(TAG, "FEX for the Battle.net prefix: $file")
} else if (ComponentsManager.republish(context)) {
Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton")
}
return file
}
private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> {
val cached = ComponentsManager.catalog(context, false)
val age = System.currentTimeMillis() / 1000 - cached.fetchedAt
if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items
val fetched = runCatching { refresh(context) }
.onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty()
return if (newestD2rFix(fetched) != null) fetched else cached.items
}
internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt()
internal fun videoMemoryOptions(megabytes: Int): String =
@@ -464,21 +411,9 @@ object BattleNet {
return true
}
fun answerFexRequest(context: Context, dir: File) {
val app = context.applicationContext
Thread({
runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
val answer = try {
"ok " + ensureFex(app)
} catch (e: Exception) {
Log.w(TAG, "FEX for the Battle.net prefix", e)
"error " + (e.message ?: e.javaClass.simpleName)
}
Log.i(TAG, "FEX request: $answer")
val result = File(dir, FEX_RESULT)
val partial = File(dir, "$FEX_RESULT.tmp")
runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) }
}, "battlenet-fex").start()
fun ensureDefaults(context: Context, program: String?) {
if (program != PROGRAM && !installed(context)) return
runCatching { ensureVideoMemory(context) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
runCatching { ensureNoSteam(context) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
}
}
@@ -112,9 +112,16 @@ object BwrapSpawner {
return out
}
internal fun withKernelPaths(sessionBinds: List<Bind>, canonical: (String) -> String): List<Bind> =
sessionBinds + sessionBinds.filter { it.host == it.guest }.mapNotNull { bind ->
runCatching { canonical(bind.host) }.getOrNull()
?.takeIf { it != bind.guest && sessionBinds.none { other -> other.guest == it } }
?.let { Bind(bind.host, it) }
}
internal fun plan(context: Context, request: JSONObject, dir: File): Plan {
val rootfs = LinuxRuntime.rootDir(context).path
val session = LinuxRuntime.lastBinds(context).map { Bind.parse(it) }
val session = withKernelPaths(LinuxRuntime.lastBinds(context).map { Bind.parse(it) }) { File(it).canonicalPath }
val root = File(dir, "root").apply { mkdirs() }
val binds = ArrayList<Bind>()
var scratch = 0
@@ -184,7 +191,10 @@ object BwrapSpawner {
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
withoutRootfsSettings(env, rootfs)
val envTool = request.optString("envTool").takeIf { it.startsWith("/") }
if (envTool == null && binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
if (envTool == null && binds.any { it.guest == "/dev" }) {
val glIcd = coveringBind(GL_ICD_DIR) != null && File(hostPath(binds, root.path, GL_ICD_DIR)).isDirectory
gpu(rootfs, root, env, glIcd = glIcd)?.forEach { addBind(it) }
}
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
if (envTool == null && preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) }
zypakShims(binds, root, dir).forEach { addBind(it) }
@@ -211,6 +221,7 @@ object BwrapSpawner {
}
private const val GPU_DIR = "/run/droiddeck-gpu"
private const val GL_ICD_DIR = "/usr/lib/aarch64-linux-gnu/GL/vulkan/icd.d"
private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib")
private val GPU_LIBS = listOf("libdisplay-info.so.3", "libdisplay-info.so.2", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")
@@ -220,9 +231,9 @@ object BwrapSpawner {
internal fun gpu(
rootfs: String, root: File, env: MutableMap<String, String>,
kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(),
kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), glIcd: Boolean = false,
): List<Bind>? {
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock, glIcd) }
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
if (driver == null || !kgslAvailable) return null
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
@@ -235,6 +246,7 @@ object BwrapSpawner {
val icd = File(root.parentFile, "freedreno_icd.json")
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_freedreno.so\", \"api_version\": \"1.4.0\"}}\n")
binds.add(Bind(icd.path, "$GPU_DIR/freedreno_icd.json"))
if (glIcd) binds.add(icdDir(root, icd))
env["VK_DRIVER_FILES"] = "$GPU_DIR/freedreno_icd.json"
env["VK_ICD_FILENAMES"] = "$GPU_DIR/freedreno_icd.json"
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
@@ -245,7 +257,14 @@ object BwrapSpawner {
return binds
}
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<Bind>? {
private fun icdDir(root: File, icd: File): Bind {
val dir = File(root.parentFile, "icd.d")
dir.mkdirs()
icd.copyTo(File(dir, icd.name), overwrite = true)
return Bind(dir.path, GL_ICD_DIR)
}
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String, glIcd: Boolean): List<Bind>? {
val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so")
if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null }
val binds = ArrayList<Bind>()
@@ -258,6 +277,7 @@ object BwrapSpawner {
}.getOrNull() ?: run { Log.w(TAG, "gpu: vkbridge session but the runtime's bridge manifest is unreadable"); return null }
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"$api\"}}\n")
binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json"))
if (glIcd) binds.add(icdDir(root, icd))
env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json"
env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json"
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
@@ -537,6 +557,9 @@ object BwrapSpawner {
return f
}
internal fun prootEnvironment(plan: Plan, startsThroughEnvTool: Boolean): Map<String, String> =
if (startsThroughEnvTool) emptyMap() else plan.env - "LD_PRELOAD"
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
@@ -558,7 +581,7 @@ object BwrapSpawner {
ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b ->
b.environment().apply {
clear()
if (!envTool) putAll(plan.env)
putAll(prootEnvironment(plan, envTool))
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
@@ -0,0 +1,303 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.time.Instant
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object CurseForgeApp {
const val NAME = "CurseForge"
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
internal const val WOW = 1
const val HELPER = "/usr/local/bin/droiddeck-curseforge"
internal const val AGENT = "/usr/local/bin/droiddeck-agent"
private const val READY_MS = 120_000L
private const val INSTALL_MS = 300_000L
private const val OUT_OF_DATE = 2
enum class Start { READY, BUSY, FAILED }
class Started(val state: Start, val inspector: String? = null)
class Project(val id: String, val installedModId: String, val folders: List<String>, val update: Boolean)
internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
class Failure(message: String, val code: String? = null) : Exception(message) {
val gone get() = code == "DEVTOOLS_UNREACHABLE"
}
fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED }
fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null)
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
internal fun helperArgv(command: String, dir: String): List<String> = listOf(HELPER, command, dir)
internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List<String> =
listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression)
internal fun lastJson(lines: List<String>): JSONObject? =
lines.asReversed().firstNotNullOfOrNull { line -> runCatching { JSONObject(line.trim()) }.getOrNull() }
internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) }
internal fun startState(exitCode: Int): Start = when (exitCode) {
0 -> Start.READY
3 -> Start.BUSY
else -> Start.FAILED
}
internal fun sortOf(sort: WowAddonCatalog.Sort): Pair<Int, Int> = when (sort) {
WowAddonCatalog.Sort.POPULAR -> 8 to 2
WowAddonCatalog.Sort.UPDATED -> 16 to 2
WowAddonCatalog.Sort.NAME -> 1 to 1
WowAddonCatalog.Sort.DOWNLOADS -> 7 to 2
}
internal fun searchRequest(guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): JSONObject {
val (column, order) = sortOf(sort)
return JSONObject().put("gameId", WOW).put("searchText", text.trim()).put("page", page + 1)
.put("sortColumn", column).put("sortOrder", order).put("gameInstanceGuid", guid)
}
internal fun installRequest(guid: String, projectId: String): JSONObject =
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
.put("installLatestFile", true).put("installSource", 4)
private const val CACHE = "__droiddeckServices"
private const val SERVICES = """(() => {
const seen = new Set(), out = {};
const walk = (o, d) => {
if (!o || typeof o !== 'object' || seen.has(o) || d > 4) return;
seen.add(o);
if (typeof o._nameOfService === 'string') { out[o._nameOfService] = o; return; }
let keys; try { keys = Object.keys(o); } catch (e) { return; }
for (const k of keys.slice(0, 4000)) {
let v; try { v = o[k]; } catch (e) { continue; }
if (v instanceof Map) { for (const x of v.values()) walk(x, d + 1); } else walk(v, d + 1);
}
};
walk(window, 0);
return out;
})()"""
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
val name = JSONObject.quote(method)
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
val key = JSONObject.quote(service)
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
"return { value: $run }; })()"
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
"if (!w) return JSON.stringify({ missing: true }); " +
"return w.webContents.executeJavaScript(${JSONObject.quote(inner)}).then(v => JSON.stringify(v)); })()"
}
internal fun unwrap(answer: JSONObject): Any? {
if (!answer.optBoolean("ok")) {
val error = answer.optJSONObject("error")
throw Failure(error?.optString("message")?.takeIf { it.isNotBlank() } ?: answer.toString(), error?.optString("code")?.takeIf { it.isNotBlank() })
}
val text = answer.opt("value") as? String ?: throw Failure("CurseForge gave no answer")
val reply = JSONObject(text)
if (reply.optBoolean("missing")) throw Failure("CurseForge is not ready")
return reply.opt("value")
}
internal fun parseSearch(value: Any?): WowAddonCatalog.Page {
val reply = value as? JSONObject ?: throw Failure("CurseForge search failed")
if (reply.has("success") && !reply.optBoolean("success")) throw Failure("CurseForge search failed")
val mods = reply.optJSONArray("mods") ?: JSONArray()
val items = (0 until mods.length()).mapNotNull { mods.optJSONObject(it) }.mapNotNull { mod ->
val id = mod.optLong("id", 0L).takeIf { it > 0 } ?: return@mapNotNull null
val name = mod.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
val author = mod.optJSONObject("primaryAuthor")?.optString("name")?.takeIf { it.isNotBlank() }
?: mod.optJSONArray("authors")?.optJSONObject(0)?.optString("name").orEmpty()
val date = mod.optJSONObject("updateVersion")?.optString("fileDate")?.takeIf { it.isNotBlank() }
?: mod.optString("projectLatestReleaseDate")
WowAddonCatalog.Addon(
id.toString(), name, author, "", mod.optLong("downloads", 0L).coerceAtLeast(0L),
runCatching { Instant.parse(date).toEpochMilli() }.getOrDefault(0L),
mod.optString("thumbnailUrl").takeIf { WowAddonCatalog.isHttps(it) },
)
}
val page = reply.optJSONObject("pagination")
val more = page != null && page.optInt("index") + page.optInt("resultCount") < page.optInt("totalCount")
return WowAddonCatalog.Page(items, more)
}
internal fun samePath(a: String, b: String) = a.trimEnd('/') == b.trimEnd('/')
internal fun instanceFor(instances: Any?, flavorDir: String, detected: String?): String? {
val list = instances as? JSONArray
val match = list?.let { all ->
(0 until all.length()).mapNotNull { all.optJSONObject(it) }
.firstOrNull { samePath(it.optString("installPath"), flavorDir) }?.optString("guid")
}
if (list != null && list.length() > 0) return match?.takeIf { it.isNotBlank() }
return detected?.takeIf { it.isNotBlank() }
}
internal fun parseProjects(value: Any?): List<Project> {
val list = value as? JSONArray ?: return emptyList()
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.mapNotNull { p ->
val id = p.optString("id").takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
val folders = p.optJSONArray("folders")?.let { f -> (0 until f.length()).mapNotNull { f.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
Project(id, p.optString("installedModId"), folders, p.optInt("status") == OUT_OF_DATE && !p.optBoolean("locked"))
}
}
internal fun owner(projects: List<Project>, folder: String): Project? =
projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } }
internal fun byFolder(projects: List<Project>): Map<String, Project> = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap()
internal fun onDisk(projects: List<Project>, addOns: File): List<Project> {
val names = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }.map { it.name.lowercase() }.toSet()
return projects.filter { project -> WowAddons.present(project.folders) { it.lowercase() in names } }
}
internal var guest: (Context, List<String>, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine ->
GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true,
cancelled = cancelled, redact = INSPECTOR, onLine = onLine)
}
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
private val connected = ConcurrentHashMap.newKeySet<String>()
private fun lines(context: Context, argv: List<String>): List<String> {
val out = ArrayList<String>()
guest(context, argv, null) { out += it }
return out
}
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? =
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
private sealed class Launch {
class Url(val inspector: String) : Launch()
class Exit(val code: Int) : Launch()
}
private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? {
val first = LinkedBlockingQueue<Launch>()
Thread({
val code = runCatching {
guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } }
}.getOrDefault(-1)
first.offer(Launch.Exit(code))
}, "curseforge-headless").apply { isDaemon = true; start() }
return first.poll(READY_MS, TimeUnit.MILLISECONDS)
}
fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started {
val dir = dir(app) ?: return Started(Start.FAILED)
if (hold.get()) return Started(Start.FAILED)
holds.put(dir, hold)?.takeIf { it !== hold }?.let {
it.set(true)
runCatching { lines(context, helperArgv("stop", dir)) }
}
val inspector = when (val first = launch(context, dir, hold)) {
is Launch.Url -> first.inspector
is Launch.Exit -> if (startState(first.code) == Start.BUSY) {
holds.remove(dir, hold)
return Started(Start.BUSY)
} else null
null -> null
}
if (inspector == null) {
stop(context, app, null, hold)
return Started(Start.FAILED)
}
val deadline = System.currentTimeMillis() + READY_MS
while (System.currentTimeMillis() < deadline && !hold.get()) {
if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector)
Thread.sleep(1_000)
}
stop(context, app, inspector, hold)
return Started(Start.FAILED)
}
fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) {
val dir = dir(app) ?: return
if (holds[dir] !== hold) {
hold.set(true)
return
}
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
hold.set(true)
inspector?.let(connected::remove)
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
}
private fun connect(context: Context, inspector: String) {
if (inspector in connected) return
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
connected += inspector
}
private fun instances(context: Context, inspector: String): Any? =
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
connect(context, inspector)
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
}
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> {
connect(context, inspector)
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000)
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
}
private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " +
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? {
val deadline = System.currentTimeMillis() + INSTALL_MS
while (System.currentTimeMillis() < deadline) {
val listed = runCatching { projects(context, inspector, guid) }
val error = listed.exceptionOrNull()
if (error is Failure && error.gone) throw error
listed.getOrNull()?.let { if (done(it)) return it }
Thread.sleep(1_000)
}
return null
}
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
}
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
}
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
connect(context, inspector)
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
if (failed == null || failed.length() > 0) return null
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
}
}
@@ -0,0 +1,102 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.session.SessionState
import java.io.File
import org.json.JSONArray
import org.json.JSONObject
object DeckyStore {
private const val TAG = "DeckyStore"
private const val LISTING = "https://plugins.deckbrew.xyz/plugins"
private const val ARTIFACTS = "https://cdn.tzatzikiweeb.moe/file/steam-deck-homebrew/versions/"
data class Version(val name: String, val hash: String)
data class Plugin(val name: String, val author: String, val description: String, val tags: List<String>, val downloads: Long, val imageUrl: String, val versions: List<Version>) {
val latest: Version? get() = versions.firstOrNull()
}
data class Installed(val name: String, val folder: String, val author: String, val version: String)
fun parseListing(body: String): List<Plugin> {
val array = JSONArray(body)
return (0 until array.length()).mapNotNull { i ->
val row = array.optJSONObject(i) ?: return@mapNotNull null
val name = row.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
val versions = row.optJSONArray("versions")?.let { list ->
(0 until list.length()).mapNotNull { v ->
val version = list.optJSONObject(v) ?: return@mapNotNull null
val hash = version.optString("hash")
if (!hash.matches(Regex("(?i)[0-9a-f]{64}"))) null else Version(version.optString("name"), hash.lowercase())
}
}.orEmpty()
if (versions.isEmpty()) return@mapNotNull null
val tags = row.optJSONArray("tags")?.let { list -> (0 until list.length()).map { list.optString(it) } }.orEmpty()
val downloads = row.optJSONArray("versions")?.let { list -> (0 until list.length()).sumOf { list.optJSONObject(it)?.optLong("downloads") ?: 0L } } ?: 0L
val image = row.optString("image_url").takeIf { it.startsWith("https://") }.orEmpty()
Plugin(name, row.optString("author"), row.optString("description"), tags, downloads, image, versions)
}
}
fun fetch(): List<Plugin>? {
val body = Downloader.downloadString(LISTING) ?: return null
return runCatching { parseListing(body) }.onFailure { Log.w(TAG, "store listing", it) }.getOrNull()
}
fun pluginsDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins")
fun installed(context: Context): List<Installed> =
pluginsDir(context).listFiles().orEmpty()
.filter { it.isDirectory && !it.name.startsWith(".droiddeck-") }
.mapNotNull { folder ->
runCatching {
val meta = JSONObject(File(folder, "plugin.json").readText())
val version = runCatching { JSONObject(File(folder, "package.json").readText()).optString("version") }.getOrDefault("")
Installed(meta.getString("name"), folder.name, meta.optString("author"), version)
}.getOrNull()
}
.sortedBy { it.name.lowercase() }
fun updateAvailable(installed: Installed, plugin: Plugin?): Boolean {
val latest = plugin?.latest?.name ?: return false
return installed.version.isNotEmpty() && latest != installed.version
}
fun install(context: Context, plugin: Plugin, version: Version, progress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin)
if (DeckyManager.installed(context) == null) return context.getString(R.string.deckymgr_loader_required)
val cache = File(context.cacheDir, "decky-store").apply { mkdirs() }
val zip = File(cache, "${version.hash}.zip")
try {
val label = context.getString(R.string.decky_store_downloading, plugin.name)
progress(label, -1)
val ok = Downloader.downloadFile("$ARTIFACTS${version.hash}.zip", zip, true, version.hash) { fraction ->
progress(label, if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100))
}
if (!ok) return context.getString(R.string.decky_store_download_failed, plugin.name)
return DeckyManager.installPluginZip(context, zip, progress)
} finally {
zip.delete()
}
}
fun remove(context: Context, plugin: Installed): String? {
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin)
val plugins = pluginsDir(context)
val folder = File(plugins, plugin.folder)
if (folder.parentFile?.canonicalFile != plugins.canonicalFile) return context.getString(R.string.decky_store_remove_failed)
if (!folder.deleteRecursively()) return context.getString(R.string.decky_store_remove_failed)
val settings = File(plugins.parentFile, "settings/loader.json")
runCatching {
val json = JSONObject(settings.readText())
for (key in listOf("pluginOrder", "frozenPlugins", "hiddenPlugins", "disabled_plugins")) {
val values = json.optJSONArray(key) ?: continue
json.put(key, JSONArray((0 until values.length()).map { values.get(it) }.filter { it != plugin.name }))
}
settings.writeText(json.toString(4))
}
return null
}
}
@@ -32,6 +32,9 @@ object DesktopLanguage {
internal fun baseUrl(desktopUrl: String) = desktopUrl.substringBeforeLast('/') + "/"
/** The index carries every pack's sha256, so it never goes through a download mirror. */
internal fun fetchIndex(base: String): Map<String, Pack>? = Downloader.downloadDirect(base + INDEX)?.let(::parseIndex)
private fun marker(root: File, tag: String, name: String) = File(root, ".droiddeck-i18n-$tag-$name")
/** Installs the desktop's translations for [locale]; false when a download failed and is worth retrying. */
@@ -44,7 +47,7 @@ object DesktopLanguage {
val pending = candidates(locale).filterNot { marker(root, tag, it).isFile }
if (pending.isEmpty()) return true
val base = baseUrl(BuildConfig.DESKTOP_KDE_URL)
val index = parseIndex(Downloader.downloadString(base + INDEX) ?: return false)
val index = fetchIndex(base) ?: return false
var complete = true
for (name in pending) {
val pack = index[name]
@@ -14,20 +14,22 @@ import java.util.concurrent.atomic.AtomicBoolean
object GuestCommand {
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
onLine: (String) -> Unit): Int {
redact: Regex? = null, onLine: (String) -> Unit): Int {
val log = logName?.let {
try {
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
} catch (e: Exception) { null }
}
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}")
try {
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) }
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) }
} finally {
log?.close()
}
}
internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "<redacted>") ?: text
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
val root = LinuxRuntime.rootDir(context)
@@ -275,12 +275,15 @@ class LinuxNetworkLinkComponent(
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
*/
private fun replace(file: File, text: String) {
val staged = File(file.path + ".staged")
java.io.FileOutputStream(staged).use { out ->
out.write(text.toByteArray())
out.fd.sync()
synchronized(WRITES) {
if (runCatching { file.isFile && file.readText() == text }.getOrDefault(false)) return
val staged = File(file.path + ".staged")
java.io.FileOutputStream(staged).use { out ->
out.write(text.toByteArray())
out.fd.sync()
}
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
}
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
}
private fun writeResolver(properties: LinkProperties?) {
@@ -333,6 +336,8 @@ class LinuxNetworkLinkComponent(
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
companion object {
private val WRITES = Any()
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
properties?.routes.orEmpty()
@@ -76,7 +76,6 @@ object NativeGuest {
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(),
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() }
@@ -84,10 +83,10 @@ object NativeGuest {
* The host command line for the guest program at [program] (an absolute guest path to a real
* file, not a symlink).
*/
fun command(root: File, program: String, args: List<String>): List<String> {
fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> {
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
val host = File(root, program.removePrefix("/"))
val launch = listOf(loader.path, "--argv0", host.name, host.path) + args
val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
}
@@ -100,7 +99,6 @@ object NativeGuest {
"DDNATV_HOSTNAME" to hostname.orEmpty(),
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
"DDNATV_PRELOAD" to preload.joinToString(":"),
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() }
}
@@ -273,7 +271,9 @@ object NativeGuest {
fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder {
val program = argv.first()
val cmd = command(root, program, argv.drop(1))
val callerDirs = env["LD_LIBRARY_PATH"]?.takeIf { it.isNotEmpty() }?.split(':').orEmpty()
val rootDirs = libraryPath(root).split(':').filterNot { it in callerDirs }
val cmd = command(root, program, argv.drop(1), (callerDirs + rootDirs).joinToString(":"))
val builder = ProcessBuilder(cmd).redirectErrorStream(false)
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
builder.environment().apply {
@@ -36,6 +36,7 @@ object UserApps {
private const val GITHUB_TAG = "github-tag"
private const val GITHUB_PUBLISHED = "github-published"
private const val GITHUB_ASSET = "github-asset"
private const val FEED = "update-feed"
enum class Kind { SCRIPT, APPIMAGE, FLATPAK }
@@ -43,10 +44,15 @@ object UserApps {
val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?,
val program: String, val args: List<String>, val copied: Boolean = false,
val repo: String? = null, val version: String? = null,
val fex: String = LinuxFex.AUTO, val arch: String? = null,
)
val fex: String = LinuxFex.AUTO, val arch: String? = null, val feed: String? = null,
) {
val updatable get() = repo != null || feed != null
}
class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String? = null)
class Release(
val tag: String, val published: String, val asset: String, val url: String,
val sha256: String? = null, val sha512: String? = null,
)
sealed class UpdateCheck {
class Current(val tag: String) : UpdateCheck()
@@ -58,6 +64,7 @@ object UserApps {
class Script(val file: File) : Source()
class AppImage(val file: File) : Source()
class GitHub(val repo: String, val asset: String? = null) : Source()
class Feed(val url: String) : Source()
class Flatpak(val id: String) : Source()
class FlatpakBundle(val file: File) : Source()
}
@@ -91,6 +98,7 @@ object UserApps {
"appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir),
repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(),
fex = LinuxFex.mode(dir), arch = FileUtils.readString(File(dir, "arch"))?.trim()?.takeIf { it.isNotEmpty() },
feed = FileUtils.readString(File(dir, FEED))?.trim()?.takeIf { it.isNotEmpty() },
)
}
val flatpaks = FlatpakManager.installedApps(context).map { app ->
@@ -115,6 +123,7 @@ object UserApps {
is Source.Script -> addScript(context, s.file, name, icon, request.meta, onProgress)
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon, request.meta) { onProgress(it, -1) }
is Source.GitHub -> addFromGitHub(context, s.repo, s.asset, name, icon, onProgress)
is Source.Feed -> addFromFeed(context, s.url, name, icon, onProgress)
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress)
}
@@ -346,11 +355,15 @@ object UserApps {
}
private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? {
val download = File(context.cacheDir, "github-${release.asset}")
val download = File(File(context.cacheDir, "user-apps").apply { mkdirs() }, release.asset)
try {
val label = context.getString(R.string.user_apps_downloading, release.asset)
val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
return if (ok) use(download) else context.getString(R.string.user_apps_download_failed)
if (!ok) return context.getString(R.string.user_apps_download_failed)
if (release.sha512 != null && !Hashes.sha512(download).equals(release.sha512, ignoreCase = true)) {
return context.getString(R.string.selfinst_checksum_mismatch)
}
return use(download)
} finally {
download.delete()
}
@@ -392,20 +405,57 @@ object UserApps {
return urls + listOfNotNull(avatar)
}
internal fun parseFeed(feed: String, body: String): Release? {
val top = body.lineSequence().filter { it.isNotEmpty() && !it[0].isWhitespace() && ':' in it }
.associate { it.substringBefore(':').trim() to it.substringAfter(':').trim().trim('\'', '"') }
val version = top["version"]?.takeIf { it.isNotEmpty() } ?: return null
val path = top["path"]?.takeIf { it.endsWith(".AppImage", ignoreCase = true) && '/' !in it && ".." !in it } ?: return null
val sha512 = top["sha512"]?.let { runCatching { java.util.Base64.getDecoder().decode(it) }.getOrNull() }
?.takeIf { it.size == 64 }?.joinToString("") { "%02x".format(it) } ?: return null
val base = feed.substringBeforeLast('/', "").takeIf { it.startsWith("https://") } ?: return null
return Release(version, top["releaseDate"].orEmpty(), path, "$base/$path", sha512 = sha512)
}
private fun feedRelease(context: Context, feed: String): Release? =
Downloader.downloadString(feed)?.let { parseFeed(feed, it) }
private fun feedMeta(feed: String, release: Release) =
mapOf(FEED to feed, GITHUB_TAG to release.tag, GITHUB_PUBLISHED to release.published, GITHUB_ASSET to release.asset)
private fun addFromFeed(context: Context, feed: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
onProgress(context.getString(R.string.user_apps_github_checking, name ?: feed), -1)
val release = feedRelease(context, feed) ?: return context.getString(R.string.user_apps_update_failed)
return withDownload(context, release, onProgress) { file ->
AppImageManager.import(context, file, name ?: release.asset.substringBefore('-'), icon, feedMeta(feed, release)) { onProgress(it, -1) }
}
}
internal fun isNewer(release: Release, published: String, installed: String?): Boolean =
if (published.isNotEmpty() && release.published.isNotEmpty()) {
val feed = runCatching { java.time.Instant.parse(release.published) }.getOrNull()
val have = runCatching { java.time.Instant.parse(published) }.getOrNull()
if (feed != null && have != null) feed > have else release.published > published
} else release.tag != installed
fun checkUpdate(context: Context, app: App): UpdateCheck {
app.feed?.let { feed ->
val release = feedRelease(context, feed) ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
val published = FileUtils.readString(File(AppImageManager.dir(context, app.key.substringAfter(':')), GITHUB_PUBLISHED))?.trim().orEmpty()
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
}
val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
val dir = AppImageManager.dir(context, app.key.substringAfter(':'))
val (release, problem) = latestRelease(context, repo, FileUtils.readString(File(dir, GITHUB_ASSET))?.trim()?.takeIf { it.isNotEmpty() })
if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed))
val published = FileUtils.readString(File(dir, GITHUB_PUBLISHED))?.trim().orEmpty()
val newer = if (published.isNotEmpty() && release.published.isNotEmpty()) release.published > published else release.tag != app.version
return if (newer) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
}
fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? {
val repo = app.repo ?: return context.getString(R.string.user_apps_update_failed)
val meta = app.feed?.let { feedMeta(it, release) }
?: app.repo?.let { githubMeta(it, release) } ?: return context.getString(R.string.user_apps_update_failed)
return withDownload(context, release, onProgress) { file ->
AppImageManager.replace(context, app.key.substringAfter(':'), file, githubMeta(repo, release)) { onProgress(it, -1) }
AppImageManager.replace(context, app.key.substringAfter(':'), file, meta) { onProgress(it, -1) }
}
}
@@ -29,6 +29,7 @@ object WowAddonCatalog {
val downloads: Long,
val updated: Long,
val thumb: String?,
val folders: List<String> = emptyList(),
)
class Page(val items: List<Addon>, val more: Boolean)
@@ -38,7 +39,6 @@ object WowAddonCatalog {
internal class Cat(val id: String, val name: String, val parents: List<String>)
private const val WOWI = "https://api.mmoui.com/v3/game/WOW/"
private const val CURSEFORGE = "https://www.curseforge.com/wow/search?class=addons"
private const val WOWI_FILES = "wowi-filelist.json"
internal const val FRESH_MS = 6L * 60 * 60 * 1000
@@ -94,8 +94,7 @@ object WowAddonCatalog {
Client(folder, version?.let(::flavorOf) ?: folderFamily(folder))
fun client(target: WowAddons.Target): Client {
val dir = target.addOns.parentFile?.parentFile
return client(target.flavor, dir?.let(::clientVersion))
return client(target.flavor, WowAddons.flavorDir(target)?.let(::clientVersion))
}
internal fun flavorMatches(flavors: Set<String>?, family: String?): Boolean =
@@ -116,9 +115,11 @@ object WowAddonCatalog {
}
val thumbs = o.optJSONArray("UIIMG_Thumbs")
val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null
val dirs = o.optJSONArray("UIDir")
val folders = if (dirs == null) emptyList() else (0 until dirs.length()).map { dirs.optString(it).trim() }.filter { it.isNotEmpty() }
val addon = Addon(
id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"),
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb,
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders,
)
out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L))
}
@@ -209,10 +210,12 @@ object WowAddonCatalog {
fun categories(context: Context): List<Category> = wowiCategories(context).map { Category(it.id, it.name) }
internal fun parseWowiDetails(json: String): Pair<String, String?>? {
internal class Details(val url: String, val md5: String?, val version: String?)
internal fun parseWowiDetails(json: String): Details? {
val o = JSONArray(json).optJSONObject(0) ?: return null
val url = o.optString("UIDownload").ifEmpty { return null }
return url to o.optString("UIMD5").ifEmpty { null }
return Details(url, o.optString("UIMD5").ifEmpty { null }, o.optString("UIVersion").trim().ifEmpty { null })
}
internal fun isHttps(url: String) = url.startsWith("https://", ignoreCase = true)
@@ -220,10 +223,11 @@ object WowAddonCatalog {
internal fun md5Matches(file: File, expected: String?): Boolean =
expected.isNullOrBlank() || Hashes.md5(file).equals(expected.trim(), ignoreCase = true)
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): File {
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): String? {
val body = StoreNet.get(WOWI + "filedetails/${URLEncoder.encode(addon.id, "UTF-8")}.json", timeoutMs = 30_000)
?: throw unreachable(context)
val (url, md5) = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
val details = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
val url = details.url
if (!isHttps(url)) throw IOException(context.getString(R.string.addons_no_file))
dest.parentFile?.mkdirs()
dest.delete()
@@ -232,14 +236,56 @@ object WowAddonCatalog {
dest.delete()
throw unreachable(context)
}
if (!md5Matches(dest, md5)) {
if (!md5Matches(dest, details.md5)) {
dest.delete()
throw IOException(context.getString(R.string.selfinst_checksum_mismatch))
}
progress(100)
return dest
return details.version
}
internal fun curseForgeUrl(text: String): String =
text.trim().let { if (it.isEmpty()) CURSEFORGE else CURSEFORGE + "&search=" + URLEncoder.encode(it, "UTF-8") }
private fun normVersion(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
internal fun sameVersion(a: String, b: String): Boolean = normVersion(a) == normVersion(b)
private val NUMERIC_VERSION = Regex("""^(\d+(?:\.\d+)*)(.*)$""")
private fun numericVersion(v: String): Pair<List<Long>, String>? {
val match = NUMERIC_VERSION.matchEntire(normVersion(v)) ?: return null
val parts = match.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
return parts to match.groupValues[2]
}
internal fun newer(have: String, latest: String): Boolean? {
val (a, aRest) = numericVersion(have) ?: return null
val (b, bRest) = numericVersion(latest) ?: return null
for (i in 0 until maxOf(a.size, b.size)) {
val x = a.getOrElse(i) { 0L }
val y = b.getOrElse(i) { 0L }
if (x != y) return y > x
}
return if (aRest == bRest) false else null
}
internal fun offersUpdate(have: String?, latest: String, sameSource: Boolean): Boolean {
if (have.isNullOrBlank() || latest.isBlank() || sameVersion(have, latest)) return false
return newer(have, latest) ?: sameSource
}
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
val byId = entries.associateBy { it.addon.id }
val seen = HashSet<String>()
return installed.mapNotNull { item ->
val id = item.wowiId ?: return@mapNotNull null
val version = item.version ?: return@mapNotNull null
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest
}.toMap()
}
fun updates(context: Context, installed: List<WowAddons.Installed>, target: WowAddons.Target): Map<String, Addon> {
if (installed.none { it.wowiId != null }) return emptyMap()
val family = client(target).family
return runCatching { findUpdates(wowiEntries(context).filter { flavorMatches(it.flavors, family) }, installed) }.getOrDefault(emptyMap())
}
}
@@ -2,15 +2,25 @@ package com.droiddeck.launcher.runtime
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import android.content.Context
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreArchiveUnpacker
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.itch.ItchArchives
import org.apache.commons.compress.archivers.zip.ZipFile
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.atomic.AtomicBoolean
object WowAddons {
var imports by mutableIntStateOf(0)
@@ -18,10 +28,28 @@ object WowAddons {
class TooLarge : IOException()
fun changed() {
imports++
}
fun flavorDir(target: Target): File? = target.addOns.parentFile?.parentFile
fun root(target: Target): File? = flavorDir(target)?.parentFile
class Target(val flavor: String, val addOns: File)
class Addon(val name: String, val root: String)
class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null)
class Origin(val id: String, val version: String)
private const val ORIGINS = ".droiddeck-sources"
private const val TOC_VERSION = "Version"
private const val TOC_WOWI_ID = "X-WoWI-ID"
private const val TOC_CURSE_ID = "X-Curse-Project-ID"
private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID, TOC_CURSE_ID)
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE)
@@ -45,53 +73,168 @@ object WowAddons {
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
.map { it.name }.sortedBy { it.lowercase() }
fun present(folders: List<String>, exists: (String) -> Boolean): Boolean = folders.isNotEmpty() && folders.all(exists)
fun folder(addOns: File, name: String): File? {
val dirs = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
return dirs.firstOrNull { it.name == name } ?: dirs.firstOrNull { it.name.equals(name, ignoreCase = true) }
}
fun details(target: Target): List<Installed> {
val origins = origins(target)
return installed(target).map { name ->
val toc = toc(File(target.addOns, name))
val origin = origins[name]
Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID])
}
}
internal fun tocFields(lines: Sequence<String>, keys: Set<String> = TOC_KEYS): Map<String, String> {
val out = LinkedHashMap<String, String>()
for (raw in lines) {
val line = raw.trim().removePrefix("\uFEFF")
if (!line.startsWith("##") || ':' !in line) continue
val key = line.removePrefix("##").substringBefore(':').trim()
if (key !in keys || key in out) continue
val value = line.substringAfter(':').trim()
if (value.isNotEmpty() && '@' !in value) out[key] = value
if (out.size == keys.size) break
}
return out
}
private fun toc(folder: File): Map<String, String> {
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }.sortedWith(
compareBy<File>(
{ !it.name.dropLast(4).equals(folder.name, ignoreCase = true) },
{ !it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) },
{ it.name.length },
{ it.name },
),
)
val out = LinkedHashMap<String, String>()
for (file in tocs) {
if (out.size == TOC_KEYS.size) break
val missing = TOC_KEYS - out.keys
runCatching { file.bufferedReader().useLines { tocFields(it, missing) } }.getOrNull()?.let(out::putAll)
}
return out
}
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
val parts = line.split('\t')
if (parts.size != 3 || parts.any { it.isBlank() }) null else parts[0] to Origin(parts[1], parts[2])
}.toMap()
internal fun formatOrigins(origins: Map<String, Origin>): String =
origins.entries.sortedBy { it.key.lowercase() }.joinToString("") { (name, o) -> "$name\t${o.id}\t${o.version.replace(Regex("\\s+"), " ")}\n" }
private fun originsFile(target: Target) = File(target.addOns, ORIGINS)
private fun origins(target: Target): Map<String, Origin> =
runCatching { parseOrigins(originsFile(target).readText()) }.getOrDefault(emptyMap())
private val originsLock = Any()
private fun keepOrigins(target: Target, names: List<String>, origin: Origin?) = synchronized(originsLock) {
val current = origins(target)
val next = current - names.toSet() + (origin?.let { o -> names.associateWith { o } } ?: emptyMap())
if (next != current) {
val file = originsFile(target)
if (next.isEmpty()) file.delete() else {
val temp = File(target.addOns, "$ORIGINS.tmp")
temp.writeText(formatOrigins(next))
if (!temp.renameTo(file)) {
temp.delete()
throw IOException("Cannot save $ORIGINS")
}
}
}
}
fun delete(target: Target, name: String) {
val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") }
?: throw IOException("Cannot find $name")
StoreInstalls.deleteTree(folder)
if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name")
runCatching { keepOrigins(target, listOf(name), null) }
imports++
}
fun import(zipFile: File, target: Target): List<String> {
fun import(archive: File, target: Target, origin: Origin? = null, context: Context? = null): List<String> {
if (context == null || ItchArchives.kind(archive, archive.name) == "zip") return importZip(archive, target, origin)
val work = File(File(context.cacheDir, "wowaddons"), "unpack-${System.nanoTime()}")
try {
if (!work.mkdirs()) throw IOException("Cannot create ${work.path}")
val unpacker = StoreArchiveUnpacker(context, AtomicBoolean(), "Addons", R.string.stores_itch_archive, R.string.stores_itch_extract_failed, "addon-unpack")
unpacker.work = work
unpacker.limit = MAX_EXPANDED_BYTES
try {
unpacker.unpack(archive, archive.name, { _, _ -> }, {})
} catch (_: StoreArchiveUnpacker.TooLarge) {
throw TooLarge()
}
return importFolder(work, target, origin)
} finally {
StoreInstalls.deleteTree(work)
}
}
private class Entry(val path: String, val open: () -> InputStream)
private fun importZip(zipFile: File, target: Target, origin: Origin?): List<String> =
ZipFile.builder().setFile(zipFile).get().use { zip ->
val all = zip.entries.toList()
if (all.any { it.isUnixSymlink }) return emptyList()
val entries = all.filter { clean(it.name) != null }
val addons = addons(entries.filter { !it.isDirectory }.mapNotNull { clean(it.name) })
if (addons.isEmpty()) return emptyList()
val addOns = target.addOns
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
try {
val fresh = File(stage, "new")
val buffer = ByteArray(64 * 1024)
var written = 0L
for (entry in entries) {
if (entry.isDirectory) continue
val path = clean(entry.name) ?: continue
val addon = addons.firstOrNull { path.startsWith(it.root) } ?: continue
val out = inside(fresh, addon.name + "/" + path.removePrefix(addon.root)) ?: continue
out.parentFile?.mkdirs()
zip.getInputStream(entry).use { input ->
out.outputStream().use { output ->
while (true) {
val read = input.read(buffer)
if (read < 0) break
written += read
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
output.write(buffer, 0, read)
}
importEntries(all.filter { !it.isDirectory }.mapNotNull { entry -> clean(entry.name)?.let { Entry(it) { zip.getInputStream(entry) } } }, target, origin)
}
internal fun importFolder(folder: File, target: Target, origin: Origin?): List<String> {
val entries = ArrayList<Entry>()
var links = false
Files.walkFileTree(folder.toPath(), object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (!attrs.isRegularFile) links = true
else clean(folder.toPath().relativize(file).joinToString("/"))?.let { entries.add(Entry(it) { Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS) }) }
return if (links) FileVisitResult.TERMINATE else FileVisitResult.CONTINUE
}
})
return if (links) emptyList() else importEntries(entries, target, origin)
}
private fun importEntries(entries: List<Entry>, target: Target, origin: Origin?): List<String> {
val addons = addons(entries.map { it.path })
if (addons.isEmpty()) return emptyList()
val addOns = target.addOns
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
try {
val fresh = File(stage, "new")
val buffer = ByteArray(64 * 1024)
var written = 0L
for (entry in entries) {
val addon = addons.firstOrNull { entry.path.startsWith(it.root) } ?: continue
val out = inside(fresh, addon.name + "/" + entry.path.removePrefix(addon.root)) ?: continue
out.parentFile?.mkdirs()
entry.open().use { input ->
out.outputStream().use { output ->
while (true) {
val read = input.read(buffer)
if (read < 0) break
written += read
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
output.write(buffer, 0, read)
}
}
}
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
} finally {
StoreInstalls.deleteTree(stage)
}
imports++
return addons.map { it.name }
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
} finally {
StoreInstalls.deleteTree(stage)
}
runCatching { keepOrigins(target, addons.map { it.name }, origin) }
imports++
return addons.map { it.name }
}
internal fun addons(files: List<String>): List<Addon> {
@@ -238,6 +238,20 @@ object ComponentsManager {
saveState(context, state)
}
private val UNPINNED_FEX = Regex("""(?i)FEXCore-\d+(?:\.\d+)*-d2rfix\d+-linux\.wcp""")
fun migrateBattleNetFex(context: Context) = synchronized(lock) {
val marker = File(dataDir(context), ".battlenet-fex-unpinned")
if (marker.isFile) return@synchronized
migratePlugin(context)
val scope = com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
if (gameComponents(context, scope)["fex"]?.let(UNPINNED_FEX::matches) == true) {
setGameComponent(context, scope, "fex", null)
Log.i(TAG, "Battle.net follows the selected FEX again")
}
marker.writeText("1\n")
}
private fun migratePlugin(context: Context) {
val marker = File(dataDir(context), ".plugin-imported")
if (marker.isFile) return
@@ -487,6 +501,7 @@ object ComponentsManager {
fun snapshotAll(context: Context) = synchronized(lock) {
migratePlugin(context)
runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
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) }
@@ -497,6 +512,7 @@ object ComponentsManager {
fun snapshot(context: Context): Snapshot = synchronized(lock) {
migratePlugin(context)
runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
val state = loadState(context)
val reapplied = HashMap<String, Long>()
runCatching {
@@ -43,6 +43,17 @@ object GameStorage {
}
}
fun isFat32(path: String): Boolean = runCatching { isFat32(path, File("/proc/mounts").readText()) }.getOrDefault(false)
/** Android mounts FAT32 as vfat and exFAT as exfat; /storage is a FUSE view, so the lookup uses the raw mount. */
internal fun isFat32(path: String, mounts: String): Boolean {
val raw = UsbLink.rawPath(path)
return mounts.lineSequence().map { it.split(' ') }
.filter { it.size >= 3 }
.filter { val point = it[1].replace("\\040", " "); raw == point || raw.startsWith("${point.trimEnd('/')}/") }
.maxByOrNull { it[1].length }?.get(2) == "vfat"
}
fun effective(context: Context): Option? {
val pref = SessionPrefs.gameStorage(context)
return when {
@@ -27,14 +27,14 @@ object GameThreadHints {
private const val PACE_TOLERANCE = 0.08
private val NOT_GAMES = setOf("steam", "steamwebhelper")
private val SOCS = setOf("CQ8725S", "SM8750")
private val SOCS = setOf("CQ8725S", "SM8750", "SM8750P")
private var worker: Thread? = null
@Synchronized
fun start(context: Context): String {
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
if (Build.VERSION.SDK_INT < 31 || !supported(Build.SOC_MODEL)) return "game thread hints: Snapdragon 8 Elite only"
if (Build.VERSION.SDK_INT < 31 || !supported(SocNames.model())) return "game thread hints: Snapdragon 8 Elite only"
val hm = context.getSystemService(PerformanceHintManager::class.java)
?: return "game thread hints: no PerformanceHintManager"
val pm = context.getSystemService(PowerManager::class.java)
@@ -11,7 +11,15 @@ import java.io.RandomAccessFile
import java.nio.charset.StandardCharsets
class LoadingState(context: Context, private val steam: Boolean = true) {
var visible by mutableStateOf(true)
private val prefs = context.getSharedPreferences("loading", Context.MODE_PRIVATE)
private val firstRun = steam && !prefs.getBoolean(FIRST_DONE, false)
private var shown by mutableStateOf(true)
var visible: Boolean
get() = shown
set(value) {
shown = value
if (!value && steam) prefs.edit().putBoolean(FIRST_DONE, true).apply()
}
var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting))
private set
var topic by mutableStateOf(Topic.SESSION)
@@ -33,7 +41,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
fun tick() {
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
elapsed = res.getString(com.droiddeck.launcher.R.string.loadstate_elapsed, seconds / 60, seconds % 60)
hint = hints[((seconds / 8) % hints.size).toInt()]
hint = if (firstRun) res.getString(com.droiddeck.launcher.R.string.loading_first_run) else hints[((seconds / 8) % hints.size).toInt()]
}
fun say(line: String, topic: Topic, readable: Boolean) {
@@ -59,6 +67,8 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
private class Line(val line: String, val percent: Int, val topic: Topic, val readable: Boolean)
private var scriptStep: Line? = null
private fun read(context: Context, log: File?): Line? {
if (log == null || !log.isFile) return null
val text = try {
@@ -81,6 +91,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
var clientDownloadAt = -1
var clientDownload: String? = null
var clientPercent = -1
var unknownAt = -1
var offset = 0
for (line in text.split('\n')) {
val at = offset
@@ -95,16 +106,34 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
}
} else {
val m = UPDATE_PROGRESS.find(line)
val p = if (m == null && steam) UPDATE_PERCENT.find(line) else null
if (m != null) {
downloadAt = at
val done = m.groupValues[1].toLong()
val total = maxOf(1L, m.groupValues[2].toLong())
val done = m.groupValues[1].replace(",", "").toLong()
val total = maxOf(1L, m.groupValues[2].replace(",", "").toLong())
downloadPercent = (done * 100 / total).toInt()
} else if (p != null) {
val percent = p.groupValues[1].toIntOrNull() ?: continue
if (percent < 0) {
downloadAt = -1
unknownAt = at
} else if (percent > 0 && applyingAt <= stepAt) {
downloadAt = at
downloadPercent = percent.coerceAtMost(100)
}
} else if (steam && UPDATE_APPLYING.matches(line)) {
applyingAt = at
}
}
}
val stepLine = when {
clientDownloadAt == stepAt && clientDownload != null -> Line(
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent,
Topic.STEAM, readable = true,
)
stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText))
else -> null
}?.also { scriptStep = it }
return when {
applyingAt > stepAt && applyingAt > downloadAt -> Line(
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1,
@@ -114,11 +143,10 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent,
Topic.STEAM, readable = true,
)
clientDownloadAt == stepAt && clientDownload != null -> Line(
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent,
Topic.STEAM, readable = true,
stepLine != null -> stepLine
unknownAt >= 0 -> scriptStep ?: Line(
context.getString(com.droiddeck.launcher.R.string.loadstate_starting), -1, Topic.SESSION, readable = false,
)
stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText))
else -> null
}
}
@@ -126,6 +154,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER }
companion object {
private const val FIRST_DONE = "first_done"
internal fun topicOf(scriptStep: String, steam: Boolean): Topic {
val t = scriptStep.lowercase()
return when {
@@ -157,7 +186,8 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
}
private const val TAIL_BYTES = 48L * 1024
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
private val UPDATE_PROGRESS = Regex("""Downloading update \(([\d,]+) of ([\d,]+) KB\)""")
private val UPDATE_PERCENT = Regex("""^\[[^\]]+\] Set percent complete: (-?\d+)\s*$""")
private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""")
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
@@ -0,0 +1,157 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.runtime.RuntimeInstallService
import kotlinx.coroutines.flow.MutableStateFlow
/** What first run installs by itself, in the order it is needed, and how far each part has got. */
object Onboarding {
enum class Step { RUNTIME, PROTON, STEAM }
data class Progress(val label: String, val percent: Int)
data class Facts(val runtime: Boolean = true, val proton: Boolean = true, val steam: Boolean = true)
enum class State { DONE, ACTIVE, WAITING, FAILED }
data class Row(val step: Step, val state: State, val label: String?, val percent: Int)
val active = MutableStateFlow<Map<Step, Progress>>(emptyMap())
val failed = MutableStateFlow<Map<Step, String>>(emptyMap())
val facts = MutableStateFlow(Facts())
@Volatile private var appContext: Context? = null
private var hold: (() -> Unit)? = null
/** The setup screens belong to the first run; later runtime, Proton and Steam client updates keep the usual Play button. */
val firstRun = MutableStateFlow(true)
fun attach(context: Context) {
appContext = context.applicationContext
val prefs = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
var done = prefs.getBoolean(KEY_FIRST_RUN_DONE, false)
if (!done && runCatching { installedAndReady(context) }.getOrDefault(false)) {
done = true
prefs.edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
}
firstRun.value = !done
}
/** Everything first run installs is in place, with the same Proton rule as [recheck]. */
private fun installedAndReady(context: Context): Boolean {
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
return LinuxRuntime.isInstalled(context) && !SteamClientPrefetch.pending(context) &&
(ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty())
}
private const val PREFS = "onboarding"
private const val KEY_FIRST_RUN_DONE = "first_run_done"
private fun markFirstRunDone() {
val context = appContext ?: return
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
firstRun.value = false
}
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
@Synchronized private fun keepAlive() {
val context = appContext ?: return
val running = active.value
if (running.isNotEmpty() && !LinuxRuntimeInstaller.isBusy()) {
if (hold == null) hold = RuntimeInstallService.holdForPackage(context, context.getString(R.string.onboarding_title))
val rows = rows(running, failed.value, facts.value)
RuntimeInstallService.packageProgress(running.values.first().label, overall(rows))
} else {
hold?.invoke()
hold = null
}
}
@Synchronized fun recheck(context: Context) {
val runtime = LinuxRuntime.isInstalled(context)
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
facts.value = Facts(
runtime = runtime,
proton = ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty(),
steam = runtime && !SteamClientPrefetch.pending(context),
)
settle()
}
/** A new attempt starts from zero once everything is ready, whichever screen is showing. */
@Synchronized fun settle() {
if (!pending(rows(active.value, failed.value, facts.value))) {
resetProgress()
markFirstRunDone()
}
}
fun report(step: Step, label: String, percent: Int) {
failed.value = failed.value - step
active.value = active.value + (step to Progress(label, percent))
keepAlive()
}
fun finish(step: Step) {
active.value = active.value - step
failed.value = failed.value - step
keepAlive()
}
fun fail(step: Step, message: String) {
active.value = active.value - step
failed.value = failed.value + (step to message)
keepAlive()
}
fun rows(active: Map<Step, Progress>, failed: Map<Step, String>, facts: Facts): List<Row> = Step.entries.map { step ->
val ready = when (step) { Step.RUNTIME -> facts.runtime; Step.PROTON -> facts.proton; Step.STEAM -> facts.steam }
val progress = active[step]
when {
progress != null -> Row(step, State.ACTIVE, progress.label, progress.percent)
failed[step] != null -> Row(step, State.FAILED, failed[step], -1)
ready -> Row(step, State.DONE, null, 100)
else -> Row(step, State.WAITING, null, -1)
}
}
fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE }
/** Whether first-run downloads are under way, as the home screen decides it. */
fun settling(): Boolean = firstRun.value && active.value.isNotEmpty() && pending(rows(active.value, failed.value, facts.value))
@Volatile private var highWater = 0
@Synchronized internal fun resetProgress() { highWater = 0 }
/**
* The aggregate fraction of the whole first-run work, weighting each step by what it downloads: about 290 MB, 630 MB and 1,050 MB.
* Steps download first and install later, restarting their own percent, so the figure only moves forward until everything is done.
*/
@Synchronized fun overall(rows: List<Row>): Int {
val measured = measure(rows)
if (!pending(rows)) {
highWater = 0
return measured
}
highWater = maxOf(highWater, measured)
return highWater
}
internal fun measure(rows: List<Row>): Int {
val weights = mapOf(Step.RUNTIME to 20, Step.PROTON to 30, Step.STEAM to 50)
val total = weights.values.sum()
val got = rows.sumOf { row ->
val w = weights.getValue(row.step)
when (row.state) {
State.DONE -> w
State.ACTIVE -> if (row.percent >= 0) w * row.percent / 100 else 0
else -> 0
}
}
return got * 100 / total
}
}
@@ -23,7 +23,12 @@ object ProtonExtras {
const val CHECK_EVERY_MS = 60L * 60 * 1000
@Volatile
var installInProgress = false
@Volatile var prefetching = false
private set
@Volatile private var checkedArchive: Triple<String, Long, Long>? = null
@Volatile private var checkedDigest: String? = null
private fun fingerprint(archive: File) = Triple(archive.path, archive.length(), archive.lastModified())
@Volatile
private var replacing = false
@@ -217,24 +222,12 @@ object ProtonExtras {
@Synchronized
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (installInProgress) return context.getString(R.string.pextra_busy)
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
installInProgress = true
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
}
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
return context.getString(R.string.pextra_no_space, tool.name)
}
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
onProgress(downloading, 0)
var downloaded = false
@@ -252,6 +245,46 @@ object ProtonExtras {
}
}
if (!downloaded) return context.getString(R.string.pextra_download_failed)
return null
}
/** Downloads the newest build of [tool] ahead of the runtime it installs into; [install] verifies and unpacks it later. */
@Synchronized
fun prefetch(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (installInProgress) return context.getString(R.string.pextra_busy)
prefetching = true
try { return prefetchNow(context, tool, onProgress) } finally { prefetching = false }
}
private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name)
val problem = fetchArchive(context, tool, asset, archive, onProgress)
checkedArchive = if (problem == null && asset.sha256 != null && asset.size > 0 && archive.length() == asset.size) fingerprint(archive) else null
checkedDigest = if (checkedArchive != null) asset.sha256 else null
return problem
}
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
return context.getString(R.string.pextra_no_space, tool.name)
}
val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) &&
checkedDigest.equals(asset.sha256, ignoreCase = true)
if (!checked) fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
if (asset.size > 0 && archive.length() != asset.size) {
if (archive.length() > asset.size) {
archive.delete()
@@ -262,6 +295,7 @@ object ProtonExtras {
onProgress(context.getString(R.string.pextra_verifying), -1)
val verified = when {
checked -> true
asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true)
asset.sha512 != null -> {
val expected = Downloader.downloadDirect(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
@@ -0,0 +1,38 @@
package com.droiddeck.launcher.session
/** A launch the user asked for that waits for something else to finish first, and is forgotten if it waits too long. */
class QueuedLaunch<T : Any>(private val lifetimeMs: Long = 15 * 60_000L) {
var launch: T? = null
private set
var queuedAt: Long = 0L
private set
fun queue(launch: T, now: Long) {
this.launch = launch
queuedAt = now
}
/** Takes back a saved launch with the time it was first queued; one without a valid time or past its lifetime is dropped. */
fun restore(launch: T?, queuedAt: Long, now: Long) {
if (launch != null && fresh(queuedAt, now)) {
this.launch = launch
this.queuedAt = queuedAt
} else {
clear()
}
}
/** The launch if it is still wanted; an expired one is cleared. */
fun current(now: Long): T? {
val queued = launch ?: return null
if (fresh(queuedAt, now)) return queued
clear()
return null
}
fun clear() {
launch = null
}
private fun fresh(queuedAt: Long, now: Long) = now - queuedAt in 0..lifetimeMs
}
@@ -0,0 +1,51 @@
package com.droiddeck.launcher.session
/**
* Starts a queued launch once nothing stands in its way and retries until it can or it expires. One runner belongs to one
* activity: destroying it clears its queue and cancels its retry, so a restored activity is the only one that starts the launch.
*/
class QueuedLaunchRunner<T : Any>(
private val queue: QueuedLaunch<T>,
private val now: () -> Long,
private val blocked: () -> Boolean,
private val busy: () -> Boolean,
private val schedule: (delayMs: Long, task: Runnable) -> Unit,
private val unschedule: (Runnable) -> Unit,
private val start: (T) -> Unit,
private val retryMs: Long = 2_000L,
) {
private var posted = false
private var retry: Runnable? = null
private var destroyed = false
/** Call whenever the blocking setting may have changed. */
fun poke() {
if (destroyed || posted) return
val launch = queue.current(now()) ?: return
if (blocked()) return
posted = true
schedule(0L, Runnable {
posted = false
attempt(launch)
})
}
private fun attempt(launch: T) {
if (destroyed || queue.current(now()) !== launch) return
if (busy()) {
val again = Runnable { if (!destroyed && queue.launch === launch) poke() }
retry = again
schedule(retryMs, again)
return
}
queue.clear()
start(launch)
}
fun destroy() {
destroyed = true
queue.clear()
retry?.let(unschedule)
retry = null
}
}
@@ -12,6 +12,9 @@ object SessionDisplay {
const val FOLLOW_SCALE_MAX = 8f
private const val FOLLOW_SCALED_PREFIX = "follow/"
const val LINK_LANDSCAPE = "link/landscape"
const val LINK_PORTRAIT = "link/portrait"
const val DEFAULT_RESOLUTION = "720p"
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
@@ -35,6 +38,23 @@ object SessionDisplay {
else -> null
}
fun isLink(choice: String): Boolean = choice == LINK_LANDSCAPE || choice == LINK_PORTRAIT
fun orientCustom(choice: String, portrait: Boolean): String {
val parts = choice.split('x').map { it.toIntOrNull() }
if (parts.size != 2 || parts.any { it == null || it <= 0 }) return choice
val width = parts[0]!!
val height = parts[1]!!
return if ((portrait && width > height) || (!portrait && height > width)) "${height}x$width" else choice
}
fun effectiveChoice(landscape: String, portrait: String, forPortrait: Boolean): String {
val own = if (forPortrait) portrait else landscape
if (!isLink(own)) return own
val other = if (forPortrait) landscape else portrait
return if (isLink(other)) DEFAULT_RESOLUTION else orientCustom(other, forPortrait)
}
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
@@ -69,8 +89,12 @@ object SessionDisplay {
const val UNFOLDED_MIN_DP = 600
fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0): Int =
(minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) - tabRow.coerceAtLeast(0)).coerceAtLeast(0) and 1.inv()
fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0, aspect: Float = 0f): Int {
val row = tabRow.coerceAtLeast(0)
val cap = (height * UNFOLDED_MAX_GAME_SHARE).toInt()
if (aspect > 0f && aspect < 16f / 9f) return minOf((width / aspect).toInt(), cap - row).coerceAtLeast(0) and 1.inv()
return (minOf(width * 9 / 16, cap) - row).coerceAtLeast(0) and 1.inv()
}
fun unfoldedControlsWanted(
enabled: Boolean,
@@ -95,7 +95,11 @@ object SessionFiles {
return all
}
fun stage(context: Context, root: File, startsSession: Boolean = false) {
private val STAGE_LOCK = Any()
fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
GameEnvironmentStore.publish(context)
@@ -126,6 +130,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply",
"usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale",
"usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language",
"usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders",
@@ -180,6 +185,8 @@ object SessionFiles {
"usr/local/bin/droiddeck-flatpak-run" to "usr/local/bin/droiddeck-flatpak-run",
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
"usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec",
"usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge",
"usr/local/bin/droiddeck-headless" to "usr/local/bin/droiddeck-headless",
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
@@ -287,6 +294,7 @@ object SessionFiles {
File(root, "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json").delete()
LegacyNames.migrateRootfs(root)
ComponentsManager.migrateLaunchDir(context)
runCatching { ComponentsManager.migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
EsyncPacks.stageBundled(context, root)
val directAudio = arrayOf(
"aarch64-unix/winedirectaudio.so",
@@ -657,6 +665,7 @@ object SessionFiles {
private const val UI_STATE = "UIStoreLocalSteamUIState"
private const val SORT_RECENT_OFF = "\\\"bSortedByRecent\\\":false"
private const val SORT_RECENT_ON = "\\\"bSortedByRecent\\\":true"
private const val LIBRARY_BIG_ART = "LibraryHomeBigArt"
private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}"
/**
@@ -706,7 +715,12 @@ object SessionFiles {
val block = out.substring(web.keyStart, web.close + 1)
out = out.replaceRange(web.keyStart, web.close + 1, setScalar(block, BATTERY_PREFERENCES, BATTERY_PERCENT_ON, newline))
}
return seedRecentSort(out, newline)
out = seedRecentSort(out, newline)
val last = findObject(out, "UserLocalConfigStore", 0, out.length) ?: return out
if (!hasKey(out.substring(last.open + 1, last.close), LIBRARY_BIG_ART)) {
out = insertInto(out, last, listOf("\"$LIBRARY_BIG_ART\"\t\t\"1\""), newline)
}
return out
}
// The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort,
@@ -726,9 +740,11 @@ object SessionFiles {
private fun insertInto(text: String, parent: VdfBlock, lines: List<String>, newline: String): String {
val lineStart = text.lastIndexOf('\n', parent.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t"
val before = text.substring(lineStart, parent.close)
val indent = before.takeWhile { it == '\t' || it == ' ' } + "\t"
val section = lines.joinToString(newline) { indent + it } + newline
return text.substring(0, lineStart) + section + text.substring(lineStart)
if (before.isBlank()) return text.substring(0, lineStart) + section + text.substring(lineStart)
return text.substring(0, parent.close) + newline + section + text.substring(parent.close)
}
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
@@ -63,6 +63,13 @@ object SessionPrefs {
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
/** The session menu's width in dp the user dragged it to; null keeps the default. */
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
fun setDrawerWidthDp(context: Context, dp: Int) {
prefs(context).edit().putInt("drawerWidthDp", dp).apply()
}
fun setOrientation(context: Context, orientation: Int) {
require(orientationOptions.any { it.first == orientation })
prefs(context).edit().putInt("orientation", orientation).apply()
@@ -85,6 +92,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("launcherFullscreen", on).apply()
}
fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true)
fun setControllerHaptics(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("controllerHaptics", on).apply()
}
fun blackFrameInsertion(context: Context): Boolean = prefs(context).getBoolean("blackFrameInsertion", false)
fun setBlackFrameInsertion(context: Context, on: Boolean) {
@@ -419,6 +432,18 @@ object SessionPrefs {
e.remove("gameStoresEnabled").remove("soundtracksEnabled").remove("agentTab").putInt("navTabLayout", version).apply()
}
fun drawerPageOrder(context: Context): List<String> = idList(prefs(context).getString("drawerPageOrder", null))
fun setDrawerPageOrder(context: Context, order: List<String>) {
prefs(context).edit().putString("drawerPageOrder", order.joinToString(",")).apply()
}
fun drawerPageHidden(context: Context): Set<String> = idList(prefs(context).getString("drawerPageHidden", null)).toSet()
fun setDrawerPageHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply()
}
fun setNavTabHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
@@ -477,6 +502,13 @@ object SessionPrefs {
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), false)
fun hudOnlyDuringGame(context: Context): Boolean =
prefs(context).getBoolean("hudOnlyDuringGame", false)
fun setHudOnlyDuringGame(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("hudOnlyDuringGame", on).apply()
}
fun setHudEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean(hudKey(context), on).apply()
}
@@ -596,6 +628,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("backHold", on).apply()
}
fun dockedMenuController(context: Context): Boolean = prefs(context).getBoolean("dockedMenuController", false)
fun setDockedMenuController(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("dockedMenuController", on).apply()
}
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
fun setBackActionsInverted(context: Context, inverted: Boolean) {
@@ -987,7 +1025,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
}
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false)
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
@@ -1296,14 +1334,31 @@ object SessionPrefs {
private fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 720)
fun resolutionChosen(context: Context, mode: String): Boolean =
fun resolutionChosen(context: Context, mode: String, portrait: Boolean = false): Boolean =
prefs(context).contains("displayResolution.$mode") ||
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null ||
(portrait && prefs(context).contains("displayResolution.portrait.$mode"))
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>): String {
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean = false): String =
SessionDisplay.effectiveChoice(
resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait)
fun resolutionStored(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean): String {
if (!portrait) return landscapeResolutionStored(context, mode, panel)
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE
if (value == SessionDisplay.LINK_LANDSCAPE || value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) ||
SessionDisplay.presetHeight(value) != null) return value
return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE
}
fun parseOrientedResolution(text: String): Pair<Int, Int>? =
parseResolution(text) ?: text.trim().split('x', 'X', '×', '*').takeIf { it.size == 2 }
?.let { parseResolution("${it[1]}x${it[0]}") }?.let { it.second to it.first }
private fun landscapeResolutionStored(context: Context, mode: String, panel: Pair<Int, Int>): String {
val saved = prefs(context)
saved.getString("displayResolution.$mode", null)?.let { value ->
if (value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) ||
if (value == SessionDisplay.MATCH_SCREEN || value == SessionDisplay.LINK_PORTRAIT || SessionDisplay.isFollow(value) ||
SessionDisplay.presetHeight(value) != null) return value
parseResolution(value)?.let { return "${it.first}x${it.second}" }
}
@@ -1315,13 +1370,22 @@ object SessionPrefs {
else "${legacy.first}x${legacy.second}"
}
fun setResolutionChoice(context: Context, mode: String, choice: String) {
val value = if (choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) ||
fun setResolutionChoice(context: Context, mode: String, choice: String, portrait: Boolean = false) {
val link = if (portrait) SessionDisplay.LINK_LANDSCAPE else SessionDisplay.LINK_PORTRAIT
val value = if (choice == link || choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) ||
SessionDisplay.presetHeight(choice) != null) choice else {
val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" }
val size = requireNotNull(if (portrait) parseOrientedResolution(choice) else parseResolution(choice)) { "Invalid resolution" }
"${size.first}x${size.second}"
}
prefs(context).edit().putString("displayResolution.$mode", value).apply()
val panel = SessionDisplay.panelSize(context)
val landscapeStored = resolutionStored(context, mode, panel, false)
val portraitStored = resolutionStored(context, mode, panel, true)
val edit = prefs(context).edit()
if (value == link && SessionDisplay.isLink(if (portrait) landscapeStored else portraitStored)) {
val concrete = SessionDisplay.effectiveChoice(landscapeStored, portraitStored, !portrait)
edit.putString(if (portrait) "displayResolution.$mode" else "displayResolution.portrait.$mode", concrete)
}
edit.putString(if (portrait) "displayResolution.portrait.$mode" else "displayResolution.$mode", value).apply()
}
fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", DEFAULT_FEX_PRESET) ?: DEFAULT_FEX_PRESET
@@ -1960,7 +2024,7 @@ object SessionPrefs {
fun displayMode(context: Context, mode: String, program: String?): String =
if (mode == SessionService.MODE_RUN && com.droiddeck.launcher.runtime.UserApps.launches(program) &&
resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP
(resolutionChosen(context, SessionService.MODE_DESKTOP) || resolutionChosen(context, SessionService.MODE_DESKTOP, true))) SessionService.MODE_DESKTOP
else prefMode(mode)
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true)
@@ -589,7 +589,10 @@ class SessionService : Service() {
val sessionDir = openSessionFolder()
try {
SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) }
SessionEvents.step("game-environment") {
com.droiddeck.launcher.runtime.BattleNet.ensureDefaults(this, SessionState.program)
GameEnvironmentStore.publish(this)
}
} catch (e: Exception) {
Log.e(TAG, "could not publish the game environment", e)
failSession(gen, "GAME_ENVIRONMENT_FAILED", getString(R.string.session_game_environment_failed), -1)
@@ -1951,11 +1954,6 @@ class SessionService : Service() {
}
return
}
if (path == com.droiddeck.launcher.runtime.BattleNet.FEX_REQUEST) {
File(dir, path).delete()
com.droiddeck.launcher.runtime.BattleNet.answerFexRequest(this@SessionService, dir)
return
}
if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) {
val request = File(dir, path)
val text = runCatching { request.readText() }.getOrNull() ?: return
@@ -2707,6 +2705,7 @@ class SessionService : Service() {
gameId: String? = null,
displayId: Int = Display.DEFAULT_DISPLAY,
) {
SteamClientPrefetch.cancel()
SessionState.activityDisplayId = displayId
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
.putExtra(EXTRA_DISPLAY_ID, displayId)
@@ -133,6 +133,7 @@ object SessionState {
@Volatile var padBridge: com.droiddeck.launcher.input.PadBridge? = null
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
@Volatile var bottomMenu = false
@Volatile var secondScreenDisplay = -1
@Volatile var secondScreenAutoOpened = false
@Volatile var secondScreenProvisional = false
@@ -12,13 +12,13 @@ object SettingsReset {
private const val TAG = "SettingsReset"
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -0,0 +1,103 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import kotlinx.coroutines.flow.update
/**
* Downloads Valve's Steam client while the session is stopped, so the first Play does not wait on it.
* It runs the same droiddeck-steam-install the session runs, which keeps what arrived when it is cut
* short and resumes from there.
*/
object SteamClientPrefetch {
private const val TAG = "SteamClientPrefetch"
private val DOWNLOADING = Regex("""downloading Steam: .*, (\d+) of (\d+) MB""")
private const val CANCELLED = "cancelled"
private val lock = Any()
private var process: Process? = null
private var cancelled = false
@Volatile private var thread: Thread? = null
internal fun parse(line: String): Pair<Int, Int>? {
val match = DOWNLOADING.find(line) ?: return null
val done = match.groupValues[1].toLongOrNull() ?: return null
val total = match.groupValues[2].toLongOrNull()?.takeIf { it > 0 } ?: return null
return (done * 100 / total).toInt().coerceIn(0, 100) to total.toInt()
}
fun running(): Boolean = thread?.isAlive == true
private const val CACHED = "root/.local/share/Steam/package/droiddeck-cached"
fun installPending(context: Context): Boolean = SteamDownloadMonitor.clientInstallPending(LinuxRuntime.rootDir(context))
fun pending(context: Context): Boolean =
installPending(context) || !File(LinuxRuntime.rootDir(context), CACHED).isFile
/** Stops a running download so a session can take over; the script resumes the partial files. */
fun cancel() {
synchronized(lock) {
cancelled = true
process?.destroy()
}
}
private fun isCancelled() = synchronized(lock) { cancelled }
@Synchronized
fun start(context: Context, label: (Int) -> String, failedLabel: String) {
if (running() || SessionState.running || !LinuxRuntime.isInstalled(context) || !pending(context)) return
val app = context.applicationContext
synchronized(lock) { cancelled = false }
thread = Thread({
Onboarding.report(Onboarding.Step.STEAM, label(-1), -1)
val problem = runCatching { run(app, label) }.getOrElse { it.message ?: it.javaClass.simpleName }
synchronized(lock) { process = null }
if (problem == null && !pending(app)) Onboarding.finish(Onboarding.Step.STEAM)
else if (SessionState.running || problem == CANCELLED || isCancelled()) Onboarding.finish(Onboarding.Step.STEAM)
else Onboarding.fail(Onboarding.Step.STEAM, problem ?: failedLabel)
val steamReady = !pending(app)
Onboarding.facts.update { it.copy(steam = steamReady) }
Onboarding.settle()
}, "steam-client-prefetch").also { it.start() }
}
private fun run(context: Context, label: (Int) -> String): String? {
if (isCancelled()) return CANCELLED
val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, root)
val install = installPending(context)
val cacheProblem = script(context, listOf("--cache"), label, 0, if (install) 90 else 100)
if (cacheProblem == CANCELLED || !install) return cacheProblem
return script(context, emptyList(), label, 90, 100)
}
private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? {
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share", "/usr/local/bin/droiddeck-steam-install",
) + args
if (isCancelled()) return CANCELLED
val child = ProtonExtras.guestProcess(context, guest).start()
synchronized(lock) {
if (cancelled) {
child.destroy()
return CANCELLED
}
process = child
}
child.inputStream.bufferedReader().useLines { lines ->
lines.forEach { line ->
Log.i(TAG, line)
val progress = parse(line)
if (progress != null) Onboarding.report(Onboarding.Step.STEAM, label(progress.second), from + progress.first * (to - from) / 100)
}
}
val status = child.waitFor()
return if (status == 0) null else "droiddeck-steam-install exited $status"
}
}
@@ -36,13 +36,14 @@ object CloudPlan {
return Plan(transfer, conflicts, same)
}
fun up(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?): Plan {
fun up(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?, deleted: Set<String> = emptySet()): Plan {
if (baseline == null) return Plan(emptyList(), emptyList(), emptyList(), refused = "no-baseline")
val transfer = ArrayList<String>(); val conflicts = ArrayList<String>(); val same = ArrayList<String>()
for ((name, l) in local) {
val r = remote[name]
val b = baseline[name]
when {
r == null && name in deleted && !localChanged(l, b) -> Unit
r == null -> transfer += name
same(l, r) -> same += name
localChanged(l, b) && cloudChanged(r, b) -> conflicts += name
@@ -430,17 +430,20 @@ object CloudSaves {
internal fun md5(data: ByteArray): String = MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) }
private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Map<String, CloudFile> {
private class Listing(val live: Map<String, CloudFile>, val deleted: Set<String>)
private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Listing {
val files = cloud.list()
val pool = Executors.newFixedThreadPool(PARALLEL, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("cloud"))
for (f in files) if (wanted(f.name)) pool.execute { runCatching { cloud.details(f) } }
pool.shutdown(); pool.awaitTermination(2, TimeUnit.MINUTES)
return files.associateBy { it.name }
val (gone, live) = files.partition(cloud::deleted)
return Listing(live.associateBy { it.name }, gone.mapTo(HashSet()) { it.name })
}
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean, claim: () -> Boolean = { true }): Result {
val files = localFiles(dir).filterKeys(cloud::wants)
val remote = remote(cloud) { it in files }
val remote = remote(cloud) { it in files }.live
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val key = scope(store, id, dir)
val base = baseline(context, store, key)
@@ -498,9 +501,10 @@ object CloudSaves {
val base = baseline(context, store, key) ?: return Result("skipped", 0, 0, "no-baseline")
val files = localFiles(dir).filterKeys(cloud::wants).let { all -> if (cloud is UbisoftCloudTransport) all.filterValues(::markUbisoftSave) else all }
if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local")
val remote = remote(cloud) { it in files }
val listing = remote(cloud) { it in files }
val remote = listing.live
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base, listing.deleted)
val alike = alike(cloud, planned.conflicts, local, remote)
val plan = settled(planned, alike)
val saved = savedConflicts(context, store, key).filter { it !in alike && it !in plan.same }
@@ -547,7 +551,7 @@ object CloudSaves {
send = send.filter { it in stamped }
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
}
val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }
val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }.live
for (name in send) {
val r = cloud.committed(name) ?: after[name]
next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
@@ -31,6 +31,7 @@ interface CloudTransport {
val contentDigests: Boolean get() = true
fun committed(name: String): CloudFile? = null
fun wants(name: String): Boolean = true
fun deleted(file: CloudFile): Boolean = false
fun list(): List<CloudFile>
fun details(file: CloudFile) {}
fun get(file: CloudFile): Pair<ByteArray, Long>
@@ -252,6 +253,8 @@ private fun gzipFile(src: File, dst: File): GzipFile {
}
}
internal const val GOG_DELETED_MD5 = "aadd86936a80ee8a369579c3926f1b3c"
internal const val GOG_CLOUD_UA = "GOGGalaxyCommunicationService/2.0.13.27 (Windows_32bit) dont_sync_marker/true installation_source/gog"
/** GOG Galaxy parses `X-Object-Meta-LocalLastModified`; objects without it fail as "invalid data". */
@@ -276,8 +279,11 @@ class GogCloud(
private fun cloudKey(name: String) = key((prefix ?: "") + name)
override fun deleted(file: CloudFile): Boolean = file.md5.equals(GOG_DELETED_MD5, ignoreCase = true)
override fun list(): List<CloudFile> {
val c = open(base, "GET", token, ua)
c.setRequestProperty("Accept", "application/json")
val code = c.responseCode
if (code == 404) { c.disconnect(); return emptyList() }
if (code !in 200..299) {
@@ -300,7 +306,7 @@ class GogCloud(
lm > 0 -> lm * 1000
iso > 0 -> iso
else -> -1L
})
}, o.optString("hash").trim().ifEmpty { null })
}
} else {
text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) }
@@ -28,20 +28,26 @@ internal class StoreArchiveUnpacker(
private val logName: String,
) {
var work: File = File("")
var limit = Long.MAX_VALUE
fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) {
class TooLarge : java.io.IOException()
fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) =
unpack(archive, filename, { done, total -> handle.stageProgress(done, total) }, handle::log)
fun unpack(archive: File, filename: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
when (val kind = ItchArchives.kind(archive, filename)) {
"zip" -> unzip(archive, handle)
"zip" -> unzip(archive, progress, log)
"7z" -> try {
sevenZip(archive, handle)
sevenZip(archive, progress, log)
} catch (e: MemoryLimitException) {
handle.log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
unrar(archive, handle, kind)
log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
unrar(archive, progress, log, kind)
}
"rar" -> unrar(archive, handle, kind)
"rar" -> unrar(archive, progress, log, kind)
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
"tar" -> untar(archive, null, handle)
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
"tar" -> untar(archive, null, progress, log)
"gz", "bz2", "xz" -> untar(archive, kind, progress, log) ?: single(archive, kind, progress, log)
else -> copy(archive, File(work, filename.ifBlank { "game" }))
}
}
@@ -53,7 +59,7 @@ internal class StoreArchiveUnpacker(
return if (path == root || path.startsWith(root + File.separator)) file else null
}
private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) {
private fun unrar(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit, kind: String) {
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(unsupported, kind))
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(work.absolutePath)
@@ -62,23 +68,28 @@ internal class StoreArchiveUnpacker(
if (!line.startsWith("proot ")) onLine(line)
}
var entries = 0L
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
var size = 0L
bsdtar(listOf("-tvf", archive.absolutePath)) { line ->
entries++
size += LISTED_SIZE.find(line)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
}
if (size > limit) throw TooLarge()
var done = 0L
val tail = ArrayDeque<String>()
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
if (line.startsWith("x ")) progress(++done, entries) else {
if (tail.size == 5) tail.removeFirst()
tail.addLast(line)
}
}
if (cancelled.get()) return
if (code != 0) {
handle.log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}")
log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}")
throw IllegalStateException(app.getString(extractFailed, code))
}
}
private fun sevenZip(archive: File, handle: DownloadQueue.JobHandle) {
private fun sevenZip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
@@ -90,7 +101,7 @@ internal class StoreArchiveUnpacker(
val entry = seven.nextEntry ?: break
val file = target(entry.name)
if (file == null) {
handle.log("$label: skipped an entry outside the game folder")
log("$label: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
@@ -105,7 +116,8 @@ internal class StoreArchiveUnpacker(
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
if (written > limit) throw TooLarge()
progress(written, total)
}
}
}
@@ -113,7 +125,7 @@ internal class StoreArchiveUnpacker(
}
}
private fun untar(archive: File, codec: String?, handle: DownloadQueue.JobHandle): Unit? {
private fun untar(archive: File, codec: String?, progress: (Long, Long) -> Unit, log: (String) -> Unit): Unit? {
val total = archive.length()
var written = 0L
var entries = 0
@@ -134,7 +146,7 @@ internal class StoreArchiveUnpacker(
entries++
val file = target(entry.name)
if (file == null) {
handle.log("$label: skipped an entry outside the game folder")
log("$label: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
@@ -149,7 +161,8 @@ internal class StoreArchiveUnpacker(
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
if (written > limit) throw TooLarge()
progress(written, total)
}
}
}
@@ -163,7 +176,7 @@ internal class StoreArchiveUnpacker(
return null
}
private fun single(archive: File, codec: String, handle: DownloadQueue.JobHandle) {
private fun single(archive: File, codec: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
val name = archive.name.substringBeforeLast('.')
val file = target(name.ifBlank { "game" }) ?: throw IllegalStateException("archive")
file.parentFile?.mkdirs()
@@ -184,7 +197,8 @@ internal class StoreArchiveUnpacker(
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
if (written > limit) throw TooLarge()
progress(written, total)
}
}
}
@@ -196,7 +210,7 @@ internal class StoreArchiveUnpacker(
FileInputStream(source).use { input -> FileOutputStream(target).use { out -> input.copyTo(out, 128 * 1024) } }
}
private fun unzip(archive: File, handle: DownloadQueue.JobHandle) {
private fun unzip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
@@ -205,7 +219,7 @@ internal class StoreArchiveUnpacker(
if (cancelled.get()) return
val target = target(entry.name)
if (target == null) {
handle.log("$label: skipped an entry outside the game folder")
log("$label: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
@@ -221,11 +235,16 @@ internal class StoreArchiveUnpacker(
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
if (written > limit) throw TooLarge()
progress(written, total)
}
}
}
}
}
}
private companion object {
val LISTED_SIZE = Regex("""^\S+\s+\d+\s+\S+\s+\S+\s+(\d+)\s""")
}
}
@@ -100,6 +100,7 @@ internal object GogContent {
val manifest = metadata(build.link, token)
onManifest(manifest)
val files = JSONArray()
val overlayPositions = HashMap<String, Int>()
val depots = if (build.generation == 1) manifest.optJSONObject("product")?.optJSONArray("depots") ?: manifest.optJSONArray("depot") else manifest.optJSONArray("depots")
check(depots != null) { "GOG build has no depot list" }
val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language)
@@ -132,10 +133,15 @@ internal object GogContent {
val directory = type == "DepotDirectory" || entry.has("directory")
val chunks = entry.optJSONArray("chunks") ?: JSONArray()
val size = if (build.generation == 2) chunks.objects().sumOf { it.optLong("size") } else entry.optLong("size")
files.put(JSONObject().put("path", path).put("size", size).put("directory", directory)
val file = JSONObject().put("path", path).put("size", size).put("directory", directory)
.put("md5", entry.optString("md5").ifBlank { entry.optString("hash") }.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) }.orEmpty())
.put("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product)
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?')))
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?'))
val position = if (build.generation == 2) overlayPositions.putIfAbsent(path, files.length()) else null
if (position == null) files.put(file) else {
require(files.getJSONObject(position).getBoolean("directory") == directory)
files.put(position, file)
}
}
}
check(files.length() > 0) { "GOG build contains no matching files" }
@@ -330,7 +330,7 @@ public final class GogDownloadManager {
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
"-d", guestDir, guestSetup),
false, "gog-innoextract", null, null, false, cancelled,
false, "gog-innoextract", null, null, false, cancelled, null,
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
} catch (Exception e) {
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
@@ -103,7 +103,9 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
XboxContent.complete(app, item, folder)
return folder.path
}
val exe = executable(folder)
val exe = runCatching { executable(folder) }.onFailure {
StoresState.logLine("Xbox: install folder holds ${folder.list().orEmpty().sorted().take(MAX_ERROR_LINES).joinToString()}")
}.getOrThrow()
StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
extra = item.extra + mapOf("contentId" to selected, "market" to market)))
@@ -21,8 +21,9 @@ internal object XboxManifest {
val files = folder.listFiles().orEmpty()
val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile }
val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile }
require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." }
val manifest = (config + legacy).single()
val manifests = config.ifEmpty { legacy }
require(manifests.size == 1) { "Missing or ambiguous game manifest." }
val manifest = manifests.single()
val rootTag = if (config.isEmpty()) "Package" else "Game"
require(manifest.length() <= 1_048_576)
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
@@ -0,0 +1,239 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.ImeOptions
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import kotlin.math.min
import kotlin.math.roundToInt
@Composable
internal 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 = {},
clearFocus: Boolean = false,
onNext: (() -> Unit)? = null,
onDone: (() -> Unit)? = null,
focusOnShow: Boolean = false,
showLabel: Boolean = true,
focusAtTap: Int? = null,
onBack: (() -> Unit)? = null,
) {
val context = LocalContext.current
val onBackLatest = rememberUpdatedState(onBack)
val focusAsked = remember { booleanArrayOf(false) }
val focusTapAsked = remember { arrayOfNulls<Int>(1) }
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
val bottomTyping = LocalBottomTyping.current
val bottomTypingLatest = rememberUpdatedState(bottomTyping)
val typingRequest = remember { arrayOfNulls<TypingRequest>(1) }
fun typeOnBottom(editText: EditText): Boolean {
if (!bottomTypingLatest.value || !DualScreenPanel.attached) return false
val text = editText.text.toString()
lateinit var request: TypingRequest
request = TypingRequest(
TextFieldValue(text, TextRange(editText.selectionStart.coerceIn(0, text.length), editText.selectionEnd.coerceIn(0, text.length))),
ImeOptions(singleLine = true, keyboardType = keyboardType, imeAction = imeAction),
{ next ->
if (editText.text.toString() != next.text) editText.setText(next.text)
editText.setSelection(next.selection.start.coerceIn(0, next.text.length), next.selection.end.coerceIn(0, next.text.length))
},
{ action -> editText.onEditorAction(imeActionFlag(action)) },
{ editText.post { if (typingRequest[0] === request) onBackLatest.value?.invoke() ?: editText.clearFocus() } },
)
typingRequest[0] = request
DualScreenPanel.startTyping(request)
return true
}
DisposableEffect(Unit) {
onDispose { typingRequest[0]?.let { DualScreenPanel.stopTyping(it) } }
}
Column(modifier = modifier.fillMaxWidth()) {
if (showLabel) Text(
label,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Medium,
color = colors.onSurfaceVariant,
maxLines = 1,
)
Box(
modifier = Modifier
.fillMaxWidth()
.height(inputHeight)
.background(colors.surfaceVariant, shape)
.glideBorder(focused, shape, palette.signal, palette.line2)
.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
}
// Search and Go are terminal: leaving them unhandled
// keeps focus in the field, so the keyboard would stay
// up over the results it was used to find.
imeAction in setOf(ImeAction.Search, ImeAction.Go) &&
(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || isEnter) -> {
onDoneLatest.value?.invoke()
post {
clearFocus()
(context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)
as? android.view.inputmethod.InputMethodManager)
?.hideSoftInputFromWindow(windowToken, 0)
}
true
}
else -> false
}
}
showSoftInputOnFocus = !bottomTyping
// B on a controller puts the keyboard away first; with no keyboard up it goes back as usual.
var hidingKeyboard = false
setOnKeyListener { view, keyCode, event ->
if (keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return@setOnKeyListener false
if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
hidingKeyboard = androidx.core.view.ViewCompat.getRootWindowInsets(view)
?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true
if (hidingKeyboard) (view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.hideSoftInputFromWindow(view.windowToken, 0)
onBackLatest.value?.let { hidingKeyboard = true; it() }
}
hidingKeyboard
}
setOnClickListener { if (hasFocus() && !typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) }
setOnFocusChangeListener { _, hasFocus ->
focused = hasFocus
if (hasFocus) { if (!typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) }
else typingRequest[0]?.let { DualScreenPanel.stopTyping(it) }
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.showSoftInputOnFocus = !bottomTyping
// A new tap may ask again: a field still on screen while it closes can be opened once more.
val fresh = if (focusAtTap != null) focusTapAsked[0] != focusAtTap else !focusAsked[0]
if (focusOnShow && fresh) {
if (focusAtTap != null) focusTapAsked[0] = focusAtTap else focusAsked[0] = true
editText.post {
if (focusAtTap != null && focusAtTap != ScreenTaps.count) return@post
editText.requestFocus()
if (!bottomTypingLatest.value) (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
}
}
if (clearFocus && editText.hasFocus()) {
editText.clearFocus()
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.hideSoftInputFromWindow(editText.windowToken, 0)
}
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))
}
},
)
}
}
}
private fun showKeyboardHere(editText: EditText) {
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
}
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
}
@@ -311,6 +311,7 @@ internal fun AppDialog(
width: Dp? = null, fitContent: Boolean = false,
back: (() -> Unit)? = null,
scrollable: Boolean = true,
fillHeight: Boolean = false,
scrollState: androidx.compose.foundation.ScrollState = rememberScrollState(),
side: (@Composable () -> Unit)? = null,
sideRoom: Dp = 0.dp,
@@ -348,6 +349,7 @@ internal fun AppDialog(
},
)
.heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp)
.then(if (fillHeight) Modifier.fillMaxHeight() else Modifier)
.shadow(24.dp, Shape16, ambientColor = Color.Black, spotColor = Color.Black)
.clip(Shape16)
.background(pal.surfaceVariant.copy(alpha = 0.97f))
@@ -358,7 +360,7 @@ internal fun AppDialog(
.then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier)
.padding(horizontal = 18.dp, vertical = 16.dp),
) {
content()
androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content() }
if (side != null && !beside) side()
}
}
@@ -1,29 +1,33 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.horizontalScroll
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.PaddingValues
import androidx.compose.foundation.layout.Row
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.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -33,26 +37,53 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.withFrameNanos
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.CurseForgeApp
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.runtime.WowAddonCatalog
import com.droiddeck.launcher.runtime.WowAddons
import com.droiddeck.launcher.session.SessionState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
private class AddonResults {
val items = mutableStateListOf<WowAddonCatalog.Addon>()
@@ -62,8 +93,178 @@ private class AddonResults {
var more by mutableStateOf(false)
}
internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
private enum class AddonSource { WOWI, CURSE }
internal class CurseState(val notice: Int? = null) : Exception()
internal class CurseLink(val app: UserApps.App) {
class Linked(val inspector: String, val guid: String)
private val lock = Object()
private val work = SupervisorJob()
@Volatile private var closed = false
@Volatile private var hold: AtomicBoolean? = null
@Volatile private var inspector: String? = null
private val guids = HashMap<String, String>()
private val scanLock = Object()
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
private val settleLock = Object()
private val settled = HashMap<String, Pair<Int, List<CurseForgeApp.Project>>>()
private val turns = HashMap<String, Int>()
var generation by mutableIntStateOf(0)
private set
fun refresh() {
generation++
}
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
synchronized(scanLock) {
scans[target.addOns.path]?.takeIf { it.first == key }?.second
?: (settledFor(target) ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }).also {
scans[target.addOns.path] = key to it
report(target, it)
}
},
target.addOns,
)
fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> =
runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) }
private fun settledFor(target: WowAddons.Target): List<CurseForgeApp.Project>? = synchronized(settleLock) {
settled.remove(target.addOns.path)?.takeIf { it.first == generation }?.second
}
fun change(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> List<CurseForgeApp.Project>?): Boolean {
val path = target.addOns.path
val turn = synchronized(settleLock) {
settled.remove(path)
((turns[path] ?: 0) + 1).also { turns[path] = it }
}
val projects = call(context, target, launch, block) ?: return false
synchronized(settleLock) {
if (turns[path] == turn) {
settled[path] = generation to projects
report(target, projects)
}
}
return true
}
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
val linked = synchronized(lock) { link(context, target, launch) }
try {
return block(linked)
} catch (e: CurseForgeApp.Failure) {
if (e.gone) synchronized(lock) {
if (inspector == linked.inspector) {
inspector = null
guids.clear()
current.compareAndSet(this, null)
}
}
throw e
}
}
private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked {
if (closed) throw CurseState()
val url = inspector ?: run {
if (!launch) throw CurseState()
val hold = AtomicBoolean(false)
this.hold = hold
if (closed) throw CurseState()
val done = CurseForgeApp.start(context, app, hold)
when (done.state) {
CurseForgeApp.Start.READY -> {
inspector = done.inspector
if (!closed) current.set(this)
done.inspector ?: throw CurseState()
}
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
else -> throw CurseState()
}
}
if (closed) throw CurseState()
guids[target.addOns.path]?.let { return Linked(url, it) }
val root = WowAddons.root(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val flavor = WowAddons.flavorDir(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val guid = CurseForgeApp.instance(context, url, root, flavor)
guids[target.addOns.path] = guid
return Linked(url, guid)
}
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = change(context, target, launch = false) { linked ->
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() }
}
internal val stopped: Job get() = work
fun close(context: Context): Job {
closed = true
current.compareAndSet(this, null)
val launch = hold
return CoroutineScope(work + Dispatchers.IO).launch {
if (launch != null) CurseForgeApp.stop(context, app, inspector, launch)
synchronized(lock) {
hold = null
inspector = null
}
}.also { work.complete() }
}
companion object {
private val current = AtomicReference<CurseLink?>()
private val reported = ConcurrentHashMap<String, List<CurseForgeApp.Project>>()
fun lastReported(target: WowAddons.Target, disk: () -> List<WowAddons.Installed> = { WowAddons.details(target) }): Map<String, String?> {
val last = reported[target.addOns.path] ?: return disk().mapNotNull { it.curseId }.associateWith { null }
return CurseForgeApp.onDisk(last, target.addOns).associate { it.id to null }
}
internal fun report(target: WowAddons.Target, projects: List<CurseForgeApp.Project>) {
reported[target.addOns.path] = projects
}
fun live(): CurseLink? = current.get()
}
}
private const val PAGES_AHEAD = 8
private const val CURSE_UPDATE = "update"
private const val UNINSTALLING = -1
private fun curseMark(project: CurseForgeApp.Project): String? = CURSE_UPDATE.takeIf { project.update }
private class Present(val curse: Map<String, String?> = emptyMap(), val disk: Map<String, WowAddons.Installed> = emptyMap())
@Composable
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, onDismiss: () -> Unit) {
internal fun rememberCurseLink(app: UserApps.App?, sessionRunning: Boolean): CurseLink? {
val context = LocalContext.current.applicationContext
val owner = LocalLifecycleOwner.current
var visible by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
DisposableEffect(owner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_START) visible = true
if (event == Lifecycle.Event.ON_STOP) visible = false
}
owner.lifecycle.addObserver(observer)
onDispose { owner.lifecycle.removeObserver(observer) }
}
val active = visible && !sessionRunning
val link = remember(app?.key, active) { app?.takeIf { active }?.let(::CurseLink) }
DisposableEffect(link) {
onDispose { link?.close(context) }
}
return link
}
@Composable
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, link: CurseLink?, onDismiss: () -> Unit) {
val context = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
val shown = rememberShown(onDismiss)
@@ -72,12 +273,34 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
var text by remember { mutableStateOf("") }
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
val results = remember(text, category, sort, target) { AddonResults() }
var source by remember { mutableStateOf(AddonSource.WOWI) }
val curse = if (source == AddonSource.CURSE && link != null) curseForge else null
LaunchedEffect(link) { link?.refresh() }
var notice by remember { mutableStateOf<Int?>(null) }
var curseInstalls by remember { mutableIntStateOf(0) }
val results = remember(text, category, sort, target, curse) { AddonResults() }
val installing = remember { mutableStateMapOf<String, Int>() }
val installed = remember { mutableStateMapOf<String, Boolean>() }
val installed = remember { mutableStateMapOf<String, Pair<String, String>>() }
val categories by produceState(emptyList<WowAddonCatalog.Category>()) {
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
}
val presentKey = curse to target.addOns
val scanKey = link?.generation to WowAddons.imports
val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) {
val into = target
val key = curse to into.addOns
if (curse != null && link != null && value.first != key) value = key to withContext(Dispatchers.IO) { Present(curse = CurseLink.lastReported(into)) }
value = key to withContext(Dispatchers.IO) {
if (curse != null && link != null) Present(curse = link.marks(context, into, scanKey))
else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() })
}
}
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: Present()
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
if (curse != null) return if (addon.id !in present.curse) AddonStatus.INSTALL else if (present.curse[addon.id] == CURSE_UPDATE) AddonStatus.UPDATE else AddonStatus.INSTALLED
val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary
return diskStatus(addon.folders, present.disk, latest, addon.id)
}
fun load(page: Int) {
if (results.loading) return
results.loading = true
@@ -86,10 +309,16 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
val words = text
val cat = category?.id
val order = sort
val via = link?.takeIf { curse != null }
notice = null
scope.launch {
val got = withContext(Dispatchers.IO) {
runCatching { WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page) }
runCatching {
if (via != null) via.call(context, into) { CurseForgeApp.search(context, it.inspector, it.guid, words, order, page) }
else WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page)
}
}
if (results.items.isEmpty()) notice = (got.exceptionOrNull() as? CurseState)?.notice
got.onSuccess {
if (page == 0) results.items.clear()
results.items.addAll(it.items.filter { addon -> results.items.none { seen -> seen.id == addon.id } })
@@ -106,6 +335,34 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
fun install(addon: WowAddonCatalog.Addon) {
val key = installKey(addon, target)
if (key in installing) return
val via = link?.takeIf { curse != null }
if (via != null) {
val into = target
val updating = status(addon) == AddonStatus.UPDATE
installing[key] = 0
scope.launch {
val done = withContext(Dispatchers.IO) {
runCatching {
via.change(context, into) {
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
}
}
}
installing.remove(key)
val ok = done.getOrNull() == true
WowAddons.changed()
curseInstalls++
val message = when {
ok && updating -> context.getString(R.string.user_apps_updated, addon.name)
ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor)
else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString)
?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name)
}
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
return
}
if (SessionState.running) {
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
return
@@ -115,48 +372,131 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
scope.launch {
val message = withContext(Dispatchers.IO) { installAddon(context, addon, into) { pct -> scope.launch { if (key in installing) installing[key] = pct } } }
installing.remove(key)
if (message.second) installed[key] = true
message.second?.let { installed[key] = addon.summary to it }
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
}
}
val sourceName = stringResource(R.string.addons_source_wowi)
AppDialog(shown, close, "addonBrowser", wide = true, scrollable = false) {
DialogTitleRow(stringResource(R.string.addons_download), close)
ModeHeader(sourceName, text, { text = it }, stringResource(R.string.stores_search_catalog, sourceName)) {
BrowseChip(stringResource(R.string.addons_source_curse), false) {
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(WowAddonCatalog.curseForgeUrl(text))).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
fun uninstall(addon: WowAddonCatalog.Addon) {
val key = installKey(addon, target)
if (key in installing) return
if (SessionState.running) {
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
return
}
ChipRow {
val into = target
val via = link?.takeIf { curse != null }
installing[key] = UNINSTALLING
scope.launch {
val done = withContext(Dispatchers.IO) {
runCatching {
val folders = if (via != null) curseFolders(into, addon.id, via.call(context, into) { linked ->
CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty()
}) else addon.folders
deleteAddons(context, into, folders, link)
}
}
installing.remove(key)
installed.remove(key)
WowAddons.changed()
curseInstalls++
if (done.isFailure) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_LONG).show()
}
}
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
val grid = rememberLazyGridState()
LaunchedEffect(results, grid) {
snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) ->
if (last != null && results.more && results.failed == null && last >= total - PAGES_AHEAD) load(results.page + 1)
}
}
val firstAction = remember(results) { FocusRequester() }
val inputMode = LocalInputModeManager.current
var searching by remember { mutableStateOf(false) }
LaunchedEffect(results, results.items.isNotEmpty()) {
if (results.items.isNotEmpty() && !searching && inputMode.inputMode == InputMode.Keyboard) focusSoon { firstAction }
}
AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true, modifier = Modifier.releaseTextFieldOnTap()) {
val sortChip: @Composable () -> Unit = {
BrowseDropdown(sortLabel(sort)) { first, done ->
WowAddonCatalog.Sort.entries.forEachIndexed { index, option ->
MenuItem(sortLabel(option), sort == option, focusRequester = if (index == 0) first else null) { sort = option; done() }
}
}
if (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
}
val sourceChip: @Composable () -> Unit = {
if (curseForge != null) BrowseDropdown(sourceName) { first, done ->
MenuItem(stringResource(R.string.addons_source_wowi), source == AddonSource.WOWI, focusRequester = first) { source = AddonSource.WOWI; done() }
MenuItem(stringResource(R.string.addons_source_curse), source == AddonSource.CURSE) { source = AddonSource.CURSE; done() }
}
}
val categoryChip: @Composable () -> Unit = {
if (curse == null && categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
MenuItem(stringResource(R.string.addons_category_all), category == null, focusRequester = first) { category = null; done() }
categories.forEach { option -> MenuItem(option.name, category?.id == option.id) { category = option; done() } }
}
}
val flavorChip: @Composable () -> Unit = {
if (targets.size > 1) BrowseDropdown(target.flavor) { first, done ->
targets.forEachIndexed { index, option ->
MenuItem(option.flavor, option.addOns == target.addOns, focusRequester = if (index == 0) first else null) { target = option; done() }
}
}
}
val height = (LocalConfiguration.current.screenHeightDp * 0.62f).dp
val search: @Composable (Modifier) -> Unit = { modifier ->
AdbTextField(
value = text, onValueChange = { text = it }, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = stringResource(R.string.stores_search_catalog, sourceName), compact = true, showLabel = false, modifier = modifier, onFocusChange = { searching = it },
)
}
val closeButton: @Composable () -> Unit = {
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.error, onClick = close)
}
BoxWithConstraints(Modifier.fillMaxWidth()) {
if (maxWidth >= 640.dp) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
search(Modifier.weight(1f))
sourceChip()
sortChip()
categoryChip()
flavorChip()
closeButton()
} else Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
search(Modifier.weight(1f))
closeButton()
}
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.horizontalScroll(rememberScrollState()),
) {
sourceChip()
sortChip()
categoryChip()
flavorChip()
}
}
}
val thumb = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
LazyVerticalGrid(
GridCells.Adaptive(libraryTileWidth() + 40.dp), Modifier.fillMaxWidth().height(height),
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
GridCells.Adaptive(400.dp), Modifier.fillMaxWidth().weight(1f).scrollThumb(grid, thumb), state = grid,
contentPadding = PaddingValues(end = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp),
) {
items(results.items, key = { it.id }) { addon ->
AddonCard(addon, installing[installKey(addon, target)], installed[installKey(addon, target)] == true) { install(addon) }
val key = installKey(addon, target)
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier, { uninstall(addon) }) { install(addon) }
}
item(key = "tail", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
item(span = { GridItemSpan(maxLineSpan) }) {
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
when {
results.loading -> LinearProgressIndicator(Modifier.fillMaxWidth())
results.failed != null -> BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
results.more -> BrowseChip(stringResource(R.string.stores_itch_load_more), false) { load(results.page + 1) }
results.failed != null && notice != null -> {
Text(stringResource(notice!!), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(0) }
}
results.failed != null -> {
Text(stringResource(R.string.addons_unreachable, sourceName), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
}
results.items.isEmpty() -> Text(stringResource(R.string.addons_none_found), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@@ -166,27 +506,69 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
}
@Composable
private fun AddonCard(addon: WowAddonCatalog.Addon, progress: Int?, done: Boolean, onInstall: () -> Unit) {
val pal = LocalPalette.current
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hot = rememberHot(src)
val shape = androidx.compose.foundation.shape.RoundedCornerShape(10.dp)
Column(
Modifier.fillMaxWidth().clip(shape).glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onInstall)
.controllerConfirm(onClick = onInstall),
) {
ArtCard(addon.name, addon.thumb, null, null, hot, capsule = false, chip = progress?.let { "$it%" }) {
if (done) Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.height(11.dp))
else Text(stringResource(if (progress != null) R.string.store_installing else R.string.store_install), fontSize = 10.sp, color = pal.signal, maxLines = 1)
}
Text(
listOf(addon.author, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "),
fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
)
internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onUninstall: () -> Unit, onInstall: () -> Unit) {
var asking by remember(addon.id) { mutableStateOf(false) }
val first = remember(addon.id) { FocusRequester() }
var refocus by remember(addon.id) { mutableStateOf(false) }
val inputMode = LocalInputModeManager.current
LaunchedEffect(status, progress) {
if (!refocus) return@LaunchedEffect
withFrameNanos { }
runCatching { first.requestFocus() }
if (progress == null) refocus = false
}
fun act(block: () -> Unit) {
refocus = inputMode.inputMode == InputMode.Keyboard
block()
}
val lead = action.focusRequester(first)
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface.copy(alpha = 0.6f)).border(1.dp, pal.line, Shape12)
.padding(start = 8.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
) {
Box(Modifier.size(44.dp).clip(Shape12).background(artBrush(hueOf(addon.name)))) {
if (addon.thumb != null) AsyncImage(model = addon.thumb, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
}
Column(Modifier.weight(1f)) {
Text(addon.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
listOf(addon.author, addon.summary, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
val uninstall = stringResource(R.string.common_uninstall)
when {
progress == UNINSTALLING -> SecondaryButton(stringResource(R.string.stores_uninstalling), compact = true, modifier = lead) {}
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = lead, progress = progress / 100f, onClick = onInstall)
status == AddonStatus.INSTALL -> PrimaryButton(stringResource(R.string.store_install), compact = true, modifier = lead) { act(onInstall) }
else -> {
if (status == AddonStatus.UPDATE) PrimaryButton(stringResource(R.string.common_update), compact = true, modifier = lead) { act(onInstall) }
SecondaryButton(uninstall, compact = true, modifier = if (status == AddonStatus.UPDATE) Modifier else lead) { asking = true }
}
}
}
if (asking) ConfirmDialog(
title = stringResource(R.string.stores_uninstall_title, addon.name),
text = stringResource(R.string.games_delete_addon_body),
confirm = stringResource(R.string.common_uninstall),
onConfirm = { asking = false; act(onUninstall) },
onDismiss = { asking = false },
)
}
private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent {
drawContent()
val info = state.layoutInfo
val visible = info.visibleItemsInfo
if (visible.isEmpty() || visible.size >= info.totalItemsCount) return@drawWithContent
val total = info.totalItemsCount.toFloat()
val length = (size.height * visible.size / total).coerceAtLeast(24.dp.toPx())
val top = (size.height - length) * (visible.first().index / (total - visible.size).coerceAtLeast(1f)).coerceIn(0f, 1f)
val width = 3.dp.toPx()
drawRoundRect(color, Offset(size.width - width, top), Size(width, length), CornerRadius(width / 2))
}
@Composable
@@ -206,21 +588,42 @@ private fun formatCount(count: Long): String = when {
else -> count.toString()
}
private fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair<String, Boolean> {
internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair<String, String?> {
val zip = File(File(context.cacheDir, "wowaddons"), "download-wowi-${addon.id.filter(Char::isLetterOrDigit)}-${java.util.UUID.randomUUID()}.zip")
return try {
WowAddonCatalog.download(context, addon, zip, progress)
if (SessionState.running) return context.getString(R.string.main_addons_close_session) to false
val names = WowAddons.import(zip, target)
if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to false
else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to true
val version = WowAddonCatalog.download(context, addon, zip, progress) ?: addon.summary
if (SessionState.running) return context.getString(R.string.main_addons_close_session) to null
val names = WowAddons.import(zip, target, WowAddons.Origin(addon.id, version).takeIf { version.isNotBlank() }, context)
if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to null
else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to version
} catch (_: WowAddons.TooLarge) {
context.getString(R.string.main_addons_too_large, addon.name) to false
context.getString(R.string.main_addons_too_large, addon.name) to null
} catch (e: Exception) {
context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to false
context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to null
} finally {
zip.delete()
}
}
internal fun diskStatus(folders: List<String>, onDisk: Map<String, WowAddons.Installed>, latest: String, id: String): AddonStatus {
if (!WowAddons.present(folders) { it.lowercase() in onDisk }) return AddonStatus.INSTALL
val have = onDisk.getValue(folders.first().lowercase())
return if (WowAddonCatalog.offersUpdate(have.version, latest, sameSource = have.wowiId == id)) AddonStatus.UPDATE else AddonStatus.INSTALLED
}
internal fun curseFolders(target: WowAddons.Target, id: String, listed: List<String>): List<String> =
listed.ifEmpty { WowAddons.details(target).filter { it.curseId == id }.map { it.name } }
internal fun deleteAddons(context: Context, target: WowAddons.Target, folders: List<String>, link: CurseLink?) {
val found = folders.mapNotNull { WowAddons.folder(target.addOns, it) }
if (found.isEmpty()) throw IOException("No addon folder to delete")
found.forEach { deleteAddon(context, target, it.name, link) }
}
internal fun deleteAddon(context: Context, target: WowAddons.Target, folder: String, link: CurseLink? = CurseLink.live()) {
val managed = link?.let { runCatching { it.uninstall(context, target, folder) }.getOrDefault(false) } == true
val left = WowAddons.folder(target.addOns, folder)
if (managed || left == null) WowAddons.changed() else WowAddons.delete(target, left.name)
}
private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.ui
import android.app.Activity
import android.content.ContextWrapper
import android.os.Build
import android.view.KeyEvent
import android.view.WindowManager
import androidx.activity.compose.LocalActivityResultRegistryOwner
@@ -10,6 +11,7 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
@@ -184,7 +186,11 @@ private fun AgentPageContent(
?: generateSequence(view.context) { (it as? ContextWrapper)?.baseContext }
.filterIsInstance<Activity>().firstOrNull()?.window
val previousMode = window?.attributes?.softInputMode
// A window fitted to the system bars with ADJUST_NOTHING reports no keyboard height to Compose.
// It stays unfitted after the page leaves: fitting it again insets the other pages twice.
val edgeToEdge = visible && hidesPet && !drawer && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
if (visible) window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
if (edgeToEdge) window?.setDecorFitsSystemWindows(false)
onDispose {
if (visible && previousMode != null) window?.setSoftInputMode(previousMode)
}
@@ -223,8 +229,14 @@ private fun AgentPageContent(
}
val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) }
val inlineControls: (@Composable () -> Unit)? = if (inline) ({
ModelChip(panel, togglePanel, inputModifier, compact = true)
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
// The open menu needs the row's width for its own buttons.
androidx.compose.animation.AnimatedVisibility(!menuOpen, enter = expandHorizontally(expandFrom = Alignment.Start) + fadeIn(),
exit = shrinkHorizontally(shrinkTowards = Alignment.Start) + fadeOut()) {
Row(verticalAlignment = Alignment.CenterVertically) {
ModelChip(panel, togglePanel, inputModifier, compact = true)
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
}
}
menu()
}) else null
// A host with a title bar shows the top bar there.
@@ -240,8 +252,11 @@ private fun AgentPageContent(
LaunchedEffect(AgentHost.approvals.size, panel) {
if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE
}
androidx.compose.foundation.layout.BoxWithConstraints(modifier.fillMaxSize()) {
// On a short page the picker would take it all and leave no conversation, so it scrolls within a share of the page.
val panelMax = maxHeight * 0.5f
Column(
modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
Modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false
if (k.action == KeyEvent.ACTION_UP) composer.open()
@@ -264,8 +279,8 @@ private fun AgentPageContent(
else -> {
if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() }
when (panel) {
AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() }
AgentPanel.MODEL -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentUsage() }
else -> Unit
}
val list = rememberLazyListState()
@@ -317,11 +332,12 @@ private fun AgentPageContent(
}
}
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest)
AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest, hideAttach = inline && menuOpen)
}
}
}
}
}
}
/** Whether the editor has the cursor; [open] puts it there. */
@@ -392,10 +408,12 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
// Closed, the outline sits flush against the lone button.
val shape = if (open) Shape16 else Shape12
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.clip(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f))
.border(1.dp, pal.line, Shape16).padding(end = 2.dp),
modifier = Modifier.clip(shape).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f))
.border(1.dp, pal.line, shape).then(if (open) Modifier.padding(top = 3.dp, bottom = 3.dp, end = 4.dp) else Modifier),
) {
androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(),
exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) {
@@ -418,7 +436,7 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
}
}
}
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu") { onOpen(!open) }
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu", startPadding = if (open) null else 0.dp) { onOpen(!open) }
}
}
@@ -432,12 +450,13 @@ private fun AgentPanelBar(title: String, onClose: () -> Unit) {
@Composable
internal fun HeaderAction(
icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, onClick: () -> Unit,
icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp,
startPadding: Dp? = null, onClick: () -> Unit,
) {
val pal = LocalPalette.current
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12)
modifier = Modifier.padding(start = startPadding ?: if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12)
.background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant)
.clickable(enabled = enabled, onClick = onClick)
.then(if (tag != null) Modifier.testTag(tag) else Modifier),
@@ -710,7 +729,7 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.
@Composable
private fun AgentComposer(
composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?,
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit,
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, hideAttach: Boolean = false,
) {
val context = LocalContext.current
var draft by draftState
@@ -742,13 +761,13 @@ private fun AgentComposer(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, visible, controls, send)
AgentEditor(composer, draftState, visible, controls, send, hideAttach)
}
}
/** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */
@Composable
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) {
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit, hideAttach: Boolean = false) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -847,14 +866,14 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
if (stacked) Column {
text(Modifier.fillMaxWidth())
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
if (attach) AttachButton()
if (AgentAttachments.gameFrame != null) GameFrameButton()
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() }
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() }
actions()
}
} else Row(verticalAlignment = Alignment.Bottom) {
if (attach) AttachButton()
if (AgentAttachments.gameFrame != null) GameFrameButton()
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
text(Modifier.weight(1f))
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
actions()
@@ -117,7 +117,7 @@ private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieS
}
@Composable
private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
internal fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
@@ -230,6 +230,7 @@ internal fun BarButton(
internal val SecondScreenMode.icon: ImageVector get() = when (this) {
SecondScreenMode.NONE -> Icons.Outlined.DesktopAccessDisabled
SecondScreenMode.MENU -> Icons.Outlined.MoreHoriz
SecondScreenMode.KEYBOARD_TRACKPAD -> Icons.Outlined.Keyboard
SecondScreenMode.TERMINAL -> Icons.Outlined.Terminal
SecondScreenMode.DECK_CONTROLS -> Icons.Outlined.SportsEsports
@@ -290,17 +291,11 @@ private fun ScreenPickerMenu(picker: ScreenPicker, open: Boolean, dismiss: () ->
leading = { Icon(painterResource(R.drawable.ic_stat_session), contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) },
focusRequester = first.takeIf { target == null }, modifier = Modifier.testTag("screen-picker-menu"),
) { dismiss(); menu() }
Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(pal.line))
Text(
stringResource(R.string.drawer_second_screen).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 4.dp),
)
}
picker.modes.forEach { mode ->
val current = mode == picker.current
MenuItem(
stringResource(mode.label), checked = current && !picker.menuShown,
detail = if (current && picker.menuShown) stringResource(R.string.screen_picker_last_used) else null,
leading = { Icon(mode.icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) },
focusRequester = first.takeIf { mode == target }, modifier = Modifier.testTag("screen-picker:${mode.id}"),
) { dismiss(); picker.onPick(mode) }
@@ -1495,22 +1495,26 @@ private fun ChoiceLine(
if (progress != null) ProgressBit(progress)
}
if (!removable) Spacer(Modifier.padding(end = 6.dp).size(44.dp))
else {
val delSrc = remember { MutableInteractionSource() }
val delHot = rememberHot(delSrc)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE)
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(delHot, ROW_SHAPE, colors.error)
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete)
.controllerConfirm(onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
}
else DeleteButton(name, onDelete = onDelete)
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
@Composable
internal fun DeleteButton(name: String, modifier: Modifier = Modifier, enabled: Boolean = true, onDelete: () -> Unit) {
val colors = MaterialTheme.colorScheme
val delSrc = remember { MutableInteractionSource() }
val delHot = rememberHot(delSrc) && enabled
Box(
contentAlignment = Alignment.Center,
modifier = modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE)
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(delHot, ROW_SHAPE, colors.error)
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, enabled = enabled, onClick = onDelete)
.controllerConfirm(enabled = enabled, onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
}
@Composable
private fun GetLine(
name: String, detail: String, progress: Int?, enabled: Boolean,
@@ -1625,7 +1629,7 @@ private fun DeviceChip(s: GpuDriversState) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.onGloballyPositioned { at = it.boundsInRoot() }.heightIn(min = 44.dp).paneItem("gpu-device").clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = open)
.controllerConfirm(onClick = open)
@@ -0,0 +1,42 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.view.InputDevice
import android.view.KeyEvent
object ControllerHaptics {
private val navKeys = setOf(
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT,
KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1,
KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2,
)
fun onKey(context: Context, event: KeyEvent) {
if (event.action != KeyEvent.ACTION_DOWN || event.keyCode !in navKeys) return
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A && event.repeatCount > 0) return
val fromController = event.isFromSource(InputDevice.SOURCE_GAMEPAD) ||
event.isFromSource(InputDevice.SOURCE_DPAD) || event.isFromSource(InputDevice.SOURCE_JOYSTICK)
if (!fromController) return
tick(context)
}
fun tick(context: Context) {
val vibrator = if (Build.VERSION.SDK_INT >= 31) {
context.getSystemService(VibratorManager::class.java)?.defaultVibrator
} else {
@Suppress("DEPRECATION") context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
} ?: return
if (!vibrator.hasVibrator()) return
if (Build.VERSION.SDK_INT >= 29) {
vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK))
} else if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(VibrationEffect.createOneShot(10, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
@Suppress("DEPRECATION") vibrator.vibrate(10)
}
}
}
@@ -0,0 +1,16 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.addPathNodes
import androidx.compose.ui.unit.dp
internal val DeckyIcon: ImageVector = ImageVector.Builder("Decky", 24.dp, 24.dp, 24f, 24f).apply {
for (d in listOf(
"M8,2h2v6H8Z",
"M14,2h2v6h-2Z",
"M5,8h14v3a7,7 0 0 1 -5,6.7V19h-4v-1.3A7,7 0 0 1 5,11Z",
"M11,19h2v3h-2Z",
)) addPath(addPathNodes(d), fill = SolidColor(Color.Black))
}.build()
@@ -0,0 +1,245 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import coil.compose.AsyncImage
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
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.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
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.runtime.DeckyManager
import com.droiddeck.launcher.runtime.DeckyStore
private enum class DeckyTab { INSTALLED, STORE, ZIP }
private const val STORE_PAGE = 30
internal fun deckyStoreMatches(plugins: List<DeckyStore.Plugin>, query: String): List<DeckyStore.Plugin> {
val words = query.trim().lowercase().split(Regex("\\s+")).filter { it.isNotEmpty() }
return plugins.filter { p ->
val haystack = (p.name + " " + p.author + " " + p.description + " " + p.tags.joinToString(" ")).lowercase()
words.all { it in haystack }
}.sortedByDescending { it.downloads }
}
@Composable
internal fun DeckyGroups(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) {
val idle = s.deckyStage == null && !s.deckySessionRunning
SettingsGroup(stringResource(R.string.mode_decky_loader)) {
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
s.deckyInstalled != s.deckyLatestRelease.tag
val status = when {
s.deckyStage != null -> s.deckyStage
s.deckyChecking -> stringResource(R.string.mode_decky_checking)
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_ready, s.deckyLatestRelease.tag)
s.deckyInstalled == null -> stringResource(R.string.mode_decky_none)
s.deckyLatestRelease == null -> stringResource(R.string.mode_decky_installed, s.deckyInstalled)
updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag)
else -> stringResource(R.string.mode_decky_current, s.deckyInstalled)
}
SettingsRow(stringResource(R.string.decky_status), status) {
val action = when {
s.deckyStage != null -> stringResource(R.string.common_working)
s.deckyChecking -> stringResource(R.string.common_checking)
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_install_latest)
s.deckyInstalled != null && updateAvailable -> stringResource(R.string.common_update)
else -> stringResource(R.string.common_check)
}
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SecondaryButton(action, enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning) {
if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck()
else s.deckyLatestRelease?.let(a.onDeckyInstall)
}
if (s.deckyInstalled != null) DeckyUninstall(enabled = idle, onUninstall = a.onDeckyUninstall)
}
}
if (s.deckyInstalled != null) ToggleRow(
host, "decky-enabled", stringResource(R.string.decky_enable),
null,
s.deckyEnabled,
enabled = idle,
onChange = a.onDeckyEnabled,
)
ChoiceRow(
host, "decky-channel", stringResource(R.string.decky_release_channel),
null,
listOf(
DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable),
DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease),
) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf(
DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing),
) else emptyList(),
s.deckyBranch,
enabled = idle,
onPick = a.onDeckyBranch,
)
if (s.deckyStage != null && s.deckyPercent >= 0) {
LinearProgressIndicator(
progress = { s.deckyPercent / 100f },
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
)
}
}
if (s.deckyInstalled == null) return
var tab by rememberSaveable { mutableStateOf(DeckyTab.INSTALLED) }
SettingsGroup(stringResource(R.string.mode_decky_plugins)) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) {
TabChip(stringResource(R.string.decky_tab_installed, s.deckyPlugins.size), tab == DeckyTab.INSTALLED, Modifier.weight(1f)) { tab = DeckyTab.INSTALLED }
TabChip(stringResource(R.string.decky_tab_store), tab == DeckyTab.STORE, Modifier.weight(1f)) { tab = DeckyTab.STORE }
TabChip(stringResource(R.string.decky_tab_zip), tab == DeckyTab.ZIP, Modifier.weight(1f)) { tab = DeckyTab.ZIP }
}
LaunchedEffect(tab) { if (tab != DeckyTab.ZIP && s.deckyStore == null && !s.deckyStoreFailed) a.onDeckyStoreRefresh() }
when (tab) {
DeckyTab.INSTALLED -> InstalledPlugins(s, a, idle)
DeckyTab.STORE -> PluginStore(s, a, idle)
DeckyTab.ZIP -> SettingsRow(
stringResource(R.string.decky_tab_zip),
stringResource(R.string.mode_decky_plugins_hint),
) {
SecondaryButton(
if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip),
enabled = idle,
modifier = Modifier.testTag("decky-install-zip"),
onClick = a.onPickDeckyPluginZip,
)
}
}
}
}
@Composable
private fun InstalledPlugins(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) {
var removing by remember { mutableStateOf<DeckyStore.Installed?>(null) }
if (s.deckyPlugins.isEmpty()) {
Text(stringResource(R.string.decky_none_installed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp))
}
for (plugin in s.deckyPlugins) {
val listed = s.deckyStore?.firstOrNull { it.name == plugin.name }
val update = listed?.takeIf { DeckyStore.updateAvailable(plugin, it) }
PluginRow(
plugin.name,
listOf(plugin.version, plugin.author).filter { it.isNotBlank() }.joinToString(" · ") +
(update?.latest?.let { " · " + stringResource(R.string.decky_update_to, it.name) } ?: ""),
listed?.imageUrl.orEmpty(),
) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
if (update != null) SecondaryButton(stringResource(R.string.common_update), enabled = idle, compact = true) { a.onDeckyStoreInstall(update) }
SecondaryButton(stringResource(R.string.decky_remove), enabled = idle, compact = true, modifier = Modifier.testTag("decky-remove-${plugin.folder}")) { removing = plugin }
}
}
}
if (s.deckyPlugins.isNotEmpty()) Text(stringResource(R.string.decky_changes_next_session), fontSize = 12.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp))
removing?.let { plugin ->
androidx.compose.material3.AlertDialog(
onDismissRequest = { removing = null },
title = { Text(stringResource(R.string.decky_remove_confirm, plugin.name)) },
text = { Text(stringResource(R.string.decky_remove_confirm_body)) },
confirmButton = { androidx.compose.material3.TextButton(onClick = { removing = null; a.onDeckyRemove(plugin) }) { Text(stringResource(R.string.decky_remove)) } },
dismissButton = { androidx.compose.material3.TextButton(onClick = { removing = null }) { Text(stringResource(R.string.common_cancel)) } },
)
}
}
@Composable
private fun PluginStore(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) {
var query by rememberSaveable { mutableStateOf("") }
var searching by remember { mutableStateOf(false) }
var shown by rememberSaveable { mutableIntStateOf(STORE_PAGE) }
val plugins = s.deckyStore
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp).padding(bottom = 12.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
Box(Modifier.weight(1f)) {
ListRow(tall = true, onClick = { searching = true }) {
androidx.compose.material3.Icon(Icons.Filled.Search, contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp))
Text(
query.ifEmpty { stringResource(R.string.decky_store_search) }, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (query.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onBackground,
modifier = Modifier.weight(1f),
)
}
}
if (query.isNotEmpty()) SecondaryButton(stringResource(R.string.boot_movie_repo_clear), compact = true) { query = ""; shown = STORE_PAGE }
}
when {
plugins == null -> Text(stringResource(R.string.common_working), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
s.deckyStoreFailed -> Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(stringResource(R.string.decky_store_failed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f))
SecondaryButton(stringResource(R.string.boot_movie_repo_retry), compact = true) { a.onDeckyStoreRefresh() }
}
else -> {
val matches = remember(plugins, query) { deckyStoreMatches(plugins, query) }
if (matches.isEmpty()) Text(stringResource(R.string.decky_store_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
for (plugin in matches.take(shown)) {
val have = s.deckyPlugins.firstOrNull { it.name == plugin.name }
val current = have != null && !DeckyStore.updateAvailable(have, plugin)
PluginRow(
plugin.name,
listOf(plugin.latest?.name.orEmpty(), plugin.author, plugin.description).filter { it.isNotBlank() }.joinToString(" · "),
plugin.imageUrl,
) {
SecondaryButton(
stringResource(when { current -> R.string.setup_installed; have != null -> R.string.common_update; else -> R.string.boot_movie_repo_install }),
enabled = idle && !current, compact = true,
modifier = Modifier.testTag("decky-store-${plugin.name}"),
) { a.onDeckyStoreInstall(plugin) }
}
}
if (matches.size > shown) SecondaryButton(stringResource(R.string.decky_store_more, matches.size - shown), compact = true) { shown += STORE_PAGE }
}
}
}
if (searching) TextEntryDialog(
stringResource(R.string.decky_store_search), query, number = false, confirm = stringResource(R.string.stores_search_open),
onSubmit = { query = it; shown = STORE_PAGE; searching = false }, onDismiss = { searching = false }, id = "decky-store-entry",
)
}
@Composable
private fun PluginRow(name: String, detail: String, imageUrl: String, actions: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
val shape = RoundedCornerShape(8.dp)
Box(Modifier.width(96.dp).aspectRatio(16f / 9f).clip(shape).background(Color(0xFF0E1218))) {
if (imageUrl.isNotEmpty()) AsyncImage(model = imageUrl, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
}
Column(Modifier.weight(1f)) {
Text(name, fontSize = 15.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) { actions() }
}
}
Loaded 100 of 403 files, more files were not shown because too many files have changed in this diff. Show more