Compare commits

...
Author SHA1 Message Date
The412Banner fb1d6955f0 test: pin the published gamescope p18 (same archive as the QA build) 2026-10-28 04:42:12 +00:00
The412Banner 4745517101 fix(steam): skip only Steam's own driver-query run in compatdata/0
Review of #1708: matching the file name alone also caught
getcompatpath for that path and a game that happens to use the name.
The wrappers now skip only "run …/d3ddriverquery64.exe" (or the 32-bit
name) with STEAM_COMPAT_DATA_PATH in compatdata/0, which is how the
client calls it; every other verb and prefix goes on to Proton.

(cherry picked from commit c5e8ad0f8069800a8dae7c2bbec5037ccc18740b)
2026-10-28 04:42:12 +00:00
The412Banner 58c262a32e Merge perf/render-on-commit (callback-paced clients, idle recheck) into test/perf-round2 2026-10-28 04:42:11 +00:00
The412Banner bfe5941ce9 fix(compositor): keep callback-paced clients at one frame per refresh
Review of #1707: a client that draws its next frame only after the
frame callback of the last one sends no new frame while the tick holds
one back, so it got one frame every two refreshes. Once a held frame is
still waiting at the next tick, the tick now draws every frame for a
second before holding one again; such a client loses at most one
refresh per second, while gamescope, which commits without waiting,
keeps drawing on arrival.

The queued draw also checks again that drawing on arrival is still on,
so a frame queued just before streaming, frame generation or paced
output switched on is left for the tick.
2026-10-28 04:40:24 +00:00
The412Banner 93bed6e931 fix(steam): answer Steam's D3D driver query without starting Wine
At every start, Steam's shader pre-caching runs d3ddriverquery64.exe
through each Proton tool (DroidDeck-Proton and the ARM64 Proton) in
compatdata/0. Here the query has never succeeded (948 of 948 runs in
the client's shader log failed, mostly exit code 1), and each run
started Wine in that prefix, where the two Protons upgraded it back and
forth (11.0-100 <-> GE-Proton11-11) with the 32-bit wine.inf install.
When that overlapped a game's start, AIO ran 25-30 % slower for its
first 5-7 seconds.

Both Proton wrappers now exit 1 for the query before doing anything
else, so Steam gets the same failure without Wine. Other launches are
unchanged.

(cherry picked from commit 0d8dbe4360ae7b81256e9c7b3236c8a8dd0225dc)
2026-10-28 02:48:47 +00:00
The412Banner c6a31be049 Merge perf/render-on-commit (tick leaves young frames for the next arrival) into test/perf-round2 2026-10-28 02:21:34 +00:00
The412Banner 1c245df6b6 fix(compositor): keep drawing frames on arrival at one frame per refresh
On the device, render-on-commit drew only 4-12 % of frames on arrival
while a game ran uncapped: gamescope delivers about one frame per
refresh, so once the tick drew a frame, the next one arrived in the same
refresh, was held back by the once-per-refresh limit and was drawn by
the next tick, which held back the one after it. Waits stayed at ~2 ms.

The tick now leaves a frame younger than one refresh for the next
arrival to draw, unless the tick itself changed the window, effects or
headset pose. A frame no other frame follows is drawn at the tick after.
2026-10-28 02:21:27 +00:00
The412Banner 6c6c68413f test: pin the gamescope QA build with 0123 and 0124 2026-10-28 01:02:53 +00:00
The412Banner d00e0b2763 test: render-on-commit + gamescope 0124 together 2026-10-28 01:02:52 +00:00
The412Banner f7cebee7ee perf(gamescope): handle a finished frame at import (0124) with upstream fence fixes (0123)
0123 backports upstream 0efe47c and 666c52b by Matthew Schwartz (commit
completion list lifetime, no Rc to a dying commit). 0124 polls a new
commit's fence at import; a finished frame is marked done at once and
handled in the same steamcompmgr pass instead of a second wake through
the image waiter. commit_ready_check (default on) turns it off.
2026-10-28 00:50:21 +00:00
The412Banner 8e7044af4c perf(compositor): draw a new frame when it arrives
A new game frame waited for the next screen tick before the compositor
drew it: 1.9-3.5 ms on average at 144 Hz, measured with the pacing
counters. With frames going straight back to the game (no compositor
limit), the compositor now draws as soon as the clients' requests are
handled, at most once per refresh: a second frame in the same refresh
still waits for the tick, and presentation times stay on the tick.

Paced output (glasses), streaming and frame generation keep drawing on
the tick. The hidden pref renderOnCommit (default on) turns it off. The
pacing log line counts the scenes drawn on arrival.
2026-10-28 00:46:16 +00:00
The412Banner 4ef6b53eb0 fix(proton): Windows CPU 0 is the fastest core (#1697)
Wine numbers the Windows CPUs like the host, so Windows CPU 0 was host
core 0, a small core on most Android chips. Games that pin their main
thread to CPU 0 ran it there: GTA IV 32 fps on the AYANEO Pocket FIT,
61 fps once CPU 0 is the fastest core.

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

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

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

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

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

* i18n(launcher): translate apps page strings

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Pins gamescope-3.16.29-p17, the archive that was A/B-tested on the
device. PATCHES.md also describes the p16 change to 0120.
2026-10-27 09:10:53 -04:00
Kurt Himebauch 0f839bef5d fix(ui): bloom into the compatibility tools loading screen (#1666) 2026-10-27 07:23:47 -04:00
The412Banner 43a0ce93f9 fix: Frame Limit sync and refresh follow on a still screen (review follow-ups) (#1663)
The Steam helper checked the Frame Limit only when the offered frame
rates changed. With the limit off during a refresh change, turning it
back on left a value the new rate does not offer, and a failed write was
not tried again. It now checks on every state change and every 5 s, and
waits for Steam's settings write so a rejected write is caught and tried
again on the next check.

gamescope 3.16.29-p16 (0120 changed): gamescope took a new host refresh
only from the presentation feedback of a frame it drew, so with nothing
moving on screen it kept the old rate. It now presents once when the
host's wl_output mode changes and keeps presenting while a new rate is
pending, so the 300 ms check runs on a still screen too.

Found by CodeRabbit in the reviews of #1650 and #1663.
2026-10-27 05:08:21 -04:00
Kurt Himebauch 07a0a7e344 fix: show gesture settings only in gesture mode (#1654) 2026-10-27 00:23:44 -04:00
maxjivi05 c25d54aced fix: leave published component choices alone when state.json cannot be read 2026-10-27 00:07:45 -04:00
maxjivi05 c781cfd525 fix: publish component choices again when a new Proton build appears
Game and global component choices were written to desired.tsv only when a
selection changed, so a Proton build installed later (DroidDeck-Proton
11-11.8) had no rows and kept its bundled FEX. Battle.net's d2rfix FEX never
reached it and StarCraft died in ClientSdk.dll's DllMain. The choices are now
republished at session start and on Battle.net's FEX request whenever the
installed tools no longer match what was published.
2026-10-27 00:07:45 -04:00
The412Banner 4c7e59ed8b feat: Steam's Frame Limit decides; gamescope and the limit follow the refresh rate (#1650)
Remove the Performance mode switch. The session always runs the way
Performance mode did: replaced buffers go back to the game at once
(except while mirroring to glasses), gamescope's WSI layer and winex11
reuse their per-present window checks, and games get eight swapchain
images while uncapped. Steam's Frame Limit in the Quick Access menu is
the only limit.

gamescope 3.16.29-p15 (p14 plus two patches):
- 0119: with the Frame Limit on, gamescope forces FIFO while the WSI
  layer hands the driver MAILBOX, so a game with eight images could
  queue up to seven frames ahead of the screen. While the limiter forces
  FIFO the layer uses its default of 3 images; DXVK and VKD3D-Proton
  recreate their swapchain when the limiter changes, other apps are asked
  to with VK_SUBOPTIMAL_KHR.
- 0120: -r fixed gamescope's pacing and limiter rate for the whole
  session. With GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST=1 a rate the host
  has reported for 300 ms replaces it (a switch from 144 to 120 Hz passes
  through 72 Hz for a few frames), and Steam gets the display information
  again. The session sets it whenever it passes -r.

Steam keeps its Frame Limit as the client setting
gamescope_app_target_framerate and offers the values gamescope's display
state lists. After a refresh change, a limit the new rate does not offer
(72 at 120 Hz) left the slider on its first value while the game kept the
old limit. The Steam helper watches the offered values and, once they
settle, keeps the limit when it is still offered and moves it to the
highest value otherwise, through Steam's own setting so the slider shows
it. Steam's webpack does not expose its module cache, so the gamescope
service is found by the calls its module makes, and the helper retries
the install every 10 s until Steam is ready.

The session window asks for the fastest mode the peak refresh setting
allows and chose again only when the display changed, so after it had
asked for 60 Hz, raising Android's refresh setting left the display,
gamescope and the limit at 60. It now also chooses again when
peak_refresh_rate or min_refresh_rate changes.
2026-10-26 23:17:35 -04:00
Kurt Himebauch 0e9a31ccfe feat: trust contributors for test builds (#1646)
* feat: trust contributors for test builds

* fix: restrict trusted list changes

* fix: retain same-repository test signing

* fix: publish completed fork builds

* feat: trust K11MCH1 test builds

* fix: recognize maintain collaborator role
2026-10-26 22:54:57 -04:00
Kurt Himebauch 8749154cbf fix(input): keep AYN system key out of Home shortcuts (#1643) 2026-10-26 21:11:46 -04:00
maxjivi05 bb9a64fa5f Reconfigure the app decoder when the capture layout changes
A capture format or buffer change now closes the app's decoder so the
next packet reopens it with the new stride and height, and a capture
slot whose remap fails no longer keeps its old mapping.
2026-10-26 20:36:24 -04:00
maxjivi05 916a39585f Decode Remote Play streams on the arm64 Steam client
Steam's arm64 streaming_client only decodes through a V4L2 stateful
decoder and libdrm dumb buffers, neither of which exist on Android, so
streams from a PC never showed a picture. The preload now offers it a
/dev/video-dec0 and a libdrm stand-in backed by dma-heap buffers, and
each frame is decoded by the app's MediaCodec (Qualcomm low-latency
mode) over the encoder socket, falling back to the FFmpeg in Steam's
runtime.
2026-10-26 20:36:24 -04:00
maxjivi05 9555cb9f65 fix(skate.): run ReSkate at D3D12 feature level 12_1
skate. under ReSkate crashed with an access violation in Skate.exe 12 to
60 seconds after it started at the default feature level 12_2; at 12_1
it loads San Vansterdam and plays. The rule matches Skate.exe with
ReSkate.dll beside it, so it covers ReSkate started from skate.'s own
Steam entry and as a non-Steam game, and a game profile can still set
another level.
2026-10-26 20:35:59 -04:00
maxjivi05 70d8fc6559 Hand a profile's WINE_CPU_TOPOLOGY to Proton as well 2026-10-26 18:31:11 -04:00
maxjivi05 70c512693a Set PROTON_CPU_TOPOLOGY too so Proton's per-game CPU list doesn't replace it
Proton sets WINE_CPU_TOPOLOGY from its own default_cpu_limit for games
like Prototype (8 cores) unless PROTON_CPU_TOPOLOGY is set, so the
pinned topology never reached the game the issue was about.
2026-10-26 18:31:11 -04:00
maxjivi05 43266b2923 Keep an empty WINE_CPU_TOPOLOGY from a game profile 2026-10-26 18:31:11 -04:00
maxjivi05 9d85af7558 fix(proton): Windows games see only the cores they are pinned to
Game cores pinned the game with taskset, but Wine counts the online
CPUs, so a game held to two cores still saw eight processors and sized
its thread pools for them. Prototype freezes at its splash screen that
way. When the session or a game profile limits the game cores, Wine now
gets WINE_CPU_TOPOLOGY for exactly those cores unless the profile sets
its own.
2026-10-26 18:31:11 -04:00
FX1922andmaxjivi05 d905f03bf7 feat(itch): collections filter in the Library (#1597)
* Add itch.io collections to the Library

A Collections button on the Library's itch tab filters the library to one collection of the signed-in account. Its games that are not installed show in the Not installed section.

* Keep itch collections complete across failures, sign-out and empty libraries

A failed later page no longer publishes a partial collection, selecting a collection refreshes it, pagination runs until an empty page, signing out clears collection state, and the itch chip shows for a signed-in account with no owned games.

* Tie itch collection requests to the account that started them

Requests capture the account generation before reading the key and dedupe per generation, sign-out clears collections after the token is removed, and the collections load follows the itch sign-in state.

* Keep paging itch collections past a page of already seen games

* Run the itch collections tests under Robolectric like the other itch tests

* Let the Installed filter apply inside a collection and keep the grid for an empty itch account

* fix(itch): stop paging a collection when a page adds no new games

* Keep the collections icon on the itch collections tab when it opens

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-10-26 18:15:24 -04:00
Kurt Himebauch f13916ee25 feat(steam): optional Steam integration setup (#1637)
* feat(steam): add optional device integration setup

* feat(steam): show integration setup as inline settings rows

* fix(steam): offer App info when shortcuts stay blocked
2026-10-26 17:51:44 -04:00
Kurt Himebauch 73daaf7adc fix(gamescope): keep Fill scaling and magnification visible (#1634)
* fix(gamescope): preserve signed plane positions

* fix(gamescope): pin validated scaling component
2026-10-26 16:06:40 -04:00
maxjivi05 aa17b0553d fix(input): end the forwarded touchpad finger when the Steam menu opens 2026-10-26 15:52:02 -04:00
maxjivi05 46076e165b fix(input): let on-screen controls work while the touchpad finger is down
The game surface only took touches in gestures mode, so in touchpad and
direct mode a finger on the game left the window with no touch target and
Android sent every later finger to the touchpad, even over a stick or
button. The surface now owns those fingers in every mode, and the
on-screen and Steam touch controls hand fingers that miss a control back
to the touchpad instead of dropping them.
2026-10-26 15:52:02 -04:00
Kurt Himebauch 2d8957a401 feat(launch): show compatibility install progress (#1629) 2026-10-26 15:41:46 -04:00
Kurt Himebauch b3561bf658 fix(input): discard queued chords on disconnect (#1632) 2026-10-26 15:31:51 -04:00
Kurt Himebauch 13eb291ba8 fix(input): handle immediate Back chords and tap timing (#1628)
* feat(input): support instant Back chords and tap timing

* fix(input): send QAM before shortcut inputs

* fix(input): stop delayed stick input on Back release
2026-10-26 15:04:55 -04:00
Kurt Himebauch c8f650e167 feat(ui): add game resource links (#1630) 2026-10-26 14:53:21 -04:00
The412Banner 830c753312 fix: turn off D3DGear's capture hook when it sits beside a game (#1627)
The Crew 2 loads D3DGear64.dll from its folder. Its DXGI Present hook
faults over a thousand times within seconds under Wine and the game
never presents again: black screen while the sound keeps playing.
droiddeck-game-env now disables the DLL when it finds it beside the
game, and DLL overrides from several engine fixes are kept together
instead of the last one replacing the others.
2026-10-26 18:07:15 +00:00
Kurt Himebauch a0a68f7280 feat(steam): sync QAM controls and pass held Back shortcuts (#1621)
Steam's native QAM sliders now control Android brightness and media
volume, with device changes reflected back in Steam. Holding Android
Back for 700 ms sends a real held QAM button for Steam shortcuts. Single
and double taps keep the existing menu/QAM order and swap setting; the
double-tap window remains 500 ms.

- Discover native brightness through a guest backlight descriptor and
use Android's Modify system settings permission. Retain the latest
pending request until permission is granted or the session stops, with a
notification action for hidden sessions.
- Give DirectAudio and fallback AAudio sinks Android media volume/mute
callbacks, keeping software gain at unity. Recover when initial volume
state is absent or invalid, brightness acknowledgements differ or never
arrive, or the Display bridge is not ready yet.
- Forward other buttons while QAM is held in Steam Deck and Steam
Controller modes. Consume release after a hold and clear pending input
on overlays, focus loss, pause, disconnect, and teardown. The session
menu retains its compact Back choice without an explanatory paragraph.

Validation:
- Local ARM64 release build passed. The latest timing change passed 20
targeted input tests, including release at 600 ms remaining a tap. The
preceding full feature check passed 61 Android input/device-control
tests, with permission cases on API 28 and 33.
- 66 Linux Python/Node/C tests passed for device controls, audio
recovery, Steam compatibility, and file dialogs. Both audio sink modules
rebuilt with Android NDK 27.2.
- Release-signed integration build 14d12cf0 is installed on the unrooted
AYN Thor, carrying the Android/input changes through 749ade4a plus the
existing portrait changes. Device checks confirmed the configured
QAM/menu tap order, Back dismissal, removal of the inline menu
description, and held QAM overlapping X with clean release. Hands-on
testing confirmed this installed build works.
- Earlier Thor testing covered brightness permission and pending
requests, brightness synchronization in both directions, native volume
changes, hardware volume key readback, and both sink backends. Failure
recovery is covered by the automated tests above.

The subsequent queued-notification fix in 4d7ceb23 is covered by the
Linux regression suite and has not replaced the Thor install.

Bluetooth/wired output switching and other device models remain
untested. CI and CodeRabbit monitoring continue against the pushed head.
2026-10-26 13:46:14 -04:00
maxjivi05 455bf0fba9 fix(fex): install DroidDeck's FEX build again when it no longer loads
A tag that matches no longer vouches for the build: FEX and FEXServer must
also load (ld.so --list), otherwise the session reinstalls it and x86
programs use the Steam or system FEX meanwhile.
2026-10-26 13:40:36 -04:00
maxjivi05 8df90c30dd fix(fex): read the fallback FEX version from droiddeck-fex-update
The pin moved there from droiddeck-steam-x64, so the client settings sheet
and its test read it from the new script. The x86-64 client notes now name
the updater and Components' FEX watcher.
2026-10-26 13:40:36 -04:00
maxjivi05 4de4c65c2a fix: wait before retrying a FEX build that did not install
A failed catalog install is retried after an hour or when the session names
another build, a missing updater falls back to the FEX already here, and the
archive download gives up on a stalled connection.
2026-10-26 13:40:36 -04:00
maxjivi05 bb1cbf95c0 docs: credit sharun and userland-execve 2026-10-26 13:40:36 -04:00
maxjivi05 7e2d13b641 fix(fex): x86 programs use DroidDeck's own FEX build, kept to the catalog's version 2026-10-26 13:40:36 -04:00
maxjivi05 5bdf0d6b04 fix(fex): report the x86 platform under AT_PLATFORM 2026-10-26 13:40:36 -04:00
maxjivi05 13493d44c3 fix: keep Sentry for Godot games that are not .NET
The Sentry GDExtension was turned off for every Godot game that ships it,
because its crash handler takes the .NET runtime down under FEX. GDScript
games such as Pathogenic call SentrySDK from their scripts, so without the
extension their autoloads fail to parse and the game quits. Only Godot .NET
builds have it turned off now.
2026-10-26 13:27:59 -04:00
Kurt Himebauch 4d7ceb2325 fix(steam): drain queued control notifications 2026-10-26 13:27:03 -04:00
maxjivi05 a984d11742 fix: run Xbox games from a short drive letter
The launch view lives under the app's files folder, so games saw an
install path like Z:\data\user\0\com.droiddeck.launcher\files\xbox-runtime
\views\launch-<n>\droiddeck-xbox-<id>. Forza Horizon checks that length and
quits with "Installation path is too long". The view is now mapped to a
free drive letter in the prefix (X: first) for the length of the launch.
2026-10-26 13:21:31 -04:00
Kurt Himebauch 749ade4a45 fix(input): delay held QAM to 700 ms 2026-10-26 13:20:51 -04:00
Kurt Himebauch fa5506df35 fix(steam): preserve Back taps and recover QAM controls 2026-10-26 13:13:08 -04:00
Kurt Himebauch dde1a55d00 feat(input): pass held Back through as Steam QAM 2026-10-26 12:49:51 -04:00
maxjivi05 c446566f42 fix: hold a setup lock instead of guessing from running processes 2026-10-26 12:47:00 -04:00
maxjivi05 2e2b950964 fix: Flatpak setup clears a package lock left by an interrupted run 2026-10-26 12:47:00 -04:00
Kurt Himebauch 53d643dd00 fix(audio): clear volume bridge during sink teardown 2026-10-26 12:34:31 -04:00
Kurt Himebauch 6a5dfe1486 feat(steam): sync QAM brightness and volume with Android 2026-10-26 12:32:36 -04:00
Kurt Himebauch da127d1b4c fix: delay client compression until game focus (#1406) 2026-10-26 12:12:04 -04:00
maxjivi05 9b68b33e73 fix: pick the HUD surface by the scene's draw order 2026-10-26 12:02:17 -04:00
maxjivi05 1f60e57749 fix: time the HUD graph from the game's frames as shown on screen 2026-10-26 12:02:17 -04:00
Kurt Himebauch eaaecf0661 feat(session): add portrait sessions and controls below the game (#1612) 2026-10-26 12:01:44 -04:00
Kurt Himebauch d08afbd878 fix: restart compression delay for new games 2026-10-26 11:55:01 -04:00
Kurt Himebauch 36135327f5 fix: resolve zram focus conflicts 2026-10-26 11:45:17 -04:00
0x1Nawaf d65912f0c5 fix: stop starting a session on the slow proot (#1395) 2026-10-26 11:41:18 -04:00
Kurt Himebauch 5d945d7784 refactor: remove duplicate session frame limiter (#1616) 2026-10-26 11:25:31 -04:00
maxjivi05 ee1b3b26e1 fix: clip damage against the buffer committed with it 2026-10-26 10:50:19 -04:00
maxjivi05 9c02233b06 fix: clip damage to the surface and let the toplevel's size count for coverage 2026-10-26 10:50:19 -04:00
maxjivi05 f98c272300 fix: compare the window's shown size with the scene 2026-10-26 10:50:19 -04:00
maxjivi05 744a42d324 fix: count one shm window, only after new GPU frames stop, with damage in buffer pixels 2026-10-26 10:50:19 -04:00
maxjivi05 30da4d2bcd fix: count a desktop window game's frames for the performance HUD 2026-10-26 10:50:19 -04:00
maxjivi05 e492a78f55 fix: treat a product.db with a damaged install record as unreadable 2026-10-26 10:30:16 -04:00
maxjivi05 538b5c5270 fix: hide registry-only games when product.db lists none, keep the Agent off without the game storage card 2026-10-26 10:30:16 -04:00
maxjivi05 be5bec2d44 fix: keep every game library mounted for Battle.net's Agent and drop games it no longer tracks 2026-10-26 10:30:16 -04:00
maxjivi05 fd9de4a21e fix: list Battle.net's games in a grid that scrolls down 2026-10-26 10:10:31 -04:00
The412Banner 1b3814a587 Hold games to the frame limit in Performance mode (#1609)
A frame limit only paced what reached the screen: a game without vsync
kept drawing hundreds of frames a second that were thrown away (AIO at
a 60 fps limit drew 155 to 2,446 fps), so the limit saved no power.

With Performance mode on and a frame limit set, the session now sets
gamescope's per-game limit over gamescope_control (gamescopectl
debug_set_fps_limit). gamescope's limiter then has its WSI layer hold
Vulkan games, DXVK and VKD3D included, to the limit. gamescope's own
--framerate-limit option is reset on its first frame in 3.16.29, and
Steam resets the per-game limit while it starts, so the session watches
gamescope's limiter state file and sets the limit again whenever it is
off (a once-a-second check with shell builtins, no process started).
With Performance mode off, a limit paces the screen only, as before.

The session also gives gamescope a fixed limiter state file path, so
gamescope stops leaving a new one behind on every start, and removes
the old ones.

Device-proven on the AYANEO Pocket FIT (Turnip, AIO D3D11, 45 s runs on
battery, three runs each): at a 60 fps limit the game held exactly
60.0 fps and the device drew 7.08 W instead of 9.45 W, with 1.3 instead
of 2.6 busy cores and 5 instead of 11 % GPU load. No limit: unchanged.
2026-10-26 09:16:05 -04:00
Kurt Himebauch 78f95c5a0c feat(ui): support portrait launcher layouts (#1606) 2026-10-26 09:14:35 -04:00
maxjivi05 db56cff880 fix: check a Battle.net game for updates again when the last check failed 2026-10-26 09:01:02 -04:00
maxjivi05 24f0b97c08 fix: report a gamescope that cannot start and ignore Agent answers that are not objects 2026-10-26 09:01:02 -04:00
maxjivi05 3b6b304f55 fix: take the Agent's empty answer for an uninstalled game as gone
Once Blizzard's Agent has removed a game it answers GET /game/<uid> with
an empty object, not installed false, so a finished uninstall read as a
failure and opened Battle.net.
2026-10-26 09:01:02 -04:00
maxjivi05 c48297e0d1 fix: wait for a cancelled Battle.net job before removing it, and bound uninstall waits
A cancelled install now waits for its Agent job to end before the
uninstall runs, and removes the folder only once the Agent no longer
lists the game or the folder is empty. Uninstall gives up when Battle.net
or a game keeps the prefix busy for a minute, so the page falls back to
opening Battle.net. An uninstall only counts when the Agent reports the
game as not installed.
2026-10-26 09:01:02 -04:00
maxjivi05 b887e8653d feat: install Battle.net games from Stores with downloads, updates and uninstall
Battle.net games now install like Epic, Xbox and itch games: Install,
pick a location, and the download runs in the Downloads tab while the
Stores page stays open. droiddeck-battlenet starts Blizzard's own Agent
on its own under a headless gamescope and drives its local API, so no
window opens and nothing waits on the Battle.net client.

- Progress, speed and time left come from the Agent, with pause, resume
  (the Agent keeps what it downloaded) and cancel, which uninstalls the
  partial game and removes its folder.
- A job only finishes once the Agent has really run it and the game is
  playable; the first status after a request can still describe the
  previous operation.
- Installed games check Blizzard's version service and show Update when
  the build on disk is behind; the update repairs missing files too.
- Battle.net games can be uninstalled from their page through the Agent.
- Games land in the chosen location: internal storage, other storage or
  a Games folder.
- The hero keeps its action row clear of the playtime column.
2026-10-26 09:01:02 -04:00
Kurt Himebauch 9fc48515c1 feat(input): unify low latency mode (#1604) 2026-10-26 08:12:47 -04:00
Kurt Himebauch 63d1e4d61d feat(library): remember visibility and store order (#1591) 2026-10-26 07:44:07 -04:00
Kurt Himebauch fbb334263c fix(ui): restore continuous ambient motion (#1592) 2026-10-26 02:05:19 -04:00
Kurt Himebauch 3fd6b1f00d fix(ui): restore consistent focus glide transitions (#1588) 2026-10-25 23:20:57 -04:00
Kurt Himebauch 5978a13f09 fix(stores): restore store capabilities in Library (#1586) 2026-10-25 22:07:42 -04:00
MaxsTechReview c71ba6da96 Run desktop games on the GPU in a window (#1584)
Steam games and Battle.net started from the KDE desktop run on the GPU in gamescope, opened as a KDE window, and Plasma no longer leaves programs with a zero realtime CPU limit that got games killed.
2026-10-25 21:09:24 -04:00
DrummingBird1 cce742766d fix: zero-copy launch log no longer points at a drawer switch that do… (#1354)
fix: describe the actual HDR zero-copy launch policy
2026-10-25 19:25:31 -04:00
Thomas Lee 4922d309c8 perf: allocate only solved DD-FG flow levels (#1556)
The flow solver starts at flowFinest_, but its images, uniform buffers and descriptor sets were allocated for every pyramid level. Keep the seven-level indices and allocate flow resources only where the solver reads and writes them.

The default preset avoids three unused RGBA16F images, saving 38,707,200 bytes of pixel payload at 2560x1440 without changing the shaders or recorded GPU work. Add native allocation/dispatch regressions and document the resource budgets.
2026-10-25 19:21:40 -04:00
0x1Nawaf aa1a8da39a merge: with main branch 2026-10-25 10:38:42 +00:00
0x1Nawaf 73e158ab3b fix: compress only while the running game is focused 2026-10-25 10:38:37 +00:00
0x1Nawaf 0a8358d11f fix: keep the gamescope cursor out of the zram change
The session script had also picked up the cursor switch from the other branch.
2026-10-23 15:52:35 +00:00
0x1Nawaf 1f1873a18e fix: compress the client only after the game window is focused 2026-10-23 15:46:00 +00:00
265 changed files with 16070 additions and 1298 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
# GitHub PR openers trusted for automatic release-signed test builds.
FX192
K11MCH1
kingokksa
ovurrsl
+10 -1
View File
@@ -494,6 +494,16 @@ jobs:
- name: Build the add-on packs
run: bash tools/packs/build.sh app/build/packs
- name: Note when the proot pack pin is behind this build
run: |
set -euo pipefail
# shellcheck disable=SC1091
source tools/packs/proot/release.env
sha=$(sha256sum app/build/packs/proot.tar.zst | cut -d' ' -f1)
if [ "$sha" != "$PROOT_PACK_SHA256" ]; then
echo "::warning::built proot pack $sha does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256). This build publishes the pack it just built. Source builds keep downloading the pinned pack until release.env is updated."
fi
- name: Build
id: build
env:
@@ -610,7 +620,6 @@ jobs:
UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }}
TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }}
APK_OUTCOME: ${{ steps.apk-upload.outcome }}
SAME_REPO: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
run: bash tools/release/report-build.sh
python-tests:
+103 -31
View File
@@ -8,6 +8,10 @@ on:
description: Open pull request number
required: true
type: string
automatic_build_run_id:
description: Completed build run for automatic publishing
required: false
type: string
pull_request_target:
types: [labeled]
branches: [main]
@@ -27,16 +31,47 @@ concurrency:
queue: max
jobs:
dispatch-fork-builds:
if: >-
github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.head_repository.full_name != github.repository
runs-on: ubuntu-24.04
timeout-minutes: 5
permissions:
actions: write
pull-requests: read
steps:
- name: Find fork PRs for the completed build
env:
GH_TOKEN: ${{ github.token }}
RUN_ID: ${{ github.event.workflow_run.id }}
RUN_SHA: ${{ github.event.workflow_run.head_sha }}
RUN_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
RUN_BRANCH: ${{ github.event.workflow_run.head_branch }}
run: |
set -euo pipefail
owner=${RUN_REPO%%/*}
gh api --paginate --slurp -X GET "repos/$GITHUB_REPOSITORY/pulls" \
-f state=open -f base=main -f "head=$owner:$RUN_BRANCH" -f per_page=100 |
jq -r --arg sha "$RUN_SHA" --arg repo "$RUN_REPO" --arg branch "$RUN_BRANCH" '
.[][] | select(.head.sha == $sha and .head.repo.full_name == $repo and .head.ref == $branch) | .number' |
while IFS= read -r number; do
gh workflow run pr-release-publish.yml -R "$GITHUB_REPOSITORY" --ref main \
-f "pr_number=$number" -f "automatic_build_run_id=$RUN_ID"
done
authorize:
if: >-
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') ||
(github.event_name == 'pull_request_target' && github.event.label.name == 'publish-test') ||
(github.event_name == 'pull_request_target' &&
(github.event.action != 'labeled' || github.event.label.name == 'publish-test')) ||
(github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.head_repository.full_name == github.repository &&
github.event.workflow_run.pull_requests[0] != null)
runs-on: ubuntu-24.04
timeout-minutes: 45
timeout-minutes: 150
outputs:
pr_number: ${{ steps.gate.outputs.pr_number }}
run_id: ${{ steps.gate.outputs.run_id }}
@@ -50,6 +85,7 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: The packages a signed build ships as
id: variants
@@ -61,22 +97,14 @@ jobs:
EVENT_NAME: ${{ github.event_name }}
REQUESTER: ${{ github.actor }}
PR_NUMBER: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }}
ACTION: ${{ github.event.action }}
BUILT_SHA: ${{ github.event.workflow_run.head_sha }}
AUTO_RUN: ${{ inputs.automatic_build_run_id }}
run: |
set -euo pipefail
[[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "::error::Invalid PR number '$PR_NUMBER'"; exit 1; }
skip() { echo "::notice::Not publishing PR #$PR_NUMBER: $1"; echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0; }
if [ "$EVENT_NAME" = workflow_run ]; then
echo "automatic=true" >> "$GITHUB_OUTPUT"
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
[ "$(jq -r .state <<<"$pr")" = open ] || skip "it is not open"
[ "$(jq -r .draft <<<"$pr")" = false ] || skip "it is a draft"
[ "$(jq -r .base.ref <<<"$pr")" = main ] || skip "it does not target main"
[ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork"
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
[ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building"
fi
if [ "$EVENT_NAME" = pull_request_target ]; then
if [ "$EVENT_NAME" = pull_request_target ] && [ "$ACTION" = labeled ]; then
permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$REQUESTER/permission" --jq .permission)
case "$permission" in
admin|maintain|write) ;;
@@ -85,29 +113,59 @@ jobs:
fi
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null ||
{ echo "::error::PR #$PR_NUMBER must be open, ready for review, and target main"; exit 1; }
skip "it must be open, ready for review, and target main"
if [ "$EVENT_NAME" = workflow_run ]; then
[ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork"
[ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building"
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
echo "automatic=true" >> "$GITHUB_OUTPUT"
elif [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; then
[[ "$AUTO_RUN" =~ ^[1-9][0-9]*$ ]] || { echo '::error::Invalid automatic build run ID'; exit 1; }
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
git fetch --no-tags origin main
opener=$(jq -r .user.login <<<"$pr")
git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener" || skip "PR opener @$opener is not trusted for automatic signing"
echo "automatic=true" >> "$GITHUB_OUTPUT"
fi
head=$(jq -r '.head.sha' <<<"$pr")
base=$(jq -r '.base.sha' <<<"$pr")
run_id=
for attempt in $(seq 1 60); do
latest=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml \
--event pull_request --commit "$head" \
--json databaseId,headSha,status,conclusion,createdAt,attempt -L 100 |
jq -c --arg head "$head" '[.[] | select(.headSha == $head)] |
sort_by([.createdAt, .attempt]) | last // empty')
for attempt in $(seq 1 240); do
latest=$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/build.yml/runs?event=pull_request&head_sha=$head&per_page=100" |
jq -c --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
[.workflow_runs[] | select(.head_sha == $head and .head_repository.full_name == $repo and .head_branch == $ref)] |
sort_by([.created_at, .run_attempt]) | last // empty')
if [[ -z "$latest" && "$attempt" == 1 ]]; then
git fetch --no-tags origin main
git fetch --no-tags origin "refs/pull/$PR_NUMBER/head"
git diff --no-renames --name-only -z "$base...FETCH_HEAD" > "$RUNNER_TEMP/pr-changed-paths"
excluded=true
while IFS= read -r -d '' path; do
case "$path" in
*.md|LICENSE|.gitignore) ;;
*) excluded=false; break ;;
esac
done < "$RUNNER_TEMP/pr-changed-paths"
[ "$excluded" = false ] || skip "its changes do not trigger the APK build"
fi
if [[ -n "$latest" && $(jq -r .status <<<"$latest") == completed ]]; then
conclusion=$(jq -r .conclusion <<<"$latest")
[[ "$conclusion" == success ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; }
run_id=$(jq -r .databaseId <<<"$latest")
break
if [[ "$conclusion" == success ]]; then
run_id=$(jq -r .id <<<"$latest")
if [ -n "$AUTO_RUN" ] && [ "$run_id" != "$AUTO_RUN" ]; then
skip "a newer build exists"
fi
break
fi
[[ "$conclusion" == action_required ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; }
fi
status=not-started
[[ -z "$latest" ]] || status=$(jq -r .status <<<"$latest")
echo "Waiting for the PR build of ${head:0:7} to finish ($status)"
sleep 30
done
[[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 30 minutes'; exit 1; }
[[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 120 minutes'; exit 1; }
run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")
jq -e --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
.event == "pull_request" and .head_sha == $head and .conclusion == "success" and
@@ -137,6 +195,13 @@ jobs:
.head.sha == $head and .base.sha == $base
' <<<"$current" >/dev/null ||
{ echo "::error::PR #$PR_NUMBER moved on while its build was checked; publish again"; exit 1; }
if [ "$EVENT_NAME" = workflow_run ] || { [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; }; then
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$current" >/dev/null && skip "it is labelled no-test-build"
if [ "$EVENT_NAME" = workflow_dispatch ]; then
git fetch --no-tags origin main
git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$(jq -r .user.login <<<"$current")" || skip "the PR opener is no longer trusted"
fi
fi
{
echo "pr_number=$PR_NUMBER"
echo "run_id=$run_id"
@@ -271,17 +336,24 @@ jobs:
echo "release=$release" >> "$GITHUB_OUTPUT"
echo "apk=$GITHUB_SERVER_URL/$repo/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
- name: Whether the PR's branch is in this repo
id: same-repo
- name: Whether the PR opener is trusted
id: trusted-opener
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
run: |
head_repo=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .head.repo.full_name)
echo "same=$([ "$head_repo" = "$GITHUB_REPOSITORY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
opener=$(jq -r .user.login <<<"$pr")
git fetch --no-tags origin main
if [ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] ||
git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener"; then
echo "trusted=true" >> "$GITHUB_OUTPUT"
else
echo "trusted=false" >> "$GITHUB_OUTPUT"
fi
- name: Clear the publish request label
if: ${{ github.event_name == 'pull_request_target' && steps.publish.outcome == 'success' }}
if: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && steps.publish.outcome == 'success' }}
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
@@ -295,12 +367,12 @@ jobs:
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
RELEASE: ${{ steps.publish.outputs.release }}
APK: ${{ steps.publish.outputs.apk }}
SAME_REPO: ${{ steps.same-repo.outputs.same }}
TRUSTED_OPENER: ${{ steps.trusted-opener.outputs.trusted }}
run: |
set -euo pipefail
short=${HEAD_SHA:0:7}
mark='<!-- droiddeck-pr-release -->'
if [ "$SAME_REPO" = true ]; then
if [ "$TRUSTED_OPENER" = true ]; then
NEXT='Each green build of a new push is signed and published here on its own. Label the PR `no-test-build` to stop that.'
else
NEXT='Pushes to this PR do not re-sign automatically. After a new green build, a maintainer can add the `publish-test` label again.'
+3 -1
View File
@@ -61,7 +61,7 @@ Compatibility and performance vary by device; hardware validation is limited. De
## Credits and licence
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc/<pid>/status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driverLine truncated
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@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, without taking their code. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. x86 AppImages packed with [sharun](https://github.com/VHSgunzo/sharun) by VHSgunzo (MIT) start because DroidDeck's own [FEX](https://github.com/FEX-Emu/FEX) build (MIT) puts the platform name under `AT_PLATFORM`, which sharun's [userland-execve](https://crates.io/crates/userland-execve) loader (MIT) requires; FEX filed it under `AT_BASE_PLATFORM`. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultLine truncated
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
@@ -71,6 +71,8 @@ Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead.
Remote Play from a PC to the arm64 Steam client goes through a stand-in for the V4L2 decoder and the libdrm dumb buffers that Steam's `streaming_client` expects: each frame is decoded by Android's MediaCodec through the app, or by the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) that ships in Steam's own runtime, into dma-heap buffers that its Vulkan renderer imports. The Qualcomm low-latency decoder settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0).
Steam's Browse buttons open a GTK 3 file chooser through PyGObject (LGPL-2.1-or-later). It runs under Steam's own `reaper` with Steam's app ID, which [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) reads from the process tree (`GetAppIdFromReaper` in `src/Utils/Process.cpp`) to show it over Steam.
Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose fixes for them (`311210.py` sets ALSA audio, `570940.py` installs VC++ 2017) fail under ARM64 Proton.
+8
View File
@@ -87,10 +87,18 @@ def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
// A source build that did not compile proot still pins a published pack, so the app
// downloads the patched binary instead of falling back to the rootfs copy.
if (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) {
return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]]
}
return [(name): [sha256: '', size: 0L]]
}
def digest = java.security.MessageDigest.getInstance('SHA-256')
+40 -5
View File
@@ -27,7 +27,10 @@
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.CAMERA" />
@@ -56,6 +59,15 @@
<meta-data android:name="android.game_mode_config" android:resource="@xml/game_mode_config" />
<service android:name=".glasses.LumaRgbCaptureService" android:exported="false"
android:process=":rgb_diagnostic" />
<service android:name=".input.HomeButtonService"
android:label="@string/integration_shortcuts_service"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:exported="true">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
</service>
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
android:permission="android.permission.DUMP"
@@ -70,10 +82,21 @@
</intent-filter>
</activity>
<activity
android:name=".PairingGuideActivity"
android:exported="false"
android:launchMode="singleTask"
android:taskAffinity="${applicationId}.pairingguide"
android:excludeFromRecents="true"
android:supportsPictureInPicture="true"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"
android:theme="@style/AppTheme" />
<activity
android:name=".FrontEndActivity"
android:exported="true"
android:screenOrientation="sensorLandscape"
android:screenOrientation="user"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
@@ -125,7 +148,7 @@
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity="${applicationId}.home"
android:screenOrientation="sensorLandscape"
android:screenOrientation="user"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -135,6 +158,18 @@
</activity>
<activity
android:name=".PinRequestActivity"
android:exported="true"
android:excludeFromRecents="true"
android:taskAffinity="${applicationId}.pin"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.content.pm.action.CONFIRM_PIN_SHORTCUT" />
<action android:name="android.content.pm.action.CONFIRM_PIN_APPWIDGET" />
</intent-filter>
</activity>
<activity
android:name=".input.ControllerEditorActivity"
android:exported="false"
@@ -146,14 +181,14 @@
<activity
android:name=".files.FileManagerActivity"
android:exported="false"
android:screenOrientation="sensorLandscape"
android:screenOrientation="user"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
<activity
android:name=".files.FilePickerActivity"
android:exported="false"
android:screenOrientation="sensorLandscape"
android:screenOrientation="user"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
@@ -185,7 +220,7 @@
<activity
android:name=".stores.StoreLoginActivity"
android:exported="false"
android:screenOrientation="sensorLandscape"
android:screenOrientation="user"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
+2 -1
View File
@@ -184,8 +184,9 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) {
VkExtent2D e = levelExtent(extent, l);
if (!makeImage(pyrA_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
if (!makeImage(pyrB_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
if (!makeImage(flowLvl_[l], e, VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
}
for (int l = flowFinest_; l < kLevels; ++l)
if (!makeImage(flowLvl_[l], levelExtent(extent, l), VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
pyrAs_.resize(kLevels);
for (int l = flowFinest_; l < kLevels; ++l)
if (!makeImage(pyrAs_[l], levelExtent(extent, l), VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
@@ -439,7 +439,7 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
if (S.flowRegUboPtr) { FlowRegUBO fu{cfg.frDt, cfg.frLambda, cfg.frEdge, cfg.frEps}; std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); }
S.flowUbo.resize(kLevels); S.flowUboMem.resize(kLevels); S.flowUboPtr.resize(kLevels);
for (int l = 0; l < kLevels; ++l) {
for (int l = fg->flowFinest(); l < kLevels; ++l) {
makeUbo(dd, dev, mp, sizeof(FlowUBO), S.flowUbo[l], S.flowUboMem[l], S.flowUboPtr[l]);
if (S.flowUboPtr[l]) { FlowUBO u{cfg.flowScale, (uint32_t)l, 0.6f, 1.6f}; std::memcpy(S.flowUboPtr[l], &u, sizeof(u)); }
}
@@ -464,13 +464,12 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
}
S.sFlow.resize(kLevels);
for (int l = 0; l < kLevels; ++l) {
for (int l = fg->flowFinest(); l < kLevels; ++l) {
S.sFlow[l] = allocSet(dd, dev, pool, pFlow.setLayout);
int pred = (l + 1 < kLevels) ? l + 1 : l;
VkImageView currLvl = (l >= fg->flowFinest()) ? pyrAs[l].view : pyrA[l].view;
wUbo(dd, dev, S.sFlow[l], 0, S.flowUbo[l], sizeof(FlowUBO));
wImg(dd, dev, S.sFlow[l], 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[l].view, samp, GEN);
wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currLvl, samp, GEN);
wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrAs[l].view, samp, GEN);
wImg(dd, dev, S.sFlow[l], 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[pred].view, samp, GEN);
wImg(dd, dev, S.sFlow[l], 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowLvl[l].view, VK_NULL_HANDLE, GEN);
}
+27 -1
View File
@@ -9,7 +9,7 @@
#define VENC_MAX_BUFFERS 16
enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5 };
enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5, VDEC_CONFIG = 6, VDEC_CAPTURE = 7, VDEC_PACKET = 8, VDEC_RESULT = 9 };
enum venc_touch_action { VENC_TOUCH_DOWN = 0, VENC_TOUCH_MOVE = 1, VENC_TOUCH_UP = 2 };
enum venc_codec { VENC_H264 = 0, VENC_HEVC = 1 };
@@ -52,4 +52,30 @@ struct venc_touch {
uint32_t x, y;
};
struct vdec_config {
uint32_t type;
uint32_t codec;
uint32_t width, height;
uint32_t stride, rows;
uint32_t bitstreams, bitstream_size;
};
struct vdec_capture {
uint32_t type;
uint32_t index;
uint32_t size;
};
struct vdec_packet {
uint32_t type;
uint32_t input, bytes, capture;
int64_t pts_us;
};
struct vdec_result {
uint32_t type;
int32_t status;
uint32_t frame;
};
#endif
+239
View File
@@ -3,6 +3,7 @@
#include <jni.h>
#include <media/NdkMediaCodec.h>
#include <media/NdkMediaFormat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
@@ -11,6 +12,7 @@
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cerrno>
#include <cstring>
#include <string>
@@ -45,6 +47,218 @@ int32_t avc_profile(int32_t v4l2) {
}
}
struct DmaBufSync {
uint64_t flags;
};
constexpr unsigned long kDmaBufIoctlSync = _IOW('b', 0, DmaBufSync);
constexpr uint64_t kDmaBufSyncWrite = 2, kDmaBufSyncStart = 0, kDmaBufSyncEnd = 4;
constexpr int32_t kColorFormatYuv420Planar = 19;
class Decoder {
public:
~Decoder() { release(); }
void release() {
if (codec_) {
AMediaCodec_stop(codec_);
AMediaCodec_delete(codec_);
codec_ = nullptr;
}
if (bitstream_) munmap((void *)bitstream_, bitstream_size_);
bitstream_ = nullptr;
for (auto &c : captures_) drop(c);
}
bool configure(const vdec_config &c, int fd) {
release();
if (c.width < 16 || c.height < 16 || c.stride < c.width || c.rows < c.height || c.bitstreams == 0 ||
c.bitstreams > VENC_MAX_BUFFERS || c.bitstream_size == 0) {
LOG("bad decoder config: %ux%u stride %u rows %u, %u bitstreams", c.width, c.height, c.stride, c.rows,
c.bitstreams);
return false;
}
bitstream_size_ = (size_t)c.bitstreams * c.bitstream_size;
void *p = mmap(nullptr, bitstream_size_, PROT_READ, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) {
LOG("could not map the bitstream buffers: %s", strerror(errno));
return false;
}
bitstream_ = (const uint8_t *)p;
config_ = c;
codec_ = create(c, true);
if (!codec_) codec_ = create(c, false);
if (!codec_) {
LOG("no %s decoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height);
release();
return false;
}
src_stride_ = (int32_t)c.width;
src_rows_ = (int32_t)c.height;
src_width_ = (int32_t)c.width;
src_height_ = (int32_t)c.height;
src_planar_ = false;
shown_ = false;
using GetName = media_status_t (*)(AMediaCodec *, char **);
using ReleaseName = void (*)(AMediaCodec *, char *);
static auto get_name = (GetName)dlsym(RTLD_DEFAULT, "AMediaCodec_getName");
static auto release_name = (ReleaseName)dlsym(RTLD_DEFAULT, "AMediaCodec_releaseName");
char *name = nullptr;
if (get_name && get_name(codec_, &name) != AMEDIA_OK) name = nullptr;
LOG("decoding %s %ux%u with %s", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height,
name ? name : "MediaCodec");
if (name && release_name) release_name(codec_, name);
return true;
}
void capture(const vdec_capture &c, int fd) {
if (c.index >= VENC_MAX_BUFFERS) {
close(fd);
return;
}
Capture &cap = captures_[c.index];
drop(cap);
void *p = mmap(nullptr, c.size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) {
LOG("could not map capture buffer %u: %s", c.index, strerror(errno));
close(fd);
return;
}
cap = {fd, (uint8_t *)p, c.size};
}
bool decode(const vdec_packet &p, bool *frame) {
*frame = false;
if (!codec_ || p.capture >= VENC_MAX_BUFFERS || !captures_[p.capture].data || p.input >= config_.bitstreams ||
p.bytes == 0 || p.bytes > config_.bitstream_size)
return false;
auto start = std::chrono::steady_clock::now();
ssize_t in = AMediaCodec_dequeueInputBuffer(codec_, 20000);
if (in < 0) return false;
size_t capacity = 0;
uint8_t *dst = AMediaCodec_getInputBuffer(codec_, (size_t)in, &capacity);
if (!dst || capacity < p.bytes) {
AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, 0, 0, 0);
return false;
}
memcpy(dst, bitstream_ + (size_t)p.input * config_.bitstream_size, p.bytes);
if (AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, p.bytes, (uint64_t)std::max<int64_t>(p.pts_us, 0), 0) !=
AMEDIA_OK)
return false;
auto wait = std::chrono::milliseconds(shown_ ? 25 : 250);
while (std::chrono::steady_clock::now() - start < wait) {
AMediaCodecBufferInfo info;
ssize_t o = AMediaCodec_dequeueOutputBuffer(codec_, &info, 2000);
if (o == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
read_format();
continue;
}
if (o < 0) continue;
size_t size = 0;
uint8_t *data = AMediaCodec_getOutputBuffer(codec_, (size_t)o, &size);
if (data && info.size > 0 && (size_t)info.offset + (size_t)info.size <= size)
*frame = copy(data + info.offset, (size_t)info.size, captures_[p.capture]) || *frame;
AMediaCodec_releaseOutputBuffer(codec_, (size_t)o, false);
if (info.presentationTimeUs >= p.pts_us) break;
}
shown_ = shown_ || *frame;
return true;
}
private:
struct Capture {
int fd = -1;
uint8_t *data = nullptr;
size_t size = 0;
};
static void drop(Capture &c) {
if (c.data) munmap(c.data, c.size);
if (c.fd >= 0) close(c.fd);
c = Capture();
}
AMediaCodec *create(const vdec_config &c, bool low_latency) {
const char *mime = c.codec == VENC_HEVC ? "video/hevc" : "video/avc";
AMediaCodec *codec = AMediaCodec_createDecoderByType(mime);
if (!codec) return nullptr;
AMediaFormat *f = AMediaFormat_new();
AMediaFormat_setString(f, AMEDIAFORMAT_KEY_MIME, mime);
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_WIDTH, (int32_t)c.width);
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_HEIGHT, (int32_t)c.height);
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatYuv420SemiPlanar);
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, (int32_t)c.bitstream_size);
if (low_latency) {
AMediaFormat_setInt32(f, "low-latency", 1);
AMediaFormat_setInt32(f, "vendor.qti-ext-dec-low-latency.enable", 1);
AMediaFormat_setInt32(f, "vendor.qti-ext-dec-picture-order.enable", 1);
AMediaFormat_setInt32(f, "priority", 0);
AMediaFormat_setFloat(f, "operating-rate", 120.0f);
}
media_status_t s = AMediaCodec_configure(codec, f, nullptr, nullptr, 0);
AMediaFormat_delete(f);
if (s == AMEDIA_OK) s = AMediaCodec_start(codec);
if (s != AMEDIA_OK) {
AMediaCodec_delete(codec);
return nullptr;
}
return codec;
}
void read_format() {
AMediaFormat *f = AMediaCodec_getOutputFormat(codec_);
if (!f) return;
int32_t v;
if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_WIDTH, &v) && v > 0) src_width_ = v;
if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_HEIGHT, &v) && v > 0) src_height_ = v;
src_stride_ = AMediaFormat_getInt32(f, "stride", &v) && v >= src_width_ ? v : src_width_;
src_rows_ = AMediaFormat_getInt32(f, "slice-height", &v) && v >= src_height_ ? v : src_height_;
src_planar_ = AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, &v) && v == kColorFormatYuv420Planar;
LOG("decoder output %dx%d stride %d rows %d %s", src_width_, src_height_, src_stride_, src_rows_,
src_planar_ ? "planar" : "semi-planar");
AMediaFormat_delete(f);
}
bool copy(const uint8_t *src, size_t size, const Capture &cap) {
size_t luma = (size_t)src_stride_ * src_rows_;
size_t chroma = src_planar_ ? 2 * (size_t)(src_stride_ / 2) * (src_rows_ / 2) : (size_t)src_stride_ * (src_rows_ / 2);
if (size < luma + chroma) return false;
uint32_t w = std::min<uint32_t>((uint32_t)src_width_, config_.stride);
uint32_t h = std::min<uint32_t>((uint32_t)src_height_, config_.rows);
if ((size_t)config_.stride * config_.rows * 3 / 2 > cap.size) return false;
DmaBufSync sync = {kDmaBufSyncStart | kDmaBufSyncWrite};
ioctl(cap.fd, kDmaBufIoctlSync, &sync);
uint8_t *y = cap.data, *uv = cap.data + (size_t)config_.stride * config_.rows;
for (uint32_t row = 0; row < h; row++)
memcpy(y + (size_t)row * config_.stride, src + (size_t)row * src_stride_, w);
const uint8_t *su = src + luma;
for (uint32_t row = 0; row < h / 2; row++) {
uint8_t *d = uv + (size_t)row * config_.stride;
if (!src_planar_) {
memcpy(d, su + (size_t)row * src_stride_, w & ~1u);
continue;
}
const uint8_t *u = su + (size_t)row * (src_stride_ / 2);
const uint8_t *vv = su + (size_t)(src_stride_ / 2) * (src_rows_ / 2) + (size_t)row * (src_stride_ / 2);
for (uint32_t x = 0; x < w / 2; x++) {
d[2 * x] = u[x];
d[2 * x + 1] = vv[x];
}
}
sync.flags = kDmaBufSyncEnd | kDmaBufSyncWrite;
ioctl(cap.fd, kDmaBufIoctlSync, &sync);
return true;
}
AMediaCodec *codec_ = nullptr;
vdec_config config_ = {};
const uint8_t *bitstream_ = nullptr;
size_t bitstream_size_ = 0;
Capture captures_[VENC_MAX_BUFFERS];
int32_t src_width_ = 0, src_height_ = 0, src_stride_ = 0, src_rows_ = 0;
bool src_planar_ = false;
bool shown_ = false;
};
class Session {
public:
explicit Session(int fd) : fd_(fd) {}
@@ -85,6 +299,24 @@ public:
memcpy(&b, buf, sizeof b);
set_bitrate(b.bitrate);
for (int i = 0; i < nfds; i++) close(fds[i]);
} else if (type == VDEC_CONFIG && n == (ssize_t)sizeof(vdec_config)) {
vdec_config c;
memcpy(&c, buf, sizeof c);
bool ok = nfds == 1 && decoder_.configure(c, fds[0]);
for (int i = 0; i < nfds; i++) close(fds[i]);
decoded(ok ? 0 : -1, false);
} else if (type == VDEC_CAPTURE && n == (ssize_t)sizeof(vdec_capture)) {
vdec_capture c;
memcpy(&c, buf, sizeof c);
if (nfds == 1) decoder_.capture(c, fds[0]);
else for (int i = 0; i < nfds; i++) close(fds[i]);
} else if (type == VDEC_PACKET && n == (ssize_t)sizeof(vdec_packet)) {
vdec_packet p;
memcpy(&p, buf, sizeof p);
bool frame = false;
bool ok = decoder_.decode(p, &frame);
for (int i = 0; i < nfds; i++) close(fds[i]);
decoded(ok ? 0 : -1, frame);
} else {
LOG("unexpected message %u of %zd bytes; closing", type, n);
for (int i = 0; i < nfds; i++) close(fds[i]);
@@ -117,7 +349,13 @@ private:
send(fd_, &d, sizeof d, MSG_NOSIGNAL);
}
void decoded(int32_t status, bool frame) {
vdec_result r = {VDEC_RESULT, status, frame ? 1u : 0u};
send(fd_, &r, sizeof r, MSG_NOSIGNAL);
}
void release() {
decoder_.release();
if (codec_) {
AMediaCodec_stop(codec_);
AMediaCodec_delete(codec_);
@@ -292,6 +530,7 @@ private:
int32_t dst_stride_ = 0, dst_rows_ = 0;
std::vector<Mapping> inputs_, outputs_;
std::vector<uint8_t> header_;
Decoder decoder_;
};
std::atomic<int> g_listener{-1};
@@ -371,8 +371,8 @@ void ahb_swapchain_set_mode(int on, int live) {
: "; gralloc frames still in flight stay on the layer (or take the copy path) until then");
else
droiddeck_log("layer", "zero-copy: %s at launch (%s)", on ? "on" : "off",
on ? "DROIDDECK_WAYLAND_ZERO_COPY=1: games present their own gralloc buffers on the display layer"
: "the drawer's Zero-copy presentation switch turns it on live");
on ? "HDR session: games present their own gralloc buffers on the display layer"
: "only HDR sessions turn it on");
if (live) wl_display_flush_clients(droiddeck_get_display());
droiddeck_request_redraw();
}
+256 -22
View File
@@ -186,6 +186,9 @@ static void on_client_created(struct wl_listener *l, void *data) {
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP, ROLE_CURSOR };
#define DAMAGE_RECTS 8
struct damage_list { int32_t r[DAMAGE_RECTS][4]; int n; };
struct surface {
struct wl_resource *resource;
struct wl_list link;
@@ -204,9 +207,11 @@ struct surface {
struct wl_resource *dmabuf;
struct dmabuf_buffer *dmabuf_buf;
struct wl_listener dmabuf_destroy;
const void *last_dmabuf;
int buf_w, buf_h, has_content;
int buf_alpha;
int opaque[4], pending_opaque[4], pending_opaque_set;
struct damage_list damage_buf, pending_damage_buf, damage_local, pending_damage_local;
int src_set, dst_set;
float src[4];
int dst[2];
@@ -257,6 +262,26 @@ static struct wl_event_source *g_render_idle, *g_frame_timer;
static int g_dirty;
static int64_t g_dirty_since_ns;
volatile int g_render_on_commit = 1;
static int64_t g_rendered_tick_ns;
static int g_tick_held;
static int64_t g_hold_missed_ns;
#define HOLD_RETRY_NS 1000000000LL
#define PACE_BUFFERS 32
static struct {
unsigned ticks, ticks_late_2ms, renders, commit_renders, null_attaches, reattaches, presented, replaced, undrawn, distinct;
int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns;
const void *buffers[PACE_BUFFERS];
uint64_t game_frames_seen;
} g_pace;
static void pace_note_buffer(const void *buffer) {
for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++)
if (g_pace.buffers[i] == buffer) return;
if (g_pace.distinct < PACE_BUFFERS) g_pace.buffers[g_pace.distinct] = buffer;
g_pace.distinct++;
}
static int64_t g_last_vsync_ns;
static int64_t g_tick_vsync_ns;
static int64_t g_refresh_ns = 16666667;
@@ -264,7 +289,7 @@ static struct wl_event_source *g_fallback_timer;
static int g_fallback_armed;
volatile int g_fps_limit;
/* fps limit -1 (Performance mode without a limit): replaced buffers go back to the client at once instead of once per refresh. */
/* fps limit -1 (phone output, not mirrored): replaced buffers go back to the client at once instead of once per refresh. */
volatile int g_release_unpaced;
volatile int g_hide_shell;
@@ -307,6 +332,7 @@ static struct {
} g_perf;
static void schedule_render(void);
static void on_commit_idle(void *data);
static int64_t now_ns(void) {
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
@@ -624,6 +650,68 @@ static void fire_frames(struct wl_list *frames) {
}
}
static void scene_size(int *w, int *h);
static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h);
static struct surface *g_hud_surface, *g_hud_shm;
static int64_t g_hud_shm_ns;
static int64_t g_hud_last_ns, g_hud_alive_ns;
static int g_hud_fresh;
static int g_hud_new;
#define HUD_TIMES 256
static pthread_mutex_t g_hud_times_lock = PTHREAD_MUTEX_INITIALIZER;
static float g_hud_times[HUD_TIMES];
static int64_t g_hud_times_total, g_hud_shown_ns;
static void hud_frame_shown(int64_t t) {
const int64_t previous = g_hud_shown_ns;
g_hud_shown_ns = t;
if (!previous || t <= previous) return;
pthread_mutex_lock(&g_hud_times_lock);
g_hud_times[g_hud_times_total % HUD_TIMES] = (float)((t - previous) / 1e6);
g_hud_times_total++;
pthread_mutex_unlock(&g_hud_times_lock);
}
static int tree_rank(const struct surface *s, const struct surface *want, int *rank, int depth) {
const struct surface *c;
if (depth > 8) return 0;
wl_list_for_each(c, &s->children, child_link)
if (c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
if (s == want) return 1;
(*rank)++;
wl_list_for_each(c, &s->children, child_link)
if (!c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
return 0;
}
static int render_rank(const struct surface *want) {
const struct surface *s;
int rank = 0;
if (g_desktop && tree_rank(g_desktop, want, &rank, 0)) return rank;
wl_list_for_each(s, &g_toplevels, toplevel_link)
if (tree_rank(s, want, &rank, 0)) return rank;
return -1;
}
static int below_surface(const struct surface *s, const struct surface *other) {
const int a = render_rank(s), b = render_rank(other);
return a >= 0 && b >= 0 && a < b;
}
int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
pthread_mutex_lock(&g_hud_times_lock);
*total = g_hud_times_total;
int64_t n = *total < len ? *total : len;
if (n > HUD_TIMES) n = HUD_TIMES;
for (int64_t i = 0; i < n; i++) out[i] = g_hud_times[(*total - n + i) % HUD_TIMES];
pthread_mutex_unlock(&g_hud_times_lock);
return (int)n;
}
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_game_program(int pid, const char *program);
static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) {
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
int32_t stride = wl_shm_buffer_get_stride(shm);
@@ -646,6 +734,33 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
g_stat_shm++;
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
if (ci && ci->asked_feedback) ci->shm_frames++;
int local_w, local_h;
surface_size(s, &local_w, &local_h);
const double region = s->src_set ? (double)s->src[2] * s->src[3] : (double)w * h;
const int64_t local_max = damage_area(&s->damage_local, local_w, local_h);
const int64_t local = local_w > 0 && local_h > 0
? (int64_t)((double)local_max * region / ((double)local_w * local_h)) : local_max;
const int64_t buffer_max = damage_area(&s->damage_buf, w, h);
const int64_t area = (int64_t)w * h;
int64_t damaged = buffer_max > local ? buffer_max : local;
if (damaged > area) damaged = area;
const int64_t now = now_ns();
if (damaged * 16 >= area && (!g_hud_surface || now - g_hud_last_ns > 1000000000LL) &&
(s == g_hud_shm || !g_hud_shm || now - g_hud_shm_ns > 1000000000LL)) {
const struct surface *top = s;
int scene_w, scene_h, top_w, top_h, depth = 0;
while (top->parent && depth++ < 8) top = top->parent;
scene_size(&scene_w, &scene_h);
surface_size(top, &top_w, &top_h);
int64_t shown = (int64_t)local_w * local_h;
if ((int64_t)top_w * top_h > shown) shown = (int64_t)top_w * top_h;
if (top->role == ROLE_TOPLEVEL && top->mapped && shown * 2 >= (int64_t)scene_w * scene_h) {
g_hud_shm = s;
g_hud_shm_ns = now;
g_hud_new = 1;
droiddeck_on_game_frame();
}
}
}
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
@@ -662,17 +777,12 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
s->has_content = s->shm_img != NULL;
}
static struct surface *g_hud_surface;
static int64_t g_hud_last_ns, g_hud_alive_ns;
static int g_hud_fresh;
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_game_program(int pid, const char *program);
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
if (!repeat) {
if (!s->dmabuf && s->last_dmabuf == buffer) g_pace.reattaches++;
s->last_dmabuf = buffer;
pace_note_buffer(buffer);
drop_dmabuf(s, 1);
s->dmabuf = buffer;
s->dmabuf_buf = b;
@@ -724,8 +834,9 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
name, b->width, b->height, (unsigned long long)b->modifier);
}
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL ||
(announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
(!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))) {
char name[160];
describe(s, name, sizeof(name));
g_hud_surface = s;
@@ -749,7 +860,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
}
if (s == g_hud_surface) {
g_hud_alive_ns = now_ns();
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_game_frames++; droiddeck_on_game_frame(); }
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; droiddeck_on_game_frame(); }
}
}
@@ -786,8 +897,45 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r,
wl_resource_add_destroy_listener(buffer, &s->pending_buffer_destroy);
}
}
static int64_t rect_area(const int32_t *r, int bound_w, int bound_h) {
int64_t x0 = r[0], y0 = r[1], x1 = (int64_t)r[0] + r[2], y1 = (int64_t)r[1] + r[3];
if (bound_w > 0 && bound_h > 0) {
if (x0 < 0) x0 = 0;
if (y0 < 0) y0 = 0;
if (x1 > bound_w) x1 = bound_w;
if (y1 > bound_h) y1 = bound_h;
}
if (x1 <= x0 || y1 <= y0) return 0;
const int64_t w = x1 - x0, h = y1 - y0;
return (w < 65536 ? w : 65536) * (h < 65536 ? h : 65536);
}
static void note_damage(struct damage_list *d, int32_t x, int32_t y, int32_t w, int32_t h) {
if (w <= 0 || h <= 0) return;
const int32_t rect[4] = { x, y, w, h };
int slot = d->n;
if (slot == DAMAGE_RECTS) {
slot = 0;
for (int i = 1; i < DAMAGE_RECTS; i++)
if (rect_area(d->r[i], 0, 0) < rect_area(d->r[slot], 0, 0)) slot = i;
if (rect_area(rect, 0, 0) <= rect_area(d->r[slot], 0, 0)) return;
} else {
d->n++;
}
memcpy(d->r[slot], rect, sizeof(rect));
}
static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h) {
int64_t max = 0;
for (int i = 0; i < d->n; i++) {
const int64_t area = rect_area(d->r[i], bound_w, bound_h);
if (area > max) max = area;
}
return max;
}
static void surface_damage(struct wl_client *c, struct wl_resource *r,
int32_t x, int32_t y, int32_t w, int32_t h) {}
int32_t x, int32_t y, int32_t w, int32_t h) {
struct surface *s = wl_resource_get_user_data(r);
note_damage(&s->pending_damage_local, x, y, w, h);
}
static void frame_callback_destroy(struct wl_resource *r) {
wl_list_remove(wl_resource_get_link(r));
}
@@ -796,12 +944,15 @@ static void feedback_resource_destroy(struct wl_resource *r) {
wl_list_remove(wl_resource_get_link(r));
}
static void feedback_discard_all(struct wl_list *list) {
static unsigned feedback_discard_all(struct wl_list *list) {
struct wl_resource *fb, *tmp;
unsigned n = 0;
wl_resource_for_each_safe(fb, tmp, list) {
wp_presentation_feedback_send_discarded(fb);
wl_resource_destroy(fb);
n++;
}
return n;
}
static uint32_t nominal_refresh_ns(void) {
@@ -830,6 +981,7 @@ static void feedback_present_all(struct wl_list *list, int64_t t) {
nominal_refresh_ns(), 0, 0,
WP_PRESENTATION_FEEDBACK_KIND_VSYNC);
wl_resource_destroy(fb);
g_pace.presented++;
}
}
@@ -987,13 +1139,18 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
s->pending_opaque_set = 0;
}
s->damage_buf = s->pending_damage_buf;
s->damage_local = s->pending_damage_local;
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
if (s->pending_attach) {
struct wl_resource *buffer = s->pending_buffer;
struct dmabuf_buffer *db = get_dmabuf(buffer);
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
uint8_t pixel[4];
feedback_discard_all(&s->feedback);
g_pace.replaced += feedback_discard_all(&s->feedback);
if (!buffer) g_pace.null_attaches++;
else if (!db) s->last_dmabuf = NULL;
if (buffer) {
wl_list_remove(&s->pending_buffer_destroy.link);
@@ -1051,7 +1208,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {}
static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {}
static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r,
int32_t x, int32_t y, int32_t w, int32_t h) {}
int32_t x, int32_t y, int32_t w, int32_t h) {
struct surface *s = wl_resource_get_user_data(r);
note_damage(&s->pending_damage_buf, x, y, w, h);
}
static void surface_offset(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y) {}
static const struct wl_surface_interface surface_impl = {
@@ -1094,6 +1254,7 @@ static void surface_resource_destroy(struct wl_resource *r) {
droiddeck_text_input_surface_gone(r);
if (g_desktop == s) { g_desktop = NULL; droiddeck_log("desktop", "the desktop closed"); }
if (g_hud_surface == s) { g_hud_surface = NULL; droiddeck_on_game_surface(NULL, NULL); }
if (g_hud_shm == s) g_hud_shm = NULL;
constraints_surface_gone(s);
unmap_toplevel(s);
@@ -1962,14 +2123,23 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) {
unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
static void render_scene(void) {
if (atomic_load(&g_stream_on)) { render_stream(); return; }
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
struct draw_list dl = {0};
struct surface *s;
int w, h;
const int64_t t_scene = now_ns();
int copy = 0;
if (g_dirty_since_ns) {
const int64_t wait = t_scene - g_dirty_since_ns;
g_pace.wait_ns += wait;
if (wait > g_pace.wait_max_ns) g_pace.wait_max_ns = wait;
g_pace.renders++;
g_dirty_since_ns = 0;
}
g_dirty = 0;
g_rendered_tick_ns = g_tick_vsync_ns;
g_tick_held = 0;
g_hud_fresh = 0;
g_hdr_unimported = NULL;
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
@@ -2103,9 +2273,13 @@ static void render_scene(void) {
if (rendered) {
int64_t t = presented_ns(t_scene);
g_stat_frames++;
if (g_hud_new) {
g_hud_new = 0;
hud_frame_shown(t);
}
wl_list_for_each(s, &g_surfaces, link) {
if (s->drawn) feedback_present_all(&s->feedback, t);
else feedback_discard_all(&s->feedback);
else g_pace.undrawn += feedback_discard_all(&s->feedback);
}
fire_all_frames();
} else {
@@ -2130,10 +2304,25 @@ static int on_fallback_timer(void *data) {
return 0;
}
/* A new frame is drawn when it arrives instead of at the next screen tick, at most once per refresh,
while frames go straight back to the game (no compositor limit), without streaming or frame generation. */
static int commit_renders_on(void) {
return g_render_on_commit && g_release_unpaced && !atomic_load(&g_stream_on) && !vkp_framegen_active();
}
static int render_on_commit(void) {
return commit_renders_on() && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns;
}
static void schedule_render(void) {
if (!g_dirty && !g_dirty_since_ns) g_dirty_since_ns = now_ns();
g_dirty = 1;
if (!g_display) return;
if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) return;
if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) {
if (render_on_commit())
g_render_idle = wl_event_loop_add_idle(wl_display_get_event_loop(g_display), on_commit_idle, NULL);
return;
}
if (g_fallback_armed) return;
if (!g_fallback_timer)
g_fallback_timer = wl_event_loop_add_timer(wl_display_get_event_loop(g_display),
@@ -2147,18 +2336,45 @@ static int scene_waits_for_game(int64_t now) {
return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active();
}
static void on_commit_idle(void *data) {
g_render_idle = NULL;
if (!g_dirty || !commit_renders_on() || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return;
g_pace.commit_renders++;
render_scene();
}
static void on_vsync(int64_t frame_time_ns) {
int64_t now = now_ns();
g_perf.ticks++;
if (frame_time_ns > 0 && now >= frame_time_ns) {
const int64_t late = now - frame_time_ns;
g_pace.ticks++;
g_pace.tick_late_ns += late;
if (late > g_pace.tick_late_max_ns) g_pace.tick_late_max_ns = late;
if (late > 2000000LL) g_pace.ticks_late_2ms++;
}
if (g_last_vsync_ns) {
int64_t d = now - g_last_vsync_ns;
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
}
g_last_vsync_ns = now;
g_tick_vsync_ns = frame_time_ns;
if (vkp_apply_window_request()) g_dirty = 1;
if (vkp_effects_sync()) g_dirty = 1;
if (vkp_cardboard_pose_changed()) g_dirty = 1;
int tick_change = 0;
if (vkp_apply_window_request()) tick_change = 1;
if (vkp_effects_sync()) tick_change = 1;
if (vkp_cardboard_pose_changed()) tick_change = 1;
if (tick_change) g_dirty = 1;
/* A frame that arrived after this refresh was already drawn is left for the next arrival to draw;
drawing it here would block that arrival too and keep every frame waiting for the tick. A client
that draws again only after its frame callback sends no such arrival: once a held frame is still
waiting at the next tick, the tick draws every frame for a second before holding one again. */
if (g_tick_held && g_dirty) g_hold_missed_ns = now;
g_tick_held = 0;
if (!tick_change && commit_renders_on() && g_dirty_since_ns && now - g_dirty_since_ns < g_refresh_ns &&
now - g_hold_missed_ns >= HOLD_RETRY_NS) {
g_tick_held = 1;
return;
}
if (g_dirty && !scene_waits_for_game(now)) render_scene();
}
@@ -3262,6 +3478,24 @@ static int on_stats_timer(void *data) {
#undef PERF_MS
memset(&g_perf, 0, sizeof(g_perf));
}
const uint64_t game = g_game_frames - g_pace.game_frames_seen;
if (g_pace.ticks || g_pace.renders || game || g_pace.reattaches || g_pace.null_attaches || g_pace.distinct ||
g_pace.presented || g_pace.replaced || g_pace.undrawn) {
droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | "
"new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an "
"empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, "
"%u not drawn",
g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6,
g_pace.ticks, g_pace.ticks_late_2ms,
g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6,
g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct,
g_pace.presented, g_pace.replaced, g_pace.undrawn);
}
{
const uint64_t seen = g_game_frames;
memset(&g_pace, 0, sizeof(g_pace));
g_pace.game_frames_seen = seen;
}
g_stat_frames = g_stat_dmabuf = g_stat_shm = 0;
droiddeck_color_stats_tick();
@@ -25,6 +25,7 @@ extern void droiddeck_wayland_send_pointer(int action, int x, int y);
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
extern int droiddeck_cursor_snapshot(int *out, int cap);
extern int droiddeck_cursor_serial(void);
extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total);
extern void droiddeck_wayland_send_key(int evdev, int state);
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
@@ -35,6 +36,7 @@ extern void droiddeck_wayland_output_resized(void);
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
extern volatile int g_fps_limit;
extern volatile int g_release_unpaced;
extern volatile int g_render_on_commit;
extern volatile int g_hide_shell;
extern volatile int g_zero_copy;
extern volatile unsigned g_zero_copy_last;
@@ -268,6 +270,20 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
return n;
}
JNIEXPORT jlong JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHudFrameTimes(JNIEnv *env, jclass clazz, jfloatArray out) {
(void)clazz;
if (!out) return 0;
jint cap = (*env)->GetArrayLength(env, out);
float *buf = cap > 0 ? malloc(sizeof(float) * (size_t)cap) : NULL;
if (!buf) return 0;
int64_t total = 0;
int n = droiddeck_hud_frame_times(buf, cap, &total);
if (n > 0) (*env)->SetFloatArrayRegion(env, out, 0, n, buf);
free(buf);
return (jlong)total;
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) {
(void)env; (void)clazz;
@@ -572,6 +588,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv *
free(s);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetRenderOnCommit(JNIEnv *env, jclass clazz, jboolean on) {
g_render_on_commit = on ? 1 : 0;
__android_log_print(ANDROID_LOG_INFO, TAG, "render on commit %s", on ? "on" : "off");
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
g_fps_limit = fps > 0 ? fps : 0;
@@ -52,6 +52,7 @@ import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
import com.droiddeck.launcher.core.WirelessAdbFix
import com.droiddeck.launcher.core.WifiDiscovery
import com.droiddeck.launcher.core.SteamIntegration
import com.droiddeck.launcher.core.WirelessAdbPairingService
import com.droiddeck.launcher.ui.CoreRow
import com.droiddeck.launcher.ui.PerformancePage
@@ -91,12 +92,17 @@ class FrontEndActivity : ComponentActivity() {
private val components = ComponentsMenu(this, ui)
private val decky = DeckyMenu(this, ui)
private val updates = UpdatesMenu(this, ui)
private val protons = ProtonMenu(this, ui) { !busy && flood == null && pkgStage == null && components.compBusy == null }
private val protons = ProtonMenu(this, ui) { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null }
private var installed by mutableStateOf<String?>(null)
private var flood by mutableStateOf<PendingFlood?>(null)
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
private class CompatLaunch(val intent: Intent, val loading: com.droiddeck.launcher.session.LoadingState, var menuInstall: Boolean)
private var compatLaunch by mutableStateOf<CompatLaunch?>(null)
private var compatFlood by mutableStateOf<androidx.compose.ui.graphics.Color?>(null)
private var compatLaunchPoll: Runnable? = null
private var compatLaunchVisible = false
private var returning by mutableStateOf<ReturningFlood?>(null)
private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?)
private var ready by mutableStateOf(false)
@@ -134,9 +140,14 @@ class FrontEndActivity : ComponentActivity() {
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
private var catalogLoading by mutableStateOf(false)
private var packageRows by mutableStateOf<List<PackageRow>?>(null)
private var pkgId by mutableStateOf<String?>(null)
private var pkgStage by mutableStateOf<String?>(null)
private var pkgPercent by mutableIntStateOf(-1)
private object PackageOperation {
val id = mutableStateOf<String?>(null)
val stage = mutableStateOf<String?>(null)
val percent = mutableIntStateOf(-1)
}
private var pkgId by PackageOperation.id
private var pkgStage by PackageOperation.stage
private var pkgPercent by PackageOperation.percent
private var desktopInstalled by mutableStateOf(false)
private var desktopPresent by mutableStateOf(false)
private var battleNetInstalled by mutableStateOf(false)
@@ -168,6 +179,7 @@ class FrontEndActivity : ComponentActivity() {
private var picturePosition by mutableStateOf("center")
private var stretch16x9 by mutableStateOf(false)
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
private var launcherFullscreen by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
@@ -187,6 +199,8 @@ class FrontEndActivity : ComponentActivity() {
private var wifiDiscoveryLocation by mutableStateOf(false)
private var wifiDiscoveryAsked by mutableStateOf(false)
private var wifiDiscoveryBlocked by mutableStateOf(false)
private var integrationState by mutableStateOf(SteamIntegration.State())
private var integrationFocus by mutableStateOf<SteamIntegration.Feature?>(null)
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
refreshWifiDiscovery()
@@ -255,8 +269,65 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.setWifiDiscoveryEnabled(this, false)
}
wifiDiscovery = SessionPrefs.wifiDiscoveryEnabled(this)
integrationState = readIntegration()
}
private var shortcutsTried = false
private fun readIntegration() = SteamIntegration.read(this)
.copy(locationBlocked = wifiDiscoveryBlocked, shortcutsTried = shortcutsTried)
private fun openIntegration(feature: SteamIntegration.Feature? = null) {
SteamIntegration.dismissSuggestion(this)
refreshWifiDiscovery()
integrationState = readIntegration()
integrationFocus = feature
navRequest = "setup:integration"
}
private fun readIntegrationIntent(incoming: Intent) {
if (incoming.action != SteamIntegration.ACTION_SETUP) return
openIntegration(incoming.getStringExtra(SteamIntegration.EXTRA_FEATURE)?.let {
runCatching { SteamIntegration.Feature.valueOf(it) }.getOrNull()
})
}
private fun integrationSettings(intent: Intent, fallback: String = android.provider.Settings.ACTION_SETTINGS) {
try { startActivity(intent) }
catch (_: android.content.ActivityNotFoundException) { startActivity(Intent(fallback)) }
catch (_: SecurityException) { startActivity(Intent(fallback)) }
}
private fun configureIntegration(feature: SteamIntegration.Feature) {
when (feature) {
SteamIntegration.Feature.WIFI -> {
if (wifiDiscovery && wifiDiscoveryPermission) {
SessionPrefs.setWifiDiscoveryEnabled(this, false)
} else if (wifiDiscoveryPermission) {
SessionPrefs.setWifiDiscoveryEnabled(this, true)
} else {
SessionPrefs.setWifiDiscoveryAsked(this)
wifiLocationPermission.launch(WifiDiscovery.permissions)
}
refreshWifiDiscovery()
}
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else {
HomeApp.setHomeScreenEnabled(this, true)
refreshHomeAppState()
manageHomeApp()
}
SteamIntegration.Feature.SHORTCUTS -> {
if (!integrationState.shortcuts) shortcutsTried = true
if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME)
else integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
}
}
}
private fun openAppInfo() =
integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
private fun openWifiDiscoverySettings() {
if (!WifiDiscovery.permissionGranted(this)) {
wifiPermissionSettings.launch(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
@@ -391,8 +462,6 @@ class FrontEndActivity : ComponentActivity() {
private var theme by mutableStateOf("graphite")
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
private var hdrOn by mutableStateOf(false)
private var fpsLimit by mutableStateOf(0)
private var performanceMode by mutableStateOf(false)
private var upscaler by mutableStateOf(0)
private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf<String?>(null)
@@ -426,6 +495,21 @@ class FrontEndActivity : ComponentActivity() {
private var homeScreenEnabled by mutableStateOf(false)
private var defaultHomeLabel by mutableStateOf<String?>(null)
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
private var androidAppsListing = 0
private val packageCallback = object : android.content.pm.LauncherApps.Callback() {
private fun changed() {
refreshAndroidApps()
if (HomeWidgets.providers != null) HomeWidgets.refreshProviders(this@FrontEndActivity)
}
override fun onPackageRemoved(packageName: String, user: android.os.UserHandle) = changed()
override fun onPackageAdded(packageName: String, user: android.os.UserHandle) = changed()
override fun onPackageChanged(packageName: String, user: android.os.UserHandle) = changed()
override fun onPackagesAvailable(packageNames: Array<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
override fun onPackagesUnavailable(packageNames: Array<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
override fun onShortcutsChanged(packageName: String, shortcuts: MutableList<android.content.pm.ShortcutInfo>, user: android.os.UserHandle) {
if (homeAppSelected) HomePins.refresh(this@FrontEndActivity)
}
}
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
private lateinit var displayManager: DisplayManager
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
@@ -439,16 +523,15 @@ class FrontEndActivity : ComponentActivity() {
}
override fun startActivity(intent: Intent?) {
val compat = protons.protonBusyId != null || ProtonExtras.installInProgress
if (intent?.component?.className == SessionActivity::class.java.name) {
if (compatLaunch != null) return
when {
busy || LinuxRuntimeInstaller.isBusy() -> {
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
return
}
protons.protonBusyId != null || ProtonExtras.installInProgress -> {
android.widget.Toast.makeText(this, R.string.main_wait_proton_install, android.widget.Toast.LENGTH_SHORT).show()
return
}
compat -> Unit
pkgStage != null -> {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
return
@@ -463,6 +546,10 @@ class FrontEndActivity : ComponentActivity() {
return
}
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
if (compat) {
waitForCompat(intent)
return
}
}
super.startActivity(intent)
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
@@ -474,6 +561,11 @@ class FrontEndActivity : ComponentActivity() {
flood = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
if (!busy && !LinuxRuntimeInstaller.isBusy() &&
(protons.protonBusyId != null || ProtonExtras.installInProgress)) {
compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal
waitForCompat(f.intent)
}
return
}
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
@@ -481,6 +573,72 @@ class FrontEndActivity : ComponentActivity() {
overridePendingTransition(0, 0)
}
private fun waitForCompat(next: Intent, menuInstall: Boolean = protons.protonBusyId != null) {
if (compatLaunch != null) return
com.droiddeck.launcher.ui.LaunchOrigin.take()
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
val waiting = CompatLaunch(Intent(next), com.droiddeck.launcher.session.LoadingState(this), menuInstall)
compatLaunch = waiting
val poll = object : Runnable {
override fun run() {
if (isDestroyed || isFinishing || compatLaunch !== waiting) return
if (protons.protonBusyId != null || ProtonExtras.installInProgress) {
waiting.menuInstall = waiting.menuInstall || protons.protonBusyId != null
val percent = if (protons.protonBusyId != null) protons.protonPercent else -1
val stage = protons.protonStage ?: getString(R.string.load_compat_wait)
waiting.loading.say(if (percent >= 0) getString(R.string.load_compat_progress, stage, percent) else stage,
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
waiting.loading.percent = percent
waiting.loading.tick()
ui.postDelayed(this, 250)
return
}
if (!compatLaunchVisible) { ui.postDelayed(this, 250); return }
val problem = protons.protonProblem.takeIf { waiting.menuInstall }
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null)) {
waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime),
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
waiting.loading.percent = if (pkgStage != null) pkgPercent else percent
waiting.loading.tick()
ui.postDelayed(this, 250)
return
}
compatLaunchPoll = null
if (problem != null) waiting.loading.showEnded(problem)
else {
compatLaunch = null
startActivity(waiting.intent)
}
}
}
compatLaunchPoll = poll
poll.run()
}
private fun cancelCompatLaunch() {
compatLaunchPoll?.let(ui::removeCallbacks)
compatLaunchPoll = null
compatLaunch = null
compatFlood = null
}
private fun restoreCompatLaunch(state: Bundle) {
savedIntent(state, KEY_COMPAT_LAUNCH)?.let { next ->
val problem = state.getString(KEY_COMPAT_PROBLEM)
if (problem == null) waitForCompat(next, state.getBoolean(KEY_COMPAT_MENU_INSTALL))
else compatLaunch = CompatLaunch(next,
com.droiddeck.launcher.session.LoadingState(this).apply { showEnded(problem) }, false)
}
}
private fun saveCompatLaunch(state: Bundle) {
compatLaunch?.let {
state.putParcelable(KEY_COMPAT_LAUNCH, it.intent)
state.putBoolean(KEY_COMPAT_MENU_INSTALL, it.menuInstall)
if (it.loading.ended) state.putString(KEY_COMPAT_PROBLEM, it.loading.step)
}
}
private var shortcutPicker by mutableStateOf(false)
private var shortcutLibraryScanning by mutableStateOf(false)
@Volatile private var libraryScanGeneration = 0
@@ -542,7 +700,7 @@ class FrontEndActivity : ComponentActivity() {
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
if (pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
@@ -654,7 +812,7 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.epic_client_uninstalling, android.widget.Toast.LENGTH_SHORT).show()
return false
}
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
if (pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
@@ -762,6 +920,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) readIntegrationIntent(intent)
readGameIntent(intent)
gameSyncFolder = GameFileSync.folder(this)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
@@ -775,7 +934,8 @@ class FrontEndActivity : ComponentActivity() {
steamGamesX64 = cachedX64
backActionsInverted = SessionPrefs.backActionsInverted(this)
orientation = SessionPrefs.orientation(this)
requestedOrientation = orientation
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
downloadSource = DownloadSource.mode(this)
downloadMirror = DownloadSource.mirror(this)
@@ -827,6 +987,8 @@ class FrontEndActivity : ComponentActivity() {
isHomeApp = homeAppSelected,
homeScreenEnabled = homeScreenEnabled,
defaultHomeLabel = defaultHomeLabel,
integration = integrationState,
integrationFocus = integrationFocus,
androidApps = androidApps,
secondScreenDisplays = secondScreenDisplays,
packages = packageRows,
@@ -844,6 +1006,7 @@ class FrontEndActivity : ComponentActivity() {
phantomProcessStatus = phantomProcessStatus,
showPhantomGate = showPhantomGate,
orientation = orientation,
launcherOrientation = launcherOrientation,
launcherFullscreen = launcherFullscreen,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
@@ -1026,6 +1189,10 @@ class FrontEndActivity : ComponentActivity() {
onOrientation = { value ->
SessionPrefs.setOrientation(this, value)
orientation = value
},
onLauncherOrientation = { value ->
com.droiddeck.launcher.core.AppUiPrefs.setOrientation(this, value)
launcherOrientation = value
requestedOrientation = value
},
onLauncherFullscreen = { on ->
@@ -1061,6 +1228,14 @@ class FrontEndActivity : ComponentActivity() {
downloadProxy = DownloadSource.proxyHostPort(this)
},
onHomeApp = { manageHomeApp() },
onSteamIntegration = ::openIntegration,
onIntegration = { integrationFocus = null; configureIntegration(it) },
onIntegrationAppInfo = ::openAppInfo,
onIntegrationLocation = ::openWifiDiscoverySettings,
onDismissIntegration = {
SteamIntegration.dismissSuggestion(this)
integrationState = readIntegration()
},
onHomeScreen = { on ->
HomeApp.setHomeScreenEnabled(this, on)
refreshHomeAppState()
@@ -1114,7 +1289,12 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
},
onDismissPhantomGate = { showPhantomGate = false },
onShowPhantomGate = {
refreshPhantomStatus()
showPhantomGate = true
},
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
onStartPairingGuide = { displayId -> PairingGuideActivity.start(this, displayId) },
onOpenNotificationSettings = {
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
@@ -1210,12 +1390,23 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
}
}
androidx.activity.compose.BackHandler(compatLaunch != null) { cancelCompatLaunch() }
compatLaunch?.loading?.let { loading ->
if (!loading.ended) com.droiddeck.launcher.ui.VeilRing()
com.droiddeck.launcher.ui.LoadingOverlay(
loading.step, loading.percent, loading.elapsed, getString(R.string.load_compat_hint), loading.ended,
loading.topic, loading.readable, title = getString(R.string.load_compat_title),
onCancel = ::cancelCompatLaunch, onClose = ::cancelCompatLaunch,
flood = compatFlood, onFlooded = { compatFlood = null },
)
}
}
}
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
else {
restoreCompatLaunch(savedInstanceState)
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
}
@@ -1244,6 +1435,10 @@ class FrontEndActivity : ComponentActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
if (intent.action == SteamIntegration.ACTION_SETUP) {
readIntegrationIntent(intent)
return
}
readGameIntent(intent)
refresh()
startSteamAtStartupIfEnabled()
@@ -1301,24 +1496,15 @@ class FrontEndActivity : ComponentActivity() {
}
}
override fun onUserInteraction() {
super.onUserInteraction()
com.droiddeck.launcher.ui.Ambient.poke()
}
override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean {
if (event.actionMasked == android.view.MotionEvent.ACTION_UP || event.actionMasked == android.view.MotionEvent.ACTION_CANCEL) {
com.droiddeck.launcher.ui.Ambient.poke()
}
return super.dispatchTouchEvent(event)
}
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
com.droiddeck.launcher.ui.Ambient.poke()
return super.dispatchGenericMotionEvent(event)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (compatLaunch != null) {
if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
return true
}
if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
}
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) {
@@ -1335,16 +1521,28 @@ class FrontEndActivity : ComponentActivity() {
}
}
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
if (compatLaunch != null && !compatLaunch!!.loading.ended &&
com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
return super.dispatchGenericMotionEvent(event)
}
override fun onPause() {
compatLaunchVisible = false
super.onPause()
}
override fun onResume() {
super.onResume()
compatLaunchVisible = true
orientation = SessionPrefs.orientation(this)
requestedOrientation = orientation
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
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.ui.Motion.refresh(this)
com.droiddeck.launcher.ui.Ambient.poke()
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
}
@@ -1385,10 +1583,20 @@ class FrontEndActivity : ComponentActivity() {
})
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
refreshSecondScreenDisplays()
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
HomeWidgets.startListening(this)
}
@Suppress("OVERRIDE_DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) return
@Suppress("DEPRECATION")
super.onActivityResult(requestCode, resultCode, data)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
switchingTo?.let {
outState.putParcelable(KEY_SWITCHING_TO, it)
@@ -1401,6 +1609,7 @@ class FrontEndActivity : ComponentActivity() {
else @Suppress("DEPRECATION") state.getParcelable(key)
override fun onDestroy() {
cancelCompatLaunch()
updates.unregister()
super.onDestroy()
}
@@ -1408,6 +1617,8 @@ class FrontEndActivity : ComponentActivity() {
override fun onStop() {
unregisterReceiver(wifiLocationReceiver)
unregisterReceiver(mediaReceiver)
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
HomeWidgets.stopListening(this)
ui.removeCallbacks(mediaRefresh)
com.droiddeck.launcher.stores.StoresState.libraryListener = null
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
@@ -1423,7 +1634,22 @@ class FrontEndActivity : ComponentActivity() {
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
defaultHomeLabel = HomeApp.defaultLabel(this)
androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList()
refreshAndroidApps()
integrationState = readIntegration()
}
private fun refreshAndroidApps() {
if (!homeAppSelected) {
++androidAppsListing
androidApps = emptyList()
return
}
val seq = ++androidAppsListing
HomePins.refresh(this)
Thread({
val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList())
ui.post { if (seq == androidAppsListing) androidApps = apps }
}, "home-apps").start()
}
private fun refreshSecondScreenDisplays() {
@@ -1605,7 +1831,7 @@ class FrontEndActivity : ComponentActivity() {
}
private fun openBattleNet(args: List<String> = emptyList()) {
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
if (pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return
}
@@ -1713,7 +1939,7 @@ class FrontEndActivity : ComponentActivity() {
ModeSettings(
mode = mode, resolution = resolution,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit, performanceMode = performanceMode,
hdr = hdrOn, hdrReason = hdrReason,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
@@ -1721,8 +1947,7 @@ class FrontEndActivity : ComponentActivity() {
steamDownloadsInBackground = steamDownloadsInBackground,
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
pipAutoEnter = pipAutoEnter,
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null,
unfoldedControls = if (mode == SessionService.MODE_STEAM) unfoldedControls else null,
unfoldedControlsWithController = unfoldedControlsWithController,
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
backActionsInverted = backActionsInverted,
@@ -1748,11 +1973,7 @@ class FrontEndActivity : ComponentActivity() {
bootMovieCustomName = bootMovieCustomName,
bootMovieImporting = bootMovieImporting,
bootMovieProgress = bootMovieProgress,
wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null,
wifiDiscoveryPermission = wifiDiscoveryPermission,
wifiDiscoveryLocation = wifiDiscoveryLocation,
wifiDiscoveryAsked = wifiDiscoveryAsked,
wifiDiscoveryBlocked = wifiDiscoveryBlocked,
integration = if (mode == SessionService.MODE_STEAM) integrationState else null,
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyLatest else null,
deckyBranch = decky.deckyBranch,
@@ -1761,26 +1982,12 @@ class FrontEndActivity : ComponentActivity() {
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
),
ModeSettingsActions(
onWifiDiscovery = { on ->
if (!on) {
SessionPrefs.setWifiDiscoveryEnabled(this, false)
refreshWifiDiscovery()
} else if (WifiDiscovery.permissionGranted(this)) {
SessionPrefs.setWifiDiscoveryEnabled(this, true)
refreshWifiDiscovery()
} else if (wifiDiscoveryBlocked) {
openWifiDiscoverySettings()
} else {
SessionPrefs.setWifiDiscoveryAsked(this)
wifiLocationPermission.launch(WifiDiscovery.permissions)
}
},
onWifiDiscoverySettings = { openWifiDiscoverySettings() },
onIntegration = ::configureIntegration,
onIntegrationAppInfo = ::openAppInfo,
onIntegrationLocation = ::openWifiDiscoverySettings,
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
onPerformanceMode = { on -> SessionPrefs.setPerformanceMode(this, mode, on); performanceMode = on },
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
@@ -2031,8 +2238,6 @@ class FrontEndActivity : ComponentActivity() {
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
loadBootMovie()
hdrOn = SessionPrefs.hdr(this, mode)
fpsLimit = SessionPrefs.fpsLimit(this, mode)
performanceMode = SessionPrefs.performanceMode(this, mode)
upscaler = SessionPrefs.upscaler(this)
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
@@ -2138,7 +2343,7 @@ class FrontEndActivity : ComponentActivity() {
val scanGeneration = ++libraryScanGeneration
val artRefreshesAtStart = HashMap(steamArtRefreshes)
if (shortcutPicker) shortcutLibraryScanning = true
if (SessionPrefs.steamClientArch(this) == "x86_64" && !OfflineMode.enabled(this)) {
if (!OfflineMode.enabled(this)) {
Thread({ com.droiddeck.launcher.session.FexCatalog.refresh(this) }, "fex-catalog").start()
}
Thread({
@@ -2330,6 +2535,9 @@ class FrontEndActivity : ComponentActivity() {
private const val SESSION_SWITCH_WAIT_MS = 30_000L
private const val SESSION_SWITCH_POLL_MS = 250L
private const val KEY_PENDING_SWITCH = "pending_switch"
private const val KEY_COMPAT_LAUNCH = "compat_launch"
private const val KEY_COMPAT_MENU_INSTALL = "compat_menu_install"
private const val KEY_COMPAT_PROBLEM = "compat_problem"
private const val KEY_SWITCHING_TO = "switching_to"
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
@@ -13,7 +13,7 @@ class HomeActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
routeHome()
}
@@ -6,20 +6,41 @@ import android.graphics.Bitmap
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.LauncherApps
import android.content.pm.ShortcutInfo
import android.graphics.Rect
import android.os.Process
import android.os.UserHandle
import android.os.UserManager
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.graphics.drawable.toBitmap
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlin.math.roundToInt
object HomeApp {
private const val ICON_DP = 72
data class LaunchableApp(
val label: String,
val packageName: String,
val className: String,
val icon: Bitmap?,
)
val system: Boolean = false,
val game: Boolean = false,
val installedAt: Long = 0L,
val updatedAt: Long = 0L,
val user: UserHandle? = null,
val userSerial: Long = 0L,
) {
val component get() = ComponentName(packageName, className)
val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
val work get() = userSerial != 0L
}
fun isHomeScreenEnabled(context: Context): Boolean =
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
@@ -69,33 +90,79 @@ object HomeApp {
fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS)
fun launchableApps(context: Context): List<LaunchableApp> {
val launcher = context.getSystemService(LauncherApps::class.java)
val users = context.getSystemService(UserManager::class.java)
val pm = context.packageManager
val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
val apps = pm.queryIntentActivities(launch, 0)
.asSequence()
.mapNotNull { result ->
val activity = result.activityInfo ?: return@mapNotNull null
if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null
val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName }
val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull()
LaunchableApp(label, activity.packageName, activity.name, icon)
val own = Process.myUserHandle()
val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
val apps = users.userProfiles.flatMap { user ->
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
val component = info.componentName
if (component.packageName == context.packageName && user == own) return@mapNotNull null
val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
val app = info.applicationInfo
val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
@Suppress("DEPRECATION")
val game = app.category == ApplicationInfo.CATEGORY_GAME || app.flags and ApplicationInfo.FLAG_IS_GAME != 0
LaunchableApp(
label, component.packageName, component.className, icon,
system = app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0,
game = game,
installedAt = info.firstInstallTime,
updatedAt = updated ?: info.firstInstallTime,
user = user,
userSerial = serial,
)
}
.distinctBy { it.packageName }
.toList()
return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
}
return apps.distinctBy { it.key }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
}
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) {
val intent = Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(ComponentName(app.packageName, app.className))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (displayId == null) {
context.startActivity(intent)
return
}
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
context.startActivity(intent, options.toBundle())
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null, bounds: Rect? = null) {
val options = displayId?.let { ActivityOptions.makeBasic().setLaunchDisplayId(it).toBundle() }
val launcher = context.getSystemService(LauncherApps::class.java)
launcher.startMainActivity(app.component, app.user ?: Process.myUserHandle(), bounds, options)
}
fun canUseShortcuts(context: Context): Boolean =
runCatching { context.getSystemService(LauncherApps::class.java).hasShortcutHostPermission() }.getOrDefault(false)
fun shortcuts(context: Context, app: LaunchableApp): List<ShortcutInfo> {
if (!canUseShortcuts(context)) return emptyList()
val query = LauncherApps.ShortcutQuery()
.setPackage(app.packageName)
.setActivity(app.component)
.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST)
return runCatching { context.getSystemService(LauncherApps::class.java).getShortcuts(query, app.user ?: Process.myUserHandle()) }
.getOrNull().orEmpty()
.filter { it.isEnabled }
.sortedWith(compareBy<ShortcutInfo> { if (it.isDeclaredInManifest) 0 else 1 }.thenBy { it.rank })
.take(5)
}
fun shortcutIcon(context: Context, info: ShortcutInfo, px: Int = (ICON_DP * context.resources.displayMetrics.density).roundToInt()): Bitmap? = runCatching {
context.getSystemService(LauncherApps::class.java)
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
}.getOrNull()
fun startShortcut(context: Context, info: ShortcutInfo) {
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
}
fun openAppInfo(context: Context, app: LaunchableApp) {
context.getSystemService(LauncherApps::class.java)
.startAppDetailsActivity(app.component, app.user ?: Process.myUserHandle(), null, null)
}
fun canUninstall(app: LaunchableApp): Boolean = !app.system && !app.work
fun uninstall(context: Context, app: LaunchableApp) {
context.startActivity(
Intent(Intent.ACTION_DELETE, Uri.fromParts("package", app.packageName, null))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
fun isActiveSteamSession(): Boolean =
@@ -0,0 +1,65 @@
package com.droiddeck.launcher
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import org.json.JSONArray
import org.json.JSONObject
import java.util.UUID
object HomeFolders {
data class Folder(val id: String, val name: String, val apps: List<String>)
private const val PREFS = "home_launcher"
private const val KEY = "folders"
var folders by mutableStateOf<List<Folder>>(emptyList())
private set
private var loaded = false
fun load(context: Context) {
if (loaded) return
loaded = true
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
folders = runCatching {
val array = JSONArray(raw)
(0 until array.length()).map { i ->
val o = array.getJSONObject(i)
val apps = o.getJSONArray("apps")
Folder(o.getString("id"), o.getString("name"), (0 until apps.length()).map { apps.getString(it) })
}
}.getOrDefault(emptyList())
}
fun create(context: Context, name: String, appKey: String): Folder {
val folder = Folder(UUID.randomUUID().toString(), name, listOf(appKey))
update(context, without(appKey) + folder)
return folder
}
fun add(context: Context, folderId: String, appKey: String) =
update(context, without(appKey).map { if (it.id == folderId) it.copy(apps = it.apps + appKey) else it })
fun remove(context: Context, appKey: String) = update(context, without(appKey))
fun rename(context: Context, folderId: String, name: String) =
update(context, folders.map { if (it.id == folderId) it.copy(name = name) else it })
fun delete(context: Context, folderId: String) = update(context, folders.filterNot { it.id == folderId })
fun migrateMembers(context: Context, keyFor: (String) -> String?) {
if (folders.none { f -> f.apps.any { '/' !in it } }) return
update(context, folders.map { f -> f.copy(apps = f.apps.map { if ('/' in it) it else keyFor(it) ?: it }.distinct()) })
}
private fun without(appKey: String): List<Folder> =
folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() }
private fun update(context: Context, next: List<Folder>) {
folders = next
val array = JSONArray()
for (f in next) array.put(JSONObject().put("id", f.id).put("name", f.name).put("apps", JSONArray(f.apps)))
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
}
}
@@ -0,0 +1,26 @@
package com.droiddeck.launcher
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
object HomeHidden {
private const val PREFS = "home_launcher"
private const val KEY = "hidden"
var keys by mutableStateOf<Set<String>>(emptySet())
private set
private var loaded = false
fun load(context: Context) {
if (loaded) return
loaded = true
keys = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, emptySet()).orEmpty().toSet()
}
fun set(context: Context, key: String, hidden: Boolean) {
keys = if (hidden) keys + key else keys - key
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, keys).apply()
}
}
@@ -0,0 +1,75 @@
package com.droiddeck.launcher
import android.content.Context
import android.content.pm.LauncherApps
import android.content.pm.ShortcutInfo
import android.graphics.Bitmap
import android.os.Handler
import android.os.Looper
import android.os.Process
import android.os.UserManager
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
/** Shortcuts other apps asked to put on the home screen. The system keeps the pinned set per launcher. */
object HomePins {
class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) {
val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else ""
val label get() = info.shortLabel?.toString()?.trim().orEmpty().ifEmpty { appLabel }
val work get() = userSerial != 0L
}
var pinned by mutableStateOf<List<Pinned>>(emptyList())
private set
private val main = Handler(Looper.getMainLooper())
private var listing = 0
fun refresh(context: Context) {
val app = context.applicationContext
val seq = ++listing
Thread({
val list = runCatching { load(app) }.getOrDefault(emptyList())
main.post { if (seq == listing) pinned = list }
}, "home-pins").start()
}
private fun load(context: Context): List<Pinned> {
if (!HomeApp.canUseShortcuts(context)) return emptyList()
val launcher = context.getSystemService(LauncherApps::class.java)
val users = context.getSystemService(UserManager::class.java)
val pm = context.packageManager
val own = Process.myUserHandle()
val query = LauncherApps.ShortcutQuery().setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
return users.userProfiles.flatMap { user ->
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
runCatching { launcher.getShortcuts(query, user) }.getOrNull().orEmpty()
.filter { it.isEnabled && it.isPinned }
.map { info ->
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.`package`, 0)).toString() }
.getOrDefault(info.`package`)
Pinned(info, HomeApp.shortcutIcon(context, info), appLabel, serial)
}
}
}
fun accept(context: Context, request: LauncherApps.PinItemRequest): Boolean {
val ok = runCatching { request.isValid && request.accept() }.getOrDefault(false)
if (ok) refresh(context)
return ok
}
fun unpin(context: Context, pinned: Pinned) {
val info = pinned.info
val launcher = context.getSystemService(LauncherApps::class.java)
val query = LauncherApps.ShortcutQuery().setPackage(info.`package`).setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
val unpinned = runCatching {
val current = checkNotNull(launcher.getShortcuts(query, info.userHandle))
val keep = current.map { it.id } - info.id
launcher.pinShortcuts(info.`package`, keep, info.userHandle)
}.isSuccess
if (!unpinned) return
listing++
this.pinned = this.pinned.filterNot { it.key == pinned.key }
}
}
@@ -0,0 +1,317 @@
package com.droiddeck.launcher
import android.app.Activity
import android.appwidget.AppWidgetHost
import android.appwidget.AppWidgetHostView
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProviderInfo
import android.content.Context
import android.content.Intent
import android.content.pm.LauncherApps
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.SizeF
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.graphics.drawable.toBitmap
import org.json.JSONArray
import org.json.JSONObject
import kotlin.math.hypot
import kotlin.math.roundToInt
object HomeWidgets {
data class Placed(val id: Int, val widthDp: Int, val heightDp: Int)
data class Provider(
val info: AppWidgetProviderInfo,
val label: String,
val appLabel: String,
val preview: Bitmap?,
val widthDp: Int,
val heightDp: Int,
)
private const val HOST_ID = 0x0DDE
private const val PREFS = "home_launcher"
private const val KEY = "widgets"
private const val REQUEST_BIND = 0x0DD1
private const val REQUEST_CONFIGURE = 0x0DD2
private const val REQUEST_RECONFIGURE = 0x0DD3
const val MIN_WIDTH_DP = 96
const val MIN_HEIGHT_DP = 56
var widgets by mutableStateOf<List<Placed>>(emptyList())
private set
var providers by mutableStateOf<List<Provider>?>(null)
private set
private var loaded = false
private var host: Host? = null
private var pending: AppWidgetProviderInfo? = null
private var pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
private var pinRequest: LauncherApps.PinItemRequest? = null
private val main = Handler(Looper.getMainLooper())
private class Host(context: Context) : AppWidgetHost(context, HOST_ID) {
override fun onCreateView(context: Context, appWidgetId: Int, appWidget: AppWidgetProviderInfo?): AppWidgetHostView =
HomeWidgetView(context)
}
class HomeWidgetView(context: Context) : AppWidgetHostView(context) {
var onLongPress: (() -> Unit)? = null
private var fired = false
private var downX = 0f
private var downY = 0f
private val slop = ViewConfiguration.get(context).scaledTouchSlop
private val longPress = Runnable {
fired = true
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
onLongPress?.invoke()
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
fired = false
downX = ev.x
downY = ev.y
postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong())
}
MotionEvent.ACTION_MOVE -> if (hypot(ev.x - downX, ev.y - downY) > slop) removeCallbacks(longPress)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> removeCallbacks(longPress)
}
return fired
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (fired) {
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) fired = false
return true
}
return super.onTouchEvent(event)
}
}
private fun host(context: Context): Host = host ?: Host(context.applicationContext).also { host = it }
fun load(context: Context) {
if (loaded) return
loaded = true
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
val manager = AppWidgetManager.getInstance(context)
val parsed = runCatching {
val array = JSONArray(raw)
(0 until array.length()).map { i ->
val o = array.getJSONObject(i)
Placed(o.getInt("id"), o.getInt("w"), o.getInt("h"))
}
}.getOrDefault(emptyList())
val live = parsed.filter { manager.getAppWidgetInfo(it.id) != null }
parsed.filterNot { it in live }.forEach { host(context).deleteAppWidgetId(it.id) }
widgets = live
if (live.size != parsed.size) save(context)
}
fun startListening(context: Context) {
load(context)
runCatching { host(context).startListening() }
}
fun stopListening(context: Context) {
runCatching { host(context).stopListening() }
}
fun info(context: Context, id: Int): AppWidgetProviderInfo? = AppWidgetManager.getInstance(context).getAppWidgetInfo(id)
fun createView(context: Context, id: Int): HomeWidgetView? {
val info = info(context, id) ?: return null
return host(context).createView(context, id, info) as? HomeWidgetView
}
fun applySize(view: AppWidgetHostView, widthDp: Int, heightDp: Int) {
if (Build.VERSION.SDK_INT >= 31) {
view.updateAppWidgetSize(Bundle(), listOf(SizeF(widthDp.toFloat(), heightDp.toFloat())))
} else {
@Suppress("DEPRECATION")
view.updateAppWidgetSize(null, widthDp, heightDp, widthDp, heightDp)
}
}
fun loadProviders(context: Context) {
if (providers != null) return
val app = context.applicationContext
Thread({
val pm = app.packageManager
val manager = AppWidgetManager.getInstance(app)
val dpi = app.resources.displayMetrics.densityDpi
val list = manager.installedProviders.mapNotNull { info ->
runCatching {
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.provider.packageName, 0)).toString() }
.getOrDefault(info.provider.packageName)
val drawable = info.loadPreviewImage(app, dpi) ?: info.loadIcon(app, dpi)
val preview = drawable?.let { d ->
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
val scale = minOf(1f, 360f / maxOf(w, h))
d.toBitmap((w * scale).roundToInt().coerceAtLeast(1), (h * scale).roundToInt().coerceAtLeast(1))
}
val (w, h) = defaultSize(app, info)
Provider(info, info.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { appLabel }, appLabel, preview, w, h)
}.getOrNull()
}.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, Provider::appLabel).thenBy(String.CASE_INSENSITIVE_ORDER, Provider::label))
main.post { providers = list }
}, "widget-providers").start()
}
fun refreshProviders(context: Context) {
providers = null
loadProviders(context)
}
private fun defaultSize(context: Context, info: AppWidgetProviderInfo): Pair<Int, Int> {
val density = context.resources.displayMetrics.density
var w = (info.minWidth / density).roundToInt()
var h = (info.minHeight / density).roundToInt()
if (Build.VERSION.SDK_INT >= 31) {
if (info.targetCellWidth > 0) w = maxOf(w, info.targetCellWidth * 80)
if (info.targetCellHeight > 0) h = maxOf(h, info.targetCellHeight * 80)
}
return w.coerceIn(160, 560) to h.coerceIn(MIN_HEIGHT_DP, 360)
}
fun minSize(context: Context, id: Int): Pair<Int, Int> {
val info = info(context, id) ?: return MIN_WIDTH_DP to MIN_HEIGHT_DP
val density = context.resources.displayMetrics.density
val w = (if (info.minResizeWidth > 0) info.minResizeWidth else info.minWidth) / density
val h = (if (info.minResizeHeight > 0) info.minResizeHeight else info.minHeight) / density
return w.roundToInt().coerceAtLeast(MIN_WIDTH_DP) to h.roundToInt().coerceAtLeast(MIN_HEIGHT_DP)
}
fun add(activity: Activity, provider: Provider) {
if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null)
}
/** Places a widget another app asked for; its own app has already configured it. */
fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean {
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false
val info = request.getAppWidgetProviderInfo(activity) ?: return false
load(activity)
add(activity, info, request)
return pending != null
}
private fun add(activity: Activity, info: AppWidgetProviderInfo, request: LauncherApps.PinItemRequest?) {
val h = host(activity)
val id = h.allocateAppWidgetId()
pending = info
pendingId = id
pinRequest = request
val manager = AppWidgetManager.getInstance(activity)
val bound = runCatching { manager.bindAppWidgetIdIfAllowed(id, info.profile, info.provider, null) }.getOrDefault(false)
if (bound) {
bound(activity, id, info)
return
}
val bind = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile)
@Suppress("DEPRECATION")
runCatching { activity.startActivityForResult(bind, REQUEST_BIND) }.onFailure { abandon(activity) }
}
private fun bound(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
val request = pinRequest
if (request == null) {
configure(activity, id, info)
return
}
val accepted = runCatching { request.isValid && request.accept(Bundle().apply { putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, id) }) }
.getOrDefault(false)
if (accepted) place(activity, id, info) else abandon(activity)
}
private fun configure(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
val optional = Build.VERSION.SDK_INT >= 31 &&
info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0
if (info.configure == null || optional) {
place(activity, id, info)
return
}
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_CONFIGURE, null) }
.onFailure { place(activity, id, info) }
}
fun canReconfigure(context: Context, id: Int): Boolean {
val info = info(context, id) ?: return false
if (info.configure == null) return false
return Build.VERSION.SDK_INT < 28 || info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE != 0
}
fun reconfigure(activity: Activity, id: Int) {
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_RECONFIGURE, null) }
}
fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int): Boolean {
when (requestCode) {
REQUEST_BIND -> {
val info = pending
if (resultCode == Activity.RESULT_OK && info != null) bound(activity, pendingId, info) else abandon(activity)
}
REQUEST_CONFIGURE -> {
val info = pending
if (resultCode == Activity.RESULT_OK && info != null) place(activity, pendingId, info) else abandon(activity)
}
REQUEST_RECONFIGURE -> Unit
else -> return false
}
return true
}
private fun abandon(context: Context) {
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) host(context).deleteAppWidgetId(pendingId)
pending = null
pinRequest = null
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
}
private fun place(context: Context, id: Int, info: AppWidgetProviderInfo) {
val (w, h) = defaultSize(context, info)
pending = null
pinRequest = null
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
widgets = widgets + Placed(id, w, h)
save(context)
}
fun resize(context: Context, id: Int, widthDp: Int, heightDp: Int) {
widgets = widgets.map { if (it.id == id) it.copy(widthDp = widthDp, heightDp = heightDp) else it }
save(context)
}
fun move(context: Context, id: Int, by: Int) {
val i = widgets.indexOfFirst { it.id == id }
val j = i + by
if (i < 0 || j !in widgets.indices) return
widgets = widgets.toMutableList().apply { add(j, removeAt(i)) }
save(context)
}
fun remove(context: Context, id: Int) {
host(context).deleteAppWidgetId(id)
widgets = widgets.filterNot { it.id == id }
save(context)
}
private fun save(context: Context) {
val array = JSONArray()
for (w in widgets) array.put(JSONObject().put("id", w.id).put("w", w.widthDp).put("h", w.heightDp))
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
}
}
@@ -0,0 +1,328 @@
package com.droiddeck.launcher
import android.app.ActivityOptions
import android.app.AppOpsManager
import android.app.PictureInPictureParams
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.provider.Settings
import android.util.Rational
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.core.AppLanguage
import com.droiddeck.launcher.core.GlobalSettings
import com.droiddeck.launcher.core.WirelessAdbPairingService
import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.LocalPalette
import com.droiddeck.launcher.ui.PrimaryButton
import com.droiddeck.launcher.ui.SecondaryButton
import kotlinx.coroutines.delay
class PairingGuideActivity : ComponentActivity() {
enum class Step { BUILD_NUMBER, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
private var settingsDisplay: Int? = null
private var inPip by mutableStateOf(false)
private var launchPending = false
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
setContent { DroidDeckTheme { Guide() } }
launchPending = savedInstanceState == null
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
launchPending = true
}
override fun onResume() {
super.onResume()
if (!launchPending) return
if (inPip || settingsDisplay != null) {
launchSettings()
return
}
enterPip()
if (!inPip) launchSettings()
}
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
inPip = isInPictureInPictureMode
if (isInPictureInPictureMode && launchPending) launchSettings()
}
private fun launchSettings() {
launchPending = false
openSettings(stepFor(this, WirelessAdbPairingService.stage.value))
}
private fun enterPip() {
inPip = runCatching {
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(4, 3)).build())
}.getOrDefault(false)
}
private fun openSettings(step: Step) {
val intent = if (step == Step.BUILD_NUMBER) {
Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
} else {
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val display = settingsDisplay
runCatching {
if (display == null) startActivity(intent)
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
}.onFailure {
runCatching { startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
}
private fun returnToApp() {
startActivity(Intent(this, FrontEndActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
finish()
}
@Composable
private fun Guide() {
val stage by WirelessAdbPairingService.stage.collectAsState()
val settingsState by produceState(SettingsState.read(this)) {
while (true) {
value = SettingsState.read(this@PairingGuideActivity)
delay(500)
}
}
val step = stepFor(settingsState, stage)
var previous by remember { mutableStateOf(step) }
LaunchedEffect(step) {
if (previous == Step.BUILD_NUMBER && step == Step.WIRELESS_DEBUGGING) openSettings(step)
previous = step
when (step) {
Step.DONE -> { delay(1_500); returnToApp() }
Step.FAILED -> { delay(3_000); returnToApp() }
else -> Unit
}
}
LaunchedEffect(stage) { if (stage == Stage.Idle) finish() }
BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
if (inPip) CompactStep(step, stage)
else FullGuide(step, stage)
}
}
@Composable
private fun CompactStep(step: Step, stage: Stage) {
Column(Modifier.fillMaxSize().padding(10.dp), verticalArrangement = Arrangement.SpaceBetween) {
Text(
instruction(step, stage), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onBackground, maxLines = 3, overflow = TextOverflow.Ellipsis,
)
StepVisual(step, compact = true)
StepDots(step)
}
}
@Composable
private fun FullGuide(step: Step, stage: Stage) {
Column(
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(stringResource(R.string.gate_title), style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
Text(instruction(step, stage), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground)
StepVisual(step, compact = false)
StepDots(step)
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
if (step == Step.DONE || step == Step.FAILED) {
PrimaryButton(stringResource(R.string.common_back), onClick = ::returnToApp)
} else {
PrimaryButton(stringResource(R.string.gate_open_dev), onClick = {
if (settingsDisplay == null) enterPip()
openSettings(step)
})
SecondaryButton(stringResource(R.string.common_cancel), onClick = {
WirelessAdbPairingService.cancel(this@PairingGuideActivity)
returnToApp()
})
}
}
}
}
@Composable
private fun instruction(step: Step, stage: Stage): String = when (step) {
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number)
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless)
Step.PAIR -> stringResource(R.string.pairguide_pair)
Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3)
Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_working)
Step.DONE -> stringResource(R.string.adbpair_title_done)
Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed)
}
@Composable
private fun StepVisual(step: Step, compact: Boolean) {
val colors = MaterialTheme.colorScheme
val accent = LocalPalette.current.signal
val pulse = rememberInfiniteTransition(label = "guidePulse")
val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat")
val label = when (step) {
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number)
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless)
Step.PAIR -> stringResource(R.string.pairguide_row_pair)
Step.CODE -> stringResource(R.string.adbpair_enter_code)
Step.WORKING, Step.DONE, Step.FAILED -> return
}
val rowHeight = if (compact) 34.dp else 56.dp
Row(
Modifier.fillMaxWidth().height(rowHeight).background(colors.surfaceVariant, RoundedCornerShape(10.dp))
.border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(10.dp)).padding(horizontal = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge,
color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
when (step) {
Step.WIRELESS_DEBUGGING -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent)
Box(contentAlignment = Alignment.Center) {
Box(Modifier.size(if (compact) 18.dp else 26.dp).scale(0.6f + beat * 0.8f).alpha(1f - beat)
.background(accent, CircleShape))
Box(Modifier.size(if (compact) 8.dp else 12.dp).background(accent, CircleShape))
}
}
}
}
}
@Composable
private fun Toggle(on: Boolean, accent: Color, compact: Boolean) {
val width = if (compact) 26.dp else 40.dp
val knob = if (compact) 12.dp else 18.dp
Box(
Modifier.width(width).height(knob + 4.dp)
.background(if (on) accent.copy(alpha = 0.6f) else MaterialTheme.colorScheme.outline, CircleShape).padding(2.dp),
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
) { Box(Modifier.size(knob).background(Color.White, CircleShape)) }
}
@Composable
private fun StepDots(step: Step) {
val accent = LocalPalette.current.signal
val shown = listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size
Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
shown.forEachIndexed { index, _ ->
Box(Modifier.size(if (index == at) 8.dp else 6.dp)
.background(if (index <= at) accent else MaterialTheme.colorScheme.outline, CircleShape))
}
Spacer(Modifier.width(2.dp))
}
}
private data class SettingsState(val developerOptions: Boolean, val wirelessDebugging: Boolean) {
companion object {
fun read(context: Context) = SettingsState(
GlobalSettings.developerOptionsOn(context),
GlobalSettings.wirelessDebuggingOn(context),
)
}
}
companion object {
private const val EXTRA_DISPLAY = "settingsDisplay"
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
private fun stepFor(context: Context, stage: Stage) = stepFor(SettingsState.read(context), stage)
private fun stepFor(settings: SettingsState, stage: Stage): Step = when (stage) {
is Stage.Working -> Step.WORKING
Stage.Done -> Step.DONE
is Stage.Failed -> Step.FAILED
is Stage.CodeNeeded -> Step.CODE
else -> when {
!settings.developerOptions -> Step.BUILD_NUMBER
!settings.wirelessDebugging -> Step.WIRELESS_DEBUGGING
else -> Step.PAIR
}
}
fun canFloat(context: Context): Boolean {
if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false
val ops = context.getSystemService(AppOpsManager::class.java) ?: return true
val mode = if (Build.VERSION.SDK_INT >= 29) {
ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
} else {
@Suppress("DEPRECATION")
ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
}
return mode == AppOpsManager.MODE_ALLOWED
}
fun start(context: Context, settingsDisplay: Int?): Boolean {
if (settingsDisplay == null && !canFloat(context)) return false
context.startActivity(Intent(context, PairingGuideActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) })
return true
}
}
}
@@ -0,0 +1,82 @@
package com.droiddeck.launcher
import android.content.Intent
import android.content.pm.LauncherApps
import android.graphics.Bitmap
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.core.graphics.drawable.toBitmap
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.PinRequestPrompt
class PinRequestActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val request = runCatching { getSystemService(LauncherApps::class.java).getPinItemRequest(intent) }.getOrNull()
if (request == null || !request.isValid) {
finish()
return
}
val prompt = when (request.requestType) {
LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT -> request.shortcutInfo?.let { info ->
val appLabel = appLabel(info.`package`)
Triple(info.shortLabel?.toString().orEmpty().ifEmpty { appLabel }, appLabel, HomeApp.shortcutIcon(this, info))
}
LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET -> request.getAppWidgetProviderInfo(this)?.let { info ->
val appLabel = appLabel(info.provider.packageName)
val dpi = resources.displayMetrics.densityDpi
val icon = runCatching { (info.loadPreviewImage(this, dpi) ?: info.loadIcon(this, dpi))?.let(::scaled) }.getOrNull()
Triple(info.loadLabel(packageManager)?.toString().orEmpty().ifEmpty { appLabel }, appLabel, icon)
}
else -> null
}
if (prompt == null) {
finish()
return
}
val (label, appLabel, icon) = prompt
val widget = request.requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET
setContent {
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
PinRequestPrompt(
label = label, appLabel = appLabel, icon = icon, wide = widget,
onAdd = {
if (!widget) {
HomePins.accept(this, request)
finish()
} else if (!HomeWidgets.addPinned(this, request)) finish()
},
onCancel = { finish() },
)
}
}
}
@Suppress("OVERRIDE_DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) {
finish()
return
}
@Suppress("DEPRECATION")
super.onActivityResult(requestCode, resultCode, data)
}
private fun appLabel(packageName: String): String =
runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() }
.getOrDefault(packageName)
private fun scaled(d: android.graphics.drawable.Drawable): Bitmap {
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
val k = minOf(1f, 480f / maxOf(w, h))
return d.toBitmap((w * k).toInt().coerceAtLeast(1), (h * k).toInt().coerceAtLeast(1))
}
}
@@ -20,10 +20,19 @@ internal class ProtonMenu(
private val ui: Handler,
private val idle: () -> Boolean = { true },
) {
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
var protonBusyId by mutableStateOf<String?>(null)
var protonStage by mutableStateOf<String?>(null)
var protonPercent by mutableIntStateOf(-1)
// Install workers and their results outlive the activity that starts them.
private object Operation {
val rows = mutableStateOf<List<ProtonRow>>(emptyList())
val busyId = mutableStateOf<String?>(null)
val stage = mutableStateOf<String?>(null)
val percent = mutableIntStateOf(-1)
val problem = mutableStateOf<String?>(null)
}
var protonRows by Operation.rows
var protonBusyId by Operation.busyId
var protonStage by Operation.stage
var protonPercent by Operation.percent
var protonProblem by Operation.problem
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
@@ -33,6 +42,7 @@ internal class ProtonMenu(
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
ProtonExtras.unqueue(activity, tool)
protonBusyId = id
protonProblem = null
protonStage = activity.getString(R.string.store_starting)
protonPercent = -1
Thread({
@@ -43,6 +53,7 @@ internal class ProtonMenu(
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
ui.post {
protonProblem = problem
protonBusyId = null
protonStage = null
protonPercent = -1
@@ -60,6 +71,7 @@ internal class ProtonMenu(
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return
protonBusyId = id
protonProblem = null
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
protonPercent = -1
Thread({
@@ -98,6 +110,7 @@ internal class ProtonMenu(
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
protonBusyId = ProtonExtras.OWN
protonProblem = null
Thread({
ProtonExtras.tidy(activity)
val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
@@ -9,6 +9,7 @@ import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.database.ContentObserver
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
@@ -67,6 +68,7 @@ import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.input.EvdevKeys
import com.droiddeck.launcher.input.HomeGuideInput
import com.droiddeck.launcher.input.InputSpace
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.ControllerPrefs
@@ -257,6 +259,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false }
private val uiHandler = Handler(Looper.getMainLooper())
private var pendingBackAction: Runnable? = null
private val backQamInput = com.droiddeck.launcher.input.BackQamInput(
setPressed = { padBridge?.setBackQamPressed(it) },
onTap = { performBackAction(double = it) },
doubleTapMs = { backDoubleTapMs.toLong() },
onCancel = { padBridge?.cancelBackQam() },
)
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
private var drawerDirectionDownTime = 0L
private var drawerDirectionDeviceId = -1
@@ -318,8 +326,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
private var drawerControllerActive by mutableStateOf(false)
private var backActionsInverted by mutableStateOf(false)
private var lowLatencyController by mutableStateOf(false)
private var lowLatencyTouch by mutableStateOf(false)
private var backDoubleTapMs by mutableStateOf(500)
private var lowLatency by mutableStateOf(true)
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
private var pcKeyboardOpen by mutableStateOf(false)
private var achievementsInFront by mutableStateOf<AchievementsInFront?>(null)
@@ -426,6 +434,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
// A higher refresh rate allowed in Android's settings does not change the display while this window
// still asks for a lower mode, so the mode is chosen again when the setting changes.
private val refreshSettingObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
override fun onChange(selfChange: Boolean) {
applyOutputPacing()
}
}
private fun followPanelRefresh(displayId: Int) {
if (!CompositorHost.isStarted) return
val output = glassesScreen?.display
@@ -447,6 +463,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onInputDeviceRemoved(deviceId: Int) {
Log.i(TAG, "input device $deviceId disconnected")
backQamInput.onDeviceRemoved(deviceId)
joyConVr?.refresh()
padBridge?.onDeviceRemoved(deviceId)
if (::padMouse.isInitialized) padMouse.reset()
@@ -491,11 +508,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
if (!SessionState.running) {
val prefMode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
SessionState.fpsLimit = SessionPrefs.fpsLimit(this, prefMode)
SessionState.performanceMode = SessionPrefs.performanceMode(this, prefMode)
}
applyOutputPacing()
if (!SessionState.running) SessionState.followScreen = followChoice()
applyFollowOrientation(resources.configuration)
@@ -526,6 +538,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam)
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
padBridge = bridge
bridge.setOnChordInput(backQamInput::onChordInput)
SessionState.padBridge = bridge
if (Build.VERSION.SDK_INT >= 31) {
val vr = com.droiddeck.launcher.input.JoyConVr(this, File(filesDir, ".wayland-rt/${com.droiddeck.launcher.input.JoyConVr.FILE}")) { taken, released ->
@@ -550,12 +563,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
uiHandler.removeCallbacks(cursorHide)
cursorVisible = false
}
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) }
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { controls ->
controls.onTouchMiss = miss@{ event ->
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
event.offsetLocation(controls.left - surfaceView.left.toFloat(), controls.top - surfaceView.top.toFloat())
onTouchEvent(event)
}
root.addView(controls)
}
screenKeysShown = com.droiddeck.launcher.input.ControllerPrefs.screenKeysShown(this)
screenKeys = ScreenKeys(this) { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) }.also { keys ->
keys.onTouchMiss = miss@{ event ->
if (routedTouchMode == SessionPrefs.TOUCH_GESTURES &&
!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat())
onTouchEvent(event)
}
@@ -580,8 +599,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// game surface and on-screen buttons, in either finger-down order.
root.isMotionEventSplittingEnabled = true
surfaceView.setOnTouchListener { _, event ->
if (routedTouchMode != SessionPrefs.TOUCH_GESTURES) {
gestureTouchStreamGate.reset()
if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
false
} else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) {
false
@@ -775,6 +793,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
backQamInput.cancel()
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
cancelTouchGestures()
screenKeys?.stopEditing()
}
@@ -1015,20 +1035,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
padType = id
},
backActionsInverted = backActionsInverted,
backDoubleTapMs = backDoubleTapMs,
onBackDoubleTapMs = { ms ->
SessionPrefs.setBackDoubleTapMs(this@SessionActivity, ms)
backDoubleTapMs = ms
},
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
backActionsInverted = inverted
},
lowLatencyController = lowLatencyController,
lowLatencyTouch = lowLatencyTouch,
onLowLatencyController = { on ->
SessionPrefs.setLowLatencyController(this@SessionActivity, on)
lowLatencyController = on
applyLowLatency()
},
onLowLatencyTouch = { on ->
SessionPrefs.setLowLatencyTouch(this@SessionActivity, on)
lowLatencyTouch = on
lowLatency = lowLatency,
onLowLatency = { on ->
SessionPrefs.setLowLatency(this@SessionActivity, on)
lowLatency = on
applyLowLatency()
},
onOsc = { v ->
@@ -1092,7 +1111,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
pipAutoEnter = on
pip.refresh(true)
},
unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null,
unfoldedControls = unfoldedControls,
onUnfoldedControls = ::chooseUnfoldedControls,
unfoldedControlsWithController = unfoldedControlsWithController,
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
@@ -1299,7 +1318,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
performBackAction(double = false)
}
pendingBackAction = pending
uiHandler.postDelayed(pending, 500L)
uiHandler.postDelayed(pending, backDoubleTapMs.toLong())
}
private fun performBackAction(double: Boolean) {
@@ -1312,7 +1331,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return
incoming.action = null
setIntent(incoming)
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
if (SessionState.suspended) SessionService.resume(this)
else if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
}
@@ -1633,8 +1653,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = SessionPrefs.oscMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
lowLatencyController = SessionPrefs.lowLatencyController(this)
lowLatencyTouch = SessionPrefs.lowLatencyTouch(this)
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
lowLatency = SessionPrefs.lowLatency(this)
padType = SessionPrefs.steamController(this)
}
@@ -1795,9 +1815,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val driverId = if (CompositorHost.isStarted) null else turnip.install()
val previous = SessionState.outputSize
val live = if (SessionState.followScreen && !isInPictureInPictureMode)
com.droiddeck.launcher.session.SessionDisplay.followSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
else null
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
val size = live ?: if (SessionState.running) previous else glassesOutputSize() ?: outputSize()
SessionState.outputSize = size
if (!SessionState.running) SessionState.refreshHz = refreshHz()
@@ -1854,7 +1872,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
)
onOutputAttached(holder)
if (SessionState.running && size != previous) {
Log.i(TAG, "follow screen: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
WaylandCompositor.nativeResizeOutput(size.first, size.second)
}
if (!SessionState.running) SessionEvents.record("compositor.started")
@@ -1886,15 +1904,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cancelTouchGestures()
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
CompositorHost.resize(holder.surface) { applyFrameGen() }
followWindow(width, height)
resizeOutputForWindow(width, height)
}
}
private fun followWindow(width: Int, height: Int) {
if (!SessionState.followScreen || isInPictureInPictureMode || !CompositorHost.isStarted) return
val size = com.droiddeck.launcher.session.SessionDisplay.followSize(width, height) ?: return
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
if (isInPictureInPictureMode || width <= 0 || height <= 0) return null
return if (SessionState.followScreen)
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, controlsBelowWanted())
else if (glassesScreen == null) outputSize() else null
}
private fun resizeOutputForWindow(width: Int, height: Int) {
if (!CompositorHost.isStarted) return
val size = windowOutputSize(width, height) ?: return
if (size == SessionState.outputSize) return
Log.i(TAG, "follow screen: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
SessionState.outputSize = size
val panel = panelBounds()
SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1)
@@ -1908,11 +1933,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun applyFollowOrientation(config: android.content.res.Configuration) {
val wanted = if (SessionState.followScreen && config.smallestScreenWidthDp >= 600) {
android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER
} else {
SessionPrefs.orientation(this)
}
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp)
if (requestedOrientation != wanted) requestedOrientation = wanted
}
@@ -1924,6 +1945,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cancelTouchGestures()
applyFollowOrientation(newConfig)
applyUnfoldedControls()
resizeOutputForWindow(surfaceW, surfaceH)
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
@@ -1965,7 +1987,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
else SessionPrefs.resolutionChoice(this, mode, panel)
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice)
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice,
SessionPrefs.portrait(this) && !controlsBelowWanted())
}
private fun refreshHz(): Float {
@@ -1983,9 +2006,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun mirrorRefreshLimit(): Int =
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
GlassesRendering.fpsLimit(SessionState.fpsLimit, mirrorRefreshLimit()), SessionState.performanceMode,
)
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit())
private fun applyOutputPacing() {
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit()))
@@ -2082,7 +2103,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return
}
Thread({
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile)
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
showEnded(status, hint)
@@ -2112,6 +2133,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun releasePads() {
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
backQamInput.cancel()
padBridge?.releaseAll()
joyConVr?.releaseButtons()
}
@@ -2145,6 +2168,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return EndHint(resources.getQuantityString(R.plurals.session_end_runtime_damaged, broken.size, broken.size, broken.first()), repair = true)
}
private fun prootFailureHint(): EndHint? {
if (SessionState.failureCode != "PROOT_MISSING") return null
val message = SessionState.failureMessage ?: return null
return EndHint(message)
}
private fun sessionEndHint(log: File?): EndHint? {
if (log == null || !log.isFile) return null
return try {
@@ -2181,8 +2210,28 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
val steamVolume =
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!gestureSettingsOpen && !screenKeyTextFocus && window.decorView.hasWindowFocus()
if (steamVolume) {
val audio = getSystemService(android.media.AudioManager::class.java)
if (com.droiddeck.launcher.input.SteamVolumeKeys.dispatch(event, !audio.isVolumeFixed) { direction ->
audio.adjustStreamVolume(android.media.AudioManager.STREAM_MUSIC, direction, 0)
}) return true
}
return super.dispatchKeyEvent(event)
}
}
val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
!SessionState.suspended && padBridge?.canHoldQam() == true
if (backQamInput.onKeyEvent(event, backToQam)) {
pendingBackAction?.let(uiHandler::removeCallbacks)
pendingBackAction = null
return true
}
if (pipUi) return true
if (screenKeyTextFocus) return super.dispatchKeyEvent(event)
@@ -2241,7 +2290,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true
}
val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START ||
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || event.keyCode == KeyEvent.KEYCODE_HOME
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || HomeGuideInput.isHome(event.keyCode)
val resumeKeyId = event.deviceId to event.keyCode
if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) {
if (event.action == KeyEvent.ACTION_DOWN) {
@@ -2312,6 +2361,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (pipUi) return true
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
drawerControllerActive = false
gestureTouchStreamGate.reset()
}
return super.dispatchTouchEvent(event)
}
@@ -2685,21 +2735,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
screenKeys?.refreshAppearance()
}
private fun controlsBelowWanted(): Boolean {
if (!::sessionRoot.isInitialized || glassesScreen != null || cardboard.enabled) return false
return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height,
pipUi || isInPictureInPictureMode)
}
private fun applyUnfoldedControls() {
if (!::sessionRoot.isInitialized) return
val width = sessionRoot.width
val height = sessionRoot.height
val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted(
enabled = unfoldedControls,
foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this),
controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected,
keepWithController = unfoldedControlsWithController,
steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad,
pip = pipUi || isInPictureInPictureMode,
width = width,
height = height,
smallestWidthDp = resources.configuration.smallestScreenWidthDp,
)
val wanted = controlsBelowWanted()
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height)
else FrameLayout.LayoutParams.MATCH_PARENT
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
@@ -2709,13 +2755,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
else "unfolded controls: game full screen")
}
var panel = unfoldedPanel
if (panel != null && panel.deckControls != SessionState.deckPad) {
sessionRoot.removeView(panel)
unfoldedPanel = null
panel = null
}
if (!wanted) {
if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() }
return
}
if (panel == null) {
panel = com.droiddeck.launcher.ui.DeckControlsPanel(this, onClose = { chooseUnfoldedControls(false) },
onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge)
onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge,
portraitDock = !com.droiddeck.launcher.session.SessionDisplay.foldable(this))
sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1)
unfoldedPanel = panel
updateOnScreenControls()
@@ -2960,6 +3012,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
uiHandler.postDelayed({ updateOnScreenControls() }, 700)
}
view.onStyle = { screenKeys?.refreshAppearance() }
view.onTouchMiss = miss@{ event ->
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
event.offsetLocation(view.left - surfaceView.left.toFloat(), view.top - surfaceView.top.toFloat())
onTouchEvent(event)
}
root.addView(view, root.indexOfChild(onScreenControls) + 1)
steamTouchControls = view
steamTouchAvailable = true
@@ -3151,7 +3208,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
super.onPictureInPictureModeChanged(inPip, newConfig)
if (::pip.isInitialized) pip.changed(inPip)
if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH)
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
applyUnfoldedControls()
updateGlassesScreen()
}
@@ -3170,6 +3227,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
started = true
refreshActivityDisplayId()
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) {
contentResolver.registerContentObserver(android.provider.Settings.System.getUriFor(name), false, refreshSettingObserver)
}
refreshSecondScreenDisplays()
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
startedScreens++
@@ -3184,6 +3244,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
started = false
updateHandCamera()
displayManager.unregisterDisplayListener(displayListener)
contentResolver.unregisterContentObserver(refreshSettingObserver)
closeSecondScreen(reset = false)
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
@@ -3239,6 +3300,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onScreenControls?.reload()
controllerSettings = ControllerPrefs.read(this)
resumed = true
com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this,
enabled = {
resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen &&
!achievementsOpen && !gestureSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended &&
SessionState.mode == SessionService.MODE_STEAM && padBridge != null
},
setPressed = { padBridge?.setHomeGuidePressed(it) },
onCancel = { padBridge?.cancelHomeGuide() },
)
updatePointerCapture()
if (!pipUi) sessionClipboard.start()
updatePadMotion()
@@ -3250,7 +3320,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onPause() {
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
if (runtimeRemovalBlocked) { super.onPause(); return }
backQamInput.cancel()
capturePausedFrame()
sessionClipboard.stop()
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
@@ -3625,15 +3697,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun unbufferedSources() =
if (lowLatencyTouch) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES
if (lowLatency) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES
private fun applyLowLatency() {
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatencyController, lowLatencyTouch)
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatency)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) window.decorView.requestUnbufferedDispatch(unbufferedSources())
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
if (!hasFocus) backQamInput.cancel()
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
if (runtimeRemovalBlocked) return
if (!hasFocus) {
@@ -3681,6 +3755,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onDestroy() {
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
backQamInput.cancel()
steamVrRecovery.close()
uiHandler.removeCallbacks(steamTouchRetry)
if (runtimeRemovalBlocked) { super.onDestroy(); return }
@@ -26,6 +26,7 @@ public class PulseAudioComponent extends SessionPart {
private final File workingDir;
private final File deviceControls;
private File logFile;
private final String micFifoPath;
private volatile int pid = -1;
@@ -36,6 +37,8 @@ public class PulseAudioComponent extends SessionPart {
public PulseAudioComponent(Context context, String micFifoPath) {
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
this.deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent.directory(
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context));
this.micFifoPath = micFifoPath;
}
@@ -94,7 +97,7 @@ public class PulseAudioComponent extends SessionPart {
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
+ socket().getAbsolutePath() + "\"");
config.add(".nofail");
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0");
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
config.add("set-default-sink DirectAudio");
config.add(".fail");
if (micFifoPath != null && !micFifoPath.isEmpty()) {
@@ -139,7 +142,7 @@ public class PulseAudioComponent extends SessionPart {
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
} else {
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "AAudioSink") != null;
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
@@ -1,11 +1,32 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.content.pm.ActivityInfo
import com.droiddeck.launcher.R
object AppUiPrefs {
const val DEFAULT_SCALE = 100
val scales = listOf(75, 85, 100, 115, 125, 150)
val orientationOptions = listOf(
ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto,
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait,
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse,
)
fun orientation(context: Context): Int =
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE)
.getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_USER)
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_USER
fun setOrientation(context: Context, value: Int) {
require(orientationOptions.any { it.first == value })
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply()
}
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
fun scale(context: Context): Int = normalizeScale(
@@ -261,6 +261,8 @@ object DeviceReport {
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
k("Guest host name", SessionPrefs.guestHostname(context))
k("DirectAudio for games", SessionPrefs.directAudio(context))
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
@@ -0,0 +1,24 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.net.Uri
import android.provider.Settings
object GlobalSettings {
// Settings.Global caches values in-process and misses deletions made over adb; ask the provider directly.
fun read(context: Context, name: String): String? {
val uri = Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
context.contentResolver.query(uri, arrayOf(Settings.NameValueTable.VALUE), null, null, null)?.use { cursor ->
return if (cursor.moveToFirst()) cursor.getString(0) else null
}
return Settings.Global.getString(context.contentResolver, name)
}
fun isOn(context: Context, name: String): Boolean =
runCatching { read(context, name)?.trim() == "1" }.getOrDefault(false)
fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED)
// Settings.Global.ADB_WIFI_ENABLED is hidden; the key is stable since Android 11.
fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled")
}
@@ -60,14 +60,14 @@ object PhantomProcessLimit {
if (usesDeviceConfig(sdk)) {
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
val global = try {
Settings.Global.getString(context.contentResolver, SETTING)
GlobalSettings.read(context, SETTING)
} catch (_: Exception) {
null
}
return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY))
}
val global = try {
Settings.Global.getString(context.contentResolver, SETTING)
GlobalSettings.read(context, SETTING)
} catch (_: Exception) {
return PhantomProcessStatus.UNREADABLE
}
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.core
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.view.accessibility.AccessibilityManager
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.input.HomeButtonService
import com.droiddeck.launcher.session.SessionPrefs
object SteamIntegration {
const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION"
const val EXTRA_FEATURE = "integration_feature"
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
data class State(
val wifi: Boolean = false,
val locationPermission: Boolean = false,
val locationOn: Boolean = false,
val locationBlocked: Boolean = false,
val brightness: Boolean = false,
val home: Boolean = false,
val shortcuts: Boolean = false,
val shortcutsRestricted: Boolean = false,
val shortcutsTried: Boolean = false,
val suggested: Boolean = true,
)
fun read(context: Context) = State(
wifi = SessionPrefs.wifiDiscoveryEnabled(context),
locationPermission = WifiDiscovery.permissionGranted(context),
locationOn = WifiDiscovery.locationEnabled(context),
brightness = Settings.System.canWrite(context),
home = HomeApp.isDefault(context),
shortcuts = context.getSystemService(AccessibilityManager::class.java)
.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any {
val service = it.resolveInfo.serviceInfo
ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java)
},
shortcutsRestricted = restrictedSettings(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
)
// Android 13+ blocks accessibility services for sideloaded APKs until the user allows restricted settings in App info.
// MODE_DEFAULT is inconclusive on Android 15, so only an explicit denial counts here.
private fun restrictedSettings(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
val mode = runCatching {
context.getSystemService(android.app.AppOpsManager::class.java)
.unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName)
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
}
fun dismissSuggestion(context: Context) {
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
}
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
Uri.parse("package:${context.packageName}"))
// ACCESSIBILITY_DETAILS_SETTINGS is restricted to system apps; the fragment args key highlights our entry in the list.
fun shortcutSettings(context: Context): Intent {
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
.putExtra(":settings:fragment_args_key", service)
.putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) })
}
}
@@ -184,12 +184,15 @@ class WirelessAdbPairingService : Service() {
setSound(null, null)
enableVibration(false)
})
manager?.createNotificationChannel(NotificationChannel(PROGRESS_CHANNEL_ID, getString(R.string.adbpair_progress_channel_name),
NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })
val open = PendingIntent.getActivity(this, 0,
Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE)
val cancel = PendingIntent.getService(this, 1,
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
val builder = Notification.Builder(this, CHANNEL_ID)
val quiet = stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working
val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentIntent(open)
.setShowWhen(false)
@@ -239,6 +242,7 @@ class WirelessAdbPairingService : Service() {
companion object {
private const val CHANNEL_ID = "wireless-adb-pairing"
private const val PROGRESS_CHANNEL_ID = "wireless-adb-pairing-progress"
private const val NOTIFICATION_ID = 3
private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.files
import androidx.compose.foundation.shape.CircleShape
import com.droiddeck.launcher.ui.focusGlide
import android.content.res.Configuration
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.background
@@ -181,14 +183,14 @@ fun CollapsibleRail(
modifier = Modifier.weight(1f),
)
if (!state.portraitLocked) {
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp)) {
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp).focusGlide(CircleShape)) {
Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
}
}
}
}
if (collapsed && !state.portraitLocked) {
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp)) {
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp).focusGlide(CircleShape)) {
Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
}
}
@@ -197,14 +199,14 @@ fun CollapsibleRail(
if (collapsed) {
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
links.forEach { link ->
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp)) {
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp).focusGlide(CircleShape)) {
Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
}
}
}
} else {
links.forEach { link ->
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) {
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp).focusGlide(CircleShape)) {
Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp))
Spacer(Modifier.width(6.dp))
Text(link.label, fontSize = 12.sp)
@@ -250,11 +252,11 @@ fun CollapsibleRail(
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
shape,
)
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
.padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp)
} else {
base
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
.padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp)
}
@@ -361,6 +363,7 @@ private fun TopTabCell(
modifier = modifier
.clip(RoundedCornerShape(9.dp))
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
.focusGlide(RoundedCornerShape(9.dp))
.then(
if (isTab) {
Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick)
@@ -21,7 +21,7 @@ class FileManagerActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
}
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.files
import androidx.compose.foundation.shape.CircleShape
import com.droiddeck.launcher.ui.focusGlide
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
@@ -39,7 +41,7 @@ import androidx.compose.material.icons.filled.Storage
import androidx.compose.material.icons.filled.Image
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -105,12 +107,14 @@ private fun FileContextMenuItems(
text = { Text(stringResource(R.string.fm_select)) },
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onSelect() },
modifier = Modifier.focusGlide(),
)
MenuItemDivider()
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_properties)) },
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onProperties() },
modifier = Modifier.focusGlide(),
)
MenuItemDivider()
if (isDir) {
@@ -124,6 +128,7 @@ private fun FileContextMenuItems(
)
},
onClick = { onToggleFavorite() },
modifier = Modifier.focusGlide(),
)
MenuItemDivider()
}
@@ -131,24 +136,28 @@ private fun FileContextMenuItems(
text = { Text(stringResource(R.string.fm_rename)) },
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onRename() },
modifier = Modifier.focusGlide(),
)
MenuItemDivider()
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_copy)) },
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onCopy() },
modifier = Modifier.focusGlide(),
)
MenuItemDivider()
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_cut)) },
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onCut() },
modifier = Modifier.focusGlide(),
)
MenuItemDivider()
DropdownMenuItem(
text = { Text(stringResource(R.string.common_delete)) },
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onDelete() },
modifier = Modifier.focusGlide(),
)
}
@@ -193,7 +202,7 @@ internal fun FileItemRow(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
@@ -212,7 +221,7 @@ internal fun FileItemRow(
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
) {
if (selectionMode) {
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() })
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() }, modifier = Modifier.focusGlide())
Spacer(Modifier.width(4.dp))
}
when {
@@ -270,7 +279,7 @@ internal fun FileItemRow(
)
}
if (showActions) Box {
IconButton(onClick = onMenu) {
IconButton(onClick = onMenu, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.MoreVert, stringResource(R.string.fm_actions), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
}
DropdownMenu(
@@ -302,7 +311,7 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
@@ -370,6 +379,7 @@ internal fun FavoritesList(
TextButton(
onClick = onPinCurrent,
enabled = !currentAlreadyPinned,
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(6.dp))
@@ -422,7 +432,7 @@ private fun FavoriteCard(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
@@ -480,7 +490,7 @@ private fun FavoriteCard(
overflow = TextOverflow.Ellipsis,
)
}
IconButton(onClick = onUnpin) {
IconButton(onClick = onUnpin, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
Icons.Filled.Star,
contentDescription = stringResource(R.string.fm_unpin_favorite),
@@ -526,7 +536,7 @@ internal fun FileGridTile(
Card(
modifier = Modifier
.padding(4.dp)
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
@@ -570,7 +580,7 @@ internal fun FileGridTile(
androidx.compose.material3.Checkbox(
checked = selected,
onCheckedChange = { onToggleSelect() },
modifier = Modifier.align(Alignment.TopStart),
modifier = Modifier.align(Alignment.TopStart).focusGlide(),
)
}
}
@@ -1,9 +1,13 @@
package com.droiddeck.launcher.files
import androidx.compose.foundation.shape.CircleShape
import com.droiddeck.launcher.ui.focusGlide
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.rememberScrollState
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -19,6 +23,7 @@ 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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.grid.GridCells
@@ -50,7 +55,7 @@ import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.SportsEsports
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
@@ -318,10 +323,10 @@ fun FileManagerScreen(
navigate(action)
}
}
}) { Text(stringResource(R.string.fm_accept)) }
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_accept)) }
},
dismissButton = {
TextButton(onClick = { pendingNavigation = null }) {
TextButton(onClick = { pendingNavigation = null }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.fm_decline))
}
},
@@ -509,15 +514,16 @@ fun FileManagerScreen(
onValueChange = { folderName = it },
label = { Text(stringResource(R.string.fm_folder_name)) },
singleLine = true,
modifier = Modifier.focusGlide(),
)
},
confirmButton = {
TextButton(onClick = {
showNewFolderDialog = false
if (folderName.isNotBlank()) createFolder(currentDir, folderName)
}) { Text(stringResource(R.string.fm_create)) }
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_create)) }
},
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text(stringResource(R.string.common_cancel)) } },
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@@ -532,6 +538,7 @@ fun FileManagerScreen(
onValueChange = { newName = it },
label = { Text(stringResource(R.string.fm_new_name)) },
singleLine = true,
modifier = Modifier.focusGlide(),
)
},
confirmButton = {
@@ -539,9 +546,9 @@ fun FileManagerScreen(
val file = renameTarget
renameTarget = null
if (file != null && newName.isNotBlank()) performRename(file, newName)
}) { Text(stringResource(R.string.fm_rename)) }
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_rename)) }
},
dismissButton = { TextButton(onClick = { renameTarget = null }) { Text(stringResource(R.string.common_cancel)) } },
dismissButton = { TextButton(onClick = { renameTarget = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@@ -563,9 +570,9 @@ fun FileManagerScreen(
TextButton(onClick = {
selectedEntry = null
performDelete(file)
}) { Text(stringResource(R.string.common_delete)) }
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) }
},
dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text(stringResource(R.string.common_cancel)) } },
dismissButton = { TextButton(onClick = { selectedEntry = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@@ -611,9 +618,9 @@ fun FileManagerScreen(
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show()
}
}
}) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
},
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text(stringResource(R.string.common_cancel)) } },
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@@ -636,6 +643,7 @@ fun FileManagerScreen(
androidx.compose.material3.Checkbox(
checked = conflictApplyToAll,
onCheckedChange = { conflictApplyToAll = it },
modifier = Modifier.focusGlide(),
)
Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp)
}
@@ -648,7 +656,7 @@ fun FileManagerScreen(
ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip),
).forEach { (choice, label) ->
TextButton(
modifier = Modifier.fillMaxWidth(),
modifier = Modifier.fillMaxWidth().focusGlide(CircleShape),
onClick = { conflictChoice = choice; pendingConflict = null },
) { Text(label, modifier = Modifier.fillMaxWidth()) }
}
@@ -656,13 +664,14 @@ fun FileManagerScreen(
},
confirmButton = {},
dismissButton = {
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) {
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.common_cancel))
}
},
)
}
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
Column(modifier = Modifier.fillMaxSize()) {
if (pickMode && !pickerTitle.isNullOrEmpty()) {
Text(
@@ -681,7 +690,7 @@ fun FileManagerScreen(
onClick = { onPick?.invoke(currentDir) },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
.padding(horizontal = 16.dp, vertical = 8.dp).focusGlide(CircleShape),
) {
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
@@ -693,9 +702,10 @@ fun FileManagerScreen(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainer)
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
}
@@ -744,6 +754,7 @@ fun FileManagerScreen(
).show()
}
},
modifier = Modifier.focusGlide(),
)
}
linuxRoot?.let { root ->
@@ -754,6 +765,7 @@ fun FileManagerScreen(
Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
},
onClick = { showDriveMenu = false; openDrive(root) },
modifier = Modifier.focusGlide(),
)
}
}
@@ -769,10 +781,10 @@ fun FileManagerScreen(
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
Spacer(Modifier.weight(1f))
if (!compactToolbar) Spacer(Modifier.weight(1f))
} else {
Text(
text = currentDir.name.ifBlank { currentDir.absolutePath },
@@ -781,12 +793,12 @@ fun FileManagerScreen(
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
}
if (launchDir != null) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
}
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
@@ -798,7 +810,7 @@ fun FileManagerScreen(
onClick = { showNewFolderDialog = true },
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
modifier = Modifier.height(32.dp),
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
) {
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(5.dp))
@@ -808,18 +820,18 @@ fun FileManagerScreen(
IconButton(onClick = {
gridView = !gridView
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
}) {
}, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) {
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
Box {
IconButton(onClick = { showSortMenu = true }) {
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
@@ -836,6 +848,7 @@ fun FileManagerScreen(
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
@@ -846,6 +859,7 @@ fun FileManagerScreen(
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
showSortMenu = false
},
modifier = Modifier.focusGlide(),
)
DropdownMenuItem(
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
@@ -855,12 +869,13 @@ fun FileManagerScreen(
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
}
}
IconButton(onClick = { showFavorites = !showFavorites }) {
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
if (showFavorites) {
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
} else {
@@ -868,7 +883,7 @@ fun FileManagerScreen(
}
}
if (!pickMode && onExit != null) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@@ -880,7 +895,7 @@ fun FileManagerScreen(
onValueChange = { searchQuery = it },
singleLine = true,
placeholder = { Text(stringResource(R.string.fm_filter_folder), fontSize = 13.sp) },
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).focusGlide(),
)
}
@@ -918,13 +933,14 @@ fun FileManagerScreen(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f))
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
.padding(horizontal = 12.dp, vertical = 6.dp),
) {
Text(
stringResource(R.string.fm_selected_count, selectedPaths.size),
color = MaterialTheme.colorScheme.onBackground,
fontSize = 13.sp,
modifier = Modifier.weight(1f),
modifier = if (compactToolbar) Modifier.padding(end = 12.dp) else Modifier.weight(1f),
)
val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths }
val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths }
@@ -935,6 +951,7 @@ fun FileManagerScreen(
selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown
},
contentPadding = selBarPadding,
modifier = Modifier.focusGlide(CircleShape),
) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) }
Spacer(Modifier.width(4.dp))
OutlinedButton(
@@ -946,6 +963,7 @@ fun FileManagerScreen(
selectedPaths = emptySet()
},
contentPadding = selBarPadding,
modifier = Modifier.focusGlide(CircleShape),
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) }
Spacer(Modifier.width(4.dp))
OutlinedButton(
@@ -957,6 +975,7 @@ fun FileManagerScreen(
selectedPaths = emptySet()
},
contentPadding = selBarPadding,
modifier = Modifier.focusGlide(CircleShape),
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) }
Spacer(Modifier.width(4.dp))
OutlinedButton(
@@ -964,11 +983,13 @@ fun FileManagerScreen(
onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } },
contentPadding = selBarPadding,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
modifier = Modifier.focusGlide(CircleShape),
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
Spacer(Modifier.width(4.dp))
OutlinedButton(
onClick = { selectionMode = false; selectedPaths = emptySet() },
contentPadding = selBarPadding,
modifier = Modifier.focusGlide(CircleShape),
) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) }
}
}
@@ -990,7 +1011,7 @@ fun FileManagerScreen(
if (isCutOperation) stringResource(R.string.fm_paste_move_here, what) else stringResource(R.string.fm_paste_here, what),
color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f),
)
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) {
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
}
}
@@ -1021,7 +1042,7 @@ fun FileManagerScreen(
isOperationRunning = false
operationDeterminate = false
loadDirectory(currentDir, resetScroll = false)
}) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
}
}
Spacer(Modifier.height(4.dp))
@@ -25,7 +25,7 @@ class FilePickerActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
}
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.files
import androidx.compose.foundation.shape.CircleShape
import com.droiddeck.launcher.ui.focusGlide
import android.widget.Toast
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
@@ -128,7 +130,7 @@ internal fun FilePropertiesDialog(
)
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.fm_done)) } },
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_done)) } },
)
}
@@ -182,6 +184,7 @@ private fun AttributeToggleRow(
checked = checked,
enabled = enabled,
onCheckedChange = onToggle,
modifier = Modifier.focusGlide(),
)
}
}
@@ -1,7 +1,7 @@
package com.droiddeck.launcher.files
import androidx.compose.foundation.border
import androidx.compose.material3.AlertDialog
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
import androidx.compose.material3.AlertDialogDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
@@ -32,12 +32,6 @@ internal object GlassesRendering {
return if (hz == 30 && kotlin.math.abs(state.hz - 30f) >= 0.5f) 60 else hz
}
fun fpsLimit(requested: Int, mirrorRefreshLimit: Int): Int = when {
mirrorRefreshLimit <= 0 -> requested
requested <= 0 -> mirrorRefreshLimit
else -> minOf(requested, mirrorRefreshLimit)
}
fun usesGlasses(state: GlassesState, outputActive: Boolean, steamVrRunning: Boolean): Boolean =
outputActive || (steamVrRunning && state.usable)
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.input
import android.view.KeyEvent
import android.os.Handler
import android.os.Looper
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit,
private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {}) {
private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false)
private val handler = Handler(Looper.getMainLooper())
private val presses = mutableMapOf<Int, Press>()
private val cancelled = mutableSetOf<Int>()
private var tapPending = false
private val singleTap = Runnable { tapPending = false; onTap(false) }
private fun cancelTap() {
handler.removeCallbacks(singleTap)
tapPending = false
}
fun onChordInput() {
if (presses.isEmpty()) return
val alreadyHeld = presses.values.any { it.held }
presses.values.forEach {
handler.removeCallbacks(it.hold)
it.held = true
it.used = true
}
cancelTap()
if (!alreadyHeld) setPressed(true)
}
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
if (!enabled) cancel()
if (event.keyCode != KeyEvent.KEYCODE_BACK) return false
val device = event.deviceId
return when (event.action) {
KeyEvent.ACTION_DOWN -> {
if (event.repeatCount > 0) return enabled || device in presses || device in cancelled
cancelled.remove(device)
if (!enabled || event.isCanceled) return false
if (device in presses) return true
handler.removeCallbacks(singleTap)
val hold = Runnable {
val press = presses[device] ?: return@Runnable
val alreadyHeld = presses.values.any { it.held }
press.held = true
presses.values.forEach { it.used = true }
cancelTap()
if (!alreadyHeld) setPressed(true)
}
presses[device] = Press(hold, used = presses.values.any { it.held })
handler.postDelayed(hold, 700)
true
}
KeyEvent.ACTION_UP -> {
val press = presses.remove(device)
val wasCancelled = cancelled.remove(device)
if (press != null) {
handler.removeCallbacks(press.hold)
if (press.held && presses.values.none { it.held }) setPressed(false)
if (!press.used && !event.isCanceled) {
if (tapPending) { cancelTap(); onTap(true) }
else { tapPending = true; handler.postDelayed(singleTap, doubleTapMs()) }
} else if (event.isCanceled) cancelTap()
}
press != null || wasCancelled || enabled
}
else -> device in presses || device in cancelled
}
}
fun cancel() {
cancelTap()
val wasHeld = presses.values.any { it.held }
presses.values.forEach { handler.removeCallbacks(it.hold) }
cancelled.addAll(presses.keys)
presses.clear()
onCancel()
if (wasHeld) setPressed(false)
}
fun onDeviceRemoved(device: Int) {
cancelled.remove(device)
val press = presses.remove(device) ?: return
handler.removeCallbacks(press.hold)
cancelTap()
if (press.held && presses.values.none { it.held }) {
onCancel()
setPressed(false)
}
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.ui.focusGlide
import android.os.Build
import android.os.Bundle
import android.view.Gravity
@@ -104,6 +105,7 @@ class ControllerEditorActivity : ComponentActivity() {
else -> Color.White.copy(alpha = 0.06f)
},
)
.focusGlide(RoundedCornerShape(50))
.then(
if (selected == null) Modifier.clickable(onClick = onClick)
else Modifier.toggleable(value = selected, role = Role.Switch, onValueChange = { onClick() }),
@@ -525,8 +525,8 @@ public class FakeInputWriter {
}
}
public static void setLowLatency(boolean controller, boolean touch) {
int flags = (controller ? LATENCY_CONTROLLER : 0) | (touch ? LATENCY_TOUCH : 0);
public static void setLowLatency(boolean enabled) {
int flags = enabled ? LATENCY_CONTROLLER | LATENCY_TOUCH : 0;
latency = flags;
RingSlot ringSlot;
synchronized (RING_LOCK) {
@@ -4,7 +4,7 @@ import android.view.MotionEvent
/** Keeps split Android touch targets from restarting one shared gesture recognizer. */
internal class GestureTouchStreamGate {
enum class Source { SURFACE, SCREEN_KEYS }
enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS }
private var owner: Source? = null
@@ -0,0 +1,71 @@
package com.droiddeck.launcher.input
import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.content.Intent
import android.hardware.input.InputManager
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.view.accessibility.AccessibilityEvent
import com.droiddeck.launcher.HomeApp
object HomeButtonShortcuts {
private var owner: Any? = null
private var enabled: () -> Boolean = { false }
private var setPressed: (Boolean) -> Unit = {}
private var onCancel: () -> Unit = {}
private val input = HomeGuideInput({ setPressed(it) }, { onCancel() })
fun attach(owner: Any, enabled: () -> Boolean, setPressed: (Boolean) -> Unit, onCancel: () -> Unit) {
input.cancel()
this.owner = owner
this.enabled = enabled
this.setPressed = setPressed
this.onCancel = onCancel
}
fun cancel(owner: Any) { if (this.owner === owner) input.cancel() }
fun detach(owner: Any) {
if (this.owner !== owner) return
input.cancel()
this.owner = null
enabled = { false }
setPressed = {}
onCancel = {}
}
fun onKeyEvent(context: Context, event: KeyEvent): Boolean {
// AYN maps its system-assistant key (gpio-keys KEY_F24) to HOME too; only the pad's Home is Guide.
if (!HomeGuideInput.isHome(event.keyCode) || !PadBridge.isControllerKeyEvent(event)) return false
return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context))
}
fun release() = input.cancel()
fun onDeviceRemoved(device: Int) = input.onDeviceRemoved(device)
}
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
override fun onServiceConnected() {
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
}
override fun onKeyEvent(event: KeyEvent) = HomeButtonShortcuts.onKeyEvent(this, event)
override fun onAccessibilityEvent(event: AccessibilityEvent?) {}
override fun onInterrupt() { HomeButtonShortcuts.release() }
override fun onInputDeviceAdded(deviceId: Int) {}
override fun onInputDeviceChanged(deviceId: Int) {}
override fun onInputDeviceRemoved(deviceId: Int) { HomeButtonShortcuts.onDeviceRemoved(deviceId) }
override fun onUnbind(intent: Intent?): Boolean {
HomeButtonShortcuts.release()
return super.onUnbind(intent)
}
override fun onDestroy() {
HomeButtonShortcuts.release()
getSystemService(InputManager::class.java).unregisterInputDeviceListener(this)
super.onDestroy()
}
}
@@ -0,0 +1,47 @@
package com.droiddeck.launcher.input
import android.view.KeyEvent
class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCancel: () -> Unit = {}) {
private val presses = mutableSetOf<Int>()
private val cancelled = mutableSetOf<Int>()
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
if (!isHome(event.keyCode)) return false
if (!enabled) cancel()
val device = event.deviceId
return when (event.action) {
KeyEvent.ACTION_DOWN -> {
if (event.repeatCount > 0) return device in presses || device in cancelled
cancelled.remove(device)
if (!enabled || event.isCanceled) return false
if (presses.add(device) && presses.size == 1) setPressed(true)
true
}
KeyEvent.ACTION_UP -> {
val owned = presses.remove(device)
val wasCancelled = cancelled.remove(device)
if (owned && presses.isEmpty()) setPressed(false)
owned || wasCancelled
}
else -> device in presses || device in cancelled
}
}
fun cancel() {
val held = presses.isNotEmpty()
cancelled.addAll(presses)
presses.clear()
if (held) { onCancel(); setPressed(false) }
}
fun onDeviceRemoved(device: Int) {
cancelled.remove(device)
if (presses.remove(device) && presses.isEmpty()) { onCancel(); setPressed(false) }
}
companion object {
// The Retroid Nova pad falls back to Generic.kl, which maps its Home scan code to MOVE_HOME.
fun isHome(keyCode: Int) = keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_HOME
}
}
@@ -96,6 +96,8 @@ class OnScreenControls(
private var quickHidden = false
private var quickPressedBy = -1
private var keyboardPressedBy = -1
private var forwardedPointerBits = 0
var onTouchMiss: ((MotionEvent) -> Unit)? = null
private var settings = ControllerPrefs.read(context)
private var snap = settings.snap
private var safe = Rect()
@@ -515,6 +517,9 @@ class OnScreenControls(
val index = event.actionIndex
val x = event.getX(index)
val y = event.getY(index)
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
if (event.actionMasked == MotionEvent.ACTION_POINTER_DOWN && forwardMiss(event, x, y)) return true
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
if (event.actionMasked == MotionEvent.ACTION_DOWN && keyboardContains(x, y)) {
keyboardPressedBy = event.getPointerId(index)
invalidate()
@@ -542,11 +547,13 @@ class OnScreenControls(
return true
}
MotionEvent.ACTION_MOVE -> {
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
if (keyboardPressedBy != -1) return true
if (quickPressedBy != -1) return true
var changed = false
for (index in 0 until event.pointerCount) {
val pointer = event.getPointerId(index)
if (forwardedPointerBits and (1 shl pointer) != 0) continue
val x = event.getX(index)
val y = event.getY(index)
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
@@ -568,10 +575,16 @@ class OnScreenControls(
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
val pointer = event.getPointerId(event.actionIndex)
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
if (event.actionMasked == MotionEvent.ACTION_CANCEL) {
forwardedPointerBits = 0
releaseAll()
return true
}
if (forwardedPointerBits and (1 shl pointer) != 0) {
forwardedPointerBits = forwardedPointerBits and (1 shl pointer).inv()
return true
}
if (keyboardPressedBy == pointer) {
val tapped = event.actionMasked == MotionEvent.ACTION_UP && keyboardContains(event.x, event.y)
keyboardPressedBy = -1
@@ -604,6 +617,23 @@ class OnScreenControls(
return false
}
private fun forwardMiss(event: MotionEvent, x: Float, y: Float): Boolean {
if (onTouchMiss == null || keyboardPressedBy != -1 || quickPressedBy != -1) return false
if (!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null) return false
forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(event.actionIndex))
forwardPointers(event, forwardedPointerBits)
return true
}
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
val split = event.pointerSubset(pointerIdBits) ?: return
try {
onTouchMiss?.invoke(split)
} finally {
split.recycle()
}
}
private fun onEditTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
@@ -53,6 +53,7 @@ public final class PadBridge {
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS];
private final PadState effectiveState = new PadState();
private final PadState homeGuideReport = new PadState();
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private boolean open;
private volatile boolean selectSteam;
@@ -61,12 +62,21 @@ public final class PadBridge {
private final PadState routedTouch = new PadState();
private boolean systemGuidePressed;
private boolean systemQamPressed;
private boolean backQamPressed;
private boolean homeGuidePressed;
private int homeGuideSlot = -1;
private final PadState lastBackQamReport = new PadState();
private final PadState lastWrittenReport = new PadState();
private boolean backQamAxesBlocked;
private final java.util.Set<Runnable> backQamWrites = new java.util.HashSet<>();
private long backQamDelayMs, backQamWriteAt;
private boolean qamChordActive;
private int chordButton = -1;
private boolean chordButtonPressed;
private boolean qamTapPressed;
private int qamChordGeneration;
private volatile Runnable onPlayerInput;
private Runnable onChordInput;
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private static final long STATS_WINDOW_MS = 10_000;
@@ -129,9 +139,12 @@ public final class PadBridge {
}
private void resetBuiltin() {
homeGuidePressed = false;
clearBackQamWrites();
routedTouch.clear();
systemGuidePressed = false;
systemQamPressed = false;
backQamPressed = false;
qamTapPressed = false;
qamChordActive = false;
chordButtonPressed = false;
@@ -150,6 +163,9 @@ public final class PadBridge {
}
public synchronized void stop() {
homeGuidePressed = false;
homeGuideSlot = -1;
clearBackQamWrites();
releaseBackPaddles();
activeControllerId = NO_CONTROLLER;
for (int slot = 0; slot < SLOTS; slot++) {
@@ -165,6 +181,7 @@ public final class PadBridge {
}
systemGuidePressed = false;
systemQamPressed = false;
backQamPressed = false;
qamChordActive = false;
chordButtonPressed = false;
qamTapPressed = false;
@@ -215,6 +232,7 @@ public final class PadBridge {
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_MOVE_HOME:
if (!isFromController(device)) return false;
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|| device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC
@@ -273,6 +291,14 @@ public final class PadBridge {
onPlayerInput = listener;
}
public synchronized void setOnChordInput(Runnable listener) {
onChordInput = listener;
}
private void noteChordInput(int slot) {
if (slot == 0 && onChordInput != null) onChordInput.run();
}
private void notePlayerInput() {
Runnable listener = onPlayerInput;
if (listener == null || !playerInputPosted.compareAndSet(false, true)) return;
@@ -307,7 +333,8 @@ public final class PadBridge {
case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.press(9, pressed); break;
case KeyEvent.KEYCODE_BUTTON_MODE:
case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_MOVE_HOME: pad.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Z:
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed);
break;
@@ -323,6 +350,7 @@ public final class PadBridge {
default: return false;
}
noteDevice(event.getDevice(), slot);
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
if (pressed) notePlayerInput();
statButtons++;
scheduleStats();
@@ -352,6 +380,7 @@ public final class PadBridge {
pad.rightX = x;
pad.rightY = y;
}
if (x != 0f || y != 0f) noteChordInput(slot);
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
publish(slot);
return true;
@@ -382,6 +411,8 @@ public final class PadBridge {
pad.up = hatY < -0.5f;
pad.down = hatY > 0.5f;
}
if (pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|| lt > 0f || rt > 0f || pad.up || pad.right || pad.down || pad.left) noteChordInput(slot);
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
notePlayerInput();
@@ -458,7 +489,11 @@ public final class PadBridge {
}
public synchronized void releaseAll() {
homeGuidePressed = false;
homeGuideSlot = -1;
clearBackQamWrites();
routedTouch.clear();
backQamPressed = false;
releaseBackPaddles();
state.clear();
publish();
@@ -479,6 +514,146 @@ public final class PadBridge {
return SessionState.getDeckPad() && FakeInputWriter.padHasQam();
}
public boolean canHoldQam() {
return builtinPad && nativeQam();
}
public synchronized void setHomeGuidePressed(boolean pressed) {
int slot = pressed ? firstPlayerSlot() : homeGuideSlot;
if (slot > 0) {
homeGuideSlot = pressed ? slot : -1;
publish(slot);
return;
}
if (homeGuidePressed == pressed) return;
homeGuidePressed = pressed;
updateHeldModifier(PadState.GUIDE, pressed);
}
public synchronized void cancelHomeGuide() {
int slot = homeGuideSlot;
if (slot > 0) {
homeGuideSlot = -1;
publish(slot);
}
if (!homeGuidePressed) return;
clearBackQamWrites();
homeGuidePressed = false;
state.clear();
publish();
}
public synchronized void setBackQamPressed(boolean pressed) {
if (pressed && !canHoldQam()) return;
if (backQamPressed == pressed) return;
backQamPressed = pressed;
updateHeldModifier(PadState.QAM, pressed);
}
private void updateHeldModifier(int button, boolean pressed) {
if (pressed && (open || start())) {
backQamAxesBlocked = false;
long now = android.os.SystemClock.uptimeMillis();
long modifierAt = Math.max(now, backQamWriteAt);
backQamDelayMs = modifierAt - now + QAM_GUIDE_LEAD_MIN_MS;
PadState modifier = new PadState();
modifier.copyFrom(lastBackQamReport);
modifier.press(button, true);
writeBackQamReport(modifier, modifierAt);
}
if (!pressed && !backQamPressed && !homeGuidePressed) {
backQamAxesBlocked = hasAxes(state);
if (!backQamWrites.isEmpty()) {
PadState neutral = new PadState();
neutral.copyFrom(lastWrittenReport);
clearAxes(neutral);
writer.writePad(neutral);
lastWrittenReport.copyFrom(neutral);
}
}
publish();
}
public synchronized void cancelBackQam() {
if (!backQamPressed && backQamWrites.isEmpty()) return;
clearBackQamWrites();
backQamPressed = false;
state.clear();
publish();
}
private void clearBackQamWrites() {
for (Runnable pending : backQamWrites) mainHandler.removeCallbacks(pending);
backQamWrites.clear();
backQamDelayMs = backQamWriteAt = 0;
lastBackQamReport.clear();
lastWrittenReport.clear();
backQamAxesBlocked = false;
}
private void writeBackQamReport(PadState report, long at) {
lastBackQamReport.copyFrom(report);
if (backQamWrites.isEmpty() && at <= android.os.SystemClock.uptimeMillis()) {
writeReport(report, false);
return;
}
PadState queued = new PadState();
queued.copyFrom(report);
Runnable pending = new Runnable() {
@Override public void run() {
synchronized (PadBridge.this) {
if (!backQamWrites.remove(this)) return;
writeReport(queued, true);
if (backQamWrites.isEmpty() && !hasButtons(lastBackQamReport)) backQamDelayMs = 0;
}
}
};
backQamWrites.add(pending);
backQamWriteAt = at;
mainHandler.postAtTime(pending, at);
}
private void writePad(PadState report) {
if (backQamAxesBlocked && !hasAxes(state)) backQamAxesBlocked = false;
long at = android.os.SystemClock.uptimeMillis();
// Steam must see the modifier before a partner; preserve quick press/release pairs in order.
if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
writeBackQamReport(report, at);
}
private static boolean hasAxes(PadState pad) {
return pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|| pad.leftTrigger != 0f || pad.rightTrigger != 0f;
}
private static void clearAxes(PadState pad) {
pad.leftX = pad.leftY = pad.rightX = pad.rightY = pad.leftTrigger = pad.rightTrigger = 0f;
}
private static boolean hasButtons(PadState pad) {
for (int i = 0; i < 10; i++) if (pad.isDown(i)) return true;
return pad.isDown(PadState.GUIDE) || pad.up || pad.right || pad.down || pad.left;
}
private void writeReport(PadState report, boolean queued) {
if (!queued && !backQamAxesBlocked) {
lastWrittenReport.copyFrom(report);
writer.writePad(report);
return;
}
PadState live = new PadState();
live.copyFrom(report);
if (queued) {
live.leftX = state.leftX; live.leftY = state.leftY;
live.rightX = state.rightX; live.rightY = state.rightY;
live.leftTrigger = state.leftTrigger; live.rightTrigger = state.rightTrigger;
}
boolean held = (backQamPressed && report.isDown(PadState.QAM)) || (homeGuidePressed && report.isDown(PadState.GUIDE));
if ((queued && !held) || backQamAxesBlocked) clearAxes(live);
lastWrittenReport.copyFrom(live);
writer.writePad(live);
}
public synchronized void triggerQam() {
if (!builtinPad) return;
if (!nativeQam()) {
@@ -557,7 +732,9 @@ public final class PadBridge {
slotJoyCons.set(slot * 2 + side, id);
slotJoyCons.set(slot * 2 + 1 - side, owner.getId());
if (slot == firstPlayerSlot()) releaseBackPaddles();
if (slot == 0) clearBackQamWrites();
stateFor(slot).clear();
if (slot == 0) publish();
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1));
return slot;
}
@@ -592,6 +769,7 @@ public final class PadBridge {
}
private void leave(int slot, int id) {
if (slot == 0) clearBackQamWrites();
if (partners[slot] == NO_CONTROLLER) {
free(slot);
return;
@@ -618,6 +796,7 @@ public final class PadBridge {
partners[slot] = NO_CONTROLLER;
clearJoyCons(slot);
slotControllers.set(slot, NO_CONTROLLER);
if (slot == homeGuideSlot) homeGuideSlot = -1;
if (slot == firstPlayerSlot()) releaseBackPaddles();
if (slot == 0) {
state.clear();
@@ -674,7 +853,13 @@ public final class PadBridge {
}
playerWriters[slot] = player;
}
player.writePad(playerStates[slot]);
PadState report = playerStates[slot];
if (slot == homeGuideSlot) {
homeGuideReport.copyFrom(report);
homeGuideReport.press(PadState.GUIDE, true);
report = homeGuideReport;
}
player.writePad(report);
}
private void publish() {
@@ -683,17 +868,17 @@ public final class PadBridge {
statDropped++;
return;
}
boolean guide = systemGuidePressed || qamChordActive;
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed);
boolean guide = systemGuidePressed || qamChordActive || homeGuidePressed;
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed || backQamPressed);
if (!guide && !qam) {
writer.writePad(state);
writePad(state);
return;
}
effectiveState.copyFrom(state);
if (guide) effectiveState.press(PadState.GUIDE, true);
if (qam) effectiveState.press(PadState.QAM, true);
if (chordButtonPressed) effectiveState.press(chordButton, true);
writer.writePad(effectiveState);
writePad(effectiveState);
}
public static boolean wiredXboxLayout(MotionEvent event) {
@@ -0,0 +1,35 @@
package com.droiddeck.launcher.input
import android.view.MotionEvent
internal fun MotionEvent.pointerSubset(pointerIdBits: Int): MotionEvent? {
val indices = (0 until pointerCount).filter { index ->
pointerIdBits and (1 shl getPointerId(index)) != 0
}
if (indices.isEmpty()) return null
val splitIndex = indices.indexOf(actionIndex)
val splitAction = when (actionMasked) {
MotionEvent.ACTION_DOWN -> if (splitIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_POINTER_DOWN -> if (splitIndex >= 0) {
if (indices.size == 1) MotionEvent.ACTION_DOWN
else MotionEvent.ACTION_POINTER_DOWN or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
} else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_UP -> if (splitIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_POINTER_UP -> if (splitIndex >= 0) {
if (indices.size == 1) MotionEvent.ACTION_UP
else MotionEvent.ACTION_POINTER_UP or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
} else MotionEvent.ACTION_MOVE
else -> action
}
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
indices.forEachIndexed { target, index ->
getPointerProperties(index, properties[target])
getPointerCoords(index, coordinates[target])
}
return MotionEvent.obtain(
downTime, eventTime, splitAction, indices.size, properties, coordinates,
metaState, buttonState, xPrecision, yPrecision,
deviceId, edgeFlags, source, flags,
)
}
@@ -926,35 +926,7 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
}
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
val indices = (0 until event.pointerCount).filter { index ->
pointerIdBits and (1 shl event.getPointerId(index)) != 0
}
if (indices.isEmpty()) return
val actionIndex = indices.indexOf(event.actionIndex)
val action = when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> if (actionIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_POINTER_DOWN -> if (actionIndex >= 0) {
if (indices.size == 1) MotionEvent.ACTION_DOWN
else MotionEvent.ACTION_POINTER_DOWN or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
} else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_UP -> if (actionIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_POINTER_UP -> if (actionIndex >= 0) {
if (indices.size == 1) MotionEvent.ACTION_UP
else MotionEvent.ACTION_POINTER_UP or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
} else MotionEvent.ACTION_MOVE
else -> event.action
}
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
indices.forEachIndexed { target, source ->
event.getPointerProperties(source, properties[target])
event.getPointerCoords(source, coordinates[target])
}
val split = MotionEvent.obtain(
event.downTime, event.eventTime, action, indices.size, properties, coordinates,
event.metaState, event.buttonState, event.xPrecision, event.yPrecision,
event.deviceId, event.edgeFlags, event.source, event.flags,
)
val split = event.pointerSubset(pointerIdBits) ?: return
try {
onTouchMiss?.invoke(split)
} finally {
@@ -103,6 +103,8 @@ class SteamTouchControls(
private class Finger(val element: Element?, var x: Float, var y: Float, val toolbar: Int = -1)
private val fingers = HashMap<Int, Finger>()
private var forwardedPointerBits = 0
var onTouchMiss: ((MotionEvent) -> Unit)? = null
private var editing = false
private var editElements: MutableList<Element> = mutableListOf()
@@ -629,7 +631,17 @@ class SteamTouchControls(
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
val x = event.getX(index)
val y = event.getY(index)
val e = hit(live(), x, y) ?: return event.actionMasked == MotionEvent.ACTION_POINTER_DOWN
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
val e = hit(live(), x, y)
if (e == null) {
if (event.actionMasked == MotionEvent.ACTION_DOWN) return false
if (onTouchMiss != null) {
forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(index))
forwardPointers(event, forwardedPointerBits)
}
return true
}
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
fingers[event.getPointerId(index)] = Finger(e, x, y)
if (feedback) performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
requestUnbufferedDispatch(event)
@@ -637,6 +649,7 @@ class SteamTouchControls(
return true
}
MotionEvent.ACTION_MOVE -> {
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
for (i in 0 until event.pointerCount) {
val f = fingers[event.getPointerId(i)] ?: continue
f.x = event.getX(i)
@@ -655,12 +668,14 @@ class SteamTouchControls(
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
val id = event.getPointerId(index)
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
forwardedPointerBits = if (event.actionMasked == MotionEvent.ACTION_CANCEL) 0 else forwardedPointerBits and (1 shl id).inv()
val f = fingers.remove(id)
if (event.actionMasked == MotionEvent.ACTION_CANCEL) fingers.clear()
val e = f?.element
if (event.actionMasked != MotionEvent.ACTION_CANCEL && e != null && reach(e, event.getX(index), event.getY(index)) <= 1.3f) {
when (e.type) {
SteamTouchConfig.THUMB -> openMenu()
SteamTouchConfig.THUMB -> { cancelForwarded(event); openMenu() }
SteamTouchConfig.KEYBOARD -> onKeyboard()
SteamTouchConfig.PASTE -> onPaste()
}
@@ -673,6 +688,25 @@ class SteamTouchControls(
}
private fun cancelForwarded(event: MotionEvent) {
val split = event.pointerSubset(forwardedPointerBits).also { forwardedPointerBits = 0 } ?: return
split.action = MotionEvent.ACTION_CANCEL
try {
onTouchMiss?.invoke(split)
} finally {
split.recycle()
}
}
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
val split = event.pointerSubset(pointerIdBits) ?: return
try {
onTouchMiss?.invoke(split)
} finally {
split.recycle()
}
}
val isEditing get() = editing
fun startEditing() {
@@ -0,0 +1,22 @@
package com.droiddeck.launcher.input
import android.media.AudioManager
import android.view.KeyEvent
/** Use Steam's PulseAudio bridge for feedback instead of requesting Android's volume UI. */
internal object SteamVolumeKeys {
fun dispatch(event: KeyEvent, enabled: Boolean, adjust: (Int) -> Unit): Boolean {
val direction = when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP -> AudioManager.ADJUST_RAISE
KeyEvent.KEYCODE_VOLUME_DOWN -> AudioManager.ADJUST_LOWER
KeyEvent.KEYCODE_VOLUME_MUTE -> AudioManager.ADJUST_TOGGLE_MUTE
else -> return false
}
if (!enabled) return false
if (event.action == KeyEvent.ACTION_DOWN &&
(event.keyCode != KeyEvent.KEYCODE_VOLUME_MUTE || event.repeatCount == 0)) {
adjust(direction)
}
return event.action == KeyEvent.ACTION_DOWN || event.action == KeyEvent.ACTION_UP
}
}
@@ -17,45 +17,45 @@ object BattleNet {
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)
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null)
internal val TITLES = listOf(
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight"),
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades"),
Title("wow_classic_era", "World of Warcraft Classic", "WoWC"),
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC"),
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii"),
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow"),
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic"),
Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era"),
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary"),
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"),
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii"),
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered"),
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone"),
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm"),
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch"),
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged"),
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4"),
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare"),
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered"),
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war"),
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard"),
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii"),
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii"),
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4"),
Title("osi", "Diablo II: Resurrected", "OSI"),
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection"),
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal"),
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
Title("d1", "Diablo", "D1", shop = "diablo"),
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans"),
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition"),
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered"),
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered"),
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble"),
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages"),
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves"),
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2"),
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710),
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed"),
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"),
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered", product = "s1"),
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone", product = "hsb"),
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm", product = "hero"),
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch", product = "pro"),
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged", product = "w3"),
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4", product = "viper"),
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare", product = "odin"),
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered", product = "lazr"),
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war", product = "zeus"),
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard", product = "fore"),
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii", product = "auks"),
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii", product = "pinta"),
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4", product = "wlby"),
Title("osi", "Diablo II: Resurrected", "OSI", product = "osi"),
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection", product = "rtro"),
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal", product = "anbs"),
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
Title("d1", "Diablo", "D1", shop = "diablo", product = "drtl"),
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans", product = "war1"),
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition", product = "w2bn"),
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered", product = "w1r"),
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered", product = "w2r"),
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble", product = "gryphon"),
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages", product = "aris"),
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves", product = "scor"),
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2", product = "ark"),
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710, product = "lbra"),
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" }
@@ -104,7 +104,7 @@ object BattleNet {
private val NOT_GAMES = setOf("agent", "bna", "battle.net")
class Game(val uid: String, val name: String, val code: String, val folder: File) {
class Game(val uid: String, val name: String, val code: String, val folder: File, val installUid: String = uid) {
val title: Title get() = title(uid) ?: Title(uid, name, code)
}
@@ -161,8 +161,10 @@ object BattleNet {
fun games(context: Context): List<Game> {
val pfx = File(prefix(context), "pfx")
val entries = runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()) +
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrDefault(emptyList())
val entries = installs(
runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()),
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull(),
)
val found = LinkedHashMap<String, Game>()
for ((uid, path) in entries) {
val title = title(uid)
@@ -172,11 +174,17 @@ object BattleNet {
}
if (title.code in found) continue
val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue
found[title.code] = Game(title.uid, title.name, title.code, folder)
found[title.code] = Game(title.uid, title.name, title.code, folder, uid)
}
return found.values.toList()
}
internal fun installs(registry: List<Pair<String, String>>, agent: List<Pair<String, String>>?): List<Pair<String, String>> {
if (agent == null) return registry
val tracked = agent.map { it.first.lowercase() }.toSet()
return registry.filter { it.first.lowercase() in tracked } + agent
}
internal fun hostFolder(context: Context, path: String): File? {
val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
val relative = drive.groupValues[2].replace('\\', '/').trim('/')
@@ -242,9 +250,9 @@ object BattleNet {
return out.toString()
}
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>> {
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrDefault(emptyList()).filter { it.first == 1 }
return installs.mapNotNull { (_, start, end) ->
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? {
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null
return installs.map { (_, start, end) ->
runCatching {
val install = fields(bytes, start, end)
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
@@ -253,8 +261,8 @@ object BattleNet {
val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
?.let { s -> varints(bytes, s.second, s.third)[1] }
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path
}.getOrNull()
}
}.getOrElse { return null }
}.filterNotNull()
}
private fun fields(bytes: ByteArray, from: Int, to: Int): List<Triple<Int, Int, Int>> = walk(bytes, from, to) { _, _ -> }
@@ -352,6 +360,8 @@ object BattleNet {
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
}
@@ -0,0 +1,188 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.content.Intent
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.database.ContentObserver
import android.media.AudioManager
import android.os.FileObserver
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.R
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import org.json.JSONObject
import kotlin.math.roundToInt
class DeviceControlsComponent(context: Context, root: File, private val activityVisible: () -> Boolean = { false }) : SessionPart() {
private val context = context.applicationContext
private val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
private val directory = directory(root)
private val handler = Handler(Looper.getMainLooper())
private var running = false
private var permissionNotified = false
private var previous = ""
private var revision = 0L
init { prepareBacklight(context, root) }
private val observer = object : ContentObserver(handler) {
override fun onChange(selfChange: Boolean) { if (running) publish() }
}
private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) {
override fun onEvent(event: Int, path: String?) {
if (path in REQUESTS) handler.post { if (running) consume() }
}
}
private val refresh = object : Runnable {
override fun run() {
if (!running) return
consume()
if (permissionNotified && Settings.System.canWrite(context))
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
publish()
handler.postDelayed(this, 250)
}
}
fun publish(force: Boolean = false) {
try {
directory.mkdirs()
val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1)
val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC)
write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n")
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
write("backlight/droiddeck/brightness", "$value\n")
write("backlight/droiddeck/actual_brightness", "$value\n")
val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0)
.put("brightnessWritable", Settings.System.canWrite(context)).toString()
if (force || state != previous) {
write("state.json", JSONObject(state).put("revision", ++revision).toString())
previous = state
}
} catch (e: Exception) {
Log.w(TAG, "Could not publish Android controls", e)
}
}
override fun start() {
handler.post {
REQUESTS.forEach {
File(directory, it).delete()
File(directory, "$it.processing").delete()
}
running = true
permissionNotified = false
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
requests.startWatching()
refresh.run()
}
}
override fun stop() {
handler.post {
running = false
handler.removeCallbacks(refresh)
requests.stopWatching()
context.contentResolver.unregisterContentObserver(observer)
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
}
}
private fun consume() {
for (name in REQUESTS) {
val file = File(directory, name)
if (!file.isFile) continue
val claimed = File(directory, "$name.processing")
try {
Files.move(file.toPath(), claimed.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
if (claimed.length() > 64) continue
val text = claimed.readText().trim()
when (name) {
"brightness.request" -> text.toFloatOrNull()?.takeIf { it.isFinite() && it in 0f..1f }?.let(::brightness)
"volume.request" -> text.toIntOrNull()?.let {
audio.setStreamVolume(AudioManager.STREAM_MUSIC,
it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0)
}
"mute.request" -> if (text == "0" || text == "1") {
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0)
}
}
} catch (e: Exception) {
Log.w(TAG, "Could not apply $name", e)
} finally {
publish(force = true)
claimed.delete()
}
}
}
private fun brightness(value: Float) {
if (!Settings.System.canWrite(context)) {
if (!permissionNotified) {
permissionNotified = true
try {
val intent = Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java)
.setAction(com.droiddeck.launcher.core.SteamIntegration.ACTION_SETUP)
.putExtra(com.droiddeck.launcher.core.SteamIntegration.EXTRA_FEATURE, "BRIGHTNESS")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
val manager = context.getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(NotificationChannel(PERMISSION_CHANNEL,
context.getString(R.string.brightness_permission_title), NotificationManager.IMPORTANCE_DEFAULT))
val action = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
manager.notify(PERMISSION_NOTIFICATION, Notification.Builder(context, PERMISSION_CHANNEL)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(context.getString(R.string.brightness_permission_title))
.setContentText(context.getString(R.string.brightness_permission_text))
.setContentIntent(action).setOnlyAlertOnce(true).setAutoCancel(true).build())
if (activityVisible()) android.widget.Toast.makeText(context, R.string.integration_brightness_needed,
android.widget.Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Log.w(TAG, "Could not open brightness permission", e)
}
}
return
}
val level = 1 + (value * 254).roundToInt()
try {
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, level)
} catch (e: SecurityException) {
Log.w(TAG, "Brightness permission was revoked", e)
}
}
private fun write(name: String, text: String) {
val file = File(directory, name)
if (file.isFile && file.readText() == text) return
val staged = File(directory, "$name.tmp")
staged.writeText(text)
Files.move(staged.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
}
companion object {
private const val TAG = "DeviceControls"
private const val PERMISSION_CHANNEL = "brightness_permission"
private const val PERMISSION_NOTIFICATION = 0x4442
private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request")
@JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls")
@JvmStatic fun prepareBacklight(context: Context, root: File): File {
val base = File(directory(root), "backlight")
val panel = File(base, "droiddeck").apply { mkdirs() }
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
for ((name, text) in mapOf("type" to "raw", "max_brightness" to "255", "brightness" to "$value",
"actual_brightness" to "$value", "bl_power" to "0", "scale" to "linear")) {
File(panel, name).writeText("$text\n")
}
return base
}
}
}
@@ -63,15 +63,48 @@ public final class LinuxRuntime {
}
private static final String HOST_DIR = "opt/android-host";
/** The downloaded add-on pack. The APK does not ship this binary. */
public static final String PROOT_PACK = "add-on pack";
/** Termux's unpatched proot inside the rootfs. Developer switch only. */
public static final String PROOT_ROOTFS = "rootfs fallback";
public static final String PROOT_MISSING = "missing";
private static File rootfsProot(Context context) {
return new File(rootDir(context), HOST_DIR + "/proot");
}
private static File rootfsLoader(Context context) {
return new File(rootDir(context), HOST_DIR + "/loader");
}
private static boolean rootfsProotReady(Context context) {
return rootfsProot(context).isFile() && rootfsLoader(context).isFile();
}
/** Patched proot is the add-on pack. The rootfs copy is not that binary. */
public static boolean patchedProot(Context context) {
return AddonPack.PROOT.installed(context);
}
public static File prootBinary(Context context) {
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot.so");
return new File(rootDir(context), HOST_DIR + "/proot");
if (SessionPrefs.allowStockProot(context)) return rootfsProot(context);
return AddonPack.PROOT.file(context, "libproot.so");
}
public static File prootLoader(Context context) {
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot-loader.so");
return new File(rootDir(context), HOST_DIR + "/loader");
if (SessionPrefs.allowStockProot(context)) return rootfsLoader(context);
return AddonPack.PROOT.file(context, "libproot-loader.so");
}
/** Where {@link #prootBinary} came from: {@link #PROOT_PACK}, {@link #PROOT_ROOTFS} or {@link #PROOT_MISSING}. */
public static String prootSource(Context context) {
File bin = prootBinary(context);
if (!bin.isFile()) return PROOT_MISSING;
if (AddonPack.PROOT.installed(context)
&& bin.getPath().equals(AddonPack.PROOT.file(context, "libproot.so").getPath())) return PROOT_PACK;
return PROOT_ROOTFS;
}
public static String prootLibraryPath(Context context) {
@@ -85,8 +118,7 @@ public final class LinuxRuntime {
return new File(root, "usr/bin/gamescope").isFile()
&& (new File(root, SESSION_SCRIPT.substring(1)).isFile()
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile())
&& prootBinary(context).isFile()
&& prootLoader(context).isFile();
&& (patchedProot(context) || rootfsProotReady(context));
}
public static File vulkanIcd(Context context) {
@@ -160,6 +192,7 @@ public final class LinuxRuntime {
bind(cmd, "/dev");
bind(cmd, "/proc");
bind(cmd, "/sys");
bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight");
bind(cmd, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd");
bind(cmd, "/proc/self/fd/0:/dev/stdin");
@@ -6,6 +6,7 @@ import android.util.Log;
import com.droiddeck.launcher.R;
import com.droiddeck.launcher.session.SessionPrefs;
import com.droiddeck.launcher.core.ArchivePaths;
import com.droiddeck.launcher.core.Downloader;
import com.droiddeck.launcher.core.Hashes;
@@ -262,7 +263,9 @@ public final class LinuxRuntimeInstaller {
emptyTrash(LinuxRuntime.rootDir(context).getParentFile());
String downloading = context.getString(R.string.rtinst_downloading);
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
if (!AddonPack.PROOT.await(context)) throw new IOException("Cannot download proot");
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context)
&& !SessionPrefs.allowStockProot(context))
throw new IOException("Cannot download proot");
if (!AddonPack.DIRECTAUDIO.await(context)) throw new IOException("Cannot download DirectAudio");
boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> {
if (listener != null) {
@@ -1,18 +1,32 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.core.AddonPack
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.MessageDigest
object ProotFastPath {
private const val TAG = "ProotFastPath"
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
const val MAX_BINDS = 256
fun enabled(context: Context): Boolean =
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context) &&
LinuxRuntime.prootBinary(context).parentFile == AddonPack.PROOT.dir(context)
/**
* The fast path's trampoline is let through only by the proot built with patches/0014.
* The rootfs copy (Termux's stock proot) is not that binary, so the library stays out.
*/
fun allows(preference: Boolean, noSeccomp: Boolean, source: String): Boolean =
preference && !noSeccomp && source == LinuxRuntime.PROOT_PACK
fun enabled(context: Context): Boolean {
val preference = SessionPrefs.prootFastPath(context)
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
val source = LinuxRuntime.prootSource(context)
val on = allows(preference, noSeccomp, source)
if (preference && !noSeccomp && !on)
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
return on
}
fun key(root: File, binds: List<String>): String? {
if (binds.size > MAX_BINDS || binds.any { it.contains('|') } || root.path.contains('|')) return null
@@ -155,8 +155,7 @@ object ComponentsManager {
if (staged.exists()) check(staged.delete()) { "Could not remove unpublished component selections" }
}
private fun saveState(context: Context, state: JSONObject) {
val prepared = prepareLaunchState(context, state)
private fun saveState(context: Context, state: JSONObject, prepared: PreparedLaunchState = prepareLaunchState(context, state)) {
val dir = launchDir(context)
val tmp = File(dir, "desired.tsv.tmp")
try {
@@ -175,6 +174,17 @@ object ComponentsManager {
?.forEach { it.deleteRecursively() }
}
fun republish(context: Context): Boolean = synchronized(lock) {
recoverState(context)
val saved = stateFile(context)
if (saved.exists() && runCatching { JSONObject(saved.readText()) }.isFailure) return false
val state = loadState(context)
val prepared = prepareLaunchState(context, state)
if ((FileUtils.readString(File(launchDir(context), "desired.tsv")) ?: "") == prepared.text) return false
saveState(context, state, prepared)
true
}
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
private fun rememberProfiledComponent(state: JSONObject, comp: String) {
@@ -8,7 +8,7 @@ import org.json.JSONObject
import java.io.File
/**
* The FEX build DroidDeck-Components' fex.json names for the x86-64 client. A session uses the last copy read.
* The FEX build DroidDeck-Components' fex.json names for x86 programs. A session uses the last copy read.
* Components' build-fex.yml replaces the archive on its single `fex` release and records the build's version;
* a release per build (fex-2610-r5) is still read.
*/
@@ -62,7 +62,7 @@ object FexCatalog {
return build
}
/** For droiddeck-steam-x64: the build and every source its archive may come from (it checks the sha256). */
/** For droiddeck-fex-update: the build and every source its archive may come from (it checks the sha256). */
fun environment(build: Build, sources: List<String> = DownloadSource.candidates(build.url)): List<String> = listOf(
"BL_FEX_TAG=${build.tag}",
"BL_FEX_SHA256=${build.sha256}",
@@ -51,7 +51,8 @@ object NoSteamLaunch {
fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? {
val id = game.appId.toLong() and 0xFFFFFFFFL
return AddedGames.scan(context).firstOrNull { settingsId(it) == id }
val one = game.gameFiles?.let { AddedGames.single(context, it.path) }
return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id }
}
fun nameFor(program: String?, args: List<String>): String? = when (program) {
@@ -18,7 +18,6 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.util.Locale
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
class PerfHud(context: Context) {
var text by mutableStateOf("")
@@ -32,9 +31,9 @@ class PerfHud(context: Context) {
private var lastFps = 0f
private var running = false
private val handler = Handler(Looper.getMainLooper())
private val intervals = FloatArray(GRAPH)
private val graphWrite = AtomicInteger()
private val lastFrameNs = AtomicLong()
private val samples = FloatArray(GRAPH)
private var graphBase = 0L
private var graphSeen = 0L
@Volatile private var showFps = true
@Volatile private var showBattery = true
@@ -59,14 +58,6 @@ class PerfHud(context: Context) {
}
override fun onGameFrame() {
frames.incrementAndGet()
if (!showGraph) return
val now = System.nanoTime()
val previous = lastFrameNs.getAndSet(now)
if (previous == 0L) return
val ms = ((now - previous) / 1_000_000f).coerceIn(0f, 50f)
val slot = graphWrite.get()
intervals[slot and (GRAPH - 1)] = ms
graphWrite.compareAndSet(slot, slot + 1)
}
}
@@ -100,9 +91,9 @@ class PerfHud(context: Context) {
if (!enabled || !anyPart || running) return
running = true
lastTick = SystemClock.elapsedRealtime()
lastFrameNs.set(0L)
frames.set(0)
graphWrite.set(0)
graphBase = shownTotal()
graphSeen = graphBase
WaylandCompositor.setGameListener(listener)
handler.postDelayed(tick, TICK_MS)
}
@@ -135,23 +126,19 @@ class PerfHud(context: Context) {
return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
}
private fun shownTotal(): Long = try { WaylandCompositor.nativeHudFrameTimes(samples) } catch (t: Throwable) { 0L }
private fun clearGraph() {
lastFrameNs.set(0L)
graphWrite.set(0)
graphBase = shownTotal()
graphSeen = graphBase
if (graph.isNotEmpty()) graph = FloatArray(0)
}
private fun publishGraph() {
val count = graphWrite.get()
val shown = minOf(count, GRAPH)
if (shown < 2) {
graph = FloatArray(0)
return
}
val out = FloatArray(shown)
val start = count - shown
for (i in 0 until shown) out[i] = intervals[(start + i) and (GRAPH - 1)]
graph = out
val total = shownTotal()
if (total == graphSeen && graph.isNotEmpty()) return
graphSeen = total
graph = recent(samples, total, graphBase)
}
private fun line(base: Float): String {
@@ -176,6 +163,14 @@ class PerfHud(context: Context) {
companion object {
private const val TICK_MS = 1_000L
private const val GRAPH = 128
internal const val GRAPH_MAX_MS = 50f
internal fun recent(samples: FloatArray, total: Long, base: Long): FloatArray {
val filled = minOf(total, samples.size.toLong()).toInt()
val shown = minOf(filled.toLong(), (total - base).coerceAtLeast(0L)).toInt()
if (shown < 2) return FloatArray(0)
return FloatArray(shown) { samples[filled - shown + it].coerceIn(0f, GRAPH_MAX_MS) }
}
internal fun batteryCelsius(deci: Int): String? =
if (deci <= 0) null else String.format(Locale.US, "%.1f°C", deci / 10f)
@@ -30,6 +30,7 @@ class RumbleComponent : SessionPart() {
private val joyConPairs = HashMap<Long, Motors>()
private var preferences: SharedPreferences? = null
private var enabled = false
private var quiet = false
private var motorThread: HandlerThread? = null
private var handler: Handler? = null
private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
@@ -44,6 +45,11 @@ class RumbleComponent : SessionPart() {
if (!enabled) cancelAll()
}
@Synchronized fun quiet(on: Boolean) {
quiet = on
if (on) cancelAll()
}
override fun start() {
val ctx = app() ?: return
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
@@ -89,7 +95,7 @@ class RumbleComponent : SessionPart() {
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
if (!enabled) return
if (!enabled || quiet) return
val target = target(slot)
val previous = playing[slot]
if (target !== previous) {
@@ -17,12 +17,13 @@ object SessionDisplay {
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())
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> {
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return screenSize(panel)
presetHeight(choice)?.let { return resolve(panel, it, SessionPrefs.SHAPE_AUTO) }
fun resolveChoice(panel: Pair<Int, Int>, choice: String, portrait: Boolean = false): Pair<Int, Int> {
fun orient(size: Pair<Int, Int>) = if (portrait) size.second to size.first else size
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return orient(screenSize(panel))
presetHeight(choice)?.let { return orient(resolve(panel, it, SessionPrefs.SHAPE_AUTO)) }
val parts = choice.split('x').map { it.toIntOrNull() }
return if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
else resolve(panel, 720, SessionPrefs.SHAPE_AUTO)
else orient(resolve(panel, 720, SessionPrefs.SHAPE_AUTO))
}
fun resolutionOptions(panel: Pair<Int, Int>): List<String> {
@@ -31,8 +32,10 @@ object SessionDisplay {
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN + FOLLOW_SCREEN
}
fun followSize(width: Int, height: Int): Pair<Int, Int>? =
if (minOf(width, height) < FOLLOW_MIN_SIDE) null else (width and 1.inv()) to (height and 1.inv())
fun followSize(width: Int, height: Int, controlsBelow: Boolean = false): Pair<Int, Int>? =
if (width <= 0 || height <= 0 ||
(if (controlsBelow) width else minOf(width, height)) < FOLLOW_MIN_SIDE) null
else (width and 1.inv()) to (height and 1.inv())
const val UNFOLDED_MAX_GAME_SHARE = 0.8f
@@ -49,13 +52,14 @@ object SessionDisplay {
foldable: Boolean,
controllerConnected: Boolean,
keepWithController: Boolean,
steamDeckPad: Boolean,
gamepadAvailable: Boolean,
pip: Boolean,
width: Int,
height: Int,
smallestWidthDp: Int,
): Boolean = enabled && foldable && (keepWithController || !controllerConnected) && steamDeckPad &&
!pip && width > 0 && height > 0 && smallestWidthDp >= UNFOLDED_MIN_DP
): Boolean = enabled && (keepWithController || !controllerConnected) && gamepadAvailable &&
!pip && width > 0 && height > 0 &&
(height > width || (foldable && smallestWidthDp >= UNFOLDED_MIN_DP))
fun panelSize(context: Context): Pair<Int, Int> {
@@ -81,6 +81,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
"usr/local/bin/droiddeck-steam-x64" to "usr/local/bin/droiddeck-steam-x64",
"usr/local/bin/droiddeck-fex-update" to "usr/local/bin/droiddeck-fex-update",
"usr/local/bin/droiddeck-steamrt-shim" to "usr/local/bin/droiddeck-steamrt-shim",
"usr/local/bin/droiddeck-x64-arm-proton" to "usr/local/bin/droiddeck-x64-arm-proton",
"usr/local/bin/droiddeck-x64-arm-webhelper" to "usr/local/bin/droiddeck-x64-arm-webhelper",
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.ScreenEffects
import org.json.JSONObject
import java.io.File
object SessionPrefs {
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
@@ -43,6 +44,8 @@ object SessionPrefs {
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
val orientationOptions = listOf(
ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto,
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait,
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse,
@@ -58,6 +61,17 @@ object SessionPrefs {
prefs(context).edit().putInt("orientation", orientation).apply()
}
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int =
if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation"))
ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context)
fun portrait(context: Context): Boolean = when (orientation(context)) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true
ActivityInfo.SCREEN_ORIENTATION_USER ->
context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
else -> false
}
fun launcherFullscreen(context: Context): Boolean = prefs(context).getBoolean("launcherFullscreen", true)
fun setLauncherFullscreen(context: Context, on: Boolean) {
@@ -111,6 +125,12 @@ object SessionPrefs {
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
}
fun libraryShowUninstalled(context: Context): Boolean = prefs(context).getBoolean("libraryShowUninstalled", false)
fun setLibraryShowUninstalled(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowUninstalled", show).apply()
}
fun storesTabOrder(context: Context): List<String> = idList(prefs(context).getString("storesTabOrder", null))
fun setStoresTabOrder(context: Context, order: List<String>) {
@@ -223,16 +243,10 @@ object SessionPrefs {
private fun mangoappSession(context: Context) =
SessionState.mode == SessionService.MODE_STEAM && mangoapp(context)
fun lowLatencyController(context: Context): Boolean = prefs(context).getBoolean("lowLatencyController", false)
fun lowLatency(context: Context): Boolean = prefs(context).getBoolean("lowLatency", true)
fun setLowLatencyController(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("lowLatencyController", on).apply()
}
fun lowLatencyTouch(context: Context): Boolean = prefs(context).getBoolean("lowLatencyTouch", false)
fun setLowLatencyTouch(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("lowLatencyTouch", on).apply()
fun setLowLatency(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("lowLatency", on).apply()
}
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
@@ -241,6 +255,16 @@ object SessionPrefs {
prefs(context).edit().putBoolean("backActionsInverted", inverted).apply()
}
val BACK_DOUBLE_TAP_MS_OPTIONS = (100..800 step 100).toList()
fun backDoubleTapMs(context: Context): Int =
prefs(context).getInt("backDoubleTapMs", 500).takeIf { it in BACK_DOUBLE_TAP_MS_OPTIONS } ?: 500
fun setBackDoubleTapMs(context: Context, ms: Int) {
require(ms in BACK_DOUBLE_TAP_MS_OPTIONS)
prefs(context).edit().putInt("backDoubleTapMs", ms).apply()
}
const val TOUCH_AUTO = "auto"
const val TOUCH_PAD = "touchpad"
const val TOUCH_DIRECT = "direct"
@@ -527,6 +551,15 @@ object SessionPrefs {
prefs(context).edit().putBoolean("cursorComposite", on).apply()
}
/**
* The rootfs ships Termux's unpatched proot. A session uses it only when this file exists,
* so a missing add-on pack cannot silently fall back to it.
* Path: Android/data/&lt;package&gt;/files/droiddeck-stock-proot
*/
@JvmStatic
fun allowStockProot(context: Context): Boolean =
context.getExternalFilesDir(null)?.let { File(it, "droiddeck-stock-proot").isFile } == true
const val DEFAULT_GUEST_HOSTNAME = "DroidDeck"
@JvmStatic
@@ -569,6 +602,8 @@ object SessionPrefs {
}
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true)
fun renderOnCommit(context: Context): Boolean = prefs(context).getBoolean("renderOnCommit", true)
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
@@ -654,8 +689,10 @@ object SessionPrefs {
parseResolution(value)?.let { return "${it.first}x${it.second}" }
}
if (!resolutionChosen(context, mode) && !saved.contains("shape")) return SessionDisplay.DEFAULT_RESOLUTION
val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), customResolution(context, mode))
val custom = customResolution(context, mode)
val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), custom)
return if (legacy == SessionDisplay.screenSize(panel)) SessionDisplay.MATCH_SCREEN
else if (custom == null && legacy == SessionDisplay.resolve(panel, legacy.second, SHAPE_AUTO)) "${legacy.second}p"
else "${legacy.first}x${legacy.second}"
}
@@ -903,32 +940,15 @@ object SessionPrefs {
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
}
fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0).coerceAtLeast(0)
fun setFpsLimit(context: Context, mode: String, fps: Int) {
prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply()
}
val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120")
fun fpsLimitChoices(context: Context): List<Pair<Int, String>> =
fpsLimitChoices.map { (fps, label) -> fps to if (fps == 0) context.getString(R.string.frame_gen_off) else label }
/**
* Performance mode: without a frame limit, buffers go back to the game as soon as they are replaced
* instead of once per refresh, and gamescope's WSI layer and winex11 reuse their per-present window checks.
*/
fun performanceMode(context: Context, mode: String): Boolean = prefs(context).getBoolean("performanceMode.$mode", false)
fun setPerformanceMode(context: Context, mode: String, on: Boolean) {
prefs(context).edit().putBoolean("performanceMode.$mode", on).apply()
}
/** Compositor frame limit that releases buffers to the game unpaced. */
const val FPS_UNPACED = -1
/** The limit handed to the compositor: Performance mode without a limit is unpaced, a chosen limit still paces. */
fun compositorFpsLimit(limit: Int, performanceMode: Boolean): Int = if (performanceMode && limit <= 0) FPS_UNPACED else limit
/**
* Buffers go back to the game as soon as they are replaced instead of once per refresh;
* Steam's Frame Limit in the Quick Access menu caps games. Mirroring still follows the glasses' refresh rate.
*/
fun compositorFpsLimit(mirrorRefreshLimit: Int): Int =
if (mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
val upscalerChoices = listOf(
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
@@ -1117,6 +1137,18 @@ object SessionPrefs {
fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", false)
fun controlsBelowWanted(context: Context, mode: String, width: Int, height: Int, pip: Boolean = false): Boolean =
SessionDisplay.unfoldedControlsWanted(
enabled = unfoldedControls(context),
foldable = SessionDisplay.foldable(context),
controllerConnected = com.droiddeck.launcher.input.PadBridge.anyControllerConnected() ||
com.droiddeck.launcher.input.SteamControllerBle.connected,
keepWithController = unfoldedControlsWithController(context),
gamepadAvailable = mode == SessionService.MODE_STEAM && builtinPad(context),
pip = pip, width = width, height = height,
smallestWidthDp = context.resources.configuration.smallestScreenWidthDp,
)
fun setUnfoldedControls(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean("unfoldedControls", enabled).apply()
}
@@ -25,6 +25,7 @@ import android.os.PowerManager
import android.hardware.display.DisplayManager
import android.view.Display
import android.util.Log
import android.widget.Toast
import com.droiddeck.launcher.R
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.audio.DirectAudioRelayComponent
@@ -430,8 +431,30 @@ class SessionService : Service() {
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
killStragglers()
for (pack in listOf(AddonPack.PROOT, AddonPack.DIRECTAUDIO))
if (!pack.await(this, { gen == sessionGen && SessionState.running })) Log.w(TAG, "${pack.name} pack unavailable")
val stillStarting = { gen == sessionGen && SessionState.running }
val prootPack = LinuxRuntime.patchedProot(this) || AddonPack.PROOT.await(this, stillStarting)
val directAudioPack = AddonPack.DIRECTAUDIO.await(this, stillStarting)
if (!stillStarting()) {
Log.i(TAG, "session stopped while add-on packs were downloading")
return
}
if (!directAudioPack) {
Log.w(TAG, "directaudio pack unavailable; game audio drivers will not be staged")
mainHandler.post {
Toast.makeText(this, R.string.session_directaudio_missing, Toast.LENGTH_LONG).show()
}
}
if (!LinuxRuntime.patchedProot(this)) {
if (SessionPrefs.allowStockProot(this)) {
Log.w(TAG, "proot: patched proot missing; droiddeck-stock-proot allows the rootfs copy")
} else {
val message = getString(R.string.session_proot_missing)
Log.e(TAG, "$message (pack ready=$prootPack)")
SessionEvents.fail("PROOT_MISSING", message, -1)
stopSession(-1)
return
}
}
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
@@ -446,6 +469,10 @@ class SessionService : Service() {
val sessionDir = openSessionFolder()
val sessionLog = File(sessionDir, "session.log")
val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})"
Log.i(TAG, prootLine)
runCatching { sessionLog.appendText(prootLine + "\n") }
.onFailure { Log.w(TAG, "could not write the proot line to ${sessionLog.path}", it) }
Log.i(TAG, GpuClockPin.start(this))
Log.i(TAG, GameThreadHints.start(this))
@@ -453,6 +480,9 @@ class SessionService : Service() {
val size = SessionState.outputSize
val guest = ArrayList<String>()
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
runCatching { ComponentsManager.republish(this) }
.onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") }
.onFailure { Log.w(TAG, "component selections", it) }
if (steamHere) {
runCatching { ComponentsManager.ensureForcedPackages(this) }
.onSuccess { if (it != null) Log.i(TAG, it) }
@@ -462,7 +492,7 @@ class SessionService : Service() {
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
val fastPathAt = guest.size
val pulse = startAudio(guest, sessionDir)
val pulse = startAudio(guest, sessionDir, directAudioPack)
if (steamHere) {
val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock"))
encoder.attach(this)
@@ -472,23 +502,21 @@ class SessionService : Service() {
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
if (SessionState.followScreen) guest.add("BL_FOLLOW_OUTPUT=1")
if (SessionState.followScreen || size.first < size.second ||
SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
guest.add("BL_FOLLOW_OUTPUT=1")
if (SessionState.hdr) {
guest.add("BL_HDR=1")
guest.add("DXVK_HDR=1")
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
}
guest.add("BL_FPS=" + SessionState.fpsLimit)
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long; 0 checks on every present.
val windowCheckMs = if (SessionState.performanceMode) 100 else 0
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=$windowCheckMs")
guest.add("WINE_OFFSCREEN_CHECK_MS=$windowCheckMs")
if (SessionPrefs.compositorFpsLimit(SessionState.fpsLimit, SessionState.performanceMode) == SessionPrefs.FPS_UNPACED) {
// gamescope turns buffers around slower than an unpaced game draws; more images keep it drawing.
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
}
Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off") + ", frame limit " + SessionState.fpsLimit)
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long.
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
// gamescope turns buffers around slower than an uncapped game draws; more images keep it drawing.
// The WSI layer goes back to its default count while Steam's Frame Limit holds the game.
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
@@ -602,6 +630,10 @@ class SessionService : Service() {
networkLink.attach(this)
networkLink.publish()
components.add(networkLink)
val deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent(this, root) { activityVisible && screenOn }
deviceControls.attach(this)
deviceControls.publish()
components.add(deviceControls)
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while it was starting; not launching it")
if (gen == sessionGen) components.clear()
@@ -749,8 +781,8 @@ class SessionService : Service() {
SessionArtifacts.recordClient(it, arch)
SessionArtifacts.markSteamLogs(it, File(SessionPrefs.steamRoot(this, arch), "logs"))
}
if (arch == "x86_64") FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) }
}
FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) }
if (SessionState.mode == MODE_STEAM) {
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
}
@@ -782,8 +814,9 @@ class SessionService : Service() {
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
val wantsDirectAudio = directAudioPack &&
(SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
SessionPrefs.directAudio(this)
val wantsMic = SessionPrefs.micEnabled(this) &&
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
@@ -852,7 +885,7 @@ class SessionService : Service() {
SessionState.deckPad = deckBinds.isNotEmpty()
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
logControllersAtStart()
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatencyController(this), SessionPrefs.lowLatencyTouch(this))
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatency(this))
if (uinput) {
guest.add("FAKE_EVDEV_UINPUT=1")
if (SessionState.deckPad) {
@@ -1525,6 +1558,9 @@ class SessionService : Service() {
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && prepared && !downloadsBlockingSuspend
else -> false
}
// A frozen game never sends the stop for a held rumble, so the keepalive would run on.
val quietRumble = !screenOn || shouldSuspend || SessionState.suspended
components.forEach { (it as? RumbleComponent)?.quiet(quietRumble) }
if (freezePending && !shouldSuspend && !freezeCancelled) {
freezeCancelled = true
controller.cancelFreeze()
@@ -103,12 +103,6 @@ object SessionState {
@Volatile
var upscaleRatio: Float = 0f
@Volatile
var fpsLimit: Int = 0
@Volatile
var performanceMode = false
@Volatile
var firstFrameSeen = false
@@ -14,7 +14,7 @@ object SettingsReset {
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
@@ -88,6 +88,7 @@ class StoreLoginActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
store = Store.byId(intent.getStringExtra(EXTRA_STORE))
clientUrl = intent.getStringExtra(EXTRA_CLIENT_URL)?.takeIf { store == Store.EPIC }
oauthState = savedInstanceState?.getString(KEY_STATE) ?: generateState()
@@ -130,7 +130,7 @@ object StoresState {
fun detailItem(store: Store, id: String): CatalogItem? = detailCatalogItem(
store, id, library[store].orEmpty(),
found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items else emptyList(),
found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items + com.droiddeck.launcher.stores.itch.ItchCollections.items() else emptyList(),
shelves[store],
)
@@ -191,6 +191,7 @@ object StoresState {
backend?.signOut(app)
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchCollections.clear()
main.post {
if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store)
@@ -236,7 +237,7 @@ object StoresState {
fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) {
val app = context.applicationContext
val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app)
if (item.store == Store.BATTLENET) {
if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) {
backends[item.store]?.install(app, item, targetRoot)
return
}
@@ -273,7 +274,7 @@ object StoresState {
uninstalling[key] = 0f
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
if (game.sidecar.store == Store.BATTLENET) {
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
main.post { uninstalling.remove(key); onDone() }
return@background
}
@@ -0,0 +1,320 @@
package com.droiddeck.launcher.stores.battlenet
import android.content.Context
import android.util.Log
import androidx.compose.runtime.mutableStateMapOf
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SecondaryLibrary
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.util.Locale
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object BattleNetInstall {
private const val TAG = "BattleNetInstall"
internal const val PROGRESS = "BNET_PROGRESS "
internal const val STATE = "BNET_STATE "
internal const val DONE = "BNET_DONE "
internal const val ERROR = "BNET_ERROR "
private const val VERSIONS = "https://%s.version.battle.net/v2/products/%s/versions"
private const val BUILD_INFO = ".build.info"
private const val CHECK_AGAIN_MS = 30 * 60_000L
private const val START_WAIT_MS = 60_000L
internal val LOCALES = listOf(
"enUS", "enGB", "esMX", "esES", "ptBR", "ptPT", "frFR", "deDE", "itIT", "ruRU", "jaJP", "koKR", "plPL", "trTR",
"zhTW", "zhCN", "thTH", "arSA",
)
internal val checks = Executors.newSingleThreadExecutor { r -> Thread(r, "battlenet-updates") }
internal val checkedAt = HashMap<String, Long>()
val updates = mutableStateMapOf<String, Boolean>()
fun product(id: String): String? = BattleNet.title(id)?.product
fun headless(item: CatalogItem): Boolean = item.store == Store.BATTLENET && product(item.id) != null
internal fun locale(locale: Locale): String {
val language = locale.language.lowercase(Locale.ROOT)
if (language == "zh") {
val traditional = locale.script.equals("Hant", true) || locale.country.uppercase(Locale.ROOT) in setOf("TW", "HK", "MO")
return if (traditional) "zhTW" else "zhCN"
}
val exact = language + locale.country.uppercase(Locale.ROOT)
return LOCALES.firstOrNull { it == exact } ?: LOCALES.firstOrNull { it.startsWith(language) } ?: "enUS"
}
internal fun country(locale: Locale): Pair<String, String> {
val two = locale.country.uppercase(Locale.ROOT)
val three = runCatching { locale.isO3Country.uppercase(Locale.ROOT) }.getOrDefault("")
return if (two.matches(Regex("[A-Z]{2}")) && three.matches(Regex("[A-Z]{3}"))) three to two else "USA" to "US"
}
internal fun binds(context: Context): List<String> {
val out = ArrayList<String>(StoreInstallRoot.externalBindSpecs(context))
val root = LinuxRuntime.rootDir(context)
GameStorage.effective(context)?.let { library ->
if (!File(library.path).isDirectory) throw IllegalStateException(context.getString(R.string.game_sync_err_game_storage))
val content = SecondaryLibrary.contentPath(File(library.path)).path
for (guest in SecondaryLibrary.CARD_GUESTS) {
File(root, guest.removePrefix("/")).mkdirs()
out += "$content:$guest"
}
}
for (folder in AddedGames.roots(context)) {
if (!folder.host.isDirectory || !folder.host.canRead()) continue
File(root, folder.guest.removePrefix("/")).mkdirs()
out += folder.host.path + ":" + folder.guest
}
return out
}
internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
GuestCommand.run(
context, listOf(BattleNet.PROGRAM) + args, logName = "battlenet-agent",
extraBinds = binds(context), fastPath = true, cancelled = cancelled, onLine = onLine,
)
fun enqueue(context: Context, item: CatalogItem, folder: File, update: Boolean = false) {
val app = context.applicationContext
val entry = DownloadEntry(
Store.BATTLENET, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl,
location = StoreInstallRoot.labelFor(app, folder),
)
DownloadQueue.enqueue(app, entry) { BattleNetInstaller(app, item, folder, update) }
}
fun update(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
Thread({
val item = CatalogItem(
Store.BATTLENET, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true,
extra = mapOf(INSTALL_UID to installUid(app, game)),
)
game.folder.parentFile?.parentFile?.let { com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, it) }
enqueue(app, item, game.folder, update = true)
}, "battlenet-update").start()
}
internal const val INSTALL_UID = "installUid"
internal fun installUid(context: Context, game: InstalledStoreGame): String =
runCatching { BattleNet.games(context).firstOrNull { it.uid == game.sidecar.id }?.installUid }.getOrNull() ?: game.sidecar.id
fun uninstall(context: Context, game: InstalledStoreGame): Boolean {
if (product(game.sidecar.id) == null || !BattleNet.installed(context)) return false
val done = agentUninstall(context, installUid(context, game))
if (done) StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) }
return done
}
internal fun agentUninstall(context: Context, uid: String): Boolean {
val stop = AtomicBoolean(false)
val started = AtomicBoolean(false)
val done = AtomicBoolean(false)
val guard = Thread({
try {
Thread.sleep(START_WAIT_MS)
if (!started.get()) stop.set(true)
} catch (_: InterruptedException) {
}
}, "battlenet-uninstall-wait").apply { isDaemon = true; start() }
val code = runCatching {
run(context, listOf("agent-uninstall", uid), stop) { line ->
if (line == STATE + "starting") started.set(true)
if (line.startsWith(DONE)) done.set(true)
}
}.onFailure { Log.w(TAG, "uninstall $uid", it) }.getOrDefault(-1)
guard.interrupt()
Log.i(TAG, "uninstall $uid: ${if (done.get()) "done" else if (stop.get()) "Battle.net stayed busy" else "exit $code"}")
return done.get()
}
internal fun buildKey(text: String): Pair<String, String>? {
val rows = text.lines().filter { it.isNotBlank() }
if (rows.size < 2) return null
val head = rows[0].split('|').map { it.substringBefore('!') }
val branch = head.indexOf("Branch")
val active = head.indexOf("Active")
val key = head.indexOf("Build Key")
if (branch < 0 || key < 0) return null
val row = rows.drop(1).map { it.split('|') }.firstOrNull { active < 0 || it.getOrNull(active) == "1" } ?: return null
val region = row.getOrNull(branch)?.takeIf { it.matches(Regex("[a-z]{2}")) } ?: return null
val build = row.getOrNull(key)?.takeIf { it.matches(Regex("[0-9a-f]{32}")) } ?: return null
return region to build
}
internal fun latestBuild(text: String, region: String): String? {
val rows = text.lines().filter { it.isNotBlank() && !it.startsWith("##") }
if (rows.isEmpty()) return null
val head = rows[0].split('|').map { it.substringBefore('!') }
val at = head.indexOf("Region")
val key = head.indexOf("BuildConfig")
if (at < 0 || key < 0) return null
return rows.drop(1).map { it.split('|') }.firstOrNull { it.getOrNull(at) == region }?.getOrNull(key)
?.takeIf { it.matches(Regex("[0-9a-f]{32}")) }
}
fun checkUpdate(context: Context, game: InstalledStoreGame, force: Boolean = false) = check(game.sidecar.id, game.folder, force)
internal fun check(id: String, folder: File, force: Boolean) {
val product = product(id) ?: return
val now = System.currentTimeMillis()
synchronized(checkedAt) {
if (!force && now - (checkedAt[id] ?: 0L) < CHECK_AGAIN_MS) return
checkedAt[id] = now
}
fun retryLater() = synchronized(checkedAt) { if (checkedAt[id] == now) checkedAt.remove(id) }
checks.execute {
val local = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull()
?: return@execute retryLater()
val latest = runCatching { latestBuild(fetch(VERSIONS.format(Locale.ROOT, local.first, product)), local.first) }
.onFailure { Log.w(TAG, "versions of $product: ${it.javaClass.simpleName}") }.getOrNull()
?: return@execute retryLater()
val behind = latest != local.second
Log.i(TAG, "$id: ${if (behind) "update available" else "up to date"}")
StoresState.post { if (behind) updates[id] = true else updates.remove(id) }
}
}
private fun fetch(url: String): String {
val conn = (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = 15_000
readTimeout = 15_000
setRequestProperty("User-Agent", "DroidDeck")
}
try {
if (conn.responseCode != 200) throw java.io.IOException("HTTP ${conn.responseCode}")
return conn.inputStream.bufferedReader().use { it.readText() }
} finally {
conn.disconnect()
}
}
internal fun failure(context: Context, reason: String?, code: Int): String {
val detail = when {
reason == null -> "exit $code"
reason == "client" -> return context.getString(R.string.bnet_dl_client_first)
reason.startsWith("agent ") -> context.getString(R.string.bnet_dl_agent_error, reason.removePrefix("agent "))
else -> reason.removePrefix("stopped ")
}
return context.getString(R.string.bnet_dl_failed, detail)
}
internal fun localeTag(context: Context): String = locale(StoreLanguage.localeFor(null, context))
internal enum class Step { PREPARING, DOWNLOADING, APPLYING }
internal fun step(state: Int, phase: Int, current: Long, total: Long): Step = when {
state == DONE_STATE || phase == APPLY_PHASE || total > 0L && current >= total -> Step.APPLYING
total > 0L -> Step.DOWNLOADING
else -> Step.PREPARING
}
private const val DONE_STATE = 1004
private const val APPLY_PHASE = 2000
}
internal class BattleNetInstaller(
private val app: Context,
private val item: CatalogItem,
private val folder: File,
private val update: Boolean,
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val started = AtomicBoolean(false)
private val ended = java.util.concurrent.CountDownLatch(1)
private var before = 0L
private var kept = -1L
override fun run(handle: DownloadQueue.JobHandle): String? {
started.set(true)
try {
return if (cancelled.get()) null else work(handle)
} finally {
ended.countDown()
}
}
private fun work(handle: DownloadQueue.JobHandle): String? {
before = DownloadQueue.entry(handle.key)?.bytesTotal ?: 0L
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting))
if (!BattleNet.installed(app)) throw IllegalStateException(app.getString(R.string.bnet_dl_client_first))
val title = BattleNet.title(item.id)
val product = title?.product ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, item.id))
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: title.uid
if (!update) folder.mkdirs()
val guest = AddedGames.guestPath(app, folder) ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, folder.path))
val (country, region) = BattleNetInstall.country(Locale.getDefault())
val args = if (update) listOf("agent-update", uid)
else listOf("agent-install", uid, product, guest, BattleNetInstall.localeTag(app), country, region)
var done: JSONObject? = null
var reason: String? = null
val code = BattleNetInstall.run(app, args, cancelled) { line ->
when {
line.startsWith(BattleNetInstall.PROGRESS) ->
runCatching { JSONObject(line.removePrefix(BattleNetInstall.PROGRESS)) }.getOrNull()?.let { progress(handle, it) }
line == BattleNetInstall.STATE + "waiting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_waiting))
line == BattleNetInstall.STATE + "queued" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_queued))
line == BattleNetInstall.STATE + "starting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting))
line.startsWith(BattleNetInstall.DONE) -> done = runCatching { JSONObject(line.removePrefix(BattleNetInstall.DONE)) }.getOrNull()
line.startsWith(BattleNetInstall.ERROR) -> reason = line.removePrefix(BattleNetInstall.ERROR)
}
}
if (cancelled.get()) return null
if (done == null) throw IllegalStateException(BattleNetInstall.failure(app, reason, code))
handle.log("Battle.net: ${item.title} ${if (update) "updated" else "installed"} ${done?.optString("version").orEmpty()}".trimEnd())
StoresState.post {
BattleNetInstall.updates.remove(item.id)
StoresState.notifyLibraryChanged(app)
}
BattleNetInstall.check(item.id, folder, force = true)
return folder.absolutePath
}
private fun progress(handle: DownloadQueue.JobHandle, status: JSONObject) {
val current = status.optLong("download_current", 0L)
val total = status.optLong("download_total", 0L)
when (BattleNetInstall.step(status.optInt("state", 0), status.optInt("phase", 0), current, total)) {
BattleNetInstall.Step.PREPARING -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_stage_checking))
BattleNetInstall.Step.DOWNLOADING -> {
if (kept < 0L) kept = (before - total).coerceAtLeast(0L)
handle.progress(kept + current, kept + total)
}
BattleNetInstall.Step.APPLYING -> handle.stage(DownloadStage.INSTALL)
}
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (!deleteFiles || update) return
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: BattleNet.title(item.id)?.uid ?: return
Thread({
if (started.get() && !ended.await(END_WAIT_S, TimeUnit.SECONDS)) Log.w("BattleNetInstall", "the cancelled install of $uid is still stopping")
val gone = BattleNetInstall.agentUninstall(app, uid)
if (folder.isDirectory && (gone || folder.list().isNullOrEmpty())) com.droiddeck.launcher.core.FileUtils.delete(folder)
Log.i("BattleNetInstall", "cancelled install of $uid: ${if (gone) "removed" else "left for Battle.net to remove"}")
}, "battlenet-cancel").start()
}
}
private const val END_WAIT_S = 120L
@@ -189,9 +189,15 @@ object BattleNetBackend : StoreBackend {
override fun search(context: Context, query: String): List<CatalogItem> =
BattleNet.STORE.filter { it.name.contains(query, ignoreCase = true) }.map { item(context, it) }
override fun install(context: Context, item: CatalogItem, root: File) = BattleNetClient.installGame(context, item.id, root)
override fun install(context: Context, item: CatalogItem, root: File) {
if (!BattleNetInstall.headless(item)) return BattleNetClient.installGame(context, item.id, root)
val app = context.applicationContext
BattleNetInstall.enqueue(app, item, StoreInstallRoot.folderFor(app, store, item.id, item.title, root))
}
override fun uninstall(context: Context, game: InstalledStoreGame) = BattleNetClient.open(emptyList())
override fun uninstall(context: Context, game: InstalledStoreGame) {
if (!BattleNetInstall.uninstall(context, game)) BattleNetClient.open(emptyList())
}
fun installed(context: Context): List<BattleNet.Game> = if (BattleNet.installed(context)) BattleNet.games(context) else emptyList()
@@ -19,6 +19,11 @@ internal object ItchApi {
fun ownedKeys(key: String, page: Int): JSONObject? = get("/profile/owned-keys?page=$page&per_page=500", key)
fun collections(key: String): JSONArray? = get("/profile/collections", key)?.optJSONArray("collections")
fun collectionGames(key: String, collectionId: String, page: Int): JSONObject? =
get("/collections/$collectionId/collection-games?page=$page", key)
fun uploads(key: String, gameId: String, downloadKeyId: String): JSONArray? =
get("/games/$gameId/uploads" + keyQuery(downloadKeyId), key)?.optJSONArray("uploads")
@@ -0,0 +1,116 @@
package com.droiddeck.launcher.stores.itch
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.ConcurrentHashMap
internal class ItchCollection(val id: String, val title: String, val count: Int)
internal object ItchCollections {
var list by mutableStateOf<List<ItchCollection>>(emptyList())
private set
var selected by mutableStateOf<String?>(null)
private set
private val games = mutableStateMapOf<String, List<CatalogItem>>()
private val loading = ConcurrentHashMap.newKeySet<String>()
@Volatile private var generation = 0
fun items(): List<CatalogItem> = games.values.flatten()
fun gamesOf(id: String): List<CatalogItem>? = games[id]
fun chosen(): ItchCollection? = list.firstOrNull { it.id == selected }
fun clear() {
generation++
StoresState.post {
list = emptyList()
selected = null
games.clear()
}
}
fun load(context: Context) {
val app = context.applicationContext
val started = generation
val guard = "$started:"
if (!loading.add(guard)) return
Thread({
try {
val key = ItchAuth.key(app)
if (key.isBlank()) return@Thread
val parsed = parseCollections(ItchApi.collections(key) ?: return@Thread)
if (started != generation) return@Thread
StoresState.post {
if (started != generation) return@post
list = parsed
if (selected != null && parsed.none { it.id == selected }) selected = null
}
StoresState.logLine("itch.io: ${parsed.size} collections")
selected?.let { fetchGames(key, it, started) }
} finally {
loading.remove(guard)
}
}, "itch-collections").start()
}
fun select(context: Context, id: String?) {
selected = id
if (id == null) return
val app = context.applicationContext
val started = generation
Thread({
val key = ItchAuth.key(app)
if (key.isNotBlank()) fetchGames(key, id, started)
}, "itch-collection-games").start()
}
private fun fetchGames(key: String, id: String, started: Int) {
val guard = "$started:$id"
if (!loading.add(guard)) return
try {
val out = ArrayList<CatalogItem>()
val seen = HashSet<String>()
var page = 1
while (true) {
val body = ItchApi.collectionGames(key, id, page)
if (body == null) {
StoresState.logLine("itch.io: collection $id page $page failed")
return
}
val batch = parseGames(body)
if (batch.isEmpty()) break
val before = out.size
out.addAll(batch.filter { seen.add(it.id) })
if (out.size == before) break
page++
}
val distinct = out.toList()
StoresState.post { if (started == generation) games[id] = distinct }
StoresState.logLine("itch.io: collection $id has ${distinct.size} games")
} finally {
loading.remove(guard)
}
}
internal fun parseCollections(array: JSONArray): List<ItchCollection> = (0 until array.length()).mapNotNull { i ->
val c = array.optJSONObject(i) ?: return@mapNotNull null
val id = c.opt("id")?.toString().orEmpty().takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
val title = c.optString("title").ifBlank { return@mapNotNull null }
ItchCollection(id, title, c.optInt("games_count", c.optInt("gamesCount")))
}
internal fun parseGames(body: JSONObject): List<CatalogItem> {
val rows = body.optJSONArray("collection_games") ?: body.optJSONArray("collectionGames") ?: return emptyList()
return (0 until rows.length()).mapNotNull { i ->
rows.optJSONObject(i)?.optJSONObject("game")?.let { ItchLibrary.item(it, "") }
}
}
}
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.stores.xbox
import androidx.compose.foundation.shape.CircleShape
import com.droiddeck.launcher.ui.focusGlide
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
@@ -45,7 +47,7 @@ class XboxCloudSettingsActivity : ComponentActivity() {
}
Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).verticalScroll(rememberScrollState())) {
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
OutlinedButton(onClick = { finish() }) { Text("Back") }
OutlinedButton(onClick = { finish() }, modifier = Modifier.focusGlide(CircleShape)) { Text("Back") }
Text("Xbox Cloud Gaming", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 16.dp))
}
@@ -1,5 +1,8 @@
package com.droiddeck.launcher.stores.xbox
import com.droiddeck.launcher.ui.glideBorder
import androidx.compose.foundation.shape.CircleShape
import com.droiddeck.launcher.ui.focusGlide
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
@@ -16,7 +19,6 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.foundation.border
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.detectTapGestures
@@ -148,7 +150,7 @@ private fun PanelContent(
Toggle("Toon", "Cartoon outlines.", settings.toon) { onChange(settings.copy(toon = it)) }
Choice("Frame-rate cap", listOf(0 to "Off", 30 to "30 fps", 45 to "45 fps", 60 to "60 fps"), settings.maxFps) { onChange(settings.copy(maxFps = it)) }
Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = { onChange(settings.withoutEffects()) }) { Text("Reset picture") }
OutlinedButton(onClick = { onChange(settings.withoutEffects()) }, modifier = Modifier.focusGlide(CircleShape)) { Text("Reset picture") }
}
Text("Effects cost a little GPU time; with none set the stream is shown directly.", style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))
@@ -220,7 +222,7 @@ private fun SettingRow(
Row(
Modifier.fillMaxWidth().padding(vertical = 1.dp).clip(shape)
.background(if (focused) cs.primary.copy(alpha = 0.16f) else Color.Transparent)
.border(2.dp, if (focused) cs.primary else Color.Transparent, shape)
.glideBorder(focused, shape, cs.primary, hotFillAlpha = 0f)
.let { if (panel != null && index >= 0) it.focusRequester(panel.requester(index)) else it }
.onFocusChanged { state -> focused = state.isFocused; if (state.isFocused && index >= 0) panel?.onFocused?.invoke(index) }
.onKeyEvent { event ->
@@ -299,8 +301,9 @@ internal fun XboxMenuEntry(title: String, note: String?, focus: FocusRequester?
val shape = RoundedCornerShape(10.dp)
androidx.compose.material3.Surface(
onClick = onClick, color = if (focused) cs.primary.copy(alpha = 0.2f) else cs.surfaceContainerHigh, shape = shape,
border = if (focused) androidx.compose.foundation.BorderStroke(2.dp, cs.primary) else null,
border = null,
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 3.dp)
.glideBorder(focused, shape, cs.primary, hotFillAlpha = 0f)
.let { if (focus != null) it.focusRequester(focus) else it }
.onFocusChanged { state -> focused = state.isFocused; if (state.isFocused) onFocused() }
.onKeyEvent { event -> if (event.type == KeyEventType.KeyDown && event.key == Key.ButtonA) { onClick(); true } else false },
@@ -36,6 +36,7 @@ class XboxLoginActivity : ComponentActivity() {
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
host = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setBackgroundColor(Color.BLACK) }
status = TextView(this).apply { setTextColor(Color.WHITE); text = "Preparing Microsoft sign-in…"; setPadding(24, 16, 24, 16) }
host.addView(status)
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.stores.xbox
import androidx.compose.foundation.shape.CircleShape
import com.droiddeck.launcher.ui.focusGlide
import android.content.Context
import android.content.Intent
import android.graphics.Color
@@ -181,10 +183,10 @@ class XboxNativePlayerActivity : ComponentActivity() {
fun NoticeButton(label: String, focus: androidx.compose.ui.focus.FocusRequester?, onClick: () -> Unit) =
androidx.compose.material3.TextButton(onClick = onClick,
modifier = androidx.compose.ui.Modifier.let { if (focus != null) it.focusRequester(focus) else it }
.onKeyEvent { e -> if (e.type == KeyEventType.KeyDown && e.key == Key.ButtonA) { onClick(); true } else false }) {
.onKeyEvent { e -> if (e.type == KeyEventType.KeyDown && e.key == Key.ButtonA) { onClick(); true } else false }.focusGlide(CircleShape)) {
androidx.compose.material3.Text(label)
}
androidx.compose.material3.AlertDialog(
com.droiddeck.launcher.ui.GlideAlertDialog(
onDismissRequest = { finish() },
properties = androidx.compose.ui.window.DialogProperties(dismissOnClickOutside = false),
title = { androidx.compose.material3.Text(title) },
@@ -88,7 +88,7 @@ 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 androidx.compose.ui.window.Dialog
import com.droiddeck.launcher.ui.GlideDialog as Dialog
import androidx.compose.ui.window.DialogProperties
import coil.compose.AsyncImage
import coil.request.ImageRequest
@@ -475,7 +475,7 @@ internal fun TextEntryDialog(title: String, initial: String, onDismiss: () -> Un
AppDialog(shown, close, "textEntry", wide = false, maxWidth = 460.dp) {
DialogTitleRow(title, onClose = close)
androidx.compose.material3.OutlinedTextField(
value, { value = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusRequester(focus),
value, { value = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusRequester(focus).focusGlide(),
keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { onSave(value.trim()); close() }),
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Done),
)
@@ -644,7 +644,7 @@ private fun SgdbSearchDialog(
SmallIconButton(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.common_back), colors.onBackground, onClick = back)
})
androidx.compose.material3.OutlinedTextField(
query, { query = it }, singleLine = true, modifier = Modifier.fillMaxWidth(),
query, { query = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusGlide(),
label = { Text(stringResource(R.string.art_sgdb_search_label)) },
keyboardActions = androidx.compose.foundation.text.KeyboardActions(onSearch = { leaveField(); search() }),
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Search),
@@ -0,0 +1,959 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.FilterAlt
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material.icons.filled.Widgets
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.zIndex
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.HomeFolders
import com.droiddeck.launcher.HomeHidden
import com.droiddeck.launcher.HomePins
import android.content.pm.ShortcutInfo
import android.graphics.Bitmap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import com.droiddeck.launcher.HomeWidgets
import com.droiddeck.launcher.R
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
private sealed interface AppEntry : AppEntryKey {
val key: String
class App(val app: HomeApp.LaunchableApp) : AppEntry {
override val label get() = app.label
override val key get() = "app:" + app.key
override val installedAt get() = app.installedAt
override val updatedAt get() = app.updatedAt
}
class Folder(val folder: HomeFolders.Folder, val apps: List<HomeApp.LaunchableApp>) : AppEntry {
override val label get() = folder.name
override val key get() = "folder:" + folder.id
override val installedAt get() = apps.maxOf { it.installedAt }
override val updatedAt get() = apps.maxOf { it.updatedAt }
}
class Shortcut(val pinned: HomePins.Pinned) : AppEntry {
override val label get() = pinned.label
override val key get() = pinned.key
override val installedAt get() = 0L
override val updatedAt get() = 0L
}
}
private fun indexLetter(label: String): String {
val c = label.trim().firstOrNull()?.uppercaseChar() ?: return "#"
return if (c in 'A'..'Z') c.toString() else if (c.isLetter()) c.toString() else "#"
}
private fun searchRank(label: String, q: String): Int? {
if (label.startsWith(q, ignoreCase = true)) return 0
if (label.split(' ', '-', '_', '.').any { it.startsWith(q, ignoreCase = true) }) return 1
if (label.contains(q, ignoreCase = true)) return 2
return null
}
internal fun Context.findActivity(): Activity? {
var c: Context? = this
while (c is ContextWrapper) {
if (c is Activity) return c
c = c.baseContext
}
return null
}
private fun Modifier.menuKey(onMenu: () -> Unit): Modifier = onPreviewKeyEvent { event ->
val k = event.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y && k.keyCode != KeyEvent.KEYCODE_MENU) false
else {
if (k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) onMenu()
true
}
}
internal object AppsView {
const val ALL = "all"
const val GAMES = "games"
const val DOWNLOADED = "downloaded"
const val SYSTEM = "system"
const val HIDDEN = "hidden"
val FILTERS = listOf(ALL, GAMES, DOWNLOADED, SYSTEM, HIDDEN)
const val NAME_ASC = "nameAsc"
const val NAME_DESC = "nameDesc"
const val INSTALLED = "installed"
const val UPDATED = "updated"
val SORTS = listOf(NAME_ASC, NAME_DESC, INSTALLED, UPDATED)
var filter by mutableStateOf(ALL)
var sort by mutableStateOf(NAME_ASC)
private var loaded = false
private fun prefs(context: Context) = context.getSharedPreferences("home_launcher", Context.MODE_PRIVATE)
fun load(context: Context) {
if (loaded) return
loaded = true
val p = prefs(context)
filter = p.getString("filter", ALL)?.takeIf { it in FILTERS } ?: ALL
sort = p.getString("sort", NAME_ASC)?.takeIf { it in SORTS } ?: NAME_ASC
}
fun setFilter(context: Context, value: String) {
filter = value
prefs(context).edit().putString("filter", value).apply()
}
fun setSort(context: Context, value: String) {
sort = value
prefs(context).edit().putString("sort", value).apply()
}
fun keeps(app: HomeApp.LaunchableApp): Boolean {
val hidden = app.key in HomeHidden.keys
return when (filter) {
HIDDEN -> hidden
GAMES -> !hidden && app.game
DOWNLOADED -> !hidden && !app.system
SYSTEM -> !hidden && app.system
else -> !hidden
}
}
fun comparator(): Comparator<AppEntryKey> = when (sort) {
NAME_DESC -> compareBy<AppEntryKey, String>(String.CASE_INSENSITIVE_ORDER) { it.label }.reversed()
INSTALLED -> compareByDescending<AppEntryKey> { it.installedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label }
UPDATED -> compareByDescending<AppEntryKey> { it.updatedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label }
else -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }
}
}
internal interface AppEntryKey {
val label: String
val installedAt: Long
val updatedAt: Long
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) {
val ctx = LocalContext.current
remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); true }
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
val padH = if (narrow) 16.dp else 22.dp
var query by rememberSaveable { mutableStateOf("") }
var openFolder by rememberSaveable { mutableStateOf<String?>(null) }
var renameOnOpen by rememberSaveable { mutableStateOf(false) }
var picking by rememberSaveable { mutableStateOf(false) }
val folders = HomeFolders.folders
val byKey = remember(s.androidApps) { s.androidApps.associateBy { it.key } }
val byPkg = remember(s.androidApps) { s.androidApps.filterNot { it.work }.groupBy { it.packageName }.mapNotNull { (pkg, apps) -> apps.singleOrNull()?.let { pkg to it } }.toMap() }
LaunchedEffect(byPkg) { if (byPkg.isNotEmpty()) HomeFolders.migrateMembers(ctx) { byPkg[it]?.key } }
val member: (String) -> HomeApp.LaunchableApp? = { byKey[it] ?: byPkg[it] }
val pins = HomePins.pinned
val hidden = HomeHidden.keys
val q = query.trim()
val filter = AppsView.filter
val sort = AppsView.sort
val entries: List<AppEntry> = remember(s.androidApps, folders, q, filter, sort, pins, hidden) {
val kept = s.androidApps.filter { AppsView.keeps(it) }
val shortcuts = if (filter == AppsView.ALL) pins.map { AppEntry.Shortcut(it) } else emptyList()
if (q.isNotEmpty()) {
(kept.map { AppEntry.App(it) } + shortcuts).mapNotNull { e -> searchRank(e.label, q)?.let { it to e } }
.sortedWith(compareBy<Pair<Int, AppEntry>> { it.first }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.second.label })
.map { it.second }
} else if (filter != AppsView.ALL) {
kept.map { AppEntry.App(it) }.sortedWith(AppsView.comparator())
} else {
val folderEntries = folders.mapNotNull { f ->
val apps = f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
if (apps.isEmpty()) null else AppEntry.Folder(f, apps)
}
val grouped = folderEntries.flatMap { f -> f.apps.map { it.key } }.toSet()
(folderEntries + kept.filter { it.key !in grouped }.map { AppEntry.App(it) } + shortcuts).sortedWith(AppsView.comparator())
}
}
val grid = rememberLazyGridState()
LaunchedEffect(q, filter, sort) { grid.scrollToItem(0) }
val widgetsShown = q.isEmpty() && filter == AppsView.ALL && HomeWidgets.widgets.isNotEmpty()
val leadItems = if (widgetsShown) 1 else 0
val byName = sort == AppsView.NAME_ASC || sort == AppsView.NAME_DESC
val newFolder: (HomeApp.LaunchableApp) -> Unit = { app ->
val f = HomeFolders.create(ctx, ctx.getString(R.string.apps_folder_default), app.key)
renameOnOpen = true
openFolder = f.id
}
Box(modifier) {
Column(Modifier.fillMaxSize().imePadding()) {
Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = if (narrow) 8.dp else 12.dp)) {
ModeHeader(
stringResource(R.string.content_android_apps), query, { query = it },
placeholder = stringResource(R.string.apps_search_hint),
clearSearchFocus = openFolder != null || picking,
lead = {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
Text(stringResource(R.string.content_android_apps), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
val shownCount = s.androidApps.count { AppsView.keeps(it) } + if (filter == AppsView.ALL) pins.size else 0
Text(androidx.compose.ui.res.pluralStringResource(R.plurals.apps_count, shownCount, shownCount), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
},
) {
AppsFilterButton()
AppsSortButton()
HeaderIconButton(stringResource(R.string.apps_add_widget), Icons.Filled.Widgets, "add-widget") {
HomeWidgets.loadProviders(ctx)
picking = true
}
}
}
Box(Modifier.weight(1f).fillMaxWidth()) {
val scroller = q.isEmpty() && byName && entries.size > 16
LazyVerticalGrid(
columns = GridCells.Adaptive(if (narrow) 84.dp else 96.dp),
state = grid,
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(start = padH, end = if (scroller) padH + 22.dp else padH, top = 12.dp, bottom = 16.dp),
modifier = Modifier.fillMaxSize(),
) {
if (widgetsShown) item(key = "widgets", span = { GridItemSpan(maxLineSpan) }) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val maxW = maxWidth
FlowRow(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp),
) {
for (w in HomeWidgets.widgets) key(w.id) { WidgetCard(w, maxW.value.toInt()) }
}
}
}
if (entries.isEmpty()) item(key = "empty", span = { GridItemSpan(maxLineSpan) }) {
Note(
when {
q.isNotEmpty() -> stringResource(R.string.apps_no_match, q)
filter == AppsView.HIDDEN -> stringResource(R.string.apps_hidden_none)
else -> stringResource(R.string.content_no_android_apps)
},
)
}
items(entries, key = { it.key }) { entry ->
when (entry) {
is AppEntry.App -> AppTile(
entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder,
first = entry === entries.first(),
)
is AppEntry.Shortcut -> PinnedTile(entry.pinned, first = entry === entries.first())
is AppEntry.Folder -> FolderTile(entry, first = entry === entries.first(), onOpen = { renameOnOpen = false; openFolder = entry.folder.id }) {
renameOnOpen = true
openFolder = entry.folder.id
}
}
}
}
if (scroller) AlphabetScroller(entries, grid, leadItems, Modifier.align(Alignment.CenterEnd).fillMaxHeight().padding(end = 4.dp, top = 8.dp, bottom = 8.dp))
}
}
val folder = folders.firstOrNull { it.id == openFolder }
LaunchedEffect(folder == null, openFolder) { if (folder == null && openFolder != null) openFolder = null }
AnimatedVisibility(
folder != null, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
modifier = Modifier.fillMaxSize().zIndex(2f),
) {
var last by remember { mutableStateOf(folder) }
if (folder != null) last = folder
last?.let { f ->
FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder) {
openFolder = null
renameOnOpen = false
}
}
}
AnimatedVisibility(
picking, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
modifier = Modifier.fillMaxSize().zIndex(3f),
) { WidgetPicker(padH) { picking = false } }
}
}
@Composable
private fun SwipeLock() {
DisposableEffect(Unit) {
PageSwipe.locks++
onDispose { PageSwipe.locks-- }
}
}
@Composable
private fun appsFilterLabel(filter: String): String = stringResource(
when (filter) {
AppsView.GAMES -> R.string.apps_filter_games
AppsView.DOWNLOADED -> R.string.apps_filter_downloaded
AppsView.SYSTEM -> R.string.apps_filter_system
AppsView.HIDDEN -> R.string.apps_filter_hidden
else -> R.string.apps_filter_all
},
)
@Composable
private fun appsSortLabel(sort: String): String = stringResource(
when (sort) {
AppsView.NAME_DESC -> R.string.apps_sort_name_desc
AppsView.INSTALLED -> R.string.apps_sort_installed
AppsView.UPDATED -> R.string.apps_sort_updated
else -> R.string.apps_sort_name_asc
},
)
@Composable
private fun AppsFilterButton() = HeaderChoiceButton(
stringResource(R.string.apps_filter), Icons.Filled.FilterAlt, "apps-filter",
AppsView.FILTERS, AppsView.filter, { appsFilterLabel(it) }, AppsView::setFilter,
)
@Composable
private fun AppsSortButton() = HeaderChoiceButton(
stringResource(R.string.stores_sort), Icons.Filled.Sort, "apps-sort",
AppsView.SORTS, AppsView.sort, { appsSortLabel(it) }, AppsView::setSort,
)
@Composable
private fun HeaderChoiceButton(
title: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String,
options: List<String>, current: String, label: @Composable (String) -> String, onPick: (Context, String) -> Unit,
) {
val pal = LocalPalette.current
val ctx = LocalContext.current
var at by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
HeaderIconButton("$title · ${label(current)}", icon, key) {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = options.size,
handle = { Icon(icon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
) {
StepTitle(title)
StepList {
options.forEachIndexed { i, option ->
StepChoice(
label(option), selected = option == current, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (option == current) Modifier.focusRequester(first) else Modifier),
) {
onPick(ctx, option)
Steps.fold()
}
}
}
})
}
}
}
@Composable
private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scope = rememberCoroutineScope()
val firstAt = remember(entries) {
val map = LinkedHashMap<String, Int>()
entries.forEachIndexed { i, e -> map.putIfAbsent(indexLetter(e.label), i) }
map
}
val letters = remember(firstAt) { firstAt.keys.toList() }
var dragging by remember { mutableStateOf<String?>(null) }
val current by remember(entries, leadItems) {
derivedStateOf {
val i = (grid.firstVisibleItemIndex - leadItems).coerceIn(0, (entries.size - 1).coerceAtLeast(0))
entries.getOrNull(i)?.let { indexLetter(it.label) }
}
}
var height by remember { mutableIntStateOf(1) }
val jump: (Float) -> Unit = { y ->
val i = ((y / height) * letters.size).toInt().coerceIn(0, letters.size - 1)
val letter = letters[i]
if (letter != dragging) {
dragging = letter
val at = firstAt[letter] ?: 0
scope.launch { grid.scrollToItem(if (at == 0) 0 else leadItems + at) }
}
}
Box(modifier.width(22.dp)) {
Column(
verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
.clip(RoundedCornerShape(11.dp))
.background(if (dragging != null) colors.surface.copy(alpha = 0.85f) else Color.Transparent)
.onSizeChanged { height = it.height.coerceAtLeast(1) }
.pointerInput(letters) {
awaitEachGesture {
val down = awaitFirstDown()
down.consume()
jump(down.position.y)
while (true) {
val event = awaitPointerEvent()
val c = event.changes.firstOrNull { it.id == down.id } ?: break
if (!c.pressed) break
c.consume()
jump(c.position.y)
}
dragging = null
}
},
) {
for (l in letters) {
val on = l == (dragging ?: current)
Text(
l, fontSize = 10.sp, lineHeight = 11.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Medium,
color = if (on) pal.signal else colors.onSurfaceVariant, textAlign = TextAlign.Center,
)
}
}
dragging?.let { l ->
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.align(Alignment.Center).offset { IntOffset(-64.dp.roundToPx(), 0) }.size(56.dp)
.clip(CircleShape).background(pal.signal),
) { Text(l, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = pal.onPrimary) }
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TileFrame(
id: String, first: Boolean, onClick: () -> Unit, onMenu: () -> Unit,
content: @Composable (hot: Boolean) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.95f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "appScale")
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
.paneItem("tile:$id").then(if (first) Modifier.firstTile().paneEntry() else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(Shape12)
.background(if (hot) colors.surface else colors.surface.copy(alpha = 0.55f))
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
.hoverable(src)
.combinedClickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onLongClick = onMenu, onClick = onClick)
.controllerConfirm(onClick = onClick)
.menuKey(onMenu)
.padding(horizontal = 6.dp, vertical = 10.dp),
) { content(hot) }
}
@Composable
private fun TileLabel(text: String) = Text(
text, fontSize = 12.sp, lineHeight = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
)
@Composable
private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.Dp) {
val icon = app.icon
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(size))
else Box(Modifier.size(size).clip(CircleShape).background(artBrush(hueOf(app.label))))
}
@Composable
private fun AppTile(
app: HomeApp.LaunchableApp, folderId: String?, first: Boolean,
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
) {
var menu by remember { mutableStateOf(false) }
Box {
TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) {
AppIcon(app, 52.dp)
TileLabel(app.label)
}
AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder)
}
}
@Composable
private fun AppMenu(
app: HomeApp.LaunchableApp, folderId: String?, open: Boolean,
onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
) {
val ctx = LocalContext.current
var choosing by remember { mutableStateOf(false) }
var shortcuts by remember { mutableStateOf<List<Pair<ShortcutInfo, Bitmap?>>>(emptyList()) }
LaunchedEffect(open) {
if (!open) {
choosing = false
return@LaunchedEffect
}
shortcuts = withContext(Dispatchers.IO) {
HomeApp.shortcuts(ctx, app).map { it to HomeApp.shortcutIcon(ctx, it, 64) }
}
}
val isHidden = app.key in HomeHidden.keys
AnchoredMenu(open, onDismiss = onDismiss, title = app.label, compact = true, minWidth = 200.dp) { first ->
if (choosing) {
val others = HomeFolders.folders.filter { it.id != folderId }
var firstUsed = false
for (f in others) key(f.id) {
MenuItem(f.name, checked = false, focusRequester = if (!firstUsed) first.also { firstUsed = true } else null) {
HomeFolders.add(ctx, f.id, app.key)
onDismiss()
}
}
MenuItem(stringResource(R.string.apps_new_folder), checked = false, focusRequester = if (others.isEmpty()) first else null) {
onDismiss()
onNewFolder(app)
}
} else {
shortcuts.forEachIndexed { i, (info, icon) ->
key(info.id) {
MenuItem(
info.shortLabel?.toString().orEmpty(), checked = false,
focusRequester = if (i == 0) first else null,
leading = { MenuIcon(icon) },
) {
onDismiss()
runCatching { HomeApp.startShortcut(ctx, info) }
}
}
}
if (shortcuts.isNotEmpty()) Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(LocalPalette.current.line))
if (!isHidden) MenuItem(stringResource(R.string.apps_add_to_folder), checked = false, focusRequester = if (shortcuts.isEmpty()) first else null) { choosing = true }
if (folderId != null) MenuItem(stringResource(R.string.apps_remove_from_folder), checked = false) {
HomeFolders.remove(ctx, app.key)
onDismiss()
}
MenuItem(stringResource(if (isHidden) R.string.apps_unhide else R.string.apps_hide), checked = false,
focusRequester = if (isHidden && shortcuts.isEmpty()) first else null) {
onDismiss()
HomeHidden.set(ctx, app.key, !isHidden)
}
MenuItem(stringResource(R.string.apps_app_info), checked = false) {
onDismiss()
runCatching { HomeApp.openAppInfo(ctx, app) }
}
if (HomeApp.canUninstall(app)) MenuItem(stringResource(R.string.apps_uninstall), checked = false) {
onDismiss()
runCatching { HomeApp.uninstall(ctx, app) }
}
}
}
}
@Composable
private fun MenuIcon(icon: Bitmap?) {
if (icon != null) Image(icon.asImageBitmap(), null, modifier = Modifier.size(20.dp))
else Spacer(Modifier.size(20.dp))
}
@Composable
private fun PinnedTile(pinned: HomePins.Pinned, first: Boolean) {
val ctx = LocalContext.current
var menu by remember { mutableStateOf(false) }
Box {
TileFrame(pinned.key, first, onClick = { runCatching { HomeApp.startShortcut(ctx, pinned.info) } }, onMenu = { menu = true }) {
Box {
val icon = pinned.icon
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp))
else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label))))
}
TileLabel(pinned.label)
}
AnchoredMenu(menu, onDismiss = { menu = false }, title = pinned.label, compact = true, minWidth = 180.dp) { firstItem ->
MenuItem(stringResource(R.string.apps_shortcut_remove), checked = false, detail = pinned.appLabel, focusRequester = firstItem) {
menu = false
HomePins.unpin(ctx, pinned)
}
}
}
}
@Composable
private fun FolderIcon(apps: List<HomeApp.LaunchableApp>, size: androidx.compose.ui.unit.Dp) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val cell = (size - 14.dp) / 2
Box(
Modifier.size(size).clip(RoundedCornerShape(size / 3.5f)).background(colors.surfaceVariant)
.glideBorder(false, RoundedCornerShape(size / 3.5f), pal.signal, pal.line2)
.padding(5.dp),
) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
for (row in apps.take(4).chunked(2)) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
for (a in row) AppIcon(a, cell)
}
}
}
}
@Composable
private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Unit, onRename: () -> Unit) {
val ctx = LocalContext.current
var menu by remember { mutableStateOf(false) }
Box {
TileFrame(entry.key, first, onClick = onOpen, onMenu = { menu = true }) {
FolderIcon(entry.apps, 52.dp)
TileLabel(entry.folder.name)
}
AnchoredMenu(menu, onDismiss = { menu = false }, title = entry.folder.name, compact = true, minWidth = 160.dp) { firstItem ->
MenuItem(stringResource(R.string.apps_folder_rename), checked = false, focusRequester = firstItem) {
menu = false
onRename()
}
MenuItem(stringResource(R.string.apps_folder_ungroup), checked = false) {
menu = false
HomeFolders.delete(ctx, entry.folder.id)
}
}
}
}
@Composable
private fun FolderSheet(
folder: HomeFolders.Folder, apps: List<HomeApp.LaunchableApp>, renameFirst: Boolean,
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit,
) {
SwipeLock()
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var renaming by remember(folder.id) { mutableStateOf(renameFirst) }
var name by remember(folder.id) { mutableStateOf(if (renameFirst) "" else folder.name) }
val commit = {
val n = name.trim()
if (n.isNotEmpty() && n != folder.name) HomeFolders.rename(ctx, folder.id, n)
renaming = false
}
val close = { if (renaming) commit(); onClose() }
BackHandler { close() }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f))
.pointerInput(Unit) { awaitEachGesture { val d = awaitFirstDown(); d.consume(); close() } },
) {
val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true }
AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160)), exit = scaleOut(Motion.tw(140)) + fadeOut(Motion.tw(140))) {
Column(
modifier = Modifier.widthIn(max = 620.dp).fillMaxWidth(0.9f).heightIn(max = 520.dp)
.clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f))
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
.controllerBack(close)
.padding(16.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) {
if (renaming) Box(Modifier.weight(1f)) {
AdbTextField(
value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name),
keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false,
placeholder = folder.name, focusOnShow = true, onDone = { commit() },
)
} else {
Text(folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
SmallIconButton(Icons.Filled.Edit, stringResource(R.string.apps_folder_rename), tint = colors.onSurfaceVariant) { renaming = true }
Spacer(Modifier.weight(1f))
}
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant) { close() }
}
LazyVerticalGrid(
columns = GridCells.Adaptive(92.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(apps, key = { it.key }) { app ->
AppTile(app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder)
}
}
}
}
}
}
@Composable
private fun WidgetCard(w: HomeWidgets.Placed, maxWidthDp: Int) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var menu by remember { mutableStateOf(false) }
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val width = w.widthDp.coerceAtMost(maxWidthDp)
val activity = remember(ctx) { ctx.findActivity() }
Box {
Box(
Modifier.size(width.dp, w.heightDp.dp)
.clip(Shape16)
.background(colors.surface.copy(alpha = 0.35f))
.glideBorder(hot || menu, Shape16, pal.signal)
.hoverable(src).focusable(interactionSource = src)
.controllerConfirm { menu = true }
.menuKey { menu = true },
) {
AndroidView(
factory = { c ->
(HomeWidgets.createView(c, w.id) ?: android.view.View(c)).apply {
val radius = 16 * c.resources.displayMetrics.density
outlineProvider = object : android.view.ViewOutlineProvider() {
override fun getOutline(view: android.view.View, outline: android.graphics.Outline) =
outline.setRoundRect(0, 0, view.width, view.height, radius)
}
clipToOutline = true
}
},
update = { v ->
if (v is HomeWidgets.HomeWidgetView) {
v.onLongPress = { menu = true }
HomeWidgets.applySize(v, width, w.heightDp)
}
},
modifier = Modifier.fillMaxSize(),
)
}
val (minW, minH) = remember(w.id) { HomeWidgets.minSize(ctx, w.id) }
val index = HomeWidgets.widgets.indexOfFirst { it.id == w.id }
val label = remember(w.id) { HomeWidgets.info(ctx, w.id)?.loadLabel(ctx.packageManager) ?: "" }
AnchoredMenu(menu, onDismiss = { menu = false }, title = label, compact = true, minWidth = 180.dp) { first ->
val step = 48
MenuItem(stringResource(R.string.apps_widget_wider), checked = false, enabled = width < maxWidthDp, focusRequester = first) {
HomeWidgets.resize(ctx, w.id, (width + step).coerceAtMost(maxWidthDp), w.heightDp)
}
MenuItem(stringResource(R.string.apps_widget_narrower), checked = false, enabled = width > minW) {
HomeWidgets.resize(ctx, w.id, (width - step).coerceAtLeast(minW), w.heightDp)
}
MenuItem(stringResource(R.string.apps_widget_taller), checked = false, enabled = w.heightDp < 480) {
HomeWidgets.resize(ctx, w.id, width, (w.heightDp + step).coerceAtMost(480))
}
MenuItem(stringResource(R.string.apps_widget_shorter), checked = false, enabled = w.heightDp > minH) {
HomeWidgets.resize(ctx, w.id, width, (w.heightDp - step).coerceAtLeast(minH))
}
if (index > 0) MenuItem(stringResource(R.string.apps_widget_move_earlier), checked = false) { HomeWidgets.move(ctx, w.id, -1) }
if (index in 0 until HomeWidgets.widgets.size - 1) MenuItem(stringResource(R.string.apps_widget_move_later), checked = false) { HomeWidgets.move(ctx, w.id, 1) }
if (activity != null && HomeWidgets.canReconfigure(ctx, w.id)) MenuItem(stringResource(R.string.apps_widget_configure), checked = false) {
menu = false
HomeWidgets.reconfigure(activity, w.id)
}
MenuItem(stringResource(R.string.apps_widget_remove), checked = false) {
menu = false
HomeWidgets.remove(ctx, w.id)
}
}
}
}
@Composable
private fun WidgetPicker(padH: androidx.compose.ui.unit.Dp, onClose: () -> Unit) {
SwipeLock()
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val activity = remember(ctx) { ctx.findActivity() }
BackHandler { onClose() }
val providers = HomeWidgets.providers
Column(Modifier.fillMaxSize().background(colors.background).pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false) } }) {
LazyVerticalGrid(
columns = GridCells.Adaptive(150.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(horizontal = padH, vertical = 14.dp),
modifier = Modifier.fillMaxSize(),
) {
item(key = "back", span = { GridItemSpan(maxLineSpan) }) {
Column {
Box(Modifier.padding(bottom = 10.dp)) { BackLink(stringResource(R.string.rail_apps), compact = true, onClick = onClose) }
PageHeader(stringResource(R.string.apps_add_widget)) {
if (providers != null) Chip(providers.size.toString(), ok = false)
}
}
}
when {
providers == null -> item(key = "loading", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_loading)) }
providers.isEmpty() -> item(key = "none", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_none)) }
else -> items(providers, key = { it.info.provider.flattenToString() }) { p ->
ProviderCard(p, first = p === providers.first()) {
onClose()
if (activity != null) HomeWidgets.add(activity, p)
}
}
}
}
}
}
@Composable
private fun ProviderCard(p: HomeWidgets.Provider, first: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Column(
modifier = Modifier.fillMaxWidth().paneItem("widget:" + p.info.provider.flattenToString()).then(if (first) Modifier.firstTile() else Modifier)
.clip(Shape12).background(colors.surface)
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick),
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxWidth().aspectRatio(1.6f).background(colors.surfaceVariant).padding(10.dp),
) {
val preview = p.preview
if (preview != null) Image(preview.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())
}
Column(Modifier.padding(horizontal = 10.dp, vertical = 8.dp)) {
Text(p.label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val cells = "${(p.widthDp / 80f).roundToInt().coerceAtLeast(1)} × ${(p.heightDp / 80f).roundToInt().coerceAtLeast(1)}"
Text(if (p.appLabel == p.label) cells else "${p.appLabel} · $cells", fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
@Composable
fun PinRequestPrompt(label: String, appLabel: String, icon: Bitmap?, wide: Boolean, onAdd: () -> Unit, onCancel: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
BackHandler { onCancel() }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f))
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); onCancel() } },
) {
val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true }
AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160))) {
Column(
verticalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.widthIn(min = 280.dp, max = 420.dp)
.clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f))
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
.controllerBack(onCancel)
.padding(18.dp),
) {
Text(
stringResource(R.string.apps_pin_title).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
letterSpacing = 1.5.sp, color = colors.onSurfaceVariant,
)
if (wide && icon != null) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxWidth().heightIn(max = 180.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface).padding(10.dp),
) { Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxWidth()) }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
if (!wide) {
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp))
else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(label))))
}
Column(Modifier.weight(1f)) {
Text(label, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(appLabel, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
SecondaryButton(stringResource(R.string.common_cancel), onClick = onCancel)
PrimaryButton(stringResource(R.string.apps_pin_add), onClick = onAdd)
}
}
}
}
}
@@ -308,12 +308,12 @@ private fun InstalledMoviesDialog(a: ModeSettingsActions, onDismiss: () -> Unit)
@Composable
private fun RemoveMovieDialog(entry: BootMovieLibrary.Entry, onConfirm: () -> Unit, onDismiss: () -> Unit) {
androidx.compose.material3.AlertDialog(
com.droiddeck.launcher.ui.GlideAlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.boot_movie_remove_confirm, entry.title)) },
text = { Text(stringResource(R.string.boot_movie_remove_confirm_body)) },
confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm) { Text(stringResource(R.string.boot_movie_remove)) } },
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.boot_movie_remove)) } },
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@@ -0,0 +1,15 @@
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 CollectionsIcon: ImageVector = ImageVector.Builder("Collections", 24.dp, 24.dp, 24f, 24f).apply {
for (d in listOf(
"M2.65,4.6H7.33V22H2.65Z",
"M8.32,2H13V22H8.32Z",
"M13.9,5.4H18.5L21.4,22H16.8Z",
)) addPath(addPathNodes(d), fill = SolidColor(Color.Black))
}.build()
@@ -38,7 +38,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.AlertDialog
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
@@ -699,7 +699,7 @@ fun ComponentsPage(
Box(Modifier.fillMaxSize().onGloballyPositioned { pageAt = it.positionInRoot() }.onFocusChanged { pageFocused = it.hasFocus }) {
Column(
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp).padding(top = if (narrow) 12.dp else 18.dp)
.then(if (selectedGame == null) Modifier.bumpers(
onPrevious = { pick(layerStep(layer, -1)) },
onNext = { pick(layerStep(layer, 1)) },
@@ -972,7 +972,7 @@ private fun Stack(
onFocus = { onFocus(l) }, onClick = { onOpen(l) },
)
}
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
StackHeading(stringResource(R.string.comp_this_device))
card(GPU_TAB)
Spacer(Modifier.height(6.dp))
@@ -37,10 +37,12 @@ class DeckControlsPanel(
private val onSteamMenu: () -> Unit,
private val onQam: () -> Unit,
private val pad: PadBridge? = null,
private val portraitDock: Boolean = false,
) : LinearLayout(context) {
private enum class Tab(val label: Int) { GAMEPAD(R.string.deck_tab_gamepad), GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) }
private val content = FrameLayout(context)
val deckControls = pad == null || SessionState.deckPad
private val tabViews = HashMap<Tab, TextView>()
private val topBar: View by lazy { topBar() }
@@ -49,7 +51,7 @@ class DeckControlsPanel(
setBackgroundColor(Color.BLACK)
addView(topBar, LayoutParams(LayoutParams.MATCH_PARENT, dp(64)))
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
select(if (pad != null) selectedWithPad else selected)
select(if (pad != null && !deckControls) Tab.GAMEPAD else if (pad != null) selectedWithPad else selected)
}
override fun onDetachedFromWindow() {
@@ -67,6 +69,7 @@ class DeckControlsPanel(
background = outline(CORNER_PILL, SURFACE)
setPadding(dp(4), dp(4), dp(4), dp(4))
for (tab in Tab.values()) {
if (!deckControls && tab != Tab.GAMEPAD) continue
if (tab == Tab.GAMEPAD && pad == null) continue
val view = TextView(context).apply {
text = context.getString(tab.label)
@@ -170,7 +173,7 @@ class DeckControlsPanel(
addView(grips, LayoutParams(LayoutParams.MATCH_PARENT, dp(84)))
}
private fun gamepad(pad: PadBridge): View = GamepadLayout(context).apply {
private fun gamepad(pad: PadBridge): View = GamepadLayout(context, portraitDock).apply {
fun pill(label: String, write: (PadState, Boolean) -> Unit) = PadButton(context, pad, label, write)
place(surfaceSlot(pad, right = false), GamepadGeometry.Slot.LEFT_MAIN)
place(DirectionPad(context, pad), GamepadGeometry.Slot.LEFT_SECOND)
@@ -186,14 +189,22 @@ class DeckControlsPanel(
place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM)
}
place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU)
place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
if (deckControls) place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
GamepadGeometry.Slot.PANELS)
if (portraitDock && deckControls) {
place(GripButton(context, "L4", null, DeckControls.L4), GamepadGeometry.Slot.L4)
place(GripButton(context, "L5", null, DeckControls.L5), GamepadGeometry.Slot.L5)
place(GripButton(context, "R5", null, DeckControls.R5), GamepadGeometry.Slot.R5)
place(GripButton(context, "R4", null, DeckControls.R4), GamepadGeometry.Slot.R4)
}
}
private fun centreTap(label: String, description: String, onClick: () -> Unit) = TextView(context).apply {
text = label
contentDescription = description
textSize = 13f
maxLines = 1
setAutoSizeTextTypeUniformWithConfiguration(9, 13, 1, android.util.TypedValue.COMPLEX_UNIT_SP)
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
letterSpacing = 0.08f
gravity = Gravity.CENTER
@@ -206,6 +217,11 @@ class DeckControlsPanel(
}
private fun surfaceSlot(pad: PadBridge, right: Boolean): View = FrameLayout(context).apply {
if (!deckControls) {
addView(StickView(context, pad, right),
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
return@apply
}
val slot = this
fun show() {
slot.removeAllViews()
@@ -617,7 +633,7 @@ class DeckControlsPanel(
}
}
private class GamepadLayout(context: Context) : ViewGroup(context) {
private class GamepadLayout(context: Context, private val portraitDock: Boolean) : ViewGroup(context) {
private val slots = LinkedHashMap<View, GamepadGeometry.Slot>()
fun place(view: View, slot: GamepadGeometry.Slot) {
@@ -625,7 +641,7 @@ class DeckControlsPanel(
addView(view)
}
private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density)
private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density, portraitDock)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val w = MeasureSpec.getSize(widthMeasureSpec)
@@ -31,7 +31,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material3.AlertDialog
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
@@ -11,6 +11,7 @@ import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
@@ -23,6 +24,7 @@ import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
@@ -54,10 +56,21 @@ internal class GlideSource {
var shape: Shape by mutableStateOf<Shape>(androidx.compose.ui.graphics.RectangleShape)
var color by mutableStateOf(Color.Transparent)
var width by mutableStateOf(2.dp)
var fillAlpha by mutableFloatStateOf(RING_FILL)
val requester = androidx.compose.ui.focus.FocusRequester()
}
internal class FocusGlide(val view: View) {
internal class FocusGlide(view: View?) {
private val deferredWindow = view == null
var view = view
private set
fun accepts(view: View): Boolean {
// DropdownMenu recreates its popup view after closing.
if (this.view == null || deferredWindow && this.view !== view && host?.isAttached != true) this.view = view
return this.view === view
}
var host: LayoutCoordinates? = null
val hot = mutableStateListOf<GlideSource>()
var moves by mutableIntStateOf(0)
@@ -107,15 +120,17 @@ internal fun Modifier.glideBorder(
restColor: Color = Color.Transparent,
hotWidth: Dp = 2.dp,
restWidth: Dp = 1.dp,
hotFillAlpha: Float = RING_FILL,
): Modifier {
val glide = LocalFocusGlide.current
if (glide == null || glide.view !== LocalView.current) {
if (glide == null || !glide.accepts(LocalView.current)) {
return border(if (hot) hotWidth else restWidth, if (hot) hotColor else restColor, shape)
}
val src = remember { GlideSource() }
src.shape = shape
src.color = hotColor
src.width = hotWidth
src.fillAlpha = hotFillAlpha
DisposableEffect(glide, hot) {
if (hot) glide.claim(src)
onDispose { glide.release(src) }
@@ -140,12 +155,36 @@ private const val REPEAT_MS = 180L
private val FAR = 360.dp
@Composable
internal fun Modifier.focusGlide(
shape: Shape = Shape12,
color: Color = LocalPalette.current.signal,
): Modifier {
var focused by remember { mutableStateOf(false) }
return glideBorder(focused, shape, color, hotFillAlpha = 0f)
.onFocusChanged { focused = it.isFocused }
}
@Composable
internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
val view = LocalView.current
val glide = remember(view) { FocusGlide(view) }
Box(modifier.focusGlideOverlay(glide)) {
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
}
}
@Composable
internal fun FocusGlideWindow(content: @Composable (Modifier) -> Unit) {
val glide = remember { FocusGlide(null) }
val overlay = Modifier.focusGlideOverlay(glide)
CompositionLocalProvider(LocalFocusGlide provides glide) { content(overlay) }
}
@Composable
private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
val density = LocalDensity.current
val dir = LocalLayoutDirection.current
val glide = remember(view) { FocusGlide(view) }
val edges = remember { List(4) { Animatable(0f) } }
val corner = remember { Animatable(0f) }
val solid = remember { Animatable(0f) }
@@ -162,6 +201,8 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
val color by animateColorAsState(cur?.color ?: lastColor, Motion.tw(160), label = "glideColor")
var width by remember { mutableStateOf(2.dp) }
if (cur != null) width = cur.width
var fillAlpha by remember { mutableFloatStateOf(RING_FILL) }
if (cur != null) fillAlpha = cur.fillAlpha
LaunchedEffect(glide, Motion.scale) {
var shown: GlideSource? = null
@@ -339,8 +380,7 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
}
}
Box(
modifier
return this
.onGloballyPositioned { glide.host = it }
.drawWithContent {
drawContent()
@@ -359,15 +399,12 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
if (f < 0.99f) {
drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * RING_FILL,
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha,
)
drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
)
}
},
) {
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
}
}
}
@@ -10,6 +10,8 @@ import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.snap
import androidx.compose.animation.core.tween
import androidx.compose.animation.scaleIn
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.scaleOut
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.rememberUpdatedState
@@ -105,7 +107,7 @@ import java.io.File
internal fun Pane(
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
) {
BoxWithConstraints(modifier = modifier) {
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
@@ -138,12 +140,19 @@ internal fun Pane(
before[0] = target
val targetNow by rememberUpdatedState(target)
val leave = if (Hops.linking) PageLeave.Link else PageLeave.Ordinary
LaunchedEffect(target) { Hops.linking = false }
LaunchedEffect(target) {
Hops.linking = false
PageSwipe.direction = 0
}
AnimatedContent(
targetState = target,
modifier = Modifier.onGloballyPositioned { paneAt[0] = it.positionInRoot() },
transitionSpec = {
val swipe = PageSwipe.direction
when {
swipe != 0 -> (fadeIn(Motion.tw(260, 40)) + slideInHorizontally(Motion.tw(360)) { it * swipe / 8 })
.togetherWith(fadeOut(Motion.tw(160)) + slideOutHorizontally(Motion.tw(220)) { -it * swipe / 8 })
.apply { targetContentZIndex = 1f }
targetState in origins -> (fadeIn(Motion.tw(120)))
.togetherWith(fadeOut(Motion.tw(320, 80)) + scaleOut(Motion.tw(480), targetScale = 0.95f))
.apply { targetContentZIndex = 1f }
@@ -162,7 +171,7 @@ internal fun Pane(
label = "pane",
) { key ->
val drawn = (if (page != null && key == s.pageKey) page else pages[key])
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb) }
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) }
val hopSink by androidx.compose.animation.core.animateFloatAsState(
if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink",
)
@@ -223,7 +232,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, L
private fun Content(
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
@@ -232,13 +241,13 @@ private fun Content(
val padH = if (narrow) 16.dp else 22.dp
val padV = if (narrow) 12.dp else 18.dp
if (selected == "setup") {
Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) {
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
Column(modifier = modifier.padding(horizontal = padH).padding(top = padV)) {
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging)
}
return
}
if (selected == "updates") {
UpdatesPage(s, a, modifier.padding(horizontal = padH, vertical = padV))
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
return
}
if (selected == "steam") {
@@ -261,24 +270,12 @@ private fun Content(
DesktopPage(s, a, modifier, onSelect)
return
}
if (selected == "android-apps" && s.isHomeApp) {
AndroidAppsPage(s, modifier, onAndroidAppClick)
return
}
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
when {
selected == "android-apps" && s.isHomeApp -> {
Rise(0) { PageHeader(stringResource(R.string.content_android_apps)) { Chip(stringResource(R.string.content_apps_count, s.androidApps.size), ok = false) } }
if (s.androidApps.isEmpty()) Rise(3) { Note(stringResource(R.string.content_no_android_apps)) }
else Rise(3, Modifier.fillMaxWidth()) {
ArtGrid(s.androidApps.map { app ->
Tile(
app.label,
null,
null,
"android:${app.packageName}",
onClick = { onAndroidAppClick(app) },
iconBitmap = app.icon,
)
})
}
}
selected.startsWith("user:") -> {
val app = UserAppsState.items.firstOrNull { "user:${it.key}" == selected }
if (app == null) Note(stringResource(R.string.user_apps_gone)) else UserAppPage(app, s, a, onSelect)
@@ -41,6 +41,9 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Apps
@@ -81,12 +84,48 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.layout.boundsInParent
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onPlaced
import com.droiddeck.launcher.core.PhantomProcessLimit
internal val AttentionAmber = Color(0xFFFFB547)
@Composable
internal fun BottomBar(
s: FrontEndState, selected: String,
onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit, a: FrontEndActions, modifier: Modifier,
) {
val shown = Hops.railPreview ?: selected
val keys = navigationKeys(s)
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
val content = remember { arrayOfNulls<LayoutCoordinates>(1) }
Row(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface), verticalAlignment = Alignment.CenterVertically) {
BoxWithConstraints(Modifier.weight(1f)) {
val itemWidth = (maxWidth / keys.size).coerceIn(56.dp, 88.dp)
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onPlaced { content[0] = it }) {
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f)
Row(Modifier.selectableGroup().padding(vertical = 4.dp), horizontalArrangement = Arrangement.Center) {
NavigationItems(s, shown, compact = true, iconOnly = false, height = 56.dp, width = itemWidth,
place = { key -> Modifier.onGloballyPositioned { item -> content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }; Hops.railBounds[key] = item.boundsInRoot() } },
onSelect = onSelect, onFocusSelect = onFocusSelect)
}
}
}
if (s.running != null) ResumeRailItem(s.running, compact = true, iconOnly = true, a.onResume)
}
}
internal fun navigationKeys(s: FrontEndState) = buildList {
add("steam"); add("games")
if (s.gameStoresEnabled) add("stores")
add("desktop"); add("components")
if (s.isHomeApp) add("android-apps")
add("setup"); add("updates")
}
@Composable
internal fun SideRail(
s: FrontEndState, selected: String,
@@ -95,8 +134,6 @@ internal fun SideRail(
val colors = MaterialTheme.colorScheme
val compact = LocalConfiguration.current.screenHeightDp < 420
val iconOnly = isNarrowScreen()
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
@@ -105,38 +142,24 @@ internal fun SideRail(
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
val shown = Hops.railPreview ?: selected
val keys = buildList {
add("steam"); add("games")
if (s.gameStoresEnabled) add("stores")
add("desktop")
add("components")
if (s.isHomeApp) add("android-apps")
add("setup"); add("updates")
}
val keys = navigationKeys(s)
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
var railAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onGloballyPositioned { railAt = it.boundsInRoot().topLeft }) {
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-railAt), tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
val content = remember { arrayOfNulls<LayoutCoordinates>(1) }
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onPlaced { content[0] = it }) {
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.fillMaxWidth().selectableGroup(),
) {
val place: (String) -> Modifier = { key ->
Modifier.onGloballyPositioned {
bounds[key] = it.boundsInRoot()
Hops.railBounds[key] = it.boundsInRoot()
Modifier.onGloballyPositioned { item ->
content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }
Hops.railBounds[key] = item.boundsInRoot()
}
}
RailItem(stringResource(R.string.rail_steam), Icons.Outlined.SportsEsports, "steam", shown == "steam", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", shown == "games", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("games") }) { onSelect("games") }
if (s.gameStoresEnabled) RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", shown == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, place = place, onFocus = { onFocusSelect("stores") }) { onSelect("stores") }
RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", shown == "desktop", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", shown == "components", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("components") }) { onSelect("components") }
if (s.isHomeApp) RailItem(stringResource(R.string.rail_apps), Icons.Outlined.Apps, "android-apps", shown == "android-apps", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
RailItem(stringResource(R.string.rail_setup), Icons.Outlined.Tune, "setup", shown == "setup", compact, iconOnly, fit, badge = setupNeedsAttention, place = place, onFocus = { onFocusSelect("setup") }) { onSelect("setup") }
RailItem(stringResource(R.string.rail_updates), Icons.Outlined.SystemUpdate, "updates", shown == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, place = place, onFocus = { onFocusSelect("updates") }) { onSelect("updates") }
NavigationItems(s, shown, compact, iconOnly, fit, if (iconOnly) 52.dp else 80.dp, place, onSelect, onFocusSelect)
}
}
}
@@ -151,8 +174,36 @@ internal fun SideRail(
}
@Composable
private fun NavigationItems(
s: FrontEndState, shown: String, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp,
place: (String) -> Modifier, onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit,
) {
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
for (key in navigationKeys(s)) {
val (label, icon) = when (key) {
"steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports
"games" -> R.string.rail_games to Icons.Outlined.VideoLibrary
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
"desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows
"components" -> R.string.rail_components to Icons.Outlined.Layers
"android-apps" -> R.string.rail_apps to Icons.Outlined.Apps
"setup" -> R.string.rail_setup to Icons.Outlined.Tune
else -> R.string.rail_updates to Icons.Outlined.SystemUpdate
}
key(key) {
RailItem(stringResource(label), icon, key, shown == key, compact, iconOnly, height, width,
badge = (key == "setup" && setupNeedsAttention) || (key == "updates" && s.updates.hasUpdate),
count = if (key == "stores") s.storeDownloadsActive else 0,
place = place, onFocus = { onFocusSelect(key) }) { onSelect(key) }
}
}
}
@Composable
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
private fun RailItem(
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp,
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp,
badge: Boolean = false,
count: Int = 0,
place: (String) -> Modifier = { Modifier },
@@ -181,6 +232,8 @@ private fun RailItem(
Motion.tw(220), label = "railFill",
)
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "railScale")
val bringIntoView = remember { BringIntoViewRequester() }
LaunchedEffect(current) { if (current) bringIntoView.bringIntoView() }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
@@ -189,7 +242,8 @@ private fun RailItem(
.then(place(key))
.landingPop(Hops.railLanded[key] ?: 0)
.graphicsLayer { scaleX = scale; scaleY = scale }
.size(width = if (iconOnly) 52.dp else 80.dp, height = height)
.size(width = width, height = height)
.bringIntoViewRequester(bringIntoView)
.clip(Shape14)
.background(fill)
.glideBorder(focused, Shape14, pal.signal)
@@ -11,6 +11,7 @@ import androidx.compose.foundation.focusGroup
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.onFocusChanged
import android.provider.Settings
import android.view.Display
@@ -120,6 +121,8 @@ class FrontEndState(
val isHomeApp: Boolean = false,
val homeScreenEnabled: Boolean = false,
val defaultHomeLabel: String? = null,
val integration: com.droiddeck.launcher.core.SteamIntegration.State = com.droiddeck.launcher.core.SteamIntegration.State(suggested = false),
val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null,
val androidApps: List<HomeApp.LaunchableApp> = emptyList(),
val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(),
val packages: List<PackageRow>? = null,
@@ -138,6 +141,7 @@ class FrontEndState(
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val showPhantomGate: Boolean = false,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
val launcherFullscreen: Boolean = true,
val downloadSource: String = DownloadSource.MODE_AUTO,
val downloadMirror: String = "",
@@ -219,6 +223,7 @@ class FrontEndActions(
val onAppScale: (Int) -> Unit = {},
val onLauncherIcon: (String) -> Unit = {},
val onOrientation: (Int) -> Unit = {},
val onLauncherOrientation: (Int) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onDownloadSource: (String) -> Unit = {},
@@ -234,6 +239,11 @@ class FrontEndActions(
val onLibraryChanged: () -> Unit = {},
val onHomeApp: () -> Unit = {},
val onHomeScreen: (Boolean) -> Unit = {},
val onSteamIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature?) -> Unit = {},
val onDismissIntegration: () -> Unit = {},
val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {},
val onIntegrationAppInfo: () -> Unit = {},
val onIntegrationLocation: () -> Unit = {},
val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> },
val onBackActionsInverted: (Boolean) -> Unit = {},
val onRefreshPhantomStatus: () -> Unit = {},
@@ -245,6 +255,8 @@ class FrontEndActions(
val onCopyPhantomCommand: (Boolean) -> Unit = {},
val onDismissPhantomGate: () -> Unit = {},
val onStartWirelessAdbPairing: () -> Unit = {},
val onStartPairingGuide: (Int?) -> Boolean = { false },
val onShowPhantomGate: () -> Unit = {},
val onOpenNotificationSettings: () -> Unit = {},
val controller: ControllerActions? = null,
val updates: UpdatesActions = UpdatesActions(),
@@ -265,12 +277,6 @@ internal object Motion {
if (scale == 0f) snap() else spring(damping, stiffness)
}
internal object Ambient {
var poked by mutableStateOf(0L)
private set
fun poke() { poked = android.os.SystemClock.uptimeMillis() }
}
private val Shape10 = RoundedCornerShape(10.dp)
internal val Shape12 = RoundedCornerShape(12.dp)
@@ -392,7 +398,12 @@ internal suspend fun focusSoon(target: () -> FocusRequester) {
@Composable
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
val frontFocus = remember { FrontFocus() }
CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus) }
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) {
CompositionLocalProvider(
LocalFrontFocus provides frontFocus,
LocalNarrowPane provides (maxWidth < NarrowPaneWidth),
) { FrontEndScreenBody(s, a, page, frontFocus) }
}
}
@OptIn(ExperimentalComposeUiApi::class)
@@ -406,6 +417,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
"stores:downloads" -> { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" }
"components" -> a.onComponents(true)
"setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" }
"setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" }
else -> selected = target
}
a.onNavigated()
@@ -415,6 +427,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
val colors = MaterialTheme.colorScheme
@@ -423,9 +436,36 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
val requestDeveloperOptions = {
developerChoiceGuided = false
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
else showDeveloperDisplayChoice = true
}
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
if (developerChoiceGuided) a.onStartWirelessAdbPairing()
if (!developerChoiceGuided || !a.onStartPairingGuide(displayId)) a.onOpenDeveloperOptions(displayId)
developerChoiceGuided = false
}
val startGuidedPairing = {
if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) {
wirelessAdbDesiredEnabled = false
showWirelessAdbFix = true
} else {
developerChoiceGuided = true
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
else showDeveloperDisplayChoice = true
}
}
var applyingSavedPairing by remember { mutableStateOf(false) }
val fixPhantomLimit = {
if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing()
else if (!applyingSavedPairing) {
applyingSavedPairing = true
a.onSetPhantomProcessLimit(false) { error ->
applyingSavedPairing = false
if (error != null) startGuidedPairing()
}
}
}
val requestWirelessAdbFix: (Boolean) -> Unit = { enabled ->
wirelessAdbDesiredEnabled = enabled
showWirelessAdbFix = true
@@ -467,6 +507,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop"
else -> s.pageKey ?: selected
}
val railSelectionNow = androidx.compose.runtime.rememberUpdatedState(railSelection)
var railPicks by remember { mutableStateOf(0) }
val showRailPage: (String, Boolean) -> Unit = { key, focusContent ->
if (key == "components") a.onComponents(focusContent)
@@ -492,11 +533,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
val window = LocalWindowInfo.current
val androidContext = androidx.compose.ui.platform.LocalContext.current
var anyFocused by remember { mutableStateOf(false) }
Box(
androidx.compose.foundation.layout.BoxWithConstraints(
modifier = Modifier.fillMaxSize().background(colors.background)
.windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
.onFocusChanged { anyFocused = it.hasFocus },
) {
val bottomNavigation = maxHeight > maxWidth
LaunchedEffect(processSettingsPageVisible) {
if (processSettingsPageVisible) return@LaunchedEffect
snapshotFlow { window.isWindowFocused }.first { it }
@@ -533,10 +575,19 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
focusWithinFrames({ frontFocus.focusedRail == null && anyFocused }) { frontFocus.paneEntry() }
}
val paneFocus = Modifier
.focusProperties { enter = { frontFocus.paneEntry() } }
.focusProperties {
enter = { frontFocus.paneEntry() }
exit = { direction ->
if (bottomNavigation && direction == FocusDirection.Down) frontFocus.railFor(railSelection)
else FocusRequester.Default
}
}
.focusGroup()
val railFocus = Modifier
.focusProperties { enter = { frontFocus.railFor(railSelection) } }
.focusProperties {
enter = { frontFocus.railFor(railSelection) }
if (bottomNavigation) up = frontFocus.paneEntry()
}
.focusGroup()
LaunchedEffect(Hops.restore) {
val r = Hops.restore ?: return@LaunchedEffect
@@ -550,25 +601,39 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
var screenAt by remember { mutableStateOf(Offset.Zero) }
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
Row(modifier = Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }) {
SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line))
Column(modifier = Modifier.weight(1f).fillMaxHeight()) {
LauncherLayout(
bottomNavigation, pal.line,
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() },
navigation = {
if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
else SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
},
) {
Pane(
s, selected, a, page, Modifier.weight(1f).fillMaxWidth().then(paneFocus), { selected = it },
s, selected, a, page,
Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }) { dir ->
val keys = navigationKeys(s)
val at = keys.indexOf(railSelectionNow.value)
if (at >= 0) keys.getOrNull(at + dir)?.let { key ->
PageSwipe.direction = dir
showRailPage(key, false)
}
},
{ selected = it },
onAndroidAppClick = { app ->
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
else appToChooseDisplay = app
},
onOpenDeveloperOptions = requestDeveloperOptions,
onRequestWirelessAdb = requestWirelessAdbFix,
onPairWirelessDebugging = startGuidedPairing,
)
}
}
}
FlightsLayer(screenAt)
GamesDialogs(a, s.steamGames)
StoreTheme(com.droiddeck.launcher.stores.Store.XBOX) { XboxStoreDialogs() }
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
StepsLayer(screenAt)
@@ -595,10 +660,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
status = s.phantomProcessStatus,
onDismiss = a.onDismissPhantomGate,
onOpenDeveloperOptions = requestDeveloperOptions,
onFixWithWirelessDebugging = {
a.onStartWirelessAdbPairing()
requestDeveloperOptions()
},
applyingSavedPairing = applyingSavedPairing,
onFixWithWirelessDebugging = fixPhantomLimit,
onEnterAddressManually = { requestWirelessAdbFix(false) },
onCopyCommand = { a.onCopyPhantomCommand(false) },
onOpenNotificationSettings = a.onOpenNotificationSettings,
@@ -624,13 +687,16 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
},
onMainScreen = {
showDeveloperDisplayChoice = false
a.onOpenDeveloperOptions(null)
openDeveloperOptionsOn(null)
},
onSecondaryScreen = { displayId ->
showDeveloperDisplayChoice = false
a.onOpenDeveloperOptions(displayId)
openDeveloperOptionsOn(displayId)
},
onDismiss = {
showDeveloperDisplayChoice = false
developerChoiceGuided = false
},
onDismiss = { showDeveloperDisplayChoice = false },
)
}
}
@@ -91,6 +91,7 @@ private const val LAUNCHER_TAB = 2
internal object SetupTabs {
var openLauncher = false
var openOverview = false
}
private const val GLASSES_TAB = 5
@@ -140,6 +141,7 @@ internal fun SetupPanel(
a: FrontEndActions,
onOpenDeveloperOptions: () -> Unit,
onRequestWirelessAdb: (Boolean) -> Unit,
onPairWirelessDebugging: () -> Unit,
) {
val host = rememberMenuHost()
val ctx = LocalContext.current
@@ -191,6 +193,7 @@ internal fun SetupPanel(
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) }
SetupTabs.openLauncher = false
if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false }
val chipFocus = remember { List(tabs.size) { FocusRequester() } }
var tabTurned by remember { mutableStateOf(false) }
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true }
@@ -201,6 +204,12 @@ internal fun SetupPanel(
tab = STORAGE_TAB
}
}
LaunchedEffect(Unit) {
while (true) {
kotlinx.coroutines.delay(2_000)
a.onRefreshPhantomStatus()
}
}
LaunchedEffect(tab) {
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
androidx.compose.runtime.withFrameNanos { }
@@ -277,7 +286,7 @@ internal fun SetupPanel(
},
divider = divider && !showLimitDetails,
) {
if (limitBlocks) PrimaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_fix_it), compact = true) { showLimitDetails = !showLimitDetails }
if (limitBlocks) PrimaryButton(stringResource(R.string.setup_fix_it), compact = true, onClick = a.onShowPhantomGate)
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
SecondaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_details), compact = true) { showLimitDetails = !showLimitDetails }
}
@@ -290,11 +299,7 @@ internal fun SetupPanel(
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
)
Actions {
if (limitBlocks) {
PrimaryButton(stringResource(R.string.setup_dev_options), compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton(stringResource(R.string.setup_use_wireless), compact = true, enabled = !processLimitBusy) { setProcessLimit(false) }
SecondaryButton(stringResource(R.string.setup_check_again), compact = true, onClick = a.onRefreshPhantomStatus)
} else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
SecondaryButton(stringResource(R.string.setup_limit_turn_on), compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
}
}
@@ -341,6 +346,7 @@ internal fun SetupPanel(
}
}
SettingsGroup(stringResource(R.string.setup_runtime)) { runtimeCheck(false) }
SteamIntegrationGroup(s.integration, s.integrationFocus, a.onIntegration, a.onIntegrationAppInfo, a.onIntegrationLocation)
}
1 -> {
val controller = s.controller
@@ -398,7 +404,12 @@ internal fun SetupPanel(
ActionRow(stringResource(R.string.setup_default_home), s.defaultHomeLabel ?: stringResource(R.string.setup_choose_home), stringResource(R.string.setup_choose), a.onHomeApp)
}
ChoiceRow(
host, "orientation", stringResource(R.string.setup_orientation), null,
host, "launcher-orientation", stringResource(R.string.setup_launcher_orientation), null,
com.droiddeck.launcher.core.AppUiPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
s.launcherOrientation, onPick = a.onLauncherOrientation,
)
ChoiceRow(
host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
s.orientation, onPick = a.onOrientation,
)
@@ -501,7 +512,7 @@ internal fun SetupPanel(
)
if (!s.adbPaired) ActionRow(
stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint),
stringResource(R.string.setup_adb_pair_button), { onRequestWirelessAdb(false) },
stringResource(R.string.setup_adb_pair_button), onPairWirelessDebugging,
)
}
}
@@ -186,7 +186,7 @@ internal fun PrimaryButton(
.clip(Shape12)
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, Shape12))
.then(if (hot) Modifier.border(2.dp, pal.signal, Shape12) else Modifier)
.glideBorder(hot, Shape12, pal.signal, hotFillAlpha = 0f)
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) {
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
onClick()
@@ -56,6 +56,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalConfiguration
@@ -86,6 +87,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
@@ -217,6 +219,9 @@ internal fun GameDetail(
}
}
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
if (!s.shortcutPicker) Rise(2) {
GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game, Modifier.padding(top = 6.dp))
}
if (tab != null) Rise(2) {
Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
val labels = tabs.map { t ->
@@ -267,13 +272,15 @@ private fun GameHero(
)
}
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.55f to colors.background.copy(alpha = 0.58f), 1f to Color.Transparent)))
var scoresWidth by remember { mutableStateOf(0) }
if (scores != null) {
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0.45f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp))
HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp).onSizeChanged { scoresWidth = it.width })
}
val scoresSpace = with(LocalDensity.current) { if (scores != null && scoresWidth > 0) scoresWidth.toDp() + 16.dp else 0.dp }
Column(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp),
modifier = Modifier.align(Alignment.BottomStart).padding(start = 22.dp, end = 22.dp + scoresSpace, top = 18.dp, bottom = 18.dp),
content = content,
)
Box(Modifier.align(Alignment.TopEnd).padding(12.dp), content = corner)
@@ -319,7 +326,7 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
}
@Composable
private fun GameActions(
internal fun GameActions(
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
s: FrontEndState, a: FrontEndActions, leadOn: Modifier,
) {
@@ -328,22 +335,14 @@ private fun GameActions(
val rawDownload = storeKey?.let { StoresState.download(it) }
val download = rawDownload?.takeIf { it.isActive }
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
val cloud = game?.library == Library.XBOX_CLOUD && installed == null
Actions {
when {
s.shortcutPicker && game != null -> {
PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
FileButtons(game, a)
}
game?.library == Library.XBOX_CLOUD -> {
val cloudId = game.storeId.orEmpty()
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
if (download != null) ActionChip(downloadLabel(download), ok = false)
else if (item?.installable == true) SecondaryButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
) { StoresState.requestInstall(ctx, item) }
XboxLibraryButton(cloudId, item)
}
game != null || installed != null -> {
!cloud && (game != null || installed != null) -> {
val gone = storeKey?.let { StoresState.uninstalling[it] }
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
PrimaryButton(
@@ -366,7 +365,19 @@ private fun GameActions(
}
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
}
if (store == Store.BATTLENET) SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
if (store == Store.BATTLENET) {
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
ActionChip(downloadLabel(download), ok = false)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
}
}
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
}
download != null -> {
ActionChip(downloadLabel(download), ok = false)
@@ -381,6 +392,19 @@ private fun GameActions(
}
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
}
cloud -> {
val cloudId = game.storeId.orEmpty()
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
if (item?.installable == true && item.xboxPc) {
SecondaryButton(
if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install)
else if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes))
else stringResource(R.string.stores_install),
) { StoresState.requestInstall(ctx, item) }
}
if (item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
XboxLibraryButton(cloudId, item)
}
store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> {
XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
@@ -408,6 +432,10 @@ private fun GameActions(
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
}
if (cloud && (download != null || failed != null)) {
XboxStreamButton(game.storeId.orEmpty(), game.name)
XboxLibraryButton(game.storeId.orEmpty(), item)
}
BusyChip(s)
}
}
@@ -525,7 +553,7 @@ private fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, la
private fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id) return
if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id && installed?.sidecar?.id?.let(BattleNetInstall::product) == null) return
if (installed != null) {
val key = installed.key
val gone = StoresState.uninstalling[key]
@@ -0,0 +1,90 @@
package com.droiddeck.launcher.ui
import androidx.annotation.StringRes
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import java.net.URLEncoder
internal data class GameResource(@StringRes val label: Int, val url: String, @StringRes val detail: Int? = null)
internal fun gameResources(title: String, game: Library.SteamGame?): List<GameResource> {
if (title.isBlank()) return emptyList()
val query = URLEncoder.encode(title.trim(), "UTF-8").replace("+", "%20")
val steamId = game?.takeIf { Library.fromSteamClient(it) && it.appId > 0 }?.appId
return buildList {
add(GameResource(R.string.game_resource_pcgw, "https://www.pcgamingwiki.com/w/index.php?search=$query"))
add(GameResource(R.string.game_resource_guides, "https://gamefaqs.gamespot.com/search?game=$query"))
if (steamId != null) {
add(GameResource(R.string.game_resource_protondb, "https://www.protondb.com/app/$steamId", R.string.game_resource_protondb_detail))
add(GameResource(R.string.game_resource_steam_cloud, "https://store.steampowered.com/account/remotestorageapp/?appid=$steamId", R.string.game_resource_steam_cloud_detail))
}
add(GameResource(R.string.game_resource_search, "https://www.google.com/search?q=$query"))
}
}
@Composable
@OptIn(ExperimentalLayoutApi::class)
internal fun GameResourcesRow(title: String, game: Library.SteamGame?, modifier: Modifier = Modifier) {
val links = remember(title, game) { gameResources(title, game) }
if (links.isEmpty()) return
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
links.forEach { ResourceLink(it) }
}
}
@Composable
private fun ResourceLink(link: GameResource) {
val ctx = LocalContext.current
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
val hot = rememberHot(source)
val shape = RoundedCornerShape(8.dp)
val label = stringResource(link.label)
val description = listOfNotNull(label, link.detail?.let { stringResource(it) }, stringResource(R.string.game_resources_browser)).joinToString(". ")
val open = { openUrl(ctx, link.url) }
val tint = if (hot) pal.signal else pal.onSurfaceVariant
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 44.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.08f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, restColor = Color.Transparent)
.semantics { contentDescription = description }
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = open)
.controllerConfirm(onClick = open).padding(horizontal = 8.dp),
) {
Text(label, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = tint, maxLines = 1)
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = tint.copy(alpha = 0.65f), modifier = Modifier.size(11.dp))
}
}
@@ -8,6 +8,7 @@ object GamepadGeometry {
LEFT_OUTER_SHOULDER, LEFT_INNER_SHOULDER, RIGHT_INNER_SHOULDER, RIGHT_OUTER_SHOULDER,
VIEW, STEAM, QAM, MENU,
PANELS,
L4, L5, R5, R4,
}
data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) {
@@ -25,8 +26,11 @@ object GamepadGeometry {
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
fun layout(w: Float, h: Float, density: Float): Map<Slot, Box> {
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map<Slot, Box> {
if (w <= 0f || h <= 0f) return emptyMap()
if (portraitDock && h >= w * 0.9f && w >= 300 * density && h >= 360 * density) {
return portraitLayout(w, h, density)
}
val pad = 8 * density
val buttonH = 40 * density
val rowButton = 64 * density
@@ -67,7 +71,7 @@ object GamepadGeometry {
}
middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f)
} else {
val side = min(w * 0.5f, h * 0.70f)
val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f)
val main = side * 0.62f
val second = side * 0.46f
val secondCy = h - side * 0.97f
@@ -87,4 +91,39 @@ object GamepadGeometry {
}
return boxes
}
private fun portraitLayout(w: Float, h: Float, density: Float): Map<Slot, Box> {
val pad = 8 * density
val gap = 8 * density
val buttonH = 44 * density
val scale = min(1f, (h - 2 * pad - 4 * gap - 3 * buttonH) / (w * 0.7f))
val main = w * 0.4f * scale
val second = w * 0.3f * scale
val mainY = h - pad - main / 2f
val secondY = mainY - main / 2f - gap - second / 2f
val shoulderY = secondY - second / 2f - gap - buttonH / 2f
val boxes = linkedMapOf(
Slot.LEFT_MAIN to Box(w * 0.25f, mainY, main, main),
Slot.RIGHT_MAIN to Box(w * 0.75f, mainY, main, main),
Slot.LEFT_SECOND to Box(w * 0.25f, secondY, second, second),
Slot.RIGHT_SECOND to Box(w * 0.75f, secondY, second, second),
)
val utilityW = (w - 2 * pad - 3 * gap) / 4f
for ((i, slot) in middle.withIndex()) {
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), pad + buttonH / 2f, utilityW, buttonH)
}
val gripTop = pad + buttonH + gap
val gripH = min(64 * density, shoulderY - buttonH / 2f - gap - gripTop)
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), gripTop + gripH / 2f, utilityW, gripH)
}
val panelsW = min(112 * density, w * 0.22f)
val shoulderW = (w - 2 * pad - 4 * gap - panelsW) / 4f
boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
boxes[Slot.LEFT_OUTER_SHOULDER] = Box(pad + shoulderW / 2f, shoulderY, shoulderW, buttonH)
boxes[Slot.LEFT_INNER_SHOULDER] = Box(pad + shoulderW * 1.5f + gap, shoulderY, shoulderW, buttonH)
boxes[Slot.RIGHT_INNER_SHOULDER] = Box(w - pad - shoulderW * 1.5f - gap, shoulderY, shoulderW, buttonH)
boxes[Slot.RIGHT_OUTER_SHOULDER] = Box(w - pad - shoulderW / 2f, shoulderY, shoulderW, buttonH)
return boxes
}
}
@@ -1,7 +1,9 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.Modifier
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
@@ -32,8 +34,8 @@ internal fun GlassesCalibrationControls(
onDismissRequest = { reset = false },
title = { Text(stringResource(R.string.glasses_calibration_reset)) },
text = { Text(stringResource(R.string.glasses_calibration_reset_hint)) },
confirmButton = { TextButton(onClick = { onReset(); reset = false }) { Text(stringResource(R.string.glasses_calibration_reset_button)) } },
dismissButton = { TextButton(onClick = { reset = false }) { Text(stringResource(R.string.common_cancel)) } },
confirmButton = { TextButton(onClick = { onReset(); reset = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.glasses_calibration_reset_button)) } },
dismissButton = { TextButton(onClick = { reset = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
if (shown) AlertDialog(
onDismissRequest = { onCancel(); shown = false },
@@ -57,8 +59,8 @@ internal fun GlassesCalibrationControls(
if (!state.running) TextButton(onClick = {
if (state.phase == CalibrationPhase.SAVED) { onDone(); onCancel(); shown = false }
else onStart()
}) { Text(stringResource(if (state.phase == CalibrationPhase.SAVED) R.string.glasses_calibration_done else R.string.glasses_calibration_start)) }
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(if (state.phase == CalibrationPhase.SAVED) R.string.glasses_calibration_done else R.string.glasses_calibration_start)) }
},
dismissButton = { TextButton(onClick = { onCancel(); shown = false }) { Text(stringResource(R.string.common_cancel)) } },
dismissButton = { TextButton(onClick = { onCancel(); shown = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@@ -347,6 +347,7 @@ internal fun GlassesCornerButton(slot: Int, tint: Int, opacity: Int, onClick: ()
.clip(CircleShape)
.background(fill)
.border(1.5.dp, line, CircleShape)
.focusGlide(CircleShape)
.clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick)
.testTag("glasses-button"),
) {
@@ -382,6 +383,7 @@ private fun GlassesRecenterAction(label: String, tag: String, tint: Int, opacity
.clip(shape)
.background(fill)
.border(1.5.dp, line, shape)
.focusGlide(shape)
.clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick)
.padding(horizontal = 18.dp)
.testTag(tag),
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AlertDialogDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import androidx.compose.ui.window.PopupProperties
@Composable
internal fun GlideDialog(
onDismissRequest: () -> Unit,
properties: DialogProperties = DialogProperties(),
content: @Composable () -> Unit,
) {
Dialog(onDismissRequest, properties) { FocusGlideHost(content = content) }
}
@Composable
internal fun GlidePopup(
popupPositionProvider: PopupPositionProvider,
onDismissRequest: (() -> Unit)? = null,
properties: PopupProperties = PopupProperties(),
content: @Composable () -> Unit,
) {
Popup(popupPositionProvider, onDismissRequest, properties) { FocusGlideHost(content = content) }
}
@Composable
internal fun GlideAlertDialog(
onDismissRequest: () -> Unit,
confirmButton: @Composable () -> Unit,
modifier: Modifier = Modifier,
dismissButton: (@Composable () -> Unit)? = null,
icon: (@Composable () -> Unit)? = null,
title: (@Composable () -> Unit)? = null,
text: (@Composable () -> Unit)? = null,
shape: Shape = AlertDialogDefaults.shape,
containerColor: Color = AlertDialogDefaults.containerColor,
iconContentColor: Color = AlertDialogDefaults.iconContentColor,
titleContentColor: Color = AlertDialogDefaults.titleContentColor,
textContentColor: Color = AlertDialogDefaults.textContentColor,
tonalElevation: Dp = AlertDialogDefaults.TonalElevation,
properties: DialogProperties = DialogProperties(),
) {
FocusGlideWindow { overlay ->
AlertDialog(
onDismissRequest, confirmButton, modifier.then(overlay), dismissButton, icon, title, text,
shape, containerColor, iconContentColor, titleContentColor, textContentColor, tonalElevation, properties,
)
}
}
@Composable
internal fun GlideDropdownMenu(
expanded: Boolean,
onDismissRequest: () -> Unit,
modifier: Modifier = Modifier,
offset: DpOffset = DpOffset.Zero,
scrollState: ScrollState = rememberScrollState(),
properties: PopupProperties = PopupProperties(focusable = true),
content: @Composable ColumnScope.() -> Unit,
) {
FocusGlideWindow { overlay ->
DropdownMenu(expanded, onDismissRequest, modifier.then(overlay), offset, scrollState, properties, content)
}
}
@@ -48,7 +48,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AutoAwesome
import androidx.compose.material.icons.outlined.Memory
import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material3.DropdownMenu
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.shape.CircleShape
import com.droiddeck.launcher.core.AddonPack
import android.Manifest
import android.content.Intent
@@ -28,7 +29,7 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
@@ -63,7 +64,7 @@ import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import com.droiddeck.launcher.ui.GlideDialog as Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
@@ -129,7 +130,7 @@ internal fun HandCameraPrompt(sides: Set<String>, onAllow: (String?) -> Unit, on
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))
.selectable(side == id, role = Role.RadioButton) { side = id }
.focusGlide(RoundedCornerShape(8.dp)).selectable(side == id, role = Role.RadioButton) { side = id }
.testTag("hand-camera-$id")
.padding(vertical = 4.dp),
) {
@@ -144,12 +145,12 @@ internal fun HandCameraPrompt(sides: Set<String>, onAllow: (String?) -> Unit, on
}
},
confirmButton = {
TextButton(onClick = { onAllow(if (choose) side else null) }, modifier = Modifier.testTag("hand-camera-allow")) {
TextButton(onClick = { onAllow(if (choose) side else null) }, modifier = Modifier.testTag("hand-camera-allow").focusGlide(CircleShape)) {
Text(stringResource(R.string.hand_camera_allow))
}
},
dismissButton = {
TextButton(onClick = onNotNow, modifier = Modifier.testTag("hand-camera-not-now")) { Text(stringResource(R.string.hand_camera_not_now)) }
TextButton(onClick = onNotNow, modifier = Modifier.testTag("hand-camera-not-now").focusGlide(CircleShape)) { Text(stringResource(R.string.hand_camera_not_now)) }
},
)
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.shape.CircleShape
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
@@ -9,7 +10,7 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.AlertDialog
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
@@ -91,7 +92,7 @@ internal fun ItchKeyDialog(onDismiss: () -> Unit) {
Row(horizontalArrangement = Arrangement.Start) {
TextButton(onClick = {
ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ItchApi.KEYS_PAGE)))
}) { Text(stringResource(R.string.stores_itch_get_key)) }
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.stores_itch_get_key)) }
}
if (rejected) {
Spacer(Modifier.height(8.dp))
@@ -104,12 +105,12 @@ internal fun ItchKeyDialog(onDismiss: () -> Unit) {
}
},
confirmButton = {
TextButton(enabled = key.isNotBlank() && !busy, onClick = { submit() }) {
TextButton(enabled = key.isNotBlank() && !busy, onClick = { submit() }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.game_env_save))
}
},
dismissButton = {
TextButton(enabled = !busy, onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
TextButton(enabled = !busy, onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
},
)
}
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff. Show more