Compare commits

..
Author SHA1 Message Date
The412Banner 9cf869316d feat(bionic): zero-copy for Android buffers through gamescope (test)
gamescope 0936: advertise banner_ahb_v1, relay the host compositor's mode to clients, and pass each client's
Android buffer socket on to the host with the wl_buffer gamescope creates for the same dma-buf.
Compositor: with persist.droiddeck.zero_copy_ahb=1, programs that send their own gralloc buffers are asked for them,
and a fullscreen frame that is such a buffer goes on the display layer without a copy; every other frame, and any
frame while screen effects, frame generation, BFI or the cursor need the pass, keeps the copy path. Off by default.
2026-11-20 13:30:40 -05:00
The412Banner c3f2e6e12e Merge main into feat/bionic-runtime
Main f5d879f22: on-screen controls redesign (#2861) and the Library test fix for the Hidden tab (11fb8f59d),
which main's 56986b599 lacked. No conflicts.
2026-11-20 08:32:28 -05:00
The412Banner 7598dd0c22 fix(bionic): keep WINESTEAMNOEXEC for DroidDeck's Black Ops II fix
droiddeck-game-env sets WINESTEAMNOEXEC=0 for Black Ops II (#2892), and the launcher dropped it with the rest of
the guest environment. Wine then applied its own WINESTEAMNOEXEC=1 for Black Ops II Multiplayer and Zombies
(ntdll/unix/loader.c), so the fix did not reach DroidDeck-Bionic.
2026-11-20 08:25:55 -05:00
The412Banner 8f3d7a5a40 Merge main into feat/bionic-runtime
Main 56986b599 (15 commits: Library chips, toolbar and Manage stores (#2894, #2897, #2920), screen picker (#2912), frontend launch formats (#2872), Black Ops II WINESTEAMNOEXEC=0 (#2892), proot pack pin check (#2908) and others). No conflicts.
2026-11-20 08:16:48 -05:00
Kurt Himebauch f5d879f222 feat(input): redesign on-screen controls (#2861) 2026-11-20 08:12:37 -05:00
Kurt Himebauch 11fb8f59d4 test(library): cover Hidden in tab ordering 2026-11-20 08:01:41 -05:00
Kurt Himebauch 97e0251e6a fix(input): preserve control visibility and routing 2026-11-20 07:48:12 -05:00
Kurt Himebauch 7c2955b058 fix(preview): use the mouse touch label 2026-11-20 07:33:23 -05:00
Kurt Himebauch ec1d5126c4 fix(input): reconcile the second-screen picker 2026-11-20 07:30:42 -05:00
Kurt Himebauch 56986b5999 fix(session): Home suspends a game another app launched, so Cocoon can resume it (#2919)
* fix(session): Home suspends a game another app launched, so Cocoon can resume it

A game launched from another front end (Cocoon, ES-DE, Daijisho...) or a
home-screen shortcut went into picture in picture on Home. Cocoon brings a
suspended player back by moving its task to the front, which Android ignores
for a task in picture in picture, and the floating game covered Cocoon's
Resume/Close bar. The game kept running instead of suspending, Cocoon's
Resume did nothing, and the only way back was the picture itself.

Automatic picture in picture now applies only to games DroidDeck launched
itself. For games launched by another app (the existing returnHome launch),
Home suspends the session, which is what Cocoon expects. The picture in
picture button still works for those games.

* fix(session): a new launch intent refreshes the automatic picture in picture rule at once
2026-11-20 01:37:02 -05:00
FX1922 a29315f7e0 fix(library): manage the Hidden tab from Manage stores (#2920)
The Hidden tab was the only Library tab missing from Manage stores, and
it was turned on from the Display options instead.

- Hidden is now listed in Manage stores, after Custom games by default,
with its own switch and drag handle like Favorites and Custom games
- It starts off, and a switch someone already turned on keeps its state
- Removes the Hidden entry from the Display options
- The Hidden tab is still never shown in the music tab

Adds tests for the default, the saved switch and the sort order.
2026-11-20 09:22:35 +03:00
FX192 38efe4d6d5 feat(library): manage the Hidden tab from Manage stores instead of the Display options 2026-11-20 09:12:45 +03:00
FX1922 3f5280412d fix(stores): show the itch.io browse grid on the default filters (#2918)
The Itch tab only showed the browse grid after a filter had been
changed. On the default filters it fell back to the old shelves page
(What's New, Deals, Free Games, Trending), so the first thing people saw
was the pre-overhaul layout.

- The Itch tab now always shows the browse grid, like Game Jolt
- On the default filters it loads itch.io/games, itch's own default
Popular page
- The first page loads as soon as the tab opens, and the filters narrow
it from there
- Searching and the other stores are unchanged
2026-11-20 09:05:47 +03:00
FX192 37cf698af2 fix(stores): show the itch.io browse grid on the default filters 2026-11-20 09:01:42 +03:00
Kurt Himebauch fccd13689c feat(ui): one screen picker replaces the D button and the Second screen tab (#2912)
* feat(ui): one screen picker replaces the D button and the Second screen tab

The bottom screen's bar showed the panel's name as plain text, a D
button opened the menu, and the menu's Second screen tab picked the
panel. Now the panel's name is a dropdown right of the X. It lists
"DroidDeck menu" first, then the panels, with a check on the one in
use, so switching panels takes two taps instead of three.

The docked menu's header shows the same dropdown, labelled
"DroidDeck menu", in place of the highlighted D button. Opened there,
focus starts on the last panel, so one press of A goes back to it.
When the menu is on the top screen, the dropdown lists None and the
panels without the menu entry.

The Second screen tab is gone. Its "Show the game on" and display
choices are a Second screen group at the end of the Display tab. The
mode list's hint and its Mode heading are removed with their strings.

Previews of the docked menu (Controller and Display) and of a panel's
bar are added to the rendered preview cases.

* feat(ui): the swap button on the Keyboard + trackpad and Terminal panels

Every bottom-screen panel now has the swap button when the game can move
to the bottom screen; it was only on Deck grips, Profile controls,
Dashboard and Desktop. The swapped top-screen view already shows both
panels.
2026-11-20 00:26:28 -05:00
Kurt Himebauch 5051fc8b32 fix(session): the bottom screen takes touch again while a game runs (#2910)
* fix(session): the bottom screen takes touch again while a game runs

Since #2763, a transparent KeepTopActivity covers every other display while a
session is on top. Its window is NOT_TOUCHABLE, but Android gives a
translucent activity alone in its task an ActivityRecordInputSink that eats
every touch on that display (ENABLE_TOUCH_OPAQUE_ACTIVITIES, on for this
target SDK). With the dual-screen panel closed, the bottom screen's launcher,
Cocoon or any other app could not be touched until the session ended, and
the guard stayed over it after Home/PiP as well.

- The guard now takes touches itself: a touch removes it from that display.
- It comes back when the session is top-resumed again, or after 5 s if the
  session kept the top spot (the user touched the bottom screen once and
  stayed in the game).
- Stopping or entering PiP removes the guards; PiP keeps the session at adj
  50 with or without them, so they protected nothing there.

A/B on a Retroid Pocket Duo (Android 16, Cocoon as bottom home): the guard
is on top in every state it was on top on main, except the 5 s after a
bottom touch and PiP. Under lmkd pressure (kills down to adj 50, bottom
home killed 14-31 times per run) neither build lost the top spot.

* test(session): A/B tool for the keep-top guard on rooted dual screens, with Duo findings

* test(session): the guard A/B tool stops on a failed session start and cleans up an interrupted pressure run
2026-11-20 00:18:50 -05:00
MaxsTechReview 4e81030fb8 fix: source builds start a session again on storage without hard links (#2908) 2026-11-20 00:00:27 -05:00
Kurt Himebauch dc9d1b81cc feat(frontend): launch from every frontend file format and store, with per-store game files (#2872) 2026-11-19 22:41:04 -05:00
Kurt Himebauch 45c31a480a Default WINESTEAMNOEXEC=0 for Black Ops II (#2892) 2026-11-19 21:27:49 -05:00
Kurt Himebauch 00557703da feat(dev): preview states for the Library and the in-game menu (#2899)
* Developer tools: preview states for the Library and the in-game menu

Settings › Developer gets a Preview states group (shown with developer
tools on):
- Library: nothing installed, signed out of every store, or sample games
  in every store (each store's storefront games passed off as owned, a
  few as installed). A pill on the Library says which preview is on and
  ends it. Nothing is installed, removed or signed out, and the preview
  is never saved, so a restart always turns it off.
- In-game menu: opens the session menu over the launcher for Steam,
  Desktop or a game, without starting a session. Its switches change only
  the preview. LB/RB switch pages and B or Back closes it, as in a session.

* Preview states: Back closes the menu preview; signed-out preview covers expired stores

The launcher's exit gesture no longer takes Back while the in-game menu
preview is open, so Back closes the preview. The signed-out Library
preview shows the sign-in card for an expired store with cached games too.

* Developer tools: a UI zoo sheet for previews; previews are read-only

The Developer tab keeps one UI zoo row instead of the preview pickers. It
opens a side sheet listing the in-game menu (Steam, Desktop, game) and the
Library states; nothing shows until one is picked, and picking one closes
the sheet. A Library preview switches to the Library on All games.

While a Library preview is on, opening a game shows a short note instead
of its page, which would act on the real install behind the preview.
Size sorting uses the size a card shows, so a real install shown as not
installed sorts by its catalog size.

* Developer tools: preview shortcuts, a Library toolbar button for preview states

An opt-in Preview shortcuts switch (off by default) puts a flask button
in the Library's toolbar that picks the real library or a preview state
in place, so a state is a tap away while using the launcher normally.
The UI zoo stays the catalog of every preview.

* Preview states: no real sign-in or sign-out from a Library preview

The toolbar's sign-out button is hidden while a Library preview is on,
and the sign-in card's button only says previews are read-only, so a
preview never signs a real account in or out.
2026-11-19 21:26:31 -05:00
Kurt Himebauch fc9ad2447d fix(agent): the setup install repairs broken package dependencies instead of stopping (#2901)
* fix(agent): the setup install repairs broken package dependencies instead of stopping

* fix(agent): retry the package refresh and fetch missing archives during the setup install
2026-11-19 21:12:50 -05:00
The412Banner b7480aed4e fix(bionic): a default or game pick left on another bionic build moves to the installed one
DroidDeck-Bionic keeps one build, and updates move the default and the picks of the build they replace. One
left on a build an older app deleted without moving it stayed there: the guest found no such tool and fell
back to its own Proton. The release check now moves such a default (applied, pending, or the one the guest
fell back from) and such picks to the installed DroidDeck-Bionic build.
2026-11-19 21:05:03 -05:00
The412Banner b3103eb504 fix(bionic): drive Z: is the whole device again in prefixes DroidDeck-Proton set up
Proton copies a prefix's links as relative ones, so a prefix DroidDeck-Proton set up has dosdevices/z: ->
../../../../../../../../.. . In the guest that is "/", but DroidDeck-Bionic sees the Android tree, where the
link ends at the Linux userland folder: a game outside it (SD card, shared storage) was on no drive and Wine
crashed in its start-up path conversion (AIO on the SD card, SIGSEGV 2 s after the launch). The launcher made
z: only when it was missing; it now points z: at / on every launch when it names anything else.
DroidDeck-Proton follows z: -> / in the guest's view, with proot and without.
2026-11-19 21:05:03 -05:00
The412Banner 76bc0c236a fix(bionic): start bionic picks on DroidDeck-Proton when Run without proot is off
DroidDeck-Bionic runs only without proot. With proot on, the wrapper every adopted tool gets now hands a
launch sent to a DroidDeck-Bionic tool to the newest installed DroidDeck-Proton's own wrapper before any
setup step runs, so the game starts as if that Proton had been picked: its components, DirectAudio and
store steps apply to DroidDeck-Proton. Per-game picks and the default are left as set, so the games return
to DroidDeck-Bionic once Run without proot is on again. Without an installed DroidDeck-Proton the tool
still stops with its message.
2026-11-19 20:11:58 -05:00
Kurt Himebauch d4af37937a feat(ui): Steam Deck menu icons, and Compose previews rendered to PNGs (#2900)
* Rail and second-screen icons in the Steam Deck menu's style

Solid icons throughout the rail, and Steam's glyphs where Steam has the
same place: Library is the four-square grid, Stores the price tag,
Downloads the download arrow, Settings the gear. On the second screen,
Screenshots uses Steam's Media picture and Chat its Friends people.

* Compose previews of the launcher and the in-game menu, rendered to PNGs

Debug-only previews of the launcher on each tab and the in-game menu's
pages, built from the production composables with sample state and
no-op actions, at the Duo's handheld size and in portrait.
PreviewRenderTest draws each with Robolectric's native graphics into
app/build/preview-renders/, so a UI change can be looked at without a
device, and fails on a preview that throws or draws nothing.
docs/compose-previews.md says how to run and extend them.

* Preview renders wait for store accounts before drawing

A preview case can name what the render test waits for. The Library and
Stores cases wait for store accounts, which load on a background thread,
so their PNGs never catch the loading state.

* Preview renders step the paused clock while waiting for a case to be ready
2026-11-19 19:12:10 -05:00
Kurt Himebauch df48a85a71 feat(library): Library chips and toolbar like the Stores tab, a Custom games tab, and one Manage stores sheet (#2897)
* feat(stores): one Manage stores sheet for order, visibility and accounts

Store order, which stores show, and signing in or out now live in one slide-over, the
same one Edit tabs uses, with the same sorter: drag the handle, or Y to grab and the
d-pad to move, A to show or hide.

- The Library's chip row opens it from a sliders chip at its start, in place of the
  Store accounts button at the end of the row. The Stores tab's Arrange tabs opens the
  same sheet instead of rearranging the chip row in place.
- Each store row shows its account and one action: Sign in, Sign out, Reconnect when the
  login expired, or Add key for itch.io.
- A switched-off store leaves the Library's chips too; its games stay under All. A shown
  store that is signed out keeps its chip, and picking it shows the Stores tab's sign-in
  card in the Library.
- The Stores tab, the Library's chips and the sheet share one store order.

EditTabsSheet and the new sheet share SideSheet, and the tab and store lists share
SortableRows. Sign-in from the Stores tab, the sheet and the Library goes through
startStoreSignIn.

* feat(library): Library chips match the Stores tab, cards fade in on a store change, and the sheet only arranges

The Library's chip row uses the Stores tab's chips, store-colored theme and sliding fill.
Switching store fades and lifts the visible cards in, staggered, and still when animations
are off. Sign-in now lives on each store's own tab, so Manage stores drops its account
buttons and keeps order and show or hide, with each account as a line of text.

* feat(library): chips at the top, the chosen chip's toolbar under them, and a Custom games tab

The Library drops its title row and game count. The store chips are the top row, and
under them the chosen chip's name sits beside search, display, sort, view and the game
file actions, as in the Stores tab. The add button that sat in every header becomes a
Custom games chip that is always there: empty, it opens on a card that adds a game file
or a folder of games; with games in it, its toolbar has the add button.

* feat(library): store-colored focus in the Library, an aligned All chip, and sign out from a store's toolbar

The Library's grid takes the chosen store's theme, so focus rings and accents use its
color as on the Stores tab's pages. All gets a grid mark where the other chips have a
dot, so its label lines up, and the Manage stores chip matches the chips' height. A
signed-in store's toolbar has an account button that asks before signing out, with the
Stores tab's wording.

* feat(library): drop the chosen store's name from the toolbar

The chip above already names it, so the toolbar starts with search.

* fix(library): an empty library keeps its chips, so Custom games and a store's sign-in stay reachable

With no games and no store signed in, the Library used to switch to a separate empty
page without chips. It now shows the chips and toolbar like any other library, with the
empty-library note under All games.

* fix(library): no toolbar between the chips and a sign-in or empty Custom games card

The search, display, sort and view row has nothing to act on there, so the card sits
right under the chips, as it does in the Stores tab, and Down from the chip reaches its
button.

* fix(library): sign-in and empty Custom games cards fill the space under the chips

They were a fixed 300 dp, which left the bottom of the screen empty once the toolbar
above them was gone. They now take the grid's height minus the chip row.

* fix(library): drop the Installed label and lighten the cards' left fade

The Not installed row already divides the two sections, so the Installed label above
the first games goes. The dark fade on the left of the store sign-in card and the Steam
tab's art wall is lighter, so more of the art shows while the title stays readable.

* Library: share the hero wall card and wall fade; icon handle for sign out

The Custom games splash is now built from the same card as the store
sign-in splash, with a drifting wall of the library's covers instead of a
flat gradient and no hint text. The sign-in card and the Steam tab share
one wall fade. The sign-out step shows the account icon as its handle,
like the other toolbar steps, instead of a truncated label.

* Library: sort the Custom games tab in Manage stores; keep search reachable

Opened from the Library, the Manage stores sheet lists Custom games
among the stores so it can be grabbed and moved like them. Its place is
saved as the store it follows, so hiding that store or a new store
arriving keeps it where it was. It has no switch: the tab is always there.

The Custom games splash no longer replaces the toolbar while a search is
active, so a search that matches nothing can still be cleared.

* Manage stores: sort Favorites, Steam and Custom games; hide Favorites and Custom games

Opened from the Library, the sheet lists the Library's own tabs among the
stores. Each one's place is saved as the tab it follows, so hiding a
store or a new store arriving leaves it where it was. Favorites and
Custom games have a switch; Steam can be moved but not hidden.

The sheet takes focus only in controller mode, so opening it by touch no
longer switches to controller focus and its ring. Picking up a controller
while it is open moves focus into it.

Hidden games stay off the Custom games cover wall.

* Library: keep an expired store's tab and offer sign-in when nothing is cached

An expired account no longer drops its Library tab when it has no cached
games: the tab stays and opens on the sign-in card, as on the Stores tab.
With cached games it keeps listing them.
2026-11-19 17:40:55 -05:00
Kurt Himebauch 13a6e0606a feat(library): fold not-installed games under one row, link stores' owned games, and fix card sizes and streaming progress (#2894)
* feat(library): fold not-installed games under one row, link a store's owned games, and make card sizes step

The Library shows installed games first and folds every owned-but-not-installed game
under a "Not installed · N" row that a tap or the A button opens and closes; it replaces
the installed/all-owned choice that sat in the Filter menu, which now only appears for
Xbox's access filters. Controller focus stops on the row between the two sections and
stays on it across a toggle.

A store's profile card turns its "<store> · N games" line into the link to those games
in the Library, replacing the separate text button.

Card sizes pick a column count from the pane width, one column per step, so every
Larger/Smaller step changes the grid; before, several steps landed on the same count
and only stretched the cards.

GOG streams download and install together, and each byte update and each install
update used to flip the entry's stage and reset the install count. The install count
now survives those swaps and the detail page shows both: "Downloading 9% · Installing
25%", with the download as the fill and the install as a thin bar.

The store accounts button uses an accounts icon instead of a second "+", and the
Library tab uses a game controller instead of the video library icon.

* fix(library): a store with nothing installed folds to its Not installed row instead of an empty-state button

With no installed games to show, collapsing used to swap the grid for "No installed games
match these filters" and a Browse owned games button. It now leaves only the Not installed
row, which reopens the list the same way, by tap or by A.

* feat(library): count every owned game in the header and nudge the Not installed arrow

The "N games" next to the Library title counts the games folded under Not installed
too, so a store with nothing installed reads "316 games" instead of "0 games". The
row's arrow hops twice every few seconds toward the way it opens, and at once when the
row takes controller focus; it stays still when animations are off.

* feat(rail): draw the Library tab as game cases on a shelf

Material's video library icon read as a photo or video gallery.

* feat(library): the header counts the whole library, whichever store or filter is picked

* fix(downloads): keep a streaming install's two bars until the download reaches 100%

A download at 99.95% counted as finished, so the install bar disappeared and the fill
swapped between download and install progress for the last stretch.

* fix(downloads): decide a streaming download is finished from its byte counts

A float fraction rounds 99,999,999 of 100,000,000 bytes up to 1.

* feat(downloads): show a streaming install as one bar, downloaded behind installed

Two bars that moved almost together, under a label with both percentages, read as a
glitch. The chip now shows "Installing 61%" with a light fill for what has downloaded and
a solid fill for what has installed, like a video's buffer.

* feat(downloads): the game page shows one steady bar that only fills up

The detail page's chip shows "Installing 62%" from one overall value: the download fills
the first 90% and the install the rest, also when they stream together. The fill never
steps back across stage changes, keeps one animation key per download, and the chip
keeps a minimum width with tabular digits so it does not resize as the number grows. The
Downloads tab keeps its per-stage detail.

* feat(downloads): a full-size progress button on the game page that opens Downloads

The progress chip was a 24 dp pill beside 48 dp buttons. It is now a button the size of
Pause and Cancel, filled as the job advances, with a › that opens the Downloads tab and
sends the fly-in ball to the rail's Downloads item, by touch or A.

The Library card's percent and the bottom-screen download row use the same steady value,
so every place shows one bar that only grows. The overall value keeps the install part
when the last bytes arrive while the stage still reads Download.
2026-11-19 14:57:11 -05:00
The412Banner 220f7573a7 Merge main into feat/bionic-runtime
Main at cc93ab51c (17 commits since 123c431b8).

Conflicts (Proton list, main #2831/#2864/#2889): main's new release code with
the DroidDeck-Bionic source kept (it may use prereleases), the bionic row kept
in ProtonMenu and the Components count, the sources test with four tools.

Kept apart: DroidDeck-Bionic builds are prereleases of the DroidDeck-Proton
repository, which main now lists under Experimental; they keep their own row
here and leave the Experimental list (test added).

Main removed the VRAM-cap Vulkan layer (#2853); the bionic runtime pack no
longer builds it.
2026-11-19 14:45:09 -05:00
MaxsTechReview cc93ab51c5 Log the GPU ceiling and mid-session clock hold changes (#2893)
* Log the GPU ceiling, steps and mid-session clock hold changes

The clock log now records the GPU frequency steps and floor once in
its header, probes each limit file as readable or refused, and adds
the allowed GPU maximum to every sample in the CPU cur/max(of top)
style, so a vendor or thermal cap on the GPU ceiling shows up and
changes during a session are visible. Samples are unchanged when no
limit file is readable.

The limit reading is shared with the device info GPU clock range.

Turning the GPU clock hold on or off during a session now logs the
same line the session start logs.

* Ignore a zero GPU ceiling and log hold changes in order

A ceiling file that reads zero is no longer printed as a limit and is listed
as refused, matching how the step list is read. The hold state line is logged
under the same lock as the state change, so overlapping toggles cannot log
out of order.

* Find a GPU ceiling that turns readable later and probe step tables as tables

A ceiling file that read zero at session start is looked for again on each
sample until one is found, and the log notes where it came from. Step and
floor sources are probed with the same parser that reads them, so a table
with a leading zero is listed as readable.
2026-11-19 14:31:32 -05:00
MaxsTechReview de73e429cc feat(proton): list prerelease builds under Experimental and install from any archive (#2889)
* feat(proton): install prerelease builds

* fix(proton): harden prerelease archive installs

* refactor(proton): drop the superseded test build path

* fix(proton): list only current prerelease builds and label the file install

* fix(proton): hide prerelease rows that are already installed

* fix(proton): keep relative links and modes when unpacking zip and 7z builds

* fix(proton): name file installs without the archive suffix

* fix(proton): confirm a release is gone before removing its build and tighten archive handling

* Show the Experimental section without Developer tools

* Share the refresh guard, recheck sessions before removal, skip other architectures

The update check guard is shared between menu instances and held until the result is published, so a recreated screen joins the running check and results arrive in order. Automatic removal rechecks for a running session after each release lookup. Experimental assets for other CPU architectures are ignored, and in-tree links may start with the current directory.

* Keep an experimental build in place when a session starts during its removal

Removal and session start now share one lock. The tree is renamed out of the
tools folder under that lock only while no session is running, and deleted
afterwards, so a session that starts first keeps its build.
2026-11-19 13:41:57 -05:00
The412Banner 957aae95fa fix(bionic): wait for a game that renames its process; pass bare program names to Wine
launch.sh found the game only by its process name. Wine copies a program's main
thread name to the process name, and Chromium-based games (NW.js, Electron, CEF)
name that thread CrBrowserMain, so the game was taken as exited and Wine was
stopped a few seconds after start. The program Steam started now counts while it
runs.

proton turned a bare program name (DroidDeck's store steps run "cmd.exe") into a
path inside the rootfs that does not exist. Bare names now go to Wine unchanged,
as with Proton; relative paths are taken from the current folder.
2026-11-19 11:45:54 -05:00
LunaDL 71989b4cdb Feat: Adds customizable theme and fix inner gamer theme (#2850) 2026-11-19 11:07:55 -05:00
Tushar Gandhe 8f34554516 feat(game): shape the tab bar's LB and RB keys to the bar's rounded ends (#2856) 2026-11-19 11:06:19 -05:00
Kurt Himebauch 1456c0529d feat(agent): launch and quit store games, list the library, and run Xbox and cloud save commands from droiddeckctl (#2860) 2026-11-19 11:04:34 -05:00
FryMcNugget 786166ba1a fix(lab): Fast Lab builds no longer run out of memory compiling the app (#2862) 2026-11-19 11:03:56 -05:00
FryMcNugget 674e0d6fa4 feat(agent): keep the unsent message across leaving the Agent tab (#2863) 2026-11-19 11:03:08 -05:00
Kurt Himebauch d852b1a4e5 fix(storage): let launcher prefixes and Linux system caches be removed (#2867) 2026-11-19 11:00:59 -05:00
Kurt Himebauch 2ea857a07c fix(agent): keep the closed pet chat off the app below (#2868) 2026-11-19 10:57:00 -05:00
Kurt Himebauch 697f8e73fa fix: enable Steam shader pre-caching by default (#2888) 2026-11-19 10:11:22 -05:00
The412Banner e6b7158530 fix(bionic): run Xbox games (Windows exe path, Xbox runtime environment)
DroidDeck's Xbox launch (droiddeck-xbox) hands Proton the game as a Windows
path on a drive letter of its own (X:\droiddeck-xbox-*\Game.exe). The bionic
proton script turned it into a rootfs path, so Wine could not open it and the
game ended after 2 s; launch.sh also dropped the XODUS_* environment the Xbox
runtime needs (account bridge, save sync, mount and content roots).

- proton: a Windows exe path goes to Wine unchanged; XODUS_MOUNT_ROOT and
  XODUS_CONTENT_ROOTS guest Z: paths become their Android Z: paths
- launch.sh: keep XODUS_* and RUST_LOG; take the process name after the last
  backslash; no cd for a Windows path (starts in Steam's folder)

Tested on the Pocket FIT (swap into r34): Brotato (Game Pass) runs on bionic,
Xbox save written on bionic loads on DroidDeck-Proton.
2026-11-19 09:31:22 -05:00
kingokksa c4f4e18f87 fix: the virtual pads reach non-Steam programs, where udev is resolved through dlsym (#1593) 2026-11-19 08:37:43 -05:00
MaxsTechReview c2adf3b3dd feat(performance): switch the GPU top clock hold from the in-game menu (#2882) 2026-11-19 07:33:20 -05:00
MaxsTechReview f2d8e9e837 perf(storage): answer repeated SD library checks from the directory cache (#2881) 2026-11-19 07:33:17 -05:00
FryMcNuggetandmaxjivi05 44ade5eeee feat(proton): install experimental Proton builds from a .zip (#2864)
Components > Proton gains an Experimental builds card that installs a Proton build from a .zip, lists it as Experimental-<name> and removes it with its stored and unpacked originals and selections. Replacing a build keeps its user settings and is safe to interrupt.

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-19 02:32:30 -05:00
Kurt Himebauch dcebdac765 fix(input): removed kit controls keep their actions in gamepad layouts 2026-11-19 00:44:41 -05:00
Kurt Himebauch cd5e824c1b fix(input): keep full insets while the kit fits, restore the library after a failed save 2026-11-19 00:19:56 -05:00
Kurt Himebauch 10b21321b7 fix(input): save per-game copies with the edit, keep failed choices visible and grips clear of the d-pad 2026-11-19 00:11:01 -05:00
Kurt Himebauch 885c4f0a44 fix(input): keep reported insets unless they crowd out the pad 2026-11-18 23:58:48 -05:00
Kurt Himebauch 968828afbd fix(input): kit scale fits the safe area and oversized insets are capped 2026-11-18 23:52:00 -05:00
Kurt Himebauch c664b6cfbf fix(input): Back shortcut label fits its button 2026-11-18 23:49:53 -05:00
Kurt Himebauch 446480aa19 feat(input): Settings Controller is the in-game page for the default, with per-game layouts, Just this game and a direct remap page 2026-11-18 23:45:46 -05:00
MaxsTechReview c35da09d1a feat(proton): offer DroidDeck-Proton test builds in Components (#2831)
Components > Proton offers a DroidDeck-Proton pre-release that is ahead of Stable through the existing channel toggle. Automatic installs and updates stay on Stable.
2026-11-18 23:26:45 -05:00
Kurt Himebauch afa696cef2 fix(input): Steam kits and PlayStation face buttons no smaller than the old gamepad; Steam layout menu opens the Controller page 2026-11-18 23:11:52 -05:00
Kurt Himebauch b87da99d21 fix(input): keep Steam's touch controller plugged while its layout is hidden 2026-11-18 23:05:03 -05:00
Kurt Himebauch f180d98da7 Ubisoft: show art for owned games the profile list leaves out (#2865)
Games Connect owns but the GraphQL game list does not name were added
with no image. Take their art from the product configuration's
background_image and thumb_image, following localisation keys, from
Ubisoft's launcher asset CDN.
2026-11-18 22:13:49 -05:00
MaxsTechReview adf13d0bdd feat(session): manage memory automatically and remove the manual memory controls (#2853)
Memory in the Steam session is kept above a floor by a monitor instead of the zRAM, RAM cap and VRAM cap settings, which are removed.
2026-11-18 21:58:57 -05:00
The412Banner 20b5785b17 fix(bionic): Steam Input reaches DroidDeck-Bionic games
Games that read the controller through Steam Input (Valve's Steam Deck layouts with game
actions, e.g. Left 4 Dead 2) got no input on DroidDeck-Bionic. Valve's Android
libsteamclient keeps its named shared memory in a table inside the process, so the
SteamController streams and the IPC object DroidDeck's Linux Steam publishes in /dev/shm
never reached the game, and Android's libc has no sem_open, which the library's thread
semaphores need (the game hung once the data arrived).

libsteamshm.so (preloaded by the launcher) points the library's shared-memory open and
unlink at DroidDeck's /dev/shm under Steam's uid, the way the Linux client opens them,
and gives sem_open/sem_close a table of in-process semaphores. The two functions are
found by code pattern when the library first asks for the uid; a library that does not
match is left alone. DROIDDECK_BIONIC_STEAMSHM=0 turns the redirect off.
2026-11-18 21:37:54 -05:00
Kurt Himebauch 732c97831d fix(input): editor Reset keeps the D-pad direction overrides 2026-11-18 21:04:52 -05:00
Kurt Himebauch bf75dfb9c0 fix(input): saved D-pad keeps direction overrides, held directions wait for neutral and Reset regenerates an emptied gamepad 2026-11-18 21:00:31 -05:00
Kurt Himebauch 952f363b45 fix(input): D-pad keeps direction overrides, kit bindings survive layout edits and an emptied gamepad stays empty 2026-11-18 20:41:54 -05:00
Kurt Himebauch fdcb7eb3c4 fix(input): back grips fill their box as a capsule along its long side 2026-11-18 20:37:00 -05:00
Kurt Himebauch b29a5ef8aa feat(input): both sticks and both trackpads for Steam kits in portrait 2026-11-18 20:19:02 -05:00
Kurt Himebauch 0364792111 fix(input): Steam touch tint colors the D-pad and system buttons again 2026-11-18 20:11:39 -05:00
Kurt Himebauch e67c185f13 fix(input): hide on physical controller use only and refresh the kit when the virtual controller changes 2026-11-18 20:09:36 -05:00
The412Banner fdce4ba2a3 fix(bionic): read only the DD_ setting names
Bionic has no users on app builds from before #2800, so the BL_ fallback is not needed;
the launcher change is now the same rename main made.
2026-11-18 20:06:22 -05:00
Kurt Himebauch 318d64f3d6 fix(input): keep Steam grips on a small portrait pad and fit the bottom row 2026-11-18 20:04:00 -05:00
Kurt Himebauch 6f564caba6 fix(input): keep kit bindings, D-pad directions and Steam touch tint through the redesign 2026-11-18 20:02:37 -05:00
The412Banner c1cd433cb2 fix(bionic): read the DD_ setting names main uses since #2800
The launcher read BL_SYNC, BL_FSYNC_FIRST, BL_SYNC_FALLBACK and BL_VK_DRIVER and kept
BL_WIDTH/BL_HEIGHT; main sends these as DD_*. Read DD_* first and keep BL_* as a
fallback, so a tool build works with app builds from before and after the rename.
The Steam install-script test uses dd_components / DD_COMPONENTS_SETUP.
2026-11-18 19:58:18 -05:00
The412Banner c887aa1cd2 Merge main into feat/bionic-runtime 2026-11-18 19:56:47 -05:00
Kurt Himebauch 695ae21f93 feat(input): full-size portrait pad, one top row and sticks for every non-Steam kit 2026-11-18 19:40:27 -05:00
Kurt Himebauch ceb0360cd8 feat(input): drop the Deck panel tabs from the controls under the game 2026-11-18 19:17:43 -05:00
Kurt Himebauch 40665bbb1a feat(input): portrait pad under the game, kit-aware editor reset and leaner controller settings 2026-11-18 19:06:54 -05:00
The412Banner 6b349bfd8b fix(proton): move the default on DroidDeck-Bionic updates only
ProtonMenuAutoTest pins that a DroidDeck-Proton update leaves the default request alone; the guest already keeps a
DroidDeck-Proton default on the newest build. Only a DroidDeck-Bionic default was lost (the guest falls back to
DroidDeck-Proton), so replaceOlder moves the default for the Bionic family only.
2026-11-18 19:01:48 -05:00
The412Banner 952b6983e8 fix(proton): carry the default tool over when an update replaces it
ProtonExtras.replaceOlder moved per-game picks to the new build of a tool but left the default: with
DroidDeck-Bionic as the default, an update deleted the tool the default named, the guest no longer found it and
mapped every game to DroidDeck-Proton instead.

ProtonDefault.moveDefault works out the current default as chosen() does (a pending request, else the applied
default) and, when it names a replaced tool, writes a new request for the newest build with a higher seq.
replaceOlder calls it after moveGames. Tests cover a pending request, an applied default, defaults on other tools
and Valve tools, and the request file.
2026-11-18 18:46:04 -05:00
The412Banner df058c7c1a fix(bionic): register the tool with Steam under a name that contains Proton
Steam maps Windows save folders (WinAppDataLocal, WinMyDocuments, Saved Games ...) into
compatdata/<app>/pfx/drive_c/users/steamuser only for compatibility tools whose name contains "proton": the compat
manager in steamclient.so runs a case-insensitive search for "proton" on the tool before it fills in those paths.
DroidDeck-Bionic-12.8-rN has no such word, so every Steam Cloud rule with a Windows root failed ("Unable to resolve
path with root WinAppDataLocal (3)") and Steam never uploaded those saves (MIO: Memories in Orbit).

compatibilitytool.vdf now names the tool $NAME-Proton. The folder, the version file and the release keep $NAME, which is
what DroidDeck matches on.

Tested on the Pocket FIT with r30 renamed this way and MIO run by DroidDeck-Bionic: Steam watched
.../pfx/drive_c/users/steamuser/Local Settings/Application Data/MIO/... and no longer reported the root as unresolvable.
2026-11-18 18:46:04 -05:00
Kurt Himebauch 123c431b8e feat(ea, ubisoft): cloud saves and a kept Ubisoft Denuvo token (#2824)
* feat(ubisoft): keep Denuvo game tokens per account and product until the game invalidates them

* feat(ubisoft): sync cloud saves through Ubisoft's cloud save service

* fix(xbox): turning cloud saves off passes the offline mode the game save runtime reads

* fix(ubisoft): Ubisoft games list their shared prefix, so they get a saves and cloud tab

* feat(ea): sync cloud saves through EA's cloud sync service

* fix(ea): sync at EA launch and exit, keep one rule snapshot, and check the cloud copy under the write lock

* fix(ubisoft): exact slot versions, scoped save export, and a Denuvo cache bound to its account

* fix(ea): fresh rules per sync, checksums required, backup before restore, and sign-in shown on the saves tab

* fix(ubisoft): launch-time sync on the shared prefix, saves scoped to the game, and Denuvo bound to each launch's account

* fix(ea): back up only the saves a restore replaces, refuse truncated manifests, and need a master title id

* fix(ubisoft): treat a slot whose bytes changed since the last sync as a conflict before uploading over it

* fix(ea): one resolved save folder per sync, refuse case collisions, and walk each folder once

* fix(ubisoft): sync only identified slots, keep live saves and backups safe, and tie a pending eviction to its account

* fix(cloud): a forced download fetches every saved conflict and keeps the ones it could not write

* test(ea): keep the cloud save cases in EaTest

* fix(ubisoft): report only written slots, keep drift conflicts, read whole headers, and never rename a named eviction

* fix(ea): keep real save folders in the inventory, back up any restored file, refuse duplicate or malformed cloud listings

* fix(cloud): commit Ubisoft slots one at a time and stop on a newer cloud write, name skipped and blocked slots, keep unsent conflicts

* fix(ubisoft): acknowledge an invalidation only once its marker is published and never serve a kept token after it

* fix(cloud): a cloud request the launcher cannot write still starts the game and keeps the exit upload

* fix(cloud): scope Ubisoft sync state to the account and product, compare alike slots, keep committed progress, and name partial slots

* fix(ea): ask for sign-in after a rejected refresh, upload saves reached through folder aliases

* fix(cloud): a launch that stops waiting for the cloud download claims it back, so no save is written once the game starts

* fix(ubisoft): name the account in an invalidation marker and never hold the token lock across a pipe write

* fix(ea): only invalid_grant asks for sign-in again, and case collisions count only among synced saves

* test(epic): let the launcher's ask doubles take the claim flag

* fix(ea): apply save rules in their order, match bare patterns inside the save folder, and resolve LocalLow and install folders

* fix(ubisoft): stamp a fresh identifier into a new save that has none, so it can sync

* fix(ubisoft): answer a burn ticket request as unavailable instead of leaving the game waiting

* fix(cloud): read EA manifests with the XML parser, clear conflicts whose sides match, and bound the claim and stall tests
2026-11-18 18:32:06 -05:00
Kurt Himebauch 0fba656ee2 feat(input): draw on-screen controls per virtual controller with a corner button and a simpler controller page 2026-11-18 18:08:30 -05:00
Kurt Himebauch 6ed281f78d feat(xbox): install MSIXVC2 back-compat titles from their content boxes (#2851)
* feat(xbox): install MSIXVC2 packages from their encrypted content boxes

* feat(xbox): run a package's custom install actions once per prefix

* fix(xbox): launch the program a launcher menu names instead of the menu

* fix(xbox): check free space before an MSIXVC2 install starts

* fix(xbox): keep a forwarded launch path relative when the install folder is reached through a link

* fix(xbox): rebuild the MSIXVC2 patch on the final legacy install

* fix(xbox): keep a backup whose release fails, and test an interrupted restore

* fix(xbox): verify resumed msixvc2 files, contain writes, decode install action arguments

* fix(xbox): keep one completion record per msixvc2 file, never follow a linked install state

* fix(xbox): drop a torn msixvc2 completion record before appending to it

* fix(xbox): repair a torn msixvc2 record from its tail instead of rereading it
2026-11-18 16:59:45 -05:00
Kurt Himebauch b43724e5f3 revert(hud): redraw the FPS graph every game frame outside Strip (#2857)
revert(hud): redraw the FPS graph every game frame outside Strip (#2843)
2026-11-18 16:39:07 -05:00
The412Banner 217c58d4b3 fix(bionic): Wine layer whose exception search stops on a stuck or broken frame
Layer build-bionic-layers-20261118-v16-unwind (proton-wine fecf7376 + a188791d on the ARM64EC code-map fix):
- the exception search and unwind stop when a frame does not move: Steam's iscriptevaluator.exe no longer
  spins forever at 100 % CPU when FEX faults in its own code (proven on the Elite: 4 s instead of a hang);
- the stack pointer is checked before each unwind step: closing Brawlhalla normally no longer overflows the
  stack and hangs the game; it exits (proven on the Pocket FIT: exit in 2 s, "invalid stack pointer
  5e6fb70000" instead of 48 nested faults).
2026-11-18 16:03:42 -05:00
Kurt Himebauch 5b7409d1d5 fix(game-env): restore D3D12 12_2 and shader model 6_9 for Kingdom Come: Deliverance II (#2787)
* fix(game-env): run Kingdom Come: Deliverance II at D3D12 feature level 12_0

* fix(game-env): restore feature level 12_2 and shader model 6_9 for Kingdom Come: Deliverance II
2026-11-18 15:49:44 -05:00
Kurt Himebauch f0f7f7a116 feat(agent): permission modes for every harness, asking first by default (#2854)
* fix(agent): show the side menu's agent page whenever the tab is shown

* feat(agent): permission modes for every harness, asking first by default

* test(agent): give the drawer page tests their agent page explicitly

* fix(agent): fail turns on lost stdin writes, wait for Codex to initialize, keep approvals visible

* fix(agent): redo setup on a kept process after it failed, keep approvals in view

* fix(agent): keep full-page panels closed while an approval waits
2026-11-18 15:43:55 -05:00
24f5fa20f8 fix(session): show the recorded reason when a session fails to start (#2841)
* fix(session): show the recorded reason when a session fails to start

The ended screen now shows any recorded start-up failure message except a plain guest exit, not only PROOT_MISSING. The graphics runtime staging and game environment publish failures now record GRAPHICS_RUNTIME_FAILED and GAME_ENVIRONMENT_FAILED with their own messages instead of looking like a guest exit.

* i18n(session): translate the start failure messages

---------

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-18 15:10:14 -05:00
TapuukandTapuuk e4404fbb92 perf(hud): throttle FPS-graph redraws for every HUD size (#2843)
Only the Strip size limited graph redraws; Minimal, Pill, Tiles and Mega
invalidated on every display frame for the whole session. All sizes now
redraw the graph at most once per GRAPH_REDRAW_MS (66 ms).

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
2026-11-18 15:09:38 -05:00
Kurt HimebauchandTimmyCraft a5d8abeab4 feat(xbox): install legacy EAppx titles through Windows Update (on main) (#2825)
* feat(xbox): install legacy EAppx titles through Windows Update

A legacy Store title does not ship as MSIXVC. It ships as an encrypted
EAppx bundle, which streaming rejects, so the store could list the game
and never install it.

Accept EAPPX and EAPPXBUNDLE beside MSIXVC, carry the format through the
catalogue, the install record and the cached library, and dispatch
legacy-install for those formats.

Two backend patches do the work:

- droiddeck-legacy-packages.patch lets the plan, license and extract
  verbs handle a legacy package, and expands a bundle in place (nesting
  bounded at three), decrypting each inner EAppx with the same keys.
- droiddeck-legacy-install.patch adds legacy-install: resolve,
  license, download, extract, hoist AppxManifest.xml to the game root.
  Resolution asks the Xbox content service first and Windows Update
  second, because some legacy products return no files from the content
  service at all. The WU endpoint needs no Xbox credential but chains to
  Microsoft's ECC Product Root CA 2018, which Android's CA bundle does
  not carry, so that one public root is pinned for those requests.

The manifest reader accepts AppxManifest.xml as well as
MicrosoftGame.config, since a legacy package carries only the former.

Running it against a real title exposed four things that only show up at
full size:

- A licence names a key by its 16-byte content id, while a bundle header
  names it as a (content id, package id) pair. Reading the 16-byte id
  yields a different pair, so a complete key file reported every key
  missing and no bundle could be opened. Keys are now aligned against
  the header's own ids before the header is judged.
- Windows Update answers with several updates whose PackageContentId
  differs from the bundle's own. Licensing used to take the first and
  fail with content-http 400; every candidate is now tried in order,
  preferring the one the container is named after.
- A container already in .xodus-container is reused rather than fetched
  again, so a failed run does not cost another download of tens of
  gigabytes. The space preflight no longer counts a container twice for
  the same reason.
- A bundle that carries add-on packages unpacks each into its own
  folder, leaving the manifest one level down. Hoisting lifts the
  largest folder that holds a manifest, so the game still lands at the
  root beside its add-ons.

Unpacking now reports bytes written, so the install bubble fills while a
package is decrypted instead of holding a single unchanging word.

* fix(xbox): unpack a legacy package across cores and report the bytes

Unpacking one title ran as a single thread on a saturated core at about
40 MB/s. Files sit at independent offsets, so each worker now opens its own
handle and takes every Nth file, with a 1 MiB read buffer in place of the
8 KiB default that turned one 64 KiB block into eight reads. Measured on the
Forza Horizon 4 bundle, writes went from 40 MB/s to about 200 MB/s.

Two things the first full-size run exposed:

- The container was deleted only after the whole nested tree was unpacked,
  so a title that holds its package as one member held the archive and the
  decrypted copy at once. On this device that runs out of space partway
  through the second stage. The container is now deleted once its members
  are on disk, which frees the archive before they are decrypted.
- A bundle member is written as a single file, so a counter that advances
  when a file finishes stays at zero for the whole of the longest stage.
  The reported figure now also follows the growth of the destination while
  that is the case, and never moves backwards when the container is freed.

Progress is exact during the per-file stage: each file's declared length is
added as it lands, instead of walking the whole destination every tick.

* docs(xbox): record the completed legacy install

The evidence section said a finished legacy install and its decrypted
contents were unverified, because the first run was still unpacking when it
was written. That install has now completed on the same device: the
85,219,173,025-byte container produced 79.3 GB at the game root with
AppxManifest.xml and the package DLLs directly beneath it, and the launcher
lists the title as installed.

It also records what unpacking costs, since that decided the change: one
thread held a core at 100% for about 40 MB/s and four reach about 200 MB/s,
and releasing each container once its members are on disk is what keeps the
peak footprint at one package rather than the archive plus its contents.

The launch is not part of this evidence, and the entry says so.

* fix(xbox): place the 64-bit framework beside a legacy title

A Windows Update framework category lists one package per architecture under
identifier-only names. The first package was unpacked, which on this device was
the x86 build, so a 64-bit title got 32-bit DLLs and every load failed with
STATUS_INVALID_IMAGE_FORMAT. Candidates are unpacked now and only the one whose
manifest declares ProcessorArchitecture="x64" is kept.

The framework folder was also never created, so a finished download failed at the
move with "no such file or directory".

unzip.rs belongs to this patch: legacy-install calls it and the recipe left it out,
so a rebuild from the pinned source could not compile.

* feat(xbox): report a UWP entry point at launch

An unpacked package can name a COM class as its entry point instead of
Windows.FullTrustApplication. That class is a UWP application, which expects the
app model to activate a view; Wine has no host for it, so the launch died inside
the loader with no explanation. The launch now reads the entry point and reports
uwp-entry-point, and full-trust packages are unaffected.

Forza Horizon 4 is such a package: its manifest names Forza.App. Its frameworks
are installed and the loader is clean before that point.

* fix(xbox): report why a launch was refused

A failed prepare replaced the backend message with a fixed sign-in hint, so a title
that was not installed or a runtime that refused all read as a bad account. The
reason is kept, with paths and URLs dropped, and written to the store log.

* fix(adb): dismiss the keyboard on Search and Go

Search and Go were terminal IME actions but were not handled, so focus stayed in
the field and the keyboard covered the results it had just fetched.

* fix(xbox): keep a cache row without a legacy format plain

Decoding added a format key with an empty value to every cached title, so a
library restored from storage no longer matched the one that was saved.

* test(ui): match the manifest message a legacy package reports

The message covers both a MicrosoftGame.config and an AppxManifest, so the
assertion follows the text the content dialog now prints.

* fix(xbox): refuse to start a title that needs the Windows app model

A legacy package that names an entry point other than
Windows.FullTrustApplication is a UWP application. Wine has no app-model
host, so starting its executable crashes inside the loader and the launch
looks like nothing happened. Read the entry point from the manifest the
installer already parses and stop the Play action with a message instead.

Forza Horizon 4 names Forza.App, so it installs and reports as installed
but cannot be started here yet.

* fix(xbox): dispatch on the container format of the chosen package

The catalogue records the format of the first installable desktop package, and
the picker only replaced the content id. An offer that lists MSIXVC and a legacy
container would then hand the legacy id to streaming, or the streamed id to
legacy-install, and the install failed after resolution had succeeded.

The choice now carries its own format and the catalogue value only fills a gap.

* fix(xbox): keep an extraction reason that the sanitizer rewrote

The extraction sanitizer replaces anything outside letters, digits, space, dot,
underscore and dash with a question mark, so a reason such as "(os error 28)"
arrived as "?os error 28?" and the allowlist dropped the line. The failure then
showed only the stage code, with no cause.

Add that replacement character to the class the allowlist accepts.

* fix(xbox): print the reason a launch was refused

The account channel sends a reason with a refusal, and the guest replaced it
with a fixed sign-in message, so a title that was never installed still read as
a bad account. The guest now shows the reason it was given, and a token holding
a path is dropped whole instead of having its slashes removed and its directory
names kept.

* build(xbox): leave RUST_TEST_THREADS unset when the host has no value

The recipe always passed the variable, empty when the host had none, and the
pinned test harness rejects an empty count. On an ARM64 host that runs cargo
test, so the default local build failed before compiling.

* fix(xbox): rebuild the backend patches from the tree that ran

The two patches in this branch were not the ones the verified install ran, and
one of them did not compile. `unzip.rs` inflates deflated entries but the
dependency that provides the inflater was never added, so `prepare.py` produced
a tree that failed at `flate2::read::DeflateDecoder`. Anything else missing fell
into the same gap: the install stage reported no bytes, so the bar held one
value for the whole unpack, and a container a stopped run had finished was
downloaded again.

Rebuilt from the patched source, and fixed the defects a review of the patch
found:

- Unpacking reports bytes again: the workers count each file's declared length,
  and for the single-file bundle member the folder's growth stands in, which is
  what the device run showed.
- A finished container is reused, so a retry after a failure past the download
  does not spend hours fetching it again. The space preflight counts it as
  reclaimable, since the retry truncates it first.
- An install over a folder that already has a manifest replaces the old files
  instead of leaving the new package nested and reporting success. A first
  install still refuses to merge into an existing target.
- The manifest search looks at the depth a nested bundle writes, not only one
  level down.
- `withdraw_libraries` removes only the DLLs `copy_libraries` recorded copying,
  so a framework replacement cannot delete a library the title owns.
- ZIP64 sizes and offsets stay `u64`; truncating them to `u32` read the wrong
  local header past 4 GiB.
- The extraction checks the blockmap length against the footer's before writing,
  which the crate only does when asked.
- The container being unpacked is never treated as a nested member, so
  `extract-eappx title.eappx .` no longer re-enters and deletes its own input.
- `flate2` is declared and the lock is updated.

`prepare.py` reproduces this from a pristine checkout and `cargo test` passes on
it.

* fix(xbox): apply the legacy install patch over the Nexus 0.2.15 backend

* fix(xbox): install only the newest x64 build of a legacy title and size the space check at its real peak

* fix(xbox): install a store package that is a plain archive instead of an XVD

* fix(xbox): refuse a package entry that ends before its recorded size

* fix(xbox): credit only complete staged containers toward the free space a legacy install needs

* fix(xbox): bound each package entry to its data and check ZIP64 decoded sizes

* fix(xbox): refuse duplicate package names and clear an unfinished download before measuring space

* fix(xbox): bound package entries by the next header and stage a plain package until it validates

* fix(xbox): hold the install folder lock through a legacy install

* fix(xbox): fall back to an older build when Microsoft refuses the newest one a license

* fix(xbox): keep the registered device across sign-out

* feat(xbox): explain device-limit and license refusals, with a link to manage devices

* fix(xbox): locate each build only once licensed, roll back a failed package swap, report the final license answer

* fix(xbox): skip trial and preorder packages, read runtime behavior, keep licensing timeouts

* fix(xbox): keep a failed package swap recoverable, size bundles up front, report key-write and framework errors cleanly

* fix(xbox): drop a pending manifest check on any newer launch, keep committed backups out of restores, match the app-model order

* fix(xbox): cancel pending launch checks on a new intent, remember entries a rollback could not remove

* fix(xbox): clear the removal list before a restore moves old files back

---------

Co-authored-by: TimmyCraft <46533729+TimmyTurner51@users.noreply.github.com>
2026-11-18 14:14:26 -05:00
DeathKhanandmaxjivi05 7680b4d771 fix(ui): fit the color picker on landscape screens (#2542)
* fix(ui): lay the color picker out side by side on wide screens

On a landscape screen the single column was taller than the screen. The wheel and swatches now sit beside the sliders and the hex field, so the whole picker is visible without scrolling.

* fix(ui): give the landscape color picker a larger wheel and one closing row

On a wide screen the picker still reached both screen edges: three sliders, the hex field and the buttons were stacked beside a small wheel. The wheel now fills the height of the sliders, and the comparison chip, the hex field, Cancel and OK share one row under them, so the dialog keeps a margin. OK is centered in both layouts.

* fix(ui): keep the column color picker in landscape windows narrower than 600 dp

The side by side layout needs 382 dp for its closing row before the hex field gets any width, so a small landscape window could squeeze the field to nothing.

* fix(ui): fit the side by side color picker on short landscape screens

On a 740 x 360 dp phone the closing row sat below the screen and had to be scrolled to. The wheel now takes its size from the screen height (up to the old 216 dp), and on a short screen the sliders get a shorter track and tighter spacing, so the whole dialog fits down to about 360 dp. Screens 468 dp tall and up, such as the Odin 3, look as before.

ColorPickerLayoutTest now also checks that OK is on screen without scrolling at 740 x 360, 800 x 384 and in portrait.

* chore: drop the added comments

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-18 14:05:30 -05:00
The412Banner 39a3535eb5 fix(bionic): stop waiting 90 s for a program that already ended
launch.sh waited up to 90 s for a process named like the program before it waited for the program to end.
A program that ends within a second - Steam's install-script evaluator when it has nothing to do - was
never seen, so every real evaluator run held the game's start back by 90 s.

The wait now also ends when the started Wine process is gone and no program of this prefix is left
besides Wine's own services (wineserver, services.exe, winedevice.exe, plugplay.exe, explorer.exe,
svchost.exe, rpcss.exe, conhost.exe, start.exe) and this script's window tagger. A launcher that leaves a
game running is waited for as before. Only the app's own processes are read.

Tested in Android's shell on the Pocket FIT with stand-in processes: program gone -> the wait ends at once;
a child still running in the prefix -> the wait goes on until it ends; only the tagger or another prefix's
program left -> the wait ends at once.
2026-11-18 13:25:30 -05:00
5afa8695a8 fix(session): undo start-up work when a session is stopped while starting (#2840)
* fix(session): undo start-up work when a session is stopped while starting

* style(session): drop the added comment

---------

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-18 13:14:49 -05:00
DeathKhanandmaxjivi05 8cfe19cd13 fix(apps): B in the folder name field saves the name and returns to the title (#2534)
* fix(apps): B in the folder name field saves the name and returns to the title

With a controller, B in the folder name field only hid the keyboard and left
focus in the field. The field now takes B as its way out: the keyboard goes,
the name is saved and focus lands on the folder title. AdbTextField gets an
optional onBack for this; fields without it behave as before.

* fix(apps): closing the bottom-screen keyboard also leaves the folder name field

With typing on the bottom screen, B is handled there and only cleared focus,
so the folder name was not saved. A field with onBack now leaves through it
on that path too.

* fix(apps): the folder sheet hands B to the name field while renaming

The sheet's own B handler sits above the name field and could take the press
first, closing the folder. While the name is being edited the sheet now treats
B as leaving the field: the keyboard goes, the name is saved and focus lands
on the title.

* chore: drop the added comments

* Return focus to the folder title once the frame settles after renaming

* Only let the active typing request close the field

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-18 13:13:04 -05:00
kingokksaandmaxjivi05 fc5dd7f3c5 fix(input): the layout editor shows the same placement as the session (#2783)
* fix(input): the layout editor shows the same placement as the session

Editing a layout stored for one orientation while the editor is open in
the other drew raw stored coordinates, so elements turned into flat,
overlapping bars. Route the editor through OnScreenLayout like the
on-screen controls: matched layouts are regenerated for the current
screen, everything else follows the same fit, and the dirty check
compares against what was shown when the editor opened.

* fix(input): reset and scale in the editor frame the session saves

The editor draft now carries the frame it was rebased to: the gamepad
scaler is rebuilt with the editor surface's real dimensions when edits
begin, so reset regenerates legacy controls for the display the user is
editing instead of the primary display. Stock default positions keep
their own frame aspect and are refitted into the draft frame before
being applied, so reset on a differently shaped display lands where the
editor shows and no longer marks an untouched layout as changed.

* fix(input): refit only the default positions on reset and update the test callers

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-18 12:57:15 -05:00
unixenon cca84f7b6b fix(setup): show the saved Mali (Venus) switch after the app restarts (#2684)
refresh() reloaded the Mali bridge switch from SessionPrefs but not
Mali (Venus), so after any process restart (an app update, or Android
reclaiming the app) Setup showed "Mali (Venus): off" while the saved
setting stayed on and sessions kept using Venus. Only opening the
Performance page (refreshCores) loaded the real value. The Vulkan
1.2 warning (venusHostVulkan) was dropped the same way.
2026-11-18 12:55:28 -05:00
MaxsTechReview d94906bd9c fix(audio): hold host restarts until an in-flight sink guard command finishes (#2821)
* fix(audio): hold host restarts until an in-flight sink guard command finishes

* fix(audio): judge sink guard commands by exit status and reap timed-out pactl

* test(audio): hold the sink guard command until the test has checked the queued restart

* test(audio): bound the stop check so a blocking stop fails instead of hanging

* test(audio): bound the exit check while the sink guard command is paused
2026-11-18 12:55:25 -05:00
801da99c11 fix(game-env): per-game DROIDDECK_GAME_TU_DEBUG reaches the game (#2781)
* fix(game-env): per-game DROIDDECK_GAME_TU_DEBUG reaches the game

game_gpu() ran on the inherited environment before apply_config() added
the entries from game-environment.json, so a DROIDDECK_GAME_TU_DEBUG
(or DROIDDECK_GAME_MESA_NO_ERROR) set for one game was passed through
unchanged and TU_DEBUG was never set. apply_config() now returns its
result through game_gpu(), so a per-game value is applied the same way
as one from the session.

* fix(game-env): a game's own TU_DEBUG still wins over a shared prefixed one

Resolve the prefixed GPU keys inside the shared entries and inside the
game's entries separately, before the game's entries are laid over the
shared ones. A game's plain TU_DEBUG (or its removal with null) now
beats a shared DROIDDECK_GAME_TU_DEBUG, and a prefixed value set for one
game still applies.

* fix(game-env): keep a plain TU_DEBUG over the prefixed key in the same profile

---------

Co-authored-by: zdennisz <15849186+zdennisz@users.noreply.github.com>
Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-18 12:55:22 -05:00
TapuukandTapuuk fd2f1eec8a ci: fail the checks gate when store engine tests fail (#2844)
* ci: fail the checks gate when store engine tests fail

* test(ci): expect store-tests in the checks gate

---------

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
2026-11-18 12:43:31 -05:00
TapuukandTapuuk 19fa6fd8e2 fix(files): keep private app folders out of the documents provider (#2846)
The provider rooted at dataDir exposed the wireless ADB pairing identity, shared_prefs, databases, store logins and Steam's saved login to any app the user picked the DroidDeck root for. Those folders are now hidden from listings and search, refused on open, and can't be created, renamed into, or carried out by renaming, moving or deleting a parent.

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
2026-11-18 12:42:37 -05:00
The412Banner d0796720b8 fix(game-env): skip Steam's evaluator when its scripts only run marked processes
DroidDeck skipped Steam's iscriptevaluator.exe only when the evaluator had once finished the exact same script
file. Steam rewrites evaluatorscript_<app>.vdf between launches (on the Elite it wrote two different files for
Brawlhalla within minutes), so the skip missed and the real evaluator ran again; on bionic that run hung.

install_scripts_done() now also counts the scripts as done when every action in them is a "run process" entry
and all their hasrunkeys are set in the prefix: Steam's evaluator would run nothing then. droiddeck-seed-redists
sets those keys for Steam's common redistributables. Scripts with other actions (registry values and the like)
still run once and are recorded as before. This applies to DroidDeck-Proton and DroidDeck-Bionic alike.

Checked with the Elite's real script (Steamworks Shared 228980, VC++ 2019 x86 + x64) and prefix registry and a
stamp that does not match: the old rule ran the evaluator, the new one skips it. Tests updated: a rewritten
marked-only script counts as done, a script with a registry action still runs once and is recorded.
2026-11-18 11:32:20 -05:00
The412Banner c1509a0c11 fix(bionic): clear a prefix's FEX code cache that another FEX build filled
FEX keeps translated code per program in the prefix (AppData/Local/fex-emu/DiskCache) and reuses it with any
FEX that runs the prefix later. On the Elite, Brawlhalla's prefix (made 11-07 by DroidDeck-Proton 11-12.2) held
the cache that FEX build wrote for Steam's iscriptevaluator.exe. This tool's FEX loaded it, read through a null
pointer at libarm64ecfex.dll+0x1B118, and Wine's exception unwind then looped forever on a frame in FEX's
dispatcher memory, so Steam's install-script step never ended and the game never started.

launch.sh now keeps the id of the FEX files it runs (pfx/.droiddeck-fex-cache) and removes the prefix's FEX
DiskCache when that id differs or is unknown. This also covers a different FEX picked in the Components tab.
Each existing prefix loses its FEX cache once.

Tested on the Elite (r28 with this launch.sh, the stale cache file put back, DroidDeck's install-script stamp
reset): the cache was cleared, the real evaluator finished, DroidDeck recorded it and Brawlhalla started. Before
the fix the same setup hung in 5 of 5 runs; with an empty or freshly written cache it passed.
2026-11-18 11:28:26 -05:00
The412Bannerandmaxjivi05 a139d9eff4 fix(compositor): hold releases from synchronized subsurfaces until the parent commits (#2721)
* fix(compositor): hold releases from synchronized subsurfaces until the parent commits

gamescope's Wayland backend moves layers between synchronized subsurface
planes and commits the parent last. Each child commit was applied at once,
so a buffer leaving one plane could be released before the next plane took
it, and gamescope then logged "Compositor released us but we were not
acquired". A buffer attached again also dropped its queued release, and the
buffer trace records every attach.

* fix(compositor): hold a synchronized release at its sync boundary and recheck holds on set_desync

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-18 11:10:57 -05:00
FX1922 2a274623da fix(music): hide the Favorites soundtrack collection until it has a track (#2835)
The Favorites collection in the music tab was always listed, even when
no tracks had been favorited.

- Favorites is now only listed in the Collections source once it has at
least one track
- With no favorites and no other collections, the Collections tab no
longer shows
- Adding a track to Favorites brings it back
- The collection detail page still resolves Favorites by id, so an
already-open page does not close when its last track is removed

Adds a test for the empty, populated and other-collections cases.
2026-11-18 18:51:02 +03:00
MaxsTechReview bb5218746f fix(drivers): Auto gives Xclipse GPUs the old RADV pair only where that build supports them (#2337)
* fix: route unsupported Xclipse generations upstream

* fix: let Auto load upstream Xclipse pairs

* fix: clear stale auto-owned Xclipse RADV pair

* fix(drivers): clear independently owned fallback selections

* fix(drivers): keep independently chosen drivers when session start reconciles an unsupported Xclipse

* fix(drivers): name the Xclipse from Vulkan before session start picks which drivers Auto clears

* fix(drivers): keep the Vulkan query off the UI thread when session start reconciles Xclipse drivers

* test(drivers): control Xclipse GPU family in auto-driver reconciliation test

* fix(gpu): guard Xclipse auto-driver cleanup when running and handle open-driver bundles

* fix(gpu): keep active RADV-Xclipse-upstream bundle on unsupported Xclipse
2026-11-18 10:44:32 -05:00
FX192 b74d005e7f fix(library): only list the Collections source when it has something to show 2026-11-18 18:43:26 +03:00
FX192 75c19cae68 fix(library): hide the Favorites soundtrack collection until it has a track 2026-11-18 18:28:35 +03:00
Kurt Himebauch ca7b7e74ec test(session): skip the /mnt view comparison on hosts where /mnt is a symlink (#2806)
rawAndStorageMountViewsOverlapButDistinctFoldersDoNot canonicalizes
/mnt/media_rw/... with the host JVM. On SteamOS and Fedora Atomic /mnt is a
symlink to var/mnt, so the path resolves to /var/mnt/media_rw/..., which no
Android device produces, and the unit suite fails there. Skip the case when
the host's /mnt is a symlink.
2026-11-18 10:22:28 -05:00
Kurt Himebauch 0a8d6669bf ci: install the arm64 C library headers for the verified components (#2833)
* ci: install the arm64 C library headers the verified components cross-compile against

* ci: cross-compiling component recipes install the arm64 C library headers
2026-11-18 10:09:54 -05:00
Dennis Zabolotnyandzdennisz 9e05e4c00c fix(input): keep held keyboard keys when pointer capture ends (#2779)
* fix(input): keep held keyboard keys when pointer capture ends

When a game gives up its pointer lock, Android pointer capture is
released and the session dropped every held input, including keyboard
keys. In a windowed session with Relative mouse on Auto, holding W to
run and releasing the mouse button after steering stopped the
character, because the key press is never sent again.

Losing pointer capture now releases only the mouse buttons, the pen and
the mouse back-button input. Keys are still released when the window
loses focus.

* fix(input): release held keys when pointer capture ends for the session menu

Opening the session menu releases pointer capture, and the menu then
consumes key events, including the key-up. A key held at that moment
would stay pressed in the guest after the menu closed. Capture loss with
the menu open now releases keys as before; other capture loss keeps them.

* fix(input): release held keys whenever another surface takes the keyboard

Capture loss released keys only while the session menu was open. The
other places that take input from the guest (on-screen keyboard,
achievements, input settings, WoW chat, touch editor, picture in picture)
have the same problem, so keys are now kept only when the session still
owns input and the game itself dropped its pointer lock.

* fix(input): release held keys when the session menu opens

While the menu is open it takes every key event, including the key-up,
so a key held when it opened stayed pressed in the guest. The keys are
now released when the menu opens, whether or not pointer capture was
active.

---------

Co-authored-by: zdennisz <15849186+zdennisz@users.noreply.github.com>
2026-11-18 09:53:39 -05:00
The412Banner 74bbd5c53f fix(bionic): keep Wine's update from deleting the tool's .NET stubs and comctl32 v6
wine.inf has Wine's update delete ngen.exe, fusion.dll, mscorwks.dll, comctl32_v6.dll and seven more from
system32 and syswow64 ("11,,name,-" in FakeDlls and FakeDllsWow64): in Windows they live only under
Microsoft.NET and winsxs. link_dir linked every file of the tool into those folders, and Wine deletes through
the link, so the first launch after each install removed the tool's own copies (10 files in each Wine folder,
seen on the Pocket FIT and the Elite for r25 and r27). Prefixes made after that lack comctl32 v6 in winsxs.

launch.sh now reads those names from the tool's wine.inf and link_dir leaves them out of system32 and syswow64,
removing a link an earlier run left there. DroidDeck-Proton has no such links: it links only what its
default_pfx holds.

Tested on the Pocket FIT (r27 with this launch.sh, Brawlhalla, relink and Wine's update forced, winsxs
comctl32 v6 moved aside): the tool keeps all 1042 / 1026 files, Wine rebuilt winsxs comctl32 v6 from the
tool (same bytes), the game runs, no stack overflow, no c0000142.
2026-11-18 09:41:21 -05:00
The412Banner 0a167e41c2 fix(session): Steam's install-script step no longer counts as the game for return after game (#2732) 2026-11-18 09:37:50 -05:00
Kurt Himebauch 1702f2d72d fix: trust FryMcNugget for test builds (#2830) 2026-11-18 09:11:14 -05:00
The412Banner 11d8bcba2e fix(bionic): drop dead links from a prefix so Wine can put its files back
A prefix keeps links into the tool that set it up. When that tool is deleted (an older DroidDeck-Bionic replaced
by an update, a removed DroidDeck-Proton) or no longer has a file, the links dangle. prepare_prefix relinks only
when the version changes and never looks at system32/drivers, and Wine's update cannot write over a link that
"exists", so network and controller drivers stayed missing: on the Elite, Brawlhalla said "Incorrect version"
and went offline, and the pad stopped working in game (63 links into a deleted DroidDeck-Proton 11-12.2).

launch.sh now removes dangling links in system32, syswow64, system32/drivers and Fonts at every launch and, when
it removed any, clears pfx/.update-timestamp and pfx/.droiddeck-bionic so prepare_prefix relinks this tool's
files and Wine's update writes its own drivers again (the repair the Elite session proved by hand).

Tested on the Pocket FIT (r25 with this launch.sh, Brawlhalla): 20 dead links removed, relinked, Wine updated,
game running at 99 s with no c0000142 and no stack overflow, 0 dead links left. A scan found dead links in
6 prefixes across the Pocket FIT and the Elite (up to 2,099 in one).
2026-11-18 09:03:23 -05:00
The412Banner 2435324c08 fix(bionic): DroidDeck's DXVK / VKD3D choice reaches a prefix another Proton set up
DroidDeck puts a DXVK or VKD3D-Proton component choice into the tool's files/lib/wine/dxvk and vkd3d-proton
folders. A prefix that DroidDeck-Proton had run holds real copies of its own DXVK / VKD3D in system32 and
syswow64, and link_dir keeps non-builtin files, so a DroidDeck-Bionic game kept loading DroidDeck-Proton's
versions and the choice never applied (AIO reported DXVK 2.4.1 with 3.1.1 picked).

launch.sh now links d3d8, d3d9, d3d10core, d3d11, dxgi, d3d12 and d3d12core in both folders to the tool's
files at every launch (d3d10 / d3d10_1, which DXVK does not ship, to Wine's own) and logs each change.
DroidDeck-Proton puts its own copies back when it runs the prefix again.

Tested on the Pocket FIT (r25 with this launch.sh, AIO game with a per-game DXVK 3.1.1+226 and VKD3D 3.1+65):
the game loads DXVK 3.1.1-226 (dx11 3038, dx12 3819 fps); without the choice DXVK 2.4.1 again; DroidDeck-Proton
on the same prefix afterwards runs (3221 fps) with its own copies.
2026-11-18 08:43:19 -05:00
FX1922 f1be935761 feat(library): add a Hidden tab synced with Steam's hidden games (#2803)
* feat(library): add a Hidden tab synced with Steam's hidden games

* fix(library): mark the hidden collection as modified so Steam uploads it

* fix(library): make the Steam hidden write atomic and refresh the hidden set on resume

* feat(library): show an error when hiding a game can't sync with Steam

* fix(library): keep the pending Steam upload list safe when it can't be read

* fix(library): report a failed Steam sync when the upload marker can't be saved

* fix(library): refresh the Steam hidden set from disk after a failed sync

* fix(library): keep the cached hidden set when Steam's file can't be read

* fix(library): handle a malformed hidden entry and a changed Steam root

* fix(library): refuse to overwrite a malformed hidden entry

* fix(library): validate the hidden collection, keep Steam saves separate from upload status and cover cloud and uninstalled games

* fix(library): accept numeric-string ids, keep uninstalled games in the Hidden tab and hide games from the Steam home list

* fix(library): keep hidden Steam games out of the home capsule wall

* fix(library): refresh home art when the hidden set changes and track the Steam account

* fix(library): clear the cached hidden set when the Steam account changes

* fix(library): ignore a previous account's art while the home scan runs

* fix(library): conceal home art for hidden added games that carry a Steam app id
2026-11-18 07:38:34 -05:00
The412Banner 1ac4295709 fix(bionic): Wine layer with the ARM64EC code map sized for 47-bit addresses
The bionic layer sized Wine's ARM64EC code map from the host's address space, 2^39 on Android, while
RtlIsEcCode reads it for any address below 2^47. An exception unwound through JIT frames (Brawlhalla's
Adobe AIR when its Steam extension faulted) handed it a pointer above 2^39; the read faulted again in
each nested dispatch until the main thread ran out of stack, and the game hung half-alive.

Pins proton-wine d4c9ffa7 (layer v16 + the fix, pre-release build-bionic-layers-20261118-v16-ecmap).
Tested on the Pocket FIT (r24 with the fixed ntdll): with the Steam bridge off Brawlhalla now exits on
its own instead of hanging (the old ntdll overflowed at the same address as before); AIO 64-bit
Direct3D 11 / Vulkan / Direct3D 7 / OpenGL and 32-bit Direct3D 7 / OpenGL run, Brawlhalla runs.
2026-11-18 07:36:13 -05:00
The412Banner 166ed6630f ci: build the app before the next bionic runtime pack [skip ci] 2026-11-18 07:19:19 -05:00
The412Banner a80647d0a5 feat(bionic): FEX components for DroidDeck-Bionic (Android FEX builds)
DroidDeck-Bionic loads only Android builds of FEX's unix libraries. Droid-Deck/DroidDeck-Components now
publishes them (release bionic-stable, FEXCore-<ver>-bionic.wcp, profile type FEXCore-Bionic), so FEX
becomes a component of bionic Protons again, with one rule: a file ending in -bionic.wcp goes only into
DroidDeck-Bionic*, every other FEX file only into the other Protons.

- ComponentsManager: bionic-stable is a catalog source (all its .wcp are FEX) and FEXCore-Bionic a FEX
  package type. swap, queued swaps and carry-over refuse a FEX file of the other flavor. Launch rows: a
  per-game (or saved default) FEX choice reaches each Proton as its own flavor, the twin package
  (-linux.wcp <-> -bionic.wcp) when stored, else that Proton gets no rows for that game and keeps its
  default or its own FEX. No removal rows and no deleted unix libraries for a bionic tool. A per-game
  choice starts a background download of its twin when a Proton of the other flavor is installed; a
  stored twin counts as in use.
- ComponentUpdater: DroidDeck-Bionic follows FEX (only FEX) on its own line, the newest bionic-stable
  build; the DroidDeck-Proton FEX line never takes a -bionic file. Pruning that line removes only the
  updater's own downloads.
- Components page and drawer: FEX lists show the selected Proton's flavor (per game: the game's Proton,
  else the default one); the current choice stays listed. Auto/Manual shows on a bionic Proton's FEX.
- steam-compatibility: for DroidDeck-Bionic a FEX row applies only when its source path contains
  "bionic" (a -bionic package or the tool's own saved copy); glibc and removal rows are skipped.

Tests: flavor rule, twins, launch rows per flavor, swap refusal, list filter, updater line and pruning
(ComponentsBionicFexTest, ComponentsRepublishTest); bl_components bionic rule (test_game_environment).
2026-11-18 07:04:50 -05:00
The412Banner 521da21f05 fix(bionic): Turnip without an Android build uses the display driver; keep an Android FEX choice
A DroidDeck-Bionic game loads the Android build of DroidDeck's runtime driver. When the chosen runtime
driver has none, launch.sh took the first Android driver it found. The app now passes the display's
Android driver (TurnipDriver.effectiveId) as DROIDDECK_DISPLAY_DRIVER, launch.sh uses it in that case and
logs the swap, and it takes the library name from the driver's meta.json.

launch.sh put the tool's own FEX back whenever the files differed, which would undo an Android FEX picked
in DroidDeck's components; it now restores only missing or glibc (ld-linux) FEX unix libraries, and logs
the FEX build in use.
2026-11-18 06:38:31 -05:00
The412Banner b765844842 feat(bionic): DroidDeck's in-game layers and game fixes reach bionic games
DroidDeck-Proton games load DroidDeck's GPU-load layer (the HUD's GPU reading where
Android hides the GPU load) and VRAM-cap layer from the glibc userland; a bionic game
cannot load those. The runtime pack now builds both from tools/gpuload for the bionic
userland next to the gamescope WSI layer, each still off unless its DroidDeck
variable is set.

launch.sh keeps DROIDDECK_GPU_LOAD(_DIR), DROIDDECK_VRAM_CAP(_MB) and the game fixes
droiddeck-game-env sets outside the game environment file (VKD3D_FEATURE_LEVEL,
VKD3D_SHADER_MODEL, vk_x11_strict_image_count; with the last one it leaves the swapchain
image count to the game, as droiddeck-game-env does). The proton entry turns the
GPU-load folder into its Android path.
2026-11-18 05:31:47 -05:00
The412Banner 084aa2f6a0 fix(bionic): Steam store games reach DroidDeck's Steam
The bionic layer redirects a game's steamclient(64).dll to lsteamclient only when
WINE_LSTEAMCLIENT is set, and launch.sh never set it. Valve's Windows steamclient
then ran on its own, SteamAPI_Init failed ("Failed to load module ...
steamclient64.dll"), and Brawlhalla's Steam extension read a null pointer. The
unwind of that fault looped in Wine's RtlIsEcCode until the main thread ran out of
stack, so Steam showed its launch spinner forever.

launch.sh now sets WINE_LSTEAMCLIENT=1 (a game's environment can still set 0) and
copies Steam's legacycompat client files into the prefix as Proton does, because a
prefix this tool creates has no C:\Program Files (x86)\Steam\steamclient64.dll.

Tested on the Pocket FIT (r22 with this launch.sh): Brawlhalla (291550) reaches its
main menu at 144 fps, connected to Steam and its servers; the copy step restored
both steamclient DLLs after they were moved aside.
2026-11-18 04:51:10 -05:00
Kurt Himebauch d89c2c1c2d Skip the inline page-out timing control when the machine is too fast for it (#2814) 2026-11-18 01:59:01 -05:00
Kurt Himebauch ecd74fce79 Save the store order only once the user arranges it (#2812)
* fix(stores): save the store order only once the user arranges it

* test(stores): exercise the tab save the hide toggle uses
2026-11-18 01:33:11 -05:00
Kurt Himebauch bf0260de61 fix(effects): keep upscaling and sharpening at panel size with frame generation on (#2728)
* fix(effects): keep upscaling and sharpening at panel size with frame generation on

* fix(effects): stub sharpening query in the terminal callers probe
2026-11-18 00:56:02 -05:00
Kurt Himebauch 2f07e11ba0 fix(build): make tools/build_local.sh work on x86_64 Linux (#2807)
Building the full APK locally on an x86_64 Linux host (rootful Docker, no
Docker Desktop) failed in the Xbox backend step and could not be rerun:

- The xodus-cli tests re-execute their own arm64 test binary, which needs an
  aarch64 binfmt handler on the host. Without one the child runs through
  /bin/sh ("Syntax error: & unexpected"). build-local.sh now checks for the
  handler up front and prints the one-line fix.
- msixvc's streaming tests give each request 40 ms. Under qemu with the whole
  suite in parallel they time out (28/30 pass in parallel, 30/30 serially),
  so they run with one test thread when emulated. Native arm64 is unchanged.
- The backend container runs as root, so with rootful Docker its outputs in
  the repo and the cache were root-owned and the next build_local.sh could not
  remove them. The container now hands them back to the calling user on exit.
- README lists the missing requirements: Go, a host C compiler, both MinGW-w64
  compilers (i686 with DWARF-2 exceptions; Homebrew's SJLJ build cannot link
  Rust's i686-pc-windows-gnu) and the arm64 binfmt handler.

Verified with a full tools/build_local.sh run on SteamOS (x86_64): all three
backend test suites pass and the APK is release-signed.
2026-11-18 00:54:33 -05:00
DantalianandDantalian bdc18bdd03 fix(ui): pin the file manager toolbar ends so the exit stays reachable (#2564)
fix(ui): pin the file manager toolbar ends so exit stays reachable

Below 600dp the whole toolbar scrolls, so on a phone the star and the
exit button sit past the right edge and need a swipe to reach. Scroll
only the middle section instead, keeping the back arrow, the drive chip
and exit in place, and move the grid list toggle into the sort menu to
give that section room. The disabled back arrow also stops being
painted primary, which made it look active at the drive root.

Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
2026-11-18 00:53:45 -05:00
Kurt Himebauch c336f994e1 Library store pills follow the new default store order (#2811)
* fix(library): move an unarranged store order to the new default at startup

* fix(stores): forget an unarranged store order instead of saving the default
2026-11-18 00:47:44 -05:00
Kurt Himebauch c1cf0f3a9c feat(agent): hold to talk, slide up to lock, let go to send, with guided voice setup (#2796) 2026-11-18 00:47:42 -05:00
Kurt Himebauch 384eb78215 fix: set aside an unreadable game environment file (#2808)
fix: set aside an unreadable game environment file instead of failing every session
2026-11-18 00:47:12 -05:00
Kurt Himebauch 5e704296ed Review follow-ups for tab defaults, accounts and hero flight (#2809)
* fix: address review notes on tab defaults, accounts and hero flight

* fix: zero hero drift for cover-only pages, hide search pills from accessibility

* fix(settings): drop pill semantics while search is open
2026-11-18 00:35:45 -05:00
Kurt Himebauch 52c76ead74 chore: refresh the verified preload snapshot (#2810) 2026-11-18 00:28:49 -05:00
Kurt Himebauch 08eadf7af8 feat(agent): OpenCode takes keys for Ollama Cloud and other providers, or any OpenAI-compatible server (#2741)
* feat(agent): OpenCode takes keys for Ollama Cloud and other providers, or any OpenAI-compatible server

* fix(agent): write OpenCode config atomically, check auth first, Done hides the keyboard

* fix(agent): serialize OpenCode key saves and removals

* fix(agent): restore the OpenCode config atomically when the key write fails

* fix(agent): report a failed OpenCode config rollback

* fix(agent): delete the OpenCode config with deleteIfExists, lead with the rollback warning
2026-11-18 00:27:26 -05:00
LunaDL d40c962b37 Feat: Better SMAA, make nearest the default filter and change the default store order (#2760)
* Add SMAA screen effect option

* Atualizar o smaa_frag.h

* Atualizar o smaa.frag

* Fix SMAA endpoint and crossing-edge area weights

* Atualizar o smaa.frag

* Fix SMAA diagonal edge blending

* Regenerate SMAA fragment shader header

* Fix SMAA diagonal fallback detection

* Add anti-aliasing translations

* Fix Korean anti-aliasing label

* Change default store tab order

* Put Nearest scaling before Linear

* Make Nearest the default scaling filter

* Improve SMAA diagonal blend weighting

* Improve SMAA diagonal detection and corner protection

* Reduce false positive SMAA diagonal blending

* test: update unknown upscaler fallback expectation
2026-11-18 00:26:32 -05:00
Kurt Himebauch 8953eea9e0 fix(battlenet): keep the launch behavior a player chose in Battle.net (#2750) 2026-11-18 00:26:07 -05:00
Jan PokornýandJan Pokorny 8faaac3b89 fix(agent): force clearing focus on a tap in the Agent conversation (#2769)
A tap on the conversation while the composer held focus could crash the app:
FocusManager.clearFocus() without force walks the focused chain for a custom
exit and throws IllegalArgumentException ("ActiveParent with no focused
child") when a parent is ActiveParent with no active child. The forced path
skips that walk and treats a missing child as cleared. Nothing in the Agent UI
sets a custom focus exit, so forcing changes no behaviour.

Co-authored-by: Jan Pokorny <4580066+JanPokorny@users.noreply.github.com>
2026-11-18 00:25:36 -05:00
ZeratulloandZeratullo c7cd2b55af fix(xbox): hand Xodus a launch folder the Linux guest can see (#2751)
* fix(xbox): log and show why an Xbox launch could not be prepared

* fix(xbox): hand Xodus a launch folder the Linux guest can see

---------

Co-authored-by: Zeratullo <8460122+Zeratullo@users.noreply.github.com>
2026-11-18 00:23:00 -05:00
Kurt Himebauch c8b291b9db Tabs decide what shows: new defaults and reset, Apps and Dev Harness as tabs, animated Settings search, Library store accounts (#2798) 2026-11-17 23:56:19 -05:00
Kurt Himebauch eabcfc7b74 chore: consistent code branding (#2800)
* chore: consistent code branding

* fix: carry legacy overrides, queues and live sync rows across the rename

* fix: keep queued legacy overrides on a failed rename and separate merged queue entries
2026-11-17 23:31:26 -05:00
Kurt Himebauch ad9348879d fix: remove stray pipewire lock files from the repo root (#2805)
#2780 committed 21 empty libdroiddeck-pipewire.lock files whose names are
mangled Windows temp paths. test_pipewire_helper runs the POSIX helper
under sh; on Windows it received a C:\Users\...\Temp path, so the helper's
"$dir.lock" landed in the working directory. The helper needs a POSIX
shell, flock and Unix sockets, so skip the test on Windows.
2026-11-17 23:27:24 -05:00
The412Banner 1067145839 fix(bionic): Fast OpenGL Mesa from Mesa main, so Zink stops faulting on front-buffer reads
The runtime's egl/ set (Mesa EGL + GLX + Zink, as Bannerlator's Fast OpenGL)
was built from Mesa 7cda7850 (2026-09-11). Its Zink faults in
zink_kopper_acquire_submit (swapchain image index UINT32_MAX) on each
front-buffer read after a swap, which Wine's front-buffer emulation does on
every flush for DirectDraw / WineD3D games (about 33,600 faults per AIO DX7
run). Wine swallows the fault; with Mesa's glthread on it aborted the next
synchronous GL call, so glCreateShader returned 0 and the DX7 cube drew white.

Take the same recipe built from Mesa main d8cfbe82766 (Zink kopper readback
fixes c21794353a6, MR 45267, MR 45323) from The412Banner/Banners-Turnip release
fastgl-x11egl-mesa-d8cfbe8-r1. Tested on r21 with the files swapped in: 0
faults, DX7 cube correct with glthread on, AIO OpenGL / DX7 frame rates equal to
the old set. glthread stays off by default (slower on these tests).
2026-11-17 23:20:46 -05:00
Kurt Himebauch 0ce168b913 feat(settings): one home per setting, Storage/Syncthing/Downloads tabs, scoped frame limit, clearer menus (#2791) 2026-11-17 20:26:37 -05:00
The412Banner d23b32f22e fix(bionic): Mesa's GL thread off unless the game's environment sets it
AIO's 64-bit Direct3D 7 cube (WineD3D on Zink) drew solid white on DroidDeck-Bionic instead of its per-face
vertex colours, with Bannerlator's adapter and with the fixed one. DroidDeck exports mesa_glthread=true for
the whole session; with it, WineD3D's persistent buffer writes lose the vertex colours on the Fast OpenGL Mesa
build the runtime ships. mesa_glthread=false gives the right colours (and 2556 vs 2443 fps), as does hiding
GL_ARB_buffer_storage; DroidDeck-Proton, Bannerlator (Wayland), bionic 32-bit WineD3D and D7VK drew it right.
The launcher now sets mesa_glthread=false unless the game's own DroidDeck environment names it.
2026-11-17 19:13:54 -05:00
The412Banner d7cdf12ebf fix(bionic): VKD3D-Proton from DroidDeck-Components' stable release
The pinned DD-vkd3d-proton-arm64ec-3.1+64-nightly.wcp was replaced by the +65 nightly on 2026-11-17 and the
pack build failed with a 404 (CI run 44197089822). The default VKD3D-Proton now comes from the linux-stable
release (DD-vkd3d-proton-arm64ec-3.1.wcp, same layout, sha256 pinned), whose files are not replaced by
nightlies. DroidDeck's VKD3D component choice still replaces it in files/lib/wine/vkd3d-proton.
2026-11-17 18:14:08 -05:00
The412Banner 38ec930b70 fix(bionic): Wayland adapter with placed-mapping fixes, so 32-bit OpenGL and WineD3D run
32-bit OpenGL games and 32-bit WineD3D (DirectDraw / Direct3D 1-7 without D7VK) died under Wine's wow64:
the adapter did not honour placed mapping for the exportable Vulkan memory Wine's OpenGL maps below 4 GB, did
not turn its placed-map emulation on for Wine's OpenGL device, and let the driver flush memory only the
adapter had mapped. Fixed in The412Banner/bionic-vulkan-wrapper banner/wayland-wsi-placed-export (acdf6bcc,
f7e7258f, 270cc239 on top of Bannerlator's adapter f970b6c); the pack now takes libvulkan_wrapper.so and
adapter.json from that repository's release wayland-adapter-placed-export-r1 (sha256 pinned) instead of
Bannerlator's assets, which stay unchanged. NOTICE moves the adapter entry accordingly.
Tested with the adapter swapped into r18 on the Pocket FIT: AIO 32-bit Direct3D 7 2178 / 2286 fps and 32-bit
OpenGL 2348 fps (both crashed before); 64-bit Vulkan 2147, OpenGL 2363, Direct3D 11 3510, Direct3D 7 2521,
32-bit D7VK 144, DiRT Showdown 97.0 fps.
2026-11-17 18:11:05 -05:00
MaxsTechReview 868207baf8 fix(desktop): preserve bounded Windows program diagnostics (#2695)
* fix(desktop): preserve bounded Windows program diagnostics

* fix(desktop): isolate stderr mirror failures from diagnostic file capture

* fix(desktop): continue stderr mirroring after diagnostic file limit

* fix(desktop): make diagnostic stderr messages best-effort
2026-11-17 17:37:17 -05:00
MaxsTechReview eb5aa7a536 fix: seed redist markers into new prefixes before install scripts (#2327)
* fix: initialize Proton prefix before install scripts

* game-env: start Proton first only for a new prefix

* fix: wait for new prefix wineserver before seeding

* game-env: find wineserver in either Proton layout

* fix(steam): skip redist seeding when wineserver wait fails

* fix(steam): probe new prefixes only when Proton has no template prefix

* fix(steam): check the active Proton prefix template before seeding

* fix(steam): use effective environment for redist seeding
2026-11-17 17:05:38 -05:00
MaxsTechReview cbde8b1f25 feat(quest): show the child-process command with SideQuest steps on Quest (#2306) 2026-11-17 16:20:51 -05:00
MaxsTechReview 7ce8b37824 fix(zram): back off ineffective idle compression (#2347) 2026-11-17 16:20:32 -05:00
Kurt Himebauch d7d0583c5a fix(memory): reclaim on a fast memory fall on large-RAM devices before the kill (#2754) 2026-11-17 13:37:09 -05:00
Kurt Himebauch 7909af74d6 fix(logs): say in a recovered session folder whether the device restarted (#2752) 2026-11-17 13:35:04 -05:00
Kurt Himebauch 28cf995d7b fix(agent): terminal icon for Dev Harness in the session menu (#2749) 2026-11-17 13:34:51 -05:00
Kurt Himebauch b2b2e38e67 fix(desktop): Desktop draws again and Sunshine can capture it (#2780)
* fix(desktop): keep the bundled PipeWire paths out of Plasma so the desktop draws

* fix(desktop): let the screencast portal use KWin so Sunshine can capture the desktop

* fix(proot): /proc/<pid>/root reads as the guest root so portals accept callers

* fix(nativeguest): /proc/<pid>/exe of another guest program names that program, not the loader

* fix(nativeguest): trust another process's program only when it is mapped there, and read all of its environment

* fix(nativeguest): accept versioned glibc loaders, and wait for the test program to run
2026-11-17 12:31:35 -05:00
Kurt Himebauch fa95df37d0 fix(session): keep the session the top app on dual screens under memory pressure (#2763) 2026-11-17 12:27:54 -05:00
MaxsTechReviewandKurt Himebauch b88b5f6b1d feat(steam): adopt game folders found in added libraries (#2317)
* feat: adopt game folders in added Steam libraries

* Share the appmanifest builder between steam-library and steam-games

* steam: load the shared compatibility module once per run

* Guard unreadable game folders during library adoption

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-17 11:25:04 -05:00
MaxsTechReview c31f19a9f0 fix(input): detect which axis pair is the right stick (#2333)
* fix(input): detect controller right stick axes

* fix(input): read dedicated triggers when the right stick is on RX/RY

* fix(input): stabilize mixed controller axis detection

* fix(input): normalize ranged signed triggers

* fix(input): reuse the event's device for stick and trigger detection

Pass the InputDevice captured at the start of motion handling into the
right-stick and trigger helpers instead of looking it up again, so a pad
that disappears mid-event keeps its axis layout. Write each pad-mouse
trigger only when that side has an analog source, so a held digital
trigger on the other side is not cleared.
2026-11-17 11:24:33 -05:00
MaxsTechReview 812e492302 fix(zram): page game memory out on a worker thread, not the signalled game thread (#2335)
* fix: move zram page-out off signal thread

* fix: drain pending zram requests

* Time the async and inline page-out runs on the same workload

* fix(zram): keep pageout worker responsive under load

* test(zram): synchronize signal delivery before fixture shutdown

* test(zram): compare matched single-request timings

* test(zram): correct single request timing control

* test(zram): calibrate single request timing together

* test(zram): fail the timed run when the acknowledgement never arrives
2026-11-17 11:24:05 -05:00
MaxsTechReview f84e9d5191 fix(input): the controls editor shows the layout the game uses (#2339)
* fix(input): align layout editor with game controls

* fix(input): regenerate built-in layouts for measured surfaces

* fix(input): preserve edge stick travel bounds

* Drop editor strings now translated on main

* fix(input): keep editor frame, undo state and previous edge sticks consistent

* fix(input): preserve draft controls and aspect in editor
2026-11-17 11:23:34 -05:00
MaxsTechReview 2ff890f0ec fix(dual-screen): allow game swap to external second screens (#2350)
* fix(dual-screen): allow game swap to external second screens

* fix(dual-screen): name external screens primary and secondary in the game screen choice

* Keep the selected game screen in step with display changes and session mode

* Refresh the game output when the screen is picked automatically

* Keep the game screen when controls open automatically

* Keep the external game screen across restarts and show the controls on the primary screen

* fix(dual-screen): preserve selected game display

* fix(dual-screen): retain fallback selection and keyboard access

* fix(input): clear field keyboard ownership on transitions

* fix(dual-screen): route keyboard when selected display is occupied

* fix(dual-screen): enable keyboard fallback routing

* fix(dual-screen): defer keyboard requests until focus returns

* fix(dual-screen): recheck keyboard destination on focus return and ignore stale hide events

* fix(dual-screen): end guest keyboard ownership on real dismissals
2026-11-17 11:22:33 -05:00
MaxsTechReview 913cb85c92 fix(fex): supply current Wayland libraries in the shared runtime (#2426)
* fix(fex): supply current Wayland libraries in the shared runtime

* fix(fex): provide current FreeType runtime libraries

* fix(fex): fall back when provider links are broken

* fix(fex): require ffi for provider Wayland libraries

* fix(fex): keep Wayland cursor with its provider client

* fix(fex): preserve cursor compatibility and refresh runtime cache

* fix(fex): provide current GBM runtime libraries
2026-11-17 11:22:04 -05:00
MaxsTechReviewandKurt Himebauch 7852098e63 fix(input): screen taps move the pointer without clicking while an on-screen mouse button is shown (#2465)
* fix(input): screen taps move the pointer without clicking while an on-screen mouse button is shown

* fix(input): keep tap-to-click with the stock Desktop on-screen gamepad

Only mouse buttons the user bound, not the profile base's stock bindings, make screen taps pointer-only.

* fix(input): count mouse buttons on the second-screen and foldable panels

* fix(input): keep tap clicks off on the swapped panel, copied stock panels and the scroll layer

* fix(input): move the pointer before the desktop gesture buffer when an on-screen mouse button clicks

* fix(input): the on-screen button gate leaves uninitialized gestures alone

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-17 11:21:32 -05:00
The412Banner 0f08981dd8 perf(bionic): FEX's disk cache on, as DroidDeck-Proton's launcher sets it
DroidDeck-Proton's proton script sets FEX_DISKCACHE=1 by default; the bionic launcher did not, so FEX
translated code paths again on every run and DiRT Showdown's worst frame was ~21 ms (min fps 46.7) where
DroidDeck-Proton's was ~14 ms. FEX keeps the cache in the prefix (AppData/Local/fex-emu/DiskCache), keyed by
its build and settings, so a game switched between DroidDeck-Proton and DroidDeck-Bionic rebuilds it once
after each switch (bionic's FEX replaced DroidDeck-Proton's cache folder in the test). A game's own
FEX_DISKCACHE in DroidDeck's game environment still wins.
DiRT Showdown on the Pocket FIT (r17 + this setting): first run 90.2 avg / 50.2 min, then 97.2 / 68.2 and
96.4 / 70.9 (r17 without it 92.9 / 46.7; DroidDeck-Proton 90.9 / 69.9).
2026-11-17 11:21:27 -05:00
MaxsTechReview 0794f361ad fix(rockstar): serve launcher pipes named by the executables beside a protected game (#2590)
* fix(rockstar): serve launcher pipes named by the executables beside a protected game

* fix(rockstar): skip unreadable executables beside a game instead of failing the launch

* test(rockstar): exercise case-insensitive sibling pipe name dedupe

* fix(rockstar): show the launcher service log in the session log after a Rockstar game exits

* fix(store): run the store exit hook when the session ends a store game
2026-11-17 11:21:00 -05:00
MaxsTechReview 8c8cae85cf fix(session): read the compressed client back when it is in front of a running game (#2600)
* fix(session): read the compressed client back when it is in front of a running game

* fix(session): keep the client compressed while focus is unknown

A missing or unreadable focus.json no longer counts as the client in front
of the game, so the readback timer starts only on a confirmed focus change.

* fix(session): invalidate focus snapshots after collection failures

* fix(session): retry focus snapshot publication
2026-11-17 11:20:29 -05:00
MaxsTechReview 8e49dfe190 fix(fex): GL thunk passes X errors to the program instead of exiting (#2601)
* fix(fex): GL thunk passes X errors to the program instead of exiting

* fix(fex): raise forwarded X errors on the program connection without swapping its handler

* fix(fex): release the host display lock while a forwarded X error runs the program's handler

* test(fex): cover X error forwarding with real Xlib locks under Xvfb

* test(fex): verify GLX context fallback with a valid config

* test(fex): probe GLX headers before compiling harness
2026-11-17 11:19:58 -05:00
MaxsTechReview 1951bbc92a fix(desktop): expose readable removable volumes in Dolphin (#2671) 2026-11-17 11:19:29 -05:00
MaxsTechReview d7c03ba3ec revert: remove merged bot investigation docs (#2692, #2697) (#2784)
* Revert "docs(rendering): record outdoor lighting investigation (#2692)"

This reverts commit cdb8fa6f53.

* Revert "docs(rendering): record D3D10 renderer crash investigation (#2697)"

This reverts commit 663a7003bc.
2026-11-17 11:12:11 -05:00
MaxsTechReview cdb8fa6f53 docs(rendering): record outdoor lighting investigation (#2692) 2026-11-17 11:09:22 -05:00
MaxsTechReview 663a7003bc docs(rendering): record D3D10 renderer crash investigation (#2697) 2026-11-17 11:09:17 -05:00
MaxsTechReview 2be0ba58c7 fix(flatpak): expose the runtime GPU to accelerated desktop windows (#2699) 2026-11-17 11:09:12 -05:00
Kurt Himebauch 637f4b21ee fix(shortcuts): the companion no longer keeps DroidDeck running, so Cocoon stops calling it open (#2764)
* fix(shortcuts): the companion no longer keeps DroidDeck running, so Cocoon stops calling it open

* fix(shortcuts): reset the relay holder when it is installed again
2026-11-17 10:03:25 -05:00
Kurt Himebauch 51ec4a3029 chore(shortcuts): target Android 14 like DroidDeck so Play Protect does not block the companion (#2774) 2026-11-17 09:51:22 -05:00
The412Banner 6b00181c1d perf(bionic): keep DroidDeck's Wine and DXVK settings that games get on DroidDeck-Proton
The launcher's environment filter dropped WINE_OFFSCREEN_CHECK_MS=100, which DroidDeck sets for every game
(SessionService). The bionic layer's winex11 has the same check cache as DroidDeck-Proton's Wine, so without
it each present asked wineserver twice whether the game window has children (needs_offscreen_rendering ->
GetWindowRelative GW_CHILD); in an AIO Direct3D 11 profile that was 18 % of DXVK's submit thread.
Also kept, as DroidDeck-Proton gets them: WINE_CPU_TOPOLOGY, WINE_LARGE_ADDRESS_AWARE, TZ, DXVK_LOG_LEVEL,
DXVK_HDR, VKD3D_DEBUG, VKD3D_SHADER_DEBUG.
AIO on the Pocket FIT (r16 + these settings): Direct3D 9 2820 -> 3644, Direct3D 11 2809 -> 3448,
Direct3D 12 3113 -> 4339 fps (DroidDeck-Proton 3787 / 3528 / 4847).
2026-11-17 09:35:19 -05:00
Kurt Himebauch b1a7d9b2d0 fix(preload): leave anonymous memory alone when copying noexec image pages (#2706) 2026-11-17 08:29:32 -05:00
The412Banner e26ef06695 fix(bionic): Gallium's threaded context off, so WineD3D stops crashing
AIO's Direct3D 7 (DirectDraw on WineD3D, Zink on the adapter) died of SIGSEGV in native code within seconds
of its first frames, with no Wine error. GALLIUM_THREAD=0, which Bannerlator's Fast OpenGL also sets, stops
it (mesa_glthread=false and BANNER_WSI_NO_DMABUF_WAIT=1 did not). A game's own GALLIUM_THREAD in DroidDeck's
game environment still wins and now passes the launcher's filter.
AIO on the Pocket FIT with r14's settings: Direct3D 7 1930 fps (was a crash); OpenGL 1932 / 1967 fps
(2174 with the threaded context).
2026-11-17 07:18:47 -05:00
The412Banner 58125fc723 feat(bionic): D7VK for 32-bit Direct3D 7 and older games (PROTON_USE_D7VK)
As in DroidDeck-Proton: with PROTON_USE_D7VK set and not 0, the prefix's syswow64 ddraw.dll is D7VK's and
Wine's own sits beside it as ddraw_.dll, with ddraw=n,b; unset again, Wine's link comes back. Only the
prefix links change. The ddraw.dll is the one DroidDeck-Proton 11-12.8 ships (WinterSnowfall/d7vk
06656b9e, sha256 pinned), taken from that release's archive at build time; credited in NOTICE.
PROTON_USE_D7VK now passes the launcher's environment filter.
2026-11-17 06:55:51 -05:00
The412Banner 536a05e06c perf(bionic): four swapchain images through gamescope's WSI layer
A profile of AIO's Vulkan run showed the game thread waiting about 20 % of the time in the adapter's
Wayland acquire (wl_display dispatch for a wl_buffer.release from gamescope); DroidDeck-Proton's Turnip
waits there under 1 % with the same three images. GAMESCOPE_WSI_MIN_IMAGE_COUNT=4 with
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1 (gamescope layer settings, default 3 / off) gives the swapchain
one more image; a game's own value in DroidDeck's game environment still wins.
AIO Vulkan on the Pocket FIT: about 1440 -> 1824 fps (5 images: 1841).
2026-11-17 06:30:40 -05:00
The412Banner 26c30344d9 perf(bionic): give libX11 a resource file so XGetDefault stops re-reading missing ones
With no ~/.Xdefaults and no XENVIRONMENT file, libX11 keeps no resource database and looks for both
files again on every XGetDefault call; winex11 asks for Xft settings on each GDI font selection
(xrender SelectFont), so a game drawing text every frame opened two missing files per frame (about 5 %
of AIO's Vulkan run in a profile). XENVIRONMENT now points at an empty resource file in the tool.
AIO Vulkan on the Pocket FIT: about 1440 -> 1464 / 1485 fps.
2026-11-17 06:30:39 -05:00
The412Banner 6c7c50b625 fix(bionic): load the runtime's X11 Mesa before the layer's Wayland-only one
The bionic layer's lib/ carries its own Mesa (libEGL.so.1, libgallium) built for winewayland only, and it came
first on the library path, so winex11's EGL backend got no configs and OpenGL did not start (AIO: "Failed to get
any configs from eglChooseConfig"; Zink never loaded Vulkan). The runtime's egl/ (Bannerlator's Fast OpenGL set,
x11 + wayland) now comes first, as Bannerlator orders it. Tested: AIO OpenGL on DroidDeck-Bionic, 1714.6 fps,
Zink on the adapter and Turnip.
2026-11-17 04:35:25 -05:00
The412Banner 9436447f5d fix(bionic): a prefix made by DroidDeck-Bionic can be taken over by Proton
Proton reads compatdata/tracked_files when it updates a prefix, and one made by DroidDeck-Bionic had none:
switching such a game to DroidDeck-Proton ended in "FileNotFoundError: .../tracked_files" and the game did not
start. launch.sh now leaves an empty tracked_files. Its version string is not a Proton prefix version, so Proton
updates the prefix (its "invalid version" path) rather than removing it as one from a newer Proton. Tested: AIO's
bionic-made prefix, then DroidDeck-Proton 11-12.8 ran in it.
2026-11-17 03:10:39 -05:00
The412Banner e4ab8a0e44 feat(bionic): OpenGL through Mesa's Zink, and Direct3D 8 through DXVK
OpenGL games and WineD3D (DirectDraw, Direct3D 1-7) failed on DroidDeck-Bionic: the runtime had no libGL, and
Direct3D 8 went to WineD3D because d3d8 was not overridden (AIO Graphics Test: gl, dx8 and dx7 did not start).

- build.sh: the runtime pack gets Bannerlator's bionic Mesa (EGL + GLX + Zink with the x11 and wayland platforms,
  from Banners-Turnip exp/egl-x11-platform ab76cba3) in egl/, sha256-pinned at the Bannerlator commit already used
  for the Wayland adapter; check-needed fills what it links from the imagefs.
- launch.sh: egl/ on the library path; winex11's EGL backend with Zink on Vulkan (WINE_USE_EGL=1, GALLIUM_DRIVER=
  zink, kopper), as in Bannerlator's Fast OpenGL; DroidDeck's GL settings (mesa_glthread, vblank_mode, ZINK_*,
  GALLIUM_HUD) are kept; d3d8 joins the DXVK overrides.
- NOTICE: Mesa, libwayland-client, libarchive.
2026-11-17 02:21:51 -05:00
The412Banner bade6edea5 fix(bionic): a userspace ntsync file per prefix, cleared before Wine starts
The layer's userspace ntsync keeps its state in TMPDIR/ntsync_userspace.v9.shm: one file in DroidDeck's /tmp for
every prefix (and next to DroidDeck-Proton's own ntsync state). A Wine process killed while it held that file's
lock leaves it held, and every later bionic start then hangs at the first ntsync wait (seen as wineboot --init
never answering, "failed to start wineboot 103", and a new prefix never finishing).

launch.sh sets NTSYNC_SHM to compatdata/ntsync-shm (the layer adds .v9), and before Wine starts removes that file
when no process of the prefix runs; a game start first stops Wine left running in its prefix.
2026-11-17 01:50:02 -05:00
The412Banner 981956a12f fix(bionic): keep the game environment list while filtering
launch.sh dropped DROIDDECK_BIONIC_KEEP itself while it filtered the environment, so names that came after it
were dropped as well and the log showed an empty list. It is read into KEEP before the loop.
2026-11-17 00:56:00 -05:00
The412Banner d7bb0f6dd2 fix(bionic): put the tool's own FEX back at launch
DroidDeck's component check re-applied a game's per-game FEX choice into DroidDeck-Bionic (fixed in the app by
4453a463, but older builds still do it). Those packages carry glibc unix libraries bionic Wine cannot load, so FEX
ran without its unix side. The tool now keeps a spare copy of its FEX in files/runtime/fex, and launch.sh puts any
changed FEX file back before starting Wine (DXVK and VKD3D-Proton swaps are left alone).
2026-11-17 00:09:56 -05:00
The412Banner aa76a79b49 fix(bionic): DroidDeck's game settings reach bionic games like DroidDeck-Proton's
launch.sh kept only a fixed list of variables, so DroidDeck settings that DroidDeck-Proton games get were dropped:
the games' TU_DEBUG (sysmem by default), MESA_NO_ERROR and DXVK_CONFIG (VRAM cap, per-game DXVK options), the
Game environment entries, the Wine sync choice and Force SSBS.

- proton (guest) lists the names of DroidDeck's game environment for this game (shared entries and the game's own,
  as droiddeck-game-env applied them) in DROIDDECK_BIONIC_KEEP; launch.sh keeps those names.
- launch.sh also keeps TU_DEBUG, MESA_NO_ERROR, DXVK_CONFIG, DXVK_HUD and the sync variables.
- Sync: ntsync -> userspace ntsync with esync fallback, esync -> esync, wineserver -> neither, fsync (no
  futex_waitv on Android) -> ntsync; PROTON_NO_NTSYNC / PROTON_NO_ESYNC / WINEESYNC=0 still turn one off.
- Force SSBS (DROIDDECK_FORCE_SSBS, a glibc preload on DroidDeck-Proton) maps to bionic Wine's WINE_FORCE_SSBS.
- The log names the sync, SSBS, TU_DEBUG and kept settings.
2026-11-16 23:53:36 -05:00
The412Banner 4453a46382 fix(bionic): FEX packages never reach DroidDeck-Bionic
A game's own FEX choice (per-game profile) was published for every installed Proton, and the launch-time check
re-applied it into DroidDeck-Bionic: DroidDeck's FEX packages carry glibc unix libraries, which bionic Wine cannot
load, so FEX ran without its unix side (seen with DiRT Showdown: DD-FEXCore-2611+49-nightly's 14 KB glibc
libwow64fex.so replaced the tool's Android build at its first launch).

- ComponentsManager: no FEX rows (selected, original or per-game) for DroidDeck-Bionic folders; DXVK and
  VKD3D-Proton are still swapped. Test: a game's FEX choice reaches DroidDeck-Proton but not DroidDeck-Bionic.
- steam-compatibility: the launch-time check skips FEX rows for DroidDeck-Bionic (selections published by an
  older app).
2026-11-16 23:49:09 -05:00
The412Banner e2c5a2d37f feat(bionic): FEX with DroidDeck-Proton's defaults; keep per-game FEX settings
launch.sh dropped every FEX_* variable, so FEX ran its strict defaults (x87 in full precision) while
DroidDeck-Proton uses its share/fex-emu/Config.json (x87 in 64-bit precision, TSO without the vector and memcpy
parts, MaxInst 500) and droiddeck-game-env's per-game choices (.NET, Unity, Batman). FEX_* from the environment is
now kept, and unset ones default to DroidDeck-Proton's values. Not device-tested yet.
2026-11-16 23:17:11 -05:00
The412Banner 977d8c4735 fix(proton): never follow links when deleting a Proton tool; no links out of DroidDeck-Bionic
DroidDeck-Bionic's prefix template carried dosdevices/z: -> /, and ProtonExtras deleted tool folders with
File.deleteRecursively(), which follows links into directories: removing an old DroidDeck-Bionic walked the device
root and deleted what the app could write on shared storage.

- ProtonExtras: remove, removeOlder and replaceOlder delete with FileUtils.delete, which removes a link itself and
  never what it points to. Test: a link out of two tool folders survives removing both.
- build.sh: the prefix template has no dosdevices (launch.sh makes C: and Z: in each game's prefix), and the build
  fails if any link in the tool resolves outside it.
2026-11-16 23:17:11 -05:00
Kurt Himebauch 6fe7b4ec11 feat(diagnostics): record lmkd's kill records after a low-memory kill (#2758) 2026-11-16 22:53:16 -05:00
The412Banner a5f7405032 fix(bionic): check DroidDeck-Bionic releases only with Run without proot on
ProtonExtras.offered() lists DroidDeck-Bionic only when no-proot is on; the release check and the Proton list use
it, so devices without no-proot make no extra GitHub request (the update-check test caught the new source).
test_proton_extra: the fourth source, its archive pattern next to DroidDeck-Proton's, its prerelease.
2026-11-16 21:22:50 -05:00
The412Banner 7e4ed9b7df fix(bionic): run games on Steam's game X server; focus check on gamescope's first server
DroidDeck's gamescope runs two X servers (--xwayland-count 2): Steam's UI on :0 and games on
STEAM_GAME_DISPLAY_0, which Steam passes to the tool as DISPLAY. launch.sh forced :0, so opening Steam's menu
took X focus from the game; with no Wine desktop, Wine then deactivated it and DiRT Showdown left fullscreen
and saved an 800x600 window. launch.sh now keeps Steam's DISPLAY (and GAMESCOPE_WAYLAND_DISPLAY) and logs it.

gstag tags windows on that display; gamescope publishes GAMESCOPE_FOCUSED_APP and reads
GAMESCOPECTRL_BASELAYER_APPID on its first server only, so gstag reads and writes those through a second
connection to :0.
2026-11-16 21:17:15 -05:00
The412Banner 1e659a5ea0 fix(bionic): run games on gamescope's X server, not a Wine desktop
The Wine virtual desktop reported 60 Hz modes only, so a game set to the screen's 144 Hz did not find its mode:
DiRT Showdown fell back to 1024x768 at 60 Hz on DroidDeck-Bionic, while DroidDeck-Proton kept 1280x720 at 144 Hz
in the same prefix. Games now start straight on gamescope's X server like on DroidDeck-Proton: same modes and
refresh rate, gamescope manages each game window. gstag tags every window of the prefix (WM_CLASS holds the Windows
program name, matched on ".exe" in any case) and stops with the game.
2026-11-16 21:02:44 -05:00
The412Banner a566e255af feat(bionic): DroidDeck-Bionic in the Proton list (no-proot only)
- ProtonExtras: a fourth tool, DroidDeck-Bionic (folder prefix DroidDeck-Bionic, archives
  DroidDeck-Bionic-*-aarch64.tar.(gz|xz) on Droid-Deck/DroidDeck-Proton, prereleases accepted). DroidDeck-Proton's
  archive pattern now requires the DroidDeck-Proton- prefix so it never takes a bionic archive from the same
  releases. A new DroidDeck-Bionic build replaces older ones like DroidDeck-Proton (per-game picks carried over).
- ProtonMenu: the row is listed only with Run without proot on (the tool starts its Wine outside the userland).
- ComponentsManager: DroidDeck's FEX packages (glibc unix libraries) are not offered for DroidDeck-Bionic folders,
  which carry Android-built FEX; DXVK/VKD3D stay swappable.
- droiddeck-proton-extra: the same source and prerelease rule for queued installs.
- Tests: the source list, the two archive patterns, prerelease handling.
2026-11-16 20:54:48 -05:00
The412Banner d9a788046b feat(bionic): DroidDeck-Bionic compatibility tool (exec shim, launcher, CI archive)
The CI build now also assembles DroidDeck-Bionic-<layer>-r<run>, a Steam compatibility tool in Proton's layout:
the bionic layer (bin, lib, share), its prefix template (drives C: and Z: only), FEX 2611.1 with Android-built unix
libraries, DXVK 2.4.1 gplasync and VKD3D-Proton 3.1 (DroidDeck components can swap these), and the runtime pack,
as a .tar.xz with a sha512sum. All inputs are sha256-pinned.

- execshim.c (runtime pack preload): from targetSdk 29 Android refuses execve() of app data files but the system
  linker still runs them, so execve()/posix_spawn() of a dynamic /data ELF with interpreter linker64 becomes
  "linker64 <file> args" and "#!" scripts start their interpreter; static ELFs pass through (Wine then falls back
  from wine-preloader to its loader). realpath/readlink of /proc/self/exe answer with the program linker64 runs,
  because wineserver finds its NLS files next to its executable.
- tool/proton (guest): run/waitforexitandrun/runinprefix/getcompatpath/getnativepath; no-proot only; guest paths
  to Android paths via DDNATV_BINDS; hands over to bionic/launch.sh.
- tool/launch.sh (Android sh): Steam/input variables kept, DroidDeck's chosen Turnip (Android half), Wayland
  adapter + gamescope WSI layer, ntsync, FEX, DXVK/VKD3D overrides, runtime-pack paths (no fontconfig),
  Steam pad as an Xbox 360 pad; prefix setup in compatdata/pfx (template for new prefixes, builtin links for this
  layer replacing other Protons' links and Wine builtin copies but keeping native DLLs, users/xuser linked to
  steamuser, black desktop); every start through linker64 + execshim; STEAM_GAME window tag; leftover cleanup.

Tested by hand on a Pocket FIT (DroidDeck 0.7.1, no-proot) with a locally assembled copy of this layout: DroidDeck
adopted the tool, Steam started DiRT Showdown on it, prefix set up in 38 s, benchmark completed, clean exit.
Known: DiRT Showdown picks 1024x768 instead of its configured 1280x720 under this Wine (open).
2026-11-16 20:49:22 -05:00
The412Banner 19262fd7bd fix(bionic): pack libxcb-composite.so, the name the WSI layer links against 2026-11-16 19:01:47 -05:00
The412Banner 8c7016e2c4 feat(bionic): build a bionic runtime pack in CI; fake input for bionic Proton
Adds tools/bionic-runtime and a workflow that builds the Android-side (bionic libc) pieces a bionic
DroidDeck-Proton layer needs inside DroidDeck's gamescope session, as an artifact:

- gamescope 3.16.29's WSI layer with DroidDeck's patches 0117/0119, built with the NDK (API 30)
- DroidDeck's fake input library (app/src/main/cpp/fakeinput_steam.cpp), a heap-tagging-off preload and a
  STEAM_GAME window tagger
- the Android libraries the layer v16 (proton-wine 067c719d) needs from Bannerlator's pinned base imagefs, the
  GStreamer plugins winegstreamer uses, FFmpeg 8 and the Wayland adapter from Bannerlator, all sha256-pinned
- a check that every library a pack file needs is in the pack, in the layer's lib/ or on Android

The Proton layer, GPU drivers, DXVK/VKD3D and FEX are not in the pack.

fakeinput_steam.cpp: (1) bionic's libc calls hooked functions (access) during its own start-up, before environ
exists; settings read then were empty and cached for good (hooks looked in a Termux folder). Until environ
exists hooks now see defaults, uncached; no change for glibc processes. (2) FAKE_EVDEV_STEAM_PAD_AS_X360=1
shows Steam's virtual pad (28de:11ff) to non-Steam processes as 045e:028e, because the bionic layer's winebus
has no udev bus and its SDL bus skips 28de:11ff. Off unless set.

Device-tested by hand on a Pocket FIT (Adreno 750) before this CI build: Insane 2, GTA IV, Rise of the Tomb
Raider and DiRT Showdown from Steam's Play button (DiRT Showdown benchmark: 91.4 fps bionic with ntsync vs 99.6
fps DroidDeck-Proton 11-12.8, three runs each).
2026-11-16 18:59:30 -05:00
Kurt Himebauch d13458937d feat(agent): hide the Dev Harness tab by default (#2744)
* feat(agent): hide the Agent tab by default

* feat(agent): rename the Agent tab to Dev Harness with a terminal icon
2026-11-16 16:47:50 -05:00
Kurt Himebauch fde3089900 feat(hud): long press collapses or expands the HUD, locking becomes an option (#2723)
* feat(hud): long press collapses or expands the HUD, locking becomes an option

* fix(hud): keep the collapsing tab at the press point while layout runs

The layout listener could run keepOnScreen during the dock animation and replace the press-centered target with the anchored edge position, which was then saved as the tab position. The dock animation now holds the same guard the other HUD animations use until the dock is committed.
2026-11-16 15:29:17 -05:00
MaxsTechReview 8e514ada62 fix(library): persist explicitly selected executables in discovered folders (#2703)
* fix(library): persist explicitly selected executables in discovered folders

* fix(library): keep reachable executable when selecting unmapped alias
2026-11-16 15:19:10 -05:00
MaxsTechReview aba9811357 fix(ci): wait out the API rate limit in build validation (#2672)
* fix(ci): wait out the API rate limit in build validation

* fix(ci): skip rate-limit sleep retries on status POSTs

* fix(ci): detect status POSTs via --method without changing api() call signature
2026-11-16 15:00:05 -05:00
Kurt Himebauch 5fac78797f fix(display): Steam's frame limits follow the panel, not Game Mode's FPS override (#2717) 2026-11-16 14:45:38 -05:00
LunaDL d116021ff3 Feat: Add SMAA as a anti-alliasing option and the buttom for FXAA becomes a switch. (#2708)
* Add SMAA screen effect option

* Atualizar o smaa_frag.h

* Atualizar o smaa.frag

* Fix SMAA endpoint and crossing-edge area weights

* Atualizar o smaa.frag

* Fix SMAA diagonal edge blending

* Regenerate SMAA fragment shader header

* Fix SMAA diagonal fallback detection

* Add anti-aliasing translations

* Fix Korean anti-aliasing label
2026-11-16 14:36:02 -05:00
Kurt Himebauch 25cbcf0c1f feat(agent): OpenCode as a third agent, with free Zen models or a pasted Zen key (#2711)
* feat(agent): OpenCode as a third agent, with free Zen models or a pasted Zen key

* fix(agent): OpenCode's key check reads only its own entry and never overwrites an unreadable auth.json
2026-11-16 14:33:22 -05:00
712 changed files with 38325 additions and 11750 deletions

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
ASEbrahim
FX192
FryMcNugget
K11MCH1
KeegantheVeganat0r
kingokksa
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
validate:
name: Validate source and build result
runs-on: ubuntu-24.04
timeout-minutes: 5
timeout-minutes: 70
steps:
- uses: actions/checkout@v4
with:
@@ -0,0 +1,34 @@
name: Build bionic runtime pack and DroidDeck-Bionic tool
on:
push:
paths:
- 'tools/bionic-runtime/**'
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
- 'app/src/main/cpp/fakeinput_steam.cpp'
- '.github/workflows/build-bionic-runtime.yml'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- name: Host tools
run: |
set -euo pipefail
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev \
libxcb1-dev libxcb-composite0-dev libglm-dev zstd
- name: Build
run: |
set -euo pipefail
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
export BUILD_NUMBER=${{ github.run_number }}
tools/bionic-runtime/build.sh "$RUNNER_TEMP/bionic-runtime" "$PWD/out"
- uses: actions/upload-artifact@v4
with:
name: droiddeck-bionic-runtime-${{ github.sha }}
path: out/*
+16 -13
View File
@@ -195,17 +195,17 @@ jobs:
app/src/main/assets/linuxfs
!app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet
!app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
!app/src/main/assets/linuxfs/i386/libblsession.so
!app/src/main/assets/linuxfs/i386/libddsession.so
!app/src/main/assets/linuxfs/i386/libfakeinput.so
!app/src/main/assets/linuxfs/i386/libfaultreport.so
!app/src/main/assets/linuxfs/libblaudit.so
!app/src/main/assets/linuxfs/libblfastpath.so
!app/src/main/assets/linuxfs/libddaudit.so
!app/src/main/assets/linuxfs/libddfastpath.so
!app/src/main/assets/linuxfs/libddnatv-hook.so
!app/src/main/assets/linuxfs/libblsession.so
!app/src/main/assets/linuxfs/libddsession.so
!app/src/main/assets/linuxfs/libfakeinput.so
!app/src/main/assets/linuxfs/libssbs.so
!app/src/main/assets/linuxfs/usr/local/bin/droiddeck-clipboard
!app/src/main/assets/linuxfs/x86_64/libblsession.so
!app/src/main/assets/linuxfs/x86_64/libddsession.so
!app/src/main/assets/linuxfs/x86_64/libfakeinput.so
!app/src/main/assets/linuxfs/x86_64/libfaultreport.so
!app/src/main/assets/linuxfs/x86_64/libvulkan-thunk.so
@@ -291,7 +291,7 @@ jobs:
- name: Build the non-Adreno test additions (Mali bridge client, Venus GL probe, Xclipse layer)
run: |
set -euo pipefail
bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libvulkan-dev
bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libc6-dev-arm64-cross libvulkan-dev
D=app/src/main/assets/linuxfs
mkdir -p "$D/usr/local/bin" "$D/usr/local/lib/droiddeck-xclipse"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
@@ -619,14 +619,18 @@ jobs:
export NDK="$ANDROID_HOME/ndk/$NDK_VERSION"
tools/syncthing/build.sh app/src/main/jniLibs/arm64-v8a
- name: Note when the proot pack pin is behind this build
- name: Check the proot pack pin against 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."
size=$(stat -c %s app/build/packs/proot.tar.zst)
if [ "$sha" != "$PROOT_PACK_SHA256" ] || [ "$size" != "$PROOT_PACK_SIZE" ]; then
level=warning
if [ "$GITHUB_EVENT_NAME" = pull_request ]; then level=error; fi
echo "::$level::built proot pack $sha ($size bytes) does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256, $PROOT_PACK_SIZE bytes). Source builds download the pinned pack, so set PROOT_PACK_SHA256=$sha and PROOT_PACK_SIZE=$size in tools/packs/proot/release.env."
if [ "$level" = error ]; then exit 1; fi
fi
- name: Check out MaliBridge
@@ -765,7 +769,6 @@ jobs:
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ubuntu-24.04
timeout-minutes: 15
continue-on-error: true
permissions:
contents: read
actions: read
@@ -811,7 +814,6 @@ jobs:
stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-
- name: Store engines host unit tests
timeout-minutes: 10
continue-on-error: true
run: |
set -o pipefail
cd app/src/main/rust/stores
@@ -900,7 +902,7 @@ jobs:
checks:
name: Compile and test APK
needs: [build, python-tests]
needs: [build, python-tests, store-tests]
if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
runs-on: ubuntu-24.04
timeout-minutes: 5
@@ -909,7 +911,8 @@ jobs:
env:
BUILD_RESULT: ${{ needs.build.result }}
PYTHON_RESULT: ${{ needs.python-tests.result }}
run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success
STORE_RESULT: ${{ needs.store-tests.result }}
run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success && test "$STORE_RESULT" = success
sign:
needs: [build, checks]
+5 -4
View File
@@ -47,7 +47,7 @@ Help, Preview builds and device reports are on [Discord](https://discord.gg/JRGA
## Build
Needs Docker, Java 17, the Android SDK and NDK, Rust via rustup, GitHub CLI, Python 3 and `zstd`.
Needs Docker, Java 17, the Android SDK and NDK, Rust via rustup, Go, a host C compiler, the x86_64 and i686 MinGW-w64 compilers (i686 with DWARF-2 exceptions, as Debian and Ubuntu ship it; SJLJ builds such as Homebrew's cannot link Rust's `i686-pc-windows-gnu`), GitHub CLI, Python 3 and `zstd`. On x86_64 Linux, Docker also needs an arm64 binfmt handler (`docker run --privileged --rm tonistiigi/binfmt --install arm64`).
```bash
tools/build_local.sh
@@ -70,13 +70,13 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT). FEX's code disk cache was checked in its source.
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source.
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
- Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libblsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`.
- libblsession runs Wine's arm64 `SIGUSR2` context handler (`dlls/ntdll/unix/signal_arm64.c`, LGPL-2.1-or-later) in place on a frame laid out like [Linux](https://github.com/torvalds/linux)'s `arch/arm64/kernel/signal.c`, and serves `fill_vm_counters` in `dlls/ntdll/unix/process.c` the kernel's own `/proc/<pid>/status`.
- Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libddsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`.
- libddsession runs Wine's arm64 `SIGUSR2` context handler (`dlls/ntdll/unix/signal_arm64.c`, LGPL-2.1-or-later) in place on a frame laid out like [Linux](https://github.com/torvalds/linux)'s `arch/arm64/kernel/signal.c`, and serves `fill_vm_counters` in `dlls/ntdll/unix/process.c` the kernel's own `/proc/<pid>/status`.
- droiddeck-ntsync follows the [Linux](https://github.com/torvalds/linux) ntsync semantics in `Documentation/userspace-api/ntsync.rst` (GPL-2.0).
- The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later).
- DiRT 3 and DiRT Showdown keep their telemetry socket the way RoccoC's DiRTTelemetryErrorFix (MIT) does, based on the fix by Carsten Gottschling.
@@ -97,6 +97,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
- The EA store follows the EA app's protocols as documented by [ArmchairDevelopers](https://github.com/ArmchairDevelopers)' [Maxima](https://github.com/ArmchairDevelopers/Maxima) (GPL-3.0): sign-in, the GraphQL queries (included verbatim, since EA matches them by hash), build archives, online activation licences and the LSX game endpoint. The code is DroidDeck's own.
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
- The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code.
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
- The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
+2
View File
@@ -388,6 +388,8 @@ dependencies {
implementation 'androidx.compose.material3:material3'
implementation 'androidx.compose.ui:ui-tooling-preview'
debugImplementation 'androidx.compose.ui:ui-tooling'
// Declares the ComponentActivity that createComposeRule launches, for PreviewRenderTest.
debugImplementation 'androidx.compose.ui:ui-test-manifest'
implementation 'androidx.activity:activity-compose:1.8.2'
implementation 'androidx.compose.material:material-icons-extended'
implementation 'io.coil-kt:coil-compose:2.6.0'
@@ -0,0 +1,79 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.SecondScreenMode
/** The launcher as a whole: rail and page, opened on each tab through FrontEndState.navigate. */
@Composable
private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Library.SteamGame> = sampleGames, ready: Boolean = true) =
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
@DroidDeckPreviews @Composable private fun DownloadsPreview() = Launcher("downloads")
@DroidDeckPreviews @Composable private fun SettingsPreview() = Launcher("setup")
@DroidDeckPreviews @Composable private fun RuntimeMissingPreview() = Launcher("setup", ready = false)
/** The in-game menu on one page, as a session shows it. */
@Composable
private fun SessionMenu(page: SessionDrawerPage, steam: Boolean = true, desktop: Boolean = false) = PreviewHost {
SessionDrawer(true, page, controllerActive = true, onPageChange = {}, a = sampleDrawerActions(steam, desktop))
}
@DroidDeckPreviews @Composable private fun SessionMenuControllerPreview() = SessionMenu(SessionDrawerPage.CONTROLLER)
@DroidDeckPreviews @Composable private fun SessionMenuDisplayPreview() = SessionMenu(SessionDrawerPage.DISPLAY)
@DroidDeckPreviews @Composable private fun SessionMenuHudPreview() = SessionMenu(SessionDrawerPage.HUD)
@DroidDeckPreviews @Composable private fun SessionMenuSessionPreview() = SessionMenu(SessionDrawerPage.SESSION)
@DroidDeckPreviews @Composable private fun SessionMenuDesktopPreview() = SessionMenu(SessionDrawerPage.CONTROLLER, steam = false, desktop = true)
/** The in-game menu docked on the bottom screen, with the screen picker in its header. */
@Composable
private fun DockedMenu(page: SessionDrawerPage) = PreviewHost {
SessionDrawer(true, page, controllerActive = false, onPageChange = {},
a = sampleDrawerActions(secondScreen = SecondScreenMode.KEYBOARD_TRACKPAD), docked = true)
}
/** The bottom screen's bar on a panel: the panel's name is the screen picker. */
@Composable
private fun BottomPanelBar() = PreviewHost {
val modes = secondScreenModes(false, deckPad = false, dashboard = true, desktop = false)
Column(Modifier.fillMaxSize().background(Color.Black)) {
BottomScreenBar(BottomBarModel("Keyboard + trackpad", {}, {}, {}, {},
listOf(BarExtra("Keyboard", icon = R.drawable.ic_bottom_keyboard) {}),
picker = ScreenPicker(modes, SecondScreenMode.KEYBOARD_TRACKPAD, {}, onMenu = {})))
}
}
@DroidDeckPreviews @Composable private fun SessionMenuDockedPreview() = DockedMenu(SessionDrawerPage.CONTROLLER)
@DroidDeckPreviews @Composable private fun SessionMenuDockedDisplayPreview() = DockedMenu(SessionDrawerPage.DISPLAY)
@DroidDeckPreviews @Composable private fun BottomPanelBarPreview() = BottomPanelBar()
/** The Library and Stores tabs read store accounts, which load on a background thread. */
private val storesLoaded = { com.droiddeck.launcher.stores.StoresState.accountsLoaded }
/** Every preview above, for the render test. Add a case when adding a preview. */
internal val previewCases: List<PreviewCase> = listOf(
PreviewCase("steam-tab") { Launcher("steam") },
PreviewCase("library", storesLoaded) { Launcher("games") },
PreviewCase("library-empty", storesLoaded) { Launcher("games", games = emptyList()) },
PreviewCase("stores", storesLoaded) { Launcher("stores") },
PreviewCase("downloads") { Launcher("downloads") },
PreviewCase("settings") { Launcher("setup") },
PreviewCase("runtime-missing") { Launcher("setup", ready = false) },
PreviewCase("session-menu-controller") { SessionMenu(SessionDrawerPage.CONTROLLER) },
PreviewCase("session-menu-display") { SessionMenu(SessionDrawerPage.DISPLAY) },
PreviewCase("session-menu-hud") { SessionMenu(SessionDrawerPage.HUD) },
PreviewCase("session-menu-session") { SessionMenu(SessionDrawerPage.SESSION) },
PreviewCase("session-menu-desktop") { SessionMenu(SessionDrawerPage.CONTROLLER, steam = false, desktop = true) },
PreviewCase("session-menu-docked") { DockedMenu(SessionDrawerPage.CONTROLLER) },
PreviewCase("session-menu-docked-display") { DockedMenu(SessionDrawerPage.DISPLAY) },
PreviewCase("bottom-panel-bar") { BottomPanelBar() },
)
@@ -0,0 +1,88 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.session.SessionPrefs
/**
* Debug-only support for Compose previews: the production theme around a screen, and sample state and no-op actions so
* production composables render without a device, a runtime or a network. See docs/compose-previews.md.
*/
/** The sizes the previews come in. The Duo's top screen is 1920x1080 at xhdpi, i.e. 960x540 dp. */
@Preview(name = "Handheld", widthDp = 960, heightDp = 540, device = "spec:width=960dp,height=540dp,dpi=320,orientation=landscape")
@Preview(name = "Portrait", widthDp = 540, heightDp = 960, device = "spec:width=540dp,height=960dp,dpi=320")
internal annotation class DroidDeckPreviews
@Composable
internal fun PreviewHost(content: @Composable () -> Unit) {
DroidDeckTheme {
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) { content() }
}
}
/**
* A case the render test draws: a name for its PNG and the preview's content. [ready] is what the test waits for before
* drawing, for a screen that loads something off the main thread first.
*/
internal class PreviewCase(val name: String, val ready: () -> Boolean = { true }, val content: @Composable () -> Unit) {
override fun toString() = name
}
internal val sampleGames: List<Library.SteamGame> = listOf(
"Portal 2" to 620, "Hades" to 1145360, "Celeste" to 504230, "Stardew Valley" to 413150, "Hollow Knight" to 367520,
"Balatro" to 2379780, "Dead Cells" to 588650, "Terraria" to 105600, "Vampire Survivors" to 1794680, "Slay the Spire" to 646570,
).mapIndexed { i, (name, appId) ->
Library.SteamGame(appId, name, art = null, library = "steam", lastPlayed = 1_700_000_000_000L - i * 86_400_000L)
}
internal fun sampleState(
games: List<Library.SteamGame> = sampleGames,
navigate: String? = null,
ready: Boolean = true,
): FrontEndState = FrontEndState(
installed = "ubuntu-r1", ready = ready, available = "ubuntu-r1", busy = false, stage = "", percent = 0,
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "Off", romsDir = null, logsEnabled = true,
steamGames = games, emulators = emptyList(), running = null, navigate = navigate,
)
internal val sampleActions: FrontEndActions = FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {},
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> },
)
/** The in-game menu's actions with settled sample values; its switches do nothing. */
internal fun sampleDrawerActions(
steam: Boolean = true, desktop: Boolean = false, secondScreen: SecondScreenMode? = null,
): DrawerActions = DrawerActions(
steam = steam, desktop = desktop, title = if (!steam && !desktop) "Hades" else null,
isHomeApp = false, androidApps = emptyList(),
hudOn = true, onHud = {},
frameGen = FrameGen.Mode.OFF, onFrameGenPick = {},
lossless = Lossless.State.NONE,
oscMode = SessionPrefs.OSC_AUTO, onOsc = {},
suspendPolicy = SessionPrefs.SUSPEND_MANUAL, onSuspendPolicy = {},
backActionsInverted = false, onBackActionsInverted = {},
touchMode = SessionPrefs.TOUCH_AUTO, onTouch = {}, touchAuto = "Auto (direct)",
fexPreset = "", onFexPreset = {},
secondScreenMode = secondScreen ?: SecondScreenMode.NONE, onSecondScreenMode = {}, secondScreenNone = secondScreen == null,
secondScreenDisplays = listOfNotNull(secondScreen?.let { SecondScreenDisplay(2, "Built-in · 1240×1080") }),
selectedSecondScreenDisplay = if (secondScreen != null) 2 else -1, onSecondScreenDisplay = {},
gameSwapAvailable = secondScreen != null, dashboardAvailable = secondScreen != null,
onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = if (steam) ({}) else null, onQam = if (steam) ({}) else null,
onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {},
)
+13
View File
@@ -4,6 +4,9 @@
<queries>
<package android:name="cn.nubia.gamelauncher" />
<intent>
<action android:name="android.speech.RecognitionService" />
</intent>
<intent>
<action android:name="android.content.pm.action.CONFIRM_INSTALL" />
</intent>
@@ -150,6 +153,7 @@
<category android:name="android.intent.category.CAR_LAUNCHER" />
<data android:scheme="droiddeck" android:host="game" />
<data android:scheme="droiddeck" android:host="soundtrack" />
<data android:scheme="droiddeck" android:host="settings" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" />
@@ -298,6 +302,15 @@
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".session.KeepTopActivity"
android:exported="false"
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity="${applicationId}.keeptop"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".ui.SessionTypingActivity"
android:exported="false"
+33 -2
View File
@@ -205,6 +205,11 @@ static void controller_fork_prepare();
static void controller_fork_parent();
static void controller_fork_child();
// bionic: libc's own start-up calls hooked functions (access) before environ is set. Settings read
// then would be empty and cached for good, so until environ exists hooks see defaults, uncached.
extern "C" char **environ;
static bool env_ready() { return environ != nullptr; }
struct FakeConfig {
const char *hook_dir;
const char *udev_data_dir;
@@ -218,6 +223,10 @@ struct FakeConfig {
// would throw a recursive-init error there, so the fields are filled without allocating, and a
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
static FakeConfig &config() {
if (!env_ready()) {
static FakeConfig early = {"/data/data/com.termux/files/home/fake-input", nullptr, false, false, false};
return early;
}
static FakeConfig cfg;
static std::atomic<int> state{0};
static __thread bool initializing __attribute__((tls_model("initial-exec")));
@@ -587,7 +596,7 @@ get_fake_input_rdev(const char *event) {
__attribute__((visibility("hidden"))) static void load_ring_paths() {
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
if (ring_paths_loaded)
if (ring_paths_loaded || !env_ready())
return;
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
@@ -807,12 +816,25 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
// The bionic Proton layer's winebus has no udev bus, and its SDL bus skips 28de:11ff (Proton reads Steam's virtual
// pad through udev/evdev), so with FAKE_EVDEV_STEAM_PAD_AS_X360=1 other processes see that pad as a plain Xbox 360 pad.
__attribute__((visibility("hidden"))) static bool steam_pad_as_x360() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *v = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
known = v && atoi(v) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
__attribute__((visibility("hidden"))) static bool
presents_xbox_triggers(const FakeController &fake) {
return fake.uinput || !is_steam_client();
@@ -1391,6 +1413,7 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
static bool fake_deck_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
return enabled == 1;
}
@@ -1398,6 +1421,7 @@ static bool fake_deck_enabled() {
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
static int type = -1;
if (type < 0) {
if (!env_ready()) return PAD_TYPE_DECK;
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
@@ -1470,6 +1494,7 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
static bool fake_triton_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0)
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
return enabled == 1;
@@ -2091,6 +2116,7 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
static TouchRingFile *ring = nullptr;
if (!env_ready()) return nullptr;
static std::once_flag once;
std::call_once(once, [] {
const char *path = getenv("FAKE_TOUCHCTL_RING");
@@ -2312,7 +2338,7 @@ __attribute__((visibility("hidden"))) static int inject_uevent(const char *actio
const char *subsystem, const char *devname,
unsigned major, unsigned minor) {
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "bl_udevmon_inject"));
static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "dd_udevmon_inject"));
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
}
@@ -2434,6 +2460,7 @@ __attribute__((constructor)) static void start_touch_controller() {
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
if (!env_ready()) return nullptr;
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
return dir && *dir ? dir : nullptr;
}
@@ -3689,6 +3716,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
id.bustype = 0x03;
if (made) {
id = made->id;
if (steam_pad_as_x360() && id.vendor == STEAM_VIRTUAL_VENDOR_ID && id.product == STEAM_VIRTUAL_PRODUCT_ID) {
id.vendor = X360_VENDOR_ID;
id.product = X360_PRODUCT_ID;
}
} else if (presents_steam_virtual()) {
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
id.product = STEAM_VIRTUAL_PRODUCT_ID;
+100
View File
@@ -0,0 +1,100 @@
#version 450
layout(location = 0) in vec2 fragTexCoord;
layout(location = 0) out vec4 outColor;
layout(set = 0, binding = 0) uniform sampler2D InputTexture;
layout(push_constant) uniform Constants {
vec4 ndc;
vec2 resolution;
float extra;
float pad;
} pc;
float luma(vec3 c) {
return dot(c, vec3(0.2126, 0.7152, 0.0722));
}
float edgeVertical(vec2 uv, vec2 px) {
float a = luma(texture(InputTexture, uv - vec2(px.x, 0.0)).rgb);
float b = luma(texture(InputTexture, uv + vec2(px.x, 0.0)).rgb);
return abs(a - b);
}
float edgeHorizontal(vec2 uv, vec2 px) {
float a = luma(texture(InputTexture, uv - vec2(0.0, px.y)).rgb);
float b = luma(texture(InputTexture, uv + vec2(0.0, px.y)).rgb);
return abs(a - b);
}
void main() {
vec2 px = 1.0 / max(pc.resolution, vec2(1.0));
vec2 uv = clamp(fragTexCoord, px * 0.5, vec2(1.0) - px * 0.5);
vec4 center = texture(InputTexture, uv);
float lc = luma(center.rgb);
float ll = luma(texture(InputTexture, uv - vec2(px.x, 0.0)).rgb);
float lr = luma(texture(InputTexture, uv + vec2(px.x, 0.0)).rgb);
float lu = luma(texture(InputTexture, uv - vec2(0.0, px.y)).rgb);
float ld = luma(texture(InputTexture, uv + vec2(0.0, px.y)).rgb);
float dL = abs(lc - ll);
float dR = abs(lc - lr);
float dU = abs(lc - lu);
float dD = abs(lc - ld);
float localMin = min(lc, min(min(ll, lr), min(lu, ld)));
float localMax = max(lc, max(max(ll, lr), max(lu, ld)));
float localContrast = localMax - localMin;
float threshold = max(0.045, localContrast * 0.08);
float vertical = max(dL, dR);
float horizontal = max(dU, dD);
float strongest = max(vertical, horizontal);
if (strongest <= threshold) {
outColor = center;
return;
}
bool verticalEdge = vertical >= horizontal;
vec2 tangent = verticalEdge ? vec2(0.0, px.y) : vec2(px.x, 0.0);
vec2 normal = verticalEdge
? vec2(dL >= dR ? -1.0 : 1.0, 0.0)
: vec2(0.0, dU >= dD ? -1.0 : 1.0);
float negativeRun = 0.0;
float positiveRun = 0.0;
for (int i = 1; i <= 6; ++i) {
vec2 offset = tangent * float(i);
float edgeN = verticalEdge ? edgeVertical(uv - offset, px) : edgeHorizontal(uv - offset, px);
float edgeP = verticalEdge ? edgeVertical(uv + offset, px) : edgeHorizontal(uv + offset, px);
if (negativeRun == float(i - 1) && edgeN > threshold * 0.65) negativeRun = float(i);
if (positiveRun == float(i - 1) && edgeP > threshold * 0.65) positiveRun = float(i);
}
float span = negativeRun + positiveRun;
float edgeConfidence = smoothstep(threshold, threshold * 2.5, strongest);
float nw = luma(texture(InputTexture, uv + vec2(-px.x, -px.y)).rgb);
float ne = luma(texture(InputTexture, uv + vec2(px.x, -px.y)).rgb);
float sw = luma(texture(InputTexture, uv + vec2(-px.x, px.y)).rgb);
float se = luma(texture(InputTexture, uv + vec2(px.x, px.y)).rgb);
float endpointPattern = clamp(abs(negativeRun - positiveRun) / max(span, 1.0), 0.0, 1.0);
float endpointArea = endpointPattern / (1.0 + span * 0.055);
float crossingA = verticalEdge ? abs(nw - ne) : abs(nw - sw);
float crossingB = verticalEdge ? abs(sw - se) : abs(ne - se);
float crossingContrast = abs(crossingA - crossingB);
float crossingPattern = smoothstep(threshold, threshold * 2.5, crossingContrast);
float areaWeight = 0.38 * crossingPattern * clamp(span / 4.0, 0.0, 1.0);
float diagonalContrast = max(abs(nw - se), abs(ne - sw));
float cornerFactor = 1.0 - 0.35 * smoothstep(threshold, threshold * 3.0, diagonalContrast);
float baseWeight = areaWeight * endpointArea * edgeConfidence * cornerFactor;
float diagonalStrength = min(vertical, horizontal);
float diagonalPattern = smoothstep(threshold, threshold * 2.5, diagonalStrength);
float diagonalContinuity = smoothstep(1.0, 3.0, span);
float diagonalFallback = 0.16 * diagonalPattern * edgeConfidence
* cornerFactor * diagonalContinuity * crossingPattern;
float weight = clamp(max(baseWeight, diagonalFallback), 0.0, 0.42);
vec3 across = texture(InputTexture, uv + normal * px).rgb;
outColor = vec4(mix(center.rgb, across, weight), center.a);
}
+443
View File
@@ -0,0 +1,443 @@
#pragma once
#include <stdint.h>
static const uint32_t smaa_code[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000251u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000072u, 0x000000f6u, 0x00030010u,
0x00000004u, 0x00000007u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du,
0x00000000u, 0x00050005u, 0x0000000bu, 0x616d756cu, 0x33667628u, 0x0000003bu, 0x00030005u, 0x0000000au,
0x00000063u, 0x00080005u, 0x00000012u, 0x65676465u, 0x74726556u, 0x6c616369u, 0x32667628u, 0x3266763bu,
0x0000003bu, 0x00030005u, 0x00000010u, 0x00007675u, 0x00030005u, 0x00000011u, 0x00007870u, 0x00080005u,
0x00000016u, 0x65676465u, 0x69726f48u, 0x746e6f7au, 0x76286c61u, 0x763b3266u, 0x003b3266u, 0x00030005u,
0x00000014u, 0x00007675u, 0x00030005u, 0x00000015u, 0x00007870u, 0x00030005u, 0x00000021u, 0x00000061u,
0x00060005u, 0x00000025u, 0x75706e49u, 0x78655474u, 0x65727574u, 0x00000000u, 0x00040005u, 0x00000031u,
0x61726170u, 0x0000006du, 0x00030005u, 0x00000034u, 0x00000062u, 0x00040005u, 0x0000003cu, 0x61726170u,
0x0000006du, 0x00030005u, 0x00000045u, 0x00000061u, 0x00040005u, 0x0000004eu, 0x61726170u, 0x0000006du,
0x00030005u, 0x00000051u, 0x00000062u, 0x00040005u, 0x00000059u, 0x61726170u, 0x0000006du, 0x00030005u,
0x00000062u, 0x00007870u, 0x00050005u, 0x00000064u, 0x736e6f43u, 0x746e6174u, 0x00000073u, 0x00040006u,
0x00000064u, 0x00000000u, 0x0063646eu, 0x00060006u, 0x00000064u, 0x00000001u, 0x6f736572u, 0x6974756cu,
0x00006e6fu, 0x00050006u, 0x00000064u, 0x00000002u, 0x72747865u, 0x00000061u, 0x00040006u, 0x00000064u,
0x00000003u, 0x00646170u, 0x00030005u, 0x00000066u, 0x00006370u, 0x00030005u, 0x00000070u, 0x00007675u,
0x00060005u, 0x00000072u, 0x67617266u, 0x43786554u, 0x64726f6fu, 0x00000000u, 0x00040005u, 0x0000007cu,
0x746e6563u, 0x00007265u, 0x00030005u, 0x00000080u, 0x0000636cu, 0x00040005u, 0x00000081u, 0x61726170u,
0x0000006du, 0x00030005u, 0x00000085u, 0x00006c6cu, 0x00040005u, 0x0000008du, 0x61726170u, 0x0000006du,
0x00030005u, 0x00000090u, 0x0000726cu, 0x00040005u, 0x00000098u, 0x61726170u, 0x0000006du, 0x00030005u,
0x0000009bu, 0x0000756cu, 0x00040005u, 0x000000a3u, 0x61726170u, 0x0000006du, 0x00030005u, 0x000000a6u,
0x0000646cu, 0x00040005u, 0x000000aeu, 0x61726170u, 0x0000006du, 0x00030005u, 0x000000b1u, 0x00004c64u,
0x00030005u, 0x000000b6u, 0x00005264u, 0x00030005u, 0x000000bbu, 0x00005564u, 0x00030005u, 0x000000c0u,
0x00004464u, 0x00050005u, 0x000000c5u, 0x61636f6cu, 0x6e694d6cu, 0x00000000u, 0x00050005u, 0x000000cfu,
0x61636f6cu, 0x78614d6cu, 0x00000000u, 0x00060005u, 0x000000d9u, 0x61636f6cu, 0x6e6f436cu, 0x73617274u,
0x00000074u, 0x00050005u, 0x000000ddu, 0x65726874u, 0x6c6f6873u, 0x00000064u, 0x00050005u, 0x000000e3u,
0x74726576u, 0x6c616369u, 0x00000000u, 0x00050005u, 0x000000e7u, 0x69726f68u, 0x746e6f7au, 0x00006c61u,
0x00050005u, 0x000000ebu, 0x6f727473u, 0x7365676eu, 0x00000074u, 0x00050005u, 0x000000f6u, 0x4374756fu,
0x726f6c6fu, 0x00000000u, 0x00060005u, 0x000000fau, 0x74726576u, 0x6c616369u, 0x65676445u, 0x00000000u,
0x00040005u, 0x000000feu, 0x676e6174u, 0x00746e65u, 0x00040005u, 0x0000010bu, 0x6d726f6eu, 0x00006c61u,
0x00050005u, 0x0000011du, 0x6167656eu, 0x65766974u, 0x006e7552u, 0x00050005u, 0x0000011eu, 0x69736f70u,
0x65766974u, 0x006e7552u, 0x00030005u, 0x00000120u, 0x00000069u, 0x00040005u, 0x00000129u, 0x7366666fu,
0x00007465u, 0x00040005u, 0x0000012eu, 0x65676465u, 0x0000004eu, 0x00040005u, 0x00000136u, 0x61726170u,
0x0000006du, 0x00040005u, 0x00000137u, 0x61726170u, 0x0000006du, 0x00040005u, 0x0000013eu, 0x61726170u,
0x0000006du, 0x00040005u, 0x0000013fu, 0x61726170u, 0x0000006du, 0x00040005u, 0x00000143u, 0x65676465u,
0x00000050u, 0x00040005u, 0x0000014bu, 0x61726170u, 0x0000006du, 0x00040005u, 0x0000014cu, 0x61726170u,
0x0000006du, 0x00040005u, 0x00000153u, 0x61726170u, 0x0000006du, 0x00040005u, 0x00000154u, 0x61726170u,
0x0000006du, 0x00040005u, 0x0000017bu, 0x6e617073u, 0x00000000u, 0x00060005u, 0x0000017fu, 0x65676465u,
0x666e6f43u, 0x6e656469u, 0x00006563u, 0x00030005u, 0x00000186u, 0x0000776eu, 0x00040005u, 0x00000192u,
0x61726170u, 0x0000006du, 0x00030005u, 0x00000195u, 0x0000656eu, 0x00040005u, 0x000001a0u, 0x61726170u,
0x0000006du, 0x00030005u, 0x000001a3u, 0x00007773u, 0x00040005u, 0x000001aeu, 0x61726170u, 0x0000006du,
0x00030005u, 0x000001b1u, 0x00006573u, 0x00040005u, 0x000001bbu, 0x61726170u, 0x0000006du, 0x00060005u,
0x000001beu, 0x70646e65u, 0x746e696fu, 0x74746150u, 0x006e7265u, 0x00060005u, 0x000001c7u, 0x70646e65u,
0x746e696fu, 0x61657241u, 0x00000000u, 0x00050005u, 0x000001ceu, 0x736f7263u, 0x676e6973u, 0x00000041u,
0x00050005u, 0x000001ddu, 0x736f7263u, 0x676e6973u, 0x00000042u, 0x00070005u, 0x000001ecu, 0x736f7263u,
0x676e6973u, 0x746e6f43u, 0x74736172u, 0x00000000u, 0x00060005u, 0x000001f1u, 0x736f7263u, 0x676e6973u,
0x74746150u, 0x006e7265u, 0x00050005u, 0x000001f7u, 0x61657261u, 0x67696557u, 0x00007468u, 0x00070005u,
0x00000200u, 0x67616964u, 0x6c616e6fu, 0x746e6f43u, 0x74736172u, 0x00000000u, 0x00060005u, 0x0000020au,
0x6e726f63u, 0x61467265u, 0x726f7463u, 0x00000000u, 0x00050005u, 0x00000214u, 0x65736162u, 0x67696557u,
0x00007468u, 0x00070005u, 0x0000021cu, 0x67616964u, 0x6c616e6fu, 0x65727453u, 0x6874676eu, 0x00000000u,
0x00060005u, 0x00000220u, 0x67616964u, 0x6c616e6fu, 0x74746150u, 0x006e7265u, 0x00070005u, 0x00000226u,
0x67616964u, 0x6c616e6fu, 0x746e6f43u, 0x69756e69u, 0x00007974u, 0x00070005u, 0x00000229u, 0x67616964u,
0x6c616e6fu, 0x6c6c6146u, 0x6b636162u, 0x00000000u, 0x00040005u, 0x00000235u, 0x67696577u, 0x00007468u,
0x00040005u, 0x0000023bu, 0x6f726361u, 0x00007373u, 0x00040047u, 0x00000025u, 0x00000021u, 0x00000000u,
0x00040047u, 0x00000025u, 0x00000022u, 0x00000000u, 0x00030047u, 0x00000064u, 0x00000002u, 0x00050048u,
0x00000064u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000064u, 0x00000001u, 0x00000023u,
0x00000010u, 0x00050048u, 0x00000064u, 0x00000002u, 0x00000023u, 0x00000018u, 0x00050048u, 0x00000064u,
0x00000003u, 0x00000023u, 0x0000001cu, 0x00040047u, 0x00000072u, 0x0000001eu, 0x00000000u, 0x00040047u,
0x000000f6u, 0x0000001eu, 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u,
0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000003u, 0x00040020u,
0x00000008u, 0x00000007u, 0x00000007u, 0x00040021u, 0x00000009u, 0x00000006u, 0x00000008u, 0x00040017u,
0x0000000du, 0x00000006u, 0x00000002u, 0x00040020u, 0x0000000eu, 0x00000007u, 0x0000000du, 0x00050021u,
0x0000000fu, 0x00000006u, 0x0000000eu, 0x0000000eu, 0x0004002bu, 0x00000006u, 0x00000019u, 0x3e59b3d0u,
0x0004002bu, 0x00000006u, 0x0000001au, 0x3f371759u, 0x0004002bu, 0x00000006u, 0x0000001bu, 0x3d93dd98u,
0x0006002cu, 0x00000007u, 0x0000001cu, 0x00000019u, 0x0000001au, 0x0000001bu, 0x00040020u, 0x00000020u,
0x00000007u, 0x00000006u, 0x00090019u, 0x00000022u, 0x00000006u, 0x00000001u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000001u, 0x00000000u, 0x0003001bu, 0x00000023u, 0x00000022u, 0x00040020u, 0x00000024u,
0x00000000u, 0x00000023u, 0x0004003bu, 0x00000024u, 0x00000025u, 0x00000000u, 0x00040015u, 0x00000028u,
0x00000020u, 0x00000000u, 0x0004002bu, 0x00000028u, 0x00000029u, 0x00000000u, 0x0004002bu, 0x00000006u,
0x0000002cu, 0x00000000u, 0x00040017u, 0x0000002fu, 0x00000006u, 0x00000004u, 0x0004002bu, 0x00000028u,
0x00000048u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000063u, 0x3f800000u, 0x0006001eu, 0x00000064u,
0x0000002fu, 0x0000000du, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000065u, 0x00000009u, 0x00000064u,
0x0004003bu, 0x00000065u, 0x00000066u, 0x00000009u, 0x00040015u, 0x00000067u, 0x00000020u, 0x00000001u,
0x0004002bu, 0x00000067u, 0x00000068u, 0x00000001u, 0x00040020u, 0x00000069u, 0x00000009u, 0x0000000du,
0x0005002cu, 0x0000000du, 0x0000006cu, 0x00000063u, 0x00000063u, 0x00040020u, 0x00000071u, 0x00000001u,
0x0000000du, 0x0004003bu, 0x00000071u, 0x00000072u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000075u,
0x3f000000u, 0x00040020u, 0x0000007bu, 0x00000007u, 0x0000002fu, 0x0004002bu, 0x00000006u, 0x000000deu,
0x3d3851ecu, 0x0004002bu, 0x00000006u, 0x000000e0u, 0x3da3d70au, 0x00020014u, 0x000000f1u, 0x00040020u,
0x000000f5u, 0x00000003u, 0x0000002fu, 0x0004003bu, 0x000000f5u, 0x000000f6u, 0x00000003u, 0x00040020u,
0x000000f9u, 0x00000007u, 0x000000f1u, 0x0004002bu, 0x00000006u, 0x00000113u, 0xbf800000u, 0x00040020u,
0x0000011fu, 0x00000007u, 0x00000067u, 0x0004002bu, 0x00000067u, 0x00000127u, 0x00000006u, 0x0004002bu,
0x00000006u, 0x00000161u, 0x3f266666u, 0x0004002bu, 0x00000006u, 0x00000182u, 0x40200000u, 0x0004002bu,
0x00000006u, 0x000001cau, 0x3d6147aeu, 0x0004002bu, 0x00000006u, 0x000001f8u, 0x3ec28f5cu, 0x0004002bu,
0x00000006u, 0x000001fcu, 0x40800000u, 0x0004002bu, 0x00000006u, 0x0000020bu, 0x3eb33333u, 0x0004002bu,
0x00000006u, 0x0000020eu, 0x40400000u, 0x0004002bu, 0x00000006u, 0x0000022au, 0x3e23d70au, 0x0004002bu,
0x00000006u, 0x00000239u, 0x3ed70a3du, 0x0004002bu, 0x00000028u, 0x0000024au, 0x00000003u, 0x00050036u,
0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, 0x0000000eu,
0x00000062u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000070u, 0x00000007u, 0x0004003bu, 0x0000007bu,
0x0000007cu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000080u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x00000081u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000085u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x0000008du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000090u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x00000098u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000009bu, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000000a3u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000a6u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000000aeu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000b1u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000b6u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000bbu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000c0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000c5u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000cfu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000d9u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000ddu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000e3u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000e7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000ebu, 0x00000007u, 0x0004003bu, 0x000000f9u,
0x000000fau, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x000000feu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000100u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000010bu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x0000010du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000011du, 0x00000007u, 0x0004003bu, 0x00000020u,
0x0000011eu, 0x00000007u, 0x0004003bu, 0x0000011fu, 0x00000120u, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000129u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000012eu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000130u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000136u, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000137u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000013eu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x0000013fu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000143u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000145u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000014bu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x0000014cu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000153u, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000154u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000017bu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x0000017fu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000186u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x00000192u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000195u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000001a0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001a3u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000001aeu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001b1u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000001bbu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001beu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001c7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ceu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001d0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ddu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001dfu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ecu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001f1u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001f7u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000200u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000020au, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000214u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000021cu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000220u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000226u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000229u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000235u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x0000023bu, 0x00000007u, 0x00050041u, 0x00000069u, 0x0000006au, 0x00000066u, 0x00000068u, 0x0004003du,
0x0000000du, 0x0000006bu, 0x0000006au, 0x0007000cu, 0x0000000du, 0x0000006du, 0x00000001u, 0x00000028u,
0x0000006bu, 0x0000006cu, 0x00050050u, 0x0000000du, 0x0000006eu, 0x00000063u, 0x00000063u, 0x00050088u,
0x0000000du, 0x0000006fu, 0x0000006eu, 0x0000006du, 0x0003003eu, 0x00000062u, 0x0000006fu, 0x0004003du,
0x0000000du, 0x00000073u, 0x00000072u, 0x0004003du, 0x0000000du, 0x00000074u, 0x00000062u, 0x0005008eu,
0x0000000du, 0x00000076u, 0x00000074u, 0x00000075u, 0x0004003du, 0x0000000du, 0x00000077u, 0x00000062u,
0x0005008eu, 0x0000000du, 0x00000078u, 0x00000077u, 0x00000075u, 0x00050083u, 0x0000000du, 0x00000079u,
0x0000006cu, 0x00000078u, 0x0008000cu, 0x0000000du, 0x0000007au, 0x00000001u, 0x0000002bu, 0x00000073u,
0x00000076u, 0x00000079u, 0x0003003eu, 0x00000070u, 0x0000007au, 0x0004003du, 0x00000023u, 0x0000007du,
0x00000025u, 0x0004003du, 0x0000000du, 0x0000007eu, 0x00000070u, 0x00050057u, 0x0000002fu, 0x0000007fu,
0x0000007du, 0x0000007eu, 0x0003003eu, 0x0000007cu, 0x0000007fu, 0x0004003du, 0x0000002fu, 0x00000082u,
0x0000007cu, 0x0008004fu, 0x00000007u, 0x00000083u, 0x00000082u, 0x00000082u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x00000081u, 0x00000083u, 0x00050039u, 0x00000006u, 0x00000084u, 0x0000000bu,
0x00000081u, 0x0003003eu, 0x00000080u, 0x00000084u, 0x0004003du, 0x00000023u, 0x00000086u, 0x00000025u,
0x0004003du, 0x0000000du, 0x00000087u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000088u, 0x00000062u,
0x00000029u, 0x0004003du, 0x00000006u, 0x00000089u, 0x00000088u, 0x00050050u, 0x0000000du, 0x0000008au,
0x00000089u, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000008bu, 0x00000087u, 0x0000008au, 0x00050057u,
0x0000002fu, 0x0000008cu, 0x00000086u, 0x0000008bu, 0x0008004fu, 0x00000007u, 0x0000008eu, 0x0000008cu,
0x0000008cu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000008du, 0x0000008eu, 0x00050039u,
0x00000006u, 0x0000008fu, 0x0000000bu, 0x0000008du, 0x0003003eu, 0x00000085u, 0x0000008fu, 0x0004003du,
0x00000023u, 0x00000091u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000092u, 0x00000070u, 0x00050041u,
0x00000020u, 0x00000093u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000094u, 0x00000093u,
0x00050050u, 0x0000000du, 0x00000095u, 0x00000094u, 0x0000002cu, 0x00050081u, 0x0000000du, 0x00000096u,
0x00000092u, 0x00000095u, 0x00050057u, 0x0000002fu, 0x00000097u, 0x00000091u, 0x00000096u, 0x0008004fu,
0x00000007u, 0x00000099u, 0x00000097u, 0x00000097u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu,
0x00000098u, 0x00000099u, 0x00050039u, 0x00000006u, 0x0000009au, 0x0000000bu, 0x00000098u, 0x0003003eu,
0x00000090u, 0x0000009au, 0x0004003du, 0x00000023u, 0x0000009cu, 0x00000025u, 0x0004003du, 0x0000000du,
0x0000009du, 0x00000070u, 0x00050041u, 0x00000020u, 0x0000009eu, 0x00000062u, 0x00000048u, 0x0004003du,
0x00000006u, 0x0000009fu, 0x0000009eu, 0x00050050u, 0x0000000du, 0x000000a0u, 0x0000002cu, 0x0000009fu,
0x00050083u, 0x0000000du, 0x000000a1u, 0x0000009du, 0x000000a0u, 0x00050057u, 0x0000002fu, 0x000000a2u,
0x0000009cu, 0x000000a1u, 0x0008004fu, 0x00000007u, 0x000000a4u, 0x000000a2u, 0x000000a2u, 0x00000000u,
0x00000001u, 0x00000002u, 0x0003003eu, 0x000000a3u, 0x000000a4u, 0x00050039u, 0x00000006u, 0x000000a5u,
0x0000000bu, 0x000000a3u, 0x0003003eu, 0x0000009bu, 0x000000a5u, 0x0004003du, 0x00000023u, 0x000000a7u,
0x00000025u, 0x0004003du, 0x0000000du, 0x000000a8u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000000a9u,
0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000000aau, 0x000000a9u, 0x00050050u, 0x0000000du,
0x000000abu, 0x0000002cu, 0x000000aau, 0x00050081u, 0x0000000du, 0x000000acu, 0x000000a8u, 0x000000abu,
0x00050057u, 0x0000002fu, 0x000000adu, 0x000000a7u, 0x000000acu, 0x0008004fu, 0x00000007u, 0x000000afu,
0x000000adu, 0x000000adu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000000aeu, 0x000000afu,
0x00050039u, 0x00000006u, 0x000000b0u, 0x0000000bu, 0x000000aeu, 0x0003003eu, 0x000000a6u, 0x000000b0u,
0x0004003du, 0x00000006u, 0x000000b2u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b3u, 0x00000085u,
0x00050083u, 0x00000006u, 0x000000b4u, 0x000000b2u, 0x000000b3u, 0x0006000cu, 0x00000006u, 0x000000b5u,
0x00000001u, 0x00000004u, 0x000000b4u, 0x0003003eu, 0x000000b1u, 0x000000b5u, 0x0004003du, 0x00000006u,
0x000000b7u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b8u, 0x00000090u, 0x00050083u, 0x00000006u,
0x000000b9u, 0x000000b7u, 0x000000b8u, 0x0006000cu, 0x00000006u, 0x000000bau, 0x00000001u, 0x00000004u,
0x000000b9u, 0x0003003eu, 0x000000b6u, 0x000000bau, 0x0004003du, 0x00000006u, 0x000000bcu, 0x00000080u,
0x0004003du, 0x00000006u, 0x000000bdu, 0x0000009bu, 0x00050083u, 0x00000006u, 0x000000beu, 0x000000bcu,
0x000000bdu, 0x0006000cu, 0x00000006u, 0x000000bfu, 0x00000001u, 0x00000004u, 0x000000beu, 0x0003003eu,
0x000000bbu, 0x000000bfu, 0x0004003du, 0x00000006u, 0x000000c1u, 0x00000080u, 0x0004003du, 0x00000006u,
0x000000c2u, 0x000000a6u, 0x00050083u, 0x00000006u, 0x000000c3u, 0x000000c1u, 0x000000c2u, 0x0006000cu,
0x00000006u, 0x000000c4u, 0x00000001u, 0x00000004u, 0x000000c3u, 0x0003003eu, 0x000000c0u, 0x000000c4u,
0x0004003du, 0x00000006u, 0x000000c6u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000c7u, 0x00000085u,
0x0004003du, 0x00000006u, 0x000000c8u, 0x00000090u, 0x0007000cu, 0x00000006u, 0x000000c9u, 0x00000001u,
0x00000025u, 0x000000c7u, 0x000000c8u, 0x0004003du, 0x00000006u, 0x000000cau, 0x0000009bu, 0x0004003du,
0x00000006u, 0x000000cbu, 0x000000a6u, 0x0007000cu, 0x00000006u, 0x000000ccu, 0x00000001u, 0x00000025u,
0x000000cau, 0x000000cbu, 0x0007000cu, 0x00000006u, 0x000000cdu, 0x00000001u, 0x00000025u, 0x000000c9u,
0x000000ccu, 0x0007000cu, 0x00000006u, 0x000000ceu, 0x00000001u, 0x00000025u, 0x000000c6u, 0x000000cdu,
0x0003003eu, 0x000000c5u, 0x000000ceu, 0x0004003du, 0x00000006u, 0x000000d0u, 0x00000080u, 0x0004003du,
0x00000006u, 0x000000d1u, 0x00000085u, 0x0004003du, 0x00000006u, 0x000000d2u, 0x00000090u, 0x0007000cu,
0x00000006u, 0x000000d3u, 0x00000001u, 0x00000028u, 0x000000d1u, 0x000000d2u, 0x0004003du, 0x00000006u,
0x000000d4u, 0x0000009bu, 0x0004003du, 0x00000006u, 0x000000d5u, 0x000000a6u, 0x0007000cu, 0x00000006u,
0x000000d6u, 0x00000001u, 0x00000028u, 0x000000d4u, 0x000000d5u, 0x0007000cu, 0x00000006u, 0x000000d7u,
0x00000001u, 0x00000028u, 0x000000d3u, 0x000000d6u, 0x0007000cu, 0x00000006u, 0x000000d8u, 0x00000001u,
0x00000028u, 0x000000d0u, 0x000000d7u, 0x0003003eu, 0x000000cfu, 0x000000d8u, 0x0004003du, 0x00000006u,
0x000000dau, 0x000000cfu, 0x0004003du, 0x00000006u, 0x000000dbu, 0x000000c5u, 0x00050083u, 0x00000006u,
0x000000dcu, 0x000000dau, 0x000000dbu, 0x0003003eu, 0x000000d9u, 0x000000dcu, 0x0004003du, 0x00000006u,
0x000000dfu, 0x000000d9u, 0x00050085u, 0x00000006u, 0x000000e1u, 0x000000dfu, 0x000000e0u, 0x0007000cu,
0x00000006u, 0x000000e2u, 0x00000001u, 0x00000028u, 0x000000deu, 0x000000e1u, 0x0003003eu, 0x000000ddu,
0x000000e2u, 0x0004003du, 0x00000006u, 0x000000e4u, 0x000000b1u, 0x0004003du, 0x00000006u, 0x000000e5u,
0x000000b6u, 0x0007000cu, 0x00000006u, 0x000000e6u, 0x00000001u, 0x00000028u, 0x000000e4u, 0x000000e5u,
0x0003003eu, 0x000000e3u, 0x000000e6u, 0x0004003du, 0x00000006u, 0x000000e8u, 0x000000bbu, 0x0004003du,
0x00000006u, 0x000000e9u, 0x000000c0u, 0x0007000cu, 0x00000006u, 0x000000eau, 0x00000001u, 0x00000028u,
0x000000e8u, 0x000000e9u, 0x0003003eu, 0x000000e7u, 0x000000eau, 0x0004003du, 0x00000006u, 0x000000ecu,
0x000000e3u, 0x0004003du, 0x00000006u, 0x000000edu, 0x000000e7u, 0x0007000cu, 0x00000006u, 0x000000eeu,
0x00000001u, 0x00000028u, 0x000000ecu, 0x000000edu, 0x0003003eu, 0x000000ebu, 0x000000eeu, 0x0004003du,
0x00000006u, 0x000000efu, 0x000000ebu, 0x0004003du, 0x00000006u, 0x000000f0u, 0x000000ddu, 0x000500bcu,
0x000000f1u, 0x000000f2u, 0x000000efu, 0x000000f0u, 0x000300f7u, 0x000000f4u, 0x00000000u, 0x000400fau,
0x000000f2u, 0x000000f3u, 0x000000f4u, 0x000200f8u, 0x000000f3u, 0x0004003du, 0x0000002fu, 0x000000f7u,
0x0000007cu, 0x0003003eu, 0x000000f6u, 0x000000f7u, 0x000100fdu, 0x000200f8u, 0x000000f4u, 0x0004003du,
0x00000006u, 0x000000fbu, 0x000000e3u, 0x0004003du, 0x00000006u, 0x000000fcu, 0x000000e7u, 0x000500beu,
0x000000f1u, 0x000000fdu, 0x000000fbu, 0x000000fcu, 0x0003003eu, 0x000000fau, 0x000000fdu, 0x0004003du,
0x000000f1u, 0x000000ffu, 0x000000fau, 0x000300f7u, 0x00000102u, 0x00000000u, 0x000400fau, 0x000000ffu,
0x00000101u, 0x00000106u, 0x000200f8u, 0x00000101u, 0x00050041u, 0x00000020u, 0x00000103u, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x00000104u, 0x00000103u, 0x00050050u, 0x0000000du, 0x00000105u,
0x0000002cu, 0x00000104u, 0x0003003eu, 0x00000100u, 0x00000105u, 0x000200f9u, 0x00000102u, 0x000200f8u,
0x00000106u, 0x00050041u, 0x00000020u, 0x00000107u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u,
0x00000108u, 0x00000107u, 0x00050050u, 0x0000000du, 0x00000109u, 0x00000108u, 0x0000002cu, 0x0003003eu,
0x00000100u, 0x00000109u, 0x000200f9u, 0x00000102u, 0x000200f8u, 0x00000102u, 0x0004003du, 0x0000000du,
0x0000010au, 0x00000100u, 0x0003003eu, 0x000000feu, 0x0000010au, 0x0004003du, 0x000000f1u, 0x0000010cu,
0x000000fau, 0x000300f7u, 0x0000010fu, 0x00000000u, 0x000400fau, 0x0000010cu, 0x0000010eu, 0x00000116u,
0x000200f8u, 0x0000010eu, 0x0004003du, 0x00000006u, 0x00000110u, 0x000000b1u, 0x0004003du, 0x00000006u,
0x00000111u, 0x000000b6u, 0x000500beu, 0x000000f1u, 0x00000112u, 0x00000110u, 0x00000111u, 0x000600a9u,
0x00000006u, 0x00000114u, 0x00000112u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x00000115u,
0x00000114u, 0x0000002cu, 0x0003003eu, 0x0000010du, 0x00000115u, 0x000200f9u, 0x0000010fu, 0x000200f8u,
0x00000116u, 0x0004003du, 0x00000006u, 0x00000117u, 0x000000bbu, 0x0004003du, 0x00000006u, 0x00000118u,
0x000000c0u, 0x000500beu, 0x000000f1u, 0x00000119u, 0x00000117u, 0x00000118u, 0x000600a9u, 0x00000006u,
0x0000011au, 0x00000119u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x0000011bu, 0x0000002cu,
0x0000011au, 0x0003003eu, 0x0000010du, 0x0000011bu, 0x000200f9u, 0x0000010fu, 0x000200f8u, 0x0000010fu,
0x0004003du, 0x0000000du, 0x0000011cu, 0x0000010du, 0x0003003eu, 0x0000010bu, 0x0000011cu, 0x0003003eu,
0x0000011du, 0x0000002cu, 0x0003003eu, 0x0000011eu, 0x0000002cu, 0x0003003eu, 0x00000120u, 0x00000068u,
0x000200f9u, 0x00000121u, 0x000200f8u, 0x00000121u, 0x000400f6u, 0x00000123u, 0x00000124u, 0x00000000u,
0x000200f9u, 0x00000125u, 0x000200f8u, 0x00000125u, 0x0004003du, 0x00000067u, 0x00000126u, 0x00000120u,
0x000500b3u, 0x000000f1u, 0x00000128u, 0x00000126u, 0x00000127u, 0x000400fau, 0x00000128u, 0x00000122u,
0x00000123u, 0x000200f8u, 0x00000122u, 0x0004003du, 0x0000000du, 0x0000012au, 0x000000feu, 0x0004003du,
0x00000067u, 0x0000012bu, 0x00000120u, 0x0004006fu, 0x00000006u, 0x0000012cu, 0x0000012bu, 0x0005008eu,
0x0000000du, 0x0000012du, 0x0000012au, 0x0000012cu, 0x0003003eu, 0x00000129u, 0x0000012du, 0x0004003du,
0x000000f1u, 0x0000012fu, 0x000000fau, 0x000300f7u, 0x00000132u, 0x00000000u, 0x000400fau, 0x0000012fu,
0x00000131u, 0x0000013au, 0x000200f8u, 0x00000131u, 0x0004003du, 0x0000000du, 0x00000133u, 0x00000070u,
0x0004003du, 0x0000000du, 0x00000134u, 0x00000129u, 0x00050083u, 0x0000000du, 0x00000135u, 0x00000133u,
0x00000134u, 0x0003003eu, 0x00000136u, 0x00000135u, 0x0004003du, 0x0000000du, 0x00000138u, 0x00000062u,
0x0003003eu, 0x00000137u, 0x00000138u, 0x00060039u, 0x00000006u, 0x00000139u, 0x00000012u, 0x00000136u,
0x00000137u, 0x0003003eu, 0x00000130u, 0x00000139u, 0x000200f9u, 0x00000132u, 0x000200f8u, 0x0000013au,
0x0004003du, 0x0000000du, 0x0000013bu, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000013cu, 0x00000129u,
0x00050083u, 0x0000000du, 0x0000013du, 0x0000013bu, 0x0000013cu, 0x0003003eu, 0x0000013eu, 0x0000013du,
0x0004003du, 0x0000000du, 0x00000140u, 0x00000062u, 0x0003003eu, 0x0000013fu, 0x00000140u, 0x00060039u,
0x00000006u, 0x00000141u, 0x00000016u, 0x0000013eu, 0x0000013fu, 0x0003003eu, 0x00000130u, 0x00000141u,
0x000200f9u, 0x00000132u, 0x000200f8u, 0x00000132u, 0x0004003du, 0x00000006u, 0x00000142u, 0x00000130u,
0x0003003eu, 0x0000012eu, 0x00000142u, 0x0004003du, 0x000000f1u, 0x00000144u, 0x000000fau, 0x000300f7u,
0x00000147u, 0x00000000u, 0x000400fau, 0x00000144u, 0x00000146u, 0x0000014fu, 0x000200f8u, 0x00000146u,
0x0004003du, 0x0000000du, 0x00000148u, 0x00000070u, 0x0004003du, 0x0000000du, 0x00000149u, 0x00000129u,
0x00050081u, 0x0000000du, 0x0000014au, 0x00000148u, 0x00000149u, 0x0003003eu, 0x0000014bu, 0x0000014au,
0x0004003du, 0x0000000du, 0x0000014du, 0x00000062u, 0x0003003eu, 0x0000014cu, 0x0000014du, 0x00060039u,
0x00000006u, 0x0000014eu, 0x00000012u, 0x0000014bu, 0x0000014cu, 0x0003003eu, 0x00000145u, 0x0000014eu,
0x000200f9u, 0x00000147u, 0x000200f8u, 0x0000014fu, 0x0004003du, 0x0000000du, 0x00000150u, 0x00000070u,
0x0004003du, 0x0000000du, 0x00000151u, 0x00000129u, 0x00050081u, 0x0000000du, 0x00000152u, 0x00000150u,
0x00000151u, 0x0003003eu, 0x00000153u, 0x00000152u, 0x0004003du, 0x0000000du, 0x00000155u, 0x00000062u,
0x0003003eu, 0x00000154u, 0x00000155u, 0x00060039u, 0x00000006u, 0x00000156u, 0x00000016u, 0x00000153u,
0x00000154u, 0x0003003eu, 0x00000145u, 0x00000156u, 0x000200f9u, 0x00000147u, 0x000200f8u, 0x00000147u,
0x0004003du, 0x00000006u, 0x00000157u, 0x00000145u, 0x0003003eu, 0x00000143u, 0x00000157u, 0x0004003du,
0x00000006u, 0x00000158u, 0x0000011du, 0x0004003du, 0x00000067u, 0x00000159u, 0x00000120u, 0x00050082u,
0x00000067u, 0x0000015au, 0x00000159u, 0x00000068u, 0x0004006fu, 0x00000006u, 0x0000015bu, 0x0000015au,
0x000500b4u, 0x000000f1u, 0x0000015cu, 0x00000158u, 0x0000015bu, 0x000300f7u, 0x0000015eu, 0x00000000u,
0x000400fau, 0x0000015cu, 0x0000015du, 0x0000015eu, 0x000200f8u, 0x0000015du, 0x0004003du, 0x00000006u,
0x0000015fu, 0x0000012eu, 0x0004003du, 0x00000006u, 0x00000160u, 0x000000ddu, 0x00050085u, 0x00000006u,
0x00000162u, 0x00000160u, 0x00000161u, 0x000500bau, 0x000000f1u, 0x00000163u, 0x0000015fu, 0x00000162u,
0x000200f9u, 0x0000015eu, 0x000200f8u, 0x0000015eu, 0x000700f5u, 0x000000f1u, 0x00000164u, 0x0000015cu,
0x00000147u, 0x00000163u, 0x0000015du, 0x000300f7u, 0x00000166u, 0x00000000u, 0x000400fau, 0x00000164u,
0x00000165u, 0x00000166u, 0x000200f8u, 0x00000165u, 0x0004003du, 0x00000067u, 0x00000167u, 0x00000120u,
0x0004006fu, 0x00000006u, 0x00000168u, 0x00000167u, 0x0003003eu, 0x0000011du, 0x00000168u, 0x000200f9u,
0x00000166u, 0x000200f8u, 0x00000166u, 0x0004003du, 0x00000006u, 0x00000169u, 0x0000011eu, 0x0004003du,
0x00000067u, 0x0000016au, 0x00000120u, 0x00050082u, 0x00000067u, 0x0000016bu, 0x0000016au, 0x00000068u,
0x0004006fu, 0x00000006u, 0x0000016cu, 0x0000016bu, 0x000500b4u, 0x000000f1u, 0x0000016du, 0x00000169u,
0x0000016cu, 0x000300f7u, 0x0000016fu, 0x00000000u, 0x000400fau, 0x0000016du, 0x0000016eu, 0x0000016fu,
0x000200f8u, 0x0000016eu, 0x0004003du, 0x00000006u, 0x00000170u, 0x00000143u, 0x0004003du, 0x00000006u,
0x00000171u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000172u, 0x00000171u, 0x00000161u, 0x000500bau,
0x000000f1u, 0x00000173u, 0x00000170u, 0x00000172u, 0x000200f9u, 0x0000016fu, 0x000200f8u, 0x0000016fu,
0x000700f5u, 0x000000f1u, 0x00000174u, 0x0000016du, 0x00000166u, 0x00000173u, 0x0000016eu, 0x000300f7u,
0x00000176u, 0x00000000u, 0x000400fau, 0x00000174u, 0x00000175u, 0x00000176u, 0x000200f8u, 0x00000175u,
0x0004003du, 0x00000067u, 0x00000177u, 0x00000120u, 0x0004006fu, 0x00000006u, 0x00000178u, 0x00000177u,
0x0003003eu, 0x0000011eu, 0x00000178u, 0x000200f9u, 0x00000176u, 0x000200f8u, 0x00000176u, 0x000200f9u,
0x00000124u, 0x000200f8u, 0x00000124u, 0x0004003du, 0x00000067u, 0x00000179u, 0x00000120u, 0x00050080u,
0x00000067u, 0x0000017au, 0x00000179u, 0x00000068u, 0x0003003eu, 0x00000120u, 0x0000017au, 0x000200f9u,
0x00000121u, 0x000200f8u, 0x00000123u, 0x0004003du, 0x00000006u, 0x0000017cu, 0x0000011du, 0x0004003du,
0x00000006u, 0x0000017du, 0x0000011eu, 0x00050081u, 0x00000006u, 0x0000017eu, 0x0000017cu, 0x0000017du,
0x0003003eu, 0x0000017bu, 0x0000017eu, 0x0004003du, 0x00000006u, 0x00000180u, 0x000000ddu, 0x0004003du,
0x00000006u, 0x00000181u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000183u, 0x00000181u, 0x00000182u,
0x0004003du, 0x00000006u, 0x00000184u, 0x000000ebu, 0x0008000cu, 0x00000006u, 0x00000185u, 0x00000001u,
0x00000031u, 0x00000180u, 0x00000183u, 0x00000184u, 0x0003003eu, 0x0000017fu, 0x00000185u, 0x0004003du,
0x00000023u, 0x00000187u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000188u, 0x00000070u, 0x00050041u,
0x00000020u, 0x00000189u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000018au, 0x00000189u,
0x0004007fu, 0x00000006u, 0x0000018bu, 0x0000018au, 0x00050041u, 0x00000020u, 0x0000018cu, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x0000018du, 0x0000018cu, 0x0004007fu, 0x00000006u, 0x0000018eu,
0x0000018du, 0x00050050u, 0x0000000du, 0x0000018fu, 0x0000018bu, 0x0000018eu, 0x00050081u, 0x0000000du,
0x00000190u, 0x00000188u, 0x0000018fu, 0x00050057u, 0x0000002fu, 0x00000191u, 0x00000187u, 0x00000190u,
0x0008004fu, 0x00000007u, 0x00000193u, 0x00000191u, 0x00000191u, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x00000192u, 0x00000193u, 0x00050039u, 0x00000006u, 0x00000194u, 0x0000000bu, 0x00000192u,
0x0003003eu, 0x00000186u, 0x00000194u, 0x0004003du, 0x00000023u, 0x00000196u, 0x00000025u, 0x0004003du,
0x0000000du, 0x00000197u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000198u, 0x00000062u, 0x00000029u,
0x0004003du, 0x00000006u, 0x00000199u, 0x00000198u, 0x00050041u, 0x00000020u, 0x0000019au, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x0000019bu, 0x0000019au, 0x0004007fu, 0x00000006u, 0x0000019cu,
0x0000019bu, 0x00050050u, 0x0000000du, 0x0000019du, 0x00000199u, 0x0000019cu, 0x00050081u, 0x0000000du,
0x0000019eu, 0x00000197u, 0x0000019du, 0x00050057u, 0x0000002fu, 0x0000019fu, 0x00000196u, 0x0000019eu,
0x0008004fu, 0x00000007u, 0x000001a1u, 0x0000019fu, 0x0000019fu, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x000001a0u, 0x000001a1u, 0x00050039u, 0x00000006u, 0x000001a2u, 0x0000000bu, 0x000001a0u,
0x0003003eu, 0x00000195u, 0x000001a2u, 0x0004003du, 0x00000023u, 0x000001a4u, 0x00000025u, 0x0004003du,
0x0000000du, 0x000001a5u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001a6u, 0x00000062u, 0x00000029u,
0x0004003du, 0x00000006u, 0x000001a7u, 0x000001a6u, 0x0004007fu, 0x00000006u, 0x000001a8u, 0x000001a7u,
0x00050041u, 0x00000020u, 0x000001a9u, 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000001aau,
0x000001a9u, 0x00050050u, 0x0000000du, 0x000001abu, 0x000001a8u, 0x000001aau, 0x00050081u, 0x0000000du,
0x000001acu, 0x000001a5u, 0x000001abu, 0x00050057u, 0x0000002fu, 0x000001adu, 0x000001a4u, 0x000001acu,
0x0008004fu, 0x00000007u, 0x000001afu, 0x000001adu, 0x000001adu, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x000001aeu, 0x000001afu, 0x00050039u, 0x00000006u, 0x000001b0u, 0x0000000bu, 0x000001aeu,
0x0003003eu, 0x000001a3u, 0x000001b0u, 0x0004003du, 0x00000023u, 0x000001b2u, 0x00000025u, 0x0004003du,
0x0000000du, 0x000001b3u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001b4u, 0x00000062u, 0x00000029u,
0x0004003du, 0x00000006u, 0x000001b5u, 0x000001b4u, 0x00050041u, 0x00000020u, 0x000001b6u, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x000001b7u, 0x000001b6u, 0x00050050u, 0x0000000du, 0x000001b8u,
0x000001b5u, 0x000001b7u, 0x00050081u, 0x0000000du, 0x000001b9u, 0x000001b3u, 0x000001b8u, 0x00050057u,
0x0000002fu, 0x000001bau, 0x000001b2u, 0x000001b9u, 0x0008004fu, 0x00000007u, 0x000001bcu, 0x000001bau,
0x000001bau, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000001bbu, 0x000001bcu, 0x00050039u,
0x00000006u, 0x000001bdu, 0x0000000bu, 0x000001bbu, 0x0003003eu, 0x000001b1u, 0x000001bdu, 0x0004003du,
0x00000006u, 0x000001bfu, 0x0000011du, 0x0004003du, 0x00000006u, 0x000001c0u, 0x0000011eu, 0x00050083u,
0x00000006u, 0x000001c1u, 0x000001bfu, 0x000001c0u, 0x0006000cu, 0x00000006u, 0x000001c2u, 0x00000001u,
0x00000004u, 0x000001c1u, 0x0004003du, 0x00000006u, 0x000001c3u, 0x0000017bu, 0x0007000cu, 0x00000006u,
0x000001c4u, 0x00000001u, 0x00000028u, 0x000001c3u, 0x00000063u, 0x00050088u, 0x00000006u, 0x000001c5u,
0x000001c2u, 0x000001c4u, 0x0008000cu, 0x00000006u, 0x000001c6u, 0x00000001u, 0x0000002bu, 0x000001c5u,
0x0000002cu, 0x00000063u, 0x0003003eu, 0x000001beu, 0x000001c6u, 0x0004003du, 0x00000006u, 0x000001c8u,
0x000001beu, 0x0004003du, 0x00000006u, 0x000001c9u, 0x0000017bu, 0x00050085u, 0x00000006u, 0x000001cbu,
0x000001c9u, 0x000001cau, 0x00050081u, 0x00000006u, 0x000001ccu, 0x00000063u, 0x000001cbu, 0x00050088u,
0x00000006u, 0x000001cdu, 0x000001c8u, 0x000001ccu, 0x0003003eu, 0x000001c7u, 0x000001cdu, 0x0004003du,
0x000000f1u, 0x000001cfu, 0x000000fau, 0x000300f7u, 0x000001d2u, 0x00000000u, 0x000400fau, 0x000001cfu,
0x000001d1u, 0x000001d7u, 0x000200f8u, 0x000001d1u, 0x0004003du, 0x00000006u, 0x000001d3u, 0x00000186u,
0x0004003du, 0x00000006u, 0x000001d4u, 0x00000195u, 0x00050083u, 0x00000006u, 0x000001d5u, 0x000001d3u,
0x000001d4u, 0x0006000cu, 0x00000006u, 0x000001d6u, 0x00000001u, 0x00000004u, 0x000001d5u, 0x0003003eu,
0x000001d0u, 0x000001d6u, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d7u, 0x0004003du, 0x00000006u,
0x000001d8u, 0x00000186u, 0x0004003du, 0x00000006u, 0x000001d9u, 0x000001a3u, 0x00050083u, 0x00000006u,
0x000001dau, 0x000001d8u, 0x000001d9u, 0x0006000cu, 0x00000006u, 0x000001dbu, 0x00000001u, 0x00000004u,
0x000001dau, 0x0003003eu, 0x000001d0u, 0x000001dbu, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d2u,
0x0004003du, 0x00000006u, 0x000001dcu, 0x000001d0u, 0x0003003eu, 0x000001ceu, 0x000001dcu, 0x0004003du,
0x000000f1u, 0x000001deu, 0x000000fau, 0x000300f7u, 0x000001e1u, 0x00000000u, 0x000400fau, 0x000001deu,
0x000001e0u, 0x000001e6u, 0x000200f8u, 0x000001e0u, 0x0004003du, 0x00000006u, 0x000001e2u, 0x000001a3u,
0x0004003du, 0x00000006u, 0x000001e3u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x000001e4u, 0x000001e2u,
0x000001e3u, 0x0006000cu, 0x00000006u, 0x000001e5u, 0x00000001u, 0x00000004u, 0x000001e4u, 0x0003003eu,
0x000001dfu, 0x000001e5u, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e6u, 0x0004003du, 0x00000006u,
0x000001e7u, 0x00000195u, 0x0004003du, 0x00000006u, 0x000001e8u, 0x000001b1u, 0x00050083u, 0x00000006u,
0x000001e9u, 0x000001e7u, 0x000001e8u, 0x0006000cu, 0x00000006u, 0x000001eau, 0x00000001u, 0x00000004u,
0x000001e9u, 0x0003003eu, 0x000001dfu, 0x000001eau, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e1u,
0x0004003du, 0x00000006u, 0x000001ebu, 0x000001dfu, 0x0003003eu, 0x000001ddu, 0x000001ebu, 0x0004003du,
0x00000006u, 0x000001edu, 0x000001ceu, 0x0004003du, 0x00000006u, 0x000001eeu, 0x000001ddu, 0x00050083u,
0x00000006u, 0x000001efu, 0x000001edu, 0x000001eeu, 0x0006000cu, 0x00000006u, 0x000001f0u, 0x00000001u,
0x00000004u, 0x000001efu, 0x0003003eu, 0x000001ecu, 0x000001f0u, 0x0004003du, 0x00000006u, 0x000001f2u,
0x000000ddu, 0x0004003du, 0x00000006u, 0x000001f3u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x000001f4u,
0x000001f3u, 0x00000182u, 0x0004003du, 0x00000006u, 0x000001f5u, 0x000001ecu, 0x0008000cu, 0x00000006u,
0x000001f6u, 0x00000001u, 0x00000031u, 0x000001f2u, 0x000001f4u, 0x000001f5u, 0x0003003eu, 0x000001f1u,
0x000001f6u, 0x0004003du, 0x00000006u, 0x000001f9u, 0x000001f1u, 0x00050085u, 0x00000006u, 0x000001fau,
0x000001f8u, 0x000001f9u, 0x0004003du, 0x00000006u, 0x000001fbu, 0x0000017bu, 0x00050088u, 0x00000006u,
0x000001fdu, 0x000001fbu, 0x000001fcu, 0x0008000cu, 0x00000006u, 0x000001feu, 0x00000001u, 0x0000002bu,
0x000001fdu, 0x0000002cu, 0x00000063u, 0x00050085u, 0x00000006u, 0x000001ffu, 0x000001fau, 0x000001feu,
0x0003003eu, 0x000001f7u, 0x000001ffu, 0x0004003du, 0x00000006u, 0x00000201u, 0x00000186u, 0x0004003du,
0x00000006u, 0x00000202u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x00000203u, 0x00000201u, 0x00000202u,
0x0006000cu, 0x00000006u, 0x00000204u, 0x00000001u, 0x00000004u, 0x00000203u, 0x0004003du, 0x00000006u,
0x00000205u, 0x00000195u, 0x0004003du, 0x00000006u, 0x00000206u, 0x000001a3u, 0x00050083u, 0x00000006u,
0x00000207u, 0x00000205u, 0x00000206u, 0x0006000cu, 0x00000006u, 0x00000208u, 0x00000001u, 0x00000004u,
0x00000207u, 0x0007000cu, 0x00000006u, 0x00000209u, 0x00000001u, 0x00000028u, 0x00000204u, 0x00000208u,
0x0003003eu, 0x00000200u, 0x00000209u, 0x0004003du, 0x00000006u, 0x0000020cu, 0x000000ddu, 0x0004003du,
0x00000006u, 0x0000020du, 0x000000ddu, 0x00050085u, 0x00000006u, 0x0000020fu, 0x0000020du, 0x0000020eu,
0x0004003du, 0x00000006u, 0x00000210u, 0x00000200u, 0x0008000cu, 0x00000006u, 0x00000211u, 0x00000001u,
0x00000031u, 0x0000020cu, 0x0000020fu, 0x00000210u, 0x00050085u, 0x00000006u, 0x00000212u, 0x0000020bu,
0x00000211u, 0x00050083u, 0x00000006u, 0x00000213u, 0x00000063u, 0x00000212u, 0x0003003eu, 0x0000020au,
0x00000213u, 0x0004003du, 0x00000006u, 0x00000215u, 0x000001f7u, 0x0004003du, 0x00000006u, 0x00000216u,
0x000001c7u, 0x00050085u, 0x00000006u, 0x00000217u, 0x00000215u, 0x00000216u, 0x0004003du, 0x00000006u,
0x00000218u, 0x0000017fu, 0x00050085u, 0x00000006u, 0x00000219u, 0x00000217u, 0x00000218u, 0x0004003du,
0x00000006u, 0x0000021au, 0x0000020au, 0x00050085u, 0x00000006u, 0x0000021bu, 0x00000219u, 0x0000021au,
0x0003003eu, 0x00000214u, 0x0000021bu, 0x0004003du, 0x00000006u, 0x0000021du, 0x000000e3u, 0x0004003du,
0x00000006u, 0x0000021eu, 0x000000e7u, 0x0007000cu, 0x00000006u, 0x0000021fu, 0x00000001u, 0x00000025u,
0x0000021du, 0x0000021eu, 0x0003003eu, 0x0000021cu, 0x0000021fu, 0x0004003du, 0x00000006u, 0x00000221u,
0x000000ddu, 0x0004003du, 0x00000006u, 0x00000222u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000223u,
0x00000222u, 0x00000182u, 0x0004003du, 0x00000006u, 0x00000224u, 0x0000021cu, 0x0008000cu, 0x00000006u,
0x00000225u, 0x00000001u, 0x00000031u, 0x00000221u, 0x00000223u, 0x00000224u, 0x0003003eu, 0x00000220u,
0x00000225u, 0x0004003du, 0x00000006u, 0x00000227u, 0x0000017bu, 0x0008000cu, 0x00000006u, 0x00000228u,
0x00000001u, 0x00000031u, 0x00000063u, 0x0000020eu, 0x00000227u, 0x0003003eu, 0x00000226u, 0x00000228u,
0x0004003du, 0x00000006u, 0x0000022bu, 0x00000220u, 0x00050085u, 0x00000006u, 0x0000022cu, 0x0000022au,
0x0000022bu, 0x0004003du, 0x00000006u, 0x0000022du, 0x0000017fu, 0x00050085u, 0x00000006u, 0x0000022eu,
0x0000022cu, 0x0000022du, 0x0004003du, 0x00000006u, 0x0000022fu, 0x0000020au, 0x00050085u, 0x00000006u,
0x00000230u, 0x0000022eu, 0x0000022fu, 0x0004003du, 0x00000006u, 0x00000231u, 0x00000226u, 0x00050085u,
0x00000006u, 0x00000232u, 0x00000230u, 0x00000231u, 0x0004003du, 0x00000006u, 0x00000233u, 0x000001f1u,
0x00050085u, 0x00000006u, 0x00000234u, 0x00000232u, 0x00000233u, 0x0003003eu, 0x00000229u, 0x00000234u,
0x0004003du, 0x00000006u, 0x00000236u, 0x00000214u, 0x0004003du, 0x00000006u, 0x00000237u, 0x00000229u,
0x0007000cu, 0x00000006u, 0x00000238u, 0x00000001u, 0x00000028u, 0x00000236u, 0x00000237u, 0x0008000cu,
0x00000006u, 0x0000023au, 0x00000001u, 0x0000002bu, 0x00000238u, 0x0000002cu, 0x00000239u, 0x0003003eu,
0x00000235u, 0x0000023au, 0x0004003du, 0x00000023u, 0x0000023cu, 0x00000025u, 0x0004003du, 0x0000000du,
0x0000023du, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000023eu, 0x0000010bu, 0x0004003du, 0x0000000du,
0x0000023fu, 0x00000062u, 0x00050085u, 0x0000000du, 0x00000240u, 0x0000023eu, 0x0000023fu, 0x00050081u,
0x0000000du, 0x00000241u, 0x0000023du, 0x00000240u, 0x00050057u, 0x0000002fu, 0x00000242u, 0x0000023cu,
0x00000241u, 0x0008004fu, 0x00000007u, 0x00000243u, 0x00000242u, 0x00000242u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x0000023bu, 0x00000243u, 0x0004003du, 0x0000002fu, 0x00000244u, 0x0000007cu,
0x0008004fu, 0x00000007u, 0x00000245u, 0x00000244u, 0x00000244u, 0x00000000u, 0x00000001u, 0x00000002u,
0x0004003du, 0x00000007u, 0x00000246u, 0x0000023bu, 0x0004003du, 0x00000006u, 0x00000247u, 0x00000235u,
0x00060050u, 0x00000007u, 0x00000248u, 0x00000247u, 0x00000247u, 0x00000247u, 0x0008000cu, 0x00000007u,
0x00000249u, 0x00000001u, 0x0000002eu, 0x00000245u, 0x00000246u, 0x00000248u, 0x00050041u, 0x00000020u,
0x0000024bu, 0x0000007cu, 0x0000024au, 0x0004003du, 0x00000006u, 0x0000024cu, 0x0000024bu, 0x00050051u,
0x00000006u, 0x0000024du, 0x00000249u, 0x00000000u, 0x00050051u, 0x00000006u, 0x0000024eu, 0x00000249u,
0x00000001u, 0x00050051u, 0x00000006u, 0x0000024fu, 0x00000249u, 0x00000002u, 0x00070050u, 0x0000002fu,
0x00000250u, 0x0000024du, 0x0000024eu, 0x0000024fu, 0x0000024cu, 0x0003003eu, 0x000000f6u, 0x00000250u,
0x000100fdu, 0x00010038u, 0x00050036u, 0x00000006u, 0x0000000bu, 0x00000000u, 0x00000009u, 0x00030037u,
0x00000008u, 0x0000000au, 0x000200f8u, 0x0000000cu, 0x0004003du, 0x00000007u, 0x00000018u, 0x0000000au,
0x00050094u, 0x00000006u, 0x0000001du, 0x00000018u, 0x0000001cu, 0x000200feu, 0x0000001du, 0x00010038u,
0x00050036u, 0x00000006u, 0x00000012u, 0x00000000u, 0x0000000fu, 0x00030037u, 0x0000000eu, 0x00000010u,
0x00030037u, 0x0000000eu, 0x00000011u, 0x000200f8u, 0x00000013u, 0x0004003bu, 0x00000020u, 0x00000021u,
0x00000007u, 0x0004003bu, 0x00000008u, 0x00000031u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000034u,
0x00000007u, 0x0004003bu, 0x00000008u, 0x0000003cu, 0x00000007u, 0x0004003du, 0x00000023u, 0x00000026u,
0x00000025u, 0x0004003du, 0x0000000du, 0x00000027u, 0x00000010u, 0x00050041u, 0x00000020u, 0x0000002au,
0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000002bu, 0x0000002au, 0x00050050u, 0x0000000du,
0x0000002du, 0x0000002bu, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000002eu, 0x00000027u, 0x0000002du,
0x00050057u, 0x0000002fu, 0x00000030u, 0x00000026u, 0x0000002eu, 0x0008004fu, 0x00000007u, 0x00000032u,
0x00000030u, 0x00000030u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x00000031u, 0x00000032u,
0x00050039u, 0x00000006u, 0x00000033u, 0x0000000bu, 0x00000031u, 0x0003003eu, 0x00000021u, 0x00000033u,
0x0004003du, 0x00000023u, 0x00000035u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000036u, 0x00000010u,
0x00050041u, 0x00000020u, 0x00000037u, 0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000038u,
0x00000037u, 0x00050050u, 0x0000000du, 0x00000039u, 0x00000038u, 0x0000002cu, 0x00050081u, 0x0000000du,
0x0000003au, 0x00000036u, 0x00000039u, 0x00050057u, 0x0000002fu, 0x0000003bu, 0x00000035u, 0x0000003au,
0x0008004fu, 0x00000007u, 0x0000003du, 0x0000003bu, 0x0000003bu, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x0000003cu, 0x0000003du, 0x00050039u, 0x00000006u, 0x0000003eu, 0x0000000bu, 0x0000003cu,
0x0003003eu, 0x00000034u, 0x0000003eu, 0x0004003du, 0x00000006u, 0x0000003fu, 0x00000021u, 0x0004003du,
0x00000006u, 0x00000040u, 0x00000034u, 0x00050083u, 0x00000006u, 0x00000041u, 0x0000003fu, 0x00000040u,
0x0006000cu, 0x00000006u, 0x00000042u, 0x00000001u, 0x00000004u, 0x00000041u, 0x000200feu, 0x00000042u,
0x00010038u, 0x00050036u, 0x00000006u, 0x00000016u, 0x00000000u, 0x0000000fu, 0x00030037u, 0x0000000eu,
0x00000014u, 0x00030037u, 0x0000000eu, 0x00000015u, 0x000200f8u, 0x00000017u, 0x0004003bu, 0x00000020u,
0x00000045u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000004eu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000051u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000059u, 0x00000007u, 0x0004003du, 0x00000023u,
0x00000046u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000047u, 0x00000014u, 0x00050041u, 0x00000020u,
0x00000049u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000004au, 0x00000049u, 0x00050050u,
0x0000000du, 0x0000004bu, 0x0000002cu, 0x0000004au, 0x00050083u, 0x0000000du, 0x0000004cu, 0x00000047u,
0x0000004bu, 0x00050057u, 0x0000002fu, 0x0000004du, 0x00000046u, 0x0000004cu, 0x0008004fu, 0x00000007u,
0x0000004fu, 0x0000004du, 0x0000004du, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000004eu,
0x0000004fu, 0x00050039u, 0x00000006u, 0x00000050u, 0x0000000bu, 0x0000004eu, 0x0003003eu, 0x00000045u,
0x00000050u, 0x0004003du, 0x00000023u, 0x00000052u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000053u,
0x00000014u, 0x00050041u, 0x00000020u, 0x00000054u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u,
0x00000055u, 0x00000054u, 0x00050050u, 0x0000000du, 0x00000056u, 0x0000002cu, 0x00000055u, 0x00050081u,
0x0000000du, 0x00000057u, 0x00000053u, 0x00000056u, 0x00050057u, 0x0000002fu, 0x00000058u, 0x00000052u,
0x00000057u, 0x0008004fu, 0x00000007u, 0x0000005au, 0x00000058u, 0x00000058u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x00000059u, 0x0000005au, 0x00050039u, 0x00000006u, 0x0000005bu, 0x0000000bu,
0x00000059u, 0x0003003eu, 0x00000051u, 0x0000005bu, 0x0004003du, 0x00000006u, 0x0000005cu, 0x00000045u,
0x0004003du, 0x00000006u, 0x0000005du, 0x00000051u, 0x00050083u, 0x00000006u, 0x0000005eu, 0x0000005cu,
0x0000005du, 0x0006000cu, 0x00000006u, 0x0000005fu, 0x00000001u, 0x00000004u, 0x0000005eu, 0x000200feu,
0x0000005fu, 0x00010038u,
};
+1 -1
View File
@@ -26,7 +26,7 @@ add_library(droiddeckwayland SHARED
generated/linux-dmabuf-v1-protocol.c
generated/wayland-android-protocol.c
generated/viewporter-protocol.c
generated/banner-desktop-v1-protocol.c
generated/droiddeck-desktop-v1-protocol.c
generated/presentation-time-protocol.c
generated/pointer-constraints-unstable-v1-protocol.c
generated/relative-pointer-unstable-v1-protocol.c
@@ -38,7 +38,7 @@
extern const struct wl_interface wl_surface_interface;
static const struct wl_interface *banner_desktop_v1_types[] = {
static const struct wl_interface *droiddeck_desktop_v1_types[] = {
NULL,
&wl_surface_interface,
&wl_surface_interface,
@@ -47,16 +47,16 @@ static const struct wl_interface *banner_desktop_v1_types[] = {
NULL,
};
static const struct wl_message banner_desktop_v1_requests[] = {
{ "destroy", "", banner_desktop_v1_types + 0 },
{ "set_desktop", "o", banner_desktop_v1_types + 1 },
{ "set_window", "ouii", banner_desktop_v1_types + 2 },
{ "set_zorder", "a", banner_desktop_v1_types + 0 },
static const struct wl_message droiddeck_desktop_v1_requests[] = {
{ "destroy", "", droiddeck_desktop_v1_types + 0 },
{ "set_desktop", "o", droiddeck_desktop_v1_types + 1 },
{ "set_window", "ouii", droiddeck_desktop_v1_types + 2 },
{ "set_zorder", "a", droiddeck_desktop_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface banner_desktop_v1_interface = {
"banner_desktop_v1", 1,
4, banner_desktop_v1_requests,
WL_PRIVATE const struct wl_interface droiddeck_desktop_v1_interface = {
"droiddeck_desktop_v1", 1,
4, droiddeck_desktop_v1_requests,
0, NULL,
};
@@ -1,6 +1,6 @@
#ifndef BANNER_DESKTOP_V1_SERVER_PROTOCOL_H
#define BANNER_DESKTOP_V1_SERVER_PROTOCOL_H
#ifndef DROIDDECK_DESKTOP_V1_SERVER_PROTOCOL_H
#define DROIDDECK_DESKTOP_V1_SERVER_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
@@ -14,7 +14,7 @@ struct wl_client;
struct wl_resource;
/*
* @section page_copyright_banner_desktop_v1 Copyright
* @section page_copyright_droiddeck_desktop_v1 Copyright
*
* Copyright 2026 The412Banner
*
@@ -42,15 +42,15 @@ struct wl_resource;
struct banner_desktop_v1;
struct droiddeck_desktop_v1;
struct wl_surface;
#ifndef BANNER_DESKTOP_V1_INTERFACE
#define BANNER_DESKTOP_V1_INTERFACE
extern const struct wl_interface banner_desktop_v1_interface;
#ifndef DROIDDECK_DESKTOP_V1_INTERFACE
#define DROIDDECK_DESKTOP_V1_INTERFACE
extern const struct wl_interface droiddeck_desktop_v1_interface;
#endif
struct banner_desktop_v1_interface {
struct droiddeck_desktop_v1_interface {
void (*destroy)(struct wl_client *client,
struct wl_resource *resource);
void (*set_desktop)(struct wl_client *client,
@@ -68,10 +68,10 @@ struct banner_desktop_v1_interface {
};
#define BANNER_DESKTOP_V1_DESTROY_SINCE_VERSION 1
#define BANNER_DESKTOP_V1_SET_DESKTOP_SINCE_VERSION 1
#define BANNER_DESKTOP_V1_SET_WINDOW_SINCE_VERSION 1
#define BANNER_DESKTOP_V1_SET_ZORDER_SINCE_VERSION 1
#define DROIDDECK_DESKTOP_V1_DESTROY_SINCE_VERSION 1
#define DROIDDECK_DESKTOP_V1_SET_DESKTOP_SINCE_VERSION 1
#define DROIDDECK_DESKTOP_V1_SET_WINDOW_SINCE_VERSION 1
#define DROIDDECK_DESKTOP_V1_SET_ZORDER_SINCE_VERSION 1
#ifdef __cplusplus
}
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="banner_desktop_v1">
<protocol name="droiddeck_desktop_v1">
<copyright>
Copyright 2026 The412Banner
@@ -23,7 +23,7 @@
DEALINGS IN THE SOFTWARE.
</copyright>
<interface name="banner_desktop_v1" version="1">
<interface name="droiddeck_desktop_v1" version="1">
<description summary="Windows virtual desktop layout">
Each Wine process is a separate Wayland client, so a Windows virtual
desktop can't be built from subsurfaces. Instead the process that owns
@@ -14,6 +14,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/system_properties.h>
#include <time.h>
#include <unistd.h>
@@ -25,6 +26,7 @@ struct droiddeck_dma_buf_sync_file { uint32_t flags; int32_t fd; };
#define DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE _IOW('b', 3, struct droiddeck_dma_buf_sync_file)
extern volatile int g_zero_copy;
extern volatile int g_zero_copy_ahb;
struct ahb_buf {
uint64_t id;
@@ -340,7 +342,7 @@ static void bind_ahb(struct wl_client *c, void *data, uint32_t ver, uint32_t id)
if (!r) { wl_client_post_no_memory(c); return; }
wl_resource_set_implementation(r, &ahb_impl, NULL, on_client_resource_destroyed);
wl_list_insert(&g_clients, wl_resource_get_link(r));
if (ver >= BANNER_AHB_V1_MODE_SINCE_VERSION) banner_ahb_v1_send_mode(r, g_zero_copy ? 1u : 0u);
if (ver >= BANNER_AHB_V1_MODE_SINCE_VERSION) banner_ahb_v1_send_mode(r, (g_zero_copy || g_zero_copy_ahb) ? 1u : 0u);
if (last_named != c) {
last_named = c;
droiddeck_log("layer", "zero-copy: %s bound banner_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver,
@@ -356,13 +358,14 @@ void ahb_swapchain_set_mode(int on, int live) {
on ? "on" : "off");
return;
}
if (g_mode_sent == on) return;
g_mode_sent = on;
const int want = on || g_zero_copy_ahb;
if (g_mode_sent == want) return;
g_mode_sent = want;
int told = 0;
struct wl_resource *r;
wl_resource_for_each(r, &g_clients) {
if (wl_resource_get_version(r) >= BANNER_AHB_V1_MODE_SINCE_VERSION) {
banner_ahb_v1_send_mode(r, (uint32_t)on);
banner_ahb_v1_send_mode(r, (uint32_t)want);
told++;
}
}
@@ -401,5 +404,13 @@ void ahb_swapchain_init(struct wl_display *display) {
}
g_advertised = 1;
droiddeck_log("layer", "zero-copy: banner_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)");
// Android buffers only: programs that hand over their own gralloc buffers (bionic games, also through gamescope)
// are asked for them and shown on the display layer; every other frame keeps the copy path.
char prop[PROP_VALUE_MAX] = {0};
__system_property_get("persist.droiddeck.zero_copy_ahb", prop);
if (prop[0] == '1') {
g_zero_copy_ahb = 1;
droiddeck_log("layer", "zero-copy: Android buffers only (persist.droiddeck.zero_copy_ahb=1): programs that send their own gralloc buffers go on the display layer, other frames keep the copy");
}
ahb_swapchain_set_mode(g_zero_copy, 0);
}
+95 -24
View File
@@ -24,7 +24,7 @@
#include "sc_layer.h"
#include "ahb_swapchain.h"
#include "viewporter-server-protocol.h"
#include "banner-desktop-v1-server-protocol.h"
#include "droiddeck-desktop-v1-server-protocol.h"
#include "presentation-time-server-protocol.h"
#include "pointer-constraints-unstable-v1-server-protocol.h"
#include "relative-pointer-unstable-v1-server-protocol.h"
@@ -79,7 +79,7 @@ static void open_session_log(void) {
localtime_r(&now, &tm);
strftime(stamp, sizeof(stamp), "%Y-%m-%d_%H-%M-%S", &tm);
const char *given = getenv("BL_WAYLAND_LOG");
const char *given = getenv("DD_WAYLAND_LOG");
if (given && *given) {
snprintf(path, sizeof(path), "%s", given);
} else {
@@ -256,6 +256,7 @@ struct surface {
struct wl_list child_link;
int sub_x, sub_y, sub_pending_x, sub_pending_y, sub_pending;
int below_parent;
int sub_desync;
int fullscreen;
int toplevel_committed;
@@ -316,6 +317,7 @@ static struct { unsigned lit, dark, failed; } g_bfi_stats;
volatile int g_hide_shell;
volatile int g_zero_copy;
volatile int g_zero_copy_ahb;
static int g_zero_copy_paused;
static int g_zero_copy_fx_skip_said;
@@ -332,6 +334,7 @@ struct pending_release {
struct wl_resource *buffer;
struct wl_listener destroy;
struct surface *surface;
struct surface *held_by;
int64_t at_ns;
int64_t since_ns;
struct wl_list link;
@@ -434,10 +437,54 @@ static void pending_release_free(struct pending_release *pr) {
free(pr);
}
static void release_due_buffers(void);
static void arm_release_timer(void);
static void pending_releases_forget_surface(struct surface *s) {
struct pending_release *pr;
wl_list_for_each(pr, &g_pending_releases, link)
int unheld = 0;
wl_list_for_each(pr, &g_pending_releases, link) {
if (pr->surface == s) pr->surface = NULL;
if (pr->held_by == s) { pr->held_by = NULL; unheld = 1; }
}
if (unheld) { release_due_buffers(); arm_release_timer(); }
}
static void pending_releases_cancel(struct wl_resource *buffer) {
struct pending_release *pr, *tmp;
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link)
if (pr->buffer == buffer) pending_release_free(pr);
}
static void pending_releases_apply(struct surface *holder) {
struct pending_release *pr;
int unheld = 0;
wl_list_for_each(pr, &g_pending_releases, link)
if (pr->held_by == holder) { pr->held_by = NULL; unheld = 1; }
if (unheld) { release_due_buffers(); arm_release_timer(); }
}
static struct surface *sync_holder(struct surface *s) {
struct surface *holder = NULL;
for (int depth = 0; s && s->role == ROLE_SUBSURFACE && s->parent && depth < 8; depth++) {
if (!s->sub_desync) holder = s->parent;
s = s->parent;
}
return holder;
}
static void pending_releases_rehold(struct surface *changed) {
struct pending_release *pr;
int unheld = 0;
wl_list_for_each(pr, &g_pending_releases, link) {
if (!pr->held_by || !pr->surface) continue;
struct surface *s = pr->surface;
for (int depth = 0; s && s != changed && depth < 8; depth++) s = s->parent;
if (s != changed) continue;
pr->held_by = sync_holder(pr->surface);
if (!pr->held_by) unheld = 1;
}
if (unheld) { release_due_buffers(); arm_release_timer(); }
}
static void on_pending_release_buffer_destroyed(struct wl_listener *l, void *data) {
@@ -450,20 +497,18 @@ static void arm_release_timer(void) {
int64_t earliest = 0;
if (g_release_timer_fd < 0) return;
wl_list_for_each(pr, &g_pending_releases, link)
if (!buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest))
if (!pr->held_by && !buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest))
earliest = pr->at_ns;
struct itimerspec its = {0};
if (earliest) { its.it_value.tv_sec = earliest / 1000000000LL; its.it_value.tv_nsec = earliest % 1000000000LL; }
timerfd_settime(g_release_timer_fd, TFD_TIMER_ABSTIME, &its, NULL);
}
static int on_release_timer(int fd, uint32_t mask, void *data) {
static void release_due_buffers(void) {
struct pending_release *pr, *tmp;
uint64_t expirations;
int64_t now = now_ns() + 300000;
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) {
if (pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) {
if (!pr->held_by && pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) {
/* Attached again since (to its surface or another): that surface releases it later. */
if (buffer_shown_elsewhere(pr->buffer, NULL)) {
pending_release_free(pr);
@@ -474,28 +519,39 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
pending_release_free(pr);
}
}
}
static int on_release_timer(int fd, uint32_t mask, void *data) {
uint64_t expirations;
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
release_due_buffers();
wl_display_flush_clients(g_display);
arm_release_timer();
return 0;
}
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns, struct surface *holder) {
/* No allocation or immediate-release fallback is allowed for a quarantined
* DMA-BUF. Existing queued releases stay held; their timer is disarmed. */
if (buffer_release_blocked(buffer)) return;
const int limit = g_fps_limit;
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
const int paced = !g_release_unpaced && interval > 0 && g_release_timer_fd >= 0;
if (!paced && !holder) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
int64_t now = now_ns();
int64_t at = s->next_release_ns + interval;
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
if (at < now) at = now;
if (at > latest) at = latest;
s->next_release_ns = at;
int64_t at = now;
if (paced) {
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
at = s->next_release_ns + interval;
if (at < now) at = now;
if (at > latest) at = latest;
s->next_release_ns = at;
}
struct pending_release *pr = calloc(1, sizeof(*pr));
if (!pr) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
pr->buffer = buffer;
pr->surface = s;
pr->held_by = holder;
pr->at_ns = at;
pr->since_ns = since_ns;
pr->destroy.notify = on_pending_release_buffer_destroyed;
@@ -721,7 +777,7 @@ static void drop_dmabuf(struct surface *s, int paced) {
wl_list_remove(&s->dmabuf_destroy.link);
if (buffer_shown_elsewhere(s->dmabuf, s)) {
} else if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
if (paced) release_buffer(s, s->dmabuf, now_ns());
if (paced) release_buffer(s, s->dmabuf, now_ns(), sync_holder(s));
else send_buffer_release(s->dmabuf);
}
s->dmabuf = NULL;
@@ -887,6 +943,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
s->last_dmabuf = buffer;
pace_note_buffer(buffer);
drop_dmabuf(s, 1);
pending_releases_cancel(buffer);
s->dmabuf = buffer;
s->dmabuf_buf = b;
b->refs++;
@@ -977,7 +1034,7 @@ void droiddeck_dmabuf_ref(struct dmabuf_buffer *b) { b->refs++; }
void droiddeck_dmabuf_unref(struct dmabuf_buffer *b) { dmabuf_buffer_unref(b); }
void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns) {
if (buffer_release_blocked(buffer)) return;
if (paced && s) release_buffer(s, buffer, since_ns);
if (paced && s) release_buffer(s, buffer, since_ns, NULL);
else { send_buffer_release(buffer); perf_note_release(since_ns); }
}
void droiddeck_surface_describe(const struct surface *s, char *out, size_t size) { describe(s, out, size); }
@@ -1265,6 +1322,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
s->pending_attach = 0;
surface_drop_idle(s);
buf_trace_attach(buffer);
if (s->role == ROLE_CURSOR) {
if (!buffer) {
cursor_publish_hidden();
@@ -1275,7 +1333,6 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
} else if (s->role == ROLE_NONE) {
if (buffer) surface_hold_idle(s, buffer);
} else if (db) {
buf_trace_attach(buffer);
take_dmabuf(s, db, buffer);
} else if (shm) {
drop_dmabuf(s, 1);
@@ -1289,6 +1346,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
if (buffer) send_buffer_release(buffer);
}
}
pending_releases_apply(s);
wl_list_for_each(child, &s->children, child_link) {
if (child->sub_pending) {
@@ -1486,8 +1544,14 @@ static void subsurface_place_below(struct wl_client *c, struct wl_resource *r,
struct wl_resource *sibling) {
restack_child(wl_resource_get_user_data(r), wl_resource_get_user_data(sibling), 0);
}
static void subsurface_set_sync(struct wl_client *c, struct wl_resource *r) {}
static void subsurface_set_desync(struct wl_client *c, struct wl_resource *r) {}
static void subsurface_set_sync(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
if (s) s->sub_desync = 0;
}
static void subsurface_set_desync(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
if (s) { s->sub_desync = 1; pending_releases_rehold(s); }
}
static const struct wl_subsurface_interface subsurface_impl = {
.destroy = subsurface_destroy,
.set_position = subsurface_set_position,
@@ -1521,6 +1585,7 @@ static void subcompositor_get_subsurface(struct wl_client *c, struct wl_resource
s->subsurface = sub;
s->parent = p;
s->below_parent = 0;
s->sub_desync = 0;
s->sub_x = s->sub_y = 0;
wl_list_insert(p->children.prev, &s->child_link);
}
@@ -1796,14 +1861,14 @@ static void desktop_set_zorder(struct wl_client *c, struct wl_resource *r, struc
apply_zorder();
schedule_render();
}
static const struct banner_desktop_v1_interface desktop_impl = {
static const struct droiddeck_desktop_v1_interface desktop_impl = {
.destroy = desktop_destroy_req,
.set_desktop = desktop_set_desktop,
.set_window = desktop_set_window,
.set_zorder = desktop_set_zorder,
};
static void bind_desktop(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
struct wl_resource *r = wl_resource_create(c, &banner_desktop_v1_interface, ver, id);
struct wl_resource *r = wl_resource_create(c, &droiddeck_desktop_v1_interface, ver, id);
wl_resource_set_implementation(r, &desktop_impl, NULL, NULL);
}
@@ -2340,7 +2405,13 @@ static void render_scene(void) {
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen;
int li = (g_zero_copy && !framegen && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
int li = ((g_zero_copy || g_zero_copy_ahb) && !framegen && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
if (li >= 0 && !g_zero_copy) {
/* Android buffers only: the fullscreen frame goes on the display layer only when it is a gralloc buffer
* its program handed over and no screen effect needs the pass; everything else keeps the copy. */
const struct surface *cs = surface_for_image(dl.d[li].img);
if (fx_on || !cs || !cs->dmabuf_buf || !ahb_swapchain_has_ahb(cs->dmabuf_buf)) li = -1;
}
int over = li >= 0 ? dl.n - 1 - li : 0;
const int fx_blocks = (li >= 0 && fx_on && over > 0);
if (fx_blocks) { li = -1; over = 0; }
@@ -4083,7 +4154,7 @@ int droiddeck_wayland_run(void) {
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
droiddeck_android_wlegl_init(display);
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
wl_global_create(display, &droiddeck_desktop_v1_interface, 1, NULL, bind_desktop);
wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation);
wl_global_create(display, &zwp_pointer_constraints_v1_interface, 1, NULL, bind_pointer_constraints);
wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager);
@@ -17,6 +17,7 @@
#include "cas_frag.h"
#include "color_frag.h"
#include "fxaa_frag.h"
#include "smaa_frag.h"
#include "toon_frag.h"
#include "hdr_frag.h"
#include "ntsc_frag.h"
@@ -41,7 +42,7 @@ struct fx_settings {
int color_on;
float brightness, contrast, gamma, saturation;
float b_raw, c_raw, s_raw;
int fxaa, toon, crt, ntsc;
int aa_mode, toon, crt, ntsc;
char look[48];
};
@@ -78,7 +79,7 @@ void vkp_effects_set_deband(int enabled, int pct) {
}
static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; }
void vkp_effects_set_screen(float brightness, float contrast, float gamma, float saturation,
int fxaa, int toon, int crt, int ntsc) {
int aa_mode, int toon, int crt, int ntsc) {
int on = !(brightness == 0.0f && contrast == 0.0f && gamma == 1.0f && saturation == 100.0f);
set_begin();
g_set.color_on = on;
@@ -87,7 +88,8 @@ void vkp_effects_set_screen(float brightness, float contrast, float gamma, float
g_set.contrast = clampf(contrast / 100.0f, 0.0f, 2.0f);
g_set.saturation = clampf(saturation / 100.0f, 0.0f, 2.0f);
g_set.gamma = clampf(gamma, 0.1f, 5.0f);
g_set.fxaa = fxaa ? 1 : 0; g_set.toon = toon ? 1 : 0; g_set.crt = crt ? 1 : 0; g_set.ntsc = ntsc ? 1 : 0;
g_set.aa_mode = (aa_mode >= 0 && aa_mode <= 2) ? aa_mode : 0;
g_set.toon = toon ? 1 : 0; g_set.crt = crt ? 1 : 0; g_set.ntsc = ntsc ? 1 : 0;
set_end();
}
void vkp_effects_set_look(const char *name) {
@@ -103,7 +105,7 @@ static const char *scaling_name(int m) {
static int spatial_mode(int m) { return m >= 3 && m <= 8; }
static int cas_active(const struct fx_settings *s) { return s->cas_on && s->cas_pct > 0; }
static int effect_count(const struct fx_settings *s) {
return s->fxaa + s->toon + s->color_on + cas_active(s) + s->hdr_on + s->ntsc + s->crt + s->deband_on;
return (s->aa_mode != 0) + s->toon + s->color_on + cas_active(s) + s->hdr_on + s->ntsc + s->crt + s->deband_on;
}
static void log_settings(const struct fx_settings *s) {
@@ -121,7 +123,8 @@ static void log_settings(const struct fx_settings *s) {
if (s->color_on)
n += snprintf(line + n, sizeof(line) - n, ", colour b=%+.0f c=%+.0f g=%.2f s=%.0f%%",
s->b_raw, s->c_raw, s->gamma, s->s_raw);
if (s->fxaa) n += snprintf(line + n, sizeof(line) - n, ", FXAA on");
if (s->aa_mode == 1) n += snprintf(line + n, sizeof(line) - n, ", FXAA on");
else if (s->aa_mode == 2) n += snprintf(line + n, sizeof(line) - n, ", SMAA on");
if (s->toon) n += snprintf(line + n, sizeof(line) - n, ", Toon on");
if (s->hdr_on) n += snprintf(line + n, sizeof(line) - n, ", HDR on");
if (s->ntsc) n += snprintf(line + n, sizeof(line) - n, ", NTSC on");
@@ -152,6 +155,10 @@ int vkp_effects_upscaling(void) {
return spatial_mode(g_cur.scaling) && g_cur.scaling != 6;
}
int vkp_effects_sharpening(void) {
return vkp_effects_upscaling() || cas_active(&g_cur);
}
int vkp_effects_postprocessing(void) {
vkp_effects_sync();
return effect_count(&g_cur) > 0;
@@ -202,7 +209,7 @@ static VkDescriptorSetLayout g_dsl;
static VkPipelineLayout g_pl;
static VkDescriptorPool g_dpool;
static VkSampler g_sampler;
enum { P_SGSR, P_SGSR_HQ, P_NIS, P_EASU, P_RCAS, P_CAS, P_COLOR, P_FXAA, P_TOON, P_HDR, P_NTSC, P_CRT, P_DEBAND, P_COUNT };
enum { P_SGSR, P_SGSR_HQ, P_NIS, P_EASU, P_RCAS, P_CAS, P_COLOR, P_FXAA, P_SMAA, P_TOON, P_HDR, P_NTSC, P_CRT, P_DEBAND, P_COUNT };
static VkPipeline g_pipe[P_COUNT];
static struct fx_target g_t[2], g_mid;
@@ -438,6 +445,7 @@ static int objects_ensure(void) {
MK(P_CAS, cas_code, "cas");
MK(P_COLOR, color_code, "color");
MK(P_FXAA, fxaa_code, "fxaa");
MK(P_SMAA, smaa_code, "smaa");
MK(P_TOON, toon_code, "toon");
MK(P_HDR, hdr_code, "hdr");
MK(P_NTSC, ntsc_code, "ntsc");
@@ -446,7 +454,7 @@ static int objects_ensure(void) {
#undef MK
g_vk.DestroyShaderModule(g_dev, vert, NULL);
g_ready = 1;
droiddeck_log("effects", "chain ready: 13 passes (SGSR, SGSR HQ, NIS, FSR EASU+RCAS, CAS, colour, FXAA, Toon, HDR, NTSC, CRT, deband) on %s", vkp_gpu_name());
droiddeck_log("effects", "chain ready: 14 pipelines (SGSR, SGSR HQ, NIS, FSR EASU+RCAS, CAS, colour, FXAA, SMAA, Toon, HDR, NTSC, CRT, deband) on %s", vkp_gpu_name());
return 0;
fail:
objects_destroy();
@@ -567,9 +575,10 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
cur = NULL; cur_ds = g_scene.ds;
}
enum { FX_FXAA, FX_TOON, FX_COLOR, FX_CAS, FX_HDR, FX_NTSC, FX_CRT, FX_DEBAND };
enum { FX_FXAA, FX_SMAA, FX_TOON, FX_COLOR, FX_CAS, FX_HDR, FX_NTSC, FX_CRT, FX_DEBAND };
int order[8], n = 0;
if (s->fxaa) order[n++] = FX_FXAA;
if (s->aa_mode == 1) order[n++] = FX_FXAA;
else if (s->aa_mode == 2) order[n++] = FX_SMAA;
if (s->toon) order[n++] = FX_TOON;
if (s->color_on) order[n++] = FX_COLOR;
if (cas_active(s)) order[n++] = FX_CAS;
@@ -584,6 +593,7 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
pr.res[0] = (float)cw; pr.res[1] = (float)ch;
switch (order[i]) {
case FX_FXAA: pass(cmd, g_pipe[P_FXAA], dst, cur_ds, &pr, sizeof(pr)); break;
case FX_SMAA: pass(cmd, g_pipe[P_SMAA], dst, cur_ds, &pr, sizeof(pr)); break;
case FX_TOON: pass(cmd, g_pipe[P_TOON], dst, cur_ds, &pr, sizeof(pr)); break;
case FX_COLOR: {
struct pc_color pc = {0};
@@ -11,6 +11,7 @@ int vkp_effects_sync(void);
int vkp_effects_active(void);
int vkp_effects_upscaling(void);
int vkp_effects_sharpening(void);
int vkp_effects_postprocessing(void);
VkFilter vkp_effects_blit_filter(void);
@@ -30,7 +31,7 @@ void vkp_effects_set_cas(int enabled, int pct);
void vkp_effects_set_hdr(int enabled);
void vkp_effects_set_deband(int enabled, int pct);
void vkp_effects_set_screen(float brightness, float contrast, float gamma, float saturation,
int fxaa, int toon, int crt, int ntsc);
int aa_mode, int toon, int crt, int ntsc);
void vkp_effects_set_look(const char *name);
#endif
@@ -2179,7 +2179,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
if (fx) {
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
if (fg) { mapped_w = scene_w; mapped_h = scene_h; }
if (fg && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; }
vkp_effects_set_formats(scene_fmt, scene_fmt);
result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh);
effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h,
@@ -497,8 +497,8 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDeband(JNIEnv *en
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetScreenEffects(JNIEnv *env, jclass clazz, jfloat brightness,
jfloat contrast, jfloat gamma, jfloat saturation, jboolean fxaa, jboolean toon, jboolean crt, jboolean ntsc) {
vkp_effects_set_screen(brightness, contrast, gamma, saturation, fxaa ? 1 : 0, toon ? 1 : 0, crt ? 1 : 0, ntsc ? 1 : 0);
jfloat contrast, jfloat gamma, jfloat saturation, jint aa_mode, jboolean toon, jboolean crt, jboolean ntsc) {
vkp_effects_set_screen(brightness, contrast, gamma, saturation, aa_mode, toon ? 1 : 0, crt ? 1 : 0, ntsc ? 1 : 0);
}
JNIEXPORT void JNICALL
@@ -43,15 +43,17 @@ class App : Application() {
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
CrashHandler.install(this)
com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this)
com.droiddeck.launcher.agent.AgentHost.refresh(this)
com.droiddeck.launcher.agent.AgentTab.load(this)
com.droiddeck.launcher.ui.NavTabs.load(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
com.droiddeck.launcher.lab.LabNotice.started(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.entries.map { it.id })
com.droiddeck.launcher.update.AppUpdates.init(this)
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
com.droiddeck.launcher.core.DownloadSource.init(this)
@@ -319,7 +319,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshDrivers()
return
}
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null &&
if (gpu.family.mali && !DriverPairs.autoEligible(gpu) &&
com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) {
releaseChecking = true
autoStatus = activity.getString(R.string.drivers_checking_latest)
@@ -335,14 +335,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-name").start()
return
}
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) -> " + (DriverPairs.recommendedKey(gpu, emptyList()) ?: "no pair"))
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null) {
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) eligible=${DriverPairs.autoEligible(gpu)}")
if (gpu.family.mali && !DriverPairs.autoEligible(gpu)) {
// No PanVK build covers this Mali (e.g. the G1 series, arch v14): the phone's own driver.
autoStatus = useMaliFallback(null)
refreshDrivers()
return
}
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
if (!DriverPairs.autoEligible(gpu)) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
return
}
@@ -372,7 +372,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
// RADV is not published right now: the Xclipse falls back to the system route.
SessionPrefs.ensurePowerVrAutoDrivers(activity)
if (gpu.name.contains("Xclipse", ignoreCase = true) && DriverPairs.xclipseNeedsUpstream(gpu.name)) {
if (!SessionState.running) SessionPrefs.ensurePowerVrAutoDrivers(activity, powerVr = true, autoOwnedOnly = true)
} else {
SessionPrefs.ensurePowerVrAutoDrivers(activity)
}
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
refreshDrivers()
}
@@ -99,6 +99,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
this, ui,
idle = { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null },
onInstalled = { if (!OfflineMode.enabled(this)) components.checkComponentUpdates(force = false) },
onRemoved = { components.refreshComponents() },
)
private var installed by mutableStateOf<String?>(null)
@@ -180,10 +181,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var fsyncFirst by mutableStateOf(false)
private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true)
private var ramCapMb by mutableStateOf(0)
private var zramClient by mutableStateOf(true)
private var zramIdle by mutableStateOf(true)
private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
@@ -208,8 +205,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var animationsEnabled by mutableStateOf(true)
private var lowStorageWarning by mutableStateOf(true)
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
private var gameStoresEnabled by mutableStateOf(true)
private var soundtracksEnabled by mutableStateOf(true)
private var soundtracksIngame by mutableStateOf(false)
private var soundtracks by mutableStateOf<List<Library.SteamGame>>(emptyList())
private var soundtracksLoaded by mutableStateOf(false)
@@ -281,6 +276,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) }
}
private val pickExperimentalProton = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { zip ->
protons.installExperimental { progress -> com.droiddeck.launcher.session.ExperimentalProtons.installFromFile(this, zip, progress) }
}
}
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
@@ -875,7 +875,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
}, "components-restore").start()
}
private var pendingGameLink: String? = null
private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null
private var gameLinkReading = false
private var gameLinkTried = false
private var gameSyncFolder by mutableStateOf<String?>(null)
@@ -911,6 +911,16 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun readGameIntent(request: Intent) {
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
request.data?.takeIf { it.scheme == "droiddeck" && it.host == "settings" }?.let { uri ->
val section = uri.pathSegments.firstOrNull()
navRequest = if (section in setOf("storage", "sync", "downloads")) section
else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key
request.data = null
gameLinkReading = false
pendingGameLink = null
syncDualPanel()
return
}
if (navRequest == com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS) {
homeAppSelected = HomeApp.isHomeScreenEnabled(this) && HomeApp.isDefault(this)
if (!homeAppSelected) navRequest = null
@@ -927,7 +937,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
val soundtrackId = com.droiddeck.launcher.frontend.SoundtrackShortcuts.read(request)
if (soundtrackId != null) {
soundtrackLaunch = true
navRequest = if (SessionPrefs.soundtracksEnabled(this)) "sound:$soundtrackId" else "app:$soundtrackId"
navRequest = if ("soundtracks" !in com.droiddeck.launcher.ui.NavTabs.hidden) "sound:$soundtrackId" else "app:$soundtrackId"
request.data = null
request.action = Intent.ACTION_MAIN
return
@@ -937,12 +947,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
val copy = Intent(request)
Thread({
val id = GameLaunchIntent.read(this, copy)
val game = GameLaunchIntent.read(this, copy)
ui.post {
if (intent === request && !isDestroyed) {
gameLinkReading = false
pendingGameLink = id
if (id == null) {
pendingGameLink = game
if (game == null) {
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
} else {
@@ -955,13 +965,36 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean {
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) {
val request = gameLaunchRequest.incrementAndGet()
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
if (pkgStage != null) {
onHandled()
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
return
}
val files = game.gameFiles
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
if (startGame(game, returnHome, onHandled)) onSettled()
return
}
Thread({
val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files)
ui.post {
when {
request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled()
refused -> {
onHandled()
android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show()
onSettled()
}
startGame(game, returnHome, onHandled) -> onSettled()
}
}
}, "xbox-app-model").start()
}
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean {
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
onHandled()
if (SessionState.running) {
@@ -1169,26 +1202,28 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) {
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
val id = pendingGameLink ?: return
if (!scanned && games.none { it.gameIdString == id }) return
val request = pendingGameLink ?: return
val game = request.find(games, byTitle = scanned)
if (!scanned && game == null) return
gameLinkTried = true
ui.postDelayed({
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
}, LINK_PANEL_MS)
val game = games.firstOrNull { it.gameIdString == id }
if (game == null) {
val link = intent
fun consume() {
if (intent !== link || pendingGameLink !== request) return
pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
} else if (launchGame(game, returnHome = true)) {
pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
link.data = null
link.action = Intent.ACTION_MAIN
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
}
if (game == null) {
consume()
syncDualPanel()
android.widget.Toast.makeText(this,
if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing,
android.widget.Toast.LENGTH_LONG).show()
} else launchGame(game, returnHome = true, onSettled = ::consume)
}
private fun chooseGameShortcut(game: Library.SteamGame) {
@@ -1235,8 +1270,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
lowStorageWarning = SessionPrefs.lowStorageWarning(this)
LauncherIcon.repair(this, intent?.component)
launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
soundtracksEnabled = SessionPrefs.soundtracksEnabled(this)
soundtracksIngame = SessionPrefs.soundtracksIngame(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
storesShowMature = SessionPrefs.storesShowMature(this)
@@ -1249,6 +1282,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
androidx.compose.runtime.LaunchedEffect(prootPack) {
if (prootPack == com.droiddeck.launcher.core.AddonPack.State.Ready && installed == null) refresh()
}
val appsTabShown = "android-apps" !in com.droiddeck.launcher.ui.NavTabs.hidden
androidx.compose.runtime.LaunchedEffect(appsTabShown) { if (appsTabShown && androidApps.isEmpty()) refreshAndroidApps() }
DroidDeckTheme(theme, appScale = appScale) {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) {
if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog(
@@ -1332,8 +1367,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
animationsEnabled = animationsEnabled,
lowStorageWarning = lowStorageWarning,
launcherIcon = launcherIcon,
gameStoresEnabled = gameStoresEnabled,
soundtracksEnabled = soundtracksEnabled,
soundtracksEnabled = "soundtracks" !in com.droiddeck.launcher.ui.NavTabs.hidden,
soundtracksIngame = soundtracksIngame,
soundtracks = soundtracks,
soundtracksLoaded = soundtracksLoaded,
@@ -1483,7 +1517,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onComponents = { focusContent -> openComponents(focusContent) },
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(this@FrontEndActivity, sg) } },
onAddonImport = { sg, target -> importAddons(sg.name, target) },
onAddonDelete = { target, name ->
saveAction(getString(R.string.main_addons_deleting, name)) {
@@ -1491,8 +1525,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
getString(R.string.main_addons_deleted, name)
}
},
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(this@FrontEndActivity, sg) } },
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
performancePanel = { PerformanceHost(embedded = true) },
onRoms = { showRoms = true },
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
onBrowseFiles = { dir ->
@@ -1608,8 +1643,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
offline = OfflineMode.enabled(this)
},
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
onSoundtracksEnabled = { on -> SessionPrefs.setSoundtracksEnabled(this, on); soundtracksEnabled = on },
onSoundtracksIngame = { on ->
SessionPrefs.setSoundtracksIngame(this, on)
soundtracksIngame = on
@@ -1908,6 +1941,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
gameLaunchRequest.incrementAndGet()
if (intent.action == SteamIntegration.ACTION_SETUP) {
gameLinkReading = false
pendingGameLink = null
@@ -2200,13 +2234,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
private fun refreshAndroidApps() {
if (!homeAppSelected) {
if (!homeAppSelected && "android-apps" in com.droiddeck.launcher.ui.NavTabs.hidden) {
++androidAppsListing
androidApps = emptyList()
return
}
val seq = ++androidAppsListing
HomePins.refresh(this)
if (homeAppSelected) HomePins.refresh(this)
Thread({
val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList())
ui.post { if (seq == androidAppsListing) androidApps = apps }
@@ -2401,13 +2435,20 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
),
protons = com.droiddeck.launcher.ui.ProtonsState(
rows = protons.protonRows, busyId = protons.protonBusyId, stage = protons.protonStage, percent = protons.protonPercent,
runtimeReady = ready && !busy, sessionRunning = SessionState.running,
runtimeReady = ready && !busy, sessionRunning = SessionState.running, experimental = protons.experimentalDirs,
experimentalReleases = protons.experimentalReleases,
),
protonActions = com.droiddeck.launcher.ui.ProtonsActions(
onInstall = { id -> protons.installProton(id) },
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
onRemove = { id, dir -> protons.removeProton(id, dir) },
onRemoveOlder = { id -> protons.removeProton(id, older = true) },
onExperimentalFile = {
pickExperimentalProton.launch(InAppFilePicker.buildIntent(this, EXPERIMENTAL_PROTON_EXT, getString(R.string.xproton_install_file),
android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path))
},
onExperimentalRelease = { release -> protons.installExperimentalRelease(release) },
onRemoveExperimental = { dir -> protons.removeExperimental(dir) },
),
protonOptions = {
com.droiddeck.launcher.ui.ProtonOptions(
@@ -2704,7 +2745,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
@Composable
private fun PerformanceHost() {
private fun PerformanceHost(embedded: Boolean = false) {
if (embedded) androidx.compose.runtime.LaunchedEffect(Unit) { refreshCores() }
PerformancePage(
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, paceCores = paceCores,
@@ -2714,10 +2756,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient, zramIdle = zramIdle,
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
@@ -2732,10 +2770,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
onZramIdle = { on -> SessionPrefs.setZramIdle(this, on); zramIdle = on },
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
@@ -2750,6 +2784,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.setGameCpus(this, CpuCores.format(gameCores))
},
onDismiss = { showPerformance = false },
embedded = embedded,
)
}
@@ -3033,10 +3068,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = SessionPrefs.fsyncFirst(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this)
ramCapMb = SessionPrefs.ramCapMb(this)
zramClient = SessionPrefs.zramClient(this)
zramIdle = SessionPrefs.zramIdle(this)
vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
@@ -3093,6 +3124,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
installed = LinuxRuntimeInstaller.installedVersion(this)
ready = LinuxRuntime.isInstalled(this)
vkBridge = SessionPrefs.vkBridge(this)
venus = SessionPrefs.venus(this)
venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
@@ -3299,7 +3332,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.agent.AgentTab.load(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.NavTabs.load(this)
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
}
@@ -3384,6 +3417,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val ZIP_EXT = listOf("zip")
private val EXPERIMENTAL_PROTON_EXT = listOf("zip", "7z", "tar", "gz", "xz", "zst", "bz2", "tgz", "txz", "tbz2", "tzst")
private val WCP_EXT = listOf("wcp")
}
}
@@ -7,6 +7,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
@@ -19,6 +20,7 @@ internal class ProtonMenu(
private val activity: android.app.Activity,
private val ui: Handler,
private val onInstalled: () -> Unit = {},
private val onRemoved: () -> Unit = {},
private val idle: () -> Boolean = { true },
) {
private object Operation {
@@ -27,13 +29,23 @@ internal class ProtonMenu(
val stage = mutableStateOf<String?>(null)
val percent = mutableIntStateOf(-1)
val problem = mutableStateOf<String?>(null)
val experimental = mutableStateOf<List<String>>(emptyList())
val experimentalReleases = mutableStateOf<List<ExperimentalProtons.Release>>(emptyList())
var fetchedReleases = emptyList<ExperimentalProtons.Release>()
val checking = java.util.concurrent.atomic.AtomicBoolean(false)
}
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)
var experimentalDirs by Operation.experimental
var experimentalReleases by Operation.experimentalReleases
companion object {
const val EXPERIMENTAL = "experimental"
}
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
@@ -86,21 +98,80 @@ internal class ProtonMenu(
}, "remove-proton-$id").start()
}
fun installExperimental(work: ((String, Int) -> Unit) -> String?) {
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
protonBusyId = EXPERIMENTAL
protonProblem = null
protonStage = activity.getString(R.string.store_starting)
protonPercent = -1
Thread({
val problem = runCatching {
work { label, value -> ui.post { protonStage = label; protonPercent = value } }
}.getOrElse { it.message ?: it.javaClass.simpleName }
ui.post {
protonProblem = problem
protonBusyId = null
protonStage = null
protonPercent = -1
refreshProtons()
android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.xproton_installed), android.widget.Toast.LENGTH_LONG).show()
if (problem == null) onInstalled()
}
}, "install-proton-experimental").start()
}
fun installExperimentalRelease(release: ExperimentalProtons.Release) {
installExperimental { progress -> ExperimentalProtons.installRelease(activity, release, progress) }
}
fun removeExperimental(dir: String) {
if (protonBusyId != null || SessionState.running) return
protonBusyId = EXPERIMENTAL
protonProblem = null
protonStage = activity.getString(R.string.main_removing_named, dir)
protonPercent = -1
Thread({
val removed = runCatching { ExperimentalProtons.remove(activity, dir) }.getOrDefault(false)
ui.post {
protonBusyId = null
protonStage = null
refreshProtons()
if (!removed) android.widget.Toast.makeText(activity, activity.getString(R.string.xproton_remove_failed, dir), android.widget.Toast.LENGTH_LONG).show()
}
}, "remove-proton-experimental").start()
}
private fun refreshExperimental() {
val installed = ExperimentalProtons.installed(activity)
experimentalDirs = installed.map { it.dir }
experimentalReleases = ExperimentalProtons.available(Operation.fetchedReleases, installed)
}
fun refreshProtons() {
protonRows = ProtonExtras.tools.map {
refreshExperimental()
protonRows = ProtonExtras.offered(activity).map {
val all = ProtonExtras.installedAll(activity, it)
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
}
}
fun checkUpdates(force: Boolean = false) {
if (!checking.compareAndSet(false, true)) return
if (!Operation.checking.compareAndSet(false, true)) return
Thread({
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
ui.post {
if (asked) refreshProtons()
val asked = runCatching { latestCheck(force) }.getOrDefault(false)
val experimental = runCatching { experimentalRefresh() }.getOrNull()
val published = ui.post {
try {
val before = experimentalDirs
Operation.fetchedReleases = experimental ?: emptyList()
if (asked) refreshProtons() else refreshExperimental()
if (!experimentalDirs.containsAll(before)) onRemoved()
} finally {
Operation.checking.set(false)
}
ensureAutoUpdates()
}
if (!published) Operation.checking.set(false)
}, "proton-updates").start()
}
File diff suppressed because it is too large. Load diff
@@ -76,6 +76,9 @@ class AgentBridgeProvider : ContentProvider() {
"stop" -> stop(context)
"resume" -> resume(context)
"launch" -> launch(context, request)
"library" -> AgentStores.library(context, request)
"xodus" -> AgentStores.xodus(context, request)
"cloud" -> AgentStores.cloud(context, request)
"focus" -> guest(context, JSONObject().put("kind", "focus"), 15_000)
"quit" -> guest(context, JSONObject().put("kind", "quit").put("appId", request.opt("appId"))
.put("timeout", request.optDouble("timeout", 15.0)), timeoutMs(request, 15.0, 30_000))
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.agent
import android.content.Context
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
/** The text typed in the Agent tab and not yet sent, kept across leaving the tab and restarts. */
object AgentDraft {
private const val KEY = "draft"
private var state: MutableState<String>? = null
fun state(context: Context): MutableState<String> = state ?: run {
val prefs = AgentHost.prefs(context.applicationContext)
val backing = mutableStateOf(prefs.getString(KEY, "") ?: "")
object : MutableState<String> {
override var value: String
get() = backing.value
set(text) {
if (text == backing.value) return
backing.value = text
prefs.edit().apply { if (text.isEmpty()) remove(KEY) else putString(KEY, text) }.apply()
}
override fun component1() = value
override fun component2(): (String) -> Unit = { value = it }
}.also { state = it }
}
}
@@ -58,7 +58,8 @@ object AgentEnv {
fun override(context: Context, name: String): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context)
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
if (name == "libblfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) {
if (name == LEGACY_FAST_PATH) throw AgentException("INVALID_NAME", "The fast-path library is now $FAST_PATH")
if (name == "libddfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) {
throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library")
}
val source = File(inbox(context), name)
@@ -73,7 +74,7 @@ object AgentEnv {
staged.delete()
throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
}
if (name == "libblfastpath.so" && !arm64SharedLibrary(staged)) {
if (name == "libddfastpath.so" && !arm64SharedLibrary(staged)) {
staged.delete()
throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library")
}
@@ -86,7 +87,7 @@ object AgentEnv {
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
save(context, state)
state.put("installed", "$GUEST_BIN/$name")
if (name == "libblfastpath.so") {
if (name == "libddfastpath.so") {
val digest = MessageDigest.getInstance("SHA-256")
target.inputStream().use { input ->
val buffer = ByteArray(65536)
@@ -103,10 +104,10 @@ object AgentEnv {
fun fastPathLibrary(context: Context): String = synchronized(lock) {
if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY
if ("libblfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY
val file = File(bin(context), "libblfastpath.so")
if ("libddfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY
val file = File(bin(context), "libddfastpath.so")
if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY
"$GUEST_BIN/libblfastpath.so"
"$GUEST_BIN/libddfastpath.so"
}
private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input ->
@@ -129,13 +130,18 @@ object AgentEnv {
}
val state = load(context)
val active = strings(state.optJSONArray("pending"))
val overrides = strings(state.optJSONArray("pendingOverrides"))
val queued = strings(state.optJSONArray("pendingOverrides"))
val legacy = File(bin(context), LEGACY_FAST_PATH)
val stranded = FAST_PATH in queued && legacy.isFile && !File(bin(context), FAST_PATH).exists() &&
!legacy.renameTo(File(bin(context), FAST_PATH))
if (stranded) Log.w(TAG, "could not rename the queued $LEGACY_FAST_PATH; it stays queued for the next session")
val overrides = if (stranded) queued - FAST_PATH else queued
bin(context).listFiles()
?.filter { it.name !in overrides }?.forEach { it.delete() }
?.filter { it.name !in overrides && !(stranded && it.name == LEGACY_FAST_PATH) }?.forEach { it.delete() }
val lines = strings(state.optJSONArray("persistent")) + active
val withPath = if (overrides.none { it != "libblfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
val withPath = if (overrides.none { it != "libddfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
state.put("active", JSONArray(active)).put("pending", JSONArray())
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray(if (stranded) listOf(FAST_PATH) else emptyList()))
save(context, state)
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
withPath
@@ -158,6 +164,9 @@ object AgentEnv {
save(context, state)
}
private const val FAST_PATH = "libddfastpath.so"
private const val LEGACY_FAST_PATH = "libblfastpath.so"
private fun pathOf(lines: List<String>) =
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: LinuxRuntime.GUEST_PATH
@@ -186,6 +195,9 @@ object AgentEnv {
for (key in listOf("pending", "active", "persistent", "pendingOverrides", "activeOverrides")) {
if (!state.has(key)) state.put(key, JSONArray())
}
for (key in listOf("pendingOverrides", "activeOverrides")) {
state.put(key, JSONArray(strings(state.optJSONArray(key)).map { if (it == LEGACY_FAST_PATH) FAST_PATH else it }.distinct()))
}
return state
}
@@ -1,11 +1,13 @@
package com.droiddeck.launcher.agent
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.R
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/** One coding agent CLI in the Linux userland, run one process per turn (or kept open, see [input]). */
/** One coding agent CLI in the Linux userland, run as a process that takes its turns over stdin (see [AgentProtocol]). */
interface AgentHarness {
val id: String
val name: String
@@ -19,22 +21,36 @@ interface AgentHarness {
val signedIn: List<String>
/** A guest command that signs in through $BROWSER. */
val signIn: List<String>
/**
* APIs the CLI reaches with a key pasted into DroidDeck, for a CLI whose own sign-in is a terminal
* prompt; empty when it signs in through [signIn].
*/
val providers: List<Provider> get() = emptyList()
/** Ids of the [providers] with a key saved under [rootfs]. */
fun keys(rootfs: File): Set<String> = emptySet()
/**
* Saves [key] for [provider]. A [Provider.custom] one also takes the [endpoint] it is served from, and
* [get] fetches a URL from the userland, with the key as a bearer token when it is not null.
*/
fun saveKey(rootfs: File, provider: Provider, key: String, endpoint: String? = null, get: (String, String?) -> String = { url, _ -> error("Cannot reach $url") }) {}
fun removeKey(rootfs: File, provider: Provider) {}
/** Whether the CLI has models that need no account; [useFree] then counts as signed in. */
val free: Boolean get() = false
fun useFree(rootfs: File) {}
/** Usage reports the conversation's whole cost rather than the turn's. */
val sessionCost: Boolean get() = false
/** Whether [Options.plan] means anything to this CLI. */
val plans: Boolean
/** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */
val efforts: List<String>
/** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */
fun models(rootfs: File): List<Model>
/** The guest command for one turn; [conversation] is null for the first one. */
/** How the CLI may run its tools, the one that asks before each action first and the default. */
val permissions: List<Permission>
/** The guest command of the process that runs the conversation's turns; [conversation] is null for a new one. */
fun turn(message: String, conversation: String?, options: Options): List<String>
/**
* The line that hands [message] to a [turn] process over stdin, or null when the message is already in the
* command. A process that takes its messages this way stays open between turns, so work it started in the
* background can wake it, as it does in the CLI's own terminal.
*/
fun input(message: String): String? = null
/** One line of the CLI's output, or null when it carries nothing to show. */
fun parse(line: String): AgentEvent?
/** A new reader for one [turn] process; it keeps what that process has said so far. */
fun protocol(): AgentProtocol
/** The folder, under the userland's root, where the CLI loads user skills (`<name>/SKILL.md`). */
val skills: String
/** The CLI's global instructions file under the userland's root, where DroidDeck keeps its rules in a marked block. */
@@ -46,14 +62,45 @@ interface AgentHarness {
data class Model(val id: String, val label: String)
data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null)
/** An API reached with a key; [keyPage] is where the key is made, and a [custom] one is any OpenAI-compatible server. */
data class Provider(val id: String, val name: String, val keyPage: String? = null, val custom: Boolean = false)
/** A permission mode; [id] is DroidDeck's own name for it, which each CLI maps to its flags. */
data class Permission(val id: String, @StringRes val label: Int, @StringRes val hint: Int)
data class Options(
val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null,
val permission: String = ASK, val workdir: String = "/root",
)
companion object {
val all: List<AgentHarness> = listOf(ClaudeCode, Codex)
const val ASK = "ask"
const val EDITS = "edits"
const val AUTO = "auto"
const val DONT_ASK = "dontask"
const val FULL = "full"
val all: List<AgentHarness> = listOf(ClaudeCode, Codex, OpenCode)
fun byId(id: String?): AgentHarness = all.firstOrNull { it.id == id } ?: ClaudeCode
}
}
/** What goes to one CLI process's stdin, and what its output lines mean. */
interface AgentProtocol {
/**
* The lines that start a turn of [message]; [started] is true for a process that has just been started. The
* process stays open between turns, so work it started in the background can wake it.
*/
fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List<String>
/** One line of the process's output, or null when it carries nothing to show. */
fun parse(line: String): AgentEvent?
/** The line that answers [approval]. */
fun answer(approval: AgentHost.Approval, allow: Boolean): String
}
/** The message a CLI tells its model when the user denies a tool call. */
internal const val DENIED = "The user denied this tool call."
/** What one line of output carries: whole entries, or text still being written. */
data class AgentEvent(
val conversation: String? = null,
@@ -70,6 +117,12 @@ data class AgentEvent(
val background: Boolean = false,
/** The error a background turn ended with, if it failed. */
val backgroundError: String? = null,
/** Lines to write to the process's stdin right away, the next step of a request it has answered. */
val reply: List<String> = emptyList(),
/** A tool call that waits for the user to allow it. */
val approval: AgentHost.Approval? = null,
/** The id of an approval the CLI no longer waits for. */
val resolved: String? = null,
)
/** Claude Code: `claude -p` with stream-json input and output, resumed by session id. */
@@ -111,22 +164,54 @@ object ClaudeCode : AgentHarness {
AgentHarness.Model("opus", "Opus"), AgentHarness.Model("sonnet", "Sonnet"), AgentHarness.Model("haiku", "Haiku"),
)
// DroidDeck runs the agent unattended on the user's own device; permission prompts have no one to answer them.
override val permissions = listOf(
AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint),
AgentHarness.Permission(AgentHarness.EDITS, R.string.agent_permission_edits, R.string.agent_permission_edits_hint),
AgentHarness.Permission(AgentHarness.AUTO, R.string.agent_permission_auto, R.string.agent_permission_auto_hint),
AgentHarness.Permission(AgentHarness.DONT_ASK, R.string.agent_permission_dont_ask, R.string.agent_permission_dont_ask_hint),
AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint),
)
private val MODES = mapOf(
AgentHarness.ASK to "manual", AgentHarness.EDITS to "acceptEdits", AgentHarness.AUTO to "auto",
AgentHarness.DONT_ASK to "dontAsk", AgentHarness.FULL to "bypassPermissions",
)
/**
* Prompts reach DroidDeck as can_use_tool requests on stdout (the SDK's stdio prompt tool). Plan mode keeps
* answering none, so a turn that would leave plan mode ends on its plan.
*/
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList {
addAll(listOf(binary, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions"))
val mode = if (options.plan) "plan" else MODES[options.permission] ?: "manual"
addAll(listOf("--permission-mode", mode))
if (mode != "plan" && mode != "bypassPermissions") add("--permission-prompt-tool=stdio")
options.model?.let { addAll(listOf("--model", it)) }
options.effort?.let { addAll(listOf("--effort", it)) }
options.brief?.let { addAll(listOf("--append-system-prompt", it)) }
if (conversation != null) addAll(listOf("--resume", conversation))
}
override fun input(message: String): String? = JSONObject()
fun input(message: String): String = JSONObject()
.put("type", "user")
.put("message", JSONObject().put("role", "user").put("content", JSONArray().put(JSONObject().put("type", "text").put("text", message))))
.toString()
override fun parse(line: String): AgentEvent? {
override fun protocol(): AgentProtocol = object : AgentProtocol {
override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean) = listOf(this@ClaudeCode.input(message))
override fun parse(line: String) = this@ClaudeCode.parse(line)
override fun answer(approval: AgentHost.Approval, allow: Boolean) = this@ClaudeCode.answer(approval, allow)
}
@VisibleForTesting
internal fun answer(approval: AgentHost.Approval, allow: Boolean): String {
val decision = if (allow) JSONObject().put("behavior", "allow").put("updatedInput", runCatching { JSONObject(approval.payload) }.getOrDefault(JSONObject()))
else JSONObject().put("behavior", "deny").put("message", DENIED)
return JSONObject().put("type", "control_response")
.put("response", JSONObject().put("subtype", "success").put("request_id", approval.id).put("response", decision)).toString()
}
fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
// A subagent's messages carry the call that started it; only its tool calls are shown, under that call.
@@ -173,6 +258,13 @@ object ClaudeCode : AgentHarness {
AgentEvent(conversation, results)
}
"rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info")))
"control_request" -> {
val request = o.optJSONObject("request")?.takeIf { it.optString("subtype") == "can_use_tool" } ?: return null
val tool = request.optString("tool_name")
val input = request.optJSONObject("input") ?: JSONObject()
AgentEvent(approval = AgentHost.Approval(o.optString("request_id"), tool, detail(input), fullInput(tool, input), input.toString()))
}
"control_cancel_request" -> AgentEvent(resolved = o.optString("request_id"))
// The CLI starts turns of its own for background tasks (a resumed session first answers the ones the last
// run left behind). Such a result is not the end of the user's turn; the host decides what it ends.
"result" -> {
@@ -255,7 +347,7 @@ object ClaudeCode : AgentHarness {
}.joinToString("\n")
}
/** OpenAI Codex: `codex exec --json`, resumed by thread id. */
/** OpenAI Codex: `codex app-server`, its JSON-RPC protocol over stdio, resumed by thread id. */
object Codex : AgentHarness {
override val id = "codex"
override val name = "Codex"
@@ -281,6 +373,13 @@ object Codex : AgentHarness {
override val plans = false
override val efforts = listOf("low", "medium", "high")
// Codex's sandbox needs Landlock and seccomp, which proot does not provide, so commands run unsandboxed
// and "untrusted" is what makes Codex ask before each one that is not known to be safe.
override val permissions = listOf(
AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint),
AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint),
)
/** Codex keeps the models its account can use in `~/.codex/models_cache.json` once it has run. */
override fun models(rootfs: File): List<AgentHarness.Model> = runCatching {
val o = JSONObject(File(rootfs, "root/.codex/models_cache.json").readText())
@@ -293,108 +392,652 @@ object Codex : AgentHarness {
}
}.getOrDefault(emptyList())
// Codex's own sandbox needs Landlock and seccomp, which proot does not provide.
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList {
addAll(listOf(binary, "exec"))
if (conversation != null) addAll(listOf("resume", conversation))
addAll(listOf("--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check"))
options.model?.let { addAll(listOf("-m", it)) }
options.effort?.let { addAll(listOf("-c", "model_reasoning_effort=\"$it\"")) }
// codex exec has no system prompt option, so a new conversation starts with the brief.
add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message)
}
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = withoutStderr("codex", listOf(binary, "app-server"))
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val item = o.optJSONObject("item")
val id = item?.optString("id").orEmpty()
val entries = when (o.optString("type")) {
"thread.started" -> return AgentEvent(o.optString("thread_id").takeIf { it.isNotEmpty() })
"item.started" -> when (item?.optString("type")) {
"command_execution" -> shellCommand(item.optString("command")).let { listOf(AgentHost.Entry.Used(id, "Shell", firstLine(it), it)) }
"mcp_tool_call" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.optJSONObject("arguments")?.toString(2).orEmpty()))
"web_search" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query")))
else -> emptyList()
}
"item.updated" -> when (item?.optString("type")) {
"todo_list" -> listOf(todoEntry(id, item))
else -> emptyList()
}
"item.completed" -> when (item?.optString("type")) {
"agent_message" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty()
"reasoning" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Thought(it)) }.orEmpty()
"command_execution" -> listOf(AgentHost.Entry.Result(id, item.optString("aggregated_output"),
item.has("exit_code") && !item.isNull("exit_code") && item.optInt("exit_code") != 0))
"mcp_tool_call" -> listOf(AgentHost.Entry.Result(id, item.optJSONObject("result")?.toString(2) ?: item.optJSONObject("error")?.optString("message").orEmpty(),
item.optString("status") == "failed"))
"web_search" -> listOf(AgentHost.Entry.Result(id, "", false))
"file_change" -> listOf(
AgentHost.Entry.Used(id, "Edit", changedFiles(item), changedFiles(item).replace(", ", "\n")),
AgentHost.Entry.Result(id, item.optString("status"), item.optString("status") == "failed"),
)
"todo_list" -> listOf(todoEntry(id, item))
"error" -> listOf(AgentHost.Entry.Said("⚠ " + item.optString("message")))
else -> emptyList()
}
"turn.completed" -> return AgentEvent(
entries = listOf(AgentHost.Entry.Finished(null)),
usage = o.optJSONObject("usage")?.let { AgentHost.Usage(0, 0.0, it.optLong("input_tokens") + it.optLong("cached_input_tokens"), it.optLong("output_tokens")) },
override fun protocol(): AgentProtocol = Protocol()
@VisibleForTesting
internal class Protocol : AgentProtocol {
private var next = 1
private var thread: String? = null
/** The initialize request, the thread/start or thread/resume sent once it succeeds, and the turn that waits for its thread. */
private var initializing = -1
private var initialized = false
private var open: String? = null
private var opening = -1
private var waiting: JSONObject? = null
private var starting = -1
private var turnId = ""
/** Each file change's paths and diffs, from its start; an approval for it names only the item. */
private val changes = mutableMapOf<String, JSONArray>()
private var input = 0L
private var output = 0L
override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List<String> {
val turn = JSONObject()
.put("input", JSONArray().put(JSONObject().put("type", "text").put("text", message).put("text_elements", JSONArray())))
options.model?.let { turn.put("model", it) }
options.effort?.let { turn.put("effort", it) }
val known = thread
if (!started && known != null) return listOf(startTurn(turn.put("threadId", known)))
val params = JSONObject()
.put("approvalPolicy", if (options.permission == AgentHarness.FULL) "never" else "untrusted")
.put("sandbox", "danger-full-access")
options.model?.let { params.put("model", it) }
options.brief?.let { params.put("developerInstructions", it) }
if (conversation != null) params.put("threadId", conversation)
waiting = turn
opening = next++
val request = JSONObject().put("id", opening).put("method", if (conversation != null) "thread/resume" else "thread/start").put("params", params).toString()
// Codex refuses a second initialize on one connection, so a thread that failed to open is asked for again alone.
if (initialized) return listOf(request)
open = request
initializing = next++
return listOf(
JSONObject().put("id", initializing).put("method", "initialize")
.put("params", JSONObject().put("clientInfo", JSONObject().put("name", "droiddeck").put("title", "DroidDeck").put("version", "1"))
.put("capabilities", JSONObject.NULL)).toString(),
)
"turn.failed" -> listOf(AgentHost.Entry.Finished(o.optJSONObject("error")?.optString("message") ?: "turn failed"))
// codex reports a dropped stream it is retrying as an error event, and the turn goes on.
"error" -> o.optString("message").let { message ->
if (message.startsWith("Reconnecting...")) emptyList() else listOf(AgentHost.Entry.Finished(message.ifEmpty { "error" }))
}
else -> emptyList()
}
return if (entries.isEmpty()) null else AgentEvent(entries = entries)
private fun startTurn(params: JSONObject): String {
starting = next++
return JSONObject().put("id", starting).put("method", "turn/start").put("params", params).toString()
}
override fun answer(approval: AgentHost.Approval, allow: Boolean): String =
JSONObject(approval.payload).put("result", JSONObject().put("decision", if (allow) "accept" else "decline")).toString()
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val method = o.optString("method")
if (method.isEmpty()) return response(o)
val params = o.optJSONObject("params") ?: JSONObject()
if (o.has("id")) return request(o.get("id"), method, params)
return notification(method, params)
}
private fun response(o: JSONObject): AgentEvent? {
val id = o.optInt("id", -1)
val error = o.optJSONObject("error")?.optString("message")?.ifEmpty { "error" }
return when (id) {
initializing -> {
if (error != null) return AgentEvent(entries = listOf(AgentHost.Entry.Finished(error)))
initialized = true
val request = open ?: return null
open = null
AgentEvent(reply = listOf(JSONObject().put("method", "initialized").toString(), request))
}
opening -> {
if (error != null) return AgentEvent(entries = listOf(AgentHost.Entry.Finished(error)))
val started = o.optJSONObject("result")?.optJSONObject("thread")?.optString("id")?.takeIf { it.isNotEmpty() } ?: return null
thread = started
val turn = waiting ?: return AgentEvent(started)
waiting = null
AgentEvent(started, reply = listOf(startTurn(turn.put("threadId", started))))
}
starting -> error?.let { AgentEvent(entries = listOf(AgentHost.Entry.Finished(it))) }
else -> null
}
}
private fun request(id: Any, method: String, params: JSONObject): AgentEvent {
val payload = JSONObject().put("id", id).toString()
return when (method) {
"item/commandExecution/requestApproval" -> {
val command = shellCommand(params.optString("command"))
val reason = params.optString("reason").takeIf { it.isNotEmpty() && it != "null" }
AgentEvent(approval = AgentHost.Approval(id.toString(), "Shell", firstLine(command), listOfNotNull(command, reason).joinToString("\n\n"), payload))
}
"item/fileChange/requestApproval" -> {
val list = changes[params.optString("itemId")] ?: JSONArray()
val files = (0 until list.length()).mapNotNull { list.optJSONObject(it) }
AgentEvent(approval = AgentHost.Approval(
id.toString(), "Edit", files.joinToString(", ") { it.optString("path") }.take(400),
files.joinToString("\n\n") { it.optString("path") + "\n" + patchLines(it.optString("diff"), it.optJSONObject("kind")?.optString("type").orEmpty()) }, payload,
))
}
// Everything else asks for something DroidDeck has no screen for; refusing keeps the turn going.
else -> AgentEvent(reply = listOf(JSONObject(payload)
.put("error", JSONObject().put("code", -32601).put("message", "DroidDeck cannot answer $method")).toString()))
}
}
private fun notification(method: String, params: JSONObject): AgentEvent? {
val item = params.optJSONObject("item")
val id = item?.optString("id").orEmpty()
val entries: List<AgentHost.Entry> = when (method) {
"thread/started" -> return params.optJSONObject("thread")?.optString("id")?.takeIf { it.isNotEmpty() }?.let { AgentEvent(it) }
"turn/started" -> {
turnId = params.optJSONObject("turn")?.optString("id").orEmpty()
input = 0
output = 0
return null
}
"item/agentMessage/delta" -> return AgentEvent(text = params.optString("delta"))
"item/reasoning/summaryTextDelta", "item/reasoning/textDelta" -> return AgentEvent(thinking = params.optString("delta"))
"item/started" -> when (item?.optString("type")) {
"commandExecution" -> shellCommand(item.optString("command")).let { listOf(AgentHost.Entry.Used(id, "Shell", firstLine(it), it)) }
"mcpToolCall" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.opt("arguments")?.let(::pretty).orEmpty()))
"webSearch" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query")))
"fileChange" -> {
val list = item.optJSONArray("changes") ?: JSONArray()
changes[id] = list
fileEntries(id, list)
}
else -> emptyList()
}
"item/completed" -> when (item?.optString("type")) {
"agentMessage" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty()
"reasoning" -> {
val parts = (strings(item.optJSONArray("summary")) + strings(item.optJSONArray("content"))).joinToString("\n\n").trim()
if (parts.isEmpty()) emptyList() else listOf(AgentHost.Entry.Thought(parts))
}
"commandExecution" -> {
val status = item.optString("status")
val exit = if (item.isNull("exitCode")) 0 else item.optInt("exitCode")
val out = item.optString("aggregatedOutput").takeUnless { item.isNull("aggregatedOutput") }.orEmpty()
listOf(AgentHost.Entry.Result(id, if (status == "declined") out.ifEmpty { DENIED } else out, status != "completed" || exit != 0))
}
"mcpToolCall" -> listOf(AgentHost.Entry.Result(id,
item.optJSONObject("result")?.let(::pretty) ?: item.optJSONObject("error")?.optString("message").orEmpty(), item.optString("status") == "failed"))
"webSearch" -> listOf(AgentHost.Entry.Result(id, "", false))
"fileChange" -> {
val list = item.optJSONArray("changes") ?: changes[id] ?: JSONArray()
changes.remove(id)
val failed = item.optString("status") != "completed"
(0 until list.length()).map { AgentHost.Entry.Result("$id#$it", if (failed) item.optString("status") else "", failed) }
}
else -> emptyList()
}
"turn/plan/updated" -> listOf(plan(params.optJSONArray("plan")))
"thread/tokenUsage/updated" -> {
val usage = params.optJSONObject("tokenUsage") ?: return null
val last = usage.optJSONObject("last")
input += last?.optLong("inputTokens") ?: 0
output += last?.optLong("outputTokens") ?: 0
return AgentEvent(
context = last?.optLong("totalTokens")?.takeIf { it > 0 },
window = usage.optLong("modelContextWindow").takeIf { it > 0 },
)
}
"account/rateLimits/updated" -> return rateLimits(params.optJSONObject("rateLimits"))?.let { AgentEvent(limits = it) }
"serverRequest/resolved" -> return AgentEvent(resolved = params.opt("requestId")?.toString())
"turn/completed" -> {
val turn = params.optJSONObject("turn") ?: JSONObject()
val error = when (turn.optString("status")) {
"failed" -> turn.optJSONObject("error")?.optString("message")?.ifEmpty { null } ?: "turn failed"
else -> null
}
return AgentEvent(
entries = listOf(AgentHost.Entry.Finished(error)),
usage = AgentHost.Usage(if (turn.isNull("durationMs")) 0 else turn.optLong("durationMs"), 0.0, input, output),
)
}
else -> emptyList()
}
return if (entries.isEmpty()) null else AgentEvent(entries = entries)
}
private fun plan(steps: JSONArray?): AgentHost.Entry.Used {
val text = (0 until (steps?.length() ?: 0)).mapNotNull { i ->
val step = steps?.optJSONObject(i) ?: return@mapNotNull null
val mark = when (step.optString("status")) { "completed" -> "[x]"; "inProgress" -> "[~]"; else -> "[ ]" }
"$mark ${step.optString("step")}"
}.joinToString("\n")
return AgentHost.Entry.Used("$turnId-todo", "TodoWrite", "", text, output = "")
}
}
private const val TOKEN_COUNT = "\"payload\":{\"type\":\"token_count\""
/** Codex prints no limits with --json; its session log, named after the thread, has a token_count event each step. */
override fun usage(rootfs: File, conversation: String?): AgentEvent? {
conversation ?: return null
val log = File(rootfs, "root/.codex/sessions").walkBottomUp().filter { it.isFile && it.name.endsWith("-$conversation.jsonl") }
.maxByOrNull { it.lastModified() } ?: return null
val last = runCatching { log.readLines().lastOrNull { it.contains(TOKEN_COUNT) } }.getOrNull() ?: return null
return tokenCount(last)
/** One Edit per changed file: its path, then the diff as lines led by ' ', '-' or '+'. */
private fun fileEntries(id: String, changes: JSONArray) = (0 until changes.length()).mapNotNull { i ->
val change = changes.optJSONObject(i) ?: return@mapNotNull null
val path = change.optString("path")
AgentHost.Entry.Used("$id#$i", "Edit", path, path + "\n" + patchLines(change.optString("diff"), change.optJSONObject("kind")?.optString("type").orEmpty()))
}
@VisibleForTesting
internal fun tokenCount(line: String): AgentEvent? {
val payload = runCatching { JSONObject(line).optJSONObject("payload") }.getOrNull()?.takeIf { it.optString("type") == "token_count" } ?: return null
val info = payload.optJSONObject("info")
val rates = payload.optJSONObject("rate_limits")
val limits = listOf("primary", "secondary").mapNotNull { key ->
val w = rates?.optJSONObject(key) ?: return@mapNotNull null
AgentHost.Limit(w.optInt("window_minutes"), w.optDouble("used_percent", 0.0).toInt(), w.optLong("resets_at"))
internal fun rateLimits(snapshot: JSONObject?): List<AgentHost.Limit>? {
snapshot ?: return null
return listOf("primary", "secondary").mapNotNull { key ->
val w = snapshot.optJSONObject(key) ?: return@mapNotNull null
AgentHost.Limit(w.optInt("windowDurationMins"), w.optDouble("usedPercent", 0.0).toInt(), w.optLong("resetsAt"))
}.takeIf { it.isNotEmpty() }
}
private fun strings(list: JSONArray?) = (0 until (list?.length() ?: 0)).mapNotNull { list?.optString(it)?.takeIf { s -> s.isNotBlank() } }
private fun pretty(value: Any): String = when (value) {
is JSONObject -> value.toString(2)
is JSONArray -> value.toString(2)
JSONObject.NULL -> ""
else -> value.toString()
}
}
/** OpenCode: `opencode acp`, the Agent Client Protocol over stdio, resumed by session id. */
object OpenCode : AgentHarness {
override val id = "opencode"
override val name = "OpenCode"
override val binary = "/root/.opencode/bin/opencode"
override val skills = "root/.config/opencode/skills"
override val instructions = "root/.config/opencode/AGENTS.md"
override val install = "curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path"
private const val AUTH = "root/.local/share/opencode/auth.json"
private const val CONFIG = "root/.config/opencode/opencode.json"
private const val FREE = "root/.config/opencode/.droiddeck-free"
private const val MODELS = "root/.cache/droiddeck/opencode-models"
/** The provider id DroidDeck gives a server the user names, in opencode's config and auth. */
private const val CUSTOM = "droiddeck"
// `opencode models` lists only what the saved keys reach, so the check that runs it keeps the model list current.
override val signedIn = listOf("sh", "-c",
"mkdir -p /${MODELS.substringBeforeLast('/')}; $binary models --verbose > /$MODELS.$$ 2>/dev/null && mv -f /$MODELS.$$ /$MODELS; rm -f /$MODELS.$$; " +
"grep -q '\"type\"' /$AUTH 2>/dev/null || [ -e /$FREE ] || grep -q '\"$CUSTOM\"' /$CONFIG 2>/dev/null")
// Ids are opencode's own (models.dev), so a saved key is what `opencode auth login` would save for that provider.
override val providers = listOf(
AgentHarness.Provider("opencode", "OpenCode Zen", "https://opencode.ai/auth"),
AgentHarness.Provider("ollama-cloud", "Ollama Cloud", "https://ollama.com/settings/keys"),
AgentHarness.Provider("openrouter", "OpenRouter", "https://openrouter.ai/settings/keys"),
AgentHarness.Provider("openai", "OpenAI", "https://platform.openai.com/api-keys"),
AgentHarness.Provider("anthropic", "Anthropic", "https://console.anthropic.com/settings/keys"),
AgentHarness.Provider("google", "Gemini", "https://aistudio.google.com/apikey"),
AgentHarness.Provider(CUSTOM, "Other server", custom = true),
)
override val signIn = listOf("/root/.local/bin/android-open", providers.first().keyPage!!)
override val free = true
override val plans = true
override val efforts = listOf("low", "medium", "high")
override fun keys(rootfs: File): Set<String> {
val auth = runCatching { JSONObject(File(rootfs, AUTH).readText()) }.getOrNull()
val custom = runCatching { JSONObject(File(rootfs, CONFIG).readText()).optJSONObject("provider")?.has(CUSTOM) }.getOrNull() == true
return providers.filter { auth?.has(it.id) == true || (it.custom && custom) }.map { it.id }.toSet()
}
/**
* Saves the key as opencode's own `auth login` would. A custom server also gets a provider in
* opencode's config with the models its `/models` lists, since opencode does not list them itself.
*/
override fun saveKey(rootfs: File, provider: AgentHarness.Provider, key: String, endpoint: String?, get: (String, String?) -> String) {
val token = key.trim().takeIf { it.isNotEmpty() }
// Both files are read before either is written, so one that cannot be read changes nothing.
val authFile = File(rootfs, AUTH)
val auth = readJson(authFile)
if (token != null) auth.put(provider.id, JSONObject().put("type", "api").put("key", token)) else auth.remove(provider.id)
if (!provider.custom) return writeJson(authFile, auth, private = true)
val base = endpoint(endpoint ?: "")
val configFile = File(rootfs, CONFIG)
val before = configFile.takeIf { it.exists() }?.readText()
val config = readJson(configFile)
val models = modelIds(get("$base/models", token))
check(models.isNotEmpty()) { "No models at $base" }
if (!config.has("\$schema")) config.put("\$schema", "https://opencode.ai/config.json")
val all = config.optJSONObject("provider") ?: JSONObject().also { config.put("provider", it) }
all.put(CUSTOM, JSONObject()
.put("npm", "@ai-sdk/openai-compatible")
.put("name", runCatching { java.net.URI(base).host }.getOrNull() ?: provider.name)
.put("options", JSONObject().put("baseURL", base))
.put("models", JSONObject().apply { models.forEach { put(it, JSONObject().put("name", it)) } }))
writeJson(configFile, config)
try {
writeJson(authFile, auth, private = true)
} catch (e: Exception) {
val undone = runCatching {
if (before != null) writeFile(configFile, before) else java.nio.file.Files.deleteIfExists(configFile.toPath())
}
// First, since the setup row shows two lines of the message.
undone.exceptionOrNull()?.let { throw IllegalStateException("The server config could not be put back (${it.message}): ${e.message}", e) }
throw e
}
return AgentEvent(
context = info?.optJSONObject("last_token_usage")?.optLong("total_tokens")?.takeIf { it > 0 },
window = info?.optLong("model_context_window")?.takeIf { it > 0 },
limits = limits.takeIf { it.isNotEmpty() },
)
}
private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used {
val items = item.optJSONArray("items") ?: JSONArray()
val text = (0 until items.length()).mapNotNull { i ->
val todo = items.optJSONObject(i) ?: return@mapNotNull null
"${if (todo.optBoolean("completed")) "[x]" else "[ ]"} ${todo.optString("text")}"
}.joinToString("\n")
return AgentHost.Entry.Used("$id-todo", "TodoWrite", "", text, output = "")
override fun removeKey(rootfs: File, provider: AgentHarness.Provider) {
if (File(rootfs, AUTH).exists()) editJson(File(rootfs, AUTH), private = true) { it.remove(provider.id) }
if (provider.custom && File(rootfs, CONFIG).exists()) editJson(File(rootfs, CONFIG)) { it.optJSONObject("provider")?.remove(CUSTOM) }
}
private fun changedFiles(item: JSONObject): String {
val changes = item.optJSONArray("changes") ?: return ""
return (0 until changes.length()).mapNotNull { changes.optJSONObject(it)?.optString("path") }.joinToString(", ").take(400)
/** A server address as typed, made into the OpenAI-compatible base URL opencode calls. */
@VisibleForTesting
internal fun endpoint(typed: String): String {
val url = typed.trim().trimEnd('/').let { if ("://" in it) it else "http://$it" }
require(url.substringAfter("://").isNotEmpty()) { "No server address" }
return if (url.substringAfter("://").contains('/')) url else "$url/v1"
}
@VisibleForTesting
internal fun modelIds(body: String): List<String> {
// The userland can print its own warnings ahead of the response.
val json = body.substring(body.indexOf('{').coerceAtLeast(0), body.lastIndexOf('}') + 1)
val data = runCatching { JSONObject(json).optJSONArray("data") }.getOrNull() ?: return emptyList()
return (0 until data.length()).mapNotNull { data.optJSONObject(it)?.optString("id")?.takeIf { id -> id.isNotEmpty() } }.distinct()
}
// A file that cannot be read holds the user's other providers too, so it is never replaced.
private fun readJson(file: File) = if (file.exists()) JSONObject(file.readText()) else JSONObject()
private fun editJson(file: File, private: Boolean = false, edit: (JSONObject) -> Unit) =
writeJson(file, readJson(file).also(edit), private)
/** Writes beside [file] and moves it into place, so a write that stops partway leaves the old file. */
private fun writeJson(file: File, json: JSONObject, private: Boolean = false) = writeFile(file, json.toString(2) + "\n", private)
private fun writeFile(file: File, text: String, private: Boolean = false) {
file.parentFile?.mkdirs()
val temp = File(file.parentFile, ".${file.name}.tmp")
try {
temp.writeText(text)
if (private) {
temp.setReadable(false, false)
temp.setReadable(true, true)
}
java.nio.file.Files.move(temp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING, java.nio.file.StandardCopyOption.ATOMIC_MOVE)
} finally {
temp.delete()
}
}
override fun useFree(rootfs: File) {
File(rootfs, FREE).apply { parentFile?.mkdirs() }.writeText("Free OpenCode Zen models, chosen in DroidDeck's agent setup.\n")
}
private class Listed(val modified: Long, val models: List<AgentHarness.Model>, val windows: Map<String, Long>)
@Volatile private var listed: Listed? = null
private fun listed(rootfs: File): Listed? {
val file = File(rootfs, MODELS)
val modified = file.lastModified().takeIf { it > 0 } ?: return null
listed?.takeIf { it.modified == modified }?.let { return it }
return runCatching { listModels(file.readText()) }.getOrNull()?.let { (models, windows) -> Listed(modified, models, windows) }?.also { listed = it }
}
override fun models(rootfs: File) = listed(rootfs)?.models.orEmpty()
/** `opencode models --verbose` prints each model's id on a line of its own, then its details as JSON. */
@VisibleForTesting
internal fun listModels(output: String): Pair<List<AgentHarness.Model>, Map<String, Long>> {
val models = mutableListOf<AgentHarness.Model>()
val windows = mutableMapOf<String, Long>()
var id: String? = null
val json = StringBuilder()
for (line in output.lineSequence()) {
val current = id
if (current == null) {
if (MODEL_ID.matches(line)) id = line.trim()
continue
}
json.appendLine(line)
if (line != "}") continue
runCatching { JSONObject(json.toString()) }.getOrNull()?.takeIf { it.optString("status") != "deprecated" }?.let { o ->
val provider = o.optString("providerID")
val label = o.optString("name").ifEmpty { current }
val source = if (provider == "opencode" || provider == CUSTOM) "" else providers.firstOrNull { it.id == provider }?.name ?: provider
models += AgentHarness.Model(current, if (source.isEmpty()) label else "$label · $source")
o.optJSONObject("limit")?.optLong("context")?.takeIf { it > 0 }?.let { windows[current] = it }
}
id = null
json.clear()
}
return models to windows
}
private val MODEL_ID = Regex("""^[\w.-]+/\S+$""")
override val permissions = listOf(
AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint),
AgentHarness.Permission(AgentHarness.EDITS, R.string.agent_permission_edits, R.string.agent_permission_edits_hint),
AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint),
)
/**
* Rules merged over the user's opencode config. OpenCode applies the last rule that matches in key order, so the
* asking modes name each permission rather than "*", which could land after a rule of the user's and override it.
*/
@VisibleForTesting
internal fun rules(permission: String): JSONObject {
val asks = listOf("bash", "webfetch", "websearch", "codesearch")
return when (permission) {
AgentHarness.FULL -> JSONObject().put("*", "allow")
AgentHarness.EDITS -> JSONObject().put("edit", "allow").apply { asks.forEach { put(it, "ask") } }
else -> JSONObject().put("edit", "ask").apply { asks.forEach { put(it, "ask") } }
}
}
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) =
withoutStderr("opencode", listOf("/usr/bin/env", "OPENCODE_PERMISSION=${rules(options.permission)}", binary, "acp"))
/** The conversation's cost so far; DroidDeck takes the turn's share from what its chat has recorded. */
override val sessionCost = true
override fun protocol(): AgentProtocol = Protocol()
/** `opencode acp`: the Agent Client Protocol, JSON-RPC over stdio. */
@VisibleForTesting
internal class Protocol : AgentProtocol {
private enum class Stage { INIT, SESSION, CONFIG, PROMPT, IDLE }
private var next = 1
private var stage = Stage.IDLE
private var pending = -1
private var session: String? = null
private var resume: String? = null
private var cwd = "/root"
/** Requests for the session still to send, each once the one before it has been answered. */
private val queue = ArrayDeque<(String) -> JSONObject>()
private val said = StringBuilder()
private val thought = StringBuilder()
/** Each tool call's name, which only its first update carries, and its latest entry. */
private val names = mutableMapOf<String, String>()
private val used = mutableMapOf<String, AgentHost.Entry.Used>()
private var cost = 0.0
private var started = 0L
override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List<String> {
val text = if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message
val prompt = { id: String ->
JSONObject().put("sessionId", id).put("prompt", JSONArray().put(JSONObject().put("type", "text").put("text", text)))
}
queue.clear()
val known = session
if (!started && known != null && configured) return listOf(send(Stage.PROMPT, "session/prompt", prompt(known)))
fun option(config: String, value: String) = { id: String -> JSONObject().put("sessionId", id).put("configId", config).put("value", value) }
options.model?.let { queue += option("model", it) }
options.effort?.let { queue += option("effort", it) }
queue += option("mode", if (options.plan) "plan" else "build")
queue += prompt
// A session whose options were refused sets them all again before its next prompt.
if (!started && known != null) return listOf(advance(known))
resume = conversation
cwd = options.workdir
return listOf(send(Stage.INIT, "initialize", JSONObject().put("protocolVersion", 1).put("clientCapabilities", JSONObject())))
}
private fun send(stage: Stage, method: String, params: JSONObject): String {
this.stage = stage
pending = next++
if (stage == Stage.PROMPT) started = System.currentTimeMillis()
return JSONObject().put("jsonrpc", "2.0").put("id", pending).put("method", method).put("params", params).toString()
}
/** The next queued request: the prompt once nothing else is left. */
private fun advance(id: String): String {
val make = queue.removeFirst()
val params = make(id)
configuring = params.optString("configId")
configured = queue.isEmpty()
return if (queue.isEmpty()) send(Stage.PROMPT, "session/prompt", params) else send(Stage.CONFIG, "session/set_config_option", params)
}
/** The config option the pending set_config_option sets. */
private var configuring = ""
/** The session's model, effort and mode were all set, so a later prompt can go straight to it. */
private var configured = false
override fun answer(approval: AgentHost.Approval, allow: Boolean): String = JSONObject(approval.payload).put("jsonrpc", "2.0")
.put("result", JSONObject().put("outcome", JSONObject().put("outcome", "selected").put("optionId", if (allow) "once" else "reject"))).toString()
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val method = o.optString("method")
val params = o.optJSONObject("params") ?: JSONObject()
return when {
method.isEmpty() -> response(o)
o.has("id") -> request(o.get("id"), method, params)
method == "session/update" -> update(params.optJSONObject("update") ?: return null)
else -> null
}
}
private fun response(o: JSONObject): AgentEvent? {
if (o.optInt("id", -1) != pending) return null
val error = o.optJSONObject("error")?.let { it.optJSONObject("data")?.optString("message")?.ifEmpty { null } ?: it.optString("message").ifEmpty { "error" } }
val result = o.optJSONObject("result") ?: JSONObject()
return when (stage) {
Stage.INIT -> error?.let(::failed) ?: AgentEvent(reply = listOf(
resume?.let { send(Stage.SESSION, "session/resume", JSONObject().put("sessionId", it).put("cwd", cwd).put("mcpServers", JSONArray())) }
?: send(Stage.SESSION, "session/new", JSONObject().put("cwd", cwd).put("mcpServers", JSONArray())),
))
Stage.SESSION -> {
if (error != null) return failed(error)
val id = result.optString("sessionId").ifEmpty { resume.orEmpty() }.takeIf { it.isNotEmpty() } ?: return failed("no session")
session = id
AgentEvent(id, reply = listOf(advance(id)))
}
// A model without effort levels refuses one and the turn goes on with its default; a refused
// mode would run a plan turn as a build one, so it ends the turn instead.
Stage.CONFIG -> if (error != null && configuring == "mode") failed(error) else AgentEvent(reply = listOf(advance(session ?: return null)))
Stage.PROMPT -> {
stage = Stage.IDLE
val usage = result.optJSONObject("usage")
val reason = result.optString("stopReason")
AgentEvent(
session,
flush() + AgentHost.Entry.Finished(error ?: if (reason == "refusal") "refused" else null),
usage = AgentHost.Usage(
System.currentTimeMillis() - started, cost,
(usage?.optLong("inputTokens") ?: 0) + (usage?.optLong("cachedReadTokens") ?: 0),
(usage?.optLong("outputTokens") ?: 0) + (usage?.optLong("thoughtTokens") ?: 0),
),
)
}
Stage.IDLE -> null
}
}
private fun failed(error: String): AgentEvent {
stage = Stage.IDLE
configured = false
return AgentEvent(session, flush() + AgentHost.Entry.Finished(error))
}
private fun request(id: Any, method: String, params: JSONObject): AgentEvent {
val payload = JSONObject().put("id", id).toString()
if (method != "session/request_permission") {
// File writes and terminals stay with OpenCode, which does them itself when the client declines.
return AgentEvent(reply = listOf(JSONObject(payload).put("jsonrpc", "2.0")
.put("error", JSONObject().put("code", -32601).put("message", "DroidDeck cannot answer $method")).toString()))
}
val call = params.optJSONObject("toolCall") ?: JSONObject()
val raw = call.optJSONObject("rawInput") ?: JSONObject()
val name = names[call.optString("toolCallId")] ?: call.optString("kind")
val kind = call.optString("kind")
val approval = when {
kind == "execute" -> AgentHost.Approval(id.toString(), "Bash", firstLine(raw.optString("command")), raw.optString("command"), payload)
// OpenCode asks for a folder outside the workspace on its own, before the tool's own ask.
raw.has("parentDir") -> AgentHost.Approval(
id.toString(), "External directory", raw.optString("parentDir"),
listOf(raw.optString("parentDir"), raw.optString("command")).filter { it.isNotEmpty() }.joinToString("\n\n"), payload,
)
raw.has("diff") -> {
val path = raw.optString("filepath")
AgentHost.Approval(id.toString(), "Edit", path, path + "\n" + patchLines(raw.optString("diff"), ""), payload)
}
else -> AgentHost.Approval(id.toString(), toolName(name), call.optString("title"), raw.toString(2), payload)
}
return AgentEvent(session, flush(), approval = approval)
}
private fun update(u: JSONObject): AgentEvent? = when (u.optString("sessionUpdate")) {
"agent_message_chunk" -> chunk(u)?.let { said.append(it); AgentEvent(session, text = it) }
"agent_thought_chunk" -> chunk(u)?.let { thought.append(it); AgentEvent(session, thinking = it) }
"tool_call", "tool_call_update" -> AgentEvent(session, flush() + tool(u))
"usage_update" -> {
u.optJSONObject("cost")?.optDouble("amount")?.takeIf { !it.isNaN() }?.let { cost = it }
AgentEvent(session, context = u.optLong("used").takeIf { it > 0 }, window = u.optLong("size").takeIf { it > 0 })
}
else -> null
}
private fun chunk(u: JSONObject) = u.optJSONObject("content")?.takeIf { it.optString("type") == "text" }?.optString("text")?.takeIf { it.isNotEmpty() }
/** What was written since the last entry, as whole entries. */
private fun flush(): List<AgentHost.Entry> = buildList {
thought.toString().trim().takeIf { it.isNotEmpty() }?.let { add(AgentHost.Entry.Thought(it)) }
said.toString().trim().takeIf { it.isNotEmpty() }?.let { add(AgentHost.Entry.Said(it)) }
thought.clear()
said.clear()
}
private fun tool(u: JSONObject): List<AgentHost.Entry> {
val id = u.optString("toolCallId")
if (u.optString("sessionUpdate") == "tool_call") names[id] = u.optString("title")
val input = u.optJSONObject("rawInput")?.takeIf { it.length() > 0 }
val entry = if (input != null || used[id] == null) tool(id, names[id].orEmpty(), input ?: JSONObject()) else used.getValue(id)
used[id] = entry
val raw = u.optJSONObject("rawOutput")
return when (u.optString("status")) {
"completed" -> {
val exit = raw?.optJSONObject("metadata")?.opt("exit")
listOf(entry, AgentHost.Entry.Result(id, raw?.optString("output")?.ifEmpty { null } ?: content(u), exit is Number && exit.toInt() != 0))
}
"failed" -> listOf(entry, AgentHost.Entry.Result(id, raw?.optString("error")?.ifEmpty { null } ?: content(u), true))
else -> listOf(entry)
}
}
private fun content(u: JSONObject): String {
val list = u.optJSONArray("content") ?: return ""
return (0 until list.length()).mapNotNull { list.optJSONObject(it)?.optJSONObject("content")?.optString("text") }.joinToString("\n")
}
}
private fun toolName(name: String) = name.replaceFirstChar { it.uppercase() }.ifEmpty { "Tool" }
private fun tool(id: String, name: String, input: JSONObject): AgentHost.Entry.Used {
val path = input.optString("filePath")
return when (name) {
"bash" -> AgentHost.Entry.Used(id, "Bash", firstLine(input.optString("command")), input.optString("command"))
"edit" -> AgentHost.Entry.Used(id, "Edit", path, path + "\n" + lineDiff(input.optString("oldString"), input.optString("newString")))
"write" -> AgentHost.Entry.Used(id, "Write", path, path + "\n" + lineDiff("", input.optString("content")))
"todowrite" -> AgentHost.Entry.Used(id, "TodoWrite", "", todos(input.optJSONArray("todos")))
else -> AgentHost.Entry.Used(id, toolName(name), detail(input), if (input.length() == 0) "" else input.toString(2))
}
}
private fun detail(input: JSONObject): String {
for (key in listOf("filePath", "path", "pattern", "url", "query", "description", "prompt", "command")) {
input.optString(key).takeIf { it.isNotEmpty() }?.let { return firstLine(it) }
}
return ""
}
private fun todos(list: JSONArray?) = (0 until (list?.length() ?: 0)).mapNotNull { i ->
val todo = list?.optJSONObject(i) ?: return@mapNotNull null
val mark = when (todo.optString("status")) { "completed" -> "[x]"; "in_progress" -> "[~]"; else -> "[ ]" }
"$mark ${todo.optString("content")}"
}.joinToString("\n")
}
@VisibleForTesting
internal fun firstLine(text: String) = text.lineSequence().first().take(160)
/**
* [command] with its stderr in a log of its own under /root/.cache/droiddeck. The agent's stdout and stderr share one
* pipe, and a log line written in the middle of a long JSON line would make that line unreadable.
*/
internal fun withoutStderr(log: String, command: List<String>) =
listOf("/bin/sh", "-c", "mkdir -p /root/.cache/droiddeck; exec \"\$@\" 2>/root/.cache/droiddeck/$log.log", "sh") + command
private const val DIFF_CONTEXT = 2
/**
@@ -417,6 +1060,18 @@ internal fun lineDiff(old: String, new: String): String {
}.joinToString("\n")
}
/** A unified diff's hunks without their headers; an added or deleted file's diff is its whole content. */
@VisibleForTesting
internal fun patchLines(diff: String, kind: String): String {
val lines = diff.removeSuffix("\n").lines()
when (kind) {
"add" -> return lines.joinToString("\n") { "+$it" }
"delete" -> return lines.joinToString("\n") { "-$it" }
}
val start = lines.indexOfFirst { it.startsWith("@@") }
return (if (start < 0) lines else lines.drop(start)).filter { it.isNotEmpty() && !it.startsWith("@@") && !it.startsWith("\\") }.joinToString("\n")
}
private val SHELL_WRAPPER = Regex("^/bin/(?:ba)?sh -l?c '(.*)'$", RegexOption.DOT_MATCHES_ALL)
/** Codex runs each command as `/bin/bash -lc '<command>'`; the command is what the user wants to read. */
@@ -21,8 +21,8 @@ import java.nio.file.Files
/**
* The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless
* outside any game or desktop session: one process per turn, or for a CLI that takes its messages over
* stdin one process kept open between turns, so background work can start a turn of its own. Conversations are kept on disk
* outside any game or desktop session as one process that takes its messages over stdin and stays open
* between turns, so background work can start a turn of its own. Conversations are kept on disk
* ([AgentChats]), so a restart (a Lab build, a crash) continues the same one.
*/
object AgentHost {
@@ -56,6 +56,9 @@ object AgentHost {
/** A message typed while the agent was working, sent when the turn ends. */
data class Queued(val text: String, val files: List<String>)
/** A tool call the CLI waits on the user to allow; [payload] is what its protocol needs to answer. */
data class Approval(val id: String, val tool: String, val detail: String, val input: String, val payload: String = "")
enum class State { MISSING, IDLE, WORKING }
private const val TAG = "AgentHost"
@@ -94,6 +97,12 @@ object AgentHost {
private set
var plan by mutableStateOf(false)
private set
/** The chosen [AgentHarness.Permission] of [harness]; asking first until the user picks another. */
var permission by mutableStateOf(AgentHarness.ASK)
private set
/** Tool calls of the running turn that wait for the user, oldest first. */
val approvals = mutableStateListOf<Approval>()
private var approvalNoticed = false
var chat by mutableStateOf<String?>(null)
private set
/** A reply finished since the conversation was last on screen. */
@@ -123,7 +132,9 @@ object AgentHost {
var lab by mutableStateOf<LabProgress?>(null)
private set
private class Turn(val process: Process, val pid: Int, val stdin: java.io.OutputStream? = null) {
private class Turn(val process: Process, val pid: Int, val protocol: AgentProtocol, val stdin: java.io.OutputStream) {
fun write(lines: List<String>) = synchronized(this) { stdin.apply { lines.forEach { write((it + "\n").toByteArray()) }; flush() } }
var writingGeneration: Int? = null
var exitStatus: Int? = null
var costs: AgentCostTracker? = null
@@ -171,6 +182,8 @@ object AgentHost {
model = prefs(app).getString(modelKey(harness), null)
effort = prefs(app).getString(effortKey(harness), null)?.takeIf { it in harness.efforts }
plan = prefs(app).getBoolean(PLAN_KEY, false)
permission = prefs(app).getString(permissionKey(harness), null)?.takeIf { id -> harness.permissions.any { it.id == id } }
?: harness.permissions.first().id
limits = decodeLimits(prefs(app).getString(limitsKey(harness), null))
available = LinuxRuntime.hasRootfs(app)
installed = harness.files.all { guestFileExists(app, it) }
@@ -273,6 +286,42 @@ object AgentHost {
prefs(context).edit().putBoolean(PLAN_KEY, on).apply()
}
/** Kept per CLI, for every conversation; the CLI process restarts with it on the next message. */
fun choosePermission(context: Context, id: String) {
if (harness.permissions.none { it.id == id }) return
permission = id
prefs(context).edit().putString(permissionKey(harness), id).apply()
}
/** Lets the CLI run [approval]'s tool call, or tells it the user said no. */
fun answer(context: Context, approval: Approval, allow: Boolean) {
if (!approvals.remove(approval)) return
val running = turn ?: session ?: return
val line = running.protocol.answer(approval, allow)
val app = context.applicationContext
val current = harness
Thread({ runCatching { running.write(listOf(line)) }.onFailure { lost(app, running, current, it) } }, "agent-approval").start()
approvalsChanged(app)
}
/** The approval notice goes once nothing waits on the user any more. */
private fun approvalsChanged(app: Context) {
if (approvals.isNotEmpty() || !approvalNoticed) return
approvalNoticed = false
AgentNotice.clear(app)
}
/**
* A line the CLI waits for could not be written, so it would wait forever: its process ends, which ends
* the turn, and the chat says why. A request that may have reached it is not sent again.
*/
private fun lost(app: Context, from: Turn, current: AgentHarness, error: Throwable) {
Log.w(TAG, "could not write to ${current.name}", error)
main.post { if (turn === from || session === from) record(app, Entry.Notice("Could not write to ${current.name}: ${error.message ?: error.javaClass.simpleName}")) }
AgentProcesses.killTree(from.pid)
from.process.destroy()
}
fun models(context: Context) = harness.models(LinuxRuntime.rootDir(context.applicationContext))
/** Sends [text] now, or after the current turn when the agent is working. */
@@ -303,19 +352,20 @@ object AgentHost {
val current = harness
val prompt = AgentAttachments.prompt(message, attached)
turnPlanned = plan && current.plans
val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort)
val command = current.turn(prompt, conversation, options)
val line = current.input(prompt)
val key = "${current.id}|$id|$model|$turnPlanned|$effort"
val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort, permission, workspace(app))
val key = "${current.id}|$id|$model|$turnPlanned|$effort|$permission"
val resumed = conversation
background = false
approvals.clear()
approvalsChanged(app)
val kept = session
if (kept != null && line != null && sessionKey == key && kept.process.isAlive) {
if (kept != null && sessionKey == key && kept.process.isAlive) {
main.removeCallbacks(reap)
turn = kept
kept.writingGeneration = gen
kept.clearingCosts = prompt == "/clear"
Thread({
val written = runCatching { synchronized(kept) { kept.stdin?.apply { write((line + "\n").toByteArray()); flush() } != null } }.getOrDefault(false)
val written = runCatching { kept.write(kept.protocol.input(prompt, resumed, options, started = false)) }.isSuccess
// The process died between turns: the same message goes to a new one, which resumes the conversation.
main.post {
if (kept.writingGeneration == gen) kept.writingGeneration = null
@@ -323,7 +373,7 @@ object AgentHost {
if (!written) {
dropSession()
turn = null
spawn(app, gen, current, current.turn(prompt, conversation, options), line, key)
spawn(app, gen, current, prompt, resumed, options, key)
} else kept.exitStatus?.let { processExited(app, kept, current, it) }
}
}
@@ -331,12 +381,14 @@ object AgentHost {
return
}
dropSession()
spawn(app, gen, current, command, line, key)
spawn(app, gen, current, prompt, resumed, options, key)
}
private fun spawn(app: Context, gen: Int, current: AgentHarness, command: List<String>, line: String?, key: String) {
val workdir = workspace(app)
var threadConversation = conversation
private fun spawn(app: Context, gen: Int, current: AgentHarness, prompt: String, resumed: String?, options: AgentHarness.Options, key: String) {
val workdir = options.workdir
val command = current.turn(prompt, resumed, options)
val protocol = current.protocol()
var threadConversation = resumed
Thread({
runCatching { current.prepare(LinuxRuntime.rootDir(app)) }
runCatching { AgentSetup.installHelpers(app) }
@@ -349,17 +401,18 @@ object AgentHost {
main.post { if (generation == gen) finish(app, e.message ?: "could not start") }
return@Thread
}
val started = Turn(child, AgentProcesses.pidOf(child), if (line != null) child.outputStream else null).apply {
if (current === ClaudeCode && line != null) costs = AgentCostTracker()
val started = Turn(child, AgentProcesses.pidOf(child), protocol, child.outputStream).apply {
if (current === ClaudeCode) costs = AgentCostTracker()
}
OrphanReaper.keep(started.pid)
main.post {
if (generation == gen && state == State.WORKING && turn == null) {
turn = started
if (line != null) { session = started; sessionKey = key }
session = started
sessionKey = key
} else AgentProcesses.killTree(started.pid)
}
if (line != null) runCatching { child.outputStream.apply { write((line + "\n").toByteArray()); flush() } } else child.outputStream.close()
runCatching { started.write(protocol.input(prompt, resumed, options, started = true)) }.onFailure { lost(app, started, current, it) }
val raw = runCatching {
val log = File(app.filesDir, TURN_LOG).apply { parentFile?.mkdirs() }
log.renameTo(File(app.filesDir, "$TURN_LOG.1"))
@@ -368,7 +421,8 @@ object AgentHost {
runCatching {
child.inputStream.bufferedReader().forEachLine { output ->
runCatching { raw?.apply { write(output); newLine(); flush() } }
val parsed = current.parse(output) ?: return@forEachLine
val parsed = protocol.parse(output) ?: return@forEachLine
if (parsed.reply.isNotEmpty()) runCatching { started.write(parsed.reply) }.onFailure { lost(app, started, current, it) }
parsed.conversation?.let { threadConversation = it }
val done = parsed.entries.any { it is Entry.Finished }
val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull()
@@ -410,7 +464,7 @@ object AgentHost {
if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage?.let { from.costs?.perTurn(it) ?: it })
return
}
val content = event.text != null || event.thinking != null || event.entries.any { it !is Entry.Finished }
val content = event.text != null || event.thinking != null || event.approval != null || event.entries.any { it !is Entry.Finished }
if (content && state == State.IDLE && session === from) {
main.removeCallbacks(reap)
background = true
@@ -428,10 +482,17 @@ object AgentHost {
from.clearingCosts = false
}
val applied = if (finished != null && state == State.WORKING && event.usage != null)
event.copy(usage = from.costs?.perTurn(event.usage) ?: event.usage) else event
event.copy(usage = turnCost(from.costs?.perTurn(event.usage) ?: event.usage)) else event
apply(app, applied)
}
/** A CLI that reports the conversation's whole cost spent what this chat has not recorded yet. */
private fun turnCost(usage: Usage): Usage {
if (!harness.sessionCost) return usage
val recorded = entries.sumOf { (it as? Entry.Finished)?.usage?.costUsd ?: 0.0 }
return usage.copy(costUsd = (usage.costUsd - recorded).coerceAtLeast(0.0))
}
/** Ends the CLI process kept between turns, and with it whatever it still runs in the background. */
private fun dropSession() {
main.removeCallbacks(reap)
@@ -529,6 +590,15 @@ object AgentHost {
}
event.text?.let { live += it }
event.thinking?.let { liveThinking += it }
event.resolved?.let { id ->
approvals.removeAll { it.id == id }
approvalsChanged(app)
}
event.approval?.takeIf { a -> state == State.WORKING && approvals.none { it.id == a.id } }?.let {
approvals += it
approvalNoticed = true
AgentNotice.post(app, AgentNotice.Kind.APPROVAL, listOf(it.tool, it.detail).filter { s -> s.isNotEmpty() }.joinToString(": "))
}
event.context?.let { context = it }
event.window?.let { window = it }
event.limits?.let { reported ->
@@ -549,6 +619,8 @@ object AgentHost {
private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) {
if (state != State.WORKING) return
turn = null
approvals.clear()
approvalsChanged(app)
val answeredTask = background
background = false
main.removeCallbacks(reap)
@@ -762,6 +834,7 @@ object AgentHost {
private const val LINGER_MS = 20 * 60_000L
private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
private fun permissionKey(harness: AgentHarness) = "permission_${harness.id}"
private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}"
@VisibleForTesting
@@ -16,10 +16,10 @@ internal object AgentNotice {
private const val CHANNEL_ID = "agent_done"
private const val NOTIFICATION_ID = 4108
enum class Kind { DONE, FAILED, QUESTION }
enum class Kind { DONE, FAILED, QUESTION, APPROVAL }
fun post(context: Context, kind: Kind, text: String) {
if (onScreen(context)) return
if (onScreen(context, kind)) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return
manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT))
val open = PendingIntent.getActivity(context, 2,
@@ -31,6 +31,7 @@ internal object AgentNotice {
Kind.DONE -> R.string.agent_done
Kind.FAILED -> R.string.agent_done_failed
Kind.QUESTION -> R.string.agent_done_question
Kind.APPROVAL -> R.string.agent_done_approval
})
runCatching {
manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID)
@@ -49,9 +50,9 @@ internal object AgentNotice {
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
}
/** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble. */
private fun onScreen(context: Context): Boolean {
if (AgentPet.floating) return true
/** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble but has no way to answer an approval. */
private fun onScreen(context: Context, kind: Kind): Boolean {
if (AgentPet.floating && kind != Kind.APPROVAL) return true
val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) }
return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
@@ -27,6 +27,55 @@ object AgentSetup {
val detail = mutableStateMapOf<Step, String>()
var runtimeInstalled by mutableStateOf(true)
private set
/** Ids of the harness's [AgentHarness.providers] with a key saved; signed in without one means its free models. */
var keys by mutableStateOf(emptySet<String>())
private set
/** The provider and custom server picked in the key field, kept while a save is checked. */
var provider by mutableStateOf<String?>(null)
var server by mutableStateOf("")
/** Saves a pasted key for a harness that signs in with one, then checks the sign-in again. */
fun saveKey(context: Context, provider: AgentHarness.Provider, key: String, endpoint: String? = null) = signInLocally(context) { harness, root ->
harness.saveKey(root, provider, key, endpoint) { url, token -> fetch(context.applicationContext, url, token) }
}
fun removeKey(context: Context, provider: AgentHarness.Provider) = signInLocally(context) { harness, root -> harness.removeKey(root, provider) }
/** A GET from the userland, which reaches the LAN servers the app's own cleartext policy does not. */
private fun fetch(app: Context, url: String, token: String?): String {
// The key goes in on stdin, so it is never in a command line.
val process = AgentHost.guest(app, listOf("curl", "-fsSL", "--max-time", "20", "-H", "@-", url), connectAdb = false).start()
process.outputStream.bufferedWriter().use { if (token != null) it.write("Authorization: Bearer $token\n") }
val output = process.inputStream.bufferedReader().readText()
check(process.waitFor(30, TimeUnit.SECONDS) && process.exitValue() == 0) { output.trim().lines().lastOrNull()?.takeIf { it.isNotEmpty() } ?: "Cannot reach $url" }
return output
}
fun useFree(context: Context) = signInLocally(context) { harness, root -> harness.useFree(root) }
private val signInLock = Any()
private fun signInLocally(context: Context, write: (AgentHarness, File) -> Unit) {
val app = context.applicationContext
val harness = AgentHost.harness
set(Step.SIGN_IN, Status.WORKING)
Thread({
// Each write reads the files the one before it left, including across a save's model request.
val result = synchronized(signInLock) { runCatching { write(harness, LinuxRuntime.rootDir(app)) } }
main.post {
// A failure stays on the row with the key field open, since the next check would clear it.
val error = result.exceptionOrNull()
if (error != null) {
status[Step.SIGN_IN] = Status.FAILED
detail[Step.SIGN_IN] = error.message ?: "failed"
} else {
status[Step.SIGN_IN] = Status.UNKNOWN
detail.remove(Step.SIGN_IN)
check(app)
}
}
}, "agent-sign-in").start()
}
val ready: Boolean get() = Step.entries.filter { it.required }.all { status[it] == Status.DONE }
@@ -53,6 +102,7 @@ object AgentSetup {
if (!runtimeInstalled) return
AgentHost.refresh(app)
val harness = AgentHost.harness
keys = harness.keys(LinuxRuntime.rootDir(app))
val probes = mutableListOf<Pair<Step, List<String>>>()
for (step in Step.entries) if (status[step] != Status.WORKING) {
when (step) {
@@ -79,15 +129,23 @@ object AgentSetup {
fun runsAsRoot(step: Step) = step == Step.INSTALL
/** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */
fun run(context: Context, step: Step) {
fun run(context: Context, step: Step) = run(context, step, null)
/** Opens the page where a provider's key is made, as the sign-in of a harness that takes pasted keys. */
fun openKeyPage(context: Context, page: String) = run(context, Step.SIGN_IN, listOf("/root/.local/bin/android-open", page))
private fun run(context: Context, step: Step, override: List<String>?) {
val app = context.applicationContext
val harness = AgentHost.harness
val command = when (step) {
val command = override ?: when (step) {
Step.CONNECTION -> return
Step.INSTALL -> {
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
"dpkg --configure -a; apt-get update || echo 'Some package sources could not be refreshed; continuing'; apt-get -f install -y; " +
"apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
"apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " +
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " +
"for i in 1 2 3; do apt update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
"apt -f install -y --fix-missing; " +
"apt install -y --fix-missing --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
}
Step.SIGN_IN -> harness.signIn
Step.GITHUB -> listOf("dd-gh-login")
@@ -16,13 +16,14 @@ import java.nio.file.attribute.BasicFileAttributes
/**
* What the agent adds to the Linux userland, measured and removable piece by piece. Sign-ins
* (~/.claude, ~/.codex, gh's config) are left alone, so removing a CLI and installing it again
* does not sign out.
* (~/.claude, ~/.codex, ~/.local/share/opencode, gh's config) are left alone, so removing a CLI
* and installing it again does not sign out.
*/
object AgentStorage {
enum class Item(val paths: List<String>) {
CLAUDE_CODE(listOf("/root/.local/share/claude", "/root/.local/bin/claude", "/root/cc")),
CODEX(listOf("/root/.local/bin/codex", "/root/.local/bin/codex-code-mode-host")),
OPENCODE(listOf("/root/.opencode")),
BUILD_TOOLS(listOf("/root/android-sdk", "/root/aapt2", "/root/x86root", "/root/.gradle")),
SOURCE(listOf("/root/DroidDeck")),
CACHES(listOf("/root/.cache", "/root/.npm")),
@@ -0,0 +1,91 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.frontend.LibraryCache
import com.droiddeck.launcher.stores.CloudSaves
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.xbox.Xodus
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.util.concurrent.TimeUnit
import org.json.JSONArray
import org.json.JSONObject
internal object AgentStores {
private const val OUTPUT_CAP = 160 * 1024
fun library(context: Context, request: JSONObject): JSONObject {
val query = request.optString("query").trim()
val source = request.optString("source").trim()
val games = JSONArray()
LibraryCache.load(context)
.filter { (query.isEmpty() || it.name.contains(query, ignoreCase = true)) && (source.isEmpty() || it.source.equals(source, ignoreCase = true)) }
.forEach {
games.put(JSONObject().put("id", it.gameIdString).put("name", it.name).put("source", it.source)
.put("storeId", it.storeId ?: JSONObject.NULL).put("folder", it.gameFiles?.path ?: JSONObject.NULL))
}
return JSONObject().put("ok", true).put("command", "library").put("games", games)
}
fun xodus(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val list = request.optJSONArray("args")
val args = if (list == null) emptyList() else List(list.length()) { list.optString(it) }
if (args.isEmpty() || args.any { it.isEmpty() }) throw AgentException("INVALID_REQUEST", "xodus needs its arguments")
val timeoutMs = (request.optDouble("timeout", 120.0) * 1000).toLong().coerceIn(1_000L, 900_000L)
return Xodus.start(context.applicationContext, args).use { child ->
val out = Tail(child.process.inputStream)
val err = Tail(child.process.errorStream)
val finished = child.process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)
if (!finished) child.close()
JSONObject().put("ok", true).put("command", "xodus").put("timedOut", !finished)
.put("exit", if (finished) child.process.exitValue() else JSONObject.NULL)
.put("stdout", out.text()).put("stderr", err.text())
}
}
fun cloud(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val store = Store.byId(request.optString("store"))?.takeIf(CloudSaves::supports)
?: throw AgentException("INVALID_REQUEST", "store must be one with cloud saves")
val id = request.optString("id").ifEmpty { throw AgentException("INVALID_REQUEST", "cloud needs a game id") }
val force = request.optBoolean("force")
val result = when (val direction = request.optString("direction")) {
"down" -> CloudSaves.download(context.applicationContext, store, id, force)
"up" -> CloudSaves.upload(context.applicationContext, store, id, force)
else -> throw AgentException("INVALID_REQUEST", "direction '$direction' is not down or up")
}
return JSONObject().put("ok", true).put("command", "cloud").put("result", result.result).put("files", result.files)
.put("bytes", result.bytes).put("reason", result.reason).put("conflicts", result.conflicts).put("detail", result.detail)
}
private class Tail(stream: InputStream) {
private val kept = ByteArrayOutputStream()
private var dropped = false
private val reader = Thread({
val buffer = ByteArray(8192)
stream.use { input ->
while (true) {
val n = runCatching { input.read(buffer) }.getOrDefault(-1)
if (n < 0) break
synchronized(kept) {
kept.write(buffer, 0, n)
if (kept.size() > OUTPUT_CAP * 2) {
val bytes = kept.toByteArray()
kept.reset()
kept.write(bytes, bytes.size - OUTPUT_CAP, OUTPUT_CAP)
dropped = true
}
}
}
}
}, "agent-xodus-output").apply { isDaemon = true; start() }
fun text(): String {
reader.join(2_000)
val bytes = synchronized(kept) { kept.toByteArray() }
val tail = if (bytes.size > OUTPUT_CAP) bytes.copyOfRange(bytes.size - OUTPUT_CAP, bytes.size) else bytes
return (if (dropped || bytes.size > OUTPUT_CAP) "...\n" else "") + String(tail, Charsets.UTF_8)
}
}
}
@@ -1,23 +1,9 @@
package com.droiddeck.launcher.agent
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.NavTabs
object AgentTab {
var shown by mutableStateOf(true)
private set
val shown: Boolean get() = "agent" !in NavTabs.hidden
val visible: Boolean get() = shown && AgentHost.available
fun load(context: Context) {
shown = SessionPrefs.agentTab(context)
}
fun set(context: Context, show: Boolean) {
shown = show
SessionPrefs.setAgentTab(context, show)
}
}
@@ -16,8 +16,10 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public class PulseAudioComponent extends SessionPart {
private static final String TAG = "PulseAudio";
@@ -38,6 +40,7 @@ public class PulseAudioComponent extends SessionPart {
private long generation;
private long launches;
private final IntConsumer terminate;
final ReentrantReadWriteLock commands = new ReentrantReadWriteLock();
HostLifecycle(IntConsumer terminate) {
this.terminate = terminate;
@@ -54,11 +57,27 @@ public class PulseAudioComponent extends SessionPart {
pid = -1;
}
synchronized boolean launch(long expected, IntSupplier launch) {
if (expected != generation) return false;
launches++;
pid = launch.getAsInt();
return true;
boolean launch(long expected, IntSupplier launch) {
commands.writeLock().lock();
try {
synchronized (this) {
if (expected != generation) return false;
launches++;
pid = launch.getAsInt();
return true;
}
} finally {
commands.writeLock().unlock();
}
}
<T> T command(long token, Supplier<T> command) {
commands.readLock().lock();
try {
return live(token) ? command.get() : null;
} finally {
commands.readLock().unlock();
}
}
synchronized boolean current(long expected) {
@@ -218,13 +237,13 @@ public class PulseAudioComponent extends SessionPart {
String loadedAs = null;
for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) {
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
if (pactlFor(token, "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) != null
&& pactlFor(token, "set-default-sink", "DirectAudio") != null) {
if (pactlOk(token, "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)
&& pactlOk(token, "set-default-sink", "DirectAudio")) {
loadedAs = "DirectAudio on attempt " + attempt;
} else if (pactlFor(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactlFor(token, "set-default-sink", "AAudioSink") != null) {
} else if (pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls)
&& pactlOk(token, "set-default-sink", "AAudioSink")) {
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
}
}
@@ -248,14 +267,24 @@ public class PulseAudioComponent extends SessionPart {
}
private String pactlFor(long token, String... args) {
return host.live(token) ? pactl(args) : null;
return host.command(token, () -> pactl(true, args));
}
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
private String pactl(String... args) {
private boolean pactlOk(long token, String... args) {
return host.command(token, () -> pactl(false, args)) != null;
}
private static void reap(java.lang.Process process) throws InterruptedException {
process.destroyForcibly();
process.waitFor(2, TimeUnit.SECONDS);
}
/** Runs pactl against this daemon; its stdout when captured (empty otherwise), or null when it failed or timed out. */
private String pactl(boolean capture, String... args) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || host.pid <= 1) return null;
java.lang.Process process = null;
File output = null;
try {
File modules = new File(workingDir, "modules/arm64");
ArrayList<String> cmd = new ArrayList<>();
@@ -268,29 +297,33 @@ public class PulseAudioComponent extends SessionPart {
builder.environment().put("HOME", workingDir.getAbsolutePath());
builder.environment().put("TMPDIR", workingDir.getAbsolutePath());
builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath());
process = builder.start();
String output;
try (InputStream in = process.getInputStream();
java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream()) {
byte[] buf = new byte[4096];
int n;
while ((n = in.read(buf)) != -1) {
outStream.write(buf, 0, n);
}
output = outStream.toString(java.nio.charset.StandardCharsets.UTF_8.name());
if (capture) {
output = File.createTempFile("pactl", ".out", workingDir);
builder.redirectOutput(output);
} else {
builder.redirectOutput(new File("/dev/null"));
}
process = builder.start();
if (!process.waitFor(5, TimeUnit.SECONDS)) {
process.destroyForcibly();
reap(process);
return null;
}
return process.exitValue() == 0 ? output : null;
if (process.exitValue() != 0) return null;
return capture ? new String(Files.readAllBytes(output.toPath()), java.nio.charset.StandardCharsets.UTF_8) : "";
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
} catch (Throwable t) {
return null;
} finally {
if (process != null && process.isAlive()) process.destroyForcibly();
if (process != null && process.isAlive()) {
try {
reap(process);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (output != null) output.delete();
}
}
@@ -281,9 +281,6 @@ object DeviceReport {
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(context))
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("native userland (no proot)", SessionPrefs.nativeUserland(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
@@ -122,6 +122,12 @@ public final class Downloader {
return null;
}
public static Boolean gone(String url) {
Fetch fetch = fetch(url);
if (fetch.body != null) return Boolean.FALSE;
return fetch.fatal ? Boolean.TRUE : null;
}
public static String downloadDirect(String url) {
LAST_FAILURE.remove();
return fetch(url).body;
@@ -23,6 +23,7 @@ object GameEnvironment {
)
fun validName(name: String) = namePattern.matches(name)
fun currentName(name: String) = if (name.startsWith("BL_")) "DD_" + name.removePrefix("BL_") else name
fun supported(name: String) = name !in unused && !name.startsWith("BOX64_") && !name.startsWith("BOX86_")
fun validValue(value: String) = '\u0000' !in value && value.length <= 8192
fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true)
@@ -97,14 +98,14 @@ object GameEnvironment {
val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER)
val syncKeys = listOf("BL_SYNC", "BL_FSYNC_FIRST", "BL_SYNC_FALLBACK", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
val syncKeys = listOf("DD_SYNC", "DD_FSYNC_FIRST", "DD_SYNC_FALLBACK", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
fun syncEnvironment(backend: String): Map<String, String> {
require(backend in syncBackends) { "unknown sync $backend" }
return buildMap {
put("BL_SYNC", if (backend == SessionPrefs.SYNC_NTSYNC) "1" else "0")
put("BL_FSYNC_FIRST", if (backend == SessionPrefs.SYNC_FSYNC) "1" else "0")
put("BL_SYNC_FALLBACK", if (backend == SessionPrefs.SYNC_WINESERVER) "0" else "1")
put("DD_SYNC", if (backend == SessionPrefs.SYNC_NTSYNC) "1" else "0")
put("DD_FSYNC_FIRST", if (backend == SessionPrefs.SYNC_FSYNC) "1" else "0")
put("DD_SYNC_FALLBACK", if (backend == SessionPrefs.SYNC_WINESERVER) "0" else "1")
if (backend == SessionPrefs.SYNC_FSYNC) put("PROTON_NO_ESYNC", "1")
}
}
@@ -20,7 +20,7 @@ object GameEnvironmentOptions {
Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_NO_FSYNC", "1", R.string.game_env_no_fsync, Type.TOGGLE, listOf("0", "1")),
Option("BL_FSYNC_FIRST", "1", R.string.game_env_fsync_first, Type.TOGGLE, listOf("0", "1")),
Option("DD_FSYNC_FIRST", "1", R.string.game_env_fsync_first, Type.TOGGLE, listOf("0", "1")),
Option("DXVK_HUD", "fps", R.string.game_env_hud, Type.MULTIPLE, listOf("scale=0.5", "scale=0.7", "opacity=0.5", "opacity=0.7", "devinfo", "fps", "frametimes", "submissions", "drawcalls", "pipelines", "descriptors", "memory", "gpuload", "version", "api", "cs", "compiler", "samplers")),
Option("DXVK_CONFIG", "dxvk.maxFrameRate = 60", R.string.game_env_dxvk_config, Type.TEXT),
Option("VKD3D_FRAME_RATE", "60", R.string.game_env_vkd3d_limit, Type.NUMBER),
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.os.Process
import android.util.Log
import java.io.BufferedWriter
@@ -113,7 +114,17 @@ object SessionLogCapture {
}
}
fun dumpMemoryPressure(target: File) {
internal const val LMKD_COMMAND = "logcat -d -b main,events -v threadtime -s lowmemorykiller:D killinfo:I" +
" | grep -v -E 'pgskip|zoneinfo_parse|polling check|thrashing:' | tail -n 120"
private fun lowMemoryKiller(context: Context?): String = when {
context == null -> "(not captured)\n"
!WirelessAdbFix.hasSavedPairing(context) -> "(not captured: pair DroidDeck with Wireless debugging in Settings > Diagnostics)\n"
else -> runCatching { WirelessAdbFix.shell(context, LMKD_COMMAND) }
.fold({ it.ifBlank { "(no lmkd lines in the log)\n" } }, { "(not captured: ${it.message})\n" })
}
fun dumpMemoryPressure(target: File, context: Context? = null) {
var temporary: File? = null
try {
val staged = File.createTempFile(target.name, ".part", target.parentFile).also { temporary = it }
@@ -150,7 +161,8 @@ object SessionLogCapture {
body.isNotEmpty() -> body
else -> "(no readable events were returned)\n"
} +
"\n/proc/pressure/memory:\n$pressure\n/proc/meminfo:\n$meminfo\n/sys/class/kgsl/kgsl/page_alloc:\n$gpu"
"\n/proc/pressure/memory:\n$pressure\n/proc/meminfo:\n$meminfo\n/sys/class/kgsl/kgsl/page_alloc:\n$gpu" +
"\nAndroid's low memory killer (lmkd), read over Wireless debugging:\n${lowMemoryKiller(context)}"
)
Files.move(
staged.toPath(), target.toPath(),
@@ -37,7 +37,7 @@ object SteamIntegration {
locationOn = WifiDiscovery.locationEnabled(context),
brightness = Settings.System.canWrite(context),
home = HomeApp.isDefault(context),
shortcuts = shortcutsEnabled(context),
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
shortcutsRestricted = restrictedSettings(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
)
@@ -61,6 +61,10 @@ object SteamIntegration {
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == shortcutsComponent }
}
@Suppress("DEPRECATION")
fun shortcutsCurrent(context: Context): Boolean =
runCatching { context.packageManager.getPackageInfo(Relay.PACKAGE, 0).versionCode }.getOrDefault(0) >= Relay.VERSION
fun shortcutsListed(context: Context): Boolean =
context.getSystemService(android.view.accessibility.AccessibilityManager::class.java)
?.installedAccessibilityServiceList.orEmpty()
@@ -235,6 +235,17 @@ object WirelessAdbFix {
fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
fun savedPairingIsLocal(context: Context): Boolean = savedConnection(context.applicationContext)?.host
?.let { host ->
// Unlike isLocalAddress, an address that cannot be matched to this device's own counts as remote.
runCatching {
val address = InetAddress.getByName(host)
address.isLoopbackAddress || NetworkInterface.getNetworkInterfaces().toList().any { network ->
network.inetAddresses.toList().any { it.address.contentEquals(address.address) }
}
}.getOrDefault(false)
} == true
fun clearCachedApps(context: Context) {
shell(context, "am kill-all")
}
@@ -13,6 +13,7 @@ import android.provider.DocumentsContract.Root
import android.provider.DocumentsProvider
import android.webkit.MimeTypeMap
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
@@ -26,11 +27,21 @@ import java.nio.file.attribute.BasicFileAttributes
class AppFilesProvider : DocumentsProvider() {
private lateinit var base: File
private lateinit var baseCanonical: String
private lateinit var privatePaths: List<String>
override fun attachInfo(context: Context, info: ProviderInfo) {
super.attachInfo(context, info)
base = context.dataDir
baseCanonical = base.canonicalPath
// The wireless ADB pairing identity, preferences, store logins and Steam's saved login stay app-only.
privatePaths = listOf(
context.noBackupFilesDir,
File(base, "shared_prefs"),
context.getDatabasePath("x").parentFile!!,
File(context.filesDir, "stores"),
File(SessionPrefs.steamRoot(context, "arm64"), "config"),
File(SessionPrefs.steamRoot(context, "x86_64"), "config"),
).flatMap { listOf(it.absoluteFile.normalize().path, runCatching { it.canonicalPath }.getOrDefault(it.path)) }.distinct()
}
override fun onCreate() = true
@@ -74,6 +85,7 @@ class AppFilesProvider : DocumentsProvider() {
var file = File(parent, name)
var n = 2
while (file.exists()) file = File(parent, "$name (${n++})")
if (isPrivate(file)) throw FileNotFoundException("could not create ${file.path}")
val made = try {
if (mimeType == Document.MIME_TYPE_DIR) file.mkdir() else file.createNewFile()
} catch (e: IOException) {
@@ -85,7 +97,7 @@ class AppFilesProvider : DocumentsProvider() {
override fun deleteDocument(documentId: String) {
val file = fileFor(documentId)
if (file.canonicalPath == baseCanonical) throw FileNotFoundException("the app folder itself is not deleted")
if (file.canonicalPath == baseCanonical || holdsPrivate(file)) throw FileNotFoundException("$documentId holds the app's private files")
try {
deleteTree(file.toPath())
} catch (e: IOException) {
@@ -116,17 +128,19 @@ class AppFilesProvider : DocumentsProvider() {
override fun renameDocument(documentId: String, displayName: String): String {
val file = fileFor(documentId)
if (holdsPrivate(file)) throw FileNotFoundException("$documentId holds the app's private files")
val target = File(file.parentFile, displayName.substringAfterLast('/'))
if (target.exists() || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId")
if (target.exists() || isPrivate(target) || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId")
return target.absolutePath
}
override fun moveDocument(sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String): String {
val source = fileFor(sourceDocumentId)
if (holdsPrivate(source)) throw FileNotFoundException("$sourceDocumentId holds the app's private files")
val targetParent = fileFor(targetParentDocumentId)
if (!targetParent.isDirectory) throw FileNotFoundException("$targetParentDocumentId is not a folder")
val target = File(targetParent, source.name)
if (target.exists() || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId")
if (target.exists() || isPrivate(target) || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId")
return target.absolutePath
}
@@ -163,7 +177,19 @@ class AppFilesProvider : DocumentsProvider() {
val abs = f.absoluteFile.normalize().path
if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false
val real = runCatching { f.canonicalPath }.getOrNull() ?: return false
return real == baseCanonical || real.startsWith("$baseCanonical/")
if (real != baseCanonical && !real.startsWith("$baseCanonical/")) return false
return !isPrivate(f)
}
private fun isPrivate(f: File): Boolean {
val real = runCatching { f.canonicalPath }.getOrNull() ?: return true
val paths = listOf(f.absoluteFile.normalize().path, real)
return privatePaths.any { p -> paths.any { it == p || it.startsWith("$p/") } }
}
private fun holdsPrivate(f: File): Boolean {
val paths = listOfNotNull(f.absoluteFile.normalize().path, runCatching { f.canonicalPath }.getOrNull())
return privatePaths.any { p -> paths.any { p.startsWith("$it/") } }
}
private fun addRow(result: MatrixCursor, file: File) {
@@ -173,7 +199,7 @@ class AppFilesProvider : DocumentsProvider() {
} else if (file.canWrite()) {
flags = flags or Document.FLAG_SUPPORTS_WRITE
}
if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true) {
if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true && !holdsPrivate(file)) {
flags = flags or Document.FLAG_SUPPORTS_DELETE or Document.FLAG_SUPPORTS_RENAME or
Document.FLAG_SUPPORTS_MOVE or Document.FLAG_SUPPORTS_REMOVE
}
@@ -40,12 +40,10 @@ import androidx.compose.material.icons.filled.ContentPaste
import androidx.compose.material.icons.filled.CreateNewFolder
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.SdStorage
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.ViewList
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material.icons.filled.Storage
import androidx.compose.material.icons.filled.Smartphone
@@ -727,11 +725,15 @@ 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, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
val upEnabled = canGoUp && !cancellingNavigation
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = upEnabled, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
Icons.Filled.ArrowBack,
stringResource(R.string.fm_back),
tint = if (upEnabled) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f),
)
}
val currentDriveLabel = stringResource(describeLocation(currentDir).driveLabel)
@@ -794,113 +796,119 @@ fun FileManagerScreen(
Spacer(Modifier.width(4.dp))
if (showFavorites) {
Text(
text = stringResource(R.string.fm_favorites),
color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (!compactToolbar) Spacer(Modifier.weight(1f))
} else {
Text(
text = currentDir.name.ifBlank { currentDir.absolutePath },
color = MaterialTheme.colorScheme.onSurface,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
}
if (launchDir != null) {
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))
}
if (!showFavorites) {
if (!pickMode) {
OutlinedButton(
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).focusGlide(CircleShape),
) {
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(5.dp))
Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp)
}
}
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,
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.weight(1f)
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier),
) {
if (showFavorites) {
Text(
text = stringResource(R.string.fm_favorites),
color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (!compactToolbar) Spacer(Modifier.weight(1f))
} else {
Text(
text = currentDir.name.ifBlank { currentDir.absolutePath },
color = MaterialTheme.colorScheme.onSurface,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
}
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 }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size))
.forEach { (key, label) ->
DropdownMenuItem(
text = {
Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label)
},
onClick = {
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
browsePrefs.edit().putString("fmSortBy", sortBy)
.putBoolean("fmSortDesc", sortDesc).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
DropdownMenuItem(
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) },
onClick = {
compactRows = !compactRows
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)) },
onClick = {
showHidden = !showHidden
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
}
}
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 {
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
if (launchDir != null) {
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))
}
if (!showFavorites) {
if (!pickMode) {
OutlinedButton(
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).focusGlide(CircleShape),
) {
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(5.dp))
Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp)
}
}
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 }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size))
.forEach { (key, label) ->
DropdownMenuItem(
text = {
Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label)
},
onClick = {
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
browsePrefs.edit().putString("fmSortBy", sortBy)
.putBoolean("fmSortDesc", sortDesc).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
DropdownMenuItem(
text = { Text(if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view)) },
onClick = {
gridView = !gridView
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
showSortMenu = false
},
modifier = Modifier.focusGlide(),
)
DropdownMenuItem(
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) },
onClick = {
compactRows = !compactRows
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)) },
onClick = {
showHidden = !showHidden
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
}
}
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 {
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
if (!pickMode && onExit != null) {
@@ -335,7 +335,10 @@ object AddedGames {
val path = canonical(exe)
val owner = ownerFolder(app, exe)
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let { return AddResult.Existing(it) }
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
if (guestPath(app, exe) != null) AddedExes.put(app, AddedExes.Entry(owner.path, exe.path))
return AddResult.Existing(it)
}
}
if (guestPath(app, exe) == null) {
(owner ?: exe.parentFile)?.takeIf { guestPath(app, it) == null }?.let { bindFolder(app, it) }
@@ -344,7 +347,7 @@ object AddedGames {
val folder = owner ?: exe.parentFile ?: return AddResult.NotFound
SessionPrefs.setAddedGameRemoved(app, folder.path, false)
SessionPrefs.setAddedGameExe(app, folder.path, exe.path)
if (owner == null) AddedExes.put(app, AddedExes.Entry(folder.path, exe.path))
AddedExes.put(app, AddedExes.Entry(folder.path, exe.path))
val game = single(app, folder.path) ?: return AddResult.NotFound
AddedGamesPublisher.later(app) { com.droiddeck.launcher.stores.SteamLiveShortcuts.sync(app, listOf(game)) { true } }
Log.i(TAG, "added ${game.name} from its exe")
@@ -2,6 +2,9 @@ package com.droiddeck.launcher.frontend
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import android.util.AtomicFile
import com.droiddeck.launcher.R
import androidx.core.util.readText
@@ -13,27 +16,65 @@ import java.io.InputStream
object GameFiles {
const val EXTENSION = "steam"
private const val MAX_BYTES = 128
private const val MAX_BYTES = 4096
private const val MAX_NAME_BYTES = 200
private const val INVENTORY = ".droiddeck-sync.json"
private const val FORMAT = "droiddeck-game-files-v1"
fun readIntent(context: Context, request: Intent): String? = runCatching {
fun readIntent(context: Context, request: Intent): GameRequest? = runCatching {
if (request.action != Intent.ACTION_VIEW) return null
val uri = request.data ?: return null
GameLaunchLink.parse(uri.toString())?.let { return it }
GameRequest.link(uri.toString())?.let { return GameRequest(it) }
val name = displayName(context, uri)
val extension = name?.substringAfterLast('.', "").orEmpty()
if (extension.lowercase(java.util.Locale.ROOT) in GameRequest.PROGRAMS) {
val program = localFile(context, uri)?.takeIf { it.isFile } ?: return null
return GameRequest(title = name?.substringBeforeLast('.'), program = program.canonicalFile)
}
val stream = when (uri.scheme) {
"content" -> context.contentResolver.openInputStream(uri)
"file" -> {
if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) return null
File(uri.path ?: return null).inputStream()
}
null -> File(uri.toString()).takeIf { it.isAbsolute }?.inputStream()
"content" -> runCatching { context.contentResolver.openInputStream(uri) }.getOrNull()
?: localFile(context, uri)?.takeIf { it.isFile }?.inputStream()
"file", null -> localFile(context, uri)?.inputStream()
else -> null
} ?: return null
stream.use(::read)
val id = stream.use(::read) ?: return null
GameRequest(id, GameRequest.sourceOf(extension), name?.substringBeforeLast('.'))
}.getOrNull()
private fun displayName(context: Context, uri: Uri): String? = when (uri.scheme) {
"content" -> runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
}
}.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/')?.substringAfterLast(':')
"file" -> uri.path?.let { File(it).name }
null -> File(uri.toString()).name
else -> null
}?.takeIf { it.isNotEmpty() }
private fun localFile(context: Context, uri: Uri): File? = when (uri.scheme) {
"file" -> {
if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) null
else uri.path?.let(::File)
}
null -> File(uri.toString()).takeIf { it.isAbsolute }
"content" -> storageDocument(context, uri) ?: uri.pathSegments.let { parts ->
(0..1).asSequence().map { File("/" + parts.drop(it).joinToString("/")) }.firstOrNull { it.isFile }
}
else -> null
}
// Frontends pass SAF document URIs or FileProvider URIs whose path mirrors shared storage.
private fun storageDocument(context: Context, uri: Uri): File? {
if (uri.authority != "com.android.externalstorage.documents" || !DocumentsContract.isDocumentUri(context, uri)) return null
val id = DocumentsContract.getDocumentId(uri)
val volume = id.substringBefore(':')
val path = id.substringAfter(':', "")
val root = if (volume.equals("primary", ignoreCase = true)) android.os.Environment.getExternalStorageDirectory()
else File("/storage", volume)
return File(root, path)
}
fun read(stream: InputStream): String? {
val bytes = ByteArray(MAX_BYTES + 1)
var count = 0
@@ -44,8 +85,7 @@ object GameFiles {
count += n
}
if (count > MAX_BYTES) return null
val text = String(bytes, 0, count, Charsets.UTF_8).trim()
return text.takeIf(GameLaunchLink::validId)
return GameRequest.parse(String(bytes, 0, count, Charsets.UTF_8))
}
fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String {
@@ -61,7 +101,7 @@ object GameFiles {
}
val title = String(points, 0, end).trimEnd { it.isWhitespace() || it == '.' }.ifBlank { "Game" }
val suffix = if (disambiguate) " (${game.gameIdString})" else ""
return "$title$suffix.$EXTENSION"
return "$title$suffix.${GameRequest.extension(game)}"
}
private fun contents(id: String): String {
@@ -130,7 +170,7 @@ object GameFiles {
}
for (name in previous.keys()) {
val id = previous.getString(name)
if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) {
if (!next.has(name) && ours(name) && GameLaunchLink.validId(id)) {
val file = child(context, folder, name)
if (matches(file, contents(id))) {
val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) }
@@ -141,6 +181,9 @@ object GameFiles {
if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString())
}
private fun ours(name: String) = name.substringAfterLast('.', "").lowercase(java.util.Locale.ROOT)
.let { it == EXTENSION || it in GameRequest.extensions }
private fun inventoryOwns(context: Context, folder: File, record: JSONObject, file: File, id: String): Boolean {
if (record.optString(file.name) == id) return true
if (!file.exists()) return false
@@ -11,22 +11,26 @@ object GameLaunchIntent {
fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION
fun read(context: Context, intent: Intent): String? = when (intent.action) {
fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) {
Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent)
ACTION, GAMENATIVE_ACTION -> readId(intent)
ACTION, GAMENATIVE_ACTION -> readExtras(intent)
else -> null
}
@Suppress("DEPRECATION")
internal fun readId(intent: Intent): String? = runCatching {
internal fun readExtras(intent: Intent): GameRequest? = runCatching {
if (intent.action != ACTION && intent.action != GAMENATIVE_ACTION) return null
val source = intent.extras?.get(EXTRA_GAME_SOURCE)
if (source != null && (source !is String || !source.equals("STEAM", ignoreCase = true))) return null
val source = when (val value = intent.extras?.get(EXTRA_GAME_SOURCE)) {
null -> Library.SOURCE_STEAM
is String -> GameRequest.sourceNamed(value) ?: return null
else -> return null
}
val id = when (val value = intent.extras?.get(EXTRA_APP_ID)) {
is Int -> value.takeIf { it > 0 }?.toString()
is Long -> value.takeIf { it != 0L }?.let(java.lang.Long::toUnsignedString)
is String -> value.takeIf(GameLaunchLink::validId)
else -> null
}
id
} ?: return null
GameRequest(id, source)
}.getOrNull()
}
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.stores.Store
import java.io.File
import java.util.Locale
class GameRequest(
val id: String? = null,
val source: String = Library.SOURCE_STEAM,
val title: String? = null,
val program: File? = null,
) {
fun find(games: List<Library.SteamGame>, byTitle: Boolean = true): Library.SteamGame? {
program?.let { return owner(games, it) }
val exact = id?.let { id -> games.firstOrNull { it.gameIdString == id } }
if (source == Library.SOURCE_STEAM) return exact ?: games.firstOrNull { it.appId > 0 && it.appId.toString() == id }
exact?.takeIf { it.source == source }?.let { return it }
id?.let { id -> games.firstOrNull { it.source == source && it.storeId == id } }?.let { return it }
if (!byTitle) return null
val key = title?.let(::titleKey)?.takeIf { it.isNotEmpty() } ?: return null
return games.firstOrNull { it.source == source && titleKey(it.name) == key }
}
private fun owner(games: List<Library.SteamGame>, program: File): Library.SteamGame? {
val path = program.path
return games.mapNotNull { game ->
val folder = game.gameFiles ?: return@mapNotNull null
val dir = folder.absolutePath.takeIf { inside(path, it) }
?: runCatching { folder.canonicalPath }.getOrNull()?.takeIf { inside(path, it) }
dir?.let { game to it.length }
}.maxByOrNull { it.second }?.first
}
companion object {
val PROGRAMS = setOf("exe", "bat")
private const val CUSTOM_GAME = "CUSTOM_GAME"
private const val CUSTOM_EXTENSION = "pcgame"
private val DAIJISHOU = setOf("# Daijishou Player Template", "# DST")
private val daijishouId = Regex("""(?i)\[steamappid]\s*([0-9]+)""")
private val steamLink = Regex("steam://rungameid/([1-9][0-9]{0,19})")
val extensions: Set<String> = Store.entries.map { it.id }.toSet() + CUSTOM_EXTENSION
fun extension(game: Library.SteamGame): String = Store.byId(game.source)?.id ?: GameFiles.EXTENSION
fun sourceNamed(value: String): String? = when {
value.equals(Library.SOURCE_STEAM, ignoreCase = true) -> Library.SOURCE_STEAM
value.equals(CUSTOM_GAME, ignoreCase = true) -> Library.ADDED
else -> Store.entries.firstOrNull { it.name.equals(value, ignoreCase = true) }?.id
}
fun sourceOf(extension: String): String = when (val ext = extension.lowercase(Locale.ROOT)) {
CUSTOM_EXTENSION -> Library.ADDED
else -> Store.byId(ext)?.id ?: Library.SOURCE_STEAM
}
fun link(text: String): String? = text.takeIf(GameLaunchLink::validId)
?: GameLaunchLink.parse(text)
?: steamLink.matchEntire(text)?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId)
fun parse(text: String): String? {
link(text.trim())?.let { return it }
val lines = text.lines().map { it.trim() }.filter { it.isNotEmpty() }
val header = lines.firstOrNull() ?: return null
return when {
DAIJISHOU.any { header.equals(it, ignoreCase = true) } -> lines.firstNotNullOfOrNull { daijishouId.matchEntire(it) }
?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId)
header.equals("[InternetShortcut]", ignoreCase = true) -> lines.firstOrNull { it.startsWith("URL=", ignoreCase = true) }
?.substring(4)?.trim()?.takeIf { !GameLaunchLink.validId(it) }?.let(::link)
else -> null
}
}
internal fun titleKey(name: String): String = name.lowercase(Locale.ROOT).filter { it.isLetterOrDigit() }
private fun inside(path: String, dir: String) = path.startsWith(dir.trimEnd(File.separatorChar) + File.separator)
}
}
@@ -222,16 +222,7 @@ object Library {
internal fun concealedSteamApps(root: File): Set<Long> {
val config = AddedGames.accountConfig(root) ?: return emptySet()
val hidden = runCatching {
val entries = org.json.JSONArray(File(config, "cloudstorage/cloud-storage-namespace-1.json").readText())
val entry = (0 until entries.length()).map { entries.getJSONArray(it) }
.firstOrNull { it.optString(0) == "user-collections.hidden" }?.optJSONObject(1)
if (entry == null || entry.optBoolean("is_deleted")) emptySet() else {
val collection = org.json.JSONObject(entry.optString("value"))
fun ids(key: String) = collection.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optLong(it) } }.orEmpty()
ids("added").toSet() - ids("removed").toSet()
}
}.getOrDefault(emptySet())
val hidden = SteamHidden.read(root)
val private = runCatching {
PRIVATE_APPS.find(File(config, "localconfig.vdf").readText())?.groupValues?.get(1)
?.split(',')?.mapNotNull { it.trim().toLongOrNull() }?.toSet()
@@ -302,6 +293,7 @@ object Library {
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, lastPlayed = maxOf(lastPlayed, recordedPlay(context, g.gameId)), gameFiles = g.folder,
protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory }
else if (g.source == com.droiddeck.launcher.stores.Store.UBISOFT.id) File(com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.prefix(context), "pfx").takeIf { it.isDirectory }
else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
source = g.source, storeId = g.storeId,
@@ -177,9 +177,10 @@ object SoundtrackCollections {
source = Library.SOURCE_COLLECTION, soundtrack = true,
)
fun games(context: Context, favoritesLabel: String): List<Library.SteamGame> {
fun games(context: Context, favoritesLabel: String, skipEmptyFavorites: Boolean = false): List<Library.SteamGame> {
val s = snapshot
return listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) + s.collections.map { game(context, it.id, it.name, it.tracks) }
val favorites = if (skipEmptyFavorites && s.favorites.isEmpty()) emptyList() else listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites))
return favorites + s.collections.map { game(context, it.id, it.name, it.tracks) }
}
fun album(context: Context, id: Int): Soundtrack.Album {
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.frontend
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
internal object SteamHidden {
private const val KEY = "user-collections.hidden"
private fun file(root: File): File? = AddedGames.accountConfig(root)?.let { File(it, "cloudstorage/cloud-storage-namespace-1.json") }
class Saved(val hidden: Set<Long>, val queued: Boolean)
private fun id(member: Any?): Long? = when (member) {
is Int -> member.toLong()
is Long -> member
is String -> member.toLongOrNull()
else -> null
}
private fun ids(collection: JSONObject, key: String, strict: Boolean): List<Long> {
if (!collection.has(key)) return emptyList()
val array = collection.optJSONArray(key) ?: throw IllegalStateException(key)
return (0 until array.length()).mapNotNull { index ->
id(array.get(index)) ?: if (strict) throw IllegalStateException(key) else null
}
}
fun read(root: File): Set<Long> = readOrNull(root).orEmpty()
fun readOrNull(root: File): Set<Long>? = runCatching {
val entries = JSONArray(file(root)?.readText() ?: return null)
val slot = (0 until entries.length()).map { entries.getJSONArray(it) }.firstOrNull { it.optString(0) == KEY }
val entry = slot?.optJSONObject(1)
if (slot != null && entry == null) return null
if (entry == null || entry.optBoolean("is_deleted")) emptySet() else {
val collection = JSONObject(entry.optString("value"))
ids(collection, "added", false).toSet() - ids(collection, "removed", false).toSet()
}
}.getOrNull()
fun write(root: File, appId: Long, hidden: Boolean, now: Long = System.currentTimeMillis() / 1000): Saved? = runCatching {
val target = file(root) ?: return null
val entries = JSONArray(target.readText())
val slot = (0 until entries.length()).firstOrNull { entries.getJSONArray(it).optString(0) == KEY }
val entry = if (slot == null) JSONObject().put("key", KEY) else entries.getJSONArray(slot).optJSONObject(1) ?: return null
val live = !entry.optBoolean("is_deleted")
val collection = if (live && entry.has("value")) JSONObject(entry.optString("value")) else JSONObject().put("id", "hidden")
val added = ids(collection, "added", true).filter { it != appId }
val removed = ids(collection, "removed", true).filter { it != appId }
collection.put("added", JSONArray(if (hidden) added + appId else added))
collection.put("removed", JSONArray(if (hidden) removed else removed + appId))
entry.put("value", collection.toString())
entry.put("timestamp", now)
entry.put("is_deleted", false)
entry.opt("version")?.toString()?.toLongOrNull()?.let { entry.put("version", (it + 1).toString()) }
if (slot == null) entries.put(JSONArray().put(KEY).put(entry))
val temp = File(target.parentFile, target.name + ".tmp")
temp.writeText(entries.toString())
if (!temp.renameTo(target)) {
temp.delete()
return null
}
Saved(ids(collection, "added", true).toSet() - ids(collection, "removed", true).toSet(), markModified(File(target.parentFile, "cloud-storage-namespace-1.modified.json")))
}.getOrNull()
private fun markModified(file: File): Boolean {
val pending = if (file.exists()) runCatching { JSONArray(file.readText()) }.getOrNull() ?: return false else JSONArray()
if ((0 until pending.length()).any { pending.optString(it) == KEY }) return true
val temp = File(file.parentFile, file.name + ".tmp")
val saved = runCatching {
temp.writeText(pending.put(KEY).toString())
temp.renameTo(file)
}.getOrDefault(false)
if (!saved) temp.delete()
return saved
}
}
@@ -37,22 +37,22 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
?.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 } ?: emptyList()
val gpuCandidates = gpuSources()
val gpu = gpuCandidates.firstOrNull { !it.startsWith("/proc/") && firstNumber(it) != null }
val stepSources = GpuLimits.stepSources()
val maxSources = GpuLimits.maxSources()
val minSources = GpuLimits.minSources()
val steps = GpuLimits.first(stepSources)
var ceiling = ceilingSource(maxSources)
val power = app().getSystemService(Context.POWER_SERVICE) as? PowerManager
val time = SimpleDateFormat("HH:mm:ss", Locale.US)
try {
FileWriter(logFile, true).use { w ->
w.write("== clocks: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.HARDWARE}), every ${PERIOD_MS / 1000}s\n")
w.write("cpu policies: ${policies.joinToString { p -> p.name + " " + (File(p, "related_cpus").readTextOrNull()?.trim() ?: "?") }}\n")
for (source in gpuCandidates) {
val f = File(source)
val state = when {
!f.exists() -> continue
firstNumber(source) != null -> "readable"
else -> "refused"
}
w.write("gpu source $source: $state\n")
}
probeLines("gpu source", gpuCandidates).forEach { w.write(it + "\n") }
w.write("gpu clock from: ${gpu ?: "nothing readable"}\n")
(probeLines("gpu limit", stepSources, ::firstStep) + probeLines("gpu limit", maxSources, ::limit) +
probeLines("gpu limit", minSources, ::firstStep)).distinct().forEach { w.write(it + "\n") }
limitLines(steps, ceiling, GpuLimits.first(minSources)).forEach { w.write(it + "\n") }
w.flush()
while (running && logFile.length() < MAX_BYTES) {
val line = StringBuilder(time.format(Date()))
@@ -63,7 +63,8 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
}
gpu?.let { line.append(" | gpu ${mhz(firstNumber(it))} MHz") }
if (ceiling == null) ceiling = ceilingSource(maxSources)?.also { w.write("gpu ceiling from: $it\n") }
line.append(gpuField(gpu, ceiling, steps?.mhz?.last()))
if (power != null && Build.VERSION.SDK_INT >= 29) {
line.append(" | thermal ${power.currentThermalStatus}")
if (Build.VERSION.SDK_INT >= 30) {
@@ -109,16 +110,41 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
return list.distinct()
}
internal fun probeLines(label: String, sources: List<String>, read: (String) -> Long? = ::firstNumber): List<String> = sources.mapNotNull { source ->
when {
!File(source).exists() -> null
read(source) != null -> "$label $source: readable"
else -> "$label $source: refused"
}
}
internal fun limitLines(steps: GpuLimits.Found?, ceiling: String?, floor: GpuLimits.Found?): List<String> = listOf(
"gpu steps: " + (steps?.let { "${it.mhz.joinToString(" ")} MHz from ${it.path}" } ?: "nothing readable"),
"gpu ceiling from: " + (ceiling ?: "nothing readable"),
"gpu floor: " + (floor?.let { "${it.mhz.first()} MHz from ${it.path}" } ?: "nothing readable"),
)
internal fun gpuField(clock: String?, ceiling: String?, top: Long?): String {
if (clock == null && ceiling == null) return ""
val field = StringBuilder(" | gpu ").append(mhz(clock?.let(::firstNumber)))
ceiling?.let(::limit)?.let { max ->
field.append('/').append(mhz(max))
if (top != null && GpuLimits.mhz(max) < top) field.append("(of $top)")
}
return field.append(" MHz").toString()
}
private fun File.readTextOrNull(): String? = runCatching { readText() }.getOrNull()
private fun firstNumber(path: String): Long? =
runCatching { Regex("\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
private fun mhz(raw: Long?): String = when {
raw == null -> "?"
raw > 10_000_000 -> (raw / 1_000_000).toString()
raw > 10_000 -> (raw / 1_000).toString()
else -> raw.toString()
}
internal fun limit(path: String): Long? = firstNumber(path)?.takeIf { it > 0 }
internal fun firstStep(path: String): Long? = GpuLimits.read(path).firstOrNull()
internal fun ceilingSource(sources: List<String>): String? = sources.firstOrNull { limit(it) != null }
private fun mhz(raw: Long?): String = raw?.let { GpuLimits.mhz(it).toString() } ?: "?"
}
}
@@ -87,20 +87,10 @@ object DeviceInfo {
private fun ghz(khz: Long) = String.format(Locale.US, "%.2f GHz", khz / 1e6)
private fun gpuRange(): String? {
fun mhz(hz: Long) = "${hz / 1_000_000} MHz"
val kgsl = read("/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies")
?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
if (kgsl.isNotEmpty()) return "${mhz(kgsl.min())}–${mhz(kgsl.max())} (${kgsl.size} steps)"
read("/sys/class/kgsl/kgsl-3d0/max_gpuclk")?.toLongOrNull()?.let { return "up to ${mhz(it)}" }
val node = File("/sys/class/devfreq").listFiles()?.firstOrNull { f ->
val n = f.name.lowercase()
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
} ?: return null
val steps = read("${node.path}/available_frequencies")?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
if (steps.isNotEmpty()) return "${mhz(steps.min())}–${mhz(steps.max())} (${steps.size} steps)"
val min = read("${node.path}/min_freq")?.toLongOrNull()
val max = read("${node.path}/max_freq")?.toLongOrNull() ?: return null
return (if (min != null) "${mhz(min)}–" else "up to ") + mhz(max)
GpuLimits.first(GpuLimits.stepSources())?.mhz?.let { return "${it.first()} MHz–${it.last()} MHz (${it.size} steps)" }
val max = GpuLimits.first(GpuLimits.maxSources())?.mhz?.last() ?: return null
val min = GpuLimits.first(GpuLimits.minSources())?.mhz?.first()
return (if (min != null) "$min MHz–" else "up to ") + "$max MHz"
}
private fun memory(context: Context) = Section("Memory", buildList<Pair<String, String>> {
@@ -18,6 +18,7 @@ object DriverPairs {
/** RADV-Xclipse rebased on JimVulkan's upstream: a manual choice, never Auto. */
const val NAD_RADV_XCLIPSE_UPSTREAM = "nad:radv-xclipse-upstream"
private val XCLIPSE_MODEL = Regex("""(?i)xclipse\s*(\d{3})\b""")
private val SUPPORTED_XCLIPSE_MODELS = setOf("530", "920", "940")
const val NAD_MALI_JM = "nad:panvk-mali-jm"
const val NAD_MALI_G710 = "nad:panvk-mali-g710"
const val NAD_MALI_G615 = "nad:panvk-mali-g615"
@@ -112,9 +113,12 @@ object DriverPairs {
}
}
/** 950 and 960 panic on the older build; a name without a model number is treated the same way. */
private fun xclipseNeedsUpstream(name: String): Boolean =
XCLIPSE_MODEL.find(name)?.groupValues?.get(1).let { it == null || it == "950" || it == "960" }
internal fun xclipseNeedsUpstream(name: String): Boolean =
XCLIPSE_MODEL.find(name)?.groupValues?.get(1) !in SUPPORTED_XCLIPSE_MODELS
fun autoEligible(gpu: GpuInfo, sdk: Int = android.os.Build.VERSION.SDK_INT): Boolean =
recommendedKey(gpu, emptyList(), sdk = sdk) != null ||
(gpu.family == Family.POWERVR && gpu.name.contains("Xclipse", ignoreCase = true))
fun recommendedKey(
gpu: GpuInfo, pairs: List<DriverPair>,
@@ -125,6 +129,7 @@ object DriverPairs {
Family.POWERVR -> return when {
!gpu.name.contains("Xclipse", ignoreCase = true) -> null
xclipseNeedsUpstream(gpu.name) && pairs.any { it.key == NAD_RADV_XCLIPSE_UPSTREAM } -> NAD_RADV_XCLIPSE_UPSTREAM
xclipseNeedsUpstream(gpu.name) -> null
else -> NAD_RADV_XCLIPSE
}
Family.MALI_OTHER, Family.NOT_ADRENO -> return null
@@ -118,9 +118,7 @@ data class GpuInfo(
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo(
name = when {
family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu ->
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
}
family == Family.POWERVR -> systemDriverName(SystemVulkanDriver.gpuName(), VulkanInfo.cachedOrNull())
mali != null && mali.isNotEmpty() -> mali
!adreno -> Build.HARDWARE.ifBlank { UNNAMED }
model > 0 -> "Adreno $model"
@@ -134,6 +132,9 @@ data class GpuInfo(
)
}
fun systemDriverName(gpu: String, vulkan: Map<String, String>?): String =
vulkan?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
internal fun verifiedOn(model: Int, device: String): Boolean =
model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true)
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.gpu
import java.io.File
object GpuLimits {
class Found(val path: String, val mhz: List<Long>)
private const val KGSL = "/sys/class/kgsl/kgsl-3d0"
private const val QCOM_GPU = "/sys/kernel/gpu"
fun stepSources(): List<String> = listOf(
"$KGSL/gpu_available_frequencies", "$KGSL/freq_table_mhz", "$KGSL/devfreq/available_frequencies", "$QCOM_GPU/gpu_freq_table",
) + devfreq("available_frequencies")
fun maxSources(): List<String> = listOf(
"$KGSL/max_gpuclk", "$KGSL/max_clock_mhz", "$KGSL/devfreq/max_freq", "$QCOM_GPU/gpu_max_clock",
) + devfreq("max_freq")
fun minSources(): List<String> = listOf(
"$KGSL/min_clock_mhz", "$KGSL/devfreq/min_freq", "$QCOM_GPU/gpu_min_clock",
) + devfreq("min_freq")
fun first(sources: List<String>): Found? =
sources.firstNotNullOfOrNull { path -> read(path).takeIf { it.isNotEmpty() }?.let { Found(path, it) } }
fun read(path: String): List<Long> = runCatching {
Regex("\\d+").findAll(File(path).readText()).map { mhz(it.value.toLong()) }.filter { it > 0 }.distinct().sorted().toList()
}.getOrDefault(emptyList())
fun mhz(raw: Long): Long = when {
raw > 10_000_000 -> raw / 1_000_000
raw > 10_000 -> raw / 1_000
else -> raw
}
private fun devfreq(file: String): List<String> =
File("/sys/class/devfreq").listFiles()?.filter { f ->
val n = f.name.lowercase()
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
}?.sortedBy { it.name }?.map { "${it.path}/$file" }.orEmpty()
}
@@ -12,7 +12,7 @@ import java.util.function.Supplier;
public final class LinuxVulkanDriver {
private static final String TAG = "LinuxVulkanDriver";
public static final String ENV = "BL_VK_DRIVER";
public static final String ENV = "DD_VK_DRIVER";
public static final String HELP_TEXT =
"The driver the Steam client, the games it launches and the desktop's programs render on, "
@@ -16,30 +16,36 @@ data class ScreenEffects(
val hdr: Boolean = false,
val deband: Boolean = false,
val debandStrength: Int = 100,
val fxaa: Boolean = false,
val aaMode: Int = AA_OFF,
val toon: Boolean = false,
val crt: Boolean = false,
val ntsc: Boolean = false,
) {
val fxaa: Boolean get() = aaMode == AA_FXAA
val smaa: Boolean get() = aaMode == AA_SMAA
val effectiveCas: Int get() = if (cas) casLevel else 0
val any: Boolean get() = brightness != 0 || contrast != 0 || abs(gamma - 1f) > 0.005f || saturation != 100 ||
effectiveCas > 0 || hdr || deband || fxaa || toon || crt || ntsc
effectiveCas > 0 || hdr || deband || aaMode != AA_OFF || toon || crt || ntsc
fun push(upscaler: Int) {
WaylandCompositor.nativeSetCas(cas, casLevel)
WaylandCompositor.nativeSetHdr(hdr)
WaylandCompositor.nativeSetDeband(deband, debandStrength)
WaylandCompositor.nativeSetScreenEffects(brightness.toFloat(), contrast.toFloat(), gamma, saturation.toFloat(), fxaa, toon, crt, ntsc)
WaylandCompositor.nativeSetScreenEffects(brightness.toFloat(), contrast.toFloat(), gamma, saturation.toFloat(), aaMode, toon, crt, ntsc)
WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(this, upscaler)?.name)
}
fun encode(): JSONObject = JSONObject()
.put("brightness", brightness).put("contrast", contrast).put("gamma", gamma.toDouble()).put("saturation", saturation)
.put("cas", cas).put("casLevel", casLevel).put("hdr", hdr).put("deband", deband).put("debandStrength", debandStrength)
.put("fxaa", fxaa).put("toon", toon).put("crt", crt).put("ntsc", ntsc)
.put("aaMode", aaMode).put("fxaa", fxaa).put("toon", toon).put("crt", crt).put("ntsc", ntsc)
companion object {
const val AA_OFF = 0
const val AA_FXAA = 1
const val AA_SMAA = 2
val OFF = ScreenEffects()
fun decode(json: JSONObject): ScreenEffects = ScreenEffects(
@@ -52,7 +58,7 @@ data class ScreenEffects(
hdr = json.optBoolean("hdr", false),
deband = json.optBoolean("deband", false),
debandStrength = json.optInt("debandStrength", 100).coerceIn(0, 200),
fxaa = json.optBoolean("fxaa", false),
aaMode = json.optInt("aaMode", if (json.optBoolean("fxaa", false)) AA_FXAA else AA_OFF).coerceIn(AA_OFF, AA_SMAA),
toon = json.optBoolean("toon", false),
crt = json.optBoolean("crt", false),
ntsc = json.optBoolean("ntsc", false),
@@ -79,13 +85,13 @@ object ScreenEffectLooks {
desc = "Sharpening with a touch of contrast - the everyday one.", label = R.string.look_game_clarity, descRes = R.string.look_game_clarity_desc),
Look("Vivid", ScreenEffects(brightness = 3, contrast = 10, gamma = 0.98f, saturation = 145, cas = true, casLevel = 30, deband = true),
desc = "Colour pushed hard. Deband on so skies don't stripe.", label = R.string.look_vivid, descRes = R.string.look_vivid_desc),
Look("Cinematic", ScreenEffects(brightness = -4, contrast = 22, gamma = 1.10f, saturation = 88, cas = true, casLevel = 20, fxaa = true, deband = true),
Look("Cinematic", ScreenEffects(brightness = -4, contrast = 22, gamma = 1.10f, saturation = 88, cas = true, casLevel = 20, aaMode = ScreenEffects.AA_FXAA, deband = true),
desc = "Deeper contrast, cooler colour, edges smoothed.", label = R.string.look_cinematic, descRes = R.string.look_cinematic_desc),
Look("Competitive", ScreenEffects(brightness = 16, contrast = 18, gamma = 0.92f, saturation = 82, cas = true, casLevel = 75),
desc = "Shadows lifted and heavy sharpening - spot people first.", label = R.string.look_competitive, descRes = R.string.look_competitive_desc),
Look("Adaptive Sharpen", ScreenEffects(cas = true, casLevel = 85),
desc = "Sharpening only, colour untouched.", label = R.string.look_adaptive_sharpen, descRes = R.string.look_adaptive_sharpen_desc),
Look("Filmic", ScreenEffects(brightness = -2, contrast = 16, gamma = 1.14f, saturation = 92, cas = true, casLevel = 15, fxaa = true, deband = true),
Look("Filmic", ScreenEffects(brightness = -2, contrast = 16, gamma = 1.14f, saturation = 92, cas = true, casLevel = 15, aaMode = ScreenEffects.AA_FXAA, deband = true),
desc = "Film-like curve, slightly muted.", label = R.string.look_filmic, descRes = R.string.look_filmic_desc),
Look("Arcade", ScreenEffects(brightness = 6, contrast = 20, gamma = 0.95f, saturation = 170, cas = true, casLevel = 45, deband = true),
desc = "Loud and punchy.", label = R.string.look_arcade, descRes = R.string.look_arcade_desc),
@@ -103,7 +109,7 @@ object ScreenEffectLooks {
val t = l.effects
t.brightness == e.brightness && t.contrast == e.contrast && abs(t.gamma - e.gamma) < 0.005f &&
t.saturation == e.saturation && t.effectiveCas == e.effectiveCas &&
t.fxaa == e.fxaa && t.crt == e.crt && t.toon == e.toon && t.ntsc == e.ntsc && t.deband == e.deband &&
t.aaMode == e.aaMode && t.crt == e.crt && t.toon == e.toon && t.ntsc == e.ntsc && t.deband == e.deband &&
(l.scalingMode == null || l.scalingMode == upscaler)
}
}
@@ -256,12 +256,12 @@ public final class SystemVulkanDriver {
if (xclipse) environment.add("DROIDDECK_HYBRIS_DXVK=dxvk-2.6.2");
// The Android driver has a render node, but no KMS primary node. SDL presents
// through the wrapper's Wayland Vulkan swapchain instead of a KMS-style path.
environment.add("BL_GAMESCOPE_BACKEND=sdl");
environment.add("DD_GAMESCOPE_BACKEND=sdl");
// The Android pvr kernel accepts Vulkan DMA-BUF imports but rejects PRIME GEM handles.
environment.add("BL_POWERVR_DRM_HANDLES=1");
environment.add("BL_POWERVR_RENDER_NODE=" + node);
environment.add("DD_POWERVR_DRM_HANDLES=1");
environment.add("DD_POWERVR_RENDER_NODE=" + node);
// Inner Gamescope/Xwayland lacks the bridge's Android-buffer WSI protocols.
environment.add("BL_STEAM_GL_PRESENT=1");
environment.add("DD_STEAM_GL_PRESENT=1");
// Only actual Proton game launches use the bundled DXVK and X11 WSI layer.
environment.add("DROIDDECK_POWERVR_RUNTIME=" + directory.getPath());
}
@@ -5,7 +5,7 @@ import com.droiddeck.launcher.session.SessionPrefs
internal object DroidDeckHudConfig {
val DEFAULTS: Map<String, String> = linkedMapOf(
"hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
"hudSize" to "minimal", "hudLocked" to "1", "hudHold" to "collapse", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
"hudOutline" to "40", "hudOutlineAccent" to "1",
"showGpuModel" to "1", "showGPULoad" to "1", "showCPUUsage" to "1", "showCPULoad" to "1",
"showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0",
@@ -18,6 +18,8 @@ internal object DroidDeckHudConfig {
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
)
const val HOLD_LOCKS = "lock"
private val NOT_READINGS = setOf("showCPULoad", "showRenderer", "fpsDecimal")
/** Orders saved before the GPU switch was named after the alias the HUD actually reads. */
@@ -119,6 +119,7 @@ class DroidDeckHudHost(context: Context) {
}
hud.setOnSizeCycledListener { size -> DroidDeckHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() }
hud.setOnDockChangedListener { token -> setDock(hud, DroidDeckHudDock.from(token)) }
hud.setOnHoldListener { rawX, rawY -> collapseAt(hud, rawX, rawY) }
hud.setOnScaledListener { percent ->
DroidDeckHudConfig.set(context, "hudScale", percent.toString())
onConfigChanged?.invoke()
@@ -291,7 +292,7 @@ class DroidDeckHudHost(context: Context) {
DroidDeckHudDock.RIGHT -> (maxX - hud.x) / hud.width
DroidDeckHudDock.TOP -> hud.y / hud.height
DroidDeckHudDock.BOTTOM -> (maxY - hud.y) / hud.height
DroidDeckHudDock.NONE -> 0f
DroidDeckHudDock.NONE, DroidDeckHudDock.FLOAT -> 0f
}
if (pulled >= 1f) { setDock(hud, DroidDeckHudDock.NONE); return }
wantX = hud.x; wantY = hud.y
@@ -375,12 +376,30 @@ class DroidDeckHudHost(context: Context) {
hud.scaleX = s; hud.scaleY = s
}
private fun setDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
private fun setDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, center: Pair<Float, Float>? = null) {
if (edge == hud.dock) return
animateDock(hud, edge) { commitDock(hud, edge) }
animateDock(hud, edge, center) { commitDock(hud, edge) }
}
private fun collapseAt(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
if (hud.dock != DroidDeckHudDock.NONE) return
val p = hud.parent as? View ?: return
val at = IntArray(2).also { p.getLocationOnScreen(it) }
val x = rawX - at[0]
val y = rawY - at[1]
val edge = if (snaps) nearestEdge(x, y, p.width.toFloat(), p.height.toFloat()) else DroidDeckHudDock.FLOAT
setDock(hud, edge, Pair(x, y))
}
private fun nearestEdge(x: Float, y: Float, width: Float, height: Float): DroidDeckHudDock = mapOf(
DroidDeckHudDock.LEFT to x,
DroidDeckHudDock.RIGHT to width - x,
DroidDeckHudDock.TOP to y,
DroidDeckHudDock.BOTTOM to height - y,
).minByOrNull { it.value }!!.key
private fun commitDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
snapping = false
val tabX = hud.x; val tabY = hud.y
if (edge != DroidDeckHudDock.NONE) {
val p = hud.parent as? View
@@ -407,12 +426,17 @@ class DroidDeckHudHost(context: Context) {
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
}
private fun animateDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, commit: () -> Unit) {
private fun animateDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, center: Pair<Float, Float>?, commit: () -> Unit) {
stopMotion(hud)
previewFade?.cancel(); previewFade = null
snapping = false
hud.alpha = 1f
val p = hud.parent as? View
if (edge != DroidDeckHudDock.NONE && center != null) {
val (tabW, tabH) = hud.dockTabSize()
wantX = center.first - tabW / 2f
wantY = center.second - tabH / 2f
}
if (Motion.scale == 0f || p == null || !hud.isLaidOut || hud.width <= 0) {
hud.scaleX = 1f; hud.scaleY = 1f
hud.setDockPreview(DroidDeckHudDock.NONE, 0f)
@@ -424,11 +448,14 @@ class DroidDeckHudHost(context: Context) {
hud.pivotX = 0f; hud.pivotY = 0f
hud.x = left; hud.y = top
val (tabW, tabH) = hud.dockTabSize()
wantX = left + (shownW - tabW) / 2f
wantY = top + (shownH - tabH) / 2f
if (center == null) {
wantX = left + (shownW - tabW) / 2f
wantY = top + (shownH - tabH) / 2f
}
val (tabX, tabY) = settled(p, edge, tabW, tabH)
val sx = tabW / hud.width; val sy = tabH / hud.height
val from = hud.dockPreviewBlend
snapping = true
hud.animate().x(tabX).y(tabY).scaleX(sx).scaleY(sy).setDuration(Motion.ms(220).toLong()).setInterpolator(EASE)
.setUpdateListener { hud.setDockPreview(edge, from + (1f - from) * it.animatedFraction) }
.withEndAction {
@@ -473,7 +500,7 @@ class DroidDeckHudHost(context: Context) {
DroidDeckHudDock.RIGHT -> x = maxX
DroidDeckHudDock.TOP -> y = 0f
DroidDeckHudDock.BOTTOM -> y = maxY
DroidDeckHudDock.NONE -> {}
DroidDeckHudDock.NONE, DroidDeckHudDock.FLOAT -> {}
}
return Pair(x, y)
}
@@ -118,7 +118,7 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
}
enum class DroidDeckHudDock(val token: String) {
NONE("none"), LEFT("left"), RIGHT("right"), TOP("top"), BOTTOM("bottom");
NONE("none"), LEFT("left"), RIGHT("right"), TOP("top"), BOTTOM("bottom"), FLOAT("float");
companion object {
fun from(token: String?): DroidDeckHudDock = values().firstOrNull { it.token == token } ?: NONE
@@ -191,6 +191,8 @@ class DroidDeckHudView(context: Context) : View(context) {
private var onMovedListener: BiConsumer<Float, Float>? = null
private var onSizeCycledListener: Consumer<String>? = null
private var onLockChangedListener: Consumer<Boolean>? = null
private var onHoldListener: BiConsumer<Float, Float>? = null
fun setOnHoldListener(l: BiConsumer<Float, Float>?) { onHoldListener = l }
fun setOnMovedListener(l: BiConsumer<Float, Float>?) { onMovedListener = l }
fun setOnSizeCycledListener(l: Consumer<String>?) { onSizeCycledListener = l }
fun setOnLockChangedListener(l: Consumer<Boolean>?) { onLockChangedListener = l }
@@ -209,6 +211,7 @@ class DroidDeckHudView(context: Context) : View(context) {
override fun onDragged(rawX: Float, rawY: Float) { onDraggedListener?.accept(rawX, rawY) }
override fun onFlung(velocityX: Float, velocityY: Float) { onFlungListener?.accept(velocityX, velocityY) }
override fun onLockChanged(locked: Boolean) { onLockChangedListener?.accept(locked) }
override fun onHold(rawX: Float, rawY: Float) { onHoldListener?.accept(rawX, rawY) }
override fun onPinch(factor: Float) {
val next = (scale * factor).coerceIn(MIN_SCALE, MAX_SCALE)
if (next == scale) return
@@ -224,6 +227,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private var tabStartX = 0f
private var tabStartY = 0f
private var tabDragging = false
private var tabPressed = false
private var onTabDraggedListener: BiConsumer<Float, Float>? = null
private var onTabDroppedListener: Runnable? = null
private var onTabDragCancelledListener: Runnable? = null
@@ -237,19 +241,24 @@ class DroidDeckHudView(context: Context) : View(context) {
tabDownRawX = event.rawX; tabDownRawY = event.rawY
tabStartX = x; tabStartY = y
tabDragging = false
tabPressed = true
}
MotionEvent.ACTION_MOVE -> {
MotionEvent.ACTION_MOVE -> if (tabPressed) {
val dx = event.rawX - tabDownRawX; val dy = event.rawY - tabDownRawY
if (!tabDragging && dx * dx + dy * dy > touchSlop * touchSlop) tabDragging = true
if (tabDragging) onTabDraggedListener?.accept(tabStartX + dx, tabStartY + dy)
}
MotionEvent.ACTION_UP -> {
MotionEvent.ACTION_UP -> if (tabPressed) {
tabPressed = false
if (tabDragging) { tabDragging = false; onTabDroppedListener?.run() }
else onDockChangedListener?.accept(DroidDeckHudDock.NONE.token)
}
MotionEvent.ACTION_CANCEL -> if (tabDragging) {
tabDragging = false
onTabDragCancelledListener?.run()
MotionEvent.ACTION_CANCEL -> {
tabPressed = false
if (tabDragging) {
tabDragging = false
onTabDragCancelledListener?.run()
}
}
}
return true
@@ -341,6 +350,7 @@ class DroidDeckHudView(context: Context) : View(context) {
showSession = switchOn("showSession")
tempDisplay = HudMetrics.TempDisplay.from(cfg)
lockController.setLocked(cfg.get("hudLocked", "1") == "1")
lockController.setHoldLocks(cfg.get("hudHold", "collapse") == DroidDeckHudConfig.HOLD_LOCKS)
dock = DroidDeckHudDock.from(cfg.get("hudDock", "none"))
colorIntensity = when (cfg.get("hudColor", "vivid")) {
@@ -591,7 +601,7 @@ class DroidDeckHudView(context: Context) : View(context) {
DroidDeckHudDock.RIGHT -> intArrayOf(1, 2)
DroidDeckHudDock.TOP -> intArrayOf(0, 1)
DroidDeckHudDock.BOTTOM -> intArrayOf(2, 3)
DroidDeckHudDock.NONE -> intArrayOf()
DroidDeckHudDock.NONE, DroidDeckHudDock.FLOAT -> intArrayOf()
}
for (corner in edge) { round[corner * 2] = 0f; round[corner * 2 + 1] = 0f }
tabPath.rewind()
@@ -275,7 +275,7 @@ internal class GameFrameFeed(
private const val INFO_NS = 500_000_000L
private const val SHIFT_NS = 1_000_000_000L
private const val SHIFT_RECHECK_NS = 100_000_000L
private const val CLOCK_CONTROL_PATH = "tmp/.bl-clock"
private const val CLOCK_CONTROL_PATH = "tmp/.dd-clock"
fun forRoot(root: File) = GameFrameFeed(File(root, HudFrames.PATH), clockControl = File(root, CLOCK_CONTROL_PATH))
@@ -36,6 +36,7 @@ public class HudLockController {
default void onDragged(float rawX, float rawY) {}
default void onFlung(float velocityX, float velocityY) {}
void onLockChanged(boolean locked);
default void onHold(float rawX, float rawY) {}
default void onPinch(float factor) {}
default void onPinchEnd() {}
}
@@ -53,6 +54,7 @@ public class HudLockController {
private final android.view.VelocityTracker velocity = android.view.VelocityTracker.obtain();
private boolean locked = false;
private boolean holdLocks = false;
private float downRawX, downRawY, startX, startY;
private boolean dragging = false;
@@ -80,6 +82,8 @@ public class HudLockController {
public void setLocked(boolean locked) { this.locked = locked; }
public void setHoldLocks(boolean holdLocks) { this.holdLocks = holdLocks; }
public boolean isLocked() { return locked; }
public boolean isDragging() { return dragging; }
@@ -119,6 +123,10 @@ public class HudLockController {
@Override
public void onLongPress(MotionEvent e) {
if (!holdLocks) {
cb.onHold(e.getRawX(), e.getRawY());
return;
}
locked = !locked;
cb.onLockChanged(locked);
flash(locked, HOLD_TOGGLE_MS);
@@ -7,21 +7,6 @@ object ControllerPrefs {
const val STEAM_BLUE = 0xFF1A9FFF.toInt()
const val OFF = "off"
val tints = listOf(
STEAM_BLUE to R.string.ctrl_tint_steam_blue,
0xFF66C0F4.toInt() to R.string.ctrl_tint_sky,
0xFFE8EEF4.toInt() to R.string.ctrl_tint_white,
0xFFC77DFF.toInt() to R.string.ctrl_tint_violet,
0xFF3DDC84.toInt() to R.string.ctrl_tint_green,
0xFFFFA726.toInt() to R.string.ctrl_tint_amber,
0xFFFF5252.toInt() to R.string.ctrl_tint_red,
0xFFFF6FB5.toInt() to R.string.ctrl_tint_pink,
)
val opacities = listOf(40, 60, 80, 100)
val sizes = listOf(80, 90, 100, 110, 125)
val deadZones = listOf(0, 5, 8, 12, 15, 20, 25)
const val DEFAULT_DEAD_ZONE_PERCENT = 12
@@ -39,20 +24,15 @@ object ControllerPrefs {
OFF to R.string.ctrl_target_hidden,
)
/** Settings still read: the rest only seed the one-time library and layout migrations. */
class Settings(
val tint: Int,
val opacity: Int,
val size: Int,
val stickClick: Boolean,
val adaptiveSticks: Boolean,
val rumble: Boolean,
val steamButton: Boolean,
val qamButton: Boolean,
val keyboardButton: Boolean,
val selectSteam: Boolean,
val joyConVr: Boolean,
val snap: Boolean,
val customLayout: Boolean,
val mapping: Map<String, String>,
val deadZone: Int,
)
@@ -63,50 +43,17 @@ object ControllerPrefs {
val p = prefs(context)
return Settings(
tint = p.getInt("tint", STEAM_BLUE),
opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100,
size = p.getInt("size", 100).takeIf { it in sizes } ?: 100,
opacity = p.getInt("opacity", 100).coerceIn(1, 100),
stickClick = p.getBoolean("stickClick", true),
adaptiveSticks = p.getBoolean("adaptiveSticks", true),
rumble = rumbleEnabled(context),
steamButton = p.getBoolean("steamButton", true),
qamButton = p.getBoolean("qamButton", true),
keyboardButton = p.getBoolean("keyboardButton", true),
selectSteam = p.getBoolean("selectSteam", false),
joyConVr = joyConVr(context),
snap = snap(context),
customLayout = p.all.keys.any { it.startsWith("layout.") },
mapping = mappable.associate { (id, _) -> id to target(context, id) },
mapping = mappable.associate { (id, _) -> id to (p.getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id) },
deadZone = deadZone(context),
)
}
fun target(context: Context, id: String): String =
prefs(context).getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id
fun setTarget(context: Context, id: String, target: String) {
prefs(context).edit().putString("map.$id", target).apply()
}
fun setTint(context: Context, tint: Int) {
prefs(context).edit().putInt("tint", tint).apply()
}
fun setOpacity(context: Context, percent: Int) {
prefs(context).edit().putInt("opacity", percent).apply()
}
fun setSize(context: Context, percent: Int) {
prefs(context).edit().putInt("size", percent).apply()
}
fun setStickClick(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("stickClick", on).apply()
}
fun setAdaptiveSticks(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
}
fun rumbleEnabled(context: Context): Boolean = prefs(context).getBoolean("rumble", true)
fun deadZone(context: Context): Int =
@@ -120,18 +67,6 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("rumble", on).apply()
}
fun setSteamButton(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("steamButton", on).apply()
}
fun setKeyboardButton(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("keyboardButton", on).apply()
}
fun setSelectSteam(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("selectSteam", on).apply()
}
fun joyConVr(context: Context): Boolean = prefs(context).getBoolean("joyConVr", true)
fun setJoyConVr(context: Context, on: Boolean) {
@@ -144,24 +79,6 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("snap", on).apply()
}
fun layout(context: Context, width: Int, height: Int): Map<String, Pair<Float, Float>> {
val raw = prefs(context).getString("layout.${width}x$height", null) ?: return emptyMap()
return raw.split(';').mapNotNull { entry ->
val (group, pos) = entry.split(':').takeIf { it.size == 2 } ?: return@mapNotNull null
val (x, y) = pos.split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 2 } ?: return@mapNotNull null
group to (x to y)
}.toMap()
}
fun setLayout(context: Context, width: Int, height: Int, positions: Map<String, Pair<Float, Float>>) {
val raw = positions.entries.joinToString(";") { (group, pos) -> "$group:${pos.first},${pos.second}" }
prefs(context).edit().putString("layout.${width}x$height", raw).apply()
}
fun resetLayout(context: Context, width: Int, height: Int) {
prefs(context).edit().remove("layout.${width}x$height").apply()
}
fun resetAll(context: Context) {
prefs(context).edit().clear().putBoolean("rumble", true).apply()
}
@@ -0,0 +1,123 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/** The on-screen layout each game draws, shared by the in-game Controller page and Settings › Controller. A null game is the default. */
object ControlsChoice {
const val NEW = "new"
const val DEFAULT = "default"
data class Game(val id: Long, val name: String, val layout: String)
private fun own(library: InputLibrary, id: String?): String? = id?.takeIf { bindings ->
library.bindings.any { it.id == bindings && !it.physical && it.layoutId?.let { l -> library.layouts.any { x -> x.id == l && x.supports(InputRole.PRIMARY) } } == true }
}
private fun own(context: Context, library: InputLibrary, game: Long?) = own(library, GameControls.bindings(context, game))
/** The input library with [game]'s main-screen layout selected, without saving it. */
fun library(context: Context, game: Long?, desktop: Boolean): InputLibrary {
val library = InputLibraries.read(context)
val chosen = own(context, library, game)
return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen)
}
fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null): List<Pair<String, String>> {
val library = InputLibraries.read(context)
val own = game != null && game in GameControls.games(context)
return (if (own) listOf(DEFAULT to context.getString(R.string.osc_default)) else emptyList()) +
listOf(InputLibraries.OVERLAY to context.getString(R.string.osc_layout_gamepad)) +
(if (steamMode) listOf(GameControls.STEAM to context.getString(R.string.osc_layout_steam)) else emptyList()) +
library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }.map { it.id to it.name } +
(if (game != null && !gameName.isNullOrBlank()) listOf(NEW to context.getString(R.string.osc_layout_new_for, gameName)) else emptyList())
}
fun current(context: Context, game: Long?, steamMode: Boolean, desktop: Boolean = false): String =
if (steamMode && GameControls.steamLayout(context, game)) GameControls.STEAM
else library(context, game, desktop).activeLayout(desktop, InputRole.PRIMARY)?.id ?: InputLibraries.OVERLAY
fun choose(context: Context, game: Long?, id: String, desktop: Boolean, gameName: String? = null) {
require(id != NEW)
if (id == DEFAULT) { if (game != null) useDefault(context, game); return }
val steam = id == GameControls.STEAM
val bindings = if (steam) null else {
val library = InputLibraries.read(context)
val layout = library.layouts.first { it.id == id }
library.bindings.firstOrNull { !it.physical && it.layoutId == layout.id && it.compatible(layout) }?.id ?: newInputId().also { newId ->
InputLibraries.update(context) { it.withPreset(SavedInputBindings(newId, layout.name, false, layout.id)) }
}
}
if (game != null) GameControls.choose(context, game, bindings, steam, gameName)
else {
if (bindings != null) InputLibraries.update(context) { it.selectPart(desktop, InputRole.PRIMARY, bindings) }
SessionPrefs.setSteamTouchLayout(context, steam)
}
}
/** Copies the layout [game] draws now, actions included, into a layout of its own and chooses it for that game only. */
fun newForGame(context: Context, game: Long, name: String, desktop: Boolean): Pair<String, String> {
val layoutId = newInputId()
val bindingsId = newInputId()
InputLibraries.update(context) { latest -> copyForGame(context, latest, game, name, desktop, layoutId, bindingsId) }
GameControls.choose(context, game, bindingsId, steam = false, name = name)
return layoutId to bindingsId
}
/** [latest] with a copy of the layout [game] draws now, actions included, under the given ids. Nothing is chosen for the game. */
fun copyForGame(context: Context, latest: InputLibrary, game: Long, name: String, desktop: Boolean, layoutId: String, bindingsId: String): InputLibrary {
run {
val chosen = own(context, latest, game)
val part = (if (chosen == null) latest else latest.selectPart(desktop, InputRole.PRIMARY, chosen)).activePart(desktop, InputRole.PRIMARY)
val source = latest.layouts.firstOrNull { it.id == part.layout && it.editable } ?: latest.layouts.first { it.id == InputLibraries.OVERLAY }
val actions = latest.bindings.firstOrNull { it.id == part.bindings && it.compatible(source) }
?: latest.bindings.firstOrNull { !it.physical && it.compatible(source) }
?: SavedInputBindings(bindingsId, source.name, false, source.id)
val title = name.trim().take(80).ifEmpty { source.name }
return latest.withLayout(source.derived(layoutId, title)).withPreset(actions.copy(id = bindingsId, name = title, layoutId = layoutId))
}
}
/** Uses [bindingsId], made by [copyForGame], for [game] only. */
fun useForGame(context: Context, game: Long, name: String, bindingsId: String) = GameControls.choose(context, game, bindingsId, steam = false, name = name)
/** The profile, layout and actions the editor opens for [game], or null when its layout can't be edited here. */
fun editTarget(context: Context, game: Long?, desktop: Boolean): Triple<String, String, String>? {
val library = library(context, game, desktop)
val layout = library.activeLayout(desktop, InputRole.PRIMARY)?.takeIf { it.editable } ?: return null
return Triple(library.activeId(desktop), layout.id, library.activePart(desktop, InputRole.PRIMARY).bindings)
}
/** Whether [game] has a layout of its own, rather than the default. */
fun hasOwn(context: Context, game: Long?): Boolean = own(context, InputLibraries.read(context), game) != null
/** Whether saving an edit of [game]'s layout would also change the default or another game. */
fun shared(context: Context, game: Long?): Boolean {
game ?: return false
val library = InputLibraries.read(context)
val bindings = own(context, library, game) ?: return true
val layout = library.preset(bindings).layoutId
fun drawsLayout(id: String) = library.bindings.firstOrNull { it.id == id }?.layoutId == layout
return library.usersOfLayout(layout ?: return true).isNotEmpty() ||
library.selections.values.any { s -> s.parts[InputRole.PRIMARY]?.let(::drawsLayout) == true } ||
GameControls.games(context).any { it != game && own(context, library, it)?.let(::drawsLayout) == true }
}
fun useDefault(context: Context, game: Long) = GameControls.clear(context, game)
/** Games with a layout of their own, by name. */
fun games(context: Context): List<Game> {
val library = InputLibraries.read(context)
return GameControls.games(context).mapNotNull { id ->
val layout = when {
GameControls.steamLayout(context, id) -> context.getString(R.string.osc_layout_steam)
else -> own(context, library, id)?.let { b -> library.layouts.firstOrNull { it.id == library.preset(b).layoutId }?.name } ?: return@mapNotNull null
}
val name = GameControls.name(context, id)
?: id.takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.let { runCatching { SteamTouchConfig.gameName(context, it.toInt()) }.getOrNull() }
?: id.toString()
Game(id, name, layout)
}.sortedBy { it.name.lowercase() }
}
}
@@ -0,0 +1,40 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
/** Decides where the on-screen controls go and why they're hidden, from the session's state alone. */
object ControlsPresenter {
enum class Place { NONE, MAIN, BOTTOM, STEAM }
data class State(
val mode: String,
val desktop: Boolean,
val virtualPad: Boolean,
val covered: Boolean,
val controllerInUse: Boolean,
val hiddenByTap: Boolean,
val steamLayout: Boolean,
val bottomScreen: Boolean,
)
data class Plan(val place: Place, val hidden: OnScreenControls.Hidden? = null) {
val shown get() = place != Place.NONE && hidden == null
}
fun plan(state: State): Plan = when {
state.covered || !state.virtualPad || state.mode == SessionPrefs.OSC_NEVER -> Plan(Place.NONE)
state.mode == SessionPrefs.OSC_AUTO && state.desktop -> Plan(Place.NONE)
else -> Plan(
when {
state.bottomScreen -> Place.BOTTOM
state.steamLayout -> Place.STEAM
else -> Place.MAIN
},
when {
state.hiddenByTap -> OnScreenControls.Hidden.BY_TAP
state.mode == SessionPrefs.OSC_AUTO && state.controllerInUse -> OnScreenControls.Hidden.BY_CONTROLLER
else -> null
},
)
}
}
@@ -82,6 +82,12 @@ object DualScreen {
fun sessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
display(context, displayManager, primaryDisplayId, SessionPrefs.dualScreenSessionMode(context))
fun selectedSessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, selectedDisplayId: Int): Display? =
displayManager.getDisplay(selectedDisplayId)?.takeIf {
SessionPrefs.dualScreenSessionMode(context) != MODE_OFF && it.isValid && it.displayId != primaryDisplayId &&
(it.flags and Display.FLAG_PRESENTATION) != 0 && !taken(it.displayId)
}
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
when (mode) {
MODE_OFF -> null
@@ -0,0 +1,36 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
/** Which on-screen layout each game uses. Games without a choice use the default profile's main-screen layout. */
object GameControls {
const val STEAM = "steam"
private fun prefs(context: Context) = context.getSharedPreferences("game-controls", Context.MODE_PRIVATE)
/** The main-screen bindings preset saved for [game], whose layout is the one drawn. */
fun bindings(context: Context, game: Long?): String? = game?.let { prefs(context).getString("$it.bindings", null) }
fun steamLayout(context: Context, game: Long?): Boolean {
val p = prefs(context)
return if (game != null && p.contains("$game.steam")) p.getBoolean("$game.steam", false) else SessionPrefs.steamTouchLayout(context)
}
fun choose(context: Context, game: Long, bindings: String?, steam: Boolean, name: String? = null) {
prefs(context).edit().apply { if (bindings == null) remove("$game.bindings") else putString("$game.bindings", bindings) }
.apply { if (!name.isNullOrBlank()) putString("$game.name", name) }
.putBoolean("$game.steam", steam).apply()
}
/** Games with their own choice, in the order of their ids. */
fun games(context: Context): List<Long> = prefs(context).all.keys
.filter { it.endsWith(".steam") || it.endsWith(".bindings") }
.mapNotNull { it.substringBeforeLast('.').toLongOrNull() }.distinct().sorted()
fun name(context: Context, game: Long): String? = prefs(context).getString("$game.name", null)
fun clear(context: Context, game: Long) {
prefs(context).edit().remove("$game.bindings").remove("$game.steam").apply()
}
}
@@ -9,6 +9,7 @@ object GamepadGeometry {
VIEW, STEAM, QAM, MENU,
PANELS,
L4, L5, R5, R4,
LEFT_TOUCH, RIGHT_TOUCH,
}
data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) {
@@ -26,10 +27,11 @@ object GamepadGeometry {
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map<Slot, Box> {
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false, grips: Boolean = false, upright: Boolean = false,
trackpads: 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)
if (upright || portraitDock && h >= w * 0.6f && w >= 300 * density && h >= 300 * density) {
return portraitLayout(w, h, density, grips, trackpads)
}
val pad = 8 * density
val buttonH = 40 * density
@@ -70,6 +72,7 @@ object GamepadGeometry {
else -> 1
}
middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f)
if (grips) gripsBetween(boxes, w, gap - 2 * gutter, boxes.values.maxOf { if (it.cx in (w - gap) / 2f..(w + gap) / 2f) it.bottom else 0f } + gutter, h - pad, density)
} else {
val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f)
val main = side * 0.62f
@@ -85,45 +88,75 @@ object GamepadGeometry {
val gap = w - 2 * (side * 0.40f + main / 2f)
val columns = if (gap >= 2 * gridButton) 2 else 1
val rows = (middle.size + columns - 1) / columns
middleGrid(columns, gap - 2 * gutter, h - pad - rows * buttonH - (rows - 1) * 10 * density)
val gridTop = h - pad - rows * buttonH - (rows - 1) * 10 * density
middleGrid(columns, gap - 2 * gutter, gridTop)
if (grips) gripsBetween(boxes, w, w - 2 * (side * 0.74f + second / 2f) - 2 * gutter, shoulderY + buttonH / 2f + gutter, gridTop - gutter, density)
val panelsW = min(112 * density, w - 2 * (side * 0.57f + shoulderW / 2f) - 2 * gutter)
if (panelsW >= buttonH) boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
}
return boxes
}
private fun portraitLayout(w: Float, h: Float, density: Float): Map<Slot, Box> {
/** The back grips in the gap between a landscape panel's two clusters: one row of four, or two rows of two. */
private fun gripsBetween(boxes: MutableMap<Slot, Box>, w: Float, span: Float, top: Float, bottom: Float, density: Float) {
val gap = 8 * density
val minimum = 44 * density
val rows = if ((span - 3 * gap) / 4f >= minimum) 1 else if ((span - gap) / 2f >= minimum) 2 else return
val perRow = 4 / rows
val cellW = ((span - (perRow - 1) * gap) / perRow).coerceAtMost(96 * density)
val cellH = ((bottom - top - (rows - 1) * gap) / rows).coerceAtMost(64 * density)
if (cellH < minimum) return
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
val col = i % perRow; val row = i / perRow
boxes[slot] = Box(w / 2f + (col - (perRow - 1) / 2f) * (cellW + gap), bottom - (rows - 1 - row) * (cellH + gap) - cellH / 2f, cellW, cellH)
}
}
/**
* The panel under a portrait game: shoulders with View and Menu across the top, the back grips under them when the kit has
* them, then the d-pad and face buttons and, along the bottom edge, the sticks or trackpads, each as large as the panel allows.
*/
private fun portraitLayout(w: Float, h: Float, density: Float, grips: Boolean, trackpads: Boolean): 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 boxes = LinkedHashMap<Slot, Box>()
val topGap = 4 * density
val topW = (w - 2 * pad - 5 * topGap) / 6f
val top = listOf(Slot.LEFT_OUTER_SHOULDER, Slot.LEFT_INNER_SHOULDER, Slot.VIEW, Slot.MENU, Slot.RIGHT_INNER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER)
for ((i, slot) in top.withIndex()) boxes[slot] = Box(pad + topW / 2f + i * (topW + topGap), pad + buttonH / 2f, topW, buttonH)
var areaTop = pad + buttonH + gap
if (grips) {
val gripW = (w - 2 * pad - 3 * gap) / 4f
val gripH = min(56 * density, (h - areaTop) * 0.12f).coerceAtLeast(buttonH)
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex())
boxes[slot] = Box(pad + gripW / 2f + i * (gripW + gap), areaTop + gripH / 2f, gripW, gripH)
areaTop += gripH + gap
}
val area = h - pad - areaTop - gap
if (trackpads) {
val second = min(w * 0.42f, area * 0.5f)
val rowH = area - second
val col = (w - 2 * pad - 3 * gap) / 4f
val stick = min(col, rowH)
val rowY = h - pad - rowH / 2f
val secondY = areaTop + second / 2f
boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second)
boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second)
boxes[Slot.LEFT_TOUCH] = Box(pad + col / 2f, rowY, col, rowH)
boxes[Slot.LEFT_MAIN] = Box(pad + col * 1.5f + gap, rowY, stick, stick)
boxes[Slot.RIGHT_MAIN] = Box(w - pad - col * 1.5f - gap, rowY, stick, stick)
boxes[Slot.RIGHT_TOUCH] = Box(w - pad - col / 2f, rowY, col, rowH)
return boxes
}
val main = min(w * 0.46f, area * 0.53f)
val second = min(w * 0.42f, area - main)
val secondY = areaTop + second / 2f
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)
boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second)
boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second)
boxes[Slot.LEFT_MAIN] = Box(w * 0.25f, mainY, main, main)
boxes[Slot.RIGHT_MAIN] = Box(w * 0.75f, mainY, main, main)
return boxes
}
}
@@ -10,7 +10,7 @@ import org.json.JSONObject
import java.util.UUID
object InputLibraries {
private const val VERSION = 14
private const val VERSION = 15
private const val KEY = "library"
private const val RECOVERY = "library-recovery."
const val OVERLAY = "builtin.overlay"
@@ -29,10 +29,10 @@ object InputLibraries {
val version = raw?.let { JSONObject(it).getInt("version") } ?: 0
if (version < 5) library = scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, library)))
if (version < 11) library = neutralStockLayouts(library)
if (version < 10) library = restyleGamepads(context, library)
if (version < 12) library = barStockLayouts(library)
if (version < 13) library = LegacyScreenKeyMigration.pin(library)
if (version < 14) library = deckGamepadSurfaces(context, library)
if (version < 15) library = kitGamepads(library)
if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
val legacy = LegacyScreenKeyMigration.snapshot(context)
if (legacy != null) {
@@ -83,8 +83,12 @@ object InputLibraries {
if (invalid) {
val encoded = encode(updated)
require(encoded.length <= 2_000_000) { "The input library is too large to save." }
check(p.edit().putString(RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8)), stored)
.putString(KEY, encoded).commit()) { "Could not save the input library and its recovery copy." }
val recovery = RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8))
if (!p.edit().putString(recovery, stored).putString(KEY, encoded).commit()) {
// A failed commit has already changed the in-memory preferences; put the previous library back.
p.edit().putString(KEY, stored).remove(recovery).apply()
error("Could not save the input library and its recovery copy.")
}
} else write(context, updated)
return updated
}
@@ -125,29 +129,16 @@ object InputLibraries {
return InputLibrary(profiles, layouts, bindings, selected).validate()
}
fun setAdaptiveSticks(context: Context, layoutId: String, on: Boolean): Boolean = runCatching {
update(context) { library ->
library.copy(layouts = library.layouts.map { layout ->
if (layout.id != layoutId || !layout.editable) layout
else layout.copy(elements = layout.elements.map { if (it.kind == InputElementKind.STICK) it.copy(floating = on, hideWhenIdle = on) else it })
})
}
}.onSuccess { ControllerPrefs.setAdaptiveSticks(context, on) }.isSuccess
fun setQuickButton(context: Context, layoutId: String, button: InputCommand, shown: Boolean): Boolean = runCatching {
update(context) { library -> library.layouts.firstOrNull { it.id == layoutId && it.editable }?.let { library.withLayout(it.withQuickButton(button, shown)) } ?: library }
}.isSuccess
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): List<InputSurfaceElement>? {
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): Pair<List<InputSurfaceElement>, Float>? {
val origin = layout.origin ?: layout.id
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements }
if (origin == OVERLAY || origin.startsWith("migrated.layout.")) {
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements to it.aspect }
if (origin == OVERLAY) {
val (surfaceContext, metrics) = primaryDisplay(context)
val size = if (origin == OVERLAY) listOf(metrics.widthPixels, metrics.heightPixels)
else origin.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() }
val w = metrics.widthPixels.coerceAtLeast(1)
val h = metrics.heightPixels.coerceAtLeast(1)
return KitLayout.elements(surfaceContext, PadKit.current(context), w, h, scale = layout.scale) to w.toFloat() / h
}
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.elements
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.let { it.elements to it.aspect }
}
@Suppress("DEPRECATION")
@@ -157,29 +148,12 @@ object InputLibraries {
return surfaceContext to DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) }
}
private fun restyleGamepads(context: Context, library: InputLibrary): InputLibrary {
if (library.layouts.none { it.id == OVERLAY || it.id.startsWith("migrated.layout.") }) return library
val (surfaceContext, metrics) = primaryDisplay(context)
return library.copy(layouts = library.layouts.map { layout ->
val size = when {
layout.id == OVERLAY -> listOf(metrics.widthPixels, metrics.heightPixels)
layout.id.startsWith("migrated.layout.") -> layout.id.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
else -> emptyList()
}
if (size.size != 2 || size.any { it <= 0 }) layout
else layout.copy(elements = LegacyGamepadLayout(surfaceContext, size[0], size[1]).restyle(layout.elements))
})
}
private fun upgradeOverlay(context: Context, library: InputLibrary): InputLibrary {
if (library.layouts.none { it.template == InputLayoutTemplate.OVERLAY }) return library
val (surfaceContext, metrics) = primaryDisplay(context)
val settings = ControllerPrefs.read(context)
val elements = LegacyGamepadLayout(surfaceContext, metrics.widthPixels.coerceAtLeast(1), metrics.heightPixels.coerceAtLeast(1)).elements()
val style = InputSurfaceStyle(settings.tint, settings.opacity)
val style = InputSurfaceStyle(opacity = settings.opacity)
val replacements = library.layouts.filter { it.template == InputLayoutTemplate.OVERLAY }.associate { old ->
old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style,
aspect = (metrics.widthPixels.coerceAtLeast(1).toFloat() / metrics.heightPixels.coerceAtLeast(1)).coerceIn(.05f, 20f))
old.id to old.copy(name = "Gamepad", elements = emptyList(), template = InputLayoutTemplate.CUSTOM, style = style)
}
var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it })
val migrated = mutableMapOf<Pair<String, String>, String>()
@@ -190,9 +164,8 @@ object InputLibraries {
val id = migrated.getOrPut(key) {
val old = library.preset(part.bindings)
val newId = migrationBindingId(result, old.id, layout.id)
val keyboard = elements.filter { it.id == "builtin:keyboard" }.associate { it.id to InputAction.Command(InputCommand.KEYBOARD) }
val clicks = if (settings.stickClick) old.clicks else old.clicks + elements.filter { it.hasClick }.associate { it.id to InputAction.Disabled }
result = result.withPreset(old.copy(id = newId, layoutId = layout.id, elements = old.elements + keyboard, clicks = clicks))
val clicks = if (settings.stickClick) old.clicks else old.clicks + KitLayout.clickIds.associateWith { InputAction.Disabled }
result = result.withPreset(old.copy(id = newId, layoutId = layout.id, clicks = clicks))
newId
}
part.copy(bindings = id)
@@ -201,15 +174,6 @@ object InputLibraries {
}
val oldBindings = migrated.keys.map { it.first }.toSet()
result = result.copy(bindings = result.bindings.filter { it.id !in oldBindings || result.usersOfBindings(it.id).isNotEmpty() })
// Older editor layouts were resolution-specific. Keep each as a selectable saved layout.
for (key in ControllerPrefs.prefs(context).all.keys.filter { it.startsWith("layout.") }.sorted()) {
val size = key.removePrefix("layout.").split('x').mapNotNull { it.toIntOrNull() }
if (size.size != 2 || size.any { it <= 0 } || result.layouts.size >= 128) continue
if (size[0] == metrics.widthPixels && size[1] == metrics.heightPixels) continue
val id = "migrated.$key"
if (result.layouts.none { it.id == id }) result = result.withLayout(SavedInputLayout(id, "Gamepad ${size[0]} × ${size[1]}",
LegacyGamepadLayout(surfaceContext, size[0], size[1]).elements(), style = style, aspect = (size[0].toFloat() / size[1]).coerceIn(.05f, 20f)))
}
return result.validate()
}
@@ -275,6 +239,16 @@ object InputLibraries {
return library.withLayout(saved.copy(elements = InputStockLayouts.gamepad(leftPad, rightStick))).validate()
}
/** Gamepads saved by the old editor follow the virtual controller's kit again; their positions don't map onto the new controls. */
private fun kitGamepads(library: InputLibrary): InputLibrary {
return library.copy(layouts = library.layouts.map { layout ->
val origin = layout.origin ?: layout.id
if (origin != OVERLAY && !origin.startsWith("migrated.layout.")) return@map layout
val extras = layout.elements.filterNot { KitLayout.isKit(it.id) }
layout.copy(elements = extras, origin = if (layout.id == OVERLAY) null else OVERLAY, aspect = if (extras.isEmpty()) 0f else layout.aspect, scale = 1f)
}).validate()
}
private fun migrationBindingId(library: InputLibrary, binding: String, layout: String): String {
val seed = JSONArray(listOf(binding, layout)).toString().toByteArray(Charsets.UTF_8)
val base = "migrated.bindings." + UUID.nameUUIDFromBytes(seed)
@@ -307,7 +281,7 @@ object InputLibraries {
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL).put("kitless", layout.kitless))
}
val bindings = JSONArray()
for (b in library.bindings) {
@@ -351,7 +325,7 @@ object InputLibraries {
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), layout.optionalString("origin"),
layout.optDouble("scale", 1.0).toFloat())
layout.optDouble("scale", 1.0).toFloat(), layout.optBoolean("kitless", false))
}
val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
@@ -22,6 +22,8 @@ data class SavedInputLayout(
val aspect: Float = 0f,
val origin: String? = null,
val scale: Float = 1f,
/** The player removed every kit control from this gamepad, so it must not follow the virtual controller again. */
val kitless: Boolean = false,
) {
val editable get() = template == InputLayoutTemplate.CUSTOM
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
@@ -49,7 +51,7 @@ data class SavedInputBindings(
fun action(element: InputSurfaceElement) = elements[element.id]
?: if (element.id == "legacy:${element.control.id}") controls[element.control] ?: InputAction.Native()
else InputAction.Disabled
else defaultElementAction(element.id)
fun clickAction(element: InputSurfaceElement) = clicks[element.id]
?: defaultElementClick(element, action(element)) { controls[it] ?: InputAction.Native() }
@@ -97,6 +99,16 @@ data class InputLibrary(
fun compileActive(isDesktop: Boolean, panel: String? = null): InputProfile = compileParts(activeId(isDesktop), InputRole.entries.associateWith {
preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel).bindings else activePart(isDesktop, it).bindings)
})
fun compileStock(isDesktop: Boolean, panel: String? = null): InputProfile {
val defaults = InputProfile.defaults(profile(activeId(isDesktop)).base)
val stock = InputStockLayouts.presets(InputStockLayouts.layouts())
return compileParts(defaults.id, InputRole.entries.associateWith { role ->
val part = if (role == InputRole.SECONDARY) panelPart(isDesktop, panel) else activePart(isDesktop, role)
val origin = layouts.firstOrNull { it.id == part.layout }?.origin ?: part.layout
stock.firstOrNull { it.id == part.bindings || (origin != null && it.layoutId == origin) }
?: SavedInputBindings(part.bindings, "", role == InputRole.PHYSICAL, part.layout, defaults.bindings[role].orEmpty())
})
}
fun saveSelection(isDesktop: Boolean, name: String, id: String = newInputId()): InputLibrary {
val current = profile(activeId(isDesktop))
@@ -126,8 +138,8 @@ data class InputLibrary(
fun withPreset(value: SavedInputBindings) = copy(bindings = bindings.filterNot { it.id == value.id } + value)
fun withLayout(value: SavedInputLayout) = copy(layouts = layouts.filterNot { it.id == value.id } + value,
bindings = bindings.map { preset -> if (preset.layoutId != value.id) preset else preset.copy(
elements = preset.elements.filter { (id, action) -> value.elements.any { it.id == id && action.validFor(it) } },
clicks = preset.clicks.filter { (id, action) -> value.elements.any { it.id == id && it.hasClick && action.validForClick() } }) })
elements = preset.elements.filter { (id, action) -> value.element(id)?.let { action.validFor(it) } == true },
clicks = preset.clicks.filter { (id, action) -> value.element(id)?.hasClick == true && action.validForClick() }) })
fun duplicateProfile(id: String, name: String, newId: String = newInputId(), sharePhysical: Boolean = false): InputLibrary {
require(profiles.size < 64)
@@ -261,8 +273,8 @@ data class InputLibrary(
require(preset.physical || preset.keys.isEmpty())
val layout = preset.layoutId?.let { id -> layouts.first { it.id == id } }
require(!preset.physical || layout == null && preset.elements.isEmpty() && preset.clicks.isEmpty())
require(preset.elements.all { (id, action) -> layout?.elements?.firstOrNull { it.id == id }?.let { action.validFor(it) } == true })
require(preset.clicks.all { (id, action) -> layout?.elements?.any { it.id == id && it.hasClick } == true && action.validForClick() })
require(preset.elements.all { (id, action) -> layout?.element(id)?.let { action.validFor(it) } == true })
require(preset.clicks.all { (id, action) -> layout?.element(id)?.hasClick == true && action.validForClick() })
require(preset.keys.all { it.key.device.isNotBlank() && it.key.keyCode >= 0 && it.key.scanCode >= 0 &&
it.action.validFor(InputControl.A) && (it.action !is InputAction.Native || it.action.target == null) })
}
@@ -302,3 +314,12 @@ internal fun InputAction.validFor(element: InputSurfaceElement): Boolean = when
element.kind == InputElementKind.TRIGGER -> target == InputControl.LT || target == InputControl.RT
else -> target.dimensions == 1 && target != InputControl.LT && target != InputControl.RT
}
/**
* A saved element, or the kit control that [id] names: in a layout made from the built-in gamepad every kit control keeps its
* binding while it's removed, so Reset or Restore brings it back with its action.
*/
internal fun SavedInputLayout.element(id: String): InputSurfaceElement? =
elements.firstOrNull { it.id == id } ?: KitLayout.element(id)?.takeIf {
this.id == InputLibraries.OVERLAY || origin == InputLibraries.OVERLAY || KitLayout.bindsTo(id, elements)
}
@@ -48,11 +48,21 @@ data class InputProfile(
copy(bindings = bindings + (role to (bindings[role].orEmpty() + (control to action))))
fun elementAction(role: InputRole, id: String, control: InputControl): InputAction =
elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else InputAction.Disabled
elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else defaultElementAction(id)
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
fun showsMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
val action = elementAction(role, element.id, element.control).takeIf {
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
}
val click = elementClickAction(role, element).takeIf {
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
}
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) }
}
companion object {
const val GAME = "game"
const val DESKTOP = "desktop"
@@ -105,3 +115,10 @@ internal fun InputAction.validFor(control: InputControl): Boolean = when (this)
is InputAction.Scroll -> control.dimensions == 2 && speed.isFinite() && speed in 1f..60f
else -> true
}
/** What an on-screen element with no saved action does: kit controls press their own button, everything else is unassigned. */
internal fun defaultElementAction(id: String): InputAction = when (id) {
KitLayout.DPAD_ID -> InputAction.Native()
KitLayout.KEYBOARD_ID -> InputAction.Command(InputCommand.KEYBOARD)
else -> InputAction.Disabled
}
@@ -38,8 +38,13 @@ data class InputSurfaceElement(
) {
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
fun bounded() = copy(x = x.coerceIn(0f, 0.97f), y = y.coerceIn(0f, 0.97f),
width = width.coerceIn(0.03f, (1f - x.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)), height = height.coerceIn(0.03f, (1f - y.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)))
fun bounded() = copy(x = x.coerceIn(0f, 1f - MIN_SIZE), y = y.coerceIn(0f, 1f - MIN_SIZE),
width = width.coerceIn(MIN_SIZE, (1f - x.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE)),
height = height.coerceIn(MIN_SIZE, (1f - y.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE)))
companion object {
const val MIN_SIZE = .01f
}
}
internal val QUICK_BUTTONS = listOf(InputCommand.STEAM, InputCommand.QUICK_ACCESS, InputCommand.KEYBOARD)
@@ -51,15 +56,31 @@ val InputSurfaceElement.quickButton: InputCommand? get() = when {
else -> null
}
internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceElement> = map { e ->
/** Controls whose boxes touch, grown by 15%, scale around one shared anchor so a cluster such as the face buttons keeps its shape. */
internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceElement> {
fun anchor(centre: Float) = when { centre < 1f / 3f -> 0f; centre > 2f / 3f -> 1f; else -> .5f }
val w = (e.width * factor).coerceIn(.03f, 1f)
val h = (e.height * factor).coerceIn(.03f, 1f)
val group = IntArray(size) { it }
fun root(i: Int): Int = if (group[i] == i) i else root(group[i]).also { group[i] = it }
for (i in indices) for (j in i + 1 until size) {
val a = this[i]; val b = this[j]
val near = kotlin.math.abs(a.x + a.width / 2 - b.x - b.width / 2) < (a.width + b.width) / 2 * 1.15f &&
kotlin.math.abs(a.y + a.height / 2 - b.y - b.height / 2) < (a.height + b.height) / 2 * 1.15f
if (near) group[root(i)] = root(j)
}
val anchors = indices.groupBy(::root).mapValues { (_, members) ->
anchor(members.map { this[it].x + this[it].width / 2 }.average().toFloat()) to anchor(members.map { this[it].y + this[it].height / 2 }.average().toFloat())
}
return mapIndexed { i, e -> e.scaledAround(factor, anchors.getValue(root(i))) }
}
private fun InputSurfaceElement.scaledAround(factor: Float, anchor: Pair<Float, Float>): InputSurfaceElement {
val e = this
val w = (e.width * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f)
val h = (e.height * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f)
val cx = e.x + e.width / 2
val cy = e.y + e.height / 2
val ax = anchor(cx)
val ay = anchor(cy)
e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h),
val (ax, ay) = anchor
return e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h),
width = w, height = h).bounded()
}
@@ -3,6 +3,10 @@ package com.droiddeck.launcher.input
class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole, val element: InputSurfaceElement) {
private val router = pad.inputRouter
private val route = router?.channel(role, element.control, element = element)
/** The kit's D-pad keeps each direction's own binding, as the separate direction buttons it replaced did. */
private val arms = if (element.id == KitLayout.DPAD_ID && router != null)
listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { router.channel(role, it, element = KitLayout.element("legacy:${it.id}")) }
else emptyList()
private val deck = DeckControls.source(role, routed = true)
private val clickDeck = DeckControls.source(role, routed = true)
private val clickOwner = Any()
@@ -55,6 +59,15 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
fingerDown = down
if (latched) 1f else 0f
} else value
if (arms.isNotEmpty() && route?.action is InputAction.Native) {
val ready = route.update(x, y, touching) != null
val values = listOf(y < -.5f, x > .5f, y > .5f, x < -.5f).map { if (it && ready) 1f else 0f }
val toPad = arms.mapIndexed { i, arm -> arm.update(values[i])?.takeIf { it.isPad }?.let { it to values[i] } }.filterNotNull()
if (toPad.isNotEmpty() || nativePad) writePad(this, null) { state -> state.clear(); for ((t, v) in toPad) state.add(t, v) }
nativePad = toPad.isNotEmpty()
InputTiming.end(timing)
return
}
val target = if (router == null) element.control else route?.update(x, y, touching)
val toPad = target?.isPad == true
val toDeck = target != null && !target.isPad
@@ -75,6 +88,7 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
fun cancel() {
if (closed) return
route?.takeIf { it.action is InputAction.Command }?.release()
arms.filter { it.action is InputAction.Command }.forEach { it.release() }
update(0f)
}
@@ -112,13 +126,13 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
closed = true
router?.removeSnapshot(snapshot)
releaseNative(); resetLatch()
route?.close(); clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close()
route?.close(); arms.forEach { it.close() }; clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close()
}
fun release() {
if (closed) return
releaseNative(); resetLatch()
route?.release(); clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release()
route?.release(); arms.forEach { it.release() }; clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release()
}
}
@@ -26,6 +26,8 @@ class KeyboardHost(
var imeShowing = false
private set
var onImeChanged: ((Boolean) -> Unit)? = null
val hideMeansDismissal: Boolean
get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R || (shown && imeShowing)
init {
isFocusable = false
@@ -0,0 +1,222 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.max
import kotlin.math.min
/**
* Places a virtual controller's default on-screen controls. Each kit is drawn on a 1600 × 900 reference screen; controls keep
* their distance from the nearest edge, so wider screens spread them apart instead of stretching them. Clusters such as the face
* buttons are placed by their centre so they move as one, and the row along the bottom-left edge always starts after DroidDeck's
* corner button.
*/
object KitLayout {
const val DPAD_ID = "kit:dpad"
const val KEYBOARD_ID = "builtin:keyboard"
/** Whether [id] names one of a kit's own controls rather than a key or control the player added. */
fun isKit(id: String) = id.startsWith("legacy:") || id == DPAD_ID || id == KEYBOARD_ID
/** The control a kit id stands for in a layout that keeps no kit positions, so bindings saved for it stay valid. */
fun element(id: String): InputSurfaceElement? = when {
id == DPAD_ID -> InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, id, InputElementKind.DPAD)
id == KEYBOARD_ID -> InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, id)
id.startsWith("legacy:") -> InputControl.entries.firstOrNull { "legacy:${it.id}" == id }
?.let { InputSurfaceElement(it, 0f, 0f, .1f, .1f, id, InputElementKind.from(it)) }
else -> null
}
/** The direction buttons the kit's D-pad stands in for; their saved overrides stay with the D-pad. */
val dpadDirectionIds = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { "legacy:${it.id}" }
/** Whether a binding for [id] belongs to a layout made of [elements]. */
fun bindsTo(id: String, elements: List<InputSurfaceElement>) =
elements.any { it.id == id } || id in dpadDirectionIds && elements.any { it.id == DPAD_ID }
/** Every kit control that has a click, across all virtual controllers. */
val clickIds = listOf(InputControl.LS, InputControl.RS, InputControl.LEFT_PAD, InputControl.RIGHT_PAD).map { "legacy:${it.id}" }
private const val REF_W = 1600f
private const val REF_H = 900f
/** The widest pair of side controls on any kit: a larger size never pushes the two halves, or the rows, into each other. */
private const val MIN_SPAN = 1200f
private const val MAX_HEIGHT_MM = 80f
/** The smallest half-size of any kit control in reference units. */
private const val SMALLEST_HALF = 26f
private const val CORNER_DP = 52f
private const val ROW_DP = 60f
private const val BUTTON_DP = 44f
private const val GAP_DP = 8f
private class Spec(val control: InputControl, val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw, val id: String = "legacy:${control.id}",
val kind: InputElementKind = InputElementKind.from(control), val shape: InputButtonShape = InputButtonShape.CIRCLE, val icon: Int = 0, val name: String = control.label,
val ax: Float = cx, val ay: Float = cy)
private fun shoulders() = listOf(
Spec(InputControl.LT, 140f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.LB, 140f, 148f, 88f, 30f, shape = InputButtonShape.PILL),
Spec(InputControl.RT, 1460f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.RB, 1460f, 148f, 88f, 30f, shape = InputButtonShape.PILL))
private fun face(cx: Float, cy: Float, r: Float, off: Float) = listOf(
Spec(InputControl.Y, cx, cy - off, r, ax = cx, ay = cy), Spec(InputControl.X, cx - off, cy, r, ax = cx, ay = cy),
Spec(InputControl.B, cx + off, cy, r, ax = cx, ay = cy), Spec(InputControl.A, cx, cy + off, r, ax = cx, ay = cy))
private fun dpad(cx: Float, cy: Float, half: Float) =
Spec(InputControl.LS, cx, cy, half, id = DPAD_ID, kind = InputElementKind.DPAD, shape = InputButtonShape.ROUNDED, name = "D-pad")
private fun keyboard(cx: Float) = Spec(InputControl.A, cx, 848f, 46f, id = KEYBOARD_ID, icon = InputButtonIcons.KEYBOARD, name = "Keyboard")
private fun specs(kit: PadKit): List<Spec> = when {
kit.steam -> shoulders() + listOf(
Spec(InputControl.L4, 30f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.L5, 30f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.R4, 1570f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.R5, 1570f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED),
dpad(220f, 345f, 150f)) + face(1375f, 345f, 58f, 96f) + listOf(
Spec(InputControl.LS, 290f, 640f, 96f), Spec(InputControl.RS, 1310f, 640f, 96f),
Spec(InputControl.LEFT_PAD, 470f, 360f, 88f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1130f, 360f, 88f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.SELECT, 660f, 150f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 150f, 46f, 26f, shape = InputButtonShape.PILL),
Spec(InputControl.GUIDE, 370f, 852f, 66f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.QAM, 1230f, 852f, 66f, 30f, shape = InputButtonShape.PILL),
keyboard(136f))
kit.playStation -> shoulders() + listOf(dpad(250f, 395f, 125f)) + face(1350f, 395f, 58f, 96f) + listOf(
Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f),
Spec(InputControl.L3, 430f, 590f, 42f, ax = 565f, ay = 690f), Spec(InputControl.R3, 1170f, 590f, 42f, ax = 1035f, ay = 690f),
Spec(InputControl.SELECT, 640f, 150f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 150f, 50f, 30f, shape = InputButtonShape.PILL),
Spec(InputControl.GUIDE, 800f, 250f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 675f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf(
Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f, ax = 235f, ay = 400f), Spec(InputControl.R3, 1290f, 790f, 42f, ax = 1130f, ay = 690f),
Spec(InputControl.SELECT, 690f, 162f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 162f, 38f),
Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
}
/** The default controls for [kit] on a [width] × [height] screen. */
fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f): List<InputSurfaceElement> {
if (width <= 0 || height <= 0) return emptyList()
// Insets stay as reported unless what's left is too small to keep every control above the minimum element size.
val smallestUnit = InputSurfaceElement.MIN_SIZE * max(width, height) / (2 * SMALLEST_HALF)
fun fit(a: Int, b: Int, side: Int, reference: Float): Pair<Int, Int> {
val first = a.coerceAtLeast(0); val second = b.coerceAtLeast(0)
val room = (side - (smallestUnit * reference).toInt() - 1).coerceAtLeast(0)
return if (first + second <= room) first to second else (first.toLong() * room / (first + second)).toInt() to (second.toLong() * room / (first + second)).toInt()
}
val (left, right) = fit(inset.left, inset.right, width, MIN_SPAN)
val (top, bottom) = fit(inset.top, inset.bottom, height, REF_H)
val safe = Rect(left, top, right, bottom)
if (height > width) return portrait(context, kit, width, height, safe, scale)
val w = width.toFloat(); val h = height.toFloat()
val unit = (min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale).coerceAtMost(min((w - safe.left - safe.right).coerceAtLeast(1f) / MIN_SPAN, (h - safe.top - safe.bottom).coerceAtLeast(1f) / REF_H))
fun x(ref: Float) = when {
ref < REF_W / 3f -> safe.left + ref * unit
ref > REF_W * 2f / 3f -> w - safe.right - (REF_W - ref) * unit
else -> (w / 2f + (ref - REF_W / 2f) * unit).between(safe.left + ref * unit, w - safe.right - (REF_W - ref) * unit)
}
fun y(ref: Float) = when {
ref < REF_H / 3f -> safe.top + ref * unit
ref > REF_H * 2f / 3f -> h - safe.bottom - (REF_H - ref) * unit
else -> (h / 2f + (ref - REF_H / 2f) * unit).between(safe.top + ref * unit, h - safe.bottom - (REF_H - ref) * unit)
}
val density = context.resources.displayMetrics.density
var edge = safe.left + CORNER_DP * density
val specs = specs(kit)
val row = specs.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s ->
val hw = s.hw * unit
max(x(s.cx), edge + hw).also { edge = it + hw + GAP_DP * density }
}
return specs.map { s ->
val cx = row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit); val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit
InputSurfaceElement(s.control, (cx - hw) / w, (cy - hh) / h, 2 * hw / w, 2 * hh / h, s.id, s.kind, if (s.name == s.control.label) kit.name(s.control) else s.name,
floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded()
}
}
/**
* A portrait surface gets the same pad as the panel under the game, in the lower part of the screen, with the keyboard,
* Steam, Quick Access and stick-click buttons in a row along the bottom edge that starts after DroidDeck's corner button.
*/
private fun portrait(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val density = context.resources.displayMetrics.density
val row = ROW_DP * density
val inner = (w - safe.left - safe.right).coerceAtLeast(1f)
val area = (min(h * .6f, inner * 1.15f) * scale).coerceAtMost(h - safe.top - safe.bottom - row).coerceAtLeast(1f)
val top = h - safe.bottom - row - area
val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true).map { e ->
e.copy(x = (safe.left + e.x * inner) / w, y = (top + e.y * area) / h, width = e.width * inner / w, height = e.height * area / h,
floating = e.kind == InputElementKind.STICK)
}
val specs = specs(kit)
fun spec(control: InputControl, id: String = "legacy:${control.id}") = specs.firstOrNull { it.control == control && it.id == id }
val gap = GAP_DP * density
val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3))
val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3))
val start = safe.left + CORNER_DP * density
val span = (w - safe.right - gap - start - gap * (leftRow.size + rightRow.size - 1)).coerceAtLeast(1f)
val size = min(BUTTON_DP * density, span / (leftRow + rightRow).sumOf { (it.hw / it.hh).toDouble() }.toFloat())
val cy = h - safe.bottom - row / 2f
val placed = mutableListOf<InputSurfaceElement>()
fun put(s: Spec, cx: Float) {
val bw = size * s.hw / s.hh
placed += InputSurfaceElement(s.control, (cx - bw / 2) / w, (cy - size / 2) / h, bw / w, size / h, s.id, s.kind,
if (s.name == s.control.label) kit.name(s.control) else s.name, buttonShape = s.shape, icon = s.icon)
}
var left = start
for (s in leftRow) {
val bw = size * s.hw / s.hh
put(s, left + bw / 2); left += bw + gap
}
var right = w - safe.right - gap
for (s in rightRow) {
val bw = size * s.hw / s.hh
put(s, right - bw / 2); right -= bw + gap
}
return pad + placed
}
/** Controls for the panel below the game, in [GamepadGeometry]'s slots. */
fun dock(context: Context, kit: PadKit, width: Int, height: Int, portrait: Boolean, left: InputControl, right: InputControl,
upright: Boolean = false): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val boxes = GamepadGeometry.layout(w, h, context.resources.displayMetrics.density, portrait, grips = kit.steam, upright = upright,
trackpads = kit.steam)
val placed = mutableListOf<InputSurfaceElement>()
fun put(control: InputControl, box: GamepadGeometry.Box?, shape: InputButtonShape, id: String = "legacy:${control.id}",
kind: InputElementKind = InputElementKind.from(control), name: String = kit.name(control)) {
val b = box ?: return
placed += InputSurfaceElement(control, b.left / w, b.top / h, b.width / w, b.height / h, id, kind, name, floating = false, buttonShape = shape).bounded()
}
fun square(box: GamepadGeometry.Box?) = box?.let { val side = min(it.width, it.height); GamepadGeometry.Box(it.cx, it.cy, side, side) }
val four = GamepadGeometry.Slot.LEFT_TOUCH in boxes
val leftMain = if (four || !kit.steam && left == InputControl.LEFT_PAD) InputControl.LS else left
val rightMain = if (four || !kit.steam && right == InputControl.RIGHT_PAD) InputControl.RS else right
if (four) {
put(InputControl.LEFT_PAD, boxes[GamepadGeometry.Slot.LEFT_TOUCH], InputButtonShape.ROUNDED)
put(InputControl.RIGHT_PAD, boxes[GamepadGeometry.Slot.RIGHT_TOUCH], InputButtonShape.ROUNDED)
}
put(leftMain, square(boxes[GamepadGeometry.Slot.LEFT_MAIN]), InputButtonShape.CIRCLE)
put(InputControl.LS, square(boxes[GamepadGeometry.Slot.LEFT_SECOND]), InputButtonShape.ROUNDED, DPAD_ID, InputElementKind.DPAD, "D-pad")
put(rightMain, square(boxes[GamepadGeometry.Slot.RIGHT_MAIN]), InputButtonShape.CIRCLE)
square(boxes[GamepadGeometry.Slot.RIGHT_SECOND])?.let { b ->
val r = b.width * .17f; val off = b.width * .3f
listOf(InputControl.Y to (0f to -1f), InputControl.B to (1f to 0f), InputControl.A to (0f to 1f), InputControl.X to (-1f to 0f)).forEach { (c, d) ->
put(c, GamepadGeometry.Box(b.cx + d.first * off, b.cy + d.second * off, 2 * r, 2 * r), InputButtonShape.CIRCLE)
}
}
put(InputControl.LT, boxes[GamepadGeometry.Slot.LEFT_OUTER_SHOULDER], InputButtonShape.PILL)
put(InputControl.LB, boxes[GamepadGeometry.Slot.LEFT_INNER_SHOULDER], InputButtonShape.PILL)
put(InputControl.RB, boxes[GamepadGeometry.Slot.RIGHT_INNER_SHOULDER], InputButtonShape.PILL)
put(InputControl.RT, boxes[GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER], InputButtonShape.PILL)
put(InputControl.SELECT, boxes[GamepadGeometry.Slot.VIEW], InputButtonShape.PILL)
put(InputControl.START, boxes[GamepadGeometry.Slot.MENU], InputButtonShape.PILL)
if (kit.steam) listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4).forEach { (c, slot) -> put(c, boxes[slot], InputButtonShape.ROUNDED) }
return placed
}
private fun cap(context: Context, shortSide: Int): Float {
val metrics = context.resources.displayMetrics
val nominal = metrics.densityDpi.toFloat()
val dpi = metrics.ydpi.takeIf { it > nominal * .6f && it < nominal * 1.6f } ?: nominal
val mm = shortSide / dpi * 25.4f
return min(1f, MAX_HEIGHT_MM / max(mm, 1f))
}
/** The middle band never comes closer to an edge than the edge rows' own reference spacing allows. */
private fun Float.between(low: Float, high: Float) = coerceIn(low, max(low, high))
}
@@ -1,352 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.*
internal class LegacyGamepadLayout(private val context: Context, private val width: Int, private val height: Int, private val safe: Rect = Rect(),
private val scale: Float = 1f) {
private val resources get() = context.resources
private val settings = ControllerPrefs.read(context)
private var fit = 1f
private class Control(val id: String, val group: String, val stick: Int, val radiusDp: Float, val offsetXDp: Float, val offsetYDp: Float) {
var radius = 0f
var cx = 0f
var cy = 0f
val halfW get() = if (id in shoulderIds) radius * SHOULDER_WIDTH else radius
val halfH get() = if (id in shoulderIds) radius * SHOULDER_HEIGHT else radius
}
private val controls = listOf(
Control("up", "dpad", -1, 30f, 0f, -50f),
Control("right", "dpad", -1, 30f, 50f, 0f),
Control("down", "dpad", -1, 30f, 0f, 50f),
Control("left", "dpad", -1, 30f, -50f, 0f),
Control("ls", "ls", 0, 48f, 0f, 0f),
Control("rs", "rs", 1, 48f, 0f, 0f),
Control("a", "face", -1, 30f, 0f, 50f),
Control("b", "face", -1, 30f, 50f, 0f),
Control("x", "face", -1, 30f, -50f, 0f),
Control("y", "face", -1, 30f, 0f, -50f),
Control("lb", "lb", -1, 24f, 0f, 0f),
Control("rb", "rb", -1, 24f, 0f, 0f),
Control("lt", "lt", -1, 24f, 0f, 0f),
Control("rt", "rt", -1, 24f, 0f, 0f),
Control("select", "select", -1, 20f, 0f, 0f),
Control("start", "start", -1, 20f, 0f, 0f),
Control("guide", "guide", -1, 22f, 0f, 0f),
Control("qam", "qam", -1, 22f, 0f, 0f),
)
private val groups = controls.map { it.group }.distinct()
private fun dp(value: Float) = value * resources.displayMetrics.density
private fun scaled(value: Float) = dp(value) * settings.size / 100f * scale * fit
private fun fitScale(): Float {
val metrics = resources.displayMetrics
val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi)
val faceMm = dp(60f) / pxPerMm(metrics.xdpi)
val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f)
return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f)
}
private fun pxPerMm(dpi: Float): Float {
val nominal = resources.displayMetrics.densityDpi.toFloat()
return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f
}
private fun placeAuto(w: Float, h: Float) {
val metrics = resources.displayMetrics
val mmX = pxPerMm(metrics.xdpi)
val mmY = pxPerMm(metrics.ydpi)
val usableW = w - safe.left - safe.right
val usableH = h - safe.top - safe.bottom
val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX
val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY
val gap = dp(12f)
val floor = BOTTOM_MARGIN_MM * mmY
val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap))
val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop)
put("ls", safe.left + inboard, restY)
put("face", w - safe.right - inboard, restY)
besideBelow("dpad", "ls", 1f, gap, floor)
besideBelow("rs", "face", -1f, gap, floor)
val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM
val shoulderY = if (phone) safe.top + floor + halfH("lb")
else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb")
shoulders("ls", "lb", "lt", 1f, gap, shoulderY)
shoulders("face", "rb", "rt", -1f, gap, shoulderY)
val bottom = h - safe.bottom - floor - extent("guide")
val spread = extent("guide") + gap / 2f
put("guide", w / 2f - spread, bottom)
put("qam", w / 2f + spread, bottom)
val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select")
put("select", inner, restY)
put("start", w - inner, restY)
if (phone) {
val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select")
put("select", top, shoulderY)
put("start", w - top, shoulderY)
}
if (crowded("select", gap) || crowded("start", gap)) {
above("select", "dpad", gap)
val (sx, sy) = centre("select")
put("start", w - sx, sy)
if (crowded("start", gap)) above("start", "rs", gap)
}
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
val row = centre("select").second
put("guide", w / 2f - spread, row)
put("qam", w / 2f + spread, row)
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
val top = safe.top + dp(8f) + extent("guide")
put("guide", w / 2f - spread, top)
put("qam", w / 2f + spread, top)
}
}
}
private fun drop(group: String, anchor: String, gap: Float): Float =
(extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group)
private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) {
val (ax, ay) = centre(anchor)
val reach = extent(anchor) + extent(group) + gap
val floor = height - safe.bottom - margin - extent(group)
val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay)
val dx = sqrt(max(0f, reach * reach - dy * dy))
put(group, ax + inward * dx, ay + dy)
}
private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) {
val (ax, _) = centre(anchor)
val spread = extent(bumper) + gap / 2f
put(bumper, ax + inward * spread, y)
put(trigger, ax - inward * spread, y)
}
private fun above(group: String, anchor: String, gap: Float) {
val (ax, ay) = centre(anchor)
put(group, ax, ay - extent(anchor) - gap - extent(group))
}
private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean {
val (x, y) = centre(group)
return groups.any { other ->
if (other == group || other == except) return@any false
val (ox, oy) = centre(other)
val dx = x - ox
val dy = y - oy
sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space
}
}
private fun members(group: String) = controls.filter { it.group == group }
private fun centre(group: String): Pair<Float, Float> {
val first = members(group).first()
return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp))
}
private fun extent(group: String): Float = members(group).maxOf { control ->
sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW
}
private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH }
private fun put(group: String, x: Float, y: Float) {
for (control in members(group)) {
control.cx = x + scaled(control.offsetXDp)
control.cy = y + scaled(control.offsetYDp)
}
}
private fun clamp(group: String) {
val list = members(group)
val margin = dp(4f)
val minX = list.minOf { it.cx - it.halfW } - safe.left - margin
val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin)
val minY = list.minOf { it.cy - it.halfH } - safe.top - margin
val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin)
val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f
val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f
if (dx == 0f && dy == 0f) return
for (control in list) { control.cx += dx; control.cy += dy }
}
fun elements(): List<InputSurfaceElement> {
fit = fitScale()
controls.forEach { it.radius = scaled(it.radiusDp) }
placeAuto(width.toFloat(), height.toFloat())
for ((group, position) in ControllerPrefs.layout(context, width, height)) {
if (group in groups && position.first.isFinite() && position.second.isFinite()) put(group, position.first * width, position.second * height)
}
groups.forEach(::clamp)
val result = controls.filter {
settings.mapping[it.id] != ControllerPrefs.OFF && (it.id != "guide" || settings.steamButton) && (it.id != "qam" || settings.qamButton)
}.map { c ->
InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks,
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let(::widenStick).bounded()
}.toMutableList()
if (settings.keyboardButton) result += keyboard()
return result
}
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> {
val before = from.elements().associateBy { it.id }
val after = elements().associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val w = (a.width * e.width / b.width).coerceIn(.03f, 1f)
val h = (a.height * e.height / b.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
val inset = dp(BUTTONS_ONLY_INSET_DP)
val bottom = height - safe.bottom - inset
val radius = dp(BUTTONS_ONLY_RADIUS_DP)
fun pick(control: InputControl, shown: Boolean) = stored.firstOrNull { it.id == "legacy:${control.id}" }
?: stored.firstOrNull { it.control == control && it.kind == InputElementKind.BUTTON }
?: InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE).takeIf { shown }
return listOfNotNull(
pick(InputControl.GUIDE, settings.steamButton)?.let { circle(it, safe.left + inset, bottom, radius) },
pick(InputControl.QAM, settings.qamButton)?.let { circle(it, width - safe.right - inset, bottom, radius) },
stored.firstOrNull { it.id == KEYBOARD_ID }?.let { circle(it, width / 2f, bottom, dp(KEYBOARD_RADIUS_DP)) },
)
}
fun dock(stored: List<InputSurfaceElement>, portrait: Boolean, grips: Boolean, left: InputControl = InputControl.LS,
right: InputControl = InputControl.RS): List<InputSurfaceElement> {
val boxes = GamepadGeometry.layout(width.toFloat(), height.toFloat(), resources.displayMetrics.density, portrait)
val placed = mutableListOf<InputSurfaceElement>()
fun box(control: InputControl, slot: GamepadGeometry.Slot, shape: InputButtonShape) {
val b = boxes[slot] ?: return
placed += InputSurfaceElement(control, b.left / width, b.top / height, b.width / width, b.height / height,
floating = false, buttonShape = shape).bounded()
}
fun cross(controls: List<InputControl>, slot: GamepadGeometry.Slot) {
val b = boxes[slot] ?: return
val side = min(b.width, b.height)
val spread = side * CROSS_SPREAD
val radius = side * CROSS_RADIUS
controls.zip(listOf(0f to -1f, 1f to 0f, 0f to 1f, -1f to 0f)).forEach { (control, direction) ->
placed += circle(InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE),
b.cx + direction.first * spread, b.cy + direction.second * spread, radius)
}
}
box(left, GamepadGeometry.Slot.LEFT_MAIN, InputButtonShape.CIRCLE)
cross(DPAD_ORDER, GamepadGeometry.Slot.LEFT_SECOND)
box(right, GamepadGeometry.Slot.RIGHT_MAIN, InputButtonShape.CIRCLE)
cross(FACE_ORDER, GamepadGeometry.Slot.RIGHT_SECOND)
box(InputControl.LT, GamepadGeometry.Slot.LEFT_OUTER_SHOULDER, InputButtonShape.PILL)
box(InputControl.LB, GamepadGeometry.Slot.LEFT_INNER_SHOULDER, InputButtonShape.PILL)
box(InputControl.RB, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER, InputButtonShape.PILL)
box(InputControl.RT, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER, InputButtonShape.PILL)
box(InputControl.SELECT, GamepadGeometry.Slot.VIEW, InputButtonShape.PILL)
box(InputControl.START, GamepadGeometry.Slot.MENU, InputButtonShape.PILL)
if (grips) GRIPS.forEach { (control, slot) -> box(control, slot, InputButtonShape.ROUNDED) }
val surfaces = listOf(left, right).filter { it.isTrackpad }
return withGeometry(stored, placed) + placed.filter { p -> (GRIPS.any { it.first == p.control } || p.control in surfaces) && stored.none { it.id == p.id } }
}
private fun circle(e: InputSurfaceElement, cx: Float, cy: Float, radius: Float) =
e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height).bounded()
private fun withGeometry(stored: List<InputSurfaceElement>, placed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = placed.associateBy { it.id }
return stored.mapNotNull { e -> byId[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } }
}
private fun keyboard(): InputSurfaceElement {
val radius = dp(KEYBOARD_RADIUS_DP)
val cx = safe.left + dp(KEYBOARD_X_DP)
val cy = height - safe.bottom - dp(KEYBOARD_Y_DP)
return InputSurfaceElement(InputControl.A, (cx - radius) / width, (cy - radius) / height, 2 * radius / width, 2 * radius / height,
KEYBOARD_ID, name = "Keyboard", icon = InputButtonIcons.KEYBOARD, buttonShape = InputButtonShape.CIRCLE).bounded()
}
fun restyle(elements: List<InputSurfaceElement>): List<InputSurfaceElement> {
val dpad = elements.filter { it.id == "legacy:${it.control.id}" && it.control in DPAD && it.buttonShape == InputButtonShape.ROUNDED }
val centreX = dpad.map { (it.x + it.width / 2f) * width }.average().toFloat()
val centreY = dpad.map { (it.y + it.height / 2f) * height }.average().toFloat()
val resize = untouchedDpad(dpad, centreX, centreY)
return elements.map { e ->
when {
e.id == KEYBOARD_ID && e.icon == 0 && e.name == "Keyboard" && e.buttonShape == InputButtonShape.ROUNDED &&
e.x == .02f && e.y == .9f && e.width == .12f && e.height == .08f -> keyboard()
e.id == "legacy:${e.control.id}" && e.buttonShape == InputButtonShape.ROUNDED -> {
val round = e.copy(buttonShape = if (e.control.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE)
(if (resize && e.control in DPAD) resizeDpad(round, centreX, centreY) else widenStick(round)).bounded()
}
else -> e
}
}
}
private fun untouchedDpad(dpad: List<InputSurfaceElement>, centreX: Float, centreY: Float): Boolean {
if (dpad.size != DPAD.size) return false
val radius = dpad[0].width * width / 2f
val tolerance = 1.5f
val offset = radius * LEGACY_DPAD_OFFSET_DP / LEGACY_DPAD_RADIUS_DP
return dpad.all { e ->
val old = controls.first { it.id == e.control.id }
val dx = (e.x + e.width / 2f) * width - centreX
val dy = (e.y + e.height / 2f) * height - centreY
abs(e.width * width / 2f - radius) <= tolerance && abs(e.height * height / 2f - radius) <= tolerance &&
abs(dx - offset * sign(old.offsetXDp)) <= tolerance && abs(dy - offset * sign(old.offsetYDp)) <= tolerance
}
}
private fun resizeDpad(e: InputSurfaceElement, centreX: Float, centreY: Float): InputSurfaceElement {
val old = controls.first { it.id == e.control.id }
val radius = e.width * width / 2f * old.radiusDp / LEGACY_DPAD_RADIUS_DP
val cx = centreX + ((e.x + e.width / 2f) * width - centreX) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
val cy = centreY + ((e.y + e.height / 2f) * height - centreY) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
return e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height)
}
private fun widenStick(e: InputSurfaceElement): InputSurfaceElement {
val extra = e.width * (STICK_REACH - 1f)
return when (e.control) {
InputControl.LS -> (e.x - extra).coerceAtLeast(0f).let { x -> e.copy(x = x, width = e.x + e.width - x) }
InputControl.RS -> e.copy(width = (e.width + extra).coerceAtMost(1f - e.x))
else -> e
}
}
private companion object {
const val MIN_FACE_MM = 9.5f
const val FULL_SIZE_HEIGHT_MM = 85f
const val BOTTOM_MARGIN_MM = 5f
const val DROP_DEGREES = 35.0
const val PHONE_MAX_HEIGHT_MM = 90f
const val SHOULDER_WIDTH = 1.45f
const val SHOULDER_HEIGHT = 0.8f
val shoulderIds = setOf("lb", "rb", "lt", "rt")
const val STICK_REACH = 1.25f
const val LEGACY_DPAD_RADIUS_DP = 26f
const val LEGACY_DPAD_OFFSET_DP = 52f
val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
const val KEYBOARD_ID = "builtin:keyboard"
const val KEYBOARD_RADIUS_DP = 18f
const val KEYBOARD_X_DP = 90f
const val KEYBOARD_Y_DP = 34f
const val BUTTONS_ONLY_RADIUS_DP = 30f
const val BUTTONS_ONLY_INSET_DP = 44f
const val CROSS_SPREAD = .30f
const val CROSS_RADIUS = .16f
val DPAD_ORDER = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
val FACE_ORDER = listOf(InputControl.Y, InputControl.B, InputControl.A, InputControl.X)
val GRIPS = listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
}
}
@@ -3,102 +3,78 @@ package com.droiddeck.launcher.input
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.RectF
import android.os.Build
import android.view.Gravity
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.ui.InputSurfaceView
import com.droiddeck.launcher.ui.PadArt
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
/** Why the controls are hidden while the corner button stays. */
enum class Hidden { BY_TAP, BY_CONTROLLER }
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
private var layout: SavedInputLayout? = null
private val safe = Rect()
private var viewWidth = 0
private var viewHeight = 0
private val placements = object : LinkedHashMap<Placement, List<InputSurfaceElement>>(4, .75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Placement, List<InputSurfaceElement>>) = size > PLACEMENT_CACHE
}
private val quickToggle = QuickToggle(context)
var isButtonsOnly = false
private val corner = CornerButton(context)
var hidden: Hidden? = null
private set
var isQuickHidden = false
private set
var isPinnedOnly = false
private set
val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true
/** Holding the corner button opens DroidDeck's controller menu. */
var onCornerHold: (() -> Unit)? = null
/** The player tapped the corner button. */
var onCornerTap: ((Hidden?) -> Unit)? = null
val inputSurface: InputSurfaceView get() = surface
var onTouchMiss: ((MotionEvent) -> Unit)?
get() = surface.onTouchMiss
set(value) { surface.onTouchMiss = value }
init {
addView(surface, LayoutParams(-1, -1))
val size = (QUICK_HIT_DP * 2 * resources.displayMetrics.density).toInt()
addView(quickToggle, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
val size = (CORNER_HIT_DP * resources.displayMetrics.density).toInt()
addView(corner, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
}
fun updateLayout(value: SavedInputLayout?) {
if (layout == value) return
val kit = PadKit.current(context)
if (layout == value && surface.kit == kit) return
releaseAll()
layout = value
surface.kit = kit
render()
}
fun setButtonsOnly(enabled: Boolean) {
if (isButtonsOnly == enabled) return
fun setHidden(value: Hidden?) {
if (hidden == value) return
releaseAll()
isButtonsOnly = enabled
isQuickHidden = false
hidden = value
render()
}
fun setQuickHidden(hidden: Boolean) {
if (isButtonsOnly || isQuickHidden == hidden) return
releaseAll()
isQuickHidden = hidden
render()
}
fun setPinnedOnly(enabled: Boolean) {
if (isPinnedOnly == enabled) return
releaseAll()
isPinnedOnly = enabled
render()
}
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
private fun placed(): List<InputSurfaceElement> {
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
return placements.getOrPut(key) {
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock)
}
}
private fun render() {
val elements = placed()
surface.updateCustomLayout(when {
isPinnedOnly -> elements.filter { it.alwaysShown }
isQuickHidden -> elements.filter { it.id == "builtin:keyboard" || it.alwaysShown }
else -> elements
})
val style = layout?.style ?: InputSurfaceStyle()
surface.updateStyle(style)
quickToggle.tint = style.tint
quickToggle.alpha = style.opacity / 100f
quickToggle.visibility = if (isButtonsOnly || isPinnedOnly || layout == null || dock != null) GONE else VISIBLE
quickToggle.invalidate()
val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock)
surface.updateCustomLayout(if (hidden != null) placed.filter { it.alwaysShown } else placed)
surface.updateStyle(layout?.style ?: InputSurfaceStyle())
corner.visibility = if (layout == null || dock != null) GONE else VISIBLE
corner.alpha = (layout?.style?.opacity ?: 100) / 100f
corner.invalidate()
}
fun takesTouchAt(x: Float, y: Float) = surface.takesTouchAt(x, y) ||
quickToggle.visibility == VISIBLE && x >= quickToggle.left && x < quickToggle.right && y >= quickToggle.top && y < quickToggle.bottom
corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom
fun cornerTakes(x: Float, y: Float) = corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom
fun releaseAll() = surface.releaseInputs()
fun reload() { releaseAll(); placements.clear(); render() }
fun reload() { releaseAll(); surface.kit = PadKit.current(context); render() }
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val w = MeasureSpec.getSize(widthMeasureSpec)
@@ -115,14 +91,14 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
val offset = ((QUICK_CENTER_DP - QUICK_HIT_DP) * resources.displayMetrics.density).toInt()
val params = quickToggle.layoutParams as LayoutParams
val left = (cutout?.safeInsetLeft ?: 0) + offset
val bottom = (cutout?.safeInsetBottom ?: 0) + offset
val margin = (CORNER_MARGIN_DP * resources.displayMetrics.density).toInt()
val params = corner.layoutParams as LayoutParams
val left = (cutout?.safeInsetLeft ?: 0) + margin
val bottom = (cutout?.safeInsetBottom ?: 0) + margin
if (params.leftMargin != left || params.bottomMargin != bottom) {
params.leftMargin = left
params.bottomMargin = bottom
quickToggle.layoutParams = params
corner.layoutParams = params
}
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
if (fresh != safe) {
@@ -132,42 +108,45 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
return super.onApplyWindowInsets(insets)
}
private inner class QuickToggle(context: Context) : View(context) {
var tint: Int? = ControllerPrefs.STEAM_BLUE
private val density = resources.displayMetrics.density
private inner class CornerButton(context: Context) : View(context) {
private val art = PadArt(context)
private val badge = Paint(Paint.ANTI_ALIAS_FLAG)
private var armed = false
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 1.5f * density }
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
textSize = 22 * density
}
private var held = false
private val hold = Runnable { if (armed) { held = true; performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } }
override fun onDraw(canvas: Canvas) {
val x = width / 2f
val y = height / 2f
val radius = QUICK_RADIUS_DP * density
val color = tint
fill.color = if (color != null) InputSurfaceView.shade(color, 190, 0.12f) else (InputSurfaceView.SURFACE and 0x00ffffff) or (190 shl 24)
canvas.drawCircle(x, y, radius, fill)
stroke.color = if (color != null) InputSurfaceView.light(color, 150, 0.25f) else InputSurfaceView.LINE
canvas.drawCircle(x, y, radius, stroke)
text.color = if (color != null) InputSurfaceView.light(color, 210, 0.75f) else InputSurfaceView.TEXT
canvas.drawText(if (isQuickHidden) "+" else "−", x, y + text.textSize * 0.35f, text)
val w = width.toFloat(); val h = height.toFloat()
val dimmed = hidden != null && !armed
if (dimmed) canvas.saveLayerAlpha(0f, 0f, w, h, 170)
art.system(canvas, w, h, PadArt.Shape.ROUND, PadArt.Icon.MARK, armed)
if (dimmed) canvas.restore()
if (hidden == Hidden.BY_CONTROLLER) {
val d = art.density
val r = RectF(w - 15 * d, 3 * d, w - 2 * d, 12 * d)
badge.style = Paint.Style.FILL; badge.color = Color.rgb(0x16, 0x19, 0x1E)
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge)
badge.style = Paint.Style.STROKE; badge.strokeWidth = 1.3f * d; badge.color = Color.rgb(0xFF, 0xB3, 0x47)
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge)
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> armed = true
MotionEvent.ACTION_CANCEL -> armed = false
MotionEvent.ACTION_DOWN -> { armed = true; held = false; postDelayed(hold, ViewConfiguration.getLongPressTimeout().toLong()); invalidate() }
MotionEvent.ACTION_CANCEL -> { armed = false; removeCallbacks(hold); invalidate() }
MotionEvent.ACTION_UP -> {
if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
removeCallbacks(hold)
if (armed && held) post { onCornerHold?.invoke() }
else if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
setQuickHidden(!isQuickHidden)
val next = if (hidden == null) Hidden.BY_TAP else null
setHidden(next)
onCornerTap?.invoke(next)
}
armed = false
invalidate()
}
}
return true
@@ -175,9 +154,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
}
private companion object {
const val QUICK_CENTER_DP = 34f
const val QUICK_HIT_DP = 26f
const val QUICK_RADIUS_DP = 18f
const val PLACEMENT_CACHE = 4
const val CORNER_HIT_DP = 48f
const val CORNER_MARGIN_DP = 4f
}
}
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
@@ -20,25 +19,31 @@ object OnScreenLayout {
}
}
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
/**
* The built-in gamepad keeps no kit positions until its kit is edited; until then the kit follows the virtual controller and
* the layout stores only the keys and controls the player added on top.
*/
fun generated(layout: SavedInputLayout) = (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY) &&
!layout.kitless && layout.elements.none { KitLayout.isKit(it.id) }
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null): List<InputSurfaceElement> {
val stored = layout?.elements ?: return emptyList()
if (width <= 0 || height <= 0) return stored
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
val (reference, generated) = reference(context, layout, width, height)
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
val placed = when {
gamepad.isEmpty() -> emptyList()
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
else -> generator.regenerate(gamepad)
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null): List<InputSurfaceElement> {
layout ?: return emptyList()
if (width <= 0 || height <= 0) return layout.elements
if (generated(layout)) {
val kit = PadKit.current(context)
val extras = if (layout.elements.isEmpty()) emptyList() else fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
return (if (dock != null) KitLayout.dock(context, kit, width, height, dock.portrait, dock.left, dock.right)
else KitLayout.elements(context, kit, width, height, safe, layout.scale)) + extras
}
val byId = (placed + others).associateBy { it.id }
return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
return fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect())
fun editorFrame(layout: SavedInputLayout, displayed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = displayed.associateBy { it.id }
return layout.elements.map { byId[it.id] ?: it }
}
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
@@ -64,32 +69,8 @@ object OnScreenLayout {
}
}
private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
reference(context, layout, width, height).takeIf { it.second }?.first?.let { it.first.toInt() to it.second.toInt() }
private fun reference(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Pair<Float, Float>, Boolean> {
val (display, metrics) = InputLibraries.primaryDisplay(context)
val long = max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
val short = min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
val gamepad = layout.elements.filter(::isGamepad)
if (gamepad.any { it.id.startsWith("legacy:") }) {
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
for ((w, h) in listOfNotNull(named, width to height, long to short, short to long).distinct()) {
if (matches(gamepad, LegacyGamepadLayout(display, w, h, scale = layout.scale).elements())) return (w.toFloat() to h.toFloat()) to true
}
}
val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short)
return (aspect to 1f) to false
}
private fun matches(stored: List<InputSurfaceElement>, generated: List<InputSurfaceElement>): Boolean {
val byId = generated.associateBy { it.id }
return stored.all { e ->
val g = byId[e.id] ?: return@all false
abs(e.x - g.x) <= TOLERANCE && abs(e.y - g.y) <= TOLERANCE && abs(e.width - g.width) <= TOLERANCE && abs(e.height - g.height) <= TOLERANCE
}
private fun aspect(context: Context, layout: SavedInputLayout): Float = layout.aspect.takeIf { it > 0f } ?: run {
val metrics = InputLibraries.primaryDisplay(context).second
max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1).toFloat() / min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
}
}
@@ -12,6 +12,8 @@ import com.droiddeck.launcher.session.SessionState;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicIntegerArray;
public final class PadBridge {
@@ -56,6 +58,7 @@ public final class PadBridge {
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS];
private final float[][] rawSticks = new float[SLOTS][4];
private final Map<Integer, Boolean> rightStickLayouts = new HashMap<>();
private final boolean[][] keyTriggers = new boolean[SLOTS][2];
private final int[] retainedSticks = new int[SLOTS];
private final PadState effectiveState = new PadState();
@@ -104,6 +107,8 @@ public final class PadBridge {
private volatile Runnable onPlayerInput;
private Runnable onChordInput;
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private volatile Runnable onPhysicalInput;
private final java.util.concurrent.atomic.AtomicBoolean physicalInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private static final long STATS_WINDOW_MS = 10_000;
private int statButtons, statAxes, statOnScreen, statDropped;
@@ -240,6 +245,7 @@ public final class PadBridge {
clearBackQamWrites();
releaseBackPaddles();
activeControllerId = NO_CONTROLLER;
rightStickLayouts.clear();
for (int slot = 0; slot < SLOTS; slot++) {
owners[slot] = NO_CONTROLLER;
partners[slot] = NO_CONTROLLER;
@@ -364,6 +370,20 @@ public final class PadBridge {
onPlayerInput = listener;
}
/** Input from a controller the player holds, never from the on-screen controls. */
public void setOnPhysicalInput(Runnable listener) {
onPhysicalInput = listener;
}
private void notePhysicalInput() {
Runnable listener = onPhysicalInput;
if (listener == null || !physicalInputPosted.compareAndSet(false, true)) return;
mainHandler.post(() -> {
physicalInputPosted.set(false);
listener.run();
});
}
public synchronized void setOnChordInput(Runnable listener) {
onChordInput = listener;
}
@@ -429,7 +449,7 @@ public final class PadBridge {
}
noteDevice(device, slot);
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
if (pressed) notePlayerInput();
if (pressed) { notePlayerInput(); notePhysicalInput(); }
statButtons++;
scheduleStats();
publish(slot);
@@ -517,7 +537,7 @@ public final class PadBridge {
retainStick(slot, side, x, y);
projectSticks(slot);
if (chordStickInput) noteChordInput(slot);
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) { notePlayerInput(); notePhysicalInput(); }
publish(slot);
InputTiming.end(timing);
return true;
@@ -525,20 +545,23 @@ public final class PadBridge {
float lx = event.getAxisValue(MotionEvent.AXIS_X);
float ly = event.getAxisValue(MotionEvent.AXIS_Y);
boolean wired = wiredXboxLayout(device, event.getSource());
float rx = event.getAxisValue(wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
float ry = event.getAxisValue(wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
boolean rxRyStick = rightStickUsesRxRy(event, device, rightStickLayouts);
float rx = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
float ry = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
retainStick(slot, JoyCon.LEFT, lx, ly);
retainStick(slot, JoyCon.RIGHT, rx, ry);
projectSticks(slot);
int source = event.getSource();
float lt = 0f;
float rt = 0f;
if (wired || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) {
lt = axisTrigger(leftTrigger(event, wired), keyTriggers[slot], 0);
boolean signedLeft = signedZTriggers(event, device, wired, rxRyStick, true);
boolean signedRight = signedZTriggers(event, device, wired, rxRyStick, false);
if (signedLeft || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) {
lt = axisTrigger(triggerValue(event, device, wired, rxRyStick, true), keyTriggers[slot], 0);
pad.leftTrigger = lt;
}
if (wired || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) {
rt = axisTrigger(rightTrigger(event, wired), keyTriggers[slot], 1);
if (signedRight || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) {
rt = axisTrigger(triggerValue(event, device, wired, rxRyStick, false), keyTriggers[slot], 1);
pad.rightTrigger = rt;
}
if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) {
@@ -556,6 +579,7 @@ public final class PadBridge {
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();
notePhysicalInput();
}
publish(slot);
InputTiming.end(timing);
@@ -596,6 +620,92 @@ public final class PadBridge {
return false;
}
static boolean rightStickUsesRxRy(MotionEvent event, InputDevice device, Map<Integer, Boolean> layouts) {
int source = event.getSource();
if (wiredXboxLayout(device, source)) return true;
boolean hasRxRy = hasAxis(device, source, MotionEvent.AXIS_RX)
&& hasAxis(device, source, MotionEvent.AXIS_RY);
boolean hasZRz = hasAxis(device, source, MotionEvent.AXIS_Z)
&& hasAxis(device, source, MotionEvent.AXIS_RZ);
if (!hasRxRy) return false;
if (!hasZRz) return true;
Boolean cached = layouts.get(event.getDeviceId());
if (cached != null) return cached;
boolean rxRyEvidence = atMinimum(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)
&& nearCentre(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY);
boolean zRzEvidence = atMinimum(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY)
&& nearCentre(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ);
if (rxRyEvidence == zRzEvidence) return false;
boolean useRxRy = rxRyEvidence;
layouts.put(event.getDeviceId(), useRxRy);
return useRxRy;
}
static boolean signedZTriggers(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) {
if (wired) return true;
if (!rxRyStick) return false;
int source = event.getSource();
int signedAxis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ;
int dedicatedAxis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER;
int alternateAxis = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS;
return hasAxis(device, source, signedAxis)
&& !hasAxis(device, source, dedicatedAxis, alternateAxis);
}
static float triggerValue(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) {
if (signedZTriggers(event, device, wired, rxRyStick, left)) {
int axis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ;
float value = event.getAxisValue(axis);
if (!wired && device != null) {
InputDevice.MotionRange range = device.getMotionRange(axis, event.getSource());
if (range != null && range.getMax() > range.getMin()) {
return Math.max(0f, Math.min(1f,
(value - range.getMin()) / (range.getMax() - range.getMin())));
}
}
return Math.max(0f, Math.min(1f, (value + 1f) / 2f));
}
int source = event.getSource();
int axis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER;
int alternate = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS;
if (device == null) {
float value = event.getAxisValue(axis);
return value != 0f ? value : event.getAxisValue(alternate);
}
if (hasAxis(device, source, axis)) {
float value = event.getAxisValue(axis);
return value != 0f ? value : event.getAxisValue(alternate);
}
if (hasAxis(device, source, alternate)) return event.getAxisValue(alternate);
return 0f;
}
private static float restDistance(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) {
return (restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis))
+ restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis))) / 2f;
}
private static float restDistance(InputDevice.MotionRange range, float value) {
float span = range.getMax() - range.getMin();
if (span <= 0f) return 1f;
return Math.abs(value - (range.getMin() + range.getMax()) / 2f) / span;
}
private static boolean atMinimum(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) {
return atMinimum(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis))
&& atMinimum(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis));
}
private static boolean atMinimum(InputDevice.MotionRange range, float value) {
float span = range.getMax() - range.getMin();
return value - range.getMin() <= span * 0.02f;
}
private static boolean nearCentre(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) {
return restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis)) <= 0.1f
&& restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis)) <= 0.1f;
}
public interface TouchRoute {
boolean active();
@@ -1182,16 +1292,4 @@ public final class PadBridge {
&& device.getMotionRange(MotionEvent.AXIS_RZ, source) != null;
}
public static float leftTrigger(MotionEvent event, boolean wired) {
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_Z) + 1f) / 2f));
float value = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_BRAKE);
}
public static float rightTrigger(MotionEvent event, boolean wired) {
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_RZ) + 1f) / 2f));
float value = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_GAS);
}
}
@@ -0,0 +1,48 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS }
enum class DpadStyle { CROSS, DISC, ARROWS }
enum class StickCap { RINGED, DISHED, KNURLED }
enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) {
STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true),
DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED),
DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED);
val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER
val playStation get() = this == DUALSHOCK || this == DUALSENSE
fun label(control: InputControl): String = when (control) {
InputControl.LB -> if (xbox) "LB" else "L1"
InputControl.RB -> if (xbox) "RB" else "R1"
InputControl.LT -> if (xbox) "LT" else "L2"
InputControl.RT -> if (xbox) "RT" else "R2"
else -> control.label
}
/** What the player calls [control] on this controller. */
fun name(control: InputControl): String = if (!playStation) label(control) else when (control) {
InputControl.A -> "Cross"
InputControl.B -> "Circle"
InputControl.X -> "Square"
InputControl.Y -> "Triangle"
else -> label(control)
}
companion object {
fun of(type: String) = when (type) {
SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER
SessionPrefs.CONTROLLER_XBOX360 -> XBOX
SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK
SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE
else -> STEAM_DECK
}
fun current(context: Context) = of(SessionPrefs.steamController(context))
}
}
@@ -42,6 +42,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
private val total = Sticks()
private val triggerAxes = HashMap<Int, Boolean>()
private val wiredLayout = HashMap<Int, Boolean>()
private val rightStickLayouts = HashMap<Int, Boolean>()
private val down = HashMap<Int, MutableSet<Int>>()
private val sent = HashMap<Int, IntArray>()
private val held = LinkedHashMap<Int, Int>()
@@ -87,14 +88,21 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
fun onMotion(event: MotionEvent): Boolean {
if (event.actionMasked != MotionEvent.ACTION_MOVE) return true
val sticks = physical.getOrPut(event.deviceId) { Sticks() }
val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) }
val device = event.device
val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(device, event.source) }
val rxRyStick = PadBridge.rightStickUsesRxRy(event, device, rightStickLayouts)
sticks.leftX = event.getAxisValue(MotionEvent.AXIS_X)
sticks.leftY = event.getAxisValue(MotionEvent.AXIS_Y)
sticks.rightX = scrollAxis(event, if (wired) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z)
sticks.rightY = scrollAxis(event, if (wired) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ)
if (hasTriggerAxes(event)) {
sticks.leftTrigger = PadBridge.leftTrigger(event, wired)
sticks.rightTrigger = PadBridge.rightTrigger(event, wired)
sticks.rightX = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z)
sticks.rightY = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ)
val signedLeft = PadBridge.signedZTriggers(event, device, wired, rxRyStick, true)
val signedRight = PadBridge.signedZTriggers(event, device, wired, rxRyStick, false)
val analogTriggers = hasTriggerAxes(event)
if (analogTriggers || signedLeft) {
sticks.leftTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, true)
}
if (analogTriggers || signedRight) {
sticks.rightTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, false)
}
val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X)
val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
@@ -129,6 +137,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
physical.clear()
triggerAxes.clear()
wiredLayout.clear()
rightStickLayouts.clear()
touch.clear()
down.clear()
sent.clear()
@@ -207,6 +216,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
private fun hasTriggerAxes(event: android.view.InputEvent): Boolean = triggerAxes.getOrPut(event.deviceId) {
val device = event.device ?: return@getOrPut true
device.getMotionRange(MotionEvent.AXIS_LTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_BRAKE) != null ||
device.getMotionRange(MotionEvent.AXIS_RTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_GAS) != null ||
(event is MotionEvent && wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) })
}
@@ -25,7 +25,10 @@ data class PhysicalInputKey(val device: String, val name: String, val keyCode: I
data class PhysicalInputBinding(val key: PhysicalInputKey, val action: InputAction)
class PhysicalInputBindings(private val router: InputRouter) {
class PhysicalInputBindings(
private val router: InputRouter,
private val onPress: (KeyEvent) -> Unit = {},
) {
private class Entry(val binding: PhysicalInputBinding, val channel: InputRouter.Channel) {
var heldDevice = -1
var suppressed = false
@@ -66,7 +69,10 @@ class PhysicalInputBindings(private val router: InputRouter) {
if (identity != key.device) continue
entry.heldDevice = event.deviceId
entry.suppressed = event.repeatCount != 0
if (!entry.suppressed) entry.channel.update(1f)
if (!entry.suppressed) {
entry.channel.update(1f)
onPress(event)
}
return true
}
return false
@@ -42,6 +42,7 @@ class ScrollTouchGestures(
private var flingY = 0f
private var flingAt = 0L
private var flinging = false
var clicks = true
private val longPress = Runnable {
held = true
@@ -86,7 +87,7 @@ class ScrollTouchGestures(
lastY = startY
tracker = VelocityTracker.obtain().also { it.addMovement(event) }
listener.onMove(startX, startY)
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS)
}
MotionEvent.ACTION_MOVE -> {
val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true
@@ -153,6 +154,7 @@ class ScrollTouchGestures(
private fun click(button: Int) {
releaseClick()
if (!clicks) return
listener.onButton(button, true)
clicked = button
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
@@ -40,6 +40,18 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
data class SecondScreenDisplay(val id: Int, val label: String)
object SecondScreenDisplays {
fun selection(selected: Int, available: List<Int>, gameRequested: Boolean): Int =
if (selected in available || gameRequested && selected >= 0) selected else available.firstOrNull() ?: -1
fun selection(selected: Int, available: List<Int>, gameRequested: Boolean, save: (Int) -> Unit): Int =
selection(selected, available, gameRequested).also { if (it != selected) save(it) }
fun keyboardOnPrimary(gameRequested: Boolean, selected: Int, available: List<Int>, visible: Boolean = true, taken: (Int) -> Boolean): Boolean =
visible && gameRequested && selected >= 0 && (selected !in available || taken(selected))
fun routeKeyboard(steam: Boolean, enabled: Boolean, panel: Boolean, dock: Boolean, primaryFallback: Boolean): Boolean =
steam && enabled && (panel || dock || primaryFallback)
fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List<SecondScreenDisplay> =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION)
.asSequence()
@@ -178,4 +178,56 @@ class ShortcutsRelay : Service(), InputManager.InputDeviceListener {
private companion object {
const val KEY_TIMEOUT_MS = 200L
}
// Frontends such as Cocoon treat a running player process as an open game, so the relay runs only while a screen is started.
object Holder : android.app.Application.ActivityLifecycleCallbacks, android.content.ServiceConnection {
private const val RELEASE_MS = 1_000L
private val handler = Handler(Looper.getMainLooper())
private var app: android.app.Application? = null
private var started = 0
private var bound = false
private val release = Runnable { unbind() }
fun install(application: android.app.Application) {
app?.unregisterActivityLifecycleCallbacks(this)
handler.removeCallbacks(release)
started = 0
bound = false
app = application
application.registerActivityLifecycleCallbacks(this)
}
override fun onActivityStarted(activity: android.app.Activity) {
started++
handler.removeCallbacks(release)
if (!bound) bind()
}
override fun onActivityStopped(activity: android.app.Activity) {
started = (started - 1).coerceAtLeast(0)
if (started == 0) handler.postDelayed(release, RELEASE_MS)
}
private fun bind() {
val context = app ?: return
if (runCatching { context.packageManager.getPackageInfo(Relay.PACKAGE, 0) }.isFailure) return
bound = runCatching {
context.bindService(Intent(context, ShortcutsRelay::class.java), this, Context.BIND_AUTO_CREATE)
}.getOrDefault(false)
}
private fun unbind() {
if (!bound) return
bound = false
runCatching { app?.unbindService(this) }
}
override fun onServiceConnected(name: android.content.ComponentName?, service: IBinder?) = Unit
override fun onServiceDisconnected(name: android.content.ComponentName?) = Unit
override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit
override fun onActivityResumed(activity: android.app.Activity) = Unit
override fun onActivityPaused(activity: android.app.Activity) = Unit
override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit
override fun onActivityDestroyed(activity: android.app.Activity) = Unit
}
}
@@ -20,7 +20,11 @@ import java.util.ArrayDeque
import java.util.UUID
@SuppressLint("MissingPermission")
class SteamControllerBle(private val context: Context, router: InputRouter? = null) {
class SteamControllerBle(
private val context: Context,
router: InputRouter? = null,
private val onPhysicalInput: (() -> Unit)? = null,
) {
private val inputLock = router ?: Any()
private var routedInput = router?.let(::TritonInputRouter)
@Volatile private var stopped = false
@@ -39,6 +43,7 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
private var outputSequence = 0L
private var outputWritePending = false
private var featureRead = 0L
private var lastPressedControls = 0
fun start(): Unit = synchronized(inputLock) {
if (stopped || started) return@synchronized
@@ -266,12 +271,18 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
val timing = InputTiming.begin()
FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data)
InputTiming.end(timing)
if (connected && onPhysicalInput != null) {
val pressed = TritonInputRouter.pressedControls(data)
if (pressed and lastPressedControls.inv() != 0) onPhysicalInput()
lastPressedControls = pressed
}
}
private fun release() = synchronized(inputLock) {
if (stopped) return@synchronized
routedInput?.release()
withSlot {
lastPressedControls = 0
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
}
}
@@ -166,21 +166,14 @@ object SteamTouchConfig {
fun steamRoot(context: Context) = com.droiddeck.launcher.session.SessionPrefs.activeSteamRoot(context)
private fun controllerConfigs(context: Context) = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
fun configDir(context: Context): File? {
val base = controllerConfigs(context)
val base = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
val account = accountId(context)
if (account != null) File(base, "$account/config").takeIf { it.isDirectory }?.let { return it }
return base.listFiles()?.filter { it.name.all(Char::isDigit) && File(it, "config").isDirectory }
?.maxByOrNull { it.lastModified() }?.let { File(it, "config") }
}
private fun writableConfigDir(context: Context): File? {
val account = accountId(context) ?: return configDir(context)
return File(controllerConfigs(context), "$account/config").apply { mkdirs() }.takeIf { it.isDirectory }
}
private fun accountId(context: Context): Long? = try {
val users = KeyValues.parse(File(steamRoot(context), "config/loginusers.vdf").readText())
val node = users.child("users")
@@ -204,7 +197,7 @@ object SteamTouchConfig {
}
return try {
val text = file.readText()
val kv = KeyValues.parse(text)
val kv = KeyValues.parse(text.removePrefix(""))
val mappings = kv.child("controller_mappings") ?: kv
val layouts = mappings.string("touch_layout")?.let { hex -> decodeLayouts(hexToBytes(hex)) }
Log.i(TAG, "steam touch: app $appId uses ${file.path} (${layouts?.layouts?.size ?: 0} layouts)")
@@ -396,9 +389,8 @@ object SteamTouchConfig {
bindings: Map<SteamTouchBindings.Ref, (SteamTouchBindings.Binding) -> SteamTouchBindings.Binding> = emptyMap(),
options: Options? = null,
): File? {
val dir = writableConfigDir(context) ?: return null.also { Log.w(TAG, "steam touch: no controller config folder to save app $appId in") }
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n"
else return null.also { Log.w(TAG, "steam touch: ${config.file?.path ?: "default layout"} has no readable text to save into") }
val dir = configDir(context) ?: return null
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n" else return null
val source = bindings.entries.fold(base) { text, (ref, change) ->
SteamTouchBindings.rewrite(text, ref, change) ?: text
}
@@ -416,11 +408,11 @@ object SteamTouchConfig {
val existing = Regex("""\n\s*"touch_layout"\s+"[0-9a-fA-F]*"""")
val text = if (existing.containsMatchIn(source)) source.replace(existing, "\n$line")
else source.replaceFirst(Regex("""("controller_type"\s+"controller_mobile_touch"[^\n]*)"""), "$1\n$line")
if (!text.contains("touch_layout")) return null.also { Log.w(TAG, "steam touch: ${config.file?.path} is no controller_mobile_touch config") }
if (!text.contains("touch_layout")) return null
target.parentFile?.mkdirs()
val tmp = File(target.path + ".tmp")
tmp.writeText(text)
if (!tmp.renameTo(target)) return null.also { Log.w(TAG, "steam touch: could not replace ${target.path}") }
if (!tmp.renameTo(target)) return null
selectAutosave(dir, key)
dropDeviceEntry(dir, key)
Log.i(TAG, "steam touch: saved layouts ${sets.keys} for app $appId to ${target.path}")
@@ -438,13 +430,12 @@ object SteamTouchConfig {
private fun selectAutosave(dir: File, key: String) {
val file = File(dir, CONFIGSET)
val root = file.takeIf { it.isFile }?.readText()?.let(KeyValues::parse)?.takeIf { it.child("controller_config") != null }
?: KeyValues.Node(mutableListOf("controller_config" to KeyValues.Node()))
val config = root.child("controller_config") ?: return
val entry = key to KeyValues.Node(mutableListOf("autosave" to "1"))
val at = config.entries.indexOfFirst { it.first.equals(key, true) && it.second is KeyValues.Node }
if (at >= 0) config.entries[at] = entry else config.entries += entry
File(file.path + ".tmp").apply { writeText(KeyValues.write(root)) }.renameTo(file)
val text = if (file.isFile) file.readText() else "\"controller_config\"\n{\n}\n"
val entry = "\t\"$key\"\n\t{\n\t\t\"autosave\"\t\t\"1\"\n\t}"
val block = Regex("""\n\s*"${Regex.escape(key)}"\s*\{[^}]*\}""", RegexOption.IGNORE_CASE)
val next = if (block.containsMatchIn(text)) text.replace(block) { "\n$entry" }
else text.substring(0, text.lastIndexOf('}')).trimEnd() + "\n$entry\n}\n"
File(file.path + ".tmp").apply { writeText(next) }.renameTo(file)
}
@@ -602,48 +593,34 @@ class KeyValues private constructor() {
fun string(key: String): String? = entries.firstOrNull { it.first.equals(key, true) && it.second is String }?.second as String?
}
private class Token(val text: String, val quoted: Boolean) {
val opens get() = !quoted && text == "{"
val closes get() = !quoted && text == "}"
}
companion object {
fun write(node: Node): String = write(node, "")
private fun write(node: Node, indent: String): String = node.entries.joinToString("") { (key, value) ->
if (value is Node) "$indent\"${escape(key)}\"\n$indent{\n${write(value, "$indent\t")}$indent}\n"
else "$indent\"${escape(key)}\"\t\t\"${escape(value.toString())}\"\n"
}
private fun escape(text: String) = text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\t", "\\t")
fun parse(text: String): Node {
val tokens = tokenize(text.removePrefix("\uFEFF"))
val tokens = tokenize(text)
var i = 0
fun node(): Node {
val n = Node()
while (i < tokens.size) {
val t = tokens[i++]
if (t.closes) return n
if (t.opens) continue
if (t == "}" ) return n
if (t == "{") continue
if (i >= tokens.size) break
val next = tokens[i]
if (next.opens) { i++; n.entries += t.text to node() } else { i++; n.entries += t.text to next.text }
if (next == "{") { i++; n.entries += t to node() } else { i++; n.entries += t to next }
}
return n
}
return node()
}
private fun tokenize(text: String): List<Token> {
val out = mutableListOf<Token>()
private fun tokenize(text: String): List<String> {
val out = mutableListOf<String>()
var i = 0
while (i < text.length) {
val c = text[i]
when {
c.isWhitespace() -> i++
c == '/' && i + 1 < text.length && text[i + 1] == '/' -> while (i < text.length && text[i] != '\n') i++
c == '{' || c == '}' -> { out += Token(c.toString(), false); i++ }
c == '{' || c == '}' -> { out += c.toString(); i++ }
c == '"' -> {
val sb = StringBuilder()
i++
@@ -655,13 +632,13 @@ class KeyValues private constructor() {
i++
}
i++
out += Token(sb.toString(), true)
out += sb.toString()
}
c == '[' -> { while (i < text.length && text[i] != ']') i++; i++ }
else -> {
val start = i
while (i < text.length && !text[i].isWhitespace() && text[i] != '{' && text[i] != '}' && text[i] != '"') i++
out += Token(text.substring(start, i), false)
out += text.substring(start, i)
}
}
}
@@ -119,6 +119,7 @@ class SteamTouchControls(
private var selectedArm = 0
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val art = com.droiddeck.launcher.ui.PadArt(context)
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; isFakeBoldText = true }
@@ -240,7 +241,10 @@ class SteamTouchControls(
private fun cx(e: Element) = e.x * width
private fun cy(e: Element) = e.y * height
private fun reach(e: Element, x: Float, y: Float) = hypot((x - cx(e)) / radius(e), (y - cy(e)) / radiusY(e))
private fun reach(e: Element, x: Float, y: Float): Float {
val dx = (x - cx(e)) / radius(e); val dy = (y - cy(e)) / radiusY(e)
return if (e.type in TRACKPADS) max(abs(dx), abs(dy)) else hypot(dx, dy)
}
private fun hit(list: List<Element>, x: Float, y: Float): Element? =
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
@@ -281,58 +285,61 @@ class SteamTouchControls(
val r = radius(e)
val pressed = !editing && e.type in pressedTypes()
val alpha = (255 * alphaScale * if (faded) FADED else 1f).toInt().coerceIn(30, 255)
val ink = Color.argb(alpha, Color.red(tint), Color.green(tint), Color.blue(tint))
stroke.color = if (isSelected) Color.rgb(26, 159, 255) else ink
stroke.strokeWidth = if (isSelected) lineWidth() * 2f else lineWidth()
fill.color = Color.argb((alpha * 0.85f).toInt(), 230, 233, 236)
text.color = ink
text.typeface = android.graphics.Typeface.DEFAULT_BOLD
stroke.color = Color.rgb(Color.red(tint), Color.green(tint), Color.blue(tint)); stroke.strokeWidth = lineWidth()
fill.color = Color.argb(217, 230, 233, 236)
if (alpha < 255) canvas.saveLayerAlpha(x - r * 1.5f, y - r * 1.5f, x + r * 1.5f, y + r * 1.5f, alpha)
when (e.type) {
SteamTouchConfig.DPAD -> drawDpad(canvas, e, x, y, r)
SteamTouchConfig.DPAD -> if (visuals[SteamTouchConfig.DPAD].orEmpty().any { it.binding?.hasIcon == true }) drawDpad(canvas, e, x, y, r) else {
val bits = if (editing) 0L else dpadBits(e)
val held = (if (bits and DPAD_UP != 0L) 1 else 0) or (if (bits and DPAD_RIGHT != 0L) 2 else 0) or
(if (bits and DPAD_DOWN != 0L) 4 else 0) or (if (bits and DPAD_LEFT != 0L) 8 else 0)
canvas.save(); canvas.translate(x - r, y - r)
art.dpad(canvas, 2 * r, 2 * r, PadKit.STEAM_DECK, held, ink = glyphInk())
canvas.restore()
}
SteamTouchConfig.JOYSTICK_LEFT, SteamTouchConfig.JOYSTICK_RIGHT -> {
canvas.drawCircle(x, y, r, stroke)
val f = fingers.values.firstOrNull { it.element?.type == e.type }
if (f != null && !editing) {
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
var kx = 0f; var ky = 0f
if (f != null) {
val d = hypot(f.x - x, f.y - y)
val k = if (d > r) r / d else 1f
val kx = x + (f.x - x) * k
val ky = y + (f.y - y) * k
canvas.drawCircle(kx, ky, r * 0.42f, fill)
kx = (f.x - x) * k * .54f; ky = (f.y - y) * k * .54f
}
art.stick(canvas, x, y, r, PadKit.STEAM_DECK, kx, ky, f != null)
}
SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER -> {
val rect = RectF(x - r * 1.3f, y - r * 0.85f, x + r * 1.3f, y + r * 0.85f)
if (pressed) canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, fill)
canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, stroke)
if (editing) {
text.textSize = r * 0.3f
text.color = Color.argb(alpha / 2, 255, 255, 255)
canvas.drawText(context.getString(R.string.deck_surface_trackpad), x, y - (text.descent() + text.ascent()) / 2, text)
}
}
SteamTouchConfig.STEAM -> {
if (isSelected) canvas.drawCircle(x, y, r, stroke)
drawMark(canvas, x, y, r * 0.5f, if (pressed) accent else ink, alpha)
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
canvas.save(); canvas.translate(x - r, y - r)
art.trackpad(canvas, r * 2f, r * 2f, f != null, (f?.x ?: x) - x + r, (f?.y ?: y) - y + r)
canvas.restore()
if (editing) art.text(canvas, context.getString(R.string.deck_surface_trackpad), x, y, r * .3f, Color.argb(128, 255, 255, 255))
}
SteamTouchConfig.STEAM -> systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.PILL, com.droiddeck.launcher.ui.PadArt.Icon.STEAM, pressed)
SteamTouchConfig.SELECT, SteamTouchConfig.START -> {
val binding = visuals[e.type]?.firstOrNull()?.binding
if (binding?.hasIcon == true) {
drawFace(canvas, e.type, binding, x, y, r, alpha, pressed); return
}
val rect = RectF(x - r * 1.08f, y - r * 0.55f, x + r * 1.08f, y + r * 0.55f)
if (pressed) canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, fill)
canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, stroke)
val t = r * 0.26f
val dir = if (e.type == SteamTouchConfig.START) 1f else -1f
val tri = Path().apply {
moveTo(x + dir * t, y); lineTo(x - dir * t * 0.75f, y - t); lineTo(x - dir * t * 0.75f, y + t); close()
}
canvas.drawPath(tri, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (pressed) Color.argb(alpha, 23, 26, 33) else ink })
if (binding?.hasIcon == true) drawFace(canvas, e.type, binding, x, y, r, pressed)
else systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.CHIP,
if (e.type == SteamTouchConfig.START) com.droiddeck.launcher.ui.PadArt.Icon.MENU else com.droiddeck.launcher.ui.PadArt.Icon.VIEW, pressed)
}
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, alpha, pressed)
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, pressed)
}
if (alpha < 255) canvas.restore()
if (isSelected) {
stroke.color = accent; stroke.strokeWidth = lineWidth() * 2f
if (isSquare(e.type)) canvas.drawRoundRect(RectF(x - r, y - r, x + r, y + r), r * .3f, r * .3f, stroke) else canvas.drawCircle(x, y, r, stroke)
}
}
private fun systemButton(canvas: Canvas, x: Float, y: Float, r: Float, shape: com.droiddeck.launcher.ui.PadArt.Shape,
icon: com.droiddeck.launcher.ui.PadArt.Icon, pressed: Boolean) {
canvas.save(); canvas.translate(x - r * 1.4f, y - r * 1.4f)
art.system(canvas, r * 2.8f, r * 2.8f, shape, icon, pressed, glyphInk())
canvas.restore()
}
/** Glyphs follow the colour picked for Steam touch controls; white keeps the shared artwork's own ink. */
private fun glyphInk() = if (tint != Color.WHITE) tint else com.droiddeck.launcher.ui.PadArt.INK
private fun isSquare(type: Int) = type in setOf(SteamTouchConfig.BUMPER_LEFT, SteamTouchConfig.BUMPER_RIGHT,
SteamTouchConfig.TRIGGER_LEFT, SteamTouchConfig.TRIGGER_RIGHT, SteamTouchConfig.THUMB, SteamTouchConfig.KEYBOARD,
SteamTouchConfig.PASTE, SteamTouchConfig.MACRO_1_FINGER, SteamTouchConfig.MACRO_2_FINGER) ||
@@ -350,53 +357,29 @@ class SteamTouchControls(
canvas.restore()
}
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float,
alpha: Int, pressed: Boolean) {
val square = isSquare(type)
val rect = RectF(x - r, y - r, x + r, y + r)
val corner = r * 0.3f
fun shape(paint: Paint) = if (square) canvas.drawRoundRect(rect, corner, corner, paint) else canvas.drawCircle(x, y, r, paint)
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float, pressed: Boolean) {
val shape = if (isSquare(type)) art.roundRect(x - r, y - r, x + r, y + r, r * .3f) else art.circle(x, y, r)
val icon = binding?.icon?.takeIf { it.isNotEmpty() }?.let(::iconOrLoad)
val custom = binding != null && binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
art.glass(canvas, shape, pressed && !custom, if (custom) parseColor(binding!!.background, SteamTouchBindings.DEFAULT_BACKGROUND) else 0x850E1014.toInt())
val ink = if (pressed && !custom) com.droiddeck.launcher.ui.PadArt.ON_ACCENT else glyphInk()
if (icon != null) {
val s = r * 0.62f
val custom = binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
if (custom) {
shape(Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = parseColor(binding.background, SteamTouchBindings.DEFAULT_BACKGROUND)
this.alpha = if (pressed) alpha else (alpha * 0.85f).toInt()
})
canvas.drawBitmap(tinted(binding.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { this.alpha = alpha })
} else {
if (pressed) shape(fill)
val ink = if (pressed) Color.argb(alpha, 23, 26, 33) else stroke.color
canvas.drawBitmap(inked(binding.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply {
colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN)
})
}
shape(stroke)
if (custom) canvas.drawBitmap(tinted(binding!!.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s), Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
else canvas.drawBitmap(inked(binding!!.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN) })
return
}
if (pressed) shape(fill)
shape(stroke)
if (type == SteamTouchConfig.THUMB) { drawDots(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
if (type == SteamTouchConfig.KEYBOARD) { drawKeyboardGlyph(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
val own = label(type)
val shown = own
text.textSize = when {
if (type == SteamTouchConfig.THUMB) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.QAM, ink); return }
if (type == SteamTouchConfig.KEYBOARD) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.KEYBOARD, ink); return }
val shown = label(type)
val size = when {
shown.length <= 1 -> r * 0.9f
shown.length <= 2 -> r * 0.66f
shown.length <= 5 -> r * 0.4f
else -> r * 0.3f
}
text.color = when {
pressed -> Color.argb(alpha, 23, 26, 33)
shown == own -> LABEL_COLORS[type]?.let { Color.argb(alpha, Color.red(it), Color.green(it), Color.blue(it)) } ?: text.color
else -> text.color
}
val line = if (shown.length > 10) shown.take(9) + "…" else shown
canvas.drawText(line, x, y - (text.descent() + text.ascent()) / 2, text)
art.text(canvas, if (shown.length > 10) shown.take(9) + "…" else shown, x, y, size, ink, r * 1.8f)
}
private fun drawDots(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
@@ -404,15 +387,6 @@ class SteamTouchControls(
for (i in -1..1) canvas.drawCircle(x + i * r * 0.3f, y + r * 0.22f, r * 0.08f, p)
}
private fun drawKeyboardGlyph(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeWidth = lineWidth() * 0.8f }
val body = RectF(x - r * 0.6f, y - r * 0.34f, x + r * 0.6f, y + r * 0.34f)
canvas.drawRoundRect(body, r * 0.08f, r * 0.08f, p)
val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color }
for (row in 0..1) for (i in 0..5) canvas.drawCircle(body.left + r * 0.15f + i * r * 0.18f, body.top + r * 0.18f + row * r * 0.17f, r * 0.035f, dot)
canvas.drawLine(x - r * 0.3f, body.bottom - r * 0.14f, x + r * 0.3f, body.bottom - r * 0.14f, p)
}
private val iconsLoading = HashSet<String>()
private val inkedIcons = android.util.LruCache<String, android.graphics.Bitmap>(48)
@@ -1478,6 +1452,7 @@ class SteamTouchControls(
var onSaved: () -> Unit = {}
companion object {
private val TRACKPADS = setOf(SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER)
private const val TAG = "SteamTouch"
private const val POLL_MS = 150L
private const val MOVE_REDRAW_MS = 33L
@@ -1519,11 +1494,5 @@ class SteamTouchControls(
put(SteamTouchConfig.PASTE, 0L)
}
private val LABEL_COLORS = mapOf(
SteamTouchConfig.A to Color.rgb(72, 133, 48),
SteamTouchConfig.B to Color.rgb(211, 68, 37),
SteamTouchConfig.X to Color.rgb(23, 60, 184),
SteamTouchConfig.Y to Color.rgb(235, 200, 70),
)
}
}
@@ -17,6 +17,11 @@ class TouchpadGestures(
var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f)
var sensitivity = 1.15f
var desktop = false
var clicks = true
set(value) {
if (field != value) lastTapAt = 0L
field = value
}
private val handler = Handler(Looper.getMainLooper())
private var lastX = 0f
@@ -50,12 +55,17 @@ class TouchpadGestures(
held = true
dragging = true
listener.onLongPress()
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
press(PointerGestures.BTN_LEFT)
}
private val clickUp = Runnable { releaseClick() }
private fun press(button: Int) {
if (clicks) listener.onButton(button, true, x, y)
}
private fun click(button: Int) {
releaseClick()
if (!clicks) return
listener.onButton(button, true, x, y)
clicked = button
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
@@ -108,12 +118,12 @@ class TouchpadGestures(
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
fingers = 1; pinching = false
anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false
if (event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) {
if (clicks && event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
press(PointerGestures.BTN_LEFT)
} else {
dragging = false
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS)
}
return true
}
@@ -153,7 +163,7 @@ class TouchpadGestures(
secondWasTap = false
if (!dragging) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
press(PointerGestures.BTN_LEFT)
}
}
}
@@ -63,16 +63,25 @@ class TritonInputRouter(private val router: InputRouter) {
fun release() = synchronized(router) { channels.forEach { it.release() }; last = null }
fun close() = synchronized(router) { release(); channels.forEach { it.close() }; router.removeSnapshot(snapshot) }
private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or
((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24)
private fun putBits(data: ByteArray, value: Int) { for (i in 0..3) data[i + 1] = (value ushr (i * 8)).toByte() }
private fun short(data: ByteArray, offset: Int) = ((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt()
private fun axis(data: ByteArray, offset: Int): Float = short(data, offset).let { it / if (it < 0) 32768f else 32767f }
private fun shortValue(value: Float) = (value * if (value < 0f) 32768f else 32767f).roundToInt().coerceIn(-32768, 32767)
private fun putShort(data: ByteArray, offset: Int, value: Int) { data[offset] = value.toByte(); data[offset + 1] = (value shr 8).toByte() }
companion object {
private const val CONTROL_BITS = 0x0fffffff
internal fun pressedControls(data: ByteArray): Int {
var active = bits(data) and CONTROL_BITS
if ((5..15 step 2).any { kotlin.math.abs(short(data, it)) > 16384 }) active = active or (1 shl 28)
return active
}
private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or
((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24)
private fun short(data: ByteArray, offset: Int) =
((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt()
private fun bit(c: InputControl): Int = when (c) {
InputControl.A -> 0x1; InputControl.B -> 0x2; InputControl.X -> 0x4; InputControl.Y -> 0x8
InputControl.QAM -> 0x10; InputControl.R3 -> 0x20; InputControl.START -> 0x40
@@ -218,12 +218,15 @@ object BwrapSpawner {
private fun runtimeLib(rootfs: String, name: String): File? =
LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() }
private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
internal fun gpu(
rootfs: String, root: File, env: MutableMap<String, String>,
kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(),
): List<Bind>? {
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
if (driver == null || !File("/dev/kgsl-3d0").exists()) return null
if (driver == null || !kgslAvailable) return null
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
if (env["BL_DESKTOP"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
if (env["LIBGL_ALWAYS_SOFTWARE"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
val binds = arrayListOf(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_freedreno.so"))
for (name in GPU_LIBS) {
val f = runtimeLib(rootfs, name) ?: continue
@@ -21,6 +21,10 @@ object LegacyNames {
"etc/bannerlator-network.json" to "etc/droiddeck-network.json",
"etc/bannerlator-wifi-scan-request" to "etc/droiddeck-wifi-scan-request",
)
private val RETIRED_FILES = listOf("libblsession.so", "libblfastpath.so", "libblaudit.so").map { "usr/local/lib/$it" } +
listOf("x86_64", "i386").map { "usr/local/lib/droiddeck-fex/$it/libblsession.so" }
private const val LEGACY_MARKER = ".bl-"
private val QUEUED_MARKERS = setOf(".bl-proton-extra", ".bl-steam-urls")
private val MENU_REWRITES = listOf(
Triple("usr/local/share/applications", "/usr/local/bin/bannerlator-", "/usr/local/bin/droiddeck-"),
Triple("usr/share/applications", "Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/",
@@ -38,6 +42,20 @@ object LegacyNames {
fun migrateRootfs(root: File) {
migrateEtc(root)
for ((old, new) in MOVED_FILES) move(File(root, old), File(root, new))
for (path in RETIRED_FILES) File(root, path).delete()
File(root, "root").listFiles { f -> f.name.startsWith(LEGACY_MARKER) }?.forEach {
val target = File(it.parentFile, ".dd-" + it.name.removePrefix(LEGACY_MARKER))
if (it.name in QUEUED_MARKERS && it.isFile && !isLink(it) && target.isFile && !isLink(target)) {
val queued = it.readText()
if (queued.isNotBlank()) {
val separator = if (target.length() > 0 && !target.readText().endsWith("\n")) "\n" else ""
target.appendText(separator + if (queued.endsWith("\n")) queued else queued + "\n")
}
FileUtils.delete(it)
} else {
move(it, target)
}
}
linkScripts(root)
rewriteMenuEntries(root)
}
@@ -9,7 +9,7 @@ import java.security.MessageDigest
object ProotFastPath {
private const val TAG = "ProotFastPath"
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
const val LIBRARY = "/usr/local/lib/libddfastpath.so"
const val MAX_BINDS = 256
fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
@@ -315,11 +315,11 @@ object BottomDesktop {
main.post { if (generation == guestGeneration) watchIme(imeDir) }
val binds = LinuxRuntime.binds(context, current.sessionRoot, runtime, Environment.getExternalStorageDirectory(), current.binds)
val guest = ArrayList(current.guest).apply {
add("BL_WIDTH=$width")
add("BL_HEIGHT=$height")
add("BL_DEBUG_DIR=" + dir.path)
add("BL_TOP_SESSION=" + SessionState.mode)
add("BL_IME_DIR=" + imeDir.path)
add("DD_WIDTH=$width")
add("DD_HEIGHT=$height")
add("DD_DEBUG_DIR=" + dir.path)
add("DD_TOP_SESSION=" + SessionState.mode)
add("DD_IME_DIR=" + imeDir.path)
add(SCRIPT)
}
val command = if (current.nativeUserland) {
Loaded 100 of 712 files, more files were not shown because too many files have changed in this diff. Show more