Compare commits

...
Author SHA1 Message Date
Kurt Himebauch 8ec499ae3f fix(session): relaunch into a fresh activity so Switch to Desktop does not leave the loader up (#3227) 2026-11-25 17:34:53 -05:00
The412Banner 53c1933ac8 feat(steam): DroidDeck-Proton first, Valve's ARM64 Proton only when needed (#3217)
New Steam setting "Valve Proton only when needed", on by default. While it is on and DroidDeck-Proton has not been removed by the user:

- the app installs DroidDeck-Proton before the client first starts instead of seeding Valve's Proton Experimental (ARM64) (2.09 GB on disk, 398 MB download); a stop request cancels that download
- the session no longer asks the client for appid 4427310 at every start
- the live helper fetches it only once the default or a title is set to a tool built from it ("Proton Experimental ARM64 (Compatible)"), or while no DroidDeck-Proton build is installed

FEX and the Steam Linux Runtimes are still fetched as before. An installed copy of Valve's Proton is kept and updated. Off, or with DroidDeck-Proton declined, everything works as before (DD_VALVE_PROTON=1). Fresh install on a Pocket FIT: 8.28 GB after first Steam start and tool downloads, was 10.4 GB.
2026-11-25 15:54:48 -05:00
The412Banner 4df3f775e1 fix(runtime): first-run setup no longer crashes when the app is in the background (#3212)
With targetSdk 34, Android refuses startForeground() while the app is in the background. RuntimeInstallService called it unguarded on the main thread, so the refusal (ForegroundServiceStartNotAllowedException) killed the app during first-run setup when the runtime finished while DroidDeck-Proton was still downloading (RuntimeInstallService.kt:49 via onStartCommand :22).

Both foreground starts now catch the refusal: a package hold stops the service and the downloads go on in the app, as when startForegroundService() itself is refused; a runtime install or removal still runs, without progress notifications.
2026-11-25 15:15:49 -05:00
Kurt Himebauch 6b570c573b fix(tabs): Apps tab shows when DroidDeck is the home app (#3215)
fix(tabs): Apps tab sits in the rail but hidden, and shows when DroidDeck becomes the home app
2026-11-25 14:47:18 -05:00
Kurt Himebauch d164749a7f fix(ci): save Robolectric's Android jars even when the test step fails on a Maven 429 (#3209) 2026-11-25 13:33:28 -05:00
Kurt Himebauch 50c5fd79f7 docs: point README downloads at 0.7.11 (#3210) 2026-11-25 13:25:43 -05:00
Kurt Himebauch c6169cba80 chore: bump version to 0.7.11 (20) (#3205) 2026-11-25 12:27:14 -05:00
MaxsTechReviewandKurt Himebauch 017c1c6b31 docs: DroidDeck 0.7.11 release notes (#2887)
* docs: DroidDeck 0.7.11 release notes

* docs: text-only highlights under a heading, images beside their entries

* docs: measured memory card start times for 0.7.11

* docs(release): 0.7.11 notes cover zero-copy, the Library rebuild and the latest fixes

* docs(release): 0.7.11 notes list the DroidDeck-Proton and DD-Turnip fixes

* docs(release): 0.7.11 notes cover run without proot by default, DroidDeck-Bionic, CurseForge, in-game menu pages and the latest fixes

* docs(release): screenshots for the 0.7.11 menu, first run, Decky, CurseForge, resolutions and on-screen controls

* docs(release): 0.7.11 community share excludes both maintainers, screenshots recaptured on current main

* docs(readme): headliner links to CD's Retro Corner's Odin 3 DroidDeck video instead of the GIF

* docs(readme): headliner is a short showcase GIF of quick wake, the Thor touchpad and the store tabs

* docs: README and 0.7.11 notes say no subscriptions, and the README drops its Limits section

* docs(readme): showcase GIF drops the store tabs and ends on scrolling Steam then the home screen

* docs(readme): showcase GIF opens on the table of devices

* docs(readme): showcase GIF keeps two sleep and wake cycles instead of three

* docs(release): 0.7.11 shows each new store's chip row and games from the Pocket FIT

* docs(release): 0.7.11 store screenshots show the cards without titles or sizes

* docs(release): 0.7.11 combines the three new stores into one bullet with a chip GIF

* docs(release): 0.7.11 new stores GIF is the full-screen Pocket FIT recording

* docs(release): 0.7.11 notes fold the three new stores into one bullet

* docs(release): 0.7.11 combines tab, Library and in-game menu customization into one bullet with screenshots

* docs(release): 0.7.11 headlines put no proot with DroidDeck-Bionic and zero-copy right after the stores

* docs(release): 0.7.11 explains no proot and DroidDeck-Bionic in plainer words

* docs(release): 0.7.11 says what no proot and DroidDeck-Bionic gain: CPU overhead, 1% lows, memory

* docs(release): 0.7.11 puts no proot and Bionic first and trims the headline, Features and Improvements wording

* docs(release): 0.7.11 folds small fixes and minor features into grouped lines and shortens the contributor table

* docs(release): 0.7.11 controller kits image is the cropped portrait set with the bottom button row

* docs(release): 0.7.11 moves the Xbox save and install work from Features to Fixed

* docs(release): 0.7.11 groups no proot, zero-copy and DroidDeck-Bionic as one new foundation at the top of Features

* docs(release): 0.7.11 summary leads with native execution and DroidDeck-Bionic

* docs(release): 0.7.11 summary names no proot again

* docs(release): 0.7.11 gets a Design and organization section, with the Features re-order

* docs(release): 0.7.11 moves frame generation, integer scaling, pens, XREAL and virtual pads lower in Features

* docs(release): 0.7.11 controller kits image shows four kits

* docs(release): 0.7.11 intro, store line and Lab builds wording

* docs: remove the unused steam-to-desktop headliner GIF

* docs(release): 0.7.11 summary wording, HDR and memory card lines, on-screen controls

* docs(release): 0.7.11 moves landscape and portrait resolutions to Improvements

* docs(release): 0.7.11 adds the latest main fixes and recounts the totals and leaderboard

* docs(release): 0.7.11 counts outside contributors as everyone but the three maintainers

* docs(release): 0.7.11 intro counts the 39 outside contributors

* docs(release): 0.7.11 intro counts 111 pull requests from outside contributors

* docs(release): 0.7.11 zero-copy and DroidDeck-Bionic charts

* docs(release): 0.7.11 no-proot speed chart

* docs(release): 0.7.11 shows one combined new-foundation chart

* docs(release): 0.7.11 new-foundation chart adds the SD card start times

* docs(release): 0.7.11 new-foundation chart drops its title and shrinks the headlines

* docs(release): 0.7.11 chart calls no proot native execution

* docs(release): 0.7.11 chart axes say whether higher or lower is better

* docs(release): 0.7.11 drops the HUD settings screenshots

* docs(release): 0.7.11 drops the first run screenshot

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-25 12:25:22 -05:00
a8df9a7ae1 fix(game-env): non-Adreno graphics logs no longer turn on Wine debug tracing (#2730)
* fix(game-env): non-Adreno graphics logs no longer turn on Wine debug tracing

* test(game-env): graphics-log tests use the session's DD_ variable names

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-25 11:26:24 -05:00
MaxsTechReview d38fd373f0 fix(runtime): programs can open ProgramData folders a stale Windows owner locked (#3194)
* Unlock ProgramData entries a stale Windows owner locked

Wine builds the user SID from /etc/machine-id and the uid it runs as.
When either changes, descriptors stored in user.wine.sd keep the old
owner, and the next DACL change maps to mode 000 because no ACE matches
the token. Wine then cannot open the entry, so programs such as
Battle.net cannot repair their own folders.

Before each launch, clear stale local user owners under ProgramData and
give owner access back to entries they locked.

* Heal a locked ProgramData itself and keep read-only folders

* Serialise the ProgramData heal per prefix

* Launch even when the ProgramData owner check fails

* Read the machine ID as bytes the way Wine does

* Parse a signed machine ID the way Wine does
2026-11-25 05:48:37 -05:00
MaxsTechReview a6fe10d8ff fix(input): resolve fake input's real functions before any loader lock is held (#3193)
* Resolve fake input's real functions before any loader lock is held

Each hooked call looked up its real function through a function-local
static, and the x86 dlsym hook opened libc the same way. A thread that
entered a hook first held the static's guard while dlsym waited for the
loader lock, and a thread inside dlopen held the loader lock while its
constructor called the same hook and waited for the guard. Steam's update
window hung that way under FEX, so x86 Steam stopped at Installing update.

The real functions now live in lock-free slots filled by the library's
constructor, and the dlsym hook resolves dlvsym and libc there too.

* Use an atomic handshake in the loader lock test
2026-11-25 04:24:58 -05:00
MaxsTechReview 953549704a fix(flatpak): file dialogs and forwarded descriptors work in Flatpak apps (#3190)
* fix(flatpak): file dialogs and forwarded descriptors work in Flatpak apps

Flatpak apps opened from the desktop could not open files: the file
chooser's result went through a document store that cannot mount on
Android, and image loaders started with flatpak-spawn --forward-fd lost
their D-Bus descriptor because the app relaunches sandboxes and only
stdio survived.

- A session document store hands picked files and folders back in place
  instead of failing without a mount.
- The bwrap shim offers its inherited descriptors once over a private
  socket, and the native hook puts them back on their original numbers
  before the program starts.
- The native hook resolves /proc/<pid>/root paths to the other
  process's sandbox, so xdg-desktop-portal reads .flatpak-info and
  identifies the calling app.

* fix(flatpak): check documents against the app's view and harden fd forwarding

The document store hands a picked file back in place only when the
calling app's own sandbox can open it with the requested access, so
paths the app cannot see are refused instead of handed out broken.
/proc/<pid>/root lookups follow links inside that process's view,
duplicated root descriptors keep their mapping, and close_range drops
stale records. Forwarded descriptors survive targets at the fd limit,
truncated offers are ignored, and the shim refuses more descriptors
than one message can carry.

* fix(flatpak): match picked documents by file identity and keep O_NOFOLLOW on process roots

The document store accepts an in-place path only when the app's view
holds the same file (device and inode) as the picked descriptor, and
reads each process root once. A bare /proc/<pid>/root opened with
O_NOFOLLOW is no longer mapped, so it fails like the kernel's link.

* Keep a trailing-slash process root translated and track only directory roots
2026-11-25 03:03:03 -05:00
MaxsTechReview 19d8819137 fix(battlenet): drop the unused runtime drive and list its games under the runtime path (#3188)
* fix(battlenet): drop the unused runtime drive and list its games under the runtime path

* fix(battlenet): read product.db paths decoded and keep alias-saved folders

* fix(battlenet): keep drives for paths that climb out of the runtime

* fix(battlenet): keep a drive referenced with any separator spelling

* fix(battlenet): check decoded config values before dropping a drive
2026-11-24 23:29:32 -05:00
Kurt Himebauch 1b80b506cb Default gamescope cursor drawing to on (#3187) 2026-11-24 21:40:15 -05:00
4b289a4802 fix(battlenet): games installed inside the runtime stay listed after a native session (#3148)
* fix(battlenet): games installed inside the runtime stay listed after a native session

* test(battlenet): expect the shared folder for a lone Forever install

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-24 21:12:33 -05:00
MaxsTechReview 238ef76c5c fix(preload): apps that reload libudev no longer crash in the input wrappers (#3180)
fix(preload): keep libudev loaded while the input wrappers use it

Programs that close libudev and open it again crashed in the next wrapped
udev call: the wrappers kept function pointers into the unmapped copy.
Pin libudev with RTLD_NODELETE when it is opened so those pointers and
the stored handle stay valid.
2026-11-24 20:19:53 -05:00
Kurt Himebauch 906e66e3cf fix(library): added-games selection edge cases from #2818 review (#3177)
fix(library): saved exes skip store games that are updating
2026-11-24 19:26:44 -05:00
Kurt Himebauch c0d14f9632 fix(xbox): an application element with attributes on the next line still counts (#3175)
* fix(xbox): an application element with attributes on the next line still counts

* fix(xbox): repair the patch hunk for the pretty-printed manifest test
2026-11-24 19:26:04 -05:00
Kurt Himebauch 70bda85dd5 fix(desktop): the SteamOS panel layout replaces an older or Kubuntu-default panel (#3173)
* fix(desktop): a Kubuntu-default panel gets the SteamOS layout and launcher icon

* fix(desktop): lay out Plasma's stock panel with the SteamOS pins, once, over an older panel

* fix(desktop): keep Plasma's wide-screen cap and input-method panel in the SteamOS layout

* fix(desktop): stamp the panel layout only after the old panel is backed up, never over a backup
2026-11-24 19:25:59 -05:00
The412Banner 9e6f81540f feat(bionic): DroidDeck-Bionic compatibility tool (Wine on Android's libc, no proot) (#3037)
DroidDeck-Bionic: a Steam compatibility tool that runs the game itself on Android's libc (bionic) instead of glibc inside proot. Steam, the stores and the session stay on DroidDeck's Linux side; only the game process leaves proot.

- Listed in the Proton list only when Run without proot is on, in its own row. Its builds are pre-releases on Droid-Deck/DroidDeck-Proton (DroidDeck-Bionic-12.8-rNN, runtime built by .github/workflows/build-bionic-runtime.yml from tools/bionic-runtime); the app installs and updates them like the other extra tools and never makes one the default unless the user picks it.
- With proot on, a launch sent to a bionic tool goes to the newest DroidDeck-Proton (picks stay as set).
- ProtonExtras / ProtonMenu / ExperimentalProtons / droiddeck-proton-extra: bionic pre-releases checked and listed only without proot; updates carry the default and per-game picks over; deleting a tool never follows links out of it. ProtonDefault: picks left on an older bionic build move to the installed one.
- Components: FEX builds for bionic (bionic-stable on DroidDeck-Components); each tool is offered only the FEX builds that fit it.
- Session logs: the bionic game log and its graphics logs are part of Share logs.

Synced with main twice before the merge (latest sync fbed69ce on main 67b82ad9; Build APK and validation green); a local trial merge on main 3e1fc3e6 had no conflicts and the game-environment, Proton-extra and store-launch tests pass.
2026-11-24 23:39:23 +00:00
Kurt Himebauch 3e1fc3e60e fix(xbox): a bundle with resource packages installs from its application package (#3172)
* fix(xbox): a bundle with resource packages installs from its application package

* fix(xbox): repair the patch hunk for the hoist tests
2026-11-24 18:32:38 -05:00
MaxsTechReview 826853fff5 fix(desktop): package updates that set file capabilities finish without proot (#3151) 2026-11-24 18:25:05 -05:00
MaxsTechReview 9be131cf6d fix(native): a trailing slash after a program keeps the hook's exe name like the kernel (#3171) 2026-11-24 18:24:41 -05:00
Kurt Himebauchandmaxjivi05 5ed97915c7 fix(session): report the CPU cache sizes the x86 CPUID reports to Windows programs (#2705)
* fix(session): report the CPU cache sizes the x86 CPUID reports to Windows programs

* fix(session): clear the staged core caches without following links

* fix(session): stage CPU cache binds per session generation and per core

* fix(session): keep every start's staged CPU caches until the process ends

* fix(session): give every start its own CPU cache staging folder

* test(session): a delayed worker from a recreated service keeps its own cache folder

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-24 18:18:14 -05:00
Kurt Himebauch d8654ae1be fix(retroarch): use the packaged assets, cores and core info paths (#2451)
* fix(retroarch): use the packaged assets, cores and core info paths

* fix(retroarch): migrate incomplete configs

* fix(retroarch): preserve configured core directories

* fix(retroarch): replace empty path settings in place

* fix(retroarch): keep installed core directory when repairing a blank libretro_directory
2026-11-24 18:15:35 -05:00
Kurt Himebauch 8f4744398d fix(ea): a failed touchup is retried and its output reaches the store log (#2505)
* fix(ea): a failed touchup is retried and its output reaches the store log

* fix(ea): bound the touchup output kept for the store log

The output goes to a temporary file and only its last 64 KiB are read back. The timeout test now checks the output is logged and the next launch retries.

* fix(ea): a touchup still runs when its output cannot be captured
2026-11-24 18:15:30 -05:00
The412BannerandKurt Himebauch 8f4cefd3bd fix(game-env): turn on FEX x87 FIP emulation for the SecuROM racing title that needs it (#3092)
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 18:13:22 -05:00
Kurt Himebauch 01dc415f10 fix(gog): check space for the extracted install before downloading an offline installer (#2419)
* fix(gog): bind every store root for installer extraction and log its error

* fix(gog): count the extracted size before downloading an offline installer

The installer fallback only checked free space for the download, so a
game that needs the download plus its extracted files failed after
every part was fetched, with innoextract's stream error. The failure
reason now drops innoextract's warnings and bug-report trailer.

* fix(gog): keep the internal store root visible to installer extraction

* fix(games): never give an added folder the internal store guest path

An added folder named Stores was bound at /root/Games/Stores, over the
internal store install root. legacyRoots, used by bindFolder and the
games-folder migration, now gives such a folder a suffixed guest path,
so guestBinds mounts every added root again, matching guestPath and the
session binds.

* fix(games): re-path saved folder binds that hold the internal store guest path

* test(games): verify extractor binds after migrating a saved internal-guest bind

* fix(gog): keep innoextract output in the log and leave the install failure message unchanged

* fix(gog): count known installer part sizes in the free-space check when some part has no size
2026-11-24 18:13:16 -05:00
Tushar GandheandKurt Himebauch af1fe6c61c fix(launcher): LT and RT keep the focus ring on the tab rail (#3039)
* fix(launcher): LT and RT keep the focus ring on the tab rail

A trigger step selected the tab like a tap on the rail, which also sent focus into the new page, and each page put it somewhere different. The step now shows the page and focuses its rail item, and for a second puts focus back on the rail if the page takes it, until another key is pressed. Dual screens, which have no rail on the main screen, keep focusing the page.

* fix(launcher): end the trigger step's rail hold when another navigation changes the page

A navigation that changed the selected page during the hold, such as opening a game from a link, was undone: the hold focused the stepped tab's rail item, and that focus switched the page back. The hold now stops as soon as the selection is no longer the one the step made.

* fix(launcher): end the trigger step's rail hold when another navigation opens a page

Opening the Components page does not change the selected tab, so a navigation there during the hold kept it running and the hold could pull focus from Components back to the rail. The hold now also tracks the page key: once the page its own step opened is showing, any other page ends the hold.

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 18:13:10 -05:00
The412BannerandKurt Himebauch 7bf75af8a1 fix(input): only an on-screen left mouse button stops screen taps from clicking (#3008)
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 18:13:05 -05:00
TapuukandTapuuk c08952dff9 perf(input): throttle on-screen stick knob redraws to about 30 fps (#2842)
The unified input surface redrew the overlay on every stick move. Knob-only
moves now redraw through ThrottledRedraw at 33 ms and skip sub-pixel moves
away from the rim. Pad updates still go out on every event; touch down, touch
up and reaching the rim still redraw immediately.

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
2026-11-24 17:50:20 -05:00
MaxsTechReview 58430cd393 fix(library): persist explicitly selected executables in discovered folders (#2818)
fix(library): keep re-selected executables and store launchers across scans
2026-11-24 17:50:14 -05:00
Kurt Himebauch 46d42f9ca9 fix(library): keep another program of a Steam install out of the Steam app's route (#2742)
* fix(library): keep another program of a Steam install out of the Steam app's route

* fix(library): cover a Steam-edited target in the unrouted-program test and docs

* fix(library): keep Steam-edited targets routed and release stale Spacewar imports for other programs

* fix(library): keep Steam-edited targets adopted before the marker existed routed

A saved executable and seen revision without the adoption marker are recognised
from the Steam shortcut record (its target is the current executable and differs
from the one the app asked for), and the marker is stored.
2026-11-24 17:50:09 -05:00
The412Banner 43ff1db06b fix(appimage): DwarFS AppImages unpack without proot (#3161) 2026-11-24 17:50:04 -05:00
The412Banner f934feb457 fix(input): Remote Play connects again after the controls revert (#2968)
#2958 reverted the controller redesign and its follow-ups, and #2946 was
in that list, so streaming_client lost the real libudev again. #2963
brought back #2942 but not #2946. With the session's udev answers,
SDL3 in streaming_client hands a virtual pad's handle to the real
udev_device_get_driver and crashes about a second after it starts.

streaming_client in steamrtarm64/steamrt64 keeps the real libudev again,
like the Steam client. The no-driver answer for pads that #2946 also
added is left to #2915, which covers every device call.
2026-11-24 17:49:59 -05:00
xlulx 79d41b29ad fix(gamescope): the nested mouse moves the pointer while touch is Disabled (#2961)
The nested Wayland pointer reaches wlserver as touch 0, and in the Disabled
touch click mode wlserver_touchmotion returned before moving anything.
Buttons go through wlserver_mousebutton, so they still arrived, at an X
pointer that stayed at (0,0). Steam picks Disabled for Don't Starve
Together: DroidDeck's cursor followed the mouse while every click landed
in the top-left corner. The nested pointer now warps the X pointer in
Disabled as in the other modes; real fingers are still ignored.
2026-11-24 17:49:54 -05:00
Kurt Himebauch bb6523cd9c fix(display): keep the 16:9 stretch size on the game screen after Steam resizes it (#2738) 2026-11-24 17:49:49 -05:00
Albert Carreras 925e9743a8 fix(game-env): draw Dragon Quest Monsters 4 slime bodies (#2847)
At the game's default monster mesh detail, slimes show only their tips.
Set the two skeletal mesh detail values in Engine.ini before each launch,
in the prefix the game profile selects, and keep the file's permissions.
The game ignores -ini: overrides and deletes a writable Engine.ini after
reading it, so a launch argument or a one-time write does not work.
2026-11-24 17:49:44 -05:00
JM LamboandJacob Lambert 049c4be6e5 fix(desktop): Plasma draws on the system PowerVR driver (#2836)
* fix(desktop): Plasma draws on the system PowerVR driver

KWin lacks the Android-buffer Wayland protocol the system PowerVR driver's
swapchain needs, so every Plasma client failed with "zink: could not create
swapchain" and the desktop stayed black under the cursor. Plasma's clients now
present through DRI on that path, as the Steam session already does.

* test(desktop): the kopper override reaches Plasma's child processes

* test(desktop): check the kopper override where Plasma launches

---------

Co-authored-by: Jacob Lambert <183008808+JMLambo@users.noreply.github.com>
2026-11-24 17:49:39 -05:00
e36cf24ba9 fix(guest): use /usr/bin/python3 in the payload shebangs, not /usr/bin/env (#2930)
PRoot's link2symlink resolves /usr/bin/env to a `.l2s.env….` stub and the
guest's uutils coreutils multicall refuses that name:

  Security violation: Requested utility 'env' does not match executable
  name: /usr/lib/cargo/bin/coreutils/.l2s.env0001.0116

Every exec of these five scripts therefore dies with GUEST_EXIT 1 before
Python starts, 20-60 ms into the session. They are droiddeck-diagnostic-
inventory (the session's first child), droiddeck-desktop-bookmarks (the
desktop's bookmarks refresh), droiddeck-ime, droiddeck-steam-games and
droiddeck-steam-shortcuts.

The absolute interpreter is what the other payload scripts already use,
and the guest runtime installs the python3 package (tools/ubuntu/
packages-runtime.txt), so /usr/bin/python3 exists in the rootfs.

Only the tracked overlay copies change: app/src/main/assets/linuxfs is
generated by the stageSessionScripts Gradle task, so the asset copies
follow from the overlay.

Co-authored-by: Pablo González <pgm1207@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 17:49:33 -05:00
The412BannerandKurt Himebauch 1772291da7 fix(native): programs started through the rootfs loader show their own command line (#3055)
* fix(native): programs started through the rootfs loader show their own command line

Without proot every dynamic guest program runs as "ld.so --preload <hook>
--library-path <dirs> --argv0 <name> <program> <args>", and the kernel's
/proc/<pid>/cmdline kept all of it. Launchers and the session match programs
by their command line, and Wine only moves its Windows command line over its
loader's name when its arguments follow each other, so the Battle.net launcher
never saw Battle.net.exe, gave up after five minutes and ended the session
with the game still running.

The hook now moves the program's own arguments to the front of that area at
start, as an exec of the program would have laid them out.

* fix(native): programs the app starts natively keep their path for /proc/<pid>/exe

* fix(native): the rewritten command line keeps AT_EXECFN naming the program

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 17:48:17 -05:00
The412Banner 3c4ac03656 fix(display): layer buffers are imported as AHardwareBuffers only on the phone's own Vulkan driver (#3076)
* fix(display): layer buffers are imported as AHardwareBuffers only on the phone's own Vulkan driver

* fix(display): a failed 10-bit layer pool still falls back to 8-bit linear buffers
2026-11-24 17:33:21 -05:00
The412Banner 7248d01b1b fix(storage): the Add game picker lists every card the file manager can open (#3123) 2026-11-24 17:30:41 -05:00
The412Banner f1f98c3bab fix(graphics): let Auto-installed display drivers fall back to the system driver (#2977) 2026-11-24 17:30:36 -05:00
The412Banner 4405e2a389 fix(graphics): the Mali bridge switch works on GPUs without a Mali kernel node (#3164) 2026-11-24 17:30:32 -05:00
Kurt Himebauch 67b82ad9b4 fix(epic): hand Epic's terms step to the browser instead of looping the sign-in (#2421)
* fix(epic): hand Epic's terms step to the browser instead of looping the sign-in

When Epic's redirect page answers corrective_action_required (privacy policy or EULA
acceptance, e.g. for a newly created account), open Epic's account sign-in in the Android
browser, where the step is shown, and tell the user to finish it there and retry, instead
of failing verification and reloading the sign-in.

* test(epic): remove live response identifiers from fixture

* test(epic): cover browser step selection

* fix(epic): ignore a stale sign-in page read after the login was reloaded

* fix(epic): hold the browser handoff until the sign-in screen is started
2026-11-24 17:20:00 -05:00
The412Banner 33bdc75a99 fix(logs): Share logs includes RPCS3's own log from the session (#3130) 2026-11-24 17:19:54 -05:00
The412Banner a573f8b14f fix(session): a fixed portrait resolution applies when landscape is set to Follow screen (#3124) 2026-11-24 17:19:50 -05:00
MaxsTechReviewandKurt Himebauch 7630173b24 fix(ddsession): keep path and status buffers off the wrapper fast path (#3071)
dd_descriptor_unlink, dd_descriptor_rmdir and dd_descriptor_rename put
one or two PATH_MAX buffers on their own frame (12 KB, 24 KB), and
dd_status_without_tracer put its 16 KB status buffer there, even on the
common path that only calls through to libc. Threads with small stacks,
such as .NET or Wine threads near their guard page, could overflow in
an otherwise plain unlink, rename or open.

The wrappers now do only the cheap checks and call the real function;
the buffers live in noinline helpers that run only when the descriptor
store or the status rewrite is actually needed. A test compiles both
sources with -fstack-usage and keeps each wrapper frame under 1 KB.

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 17:19:24 -05:00
DeathKhan 7d942367fd fix(apps): Up and Down in the app grid follow fast presses and keep the row in view (#2906)
* fix(apps): Up and Down in the app grid follow fast presses and keep the row in view

The grid composes rows ahead of the view without placing them. Down focused a tile there directly, so focus moved into
rows that never scrolled in, and the next Down searched from a tile with no place on screen and landed on the first
tile, sending the list back to the top. Up used the grid's own search, which works from where tiles are drawn at that
moment: with presses faster than the scroll it skipped the first row or drifted a column. And presses aimed from the
last settled focus, so fast ones were lost.

Up and Down now aim from the tile a move is already heading to, scroll that row fully into view, then focus it. At the
first or last row a press leaves the grid as before, unless a move has not landed yet, in which case it waits.

* fix(apps): a newer Up/Down move cancels the one still on its way, and a cancelled reveal frees the edge rows

A move whose target was not yet attached kept retrying its focus after a newer press, so the older tile could take
focus back. Each press now cancels the move before it. The pending target is also cleared when the reveal scroll is
cancelled (for example by a touch scroll), so Down on the last row and Up on the first no longer stay blocked.

* Apps: an Up/Down move holds its target tile by id and clears it only if it is still the latest move

A list update that shifts the tiles no longer leaves the next press aiming from the old index, and a
target that left the list drops its move. A cancelled move finishing late no longer clears the target
of a newer move to the same tile.
2026-11-24 17:14:45 -05:00
The412Banner da0a01a25b fix(input): pace stick-only pad reports to the guest at 250 Hz (#2902)
* fix(input): pace stick-only pad reports to the guest at 250 Hz

* fix(input): drop stale paced pad callbacks and time the interval from the flush
2026-11-24 17:14:40 -05:00
visail 9a7cb70969 fix(session): serialize launch requests in a coordinator (#3044)
* fix(session): serialize launch requests in a coordinator

Replace the gameLaunchRequest counter and the single pendingGameLink field
with a LaunchCoordinator. A launch is now identified by a ticket, so a stale
callback can only act on its own request, and a game link is superseded by
any newer launch. Launching is also refused while a package install stage
is in progress.

* fix(frontend): a replacement intent supersedes uncommitted launch state

A game link that resolved while the launcher was not resumed stayed pending, so
opening Settings, following a notification or picking a shortcut left it in the
coordinator and the next library refresh launched the old game over the new
screen. The same gap let an ACTION_SETUP intent leave an accepted launch current,
so a late Xbox manifest check could start the game after the user had moved on.

A replacement activity intent now cancels every ticket this activity has not
dispatched, and the refresh path may only finish a link owned by the intent the
activity shows. The toast for a superseded store lookup is gated on its ticket,
and the coordinator test now proves cancelAll() invalidates a link ticket.

The deferred Proton-compat launch is untouched: its ordering still predates this
change and has its own follow-up.
2026-11-24 17:14:35 -05:00
Kurt Himebauch 7c8f5c2707 fix(ui): changing the language restarts the launcher instead of leaving it frozen (#3163)
* fix(ui): changing the language restarts the launcher instead of leaving it frozen

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore: drop the added comment

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

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

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

---------

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

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

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

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

Fixes #694

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

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

* fix: repair a Steam target removed with its folder

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

* fix: classify a Steam target by its resolved path

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

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

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

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

---------

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

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

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

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

* fix: turn on D3DCompiler 43 for Europa Universalis IV

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

* Add HUD visibility translations for all languages

* Fix HUD game visibility and Turkish strings

* Support compositor-only HUD game detection

* Fix HUD activity reconciliation and Steam focus

* Clear stale Gamescope focus metadata

* Clear stale Steam focus when metadata is unavailable

* Prevent HUD flicker on metadata read failures

* Prevent HUD visibility flicker

* Fix HUD visibility during compositor activity

* Fix HUD visibility during compositor activity

* Prevent Steam SHM frames activating HUD

* Fix HUD activity detection when Steam is focused

* Remove HUD detection comments

* Fix HUD game activity detection

* Fix HUD compositor activity detection

* Use Gamescope frames for HUD activity detection

* Restore fullscreen SHM frame statistics callback

* Restore fullscreen SHM frame statistics callback

* Fix HUD SHM frame reporting

* Prevent Steam focus from activating game-only HUD

* Fix SHM frame freshness guard and test harness

* Used suggestion code from rabbit

* Ignore Steam UI frames for game-only HUD

* Keep default HUD stats updating over Steam UI

* Isolate Steam fallback frame statistics

* Isolate Steam fallback frame statistics

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

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

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

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

* fix(nativeguest): preserve caller library search paths

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* Delete addons through CurseForge only while it is already linked

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

* Match WoWInterface addons to the AddOns folders on disk

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* Harden headless CurseForge session and helper lifecycle

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

* Map DevTools send failures and recheck the hidden session id

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Why

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

## Behavior

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

## Compatibility

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

## Known limitation

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

## Changes

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

## Testing

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

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

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

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

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

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

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

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

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

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

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

The CurseForge web search chip is replaced by the app.

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

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

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

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

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

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

* Key the installed addon version by install target

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

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

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

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

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

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

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

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

* fix(input): restore portrait controller layouts

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

* docs: regenerate settings map for controller haptics

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

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

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

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

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

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

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

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

Adds an **Avoid notch** toggle to the Steam Display tab (under 16:9 game
fit). When it is on, the session is laid out inside the display cutout's
safe area, so the camera notch no longer covers part of the picture.

## Why

Sessions draw edge to edge under the notch. In landscape the notch cuts
into the side of the picture, and in portrait it sits on top of the
picture's upper edge. Today the only workaround is picking a smaller
custom resolution so the notch lands in the black bars. With this toggle
any resolution can be used, including Match screen, and the picture
stays clear of the notch.

## Behavior

- Off by default, so existing sessions are unchanged.
- Shown only in the Steam mode Display tab.
- The safe-area insets (left, top, right, bottom) are read from the
window's display cutout and applied as padding to the session root. The
picture, on-screen controls, HUD and overlays all stay inside it, so
cursor and touch mapping are unaffected.
- Read when the session starts and again when returning to it, and
re-applied when the window insets or configuration change (rotation,
fold, etc.), so toggling it from the launcher takes effect when you
return to the session.
- Not applied in picture-in-picture, glasses, second-screen or cardboard
output. The padding is cleared there.
- Devices without a cutout, or Android below 9 (API 28), are unaffected
because there are no cutout insets.
- Included in the settings reset and in the device report.

## Changes

- `SessionPrefs`: `avoidNotch` / `setAvoidNotch`, added to the reset key
list
- `ModeSettings` / `ModeSettingsActions` and the Display tab: new toggle
row
- `FrontEndActivity`: state, load and save for the toggle
- `SessionActivity`: `applyNotchInset()` driven by the decor view's
window insets, `readPrefs()` and configuration changes
- `DeviceReport`: logs the setting
- Strings: `display_avoid_notch` and `display_avoid_notch_hint` in all
33 locale files
- Test: `AvoidNotchPrefsTest` (default off, persists, reset turns it
off)

## Testing

- Unit tests added for the preference and the settings reset.
2026-11-21 18:25:32 +03:00
FX192 e57bc43f6a fix(session): map every activity-level touch into the surface space 2026-11-21 17:55:36 +03:00
FX192 3962b3e27f fix(session): convert activity-level mouse touches once, not control-forwarded ones 2026-11-21 17:42:14 +03:00
FX192 dc6b7f29cf fix(session): map activity-level mouse touches into the surface space 2026-11-21 17:34:36 +03:00
FX192 ca29850d04 fix(session): keep mouse, pen and unfolded layout correct with the notch inset
Map activity-level mouse and pen events into the surface's space, size the unfolded layout from the padded content area, re-evaluate the inset when the output moves to glasses, the bottom screen or cardboard, and use a clearer Arabic label.
2026-11-21 17:25:19 +03:00
FX192 c0cc3b46a0 feat(session): add an Avoid notch toggle to the Steam display options
Keeps the Steam session picture, controls and overlays inside the display cutout's safe area so the notch no longer covers part of the image, in landscape or portrait. Off by default.
2026-11-21 17:08:27 +03:00
Kurt HimebauchandK11MCH1 64b7339da9 feat(input): restyle Steam Deck buttons (#2966)
* feat(input): restyle Steam Deck buttons

* feat(input): add Steam overlay options

* fix(input): align floating overlay previews

* fix(input): polish floating Steam trackpads

* fix(input): restore overlay options on startup

* fix(input): restore original Steam Deck artwork

* fix(input): restore Steam Deck overlay geometry

* fix(input): keep the Steam Deck shortcut row apart on small screens

The Steam pill sits right of the keyboard by a density-based margin while
Select and Start sit at unit-scaled offsets from the middle, so on a small,
dense surface (800x450 at xxxhdpi) the Steam pill covered Select. Lay out
Steam, Select, Start and Quick Access left to right with an 8 dp gap.

* fix(input): fit the Steam Deck shortcut row inside the safe area

Clamping each pill on its own after spacing could move Quick Access back
onto Start when a cutout inset narrows the right side. Fit the keyboard,
Steam, Select, Start and Quick Access as one row: push each right past its
neighbour, pull the row back inside the right edge, and shrink the 8 dp gap
only when the row would not fit otherwise.

---------

Co-authored-by: K11MCH1 <81425424+K11MCH1@users.noreply.github.com>
2026-11-21 17:42:45 +09:00
MaxsTechReview 4349563fd1 feat(display): zero-copy presentation toggle and compositor display buffers (#2905)
* feat(display): zero-copy presentation toggle and compositor display buffers

Adds a Zero-copy presentation switch under Steam Settings, Display,
Session Display (on by default), and a display-buffer allocator in the
compositor: a Vulkan driver that states displayBuffers asks it for the
memory of the images it exports, so frames presented through the nested
compositor are gralloc buffers that go on the display layer without a
copy. Compressed buffers are offered only where the device's allocator
matches the layout the drivers render to; everything else stays on the
copy path.

The private buffer protocol is renamed to droiddeck-ahb-v1.

* fix(display): zero-copy frames keep the full refresh rate

Two buffers set on the game layer inside one refresh replaced each other, and a frame that slipped into the next refresh made the compositor hold and drop the on-time frame behind it. The layer now queues buffers, and a refresh takes a second frame when the one before it took none. The pacing tool no longer counts its dump time in the frame rate.

* Keep cropped scenes on the display layer and pace layer frames evenly

Accept any in-bounds source crop for the display layer and map the draw
geometry the same way the copy path does. Time layer frames against the
display's frame timeline, and when the game's rate is a steady whole
fraction of the refresh rate show each frame a fixed number of refreshes
after the last so uneven arrivals no longer reach the screen.

* List zero-copy in the settings map

* Hold display buffers until the display releases them

A buffer the game or gamescope rendered straight into went back to its
client as soon as the next one was latched, with the display's release
fence attached to the dma-buf. The KGSL driver does not wait on that
fence, so the client could draw into a buffer the panel was still
reading. Display buffers now wait for the release fence before the
release event, and gamescope composites only into output images the
host has released.

* Keep the game picture copy-free when an overlay has no display layer

When the display cannot give a second layer of its own to an overlay,
the compositor tells gamescope how many planes it can show directly.
gamescope then composes its overlays into the game picture, which still
reaches the display without a copy.

* feat(session): the panel refresh rate follows the session's frame rate

The session learns the panel's refresh rates and reports the refresh rate and
frame rate it wants. The panel moves to the highest rate the frame rate divides
evenly, frame generation counts at its output rate, and a panel whose rate the
system holds offers only that rate.

* feat(session): the panel follows a frame rate the game holds on its own

The compositor reports the game's frame rate once a second. A rate that
holds for three seconds and divides a panel rate becomes the content
rate when neither the app's limit nor the session's limiter is setting
the pace, so a game capped in its own settings gets a panel rate its
frames divide into. A rate that was dropped has to hold twice as long
before it is used again.

* Show generated frames on the game's display layer

With frame generation on, the game's own frames stay on their display
layer untouched and each generated frame is placed on the same layer
between them, timed across the game's frame interval. The compositor
pass is kept when effects, HDR routing or a cursor need it, or when the
panel cannot show the multiplied rate.

* Keep scaling, generated frames and HDR on the display layer

A scaler or frame generation with zero-copy on now draws once into the
display layer instead of falling back to the copied surface. HDR output
goes to the layer when the panel supports it; on a panel without HDR the
picture is tone-mapped on the same path, and the toggle is labelled to
match what the panel can do.

* Spread a frame limit the refresh rate does not divide evenly across refreshes

* Cover the spare-tick and panel-rate paths in the compositor source tests

* Pin the gamescope build with the display-plane, release, refresh and limiter patches

* Give the layer and terminal-caller harnesses the black fill state they compile against

* feat(display): switch HDR during a session without restarting the app

The compositor now offers HDR whenever the device can present it, and the
HDR setting only decides whether the session uses it. Both HDR switches set
gamescope's hdr_enabled, the compositor's HDR output and zero-copy for the
running session. gamescope patch 0139 lets hdr_enabled change after start.
The 'Restart the app to apply.' hint is removed from every locale.

* Remake the output images in the new format when HDR is switched during a session

* Pin the gamescope build that switches HDR during a session

* Apply a saved HDR opt-out at session start and keep HDR retries with their session

* Serialise the HDR output switch with the gate opening

* feat(display): keep the client's HDR setting and the session's in step

The session publishes its HDR state with the other device controls and the
client helper applies it to the client's own display setting. A change made in
the client is reported back and goes through the same switch the drawer and
Session Display use, so all three always show one value.

* fix(desktop): keep the display-buffer socket when the runtime directory is cleared

The desktop launcher removed everything in the runtime directory except the
compositor's Wayland socket, which took the display-buffer socket with it, so
no desktop program could ask for display buffers and every frame was copied.

* fix(display): the client's HDR setting follows the session in every client mode

The bridge only ran when a variable nothing sets was present, so the client's
HDR setting and the session's never met. It now runs whenever the session
publishes an HDR state, and a client that has no such setting is asked again
only every ten seconds.

* fix(display): harden display-buffer hand-off, layer fallbacks and HDR sync

- Stop closing a buffer handle's descriptor the allocator still owns, and free an allocation whose reply could not be sent.
- Rebuild the advertised buffer formats when zero-copy is switched during a session.
- Fall back to the copy path when a layer buffer cannot be allocated, and hide the game layer when it is skipped for a frame.
- Keep a release fence that has not signalled instead of rendering into a buffer the display still reads.
- Ignore a refresh-target reset from a client that does not own the target.
- Restart the content-rate measurement after a pause, clear it when the game stops, and lengthen engagement only for a rate that was released before.
- Compare colour conversions by their values, and read padded cursor buffers at their row width.
- Use the running session's mode for the HDR and zero-copy settings, probe the display before screen effects are pushed, retry a held panel mode, and ignore callbacks after the activity is destroyed.
- Write a newer HDR value while an earlier write is settling, and reapply the value after the bridge is reinstalled.
2026-11-21 00:26:50 -05:00
Kurt Himebauch f29f72d5d9 fix(input): restore Steam controller reattach (#2963) 2026-11-20 20:17:52 -05:00
K11MCH1andMaxsTechReview 367151be2c fix(epic): start parent-checking Epic titles under an EpicGamesLauncher.exe stand-in and stage their Rockstar SDK (#2932)
* fix(epic): start Epic titles that check their parent under an EpicGamesLauncher.exe stand-in

Rockstar's launcher only accepts an Epic copy of GTA V when a process
named EpicGamesLauncher.exe started it. DroidDeck's Epic client is a
Linux program, so the launcher logged "Epic Games Launcher not detected
as parent process", failed to relaunch through Epic and showed the game
as unowned.

- tools/epic-launcher: a small Windows EpicGamesLauncher.exe that starts
  the game with the rest of its own command line, unchanged, waits for
  it and returns its exit code. It ships as the epic add-on pack.
- The Epic .droiddeck-launch.bat runs the game through it for Epic
  titles known to need it (GTA V, GTA V Enhanced, RDR2, RDR, GTA SA DE,
  Returnal, Phantom Blade: Executioners), or for any Epic game whose
  per-game environment sets DD_EPIC_PARENT=1; DD_EPIC_PARENT=0 turns it
  off. Those titles also start without Steam's SteamAppId. Without the
  staged stand-in the game starts directly, as before.
- Steam launch options now reach Epic games (%*).
- The launch hook fetches the pack when such a title finds it missing.
- Rockstar's launcher found no Social Club SDK in the prefix and ran
  Social-Club-Setup.exe /silent, which never exits under Wine. For Epic
  titles that carry a Rockstar SDK installer, the hook now extracts the
  SDK from the launcher's own Redistributables copy (the version the
  launcher compares against) or, before the launcher is installed, from
  the game's copy, and registers it. It re-extracts when that installer
  changes and leaves the Rockstar Games Launcher key alone, so PlayGTAV
  still installs the launcher on first start.

* fix(epic): fetch the parent stand-in exactly when the game will use it; keep Cargo output out of source digests

The launch hook runs before droiddeck-game-env applies per-game
variables, so it now resolves DD_EPIC_PARENT through
droiddeck-game-env's own apply_config and game_id: an unlisted title
with DD_EPIC_PARENT=1 fetches the pack, a listed title with
DD_EPIC_PARENT=0 no longer waits for it.

runtime_inputs no longer hashes the target directory beside a Cargo.toml
under its source paths, so a local cargo build of a Windows helper does
not fail verify(). tools/epic-launcher gets the same .gitignore as the
other helpers.

* fix(epic): a DD_EPIC_PARENT in the game's sidecar env decides the stand-in fetch too

The .bat sets the sidecar's env before it reads DD_EPIC_PARENT, so that
value overrides the game environment there; the launch hook now gives it
the same precedence when deciding whether to fetch the pack.

* test(epic): keep an inherited DD_EPIC_PARENT out of the launch hook tests

---------

Co-authored-by: MaxsTechReview <maxjividen@gmail.com>
2026-11-21 09:56:31 +09:00
Kurt Himebauch 9925873764 revert(input): restore pre-overhaul controls (#2958) 2026-11-20 19:43:09 -05:00
Kurt Himebauch 33761c30ab fix(input): choosing the Gamepad layout in Steam mode keeps its gamepad actions (#2954)
Choosing a layout from the layout menu took the first actions saved for it.
Desktop and Steam mode both draw the stock Gamepad, and Desktop's actions
(stick moves the pointer, face buttons click and press Enter and Esc,
D-pad sends arrow keys) could come first, so Steam mode's on-screen pad
became a mouse and keyboard. A choice now takes the mode's own actions,
or any the other mode doesn't use, and a Steam-mode selection already
holding Desktop's actions is dropped on upgrade.
2026-11-20 15:31:42 -05:00
Kurt Himebauch 089c18b49d fix(input): keep custom layouts active on upgrade (#2950) 2026-11-20 14:44:46 -05:00
Kurt Himebauch cb8e70b940 fix(input): restore Steam and Quick Access shortcuts (#2948) 2026-11-20 14:42:52 -05:00
The412BannerandKurt Himebauch 3c0d25d83b fix(display): read linear client frames at their row pitch when the driver has no explicit modifier layouts (#2927)
* fix(display): read linear client frames at their row pitch when the driver has no explicit modifier layouts

* fix(display): keep row-pitch copied client frames eligible for layer presentation

* fix(display): order the readback layout change after the staging copy

* fix(display): skip the modifier import query when the driver lacks VK_EXT_image_drm_format_modifier

* test(display): the compositor's source-extracting tests follow the linear dma-buf helpers

vkp_image_destroy now frees through destroy_image_objects, render_impl stages
linear dma-bufs and the external-image release asks foreign_image; the two
tests that compile these functions out of vk_present.c extract or stub them,
with the image's new buffer fields in their fakes.

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-20 14:42:44 -05:00
Kurt Himebauch 6f45b5347d fix(input): the layout editor draws controls at their real size in portrait (#2949)
The editor is a dialog that starts at the default dialog size and is then
stretched to the full screen, so its preview could be laid out at a size it
was never measured at. Controls took their size from the earlier pass and
their position from the new one: in portrait, pills came out several times
taller and round buttons slid down. Each control is now sized from where the
canvas actually lays it out.
2026-11-20 13:57:12 -05:00
Kurt Himebauch a3e8b44145 fix(input): Remote Play connects again with the virtual pads present (#2946)
Since #1593 every process except the Steam client gets DroidDeck's udev
answers through dlsym. Steam's Remote Play client, streaming_client, is
an SDL3 program: for each input node it treats as a joystick, SDL3 asks
udev_device_get_driver for the device that udev_device_new_from_devnum
returned. The preload answered new_from_devnum with its own handle for a
virtual pad but did not answer get_driver, so the real libudev read the
handle as its own and streaming_client crashed before the stream opened.
It reaches that call whenever it can stat a pad node: the Xbox 360 pad,
Steam's own uinput gamepads, and since #2033 the pads it reads.

streaming_client now keeps the real libudev like the Steam client, and a
virtual pad answers get_driver with no driver, so other SDL3 programs no
longer crash on it.
2026-11-20 13:19:12 -05:00
Kurt Himebauch 0f37154933 fix(input): saved layouts keep their shape on a rotated screen, sticks aren't cut off and old gamepads are kept (#2945)
* fix(input): saved layouts keep their shape on a rotated screen, sticks aren't cut off and old gamepads are kept

- A layout shown on a screen much taller or wider than it was saved for is
  placed as one block (at the bottom in portrait) instead of anchoring each
  control by its own third, which tore clusters such as the face buttons apart
  in portrait and in the editor.
- A floating stick's base is drawn whole inside the overlay when the thumb
  lands near an edge; input still centres on the touch.
- The migration that makes old-editor gamepads follow the kit again also keeps
  a copy of each one that had kit positions, as "<name> (old layout)" with its
  actions, so players can choose their old layout again.

* fix(input): the old-layout copy keeps only actions it can use, fits the library's limits and leaves same-orientation screens alone

- Actions for kit buttons the old gamepad never placed stay on the kit-following
  gamepad and are dropped from the copy, which otherwise failed validation and
  stopped the library from loading.
- When the copy and its actions don't fit the layout, action or saved-size
  limits, the gamepad keeps its own positions instead.
- Block placement only applies when the screen and the layout differ in
  orientation; a 4:3 layout on a wide landscape screen keeps edge anchoring.
2026-11-20 13:19:08 -05:00
Kurt Himebauch 42133bec0b fix(input): the Xbox and PS buttons move to the bottom row of the floating gamepad (#2944)
The Steam kits keep their Steam and Quick Access buttons on the bottom row,
and Start and Select moved there too, but the Xbox kit's Guide button still
sat at the top centre of the screen and the PlayStation kits' PS button over
the middle of the game. Both now sit between Select and Start, where the real
pads have them, centred on the safe area like Select and Start.
2026-11-20 13:05:26 -05:00
Kurt Himebauch d7f43c26cd fix(input): Steam finds a DualShock or DualSense chosen mid-session (#2942)
* fix(input): Steam finds a DualShock or DualSense chosen mid-session

Android lets an app open a uevent netlink socket but not join its multicast
groups, and libudev joins none when no udev daemon runs, so the udev
monitors Steam's SDL opens heard nothing and the pad switch's add and remove
events reached no one. SDL only noticed a new PlayStation pad when the old
one happened to fail a read. A monitor left without a subscription is now
swapped for the session's stand-in under the same descriptor, so it
receives the injected events.

* test(preload): stub the udev monitor bind hook in the CDP guard build
2026-11-20 12:44:52 -05:00
Kurt Himebauch d5c83eae15 feat(input): describe on-screen layout choices, scope per-game layouts and delete unused ones (#2939)
* feat(input): describe on-screen layout choices, scope per-game layouts and delete unused ones

- The layout menu says what each choice is: "DroidDeck controls" work in
  every game and are edited here; "Steam touch controls" are each game's
  controls from Steam, for Steam games only.
- Layouts made with "+ New for <game>" (or "Just this game") are listed
  only for that game, marked "Just for <game>". Older ones are recognised
  by carrying the name of the game that draws them.
- Saved layouts nothing uses get a delete button in the menu. Deleting one
  also removes a profile that still uses it but can no longer be chosen,
  such as copies made by the old profile screen.
- A game set to Steam touch controls that runs without Steam shows a note
  under Layout instead of silently using the default.

* fix(input): a layout the built-in profile still lists can be deleted once another is chosen

Applying a layout used to write it into the Game profile; choosing another
now goes on top, so the profile's part is no longer drawn. Only parts a mode
actually draws count as in use, and deleting points the built-in profile
back at the stock layout.
2026-11-20 11:54:59 -05:00
Kurt Himebauch 83dc5f37e9 fix(session): launching the running game again resumes it instead of asking Steam twice (#2940)
* fix(session): launching the running game again resumes it instead of asking Steam twice

A front end that resumes a suspended player by launching the same game again
(Cocoon 3.07 does) made DroidDeck queue the game for Steam a second time,
and Steam answered with "An error occurred while launching this game: Game
already running" over the game.

queueSteamGame now resumes the session and returns when the requested game is
the current one and its process is running. A different game, or one that has
exited, still goes to Steam as before.

* fix(session): a relaunch during a pending freeze resumes too, and both game ID forms count as the same game
2026-11-20 11:40:17 -05:00
Kurt Himebauch d0022a35f9 fix(session): remove the keep-top guard from other displays (#2937)
* fix(session): remove the keep-top guard from other displays

#2763 put a transparent KeepTopActivity on every other display while a
session was on top, so lmkd killing that display's home could not move focus
off the session. A/B on a 12 GB AYN Thor (Android 13) and a Retroid Pocket
Duo (Android 16) found no case where it kept a session alive: with steady
pressure the bottom home (stock launcher or Cocoon) was killed up to 400
times per run without taking focus, and a burst big enough to matter makes
lmkd kill the session at adj 0 with or without the guard.

Its side effects were real:
- Android's ActivityRecordInputSink made the bottom screen ignore touch
  (worked around in #2910 by stepping aside on touch).
- Cocoon tracks each display's top activity, so it could not suspend or
  resume DroidDeck cleanly.
- The Thor's Game Assistant gives every app with an activity on top of the
  bottom display that display's volume, so DroidDeck's audio followed the
  bottom screen's volume slider.

Removes KeepTopActivity, the focus bounce and light pause, the memory
pressure trigger and their tests. onPause runs its departure cleanup every
time again.

tools/memory_guard_ab.py gains a burst mode, reads oom_score_adj without
su (lmkd kills the root manager app and su can then open its request screen
over the game), handles Android 13 dumps, a hung stop and a session that
does not start. docs/development/memory-guard-ab.md has the Thor results.

* test(session): the guard A/B fill mode starts its counter again, and a pressure run with no completed run fails

* test(session): the burst seed is rebuilt unless it is exactly 256 MiB

* test(session): the guard A/B burst takes its last partial chunk, and only a hog run that finished counts
2026-11-20 11:40:10 -05:00
MaxsTechReview acb2cba970 fix(ci): add-on packs compress the same on every runner (#2938)
The proot pack pin check failed on GitHub-hosted runners for PRs that do
not touch proot. The hosted image puts the latest upstream zstd (1.5.7)
in /usr/local/bin, while the self-hosted runners use zstd 1.5.5, and
zstd -19 output differs between those versions for identical tar input.

tools/packs/build.sh now compresses every pack with the zstd version
pinned in tools/packs/zstd/release.env: the system zstd when it is that
version, otherwise the checksum-verified upstream release built once
into the pack input cache.
2026-11-20 10:27:17 -05:00
Kurt Himebauch e58b463f54 fix(input): declutter the floating gamepad overlay (#2933) 2026-11-20 10:21:32 -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
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
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
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
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
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
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
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
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
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
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
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 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
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
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
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
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
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
Kurt Himebauch b1a7d9b2d0 fix(preload): leave anonymous memory alone when copying noexec image pages (#2706) 2026-11-17 08:29:32 -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
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
997 changed files with 69719 additions and 13076 deletions

No files matched your search

+2
View File
@@ -1,7 +1,9 @@
ASEbrahim
FX192
FryMcNugget
K11MCH1
KeegantheVeganat0r
kingokksa
ovurrsl
KeegantheVeganat0r
EnzoDLofi
+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,35 @@
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'
- 'tools/gpuload/**'
- '.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/*
+4 -1
View File
@@ -29,11 +29,14 @@ jobs:
persist-credentials: false
- name: Build in Arch Linux ARM
env:
GH_TOKEN: ${{ github.token }}
FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }}
FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }}
run: |
set -euo pipefail
docker run --rm -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
FEX_VERSION=$(gh api repos/FEX-Emu/FEX/releases/latest --jq .tag_name)
echo "Building $FEX_VERSION, FEX's latest release"
docker run --rm -e FEX_VERSION="$FEX_VERSION" -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
sudo chown -R "$(id -u):$(id -g)" .
- uses: actions/upload-artifact@v4
with:
+132 -14
View File
@@ -164,6 +164,9 @@ jobs:
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Clear scratch earlier runs left behind
if: runner.environment == 'self-hosted'
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
- name: Merge the pinned APK base
if: github.event_name == 'pull_request'
env:
@@ -195,17 +198,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 +294,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 \
@@ -367,6 +370,10 @@ jobs:
persist-credentials: false
submodules: recursive
- name: Clear scratch earlier runs left behind
if: runner.environment == 'self-hosted'
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
- name: Check human authorship
env:
EVENT_NAME: ${{ github.event_name }}
@@ -565,17 +572,65 @@ jobs:
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
# A hosted runner needs over 20 minutes per launcher; rebuild only when its sources change, and save each
# build as soon as it finishes so a later timeout cannot discard it.
- name: Restore the Ubisoft launcher build
id: ubisoft-cache
uses: actions/cache/restore@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
key: ubisoft-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/ubisoft-launcher/src/**', 'tools/ubisoft-launcher/Cargo.toml', 'tools/ubisoft-launcher/Cargo.lock', 'tools/ubisoft-launcher/build.sh', 'tools/ubisoft-launcher/build.rs', 'tools/ubisoft-launcher/.cargo/**') }}
- name: Ubisoft launcher service (x86_64-pc-windows-gnu)
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
run: |
set -euo pipefail
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
bash tools/ubisoft-launcher/build.sh
- name: Save the Ubisoft launcher build
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
key: ${{ steps.ubisoft-cache.outputs.cache-primary-key }}
- name: Restore the Rockstar launcher build
id: rockstar-cache
uses: actions/cache/restore@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
key: rockstar-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/rockstar-launcher/src/**', 'tools/rockstar-launcher/Cargo.toml', 'tools/rockstar-launcher/Cargo.lock', 'tools/rockstar-launcher/build.sh', 'tools/rockstar-launcher/build.rs', 'tools/rockstar-launcher/.cargo/**') }}
- name: Rockstar launcher service (32-bit and 64-bit)
if: steps.rockstar-cache.outputs.cache-hit != 'true'
run: |
set -euo pipefail
command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; }
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
bash tools/rockstar-launcher/build.sh
- name: Save the Rockstar launcher build
if: steps.rockstar-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
key: ${{ steps.rockstar-cache.outputs.cache-primary-key }}
- name: Restore the Epic launcher build
id: epic-cache
uses: actions/cache/restore@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
key: epic-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/epic-launcher/src/**', 'tools/epic-launcher/Cargo.toml', 'tools/epic-launcher/Cargo.lock', 'tools/epic-launcher/build.sh', 'tools/epic-launcher/build.rs', 'tools/epic-launcher/.cargo/**') }}
- name: Epic Games Launcher parent stand-in (x86_64-pc-windows-gnu)
if: steps.epic-cache.outputs.cache-hit != 'true'
run: |
set -euo pipefail
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
bash tools/epic-launcher/build.sh
- name: Save the Epic launcher build
if: steps.epic-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
key: ${{ steps.epic-cache.outputs.cache-primary-key }}
- uses: actions/download-artifact@v4
with:
@@ -588,7 +643,7 @@ jobs:
path: |
~/.cache/droiddeck-pack-inputs
~/.cache/droiddeck-build
key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/powervr/release.json') }}
key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/packs/zstd/release.env', 'tools/powervr/release.json') }}
restore-keys: pack-inputs-v2-
- name: Build the add-on packs
run: |
@@ -619,14 +674,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
@@ -675,6 +734,37 @@ jobs:
if-no-files-found: ignore
overwrite: true
- name: Resolve the Robolectric version
id: robolectric
run: |
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
# The cache path sits beside the workspace because runner homes are at different depths from it, and
# actions/cache stores paths relative to the workspace. Runners that keep their own ~/.m2 skip the cache.
- name: Place Robolectric's Android jars beside the workspace
id: robolectric-jars
run: |
set -euo pipefail
jars="$GITHUB_WORKSPACE/../robolectric-jars"
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
echo "cache=false" >> "$GITHUB_OUTPUT"
else
mkdir -p "$jars" "$(dirname "$m2")"
ln -sfn "$(cd "$jars" && pwd)" "$m2"
echo "cache=true" >> "$GITHUB_OUTPUT"
fi
- name: Restore Robolectric's Android jars
id: robolectric-cache
if: steps.robolectric-jars.outputs.cache == 'true'
uses: actions/cache/restore@v4
with:
path: ../robolectric-jars
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
- name: Count the restored Robolectric jars
if: steps.robolectric-jars.outputs.cache == 'true'
run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV"
- name: Unit tests
id: unit-tests
env:
@@ -685,6 +775,34 @@ jobs:
mkdir -p app/build
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
- name: Save Robolectric's Android jars
id: robolectric-jars-final
if: always() && steps.robolectric-jars.outputs.cache == 'true'
run: |
python3 - <<'PY'
import glob, os, zipfile
root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars')
for f in glob.glob(os.path.join(root, '**', '*'), recursive=True):
if not os.path.isfile(f):
continue
try:
ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None
except Exception:
ok = False
if not ok:
os.remove(f)
PY
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
- name: Store Robolectric's Android jars
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
uses: actions/cache/save@v4
with:
path: ../robolectric-jars
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
- name: Upload unit test diagnostics
id: unit-test-diagnostics
if: always() && steps.unit-tests.outcome != 'skipped'
@@ -765,7 +883,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 +928,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
@@ -821,6 +937,7 @@ jobs:
run: |
cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml
cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml
cargo test --locked --manifest-path tools/epic-launcher/Cargo.toml
python-tests:
name: Python and native regression tests
@@ -900,7 +1017,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 +1026,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]
+1 -1
View File
@@ -55,7 +55,7 @@ jobs:
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
}
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt; do
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic; do
file="packs/$name.tar.zst"
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
sha=$(sha256sum "$file" | cut -d' ' -f1)
+1
View File
@@ -37,3 +37,4 @@ app/src/main/assets/directaudio/
app/src/main/assets/hybris/
/tools/vr/out/
app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar/
app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic/
+36 -1
View File
@@ -2,7 +2,42 @@
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
# Working on the device
# Building and testing
- For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step.
- `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`.
- Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout.
- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally.
- Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '<class>'` and `python3 -m unittest discover -s tools/tests -p 'test_<area>*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI.
- For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape.
- After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`.
- Compile errors in code you didn't touch, after switching branches, are usually stale incremental state. Rebuild once before you change anything.
# Worktrees and shared machines
- After `git worktree add`, run `git submodule update --init --recursive`. Without it, `buildVkBridgeServer` fails on missing `external/MaliBridge`. Do not commit the `tools/syncthing/syncthing-android` pointer the build dirties.
- Other agents may be building on the same machine. Never run `./gradlew --stop` or kill Gradle/Kotlin daemons you did not start. If you need isolation, use `GRADLE_USER_HOME=<own dir> GRADLE_RO_DEP_CACHE=$HOME/.gradle/caches`.
# Driving the app and device
- Do it yourself with `tools/droiddeckctl` (see `docs/agent-control.md`) instead of asking the user: `cdp eval` for Steam's UI (`SteamClient.Apps.TerminateApp('<appid>', false)` quits a game, including on a Remote Play host), `input`, `quit`, `displays`, `screenshot --display <id>`.
- A stream has started only when the session state reads `Streaming`. `SteamClient.Apps.StreamGame` alone can leave Steam on its menu, so open the game page and press Stream.
- Test controller navigation with `tools/droiddeckctl input gamepad ...`, a real uinput pad. `adb shell input keyevent DPAD_*` does not arrive as a joystick event and hides d-pad/stick bugs.
- A release-signed build installs over a release-signed install with `adb install -r`. Don't back up, uninstall or clear data to update. Scope `pm` and permission resets to `com.droiddeck.launcher`, never the whole device.
# CI
- Before pushing a PR, run `tools/pre_pr.sh`. It checks authorship and the merge onto `main`, then, when app sources change, compiles and runs lint as CI does. It picks tests by name: `<File>*Test` for changed Kotlin files, and `tools/tests` modules that mention a changed path. Add any other tests that cover your change, and leave the full suites to CI.
- CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge.
- Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors.
- Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them.
- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs/<job-id>/logs`, or `gh run download <run> -n unit-test-results`. Don't call a failure a runner problem until you have read it.
- Only these are known flakes worth a `gh run rerun <run> --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real.
- A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`.
# Agents running on the device (DroidDeck's in-app agent)
These apply only where `dd-lab-build` exists. Agents on a dev host use `tools/quick_deploy.sh` instead.
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
+12 -13
View File
@@ -7,10 +7,10 @@
DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linux desktop, integration with GOG, Epic Games, Xbox, and other storefronts, Steam VR, and more!
<p align="center"><b>100% open source. No ads. No telemetry. No proprietary components. No source withheld.</b></p>
<p align="center"><b>100% open source. No ads. No Subscriptions. No telemetry. No proprietary components. No source withheld.</b></p>
<p align="center">
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.1%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.1"></a>
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.11%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.11"></a>
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
</p>
@@ -23,7 +23,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
<a href="https://trendshift.io/repositories/267852"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"></a>
</p>
<p align="center"><img src="docs/media/steam-to-desktop.gif" width="100%" alt="On a Retroid Pocket Duo: Play Steam from the DroidDeck launcher, open Pac-Man in Steam Big Picture and play it, exit the game, then Switch to Desktop from the Power menu"></p>
<p align="center"><a href="https://www.youtube.com/watch?v=ruaTSm_7a2c"><img src="docs/media/droiddeck-showcase.gif" width="60%" alt="A table of handhelds and phones all running DroidDeck, one waking to the Steam menu, the AYN Thor's bottom screen used as a touchpad, and scrolling around Steam on a phone before swiping to the home screen. Footage from Cyber Dopamine's video, linked."></a></p>
> The official website is [droid-deck.dev](https://droid-deck.dev). Only download DroidDeck from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
@@ -38,7 +38,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk), install the Linux runtime, press **Play** and sign in to Steam.
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk), install the Linux runtime, press **Play** and sign in to Steam.
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
@@ -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
@@ -57,9 +57,6 @@ The APK lands in `app/build/outputs/apk/release/`. Install it with `tools/deploy
On Windows, see `tools/run_windows.ps1` and `tools/prepare_windows_runtime.py`.
## Limits
Compatibility and performance vary by device. Desktop compositing is software rendered, and Firefox sandboxing is reduced under proot.
## Credits and licence
@@ -70,13 +67,14 @@ 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. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped 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.
@@ -91,14 +89,15 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
<details>
<summary><b>Stores</b></summary>
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send.
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send. Deleted GOG cloud saves are recognised by the empty-gzip deletion hash gogdl and Lutris skip.
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
- The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268).
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
- 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 World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. Installed addons show their `.toc` version and `X-WoWI-ID`, and are checked against that list for updates, as [WowUp](https://github.com/WowUp/WowUp) does. The Addons tab installs the official [CurseForge](https://www.curseforge.com/download/app) Linux app from CurseForge's own update feed (downloaded at install time and checked against its SHA-512, not included), which keeps its own sign-in.
- The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
+14 -10
View File
@@ -93,7 +93,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt'].collectEntries { name ->
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
@@ -125,14 +125,15 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
android {
namespace 'com.droiddeck.launcher'
compileSdk 34
ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
ndkVersion project.findProperty('ndkVersion') ?: providers.fileContents(rootProject.layout.projectDirectory.file('tools/ci/toolchains.env'))
.asText.get().readLines().find { it.startsWith('CI_ANDROID_NDK_VERSION=') }.split('=', 2)[1].trim()
defaultConfig {
applicationId "com.droiddeck.launcher"
minSdkVersion 26
targetSdkVersion 34
versionCode 19
versionName "0.7.1"
versionCode 20
versionName "0.7.11"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}"
@@ -202,7 +203,7 @@ android {
}
androidResources {
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>droiddeck-ubisoft:<dir>droiddeck-rockstar:<dir>droiddeck-dirt:<dir>directaudio:<dir>hybris'
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>droiddeck-ubisoft:<dir>droiddeck-rockstar:<dir>droiddeck-dirt:<dir>droiddeck-epic:<dir>directaudio:<dir>hybris'
}
packagingOptions {
@@ -232,6 +233,9 @@ android {
}
maxHeapSize = '2g'
maxParallelForks = 2
def jvmTemp = new File(temporaryDir, 'jvm')
systemProperty 'java.io.tmpdir', jvmTemp.absolutePath
doFirst { jvmTemp.mkdirs() }
def logTarget = providers.systemProperty('robolectric.logging').orNull
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
}
@@ -261,11 +265,9 @@ if (vitureSdkDir) {
tasks.named('preBuild').configure { dependsOn(stageVitureNotices) }
}
def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
from(rootProject.file('tools/linuxfs/overlay')) {
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
}
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
def stageSessionScripts = tasks.register('stageSessionScripts', Exec) {
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage'
}
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
@@ -388,6 +390,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,80 @@
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 SteamEmptyPreview() = Launcher("steam", games = emptyList())
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
@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 = {},
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 = {},
)
+5
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" />
@@ -228,6 +232,7 @@
android:exported="false"
android:screenOrientation="user"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:windowSoftInputMode="adjustResize"
android:theme="@style/AppTheme" />
<activity
+128 -24
View File
@@ -21,6 +21,7 @@
#define SYS_munmap 215
#define SYS_mmap 222
#define SYS_mprotect 226
#define SYS_getpid 172
#define AT_FDCWD_ (-100)
#define O_RDONLY_ 0
@@ -52,6 +53,21 @@ static size_t slen(const char *s) {
return n;
}
static int seq(const char *a, const char *b) {
while (*a && *a == *b) a++, b++;
return *a == *b;
}
static const char *env_get(char **envp, const char *name) {
size_t n = slen(name);
for (; *envp; envp++) {
size_t i = 0;
while (i < n && (*envp)[i] == name[i]) i++;
if (i == n && (*envp)[n] == '=') return *envp + n + 1;
}
return 0;
}
static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); }
static void out_num(long v) {
@@ -112,19 +128,43 @@ static int prot_of(uint32_t flags) {
static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); }
static void load(const char *path, struct image *im, uintptr_t page) {
static void read_interp(int fd, const Elf64_Phdr *ph, int phnum, char *interp, size_t size, const char *path) {
interp[0] = 0;
for (int i = 0; i < phnum; i++) {
if (ph[i].p_type != PT_INTERP) continue;
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= size) die("bad PT_INTERP", path, 0);
if (xpread(fd, interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
die("truncated PT_INTERP", path, 0);
interp[ph[i].p_filesz] = 0;
}
}
static int read_headers(const char *path, Elf64_Ehdr *eh, Elf64_Phdr *ph) {
int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0);
if (fd < 0) die("cannot open", path, fd);
Elf64_Ehdr eh;
if (xpread(fd, &eh, sizeof(eh), 0) != (long)sizeof(eh)) die("not an ELF file", path, 0);
if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || eh.e_ident[EI_MAG2] != ELFMAG2 ||
eh.e_ident[EI_MAG3] != ELFMAG3 || eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_AARCH64 ||
(eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || eh.e_phentsize != sizeof(Elf64_Phdr) ||
eh.e_phnum == 0 || eh.e_phnum > MAX_PHDRS)
if (xpread(fd, eh, sizeof(*eh), 0) != (long)sizeof(*eh)) die("not an ELF file", path, 0);
if (eh->e_ident[EI_MAG0] != ELFMAG0 || eh->e_ident[EI_MAG1] != ELFMAG1 || eh->e_ident[EI_MAG2] != ELFMAG2 ||
eh->e_ident[EI_MAG3] != ELFMAG3 || eh->e_ident[EI_CLASS] != ELFCLASS64 || eh->e_machine != EM_AARCH64 ||
(eh->e_type != ET_EXEC && eh->e_type != ET_DYN) || eh->e_phentsize != sizeof(Elf64_Phdr) ||
eh->e_phnum == 0 || eh->e_phnum > MAX_PHDRS)
die("not a 64-bit ARM ELF program", path, 0);
long size = (long)eh->e_phnum * (long)sizeof(Elf64_Phdr);
if (xpread(fd, ph, (size_t)size, (long)eh->e_phoff) != size) die("truncated program headers", path, 0);
return fd;
}
static void interp_of(const char *path, char *interp, size_t size) {
Elf64_Ehdr eh;
Elf64_Phdr ph[MAX_PHDRS];
long size = (long)eh.e_phnum * (long)sizeof(Elf64_Phdr);
if (xpread(fd, ph, (size_t)size, (long)eh.e_phoff) != size) die("truncated program headers", path, 0);
int fd = read_headers(path, &eh, ph);
read_interp(fd, ph, eh.e_phnum, interp, size, path);
sys6(SYS_close, fd, 0, 0, 0, 0, 0);
}
static void load(const char *path, struct image *im, uintptr_t page) {
Elf64_Ehdr eh;
Elf64_Phdr ph[MAX_PHDRS];
int fd = read_headers(path, &eh, ph);
uintptr_t lo = UINTPTR_MAX, hi = 0;
for (int i = 0; i < eh.e_phnum; i++) {
@@ -173,16 +213,9 @@ static void load(const char *path, struct image *im, uintptr_t page) {
im->phnum = eh.e_phnum;
im->phent = eh.e_phentsize;
im->phdr = 0;
im->interp[0] = 0;
for (int i = 0; i < eh.e_phnum; i++) {
read_interp(fd, ph, eh.e_phnum, im->interp, sizeof(im->interp), path);
for (int i = 0; i < eh.e_phnum; i++)
if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr;
if (ph[i].p_type == PT_INTERP) {
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= sizeof(im->interp)) die("bad PT_INTERP", path, 0);
if (xpread(fd, im->interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
die("truncated PT_INTERP", path, 0);
im->interp[ph[i].p_filesz] = 0;
}
}
if (!im->phdr) {
for (int i = 0; i < eh.e_phnum; i++) {
Elf64_Phdr *p = &ph[i];
@@ -202,6 +235,36 @@ static unsigned long auxv_get(const uintptr_t *auxv, unsigned long type, unsigne
return fallback;
}
static int is_self_exe(const char *execfn) {
if (!execfn) return 0;
if (seq(execfn, "/proc/self/exe") || seq(execfn, "/proc/thread-self/exe")) return 1;
const char *p = "/proc/";
while (*p && *p == *execfn) p++, execfn++;
if (*p) return 0;
char num[24];
int i = (int)sizeof(num) - 1;
num[i] = 0;
unsigned long pid = (unsigned long)sys6(SYS_getpid, 0, 0, 0, 0, 0, 0);
do {
num[--i] = (char)('0' + pid % 10);
pid /= 10;
} while (pid && i > 0);
const char *d = num + i;
while (*d && *d == *execfn) d++, execfn++;
return !*d && seq(execfn, "/exe");
}
static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) {
const char *root = env_get(envp, "DDNATV_ROOT");
if (!root || interp[0] != '/') return interp;
size_t a = slen(root), b = slen(interp);
if (a + b + 1 > size) return interp;
for (size_t i = 0; i < a; i++) buf[i] = root[i];
for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i];
if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp;
return buf;
}
__attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
long argc = (long)sp[0];
char **argv = (char **)(sp + 1);
@@ -211,25 +274,66 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1);
long naux = 0;
while (auxv[naux * 2] != AT_NULL) naux++;
if (argc < 3) die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0));
const char *path;
char **args = argv + 2;
long nargs = argc - 2;
char interp_buf[4096];
char hook_buf[4096];
if (reexec) {
path = env_get(envp, "DDNATV_REAL_EXE");
if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0);
args = argv;
nargs = argc;
const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH");
char prog_interp[256];
interp_of(path, prog_interp, sizeof(prog_interp));
if (prog_interp[0] && lib_path && lib_path[0]) {
const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf));
const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
long n = argc > 1 ? argc - 1 : 0;
char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *));
long k = 0;
v[k++] = (char *)ld_so;
if (hook == (const char *)hook_buf) {
v[k++] = (char *)"--preload";
v[k++] = (char *)hook;
}
v[k++] = (char *)"--library-path";
v[k++] = (char *)lib_path;
v[k++] = (char *)"--argv0";
v[k++] = argc > 0 ? argv[0] : (char *)path;
v[k++] = (char *)path;
for (long i = 0; i < n; i++) v[k++] = argv[1 + i];
v[k] = 0;
args = v;
nargs = k;
path = ld_so;
}
} else if (argc < 3) {
die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
} else {
path = argv[1];
}
uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096);
const char *path = argv[1];
struct image prog, interp;
load(path, &prog, page);
int has_interp = prog.interp[0] != 0;
if (has_interp) load(prog.interp, &interp, page);
if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page);
// The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one.
// The strings stay where the kernel put them.
static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN};
long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0]));
long new_argc = argc - 2;
long new_argc = nargs;
long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2;
uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp;
uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
uintptr_t *w = nsp;
*w++ = (uintptr_t)new_argc;
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2];
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i];
*w++ = 0;
for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i];
*w++ = 0;
+155 -51
View File
@@ -58,6 +58,59 @@
#define EXPORT extern "C" __attribute__((visibility("default")))
struct SymbolSlot {
std::atomic<void *> fn{nullptr};
std::atomic<bool> resolved{false};
};
template <typename Fn> static Fn resolved_symbol(SymbolSlot &slot, void *handle, const char *name) {
if (!slot.resolved.load(std::memory_order_acquire)) {
slot.fn.store(dlsym(handle, name), std::memory_order_relaxed);
slot.resolved.store(true, std::memory_order_release);
}
return reinterpret_cast<Fn>(slot.fn.load(std::memory_order_relaxed));
}
enum class Next : size_t {
open,
openat,
close,
write,
ioctl,
poll,
ppoll,
select,
stat,
stat64,
fstat,
fstat64,
xstat,
xstat64,
fxstat,
fxstat64,
statx,
statfs,
fstatfs,
access,
faccessat,
opendir,
scandir,
inotify_add_watch,
count
};
static const char *const next_names[] = {"open", "openat", "close", "write", "ioctl", "poll", "ppoll", "select", "stat", "stat64", "fstat", "fstat64", "__xstat", "__xstat64", "__fxstat", "__fxstat64", "statx", "statfs", "fstatfs", "access", "faccessat", "opendir", "scandir", "inotify_add_watch"};
static_assert(sizeof(next_names) / sizeof(next_names[0]) == static_cast<size_t>(Next::count), "next_names");
static SymbolSlot next_slots[static_cast<size_t>(Next::count)];
template <typename Fn> static Fn next_symbol(Next which) {
return resolved_symbol<Fn>(next_slots[static_cast<size_t>(which)], RTLD_NEXT, next_names[static_cast<size_t>(which)]);
}
static void resolve_next_symbols() {
for (size_t i = 0; i < static_cast<size_t>(Next::count); i++) next_symbol<void *>(static_cast<Next>(i));
}
#ifdef __GLIBC__
typedef unsigned long ioctl_request_t;
#else
@@ -205,6 +258,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 +276,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")));
@@ -433,6 +495,7 @@ void log(const char *message, ...) {
}
__attribute__((constructor)) static void library_init() {
resolve_next_symbols();
config();
controller_mutex();
controller_map();
@@ -587,7 +650,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");
@@ -724,7 +787,7 @@ open_fake_input_ring(const char *event, int flags) {
return -1;
}
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
int fd = my_open(ring_path.c_str(), O_RDWR | (flags & (O_NONBLOCK | O_CLOEXEC)));
if (fd < 0)
@@ -807,12 +870,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();
@@ -978,7 +1054,7 @@ __attribute__((visibility("hidden"))) static void unpublish_uinput(UinputWriter
}
__attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
for (int node = UINPUT_EVENT_BASE; node < UINPUT_EVENT_LIMIT; node++) {
std::string path = uinput_ring_path(node);
int fd = my_open(path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
@@ -1005,7 +1081,7 @@ __attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out)
}
__attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
int fd = -1;
int node = claim_uinput_node(&fd);
if (node < 0) return -1;
@@ -1391,6 +1467,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 +1475,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
@@ -1416,7 +1494,7 @@ __attribute__((visibility("hidden"))) static const uint8_t *ring_blocks() {
std::lock_guard<std::mutex> guard(lock);
if ((mapped = block.load(std::memory_order_acquire))) return mapped;
tries.fetch_add(1, std::memory_order_relaxed);
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
std::string path = get_ring_path_for_slot(0);
int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) return nullptr;
@@ -1470,6 +1548,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;
@@ -1768,7 +1847,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
if (!process_reads_pads()) {
Logger::log("deck: %s refused: not the Steam client\n", path);
errno = ENOENT;
@@ -1977,7 +2056,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
}
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
if (!process_reads_pads()) {
errno = ENOENT;
return -1;
@@ -2091,11 +2170,12 @@ 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");
if (!path || !*path || !fake_deck_enabled()) return;
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
int fd = my_open(path, O_RDWR | O_CLOEXEC);
if (fd < 0) {
Logger::log("touch: %s not openable (%s)\n", path, strerror(errno));
@@ -2312,7 +2392,8 @@ __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 SymbolSlot inject_slot;
const auto inject = resolved_symbol<inject_fn>(inject_slot, RTLD_DEFAULT, "dd_udevmon_inject");
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
}
@@ -2434,6 +2515,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;
}
@@ -2469,7 +2551,7 @@ __attribute__((visibility("hidden"))) static void note_deck_sysfs(const char *ho
}
EXPORT int fstatfs(int fd, struct statfs *buf) {
static auto real = reinterpret_cast<int (*)(int, struct statfs *)>(dlsym(RTLD_NEXT, "fstatfs"));
const auto real = next_symbol<int (*)(int, struct statfs *)>(Next::fstatfs);
int result = real(fd, buf);
if (fake_deck_enabled() && is_deck_sysfs_fd(fd)) {
note_deck_sysfs("fstatfs", result);
@@ -2479,7 +2561,7 @@ EXPORT int fstatfs(int fd, struct statfs *buf) {
}
EXPORT int statfs(const char *path, struct statfs *buf) {
static auto real = reinterpret_cast<int (*)(const char *, struct statfs *)>(dlsym(RTLD_NEXT, "statfs"));
const auto real = next_symbol<int (*)(const char *, struct statfs *)>(Next::statfs);
int result = real(path, buf);
if (fake_deck_enabled() && is_deck_sysfs_path(path)) {
note_deck_sysfs(path, result);
@@ -2528,7 +2610,7 @@ __attribute__((visibility("hidden"))) static int deck_imu_mode_change(const uint
}
__attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHidraw &deck, int mode) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return;
std::string path = get_ring_path_for_slot(0);
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
@@ -3037,7 +3119,7 @@ static int real_fstat(int fd, struct stat *buf);
__attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
int dirfd, const char *path, int flags, struct statx *buf) {
static auto real_openat = reinterpret_cast<decltype(&::openat)>(dlsym(RTLD_NEXT, "openat"));
const auto real_openat = next_symbol<decltype(&::openat)>(Next::openat);
int target;
if (!path || !*path) {
if (!(flags & AT_EMPTY_PATH)) return false;
@@ -3075,7 +3157,7 @@ __attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
}
EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *buf) {
static auto real = reinterpret_cast<decltype(&::statx)>(dlsym(RTLD_NEXT, "statx"));
const auto real = next_symbol<decltype(&::statx)>(Next::statx);
int result = real(dirfd, path, flags, mask, buf);
int saved_errno = errno;
constexpr unsigned unique_mount_id = 0x4000;
@@ -3096,7 +3178,7 @@ EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct s
#endif
EXPORT DIR *opendir(const char *name) {
static auto real = reinterpret_cast<DIR *(*)(const char *)>(dlsym(RTLD_NEXT, "opendir"));
const auto real = next_symbol<DIR *(*)(const char *)>(Next::opendir);
DIR *dir = real(name);
if (!dir) {
note_sys_failure(AT_FDCWD, name);
@@ -3126,7 +3208,7 @@ EXPORT int open(const char *pathname, int flags, ...) {
va_end(va);
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
@@ -3204,7 +3286,7 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) {
va_end(va);
static auto my_openat = reinterpret_cast<int (*)(int, const char *, int, ...)>(dlsym(RTLD_NEXT, "openat"));
const auto my_openat = next_symbol<int (*)(int, const char *, int, ...)>(Next::openat);
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
@@ -3363,10 +3445,10 @@ static int fake_stat_fd(int fd, S *buf, Real real) {
}
static int real_stat(const char *pathname, struct stat *statbuf) {
static auto fn = reinterpret_cast<int (*)(const char *, struct stat *)>(dlsym(RTLD_NEXT, "stat"));
const auto fn = next_symbol<int (*)(const char *, struct stat *)>(Next::stat);
if (fn) return fn(pathname, statbuf);
#ifdef _STAT_VER
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
const auto xfn = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
#endif
errno = ENOSYS;
@@ -3374,10 +3456,10 @@ static int real_stat(const char *pathname, struct stat *statbuf) {
}
static int real_fstat(int fd, struct stat *buf) {
static auto fn = reinterpret_cast<int (*)(int, struct stat *)>(dlsym(RTLD_NEXT, "fstat"));
const auto fn = next_symbol<int (*)(int, struct stat *)>(Next::fstat);
if (fn) return fn(fd, buf);
#ifdef _STAT_VER
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
const auto xfn = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
if (xfn) return xfn(_STAT_VER, fd, buf);
#endif
errno = ENOSYS;
@@ -3393,7 +3475,7 @@ EXPORT int fstat(int fd, struct stat *buf) {
}
EXPORT int access(const char *pathname, int mode) {
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
const auto my_access = next_symbol<decltype(&::access)>(Next::access);
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
@@ -3434,7 +3516,7 @@ EXPORT int access(const char *pathname, int mode) {
}
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
const auto my_faccessat = next_symbol<decltype(&::faccessat)>(Next::faccessat);
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
@@ -3478,7 +3560,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **,
const struct dirent **)) {
static auto my_scandir = reinterpret_cast<decltype(&::scandir)>(dlsym(RTLD_NEXT, "scandir"));
const auto my_scandir = next_symbol<decltype(&::scandir)>(Next::scandir);
if (dirp) {
if (!strcmp(dirp, "/dev/input")) {
@@ -3492,7 +3574,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
}
EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
static auto my_inotify_add_watch = reinterpret_cast<decltype(&::inotify_add_watch)>(dlsym(RTLD_NEXT, "inotify_add_watch"));
const auto my_inotify_add_watch = next_symbol<decltype(&::inotify_add_watch)>(Next::inotify_add_watch);
char *fake_path = nullptr;
if (pathname) {
@@ -3631,7 +3713,7 @@ static bool wait_snapshot(std::shared_ptr<FakeController> fake,
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
static const auto next = reinterpret_cast<ioctl_fn>(dlsym(RTLD_NEXT, "ioctl"));
const auto next = next_symbol<ioctl_fn>(Next::ioctl);
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
}
@@ -3689,6 +3771,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;
@@ -3866,7 +3952,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
}
EXPORT int close(int fd) {
static auto my_close = reinterpret_cast<decltype(&::close)>(dlsym(RTLD_NEXT, "close"));
const auto my_close = next_symbol<decltype(&::close)>(Next::close);
if (!watched(fd)) return my_close(fd);
close_uinput(fd);
@@ -4054,7 +4140,7 @@ EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
}
EXPORT ssize_t write(int fd, const void *buf, size_t count) {
static auto my_write = reinterpret_cast<decltype(&::write)>(dlsym(RTLD_NEXT, "write"));
const auto my_write = next_symbol<decltype(&::write)>(Next::write);
if (!watched(fd)) return my_write(fd, buf, count);
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
@@ -4129,8 +4215,8 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
const sigset_t *sigmask) {
static auto my_poll = reinterpret_cast<decltype(&::poll)>(dlsym(RTLD_NEXT, "poll"));
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
nfds_t first = 0;
while (first < nfds && !watched(fds[first].fd)) first++;
@@ -4234,7 +4320,7 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
const struct timespec *timeout, const sigset_t *sigmask) {
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
errno = EINVAL;
return -1;
@@ -4261,7 +4347,7 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout) {
static auto my_select = reinterpret_cast<decltype(&::select)>(dlsym(RTLD_NEXT, "select"));
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
fd_set original_readfds;
fd_set original_writefds;
@@ -4423,10 +4509,10 @@ EXPORT int openat64(int dirfd, const char *pathname, int flags, ...) {
}
static int real_stat64(const char *pathname, struct stat64 *statbuf) {
static auto fn = reinterpret_cast<int (*)(const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "stat64"));
const auto fn = next_symbol<int (*)(const char *, struct stat64 *)>(Next::stat64);
if (fn) return fn(pathname, statbuf);
#ifdef _STAT_VER
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
const auto xfn = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
#endif
errno = ENOSYS;
@@ -4434,10 +4520,10 @@ static int real_stat64(const char *pathname, struct stat64 *statbuf) {
}
static int real_fstat64(int fd, struct stat64 *buf) {
static auto fn = reinterpret_cast<int (*)(int, struct stat64 *)>(dlsym(RTLD_NEXT, "fstat64"));
const auto fn = next_symbol<int (*)(int, struct stat64 *)>(Next::fstat64);
if (fn) return fn(fd, buf);
#ifdef _STAT_VER
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
const auto xfn = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
if (xfn) return xfn(_STAT_VER, fd, buf);
#endif
errno = ENOSYS;
@@ -4453,27 +4539,27 @@ EXPORT int fstat64(int fd, struct stat64 *buf) {
}
EXPORT int __xstat(int version, const char *pathname, struct stat *statbuf) {
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
const auto real = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
if (!real) return stat(pathname, statbuf);
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat *buf) { return real(version, path, buf); });
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat *buf) { return real(version, path, buf); });
}
EXPORT int __xstat64(int version, const char *pathname, struct stat64 *statbuf) {
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
const auto real = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
if (!real) return stat64(pathname, statbuf);
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat64 *buf) { return real(version, path, buf); });
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat64 *buf) { return real(version, path, buf); });
}
EXPORT int __fxstat(int version, int fd, struct stat *buf) {
static auto real = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
const auto real = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
if (!real) return fstat(fd, buf);
return fake_stat_fd(fd, buf, [version](int f, struct stat *b) { return real(version, f, b); });
return fake_stat_fd(fd, buf, [version, real](int f, struct stat *b) { return real(version, f, b); });
}
EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) {
static auto real = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
const auto real = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
if (!real) return fstat64(fd, buf);
return fake_stat_fd(fd, buf, [version](int f, struct stat64 *b) { return real(version, f, b); });
return fake_stat_fd(fd, buf, [version, real](int f, struct stat64 *b) { return real(version, f, b); });
}
#if defined(__x86_64__) || defined(__i386__)
@@ -4487,18 +4573,37 @@ static const char *const interposed_names[] = {
};
static dlsym_fn next_dlsym() {
static const dlsym_fn fn = [] {
static std::atomic<dlsym_fn> fn{nullptr};
static std::atomic<bool> resolved{false};
if (!resolved.load(std::memory_order_acquire)) {
#ifdef __x86_64__
const char *base = "GLIBC_2.2.5";
#else
const char *base = "GLIBC_2.0";
#endif
dlsym_fn found{};
for (const char *version : {base, "GLIBC_2.34"}) {
if (auto found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version))) return found;
if ((found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version)))) break;
}
return dlsym_fn{};
}();
return fn;
fn.store(found, std::memory_order_relaxed);
resolved.store(true, std::memory_order_release);
}
return fn.load(std::memory_order_relaxed);
}
static void *libc_handle() {
static std::atomic<void *> handle{nullptr};
static std::atomic<bool> resolved{false};
if (!resolved.load(std::memory_order_acquire)) {
handle.store(dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD), std::memory_order_relaxed);
resolved.store(true, std::memory_order_release);
}
return handle.load(std::memory_order_relaxed);
}
__attribute__((constructor)) static void resolve_dlsym_targets() {
next_dlsym();
libc_handle();
}
static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); }
@@ -4516,8 +4621,7 @@ extern "C" __attribute__((visibility("hidden"), used)) void *fakeinput_dlsym_tar
dlsym_fn next = next_dlsym();
if (!next) return reinterpret_cast<void *>(missing_dlsym);
if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || name == nullptr) return reinterpret_cast<void *>(next);
static void *const libc = dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD);
if (handle != libc || !interposed(name)) return reinterpret_cast<void *>(next);
if (handle != libc_handle() || !interposed(name)) return reinterpret_cast<void *>(next);
return reinterpret_cast<void *>(global_dlsym);
}
+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,
};
+4 -2
View File
@@ -8,6 +8,7 @@ add_library(droiddeckwayland SHARED
src/vk_loader.c
src/sc_layer.c
src/ahb_swapchain.c
src/display_buffers.c
src/waylandcomp_jni.c
src/gpu_clock_pin.c
src/droiddeck_ext.c
@@ -26,7 +27,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
@@ -34,7 +35,8 @@ add_library(droiddeckwayland SHARED
generated/text-input-unstable-v3-protocol.c
generated/xdg-toplevel-icon-v1-protocol.c
generated/single-pixel-buffer-v1-protocol.c
generated/banner-ahb-v1-protocol.c
generated/droiddeck-ahb-v1-protocol.c
generated/droiddeck-refresh-v1-protocol.c
src/framegen_bridge.c
src/framegen_jni.c
src/hudframes.c
@@ -19,8 +19,8 @@ exactly how Turnip already imports every gralloc buffer on Android (`vk_android.
in play already have every extension needed; nothing is missing in the drivers. What is missing is
a **WSI hook**: Mesa's Wayland WSI always allocates its own dma-bufs and has no way to receive or
allocate compositor-visible buffers, so **option (a) or (c) each need a ~300-line patch to
`wsi_common_wayland.c` in our own Wayland Turnip build** (banners-turnip-wayland
`build_turnip_wayland_wsi.sh`, Mesa `7cda7850`) plus a small private Wayland protocol. Nothing in
`wsi_common_wayland.c` in our own Wayland Turnip build**
(`build_turnip_wayland_wsi.sh`, Mesa `7cda7850`) plus a small private Wayland protocol. Nothing in
the app can remove the copy on its own. Recommended: **option (a′) - the game's WSI allocates its
swapchain images as `AHardwareBuffer`s (gralloc-native, UBWC), imports them through the AHB path
Turnip already has, and hands the compositor the AHB over a Unix socket (`AHardwareBuffer_send/
@@ -77,7 +77,7 @@ Mesa's Wayland WSI creates every native swapchain image with `wsi_create_native_
(the Android-WSI import path, `tu_image.cc:880-925`) is only reachable from the Android swapchain.
The patch (in our Wayland Turnip build): a new `create_mem` for the Wayland chain, selected when the
compositor advertises a private global `banner_layer_buffer_v1`:
compositor advertises a private global `droiddeck_layer_buffer_v1`:
1. `AHardwareBuffer_allocate(w, h, R8G8B8A8, GPU_COLOR_OUTPUT | GPU_SAMPLED_IMAGE)`;
`vkGetAndroidHardwareBufferPropertiesANDROID` → `vkAllocateMemory` with
`VkImportAndroidHardwareBufferInfoANDROID` (Turnip: `tu_device.cc:3828`), bind - the image was
@@ -85,7 +85,7 @@ compositor advertises a private global `banner_layer_buffer_v1`:
2. `wsi_image.dma_buf_fd = dup(native_handle->data[0])`, `drm_modifier` / `row_pitches[0]` from
the same layout → the existing `zwp_linux_dmabuf_v1` path stays untouched: the compositor keeps
importing a dma-buf and can keep the blit path as the fallback.
3. `banner_layer_buffer_v1.attach(wl_buffer, socket_fd)`: the WSI creates a `socketpair`, sends one
3. `droiddeck_layer_buffer_v1.attach(wl_buffer, socket_fd)`: the WSI creates a `socketpair`, sends one
end in the request, and calls `AHardwareBuffer_sendHandleToUnixSocket(ahb, other_end)`; the
compositor's request handler does `AHardwareBuffer_recvHandleFromUnixSocket` and stores the AHB
on `struct dmabuf_buffer`. Per swapchain image, once - not per frame.
@@ -262,7 +262,7 @@ D3D12 tabs) as the workload, session log in `Download/Wayland-logs/`.
since the blit only changed its destination) and `dumpsys gfxinfo`/battery for 5 min each. This
is the baseline the WSI patch is measured against.
4. **Fence probe outcome → choose the acquire-fence design** (§3) before starting the WSI patch.
5. **WSI patch (option a) in banners-turnip-wayland**, wcp rebuild, then the same steps 1–3 with
5. **WSI patch (option a) in the Wayland Turnip build**, wcp rebuild, then the same steps 1–3 with
the AHB arriving from the guest: log line to add on the compositor side `layer: buffer N of
"<window>" received from the game (AHardwareBuffer WxH, UBWC)` and the fps delta vs X11.
@@ -296,7 +296,7 @@ unchanged. Off by default: with the variable unset no new code runs.
Not zero-copy yet - it is the receive side. The copy disappears when step 5 lands and
`sc_layer_present` is handed the game's own `AHardwareBuffer` instead of a pool slot.
## 7. Step 5 implemented (feat/wayland-zero-copy-wsi + banners-turnip-wayland `banner_ahb_wsi.py`)
## 7. Step 5 implemented (feat/wayland-zero-copy-wsi + the Wayland Turnip build `droiddeck_ahb_wsi.py`)
Option (a′) as recommended, with one deviation forced by the build: the Wayland Turnip is a
`platforms=wayland` build with Android detection off, so `VK_ANDROID_external_memory_android_hardware_buffer`
@@ -38,7 +38,7 @@
extern const struct wl_interface wl_buffer_interface;
static const struct wl_interface *banner_ahb_v1_types[] = {
static const struct wl_interface *droiddeck_ahb_v1_types[] = {
NULL,
&wl_buffer_interface,
NULL,
@@ -50,18 +50,18 @@ static const struct wl_interface *banner_ahb_v1_types[] = {
NULL,
};
static const struct wl_message banner_ahb_v1_requests[] = {
{ "destroy", "", banner_ahb_v1_types + 0 },
{ "attach", "ohuuuuuu", banner_ahb_v1_types + 1 },
static const struct wl_message droiddeck_ahb_v1_requests[] = {
{ "destroy", "", droiddeck_ahb_v1_types + 0 },
{ "attach", "ohuuuuuu", droiddeck_ahb_v1_types + 1 },
};
static const struct wl_message banner_ahb_v1_events[] = {
{ "mode", "2u", banner_ahb_v1_types + 0 },
static const struct wl_message droiddeck_ahb_v1_events[] = {
{ "mode", "2u", droiddeck_ahb_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface banner_ahb_v1_interface = {
"banner_ahb_v1", 2,
2, banner_ahb_v1_requests,
1, banner_ahb_v1_events,
WL_PRIVATE const struct wl_interface droiddeck_ahb_v1_interface = {
"droiddeck_ahb_v1", 2,
2, droiddeck_ahb_v1_requests,
1, droiddeck_ahb_v1_events,
};
@@ -1,6 +1,6 @@
#ifndef BANNER_AHB_V1_SERVER_PROTOCOL_H
#define BANNER_AHB_V1_SERVER_PROTOCOL_H
#ifndef DROIDDECK_AHB_V1_SERVER_PROTOCOL_H
#define DROIDDECK_AHB_V1_SERVER_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
@@ -14,7 +14,7 @@ struct wl_client;
struct wl_resource;
/*
* @section page_copyright_banner_ahb_v1 Copyright
* @section page_copyright_droiddeck_ahb_v1 Copyright
*
* Copyright 2026 The412Banner
*
@@ -42,15 +42,15 @@ struct wl_resource;
struct banner_ahb_v1;
struct droiddeck_ahb_v1;
struct wl_buffer;
#ifndef BANNER_AHB_V1_INTERFACE
#define BANNER_AHB_V1_INTERFACE
extern const struct wl_interface banner_ahb_v1_interface;
#ifndef DROIDDECK_AHB_V1_INTERFACE
#define DROIDDECK_AHB_V1_INTERFACE
extern const struct wl_interface droiddeck_ahb_v1_interface;
#endif
struct banner_ahb_v1_interface {
struct droiddeck_ahb_v1_interface {
void (*destroy)(struct wl_client *client,
struct wl_resource *resource);
void (*attach)(struct wl_client *client,
@@ -65,17 +65,17 @@ struct banner_ahb_v1_interface {
uint32_t image_count);
};
#define BANNER_AHB_V1_MODE 0
#define DROIDDECK_AHB_V1_MODE 0
#define BANNER_AHB_V1_MODE_SINCE_VERSION 2
#define DROIDDECK_AHB_V1_MODE_SINCE_VERSION 2
#define BANNER_AHB_V1_DESTROY_SINCE_VERSION 1
#define BANNER_AHB_V1_ATTACH_SINCE_VERSION 1
#define DROIDDECK_AHB_V1_DESTROY_SINCE_VERSION 1
#define DROIDDECK_AHB_V1_ATTACH_SINCE_VERSION 1
static inline void
banner_ahb_v1_send_mode(struct wl_resource *resource_, uint32_t enabled)
droiddeck_ahb_v1_send_mode(struct wl_resource *resource_, uint32_t enabled)
{
wl_resource_post_event(resource_, BANNER_AHB_V1_MODE, enabled);
wl_resource_post_event(resource_, DROIDDECK_AHB_V1_MODE, enabled);
}
#ifdef __cplusplus
@@ -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
}
@@ -0,0 +1,59 @@
/*
* Copyright 2026 DroidDeck contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include <stdint.h>
#include "wayland-util.h"
#ifndef __has_attribute
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
#endif
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
#else
#define WL_PRIVATE
#endif
static const struct wl_interface *droiddeck_refresh_v1_types[] = {
NULL,
NULL,
};
static const struct wl_message droiddeck_refresh_v1_requests[] = {
{ "destroy", "", droiddeck_refresh_v1_types + 0 },
{ "set_target", "uu", droiddeck_refresh_v1_types + 0 },
};
static const struct wl_message droiddeck_refresh_v1_events[] = {
{ "rate", "u", droiddeck_refresh_v1_types + 0 },
{ "done", "", droiddeck_refresh_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface droiddeck_refresh_v1_interface = {
"droiddeck_refresh_v1", 1,
2, droiddeck_refresh_v1_requests,
2, droiddeck_refresh_v1_events,
};
@@ -0,0 +1,175 @@
#ifndef DROIDDECK_REFRESH_V1_SERVER_PROTOCOL_H
#define DROIDDECK_REFRESH_V1_SERVER_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-server.h"
#ifdef __cplusplus
extern "C" {
#endif
struct wl_client;
struct wl_resource;
/**
* @page page_droiddeck_refresh_v1 The droiddeck_refresh_v1 protocol
* @section page_ifaces_droiddeck_refresh_v1 Interfaces
* - @subpage page_iface_droiddeck_refresh_v1 - panel refresh rates a nested compositor may ask for
* @section page_copyright_droiddeck_refresh_v1 Copyright
* <pre>
*
* Copyright 2026 DroidDeck contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
* </pre>
*/
struct droiddeck_refresh_v1;
#ifndef DROIDDECK_REFRESH_V1_INTERFACE
#define DROIDDECK_REFRESH_V1_INTERFACE
/**
* @page page_iface_droiddeck_refresh_v1 droiddeck_refresh_v1
* @section page_iface_droiddeck_refresh_v1_desc Description
*
* A nested compositor paces its clients against the refresh rate of the
* panel it is shown on. When its clients are held to a frame rate the
* panel's current rate does not divide evenly, frames are shown for an
* uneven number of refreshes. This interface lets the nested compositor
* see every refresh rate the panel can run at its current size and ask
* for the one that suits the frame rate it is pacing to.
*
* On bind the compositor sends one rate event per refresh rate, lowest
* first, followed by done. The list is sent again, in full, whenever it
* changes (a different panel, or a limit the user placed on the panel's
* rate). The rate the panel is running at is still reported the standard
* way, through wl_output.mode.
*
* A request is a preference, not a guarantee: the user, the platform or
* another output mirroring the panel may hold the panel at another rate.
* The client reads the result from wl_output.mode.
* @section page_iface_droiddeck_refresh_v1_api API
* See @ref iface_droiddeck_refresh_v1.
*/
/**
* @defgroup iface_droiddeck_refresh_v1 The droiddeck_refresh_v1 interface
*
* A nested compositor paces its clients against the refresh rate of the
* panel it is shown on. When its clients are held to a frame rate the
* panel's current rate does not divide evenly, frames are shown for an
* uneven number of refreshes. This interface lets the nested compositor
* see every refresh rate the panel can run at its current size and ask
* for the one that suits the frame rate it is pacing to.
*
* On bind the compositor sends one rate event per refresh rate, lowest
* first, followed by done. The list is sent again, in full, whenever it
* changes (a different panel, or a limit the user placed on the panel's
* rate). The rate the panel is running at is still reported the standard
* way, through wl_output.mode.
*
* A request is a preference, not a guarantee: the user, the platform or
* another output mirroring the panel may hold the panel at another rate.
* The client reads the result from wl_output.mode.
*/
extern const struct wl_interface droiddeck_refresh_v1_interface;
#endif
/**
* @ingroup iface_droiddeck_refresh_v1
* @struct droiddeck_refresh_v1_interface
*/
struct droiddeck_refresh_v1_interface {
/**
* destroy the object
*
* The preference set through this object is dropped.
*/
void (*destroy)(struct wl_client *client,
struct wl_resource *resource);
/**
* ask for a refresh rate
*
* refresh is the panel rate the client would like, in Hz, taken
* from the advertised list; 0 withdraws the preference. frame_rate
* is the frame rate the client holds its content to, in frames per
* second, or 0 when the content is not held to a rate. The
* compositor may multiply the content's frame rate itself
* (generated frames); when it does, it picks the advertised rate
* that the multiplied frame rate divides evenly instead of the
* requested one.
* @param refresh wanted panel refresh rate in Hz, 0 for none
* @param frame_rate content frame rate in frames per second, 0 for unpaced
*/
void (*set_target)(struct wl_client *client,
struct wl_resource *resource,
uint32_t refresh,
uint32_t frame_rate);
};
#define DROIDDECK_REFRESH_V1_RATE 0
#define DROIDDECK_REFRESH_V1_DONE 1
/**
* @ingroup iface_droiddeck_refresh_v1
*/
#define DROIDDECK_REFRESH_V1_RATE_SINCE_VERSION 1
/**
* @ingroup iface_droiddeck_refresh_v1
*/
#define DROIDDECK_REFRESH_V1_DONE_SINCE_VERSION 1
/**
* @ingroup iface_droiddeck_refresh_v1
*/
#define DROIDDECK_REFRESH_V1_DESTROY_SINCE_VERSION 1
/**
* @ingroup iface_droiddeck_refresh_v1
*/
#define DROIDDECK_REFRESH_V1_SET_TARGET_SINCE_VERSION 1
/**
* @ingroup iface_droiddeck_refresh_v1
* Sends an rate event to the client owning the resource.
* @param resource_ The client's resource
* @param refresh panel refresh rate in Hz
*/
static inline void
droiddeck_refresh_v1_send_rate(struct wl_resource *resource_, uint32_t refresh)
{
wl_resource_post_event(resource_, DROIDDECK_REFRESH_V1_RATE, refresh);
}
/**
* @ingroup iface_droiddeck_refresh_v1
* Sends an done event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
droiddeck_refresh_v1_send_done(struct wl_resource *resource_)
{
wl_resource_post_event(resource_, DROIDDECK_REFRESH_V1_DONE);
}
#ifdef __cplusplus
}
#endif
#endif
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="banner_ahb_v1">
<protocol name="droiddeck_ahb_v1">
<copyright>
Copyright 2026 The412Banner
@@ -23,7 +23,7 @@
DEALINGS IN THE SOFTWARE.
</copyright>
<interface name="banner_ahb_v1" version="2">
<interface name="droiddeck_ahb_v1" version="2">
<description summary="Android gralloc buffers behind dma-buf wl_buffers">
Zero-copy window layers on Android. A Vulkan swapchain image that the
client allocated as an Android AHardwareBuffer (gralloc) is still shared
@@ -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
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="droiddeck_refresh_v1">
<copyright>
Copyright 2026 DroidDeck contributors
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</copyright>
<interface name="droiddeck_refresh_v1" version="1">
<description summary="panel refresh rates a nested compositor may ask for">
A nested compositor paces its clients against the refresh rate of the
panel it is shown on. When its clients are held to a frame rate the
panel's current rate does not divide evenly, frames are shown for an
uneven number of refreshes. This interface lets the nested compositor
see every refresh rate the panel can run at its current size and ask
for the one that suits the frame rate it is pacing to.
On bind the compositor sends one rate event per refresh rate, lowest
first, followed by done. The list is sent again, in full, whenever it
changes (a different panel, or a limit the user placed on the panel's
rate). The rate the panel is running at is still reported the standard
way, through wl_output.mode.
A request is a preference, not a guarantee: the user, the platform or
another output mirroring the panel may hold the panel at another rate.
The client reads the result from wl_output.mode.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the object">
The preference set through this object is dropped.
</description>
</request>
<request name="set_target">
<description summary="ask for a refresh rate">
refresh is the panel rate the client would like, in Hz, taken from
the advertised list; 0 withdraws the preference. frame_rate is the
frame rate the client holds its content to, in frames per second, or
0 when the content is not held to a rate. The compositor may multiply
the content's frame rate itself (generated frames); when it does, it
picks the advertised rate that the multiplied frame rate divides
evenly instead of the requested one.
</description>
<arg name="refresh" type="uint" summary="wanted panel refresh rate in Hz, 0 for none"/>
<arg name="frame_rate" type="uint" summary="content frame rate in frames per second, 0 for unpaced"/>
</request>
<event name="rate">
<description summary="a refresh rate the panel can run">
Sent once per rate, lowest first, in Hz rounded to the nearest whole
number.
</description>
<arg name="refresh" type="uint" summary="panel refresh rate in Hz"/>
</event>
<event name="done">
<description summary="the list of rates is complete">
Ends a list of rate events. The rates received since the previous
done replace the earlier list.
</description>
</event>
</interface>
</protocol>
@@ -4,7 +4,7 @@
#include "droiddeck_ext.h"
#include "sc_layer.h"
#include "vk_present.h"
#include "banner-ahb-v1-server-protocol.h"
#include "droiddeck-ahb-v1-server-protocol.h"
#include <android/hardware_buffer.h>
#include <errno.h>
#include <fcntl.h>
@@ -25,6 +25,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;
void droiddeck_dmabuf_formats_stale(void);
struct ahb_buf {
uint64_t id;
@@ -37,6 +38,7 @@ struct ahb_buf {
struct wl_client *client;
struct wl_resource *resource;
struct wl_listener resource_destroy;
int display;
int on_layer;
int release_pending;
int64_t deferred_ns;
@@ -131,10 +133,10 @@ static void handle_released(uint64_t id, int fd) {
if (fd >= 0) {
struct droiddeck_dma_buf_sync_file imp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = fd};
int dmabuf_fd = droiddeck_dmabuf_fd(ab->b);
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) {
if (!ab->display && dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) {
close(fd);
} else {
if (!g_import_failed_logged) {
if (!ab->display && !g_import_failed_logged) {
g_import_failed_logged = 1;
droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_IMPORT_SYNC_FILE failed (%s): releases wait for the display's fence here instead",
strerror(errno));
@@ -187,7 +189,7 @@ int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b) {
return b && *droiddeck_dmabuf_ahb_slot((struct dmabuf_buffer *)b) != NULL;
}
int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h) {
int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h, const struct vkp_draw *draw) {
struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL;
if (!ab) return -1;
int dmabuf_fd = droiddeck_dmabuf_fd(b);
@@ -205,7 +207,7 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h,
int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw,
s ? droiddeck_surface_color(s) : NULL, ab->format);
if (r < 0) return -1;
if (r == 1) return 0;
@@ -259,6 +261,58 @@ uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b) {
}
static int adopt(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b, AHardwareBuffer *ahb,
uint32_t stride, uint32_t image_count, uint64_t modifier) {
AHardwareBuffer_Desc d;
AHardwareBuffer_describe(ahb, &d);
int bw, bh;
droiddeck_dmabuf_size(b, &bw, &bh);
struct ahb_buf *ab = calloc(1, sizeof(*ab));
if (!ab) return -1;
ab->id = g_next_id++;
ab->b = b;
droiddeck_dmabuf_ref(b);
ab->ahb = ahb;
ab->w = bw; ab->h = bh;
ab->stride = d.stride ? d.stride : stride;
ab->image_count = image_count;
ab->format = d.format;
ab->modifier = modifier;
ab->client = c;
ab->resource = buffer;
ab->resource_destroy.notify = on_buffer_resource_destroyed;
wl_resource_add_destroy_listener(buffer, &ab->resource_destroy);
ab->fence_fd = -1;
wl_list_insert(g_bufs.prev, &ab->link);
*droiddeck_dmabuf_ahb_slot(b) = ab;
if (g_last_chain.client != c || g_last_chain.w != bw || g_last_chain.h != bh ||
g_last_chain.image_count != image_count || g_last_chain.modifier != modifier || g_last_chain.format != d.format) {
char count[32] = "";
if (image_count) snprintf(count, sizeof(count), "%u images, ", image_count);
g_last_chain = (struct chain_seen){c, bw, bh, image_count, modifier, d.format};
droiddeck_log("layer", "zero-copy: %s from %s (%s%dx%d, %s, %s, stride %u px)",
image_count ? "AHB swapchain" : "display buffers", droiddeck_client_name(c), count, bw, bh,
droiddeck_ahb_format_name(d.format), modifier == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)"
: modifier == 0 ? "linear" : "unknown modifier", ab->stride);
}
return 0;
}
int ahb_swapchain_adopt(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b, AHardwareBuffer *ahb,
uint64_t modifier) {
if (!g_advertised || *droiddeck_dmabuf_ahb_slot(b)) return -1;
AHardwareBuffer_acquire(ahb);
if (adopt(c, buffer, b, ahb, 0, 0, modifier) != 0) { AHardwareBuffer_release(ahb); return -1; }
((struct ahb_buf *)*droiddeck_dmabuf_ahb_slot(b))->display = 1;
return 0;
}
AHardwareBuffer *ahb_swapchain_display_buffer(const struct dmabuf_buffer *b) {
struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot((struct dmabuf_buffer *)b) : NULL;
return ab && ab->display ? ab->ahb : NULL;
}
static void ahb_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_resource *buffer, int32_t sock,
@@ -295,36 +349,13 @@ static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_res
AHardwareBuffer_release(ahb);
return;
}
struct ahb_buf *ab = calloc(1, sizeof(*ab));
if (!ab) { AHardwareBuffer_release(ahb); wl_client_post_no_memory(c); return; }
ab->id = g_next_id++;
ab->b = b;
droiddeck_dmabuf_ref(b);
ab->ahb = ahb;
ab->w = bw; ab->h = bh;
ab->stride = d.stride ? d.stride : stride;
ab->image_count = image_count;
ab->format = d.format;
ab->modifier = modifier;
ab->client = c;
ab->resource = buffer;
ab->resource_destroy.notify = on_buffer_resource_destroyed;
wl_resource_add_destroy_listener(buffer, &ab->resource_destroy);
ab->fence_fd = -1;
wl_list_insert(g_bufs.prev, &ab->link);
*slot = ab;
if (g_last_chain.client != c || g_last_chain.w != bw || g_last_chain.h != bh ||
g_last_chain.image_count != image_count || g_last_chain.modifier != modifier || g_last_chain.format != d.format) {
g_last_chain = (struct chain_seen){c, bw, bh, image_count, modifier, d.format};
droiddeck_log("layer", "zero-copy: AHB swapchain from %s (%u images, %dx%d, %s, %s, stride %u px)", droiddeck_client_name(c),
image_count, bw, bh, droiddeck_ahb_format_name(d.format), modifier == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)"
: modifier == 0 ? "linear" : "unknown modifier", ab->stride);
if (adopt(c, buffer, b, ahb, stride, image_count, modifier) != 0) {
AHardwareBuffer_release(ahb);
wl_client_post_no_memory(c);
}
}
static const struct banner_ahb_v1_interface ahb_impl = {
static const struct droiddeck_ahb_v1_interface ahb_impl = {
.destroy = ahb_destroy,
.attach = ahb_attach,
};
@@ -336,20 +367,21 @@ static void on_client_resource_destroyed(struct wl_resource *r) {
static void bind_ahb(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
static struct wl_client *last_named;
if (ver > 2) ver = 2;
struct wl_resource *r = wl_resource_create(c, &banner_ahb_v1_interface, (int)ver, id);
struct wl_resource *r = wl_resource_create(c, &droiddeck_ahb_v1_interface, (int)ver, 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 >= DROIDDECK_AHB_V1_MODE_SINCE_VERSION) droiddeck_ahb_v1_send_mode(r, g_zero_copy ? 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,
droiddeck_log("layer", "zero-copy: %s bound droiddeck_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver,
ver >= 2 ? "follows the live switch" : "version 1: decides from its launch environment only");
}
}
void ahb_swapchain_set_mode(int on, int live) {
on = on ? 1 : 0;
if (g_zero_copy != on) droiddeck_dmabuf_formats_stale();
g_zero_copy = on;
if (!g_advertised) {
if (live) droiddeck_log("layer", "zero-copy switched %s from the drawer, but no display layer is available on this device: no change",
@@ -361,8 +393,8 @@ void ahb_swapchain_set_mode(int on, int live) {
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);
if (wl_resource_get_version(r) >= DROIDDECK_AHB_V1_MODE_SINCE_VERSION) {
droiddeck_ahb_v1_send_mode(r, (uint32_t)on);
told++;
}
}
@@ -385,7 +417,7 @@ void ahb_swapchain_init(struct wl_display *display) {
wl_list_init(&g_bufs);
wl_list_init(&g_clients);
if (!sc_layer_available()) {
droiddeck_log("layer", "zero-copy: no display layer on this device (see the line above): banner_ahb_v1 not advertised");
droiddeck_log("layer", "zero-copy: no display layer on this device (see the line above): droiddeck_ahb_v1 not advertised");
return;
}
g_loop = wl_display_get_event_loop(display);
@@ -395,11 +427,11 @@ void ahb_swapchain_init(struct wl_display *display) {
return;
}
wl_event_loop_add_fd(g_loop, g_rel_pipe[0], WL_EVENT_READABLE, on_release_pipe, NULL);
if (!wl_global_create(display, &banner_ahb_v1_interface, 2, NULL, bind_ahb)) {
droiddeck_log("error", "zero-copy: banner_ahb_v1 global creation failed");
if (!wl_global_create(display, &droiddeck_ahb_v1_interface, 2, NULL, bind_ahb)) {
droiddeck_log("error", "zero-copy: droiddeck_ahb_v1 global creation failed");
return;
}
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)");
droiddeck_log("layer", "zero-copy: droiddeck_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)");
ahb_swapchain_set_mode(g_zero_copy, 0);
}
@@ -2,16 +2,21 @@
#define AHB_SWAPCHAIN_H
#include <stddef.h>
#include <stdint.h>
#include <android/hardware_buffer.h>
#include <wayland-server.h>
struct dmabuf_buffer;
struct surface;
struct vkp_draw;
void ahb_swapchain_init(struct wl_display *display);
void ahb_swapchain_set_mode(int on, int live);
int ahb_swapchain_last_frame_age_ms(void);
int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b);
int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h);
int ahb_swapchain_adopt(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b, AHardwareBuffer *ahb,
uint64_t modifier);
AHardwareBuffer *ahb_swapchain_display_buffer(const struct dmabuf_buffer *b);
int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h, const struct vkp_draw *draw);
int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *buffer, struct surface *s, int paced);
void ahb_swapchain_surface_gone(struct surface *s);
unsigned ahb_swapchain_stats_take(void);
+367 -58
View File
@@ -23,8 +23,10 @@
#include "linux-dmabuf-v1-server-protocol.h"
#include "sc_layer.h"
#include "ahb_swapchain.h"
#include "display_buffers.h"
#include "viewporter-server-protocol.h"
#include "banner-desktop-v1-server-protocol.h"
#include "droiddeck-desktop-v1-server-protocol.h"
#include "droiddeck-refresh-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 +81,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 {
@@ -218,6 +220,7 @@ struct surface {
struct vkp_image *shm_img;
int black_fill;
struct wl_resource *dmabuf;
struct dmabuf_buffer *dmabuf_buf;
struct wl_listener dmabuf_destroy;
@@ -256,6 +259,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;
@@ -279,6 +283,8 @@ static int g_dirty;
static int64_t g_dirty_since_ns;
volatile int g_render_on_commit = 1;
static int64_t g_rendered_tick_ns;
static int g_tick_spare;
static int g_scene_queues;
static int g_tick_held;
static int64_t g_hold_missed_ns;
#define HOLD_RETRY_NS 1000000000LL
@@ -288,7 +294,11 @@ static struct {
int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns;
const void *buffers[PACE_BUFFERS];
uint64_t game_frames_seen;
unsigned gaps[4];
} g_pace;
static int64_t g_game_frame_ns;
static void note_game_frame_gap(void);
static void pace_note_buffer(const void *buffer) {
for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++)
@@ -317,6 +327,16 @@ volatile int g_hide_shell;
volatile int g_zero_copy;
static int g_zero_copy_paused;
extern volatile int g_display_buffer_driver;
extern void droiddeck_on_overlay_planes(int planes);
static int g_overlay_planes_told = -1;
static void tell_overlay_planes(void) {
const int planes = (g_zero_copy && g_display_buffer_driver) ? (sc_layer_overlay_affordable() ? 1 : 0) : -1;
if (planes == g_overlay_planes_told) return;
g_overlay_planes_told = planes;
droiddeck_on_overlay_planes(planes);
}
static int g_zero_copy_fx_skip_said;
volatile int g_ubwc = 1;
@@ -332,6 +352,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 +455,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 +515,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 +537,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;
@@ -634,6 +708,13 @@ const struct wl_buffer_interface dbuf_buffer_impl = {
.destroy = dbuf_buffer_destroy_req,
};
static struct vkp_image *import_dmabuf(struct dmabuf_buffer *b) {
AHardwareBuffer *ahb = ahb_swapchain_display_buffer(b);
struct vkp_image *img = ahb ? vkp_image_from_ahb(ahb) : NULL;
return img ? img : vkp_image_from_dmabuf(b->fd[0], b->format, b->modifier, b->width, b->height, b->stride[0],
b->offset[0]);
}
static struct dmabuf_buffer *get_dmabuf(struct wl_resource *buffer) {
if (buffer && wl_resource_instance_of(buffer, &wl_buffer_interface, &dbuf_buffer_impl))
return wl_resource_get_user_data(buffer);
@@ -656,6 +737,11 @@ static void describe(const struct surface *s, char *out, size_t size) {
else snprintf(out, size, "window %#x (%s)", w->hwnd, prog);
}
static int is_steam_client_surface(const struct surface *s) {
const char *name = client_name(wl_resource_get_client(s->resource));
return strcmp(name, "steam") == 0 || strstr(name, "steamwebhelper") != NULL;
}
static struct surface *toplevel_by_hwnd(uint32_t hwnd) {
struct surface *s;
wl_list_for_each(s, &g_toplevels, toplevel_link)
@@ -721,7 +807,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;
@@ -813,6 +899,13 @@ int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
static uint64_t g_game_frames;
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
extern void droiddeck_on_game_frame(void);
extern void droiddeck_on_compositor_frame(void);
extern void droiddeck_on_content_rate(int fps);
static int64_t g_cadence_ns;
static int64_t g_cadence_frames;
static int g_content_fps;
static int g_framegen_layer_said;
static int g_framegen_layer;
extern void droiddeck_on_game_program(int pid, const char *program);
static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) {
@@ -833,6 +926,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
s->buf_w = w;
s->buf_h = h;
s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888;
s->black_fill = 0;
s->has_content = s->shm_img != NULL;
g_stat_shm++;
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
@@ -861,9 +955,10 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
g_hud_shm = s;
g_hud_shm_ns = now;
g_hud_new = 1;
droiddeck_on_game_frame();
}
}
if (s == g_hud_shm && (!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL))
droiddeck_on_compositor_frame();
}
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
@@ -877,6 +972,7 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
s->buf_w = 1;
s->buf_h = 1;
s->buf_alpha = bgra[3] != 0xff;
s->black_fill = !bgra[0] && !bgra[1] && !bgra[2] && bgra[3] == 0xff;
s->has_content = s->shm_img != NULL;
}
@@ -887,6 +983,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++;
@@ -894,8 +991,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
wl_resource_add_destroy_listener(buffer, &s->dmabuf_destroy);
}
if (!b->img && !b->import_failed && b->n_planes >= 1) {
b->img = vkp_image_from_dmabuf(b->fd[0], b->format, b->modifier, b->width, b->height,
b->stride[0], b->offset[0]);
b->img = import_dmabuf(b);
if (b->img && g_zero_copy) sc_layer_probe_dmabuf_fd(b->fd[0]);
if (!b->img) {
b->import_failed = 1;
@@ -936,7 +1032,8 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
droiddeck_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)",
name, b->width, b->height, (unsigned long long)b->modifier);
}
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
if (s != g_hud_surface && !is_steam_client_surface(s) &&
(b->img || ahb_swapchain_has_ahb(b)) &&
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) ||
(announced_now && !below_surface(g_hud_surface, s) &&
(int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
@@ -961,9 +1058,30 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
: "the compositor's driver could NOT import it (nothing can show it)");
s->hdr_fmt_logged = b->format;
}
if (s == g_hud_surface) {
if (s == g_hud_surface && !is_steam_client_surface(s)) {
g_hud_alive_ns = now_ns();
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; droiddeck_on_game_frame(); }
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; note_game_frame_gap(); droiddeck_on_game_frame(); }
} else if (is_steam_client_surface(s) && !repeat &&
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL)) {
droiddeck_on_compositor_frame();
}
}
static void note_game_frame_gap(void) {
const int64_t now = now_ns();
if (g_game_frame_ns && g_refresh_ns > 0) {
const int64_t gap = (now - g_game_frame_ns + g_refresh_ns / 2) / g_refresh_ns;
g_pace.gaps[gap < 1 ? 0 : gap > 4 ? 3 : gap - 1]++;
}
if (g_game_frame_ns && now - g_game_frame_ns >= 1000000000LL) { g_cadence_ns = 0; g_cadence_frames = 0; }
g_game_frame_ns = now;
if (!g_cadence_ns) g_cadence_ns = now;
g_cadence_frames++;
if (now - g_cadence_ns >= 1000000000LL) {
g_content_fps = (int)((g_cadence_frames * 1000000000LL + (now - g_cadence_ns) / 2) / (now - g_cadence_ns));
droiddeck_on_content_rate(g_content_fps);
g_cadence_ns = now;
g_cadence_frames = 0;
}
}
@@ -977,7 +1095,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); }
@@ -1148,8 +1266,7 @@ static void cursor_publish_buffer(struct surface *s, struct wl_resource *buffer)
} else if (db && db->n_planes >= 1 && db->width > 0 && db->height > 0 &&
(int64_t)db->width * db->height <= CURSOR_MAX_PX) {
if (!db->img && !db->import_failed) {
db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height,
db->stride[0], db->offset[0]);
db->img = import_dmabuf(db);
if (!db->img) db->import_failed = 1;
}
if (!db->img) return;
@@ -1157,8 +1274,9 @@ static void cursor_publish_buffer(struct surface *s, struct wl_resource *buffer)
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
if (vkp_image_readback(db->img, g_cursor_rb, CURSOR_MAX_PX) != 0) return;
const int row = vkp_image_width(db->img);
cursor_publish_pixels((const uint8_t *)g_cursor_rb, db->width, db->height,
(size_t)db->width * 4, g_cursor_hx, g_cursor_hy);
(size_t)(row > db->width ? row : db->width) * 4, g_cursor_hx, g_cursor_hy);
} else {
return;
}
@@ -1265,6 +1383,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 +1394,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 +1407,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 +1605,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 +1646,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 +1922,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);
}
@@ -1820,6 +1946,57 @@ static void output_send_mode(struct wl_resource *r, int mhz) {
mhz);
}
#define PANEL_RATES_MAX 16
extern void droiddeck_on_refresh_target(int refresh, int frame_rate);
static pthread_mutex_t g_panel_rates_lock = PTHREAD_MUTEX_INITIALIZER;
static int g_panel_rates[PANEL_RATES_MAX], g_panel_rate_count;
static atomic_int g_panel_rates_pending;
static struct wl_list g_refresh_clients;
static struct wl_resource *g_refresh_target_owner;
static void refresh_send_rates(struct wl_resource *r) {
int rates[PANEL_RATES_MAX];
pthread_mutex_lock(&g_panel_rates_lock);
const int count = g_panel_rate_count;
memcpy(rates, g_panel_rates, sizeof(rates));
pthread_mutex_unlock(&g_panel_rates_lock);
for (int i = 0; i < count; i++) droiddeck_refresh_v1_send_rate(r, (uint32_t)rates[i]);
droiddeck_refresh_v1_send_done(r);
}
static void refresh_notify_rates(void) {
struct wl_resource *r;
wl_resource_for_each(r, &g_refresh_clients) refresh_send_rates(r);
}
static void refresh_resource_destroy(struct wl_resource *r) {
wl_list_remove(wl_resource_get_link(r));
if (g_refresh_target_owner != r) return;
g_refresh_target_owner = NULL;
droiddeck_on_refresh_target(0, 0);
}
static void refresh_destroy_req(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static void refresh_set_target(struct wl_client *c, struct wl_resource *r, uint32_t refresh, uint32_t frame_rate) {
if (!refresh && !frame_rate && g_refresh_target_owner && g_refresh_target_owner != r) return;
g_refresh_target_owner = refresh || frame_rate ? r : NULL;
droiddeck_on_refresh_target((int)refresh, (int)frame_rate);
}
static const struct droiddeck_refresh_v1_interface refresh_impl = {
.destroy = refresh_destroy_req,
.set_target = refresh_set_target,
};
static void bind_refresh(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
struct wl_resource *r = wl_resource_create(c, &droiddeck_refresh_v1_interface, ver, id);
if (!r) { wl_client_post_no_memory(c); return; }
wl_resource_set_implementation(r, &refresh_impl, NULL, refresh_resource_destroy);
wl_list_insert(&g_refresh_clients, wl_resource_get_link(r));
refresh_send_rates(r);
}
static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
struct wl_resource *r = wl_resource_create(c, &wl_output_interface, ver, id);
if (!r) { wl_client_post_no_memory(c); return; }
@@ -1950,19 +2127,47 @@ static int on_frame_timer(void *data) {
return 0;
}
static int black_fill_below(const struct draw_list *dl, int n) {
for (int i = 0; i < n; i++) {
struct surface *s, *found = NULL;
wl_list_for_each(s, &g_surfaces, link)
if (s->shm_img == dl->d[i].img) { found = s; break; }
if (!found || !found->black_fill || dl->d[i].blend) return 0;
}
return 1;
}
static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) {
for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) {
const struct vkp_draw *d = &dl->d[i];
if (d->blend) continue;
if (!vkp_image_is_dmabuf(d->img)) continue;
if (d->dx != 0 || d->dy != 0 || d->dw != scene_w || d->dh != scene_h) continue;
if (d->sx != 0 || d->sy != 0 || (int)d->sw != vkp_image_width(d->img) ||
(int)d->sh != vkp_image_height(d->img)) continue;
if (d->sx < 0 || d->sy < 0 || d->sw < 1.0f || d->sh < 1.0f ||
d->sx + d->sw >= vkp_image_width(d->img) + 1.0f ||
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) continue;
if (d->dx == 0 && d->dy == 0 && d->dw == scene_w && d->dh == scene_h) return i;
if (d->dx < 0 || d->dy < 0 || d->dw <= 0 || d->dh <= 0 || d->dx + d->dw > scene_w ||
d->dy + d->dh > scene_h || !black_fill_below(dl, i)) continue;
return i;
}
return -1;
}
static void note_copy_scene(const struct draw_list *dl, int scene_w, int scene_h, int pointer) {
static int said[6];
const struct vkp_draw *t = dl->n > 0 ? &dl->d[dl->n - 1] : NULL;
const int now[6] = {dl->n, pointer, t ? t->dw : 0, t ? t->dh : 0, scene_w, scene_h};
if (!memcmp(now, said, sizeof(said))) return;
memcpy(said, now, sizeof(said));
if (pointer)
droiddeck_log("layer", "zero-copy: copy path while the pointer is drawn into the scene");
else if (t)
droiddeck_log("layer", "zero-copy: copy path: no window fills the %dx%d scene on its own (%d surfaces, top one "
"%dx%d at %d,%d from %.2f,%.2f %.2fx%.2f of a %dx%d %s buffer%s)", scene_w, scene_h, dl->n, t->dw, t->dh,
t->dx, t->dy, t->sx, t->sy, t->sw, t->sh, vkp_image_width(t->img), vkp_image_height(t->img),
vkp_image_is_dmabuf(t->img) ? "GPU" : "memory", t->blend ? ", translucent" : "");
}
static struct surface *surface_for_image(const struct vkp_image *img) {
struct surface *s;
wl_list_for_each(s, &g_surfaces, link)
@@ -2002,17 +2207,28 @@ static struct surface *hdr_unimported_fullscreen(const struct draw_list *dl, int
}
static int is_hdr_surface(struct surface *s) {
const struct droiddeck_color *c = s ? droiddeck_color_of(s->resource) : NULL;
return c && (c->dataspace || c->convert);
}
static int is_raw_hdr_surface(struct surface *s) {
const struct droiddeck_color *c = s ? droiddeck_color_of(s->resource) : NULL;
return c && c->dataspace;
}
static int framegen_fits_layer(void) {
const int64_t rate = (int64_t)g_content_fps * (1 + vkp_framegen_extra_images()) * 1000;
return g_content_fps > 0 &&
rate * 100 <= (int64_t)atomic_load(&g_output_refresh_mhz) * (g_framegen_layer ? 108 : 104);
}
static int hdr_plan(const struct draw_list *dl, int w, int h, int fx_on, int framegen, struct hdr_scene *hs) {
memset(hs, 0, sizeof(*hs));
if (!droiddeck_color_hdr_open()) return 0;
struct surface *un = hdr_unimported_fullscreen(dl, w, h);
if (!un) {
struct surface *lo = ahb_layer_only_candidate(w, h);
if (lo && is_hdr_surface(lo)) un = lo;
if (lo && is_raw_hdr_surface(lo)) un = lo;
}
if (un && g_zero_copy) { hs->color = droiddeck_color_of(un->resource); hs->who = un; return 3; }
hs->hf.tonemap = !droiddeck_color_output();
@@ -2020,24 +2236,48 @@ static int hdr_plan(const struct draw_list *dl, int w, int h, int fx_on, int fra
for (int i = 0; i < dl->n; i++) {
struct surface *s = surface_for_image(dl->d[i].img);
if (!is_hdr_surface(s)) continue;
hs->is_hdr[i] = 1;
const struct droiddeck_color *c = droiddeck_color_of(s->resource);
if (c->convert && hs->hf.convert && (hs->hf.convert->gain != c->gain ||
memcmp(hs->hf.convert->to2020, c->to2020, sizeof(c->to2020)) != 0)) {
static int said;
if (!said) {
said = 1;
droiddeck_log("color", "two windows need different colour conversions in one frame: the upper one is "
"shown as SDR");
}
continue;
}
hs->is_hdr[i] = c->convert ? 2 : 1;
if (c->convert) hs->hf.convert = c;
hs->n_hdr++;
hs->color = droiddeck_color_of(s->resource);
hs->color = c;
hs->who = s;
}
if (!hs->n_hdr) { free(hs->is_hdr); hs->is_hdr = NULL; return 0; }
if (hs->color->convert) {
static struct droiddeck_color composed;
composed = *hs->color;
composed.dataspace = DROIDDECK_ADATASPACE_BT2020_PQ;
composed.convert = 0;
hs->color = &composed;
}
hs->hf.is_hdr = hs->is_hdr;
hs->hf.color = hs->color;
hs->hf.peak_nits = hs->color->max_cll > 0.0f ? hs->color->max_cll
: hs->color->has_st2086 ? hs->color->max_lum : 1000.0f;
if (framegen) return 2;
if (framegen) {
if (!g_zero_copy || !framegen_fits_layer()) return 2;
hs->why = "frame generation is on";
return 1;
}
int li = g_zero_copy ? layer_candidate(dl, w, h) : -1;
int over = li >= 0 ? dl->n - 1 - li : 0;
if (!hs->hf.tonemap && !fx_on && li >= 0 && hs->is_hdr[li] &&
if (!hs->hf.tonemap && !hs->hf.convert && !fx_on && li >= 0 && hs->is_hdr[li] &&
(over == 0 || (over == 1 && sc_layer_overlay_affordable())))
return 0;
hs->why = hs->hf.tonemap ? "HDR output is switched off in the drawer"
: fx_on ? "screen effects are on"
: hs->hf.convert ? "its colours are converted to BT.2020 PQ"
: !g_zero_copy ? "zero-copy presentation is off"
: (li >= 0 && hs->is_hdr[li]) ? "a window is above the game and this display cannot compose a second layer"
: "the HDR game is not one fullscreen window";
@@ -2110,8 +2350,7 @@ static void hdr_note_precedence(struct surface *hs, int fx_on, int framegen) {
static void hdr_count_copied(const struct draw_list *dl, const char *reason) {
for (int i = 0; i < dl->n; i++) {
struct surface *s = surface_for_image(dl->d[i].img);
const struct droiddeck_color *c = s ? droiddeck_color_of(s->resource) : NULL;
if (!c || !c->dataspace) continue;
if (!is_hdr_surface(s)) continue;
char name[160];
describe(s, name, sizeof(name));
droiddeck_color_frame_copied(name, reason);
@@ -2253,6 +2492,8 @@ static void render_scene(void) {
g_dirty_since_ns = 0;
}
g_dirty = 0;
if (g_rendered_tick_ns == g_tick_vsync_ns) g_tick_spare = 0;
g_scene_queues = 0;
g_rendered_tick_ns = g_tick_vsync_ns;
g_tick_held = 0;
g_hud_fresh = 0;
@@ -2314,7 +2555,13 @@ static void render_scene(void) {
static int fell_back;
vkp_apply_window_request();
sc_layer_hide_overlay();
if (sc_layer_present_hdr_scene(dl.d, dl.n, &hs.hf, w, h, hs.color) == 0) {
const int generated = framegen ? sc_layer_present_generated(dl.d, dl.n, &hs.hf, w, h, 1, hs.color) : 0;
if (framegen) g_framegen_layer = generated >= 0;
if (generated > 0 && g_framegen_layer_said != 3) {
g_framegen_layer_said = 3;
droiddeck_log("framegen", "generated frames and the composed HDR picture go on the game's display layer");
}
if (framegen ? generated >= 0 : sc_layer_present_hdr_scene(dl.d, dl.n, &hs.hf, w, h, hs.color) == 0) {
rendered = vkp_base_black(w, h) == 0;
if (fell_back) { fell_back = 0; droiddeck_log("color", "the composed picture is on the game's display layer again"); }
} else {
@@ -2340,13 +2587,16 @@ 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;
tell_overlay_planes();
const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer();
g_framegen_layer = fg_layer;
int li = (g_zero_copy && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -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; }
const int ov_blocks = (li >= 0 && over > 0 && !fx_blocks && !sc_layer_overlay_affordable());
if (ov_blocks) { li = -1; over = 0; }
const int blocked = framegen ? 1 : bfi ? 4 : (fx_blocks ? 2 : (ov_blocks ? 3 : 0));
const int blocked = (framegen && !fg_layer) ? 1 : bfi ? 4 : (fx_blocks ? 2 : (ov_blocks ? 3 : 0));
if (g_zero_copy && !cursor_on && blocked != g_zero_copy_paused) {
g_zero_copy_paused = blocked;
if (blocked == 1)
@@ -2355,14 +2605,21 @@ static void render_scene(void) {
droiddeck_log("effects", "zero-copy paused: a window above the game needs the compositor pass for the whole scene");
else if (blocked == 4)
droiddeck_log("bfi", "zero-copy paused: black frame insertion needs the compositor pass");
else if (blocked == 3)
droiddeck_log("layer", "zero-copy paused: a window above the game would need a second display layer, "
"which this display cannot compose in hardware - whole scene on the copy path");
else if (blocked == 3) {
const struct vkp_draw *top = &dl.d[dl.n - 1];
struct surface *ts = surface_for_image(top->img);
droiddeck_log("layer", "zero-copy paused: a window above the game (%dx%d at %d,%d%s, %s) would need a second "
"display layer, which this display cannot compose in hardware - whole scene on the copy path",
top->dw, top->dh, top->dx, top->dy, top->blend ? ", translucent" : "",
ts ? client_name(wl_resource_get_client(ts->resource)) : "no client surface");
}
else
droiddeck_log("effects", "zero-copy resumed: the game is back on its own display layer");
}
struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL;
const struct vkp_draw *ld = li >= 0 ? &dl.d[li] : NULL;
if (li < 0) ls = layer_only;
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) note_copy_scene(&dl, w, h, cursor_on);
if (cardboard) ls = NULL;
if (cursor_on) ls = NULL;
if (bfi) ls = NULL;
@@ -2375,11 +2632,23 @@ static void render_scene(void) {
if (li >= 0 || ls) {
vkp_apply_window_request();
int r = -1;
if (!(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf))
r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h);
if (r != 0 && li >= 0)
const int fg_pass = framegen && fx_on && li >= 0;
const int generated = (framegen && li >= 0)
? sc_layer_present_generated(&dl.d[li], 1, NULL, w, h, fg_pass,
ls ? droiddeck_surface_color(ls) : NULL) : 0;
if (generated > 0 && g_framegen_layer_said != 1 + fg_pass) {
g_framegen_layer_said = 1 + fg_pass;
droiddeck_log("framegen", fg_pass
? "generated frames and the game's frames go on the game's display layer straight from the screen effects pass"
: "generated frames go on the game's display layer between the game's own frames");
}
if (fg_pass)
r = generated >= 0 ? 0 : -1;
else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf))
r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld);
if (!fg_pass && generated >= 0 && r != 0 && li >= 0)
r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h)
: sc_layer_present(dl.d[li].img, w, h, ls ? droiddeck_surface_color(ls) : NULL);
: sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL);
if (r == 0) {
if (ls) ls->drawn = 1;
int go[8], ov = 0;
@@ -2393,8 +2662,10 @@ static void render_scene(void) {
hdr_copy = "the overlay layer refused the window above it";
} else {
rendered = vkp_base_black(w, h) == 0;
g_scene_queues = sc_layer_queues();
}
} else {
sc_layer_hide();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
copy = 1;
hdr_copy = "its display layer was unavailable this frame";
@@ -2454,8 +2725,12 @@ static int commit_renders_on(void) {
!g_bfi_running;
}
static int tick_takes_scene(void) {
return g_rendered_tick_ns != g_tick_vsync_ns || (g_tick_spare && g_scene_queues);
}
static int render_on_commit(void) {
return commit_renders_on() && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns;
return commit_renders_on() && !g_render_idle && tick_takes_scene();
}
static void schedule_render(void) {
@@ -2482,7 +2757,7 @@ static int scene_waits_for_game(int64_t now) {
static void on_commit_idle(void *data) {
g_render_idle = NULL;
if (!g_dirty || !commit_renders_on() || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return;
if (!g_dirty || !commit_renders_on() || !tick_takes_scene() || scene_waits_for_game(now_ns())) return;
g_pace.commit_renders++;
render_scene();
}
@@ -2557,6 +2832,7 @@ static void on_vsync(int64_t frame_time_ns) {
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
}
g_last_vsync_ns = now;
g_tick_spare = g_rendered_tick_ns != g_tick_vsync_ns;
g_tick_vsync_ns = frame_time_ns;
int tick_change = 0;
if (vkp_apply_window_request()) tick_change = 1;
@@ -3779,6 +4055,10 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
output_notify_mode();
wl_display_flush_clients(g_display);
}
if (atomic_exchange(&g_panel_rates_pending, 0)) {
refresh_notify_rates();
wl_display_flush_clients(g_display);
}
if (vsync) on_vsync(vsync_ns);
return 0;
}
@@ -3828,6 +4108,23 @@ void droiddeck_wayland_output_resized(void) {
(void)n;
}
void droiddeck_wayland_set_panel_rates(const int *rates, int count) {
if (count > PANEL_RATES_MAX) count = PANEL_RATES_MAX;
pthread_mutex_lock(&g_panel_rates_lock);
const int same = count == g_panel_rate_count && !memcmp(rates, g_panel_rates, (size_t)count * sizeof(int));
if (!same) {
memcpy(g_panel_rates, rates, (size_t)count * sizeof(int));
g_panel_rate_count = count;
}
pthread_mutex_unlock(&g_panel_rates_lock);
if (same || g_input_pipe[1] < 0) return;
atomic_store(&g_panel_rates_pending, 1);
struct input_msg m = { 10, 0, 0, 0, 0 };
ssize_t n;
do { n = write(g_input_pipe[1], &m, sizeof(m)); } while (n < 0 && errno == EINTR);
(void)n;
}
void droiddeck_wayland_set_output_refresh_rate(int mhz) {
if (mhz <= 0) mhz = 60000;
if (atomic_exchange(&g_output_refresh_mhz, mhz) == mhz || g_input_pipe[1] < 0) return;
@@ -3910,12 +4207,15 @@ static int on_stats_timer(void *data) {
struct vkp_perf vp;
vkp_perf_take(&vp);
const unsigned drops = sc_layer_drops_take();
unsigned aimed_next, aimed_later, aimed_even;
sc_layer_aim_take(&aimed_next, &aimed_later, &aimed_even);
#define PERF_MS(sum, n) ((n) ? (double)(sum) / 1e6 / (double)(n) : 0.0)
if (g_perf.scenes || vp.presents || g_perf.releases || drops)
droiddeck_log("perf", "last 10 s: %u ticks, %u scenes, %u on screen (copy %u, zero-copy %u, layer copy %u) | "
"render_scene %.2f/%.2f ms | base %u black kept, %u presented | acquire %.2f/%.2f ms | "
"present %.2f/%.2f ms (%u) | fence wait %.2f/%.2f ms (%u, %u GPU release waits) | "
"release %.2f/%.2f ms (%u, %u held) | %u pool drops",
"release %.2f/%.2f ms (%u, %u held) | %u pool drops | layer frames timed for the next refresh %u, "
"the one after %u, held to an even step %u",
g_perf.ticks, g_perf.scenes, g_stat_frames, g_perf.copy_scenes, zero_copy, layer_frames,
PERF_MS(g_perf.scene_ns, g_perf.scenes), (double)g_perf.scene_max_ns / 1e6,
vp.base_kept, vp.base_presents,
@@ -3923,7 +4223,7 @@ static int on_stats_timer(void *data) {
PERF_MS(vp.present_ns, vp.presents), (double)vp.present_max_ns / 1e6, vp.presents,
PERF_MS(vp.wait_ns, vp.waits), (double)vp.wait_max_ns / 1e6, vp.waits, vp.gpu_release_waits,
PERF_MS(g_perf.release_ns, g_perf.releases), (double)g_perf.release_max_ns / 1e6,
g_perf.releases, g_perf.releases_held, drops);
g_perf.releases, g_perf.releases_held, drops, aimed_next, aimed_later, aimed_even);
#undef PERF_MS
memset(&g_perf, 0, sizeof(g_perf));
}
@@ -3933,12 +4233,12 @@ static int on_stats_timer(void *data) {
droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | "
"new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an "
"empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, "
"%u not drawn",
"%u not drawn | game frames arrived 1/2/3/4+ refreshes apart %u/%u/%u/%u",
g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6,
g_pace.ticks, g_pace.ticks_late_2ms,
g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6,
g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct,
g_pace.presented, g_pace.replaced, g_pace.undrawn);
g_pace.presented, g_pace.replaced, g_pace.undrawn, g_pace.gaps[0], g_pace.gaps[1], g_pace.gaps[2], g_pace.gaps[3]);
}
if (g_bfi_stats.lit || g_bfi_stats.dark || g_bfi_stats.failed) {
droiddeck_log("bfi", "last 10 s: %u pictures, %u black refreshes, %u black refreshes not presented",
@@ -3964,6 +4264,12 @@ static int on_stats_timer(void *data) {
"draw - expect a black picture (main device %u:%u)", ci->name,
(unsigned)major(g_main_device), (unsigned)minor(g_main_device));
}
if (g_content_fps > 0 && now_ns() - g_game_frame_ns >= 2000000000LL) {
g_content_fps = 0;
g_cadence_ns = 0;
g_cadence_frames = 0;
droiddeck_on_content_rate(0);
}
wl_event_source_timer_update(g_stats_timer, 10000);
return 0;
}
@@ -4042,6 +4348,7 @@ int droiddeck_wayland_run(void) {
wl_list_init(&g_surfaces);
wl_list_init(&g_toplevels);
wl_list_init(&g_outputs);
wl_list_init(&g_refresh_clients);
wl_list_init(&g_constraints);
wl_list_init(&g_relative_pointers);
open_session_log();
@@ -4079,16 +4386,18 @@ int droiddeck_wayland_run(void) {
wl_display_init_shm(display);
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
wl_global_create(display, &droiddeck_refresh_v1_interface, 1, NULL, bind_refresh);
wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base);
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);
droiddeck_ext_init(display);
ahb_swapchain_init(display);
display_buffers_init(display);
droiddeck_color_init(display);
@@ -20,6 +20,7 @@
#define DRM_XBGR8888 FOURCC('X', 'B', '2', '4')
#define MOD_LINEAR VKP_MOD_LINEAR
#define MOD_INVALID VKP_MOD_INVALID
#define MOD_QCOM_COMPRESSED VKP_MOD_QCOM_COMPRESSED
#define MAX_PLANES 4
struct dmabuf_params {
@@ -0,0 +1,343 @@
#define _GNU_SOURCE
#include "display_buffers.h"
#include "ahb_swapchain.h"
#include "compositor_internal.h"
#include "droiddeck_color.h"
#include "droiddeck_ext.h"
#include "sc_layer.h"
#include <android/hardware_buffer.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
#define DISPLAY_BUFFERS_SOCKET "droiddeck-display-buffers"
#define DISPLAY_BUFFERS_MAGIC 0x42444444u
#define DISPLAY_BUFFERS_VERSION 1u
#define DISPLAY_BUFFERS_ALLOC 1u
#define DISPLAY_BUFFERS_FREE 2u
#define DISPLAY_BUFFERS_MAX_SIDE 16384u
#define DISPLAY_BUFFERS_MAX_PER_CLIENT 256
#define DISPLAY_BUFFERS_PROBE_W 1280u
#define DISPLAY_BUFFERS_PROBE_H 720u
#define ALIGN_UP(v, a) (((v) + (a) - 1) / (a) * (a))
extern volatile int g_zero_copy;
volatile int g_display_buffer_driver;
struct display_buffers_request {
uint32_t magic, version, op, width, height, format, stride, offset;
uint64_t size, id, modifier;
};
struct display_buffers_reply {
uint32_t magic, status;
uint64_t id, size;
};
struct peer {
int fd;
pid_t pid;
int count;
int logged_w, logged_h;
uint32_t logged_format;
struct wl_event_source *src;
};
struct entry {
uint64_t id;
dev_t dev;
ino_t ino;
AHardwareBuffer *ahb;
uint32_t format, stride, width, height;
uint64_t modifier;
struct peer *peer;
struct wl_list link;
};
static struct wl_list g_entries;
static struct wl_event_loop *g_loop;
static uint64_t g_next_id = 1;
static int g_refused_logged;
static int g_ubwc_promised;
static int g_ubwc_probed[2];
static uint32_t ahb_format_of(uint32_t drm, uint64_t modifier) {
switch (drm) {
case DRM_ABGR8888: case DRM_XBGR8888: return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
case DRM_ARGB8888: case DRM_XRGB8888: return modifier == MOD_QCOM_COMPRESSED ? AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM : 0;
case FOURCC('A', 'B', '3', '0'): case FOURCC('X', 'B', '3', '0'): return AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
default: return 0;
}
}
static uint64_t ubwc_meta_size(uint32_t w, uint32_t h) {
return ALIGN_UP((uint64_t)ALIGN_UP((w + 15) / 16, 64) * ALIGN_UP((h + 3) / 4, 16), 4096);
}
static uint64_t ubwc_size(uint32_t w, uint32_t h, uint32_t stride) {
return ubwc_meta_size(w, h) + ALIGN_UP((uint64_t)stride * ALIGN_UP(h, 16), 4096);
}
static void entry_free(struct entry *e) {
wl_list_remove(&e->link);
e->peer->count--;
AHardwareBuffer_release(e->ahb);
free(e);
}
static AHardwareBuffer *allocate_ubwc(uint32_t w, uint32_t h, uint32_t format, uint32_t stride, int *fd, uint64_t *size) {
const uint64_t tiers[2] = {SC_LAYER_AHB_USAGE_VENDOR_UBWC, 0};
for (int i = 0; i < 2; i++) {
AHardwareBuffer_Desc d = {
.width = w, .height = h, .layers = 1, .format = format,
.usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | tiers[i]};
AHardwareBuffer *ahb = NULL;
if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) continue;
AHardwareBuffer_Desc got;
AHardwareBuffer_describe(ahb, &got);
const uint64_t need = ubwc_size(w, h, got.stride * 4);
*fd = !stride || (uint64_t)got.stride * 4 == stride ? sc_layer_ahb_fd(ahb, need) : -1;
if (*fd >= 0 && (uint64_t)lseek(*fd, 0, SEEK_END) == need) { *size = need; return ahb; }
*fd = -1;
AHardwareBuffer_release(ahb);
}
return NULL;
}
static uint64_t gralloc_bytes(uint32_t format, uint64_t usage, uint32_t *stride) {
AHardwareBuffer_Desc d = {
.width = DISPLAY_BUFFERS_PROBE_W, .height = DISPLAY_BUFFERS_PROBE_H, .layers = 1, .format = format,
.usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | usage};
AHardwareBuffer *ahb = NULL;
if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) return 0;
AHardwareBuffer_describe(ahb, &d);
const int fd = sc_layer_ahb_fd(ahb, 1);
const off_t bytes = fd >= 0 ? lseek(fd, 0, SEEK_END) : 0;
if (fd >= 0) lseek(fd, 0, SEEK_SET);
AHardwareBuffer_release(ahb);
*stride = d.stride;
return bytes > 0 ? (uint64_t)bytes : 0;
}
static int ubwc_probe(uint32_t format) {
int *state = &g_ubwc_probed[format == AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM ? 0 : 1];
if (*state) return *state > 0;
uint32_t stride = 0, linear_stride = 0;
const uint64_t flagged = gralloc_bytes(format, SC_LAYER_AHB_USAGE_VENDOR_UBWC, &stride);
const uint64_t plain = gralloc_bytes(format, 0, &stride);
const uint64_t linear = gralloc_bytes(format, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, &linear_stride);
const uint64_t need = ubwc_size(DISPLAY_BUFFERS_PROBE_W, DISPLAY_BUFFERS_PROBE_H, stride * 4);
*state = stride && linear != need && (flagged == need || plain == need) ? 1 : -1;
droiddeck_log("layer", "display buffers: gralloc %s buffers %s (%ux%u: the layout takes %llu bytes; gralloc gives %llu "
"asked for UBWC, %llu unasked, %llu linear)", droiddeck_ahb_format_name(format),
*state > 0 ? "use the UBWC layout the drivers render to: compressed frames can go on the display layer"
: "do not match the UBWC layout the drivers render to: compressed frames are not offered",
DISPLAY_BUFFERS_PROBE_W, DISPLAY_BUFFERS_PROBE_H, (unsigned long long)need, (unsigned long long)flagged,
(unsigned long long)plain, (unsigned long long)linear);
return *state > 0;
}
int display_buffers_offer_ubwc(uint32_t drm) {
const uint32_t format = ahb_format_of(drm, MOD_QCOM_COMPRESSED);
if (!g_loop || !g_zero_copy || !g_ubwc || !g_display_buffer_driver || !format || !ubwc_probe(format)) return 0;
g_ubwc_promised = 1;
return 1;
}
void display_buffers_withdraw_ubwc(void) { g_ubwc_promised = 0; }
static AHardwareBuffer *allocate(const struct display_buffers_request *q, uint32_t format, int *fd) {
const uint32_t rows = (uint32_t)((q->size + q->stride - 1) / q->stride);
const uint32_t dims[2][2] = {{q->width, q->height}, {q->stride / 4, rows}};
for (int i = 0; i < 2; i++) {
AHardwareBuffer_Desc d = {
.width = dims[i][0], .height = dims[i][1], .layers = 1, .format = format,
.usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | AHARDWAREBUFFER_USAGE_CPU_READ_RARELY};
AHardwareBuffer *ahb = NULL;
if (i && dims[1][0] == dims[0][0] && dims[1][1] == dims[0][1]) break;
if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) continue;
AHardwareBuffer_Desc got;
AHardwareBuffer_describe(ahb, &got);
*fd = (uint64_t)got.stride * 4 == q->stride ? sc_layer_ahb_fd(ahb, q->size) : -1;
if (*fd >= 0) return ahb;
AHardwareBuffer_release(ahb);
}
return NULL;
}
static int reply(struct peer *p, const struct display_buffers_reply *r, int fd) {
char control[CMSG_SPACE(sizeof(int))] = {0};
struct iovec iov = {.iov_base = (void *)r, .iov_len = sizeof(*r)};
struct msghdr msg = {.msg_iov = &iov, .msg_iovlen = 1};
if (fd >= 0) {
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
struct cmsghdr *c = CMSG_FIRSTHDR(&msg);
c->cmsg_level = SOL_SOCKET;
c->cmsg_type = SCM_RIGHTS;
c->cmsg_len = CMSG_LEN(sizeof(int));
memcpy(CMSG_DATA(c), &fd, sizeof(int));
}
ssize_t n;
do { n = sendmsg(p->fd, &msg, MSG_NOSIGNAL); } while (n < 0 && errno == EINTR);
return n == (ssize_t)sizeof(*r) ? 0 : -1;
}
static void handle_alloc(struct peer *p, const struct display_buffers_request *q) {
struct display_buffers_reply r = {.magic = DISPLAY_BUFFERS_MAGIC, .status = 1};
const int compressed = q->modifier == MOD_QCOM_COMPRESSED;
const uint32_t format = compressed || q->modifier == MOD_LINEAR ? ahb_format_of(q->format, q->modifier) : 0;
struct entry *e = NULL;
AHardwareBuffer *ahb = NULL;
struct stat st;
uint64_t need = 0;
int fd = -1;
const int sized = format && q->width && q->height && q->width <= DISPLAY_BUFFERS_MAX_SIDE &&
q->height <= DISPLAY_BUFFERS_MAX_SIDE && q->stride % 4 == 0 && q->stride / 4 >= q->width &&
q->stride / 4 <= DISPLAY_BUFFERS_MAX_SIDE;
const int sane = !sized ? 0
: compressed ? q->offset == ubwc_meta_size(q->width, q->height) &&
q->size == ubwc_size(q->width, q->height, q->stride)
: q->offset == 0 && q->size >= (uint64_t)q->stride * q->height &&
q->size <= (uint64_t)q->stride * DISPLAY_BUFFERS_MAX_SIDE;
const int wanted = compressed ? g_ubwc_promised : g_zero_copy;
if (sane && wanted && ahb_swapchain_advertised() && p->count < DISPLAY_BUFFERS_MAX_PER_CLIENT)
ahb = compressed ? allocate_ubwc(q->width, q->height, format, q->stride, &fd, &need) : allocate(q, format, &fd);
if (ahb && fstat(fd, &st) == 0) e = calloc(1, sizeof(*e));
if (e) {
e->id = r.id = g_next_id++;
e->dev = st.st_dev; e->ino = st.st_ino;
e->ahb = ahb;
e->format = format; e->stride = q->stride;
e->width = q->width; e->height = q->height;
e->modifier = q->modifier;
e->peer = p;
p->count++;
wl_list_insert(&g_entries, &e->link);
r.status = 0;
r.size = (uint64_t)lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
if (p->logged_w != (int)q->width || p->logged_h != (int)q->height || p->logged_format != q->format) {
AHardwareBuffer_Desc got;
AHardwareBuffer_describe(ahb, &got);
p->logged_w = (int)q->width; p->logged_h = (int)q->height; p->logged_format = q->format;
droiddeck_log("layer", "display buffers: pid %d renders %ux%u %c%c%c%c %s straight into gralloc buffers "
"(%s %ux%u, stride %u px, %llu bytes for the %llu it asked for)", (int)p->pid, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", droiddeck_ahb_format_name(format), got.width, got.height,
got.stride, (unsigned long long)r.size, (unsigned long long)q->size);
}
} else {
if (ahb) AHardwareBuffer_release(ahb);
fd = -1;
if (sized && wanted && (compressed || !g_refused_logged)) {
g_refused_logged = 1;
droiddeck_log(compressed ? "error" : "layer", "display buffers: no gralloc buffer matches pid %d's %ux%u "
"%c%c%c%c %s layout (stride %u bytes, pixels at %u, %llu bytes; gralloc's layout has pixels at "
"%llu, %llu bytes): %s", (int)p->pid, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", q->stride, q->offset, (unsigned long long)q->size,
(unsigned long long)(compressed ? ubwc_meta_size(q->width, q->height) : 0),
(unsigned long long)(compressed ? ubwc_size(q->width, q->height, q->stride) : q->size),
compressed ? "its compressed frames cannot be shown" : "its frames keep the copy path");
}
}
if (reply(p, &r, fd) != 0 && e) entry_free(e);
}
static void peer_gone(struct peer *p) {
struct entry *e, *tmp;
wl_list_for_each_safe(e, tmp, &g_entries, link)
if (e->peer == p) entry_free(e);
wl_event_source_remove(p->src);
close(p->fd);
free(p);
}
static int on_peer(int fd, uint32_t mask, void *data) {
struct peer *p = data;
for (;;) {
struct display_buffers_request q;
ssize_t n = recv(fd, &q, sizeof(q), MSG_DONTWAIT);
if (n < 0 && errno == EINTR) continue;
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return 0;
if (n != (ssize_t)sizeof(q) || q.magic != DISPLAY_BUFFERS_MAGIC || q.version != DISPLAY_BUFFERS_VERSION) break;
if (q.op == DISPLAY_BUFFERS_ALLOC) {
handle_alloc(p, &q);
} else if (q.op == DISPLAY_BUFFERS_FREE) {
struct entry *e, *tmp;
wl_list_for_each_safe(e, tmp, &g_entries, link)
if (e->peer == p && e->id == q.id) entry_free(e);
} else {
break;
}
}
peer_gone(p);
return 0;
}
static int on_listen(int fd, uint32_t mask, void *data) {
int c = accept4(fd, NULL, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK);
if (c < 0) return 0;
struct peer *p = calloc(1, sizeof(*p));
if (!p) { close(c); return 0; }
struct ucred cred = {0};
socklen_t len = sizeof(cred);
if (getsockopt(c, SOL_SOCKET, SO_PEERCRED, &cred, &len) == 0) p->pid = cred.pid;
p->fd = c;
p->src = wl_event_loop_add_fd(g_loop, c, WL_EVENT_READABLE, on_peer, p);
if (!p->src) { close(c); free(p); }
return 0;
}
void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b) {
struct stat st;
struct entry *e;
if (!g_loop || wl_list_empty(&g_entries) || b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) return;
wl_list_for_each(e, &g_entries, link) {
if (e->dev != st.st_dev || e->ino != st.st_ino) continue;
AHardwareBuffer_Desc d;
AHardwareBuffer_describe(e->ahb, &d);
const int compressed = e->modifier == MOD_QCOM_COMPRESSED;
const int laid_out = compressed ? b->modifier == MOD_QCOM_COMPRESSED && (uint32_t)b->width == e->width &&
(uint32_t)b->height == e->height
: (b->modifier == MOD_LINEAR || b->modifier == MOD_INVALID) &&
e->stride == b->stride[0];
if (laid_out && e->format == ahb_format_of(b->format, e->modifier) && b->width > 0 && b->height > 0 &&
(uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height)
ahb_swapchain_adopt(c, buffer, b, e->ahb, e->modifier);
return;
}
}
void display_buffers_init(struct wl_display *display) {
wl_list_init(&g_entries);
const char *dir = getenv("XDG_RUNTIME_DIR");
struct sockaddr_un addr = {.sun_family = AF_UNIX};
if (!ahb_swapchain_advertised() || !dir) return;
if (snprintf(addr.sun_path, sizeof(addr.sun_path), "%s/" DISPLAY_BUFFERS_SOCKET, dir) >= (int)sizeof(addr.sun_path)) {
droiddeck_log("layer", "display buffers: %s is too long for a socket path, not offered", dir);
return;
}
int fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
if (fd < 0) return;
unlink(addr.sun_path);
struct wl_event_loop *loop = wl_display_get_event_loop(display);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(fd, 16) != 0 ||
!wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE, on_listen, NULL)) {
droiddeck_log("layer", "display buffers: socket %s failed (%s), not offered", addr.sun_path, strerror(errno));
close(fd);
return;
}
g_loop = loop;
droiddeck_log("layer", "display buffers: offered on %s (programs whose driver asks render into gralloc buffers while "
"zero-copy is on)", addr.sun_path);
}
@@ -0,0 +1,12 @@
#ifndef DISPLAY_BUFFERS_H
#define DISPLAY_BUFFERS_H
#include <wayland-server.h>
struct dmabuf_buffer;
void display_buffers_init(struct wl_display *display);
int display_buffers_offer_ubwc(uint32_t drm);
void display_buffers_withdraw_ubwc(void);
void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b);
#endif
@@ -16,6 +16,9 @@ struct droiddeck_color {
float max_lum, min_lum;
int has_cta861;
float max_cll, max_fall;
int convert;
float to2020[9];
float gain;
char text[256];
};
@@ -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
+11 -2
View File
@@ -12,7 +12,7 @@
#define MIXED_FORMAT VK_FORMAT_A2B10G10R10_UNORM_PACK32
struct pc_encode { float ndc[4]; float params[4]; float rects[HDRC_MAX_RECTS][4]; };
struct pc_encode { float ndc[4]; float params[4]; uint32_t rects[HDRC_MAX_RECTS][2]; float conv[3][4]; };
static VkDevice g_dev;
static int g_ready;
@@ -266,7 +266,16 @@ int hdrc_encode(VkCommandBuffer cmd, VkImage mixed, VkImage out, VkFormat out_fm
pc.params[1] = p->peak_nits > 0.0f ? p->peak_nits : 1000.0f;
pc.params[2] = p->mode == HDRC_OUT_SDR ? 1.0f : 0.0f;
pc.params[3] = (float)count + 16.0f * (float)mask;
for (int i = 0; i < count; i++) memcpy(pc.rects[i], p->rects[i], sizeof(pc.rects[i]));
for (int i = 0; i < count; i++) {
uint32_t v[4];
for (int k = 0; k < 4; k++) v[k] = p->rects[i][k] <= 0.0f ? 0u : p->rects[i][k] >= 65535.0f ? 65535u : (uint32_t)p->rects[i][k];
pc.rects[i][0] = v[0] | v[1] << 16;
pc.rects[i][1] = v[2] | v[3] << 16;
}
for (int k = 0; k < 3; k++) memcpy(pc.conv[k], &p->conv[3 * k], 3 * sizeof(float));
pc.conv[0][3] = (float)(p->conv_mask & mask);
pc.conv[1][3] = p->conv_linear ? 1.0f : 0.0f;
pc.conv[2][3] = p->conv_gain;
VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_out[slot].rp,
.framebuffer = fb, .renderArea = {{0, 0}, {(uint32_t)w, (uint32_t)h}}};
@@ -14,6 +14,10 @@ struct hdrc_params {
int count;
unsigned hdr_mask;
float rects[HDRC_MAX_RECTS][4];
unsigned conv_mask;
int conv_linear;
float conv_gain;
float conv[9];
};
void hdrc_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops);
@@ -6,7 +6,8 @@ layout(binding = 0) uniform sampler2D Mixed;
layout(push_constant) uniform PC {
vec4 ndc;
vec4 params;
vec4 rects[6];
uvec2 rects[6];
vec4 conv[3];
} pc;
layout(location = 0) in vec2 fragTexCoord;
@@ -55,28 +56,38 @@ float toneCurve(float x, float peak) {
return knee + (1.0 - knee) * (1.0 - exp(-(x - knee) / rate));
}
bool isHdrPixel(vec2 p) {
float packed = pc.params.w;
float count = mod(packed, 16.0);
float mask = floor(packed / 16.0);
int rectAt(vec2 p) {
float count = mod(pc.params.w, 16.0);
for (int i = 0; i < 6; i++) {
if (float(i) >= count - 0.5) break;
vec4 r = pc.rects[i];
if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w) {
float bit = mod(floor(mask / exp2(float(i))), 2.0);
return bit > 0.5;
}
uvec2 r = pc.rects[i];
vec2 lo = vec2(float(r.x & 0xFFFFu), float(r.x >> 16));
vec2 hi = vec2(float(r.y & 0xFFFFu), float(r.y >> 16));
if (p.x >= lo.x && p.y >= lo.y && p.x < hi.x && p.y < hi.y) return i;
}
return false;
return -1;
}
bool bitOf(float mask, int i) {
return i >= 0 && mod(floor(mask / exp2(float(i))), 2.0) > 0.5;
}
vec3 convertedNits(vec3 c) {
vec3 lin = pc.conv[1].w > 0.5 ? c : pqToLinear(c);
return vec3(dot(pc.conv[0].xyz, lin), dot(pc.conv[1].xyz, lin), dot(pc.conv[2].xyz, lin)) * pc.conv[2].w;
}
void main() {
vec3 c = texelFetch(Mixed, ivec2(gl_FragCoord.xy), 0).rgb;
bool hdr = isHdrPixel(gl_FragCoord.xy);
int at = rectAt(gl_FragCoord.xy);
bool hdr = bitOf(floor(pc.params.w / 16.0), at);
bool conv = hdr && bitOf(pc.conv[0].w, at);
float sdrWhite = max(pc.params.x, 1.0);
vec3 outc;
if (pc.params.z < 0.5) {
if (hdr) {
if (conv) {
outc = linearToPq(max(convertedNits(c), 0.0) / 10000.0);
} else if (hdr) {
outc = c;
} else {
vec3 nits = (BT709_TO_BT2020 * srgbToLinear(c)) * sdrWhite;
@@ -86,7 +97,8 @@ void main() {
if (!hdr) {
outc = c;
} else {
vec3 rel = max(BT2020_TO_BT709 * (pqToLinear(c) * 10000.0), 0.0) / sdrWhite;
vec3 nits = conv ? convertedNits(c) : pqToLinear(c) * 10000.0;
vec3 rel = max(BT2020_TO_BT709 * nits, 0.0) / sdrWhite;
float m = max(max(rel.r, rel.g), rel.b);
if (m > 1e-6) rel *= toneCurve(m, max(pc.params.y, sdrWhite) / sdrWhite) / m;
outc = linearToSrgb(clamp(rel, 0.0, 1.0));
+346 -264
View File
@@ -1,8 +1,8 @@
#pragma once
const uint32_t hdr_encode_code[] = {
0x07230203,0x00010000,0x0008000b,0x0000018e,0x00000000,0x00020011,0x00000001,0x0006000b,
0x07230203,0x00010000,0x0008000b,0x000001ff,0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
0x0008000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x0000010d,0x00000186,0x0000018d,
0x0008000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000151,0x000001f7,0x000001fe,
0x00030010,0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,
0x6e69616d,0x00000000,0x00070005,0x0000000b,0x62677273,0x694c6f54,0x7261656e,0x33667628,
0x0000003b,0x00030005,0x0000000a,0x00000063,0x00070005,0x0000000e,0x656e696c,0x6f547261,
@@ -10,272 +10,354 @@ const uint32_t hdr_encode_code[] = {
0x6f547170,0x656e694c,0x76287261,0x003b3366,0x00030005,0x00000010,0x00000065,0x00060005,
0x00000014,0x656e696c,0x6f547261,0x76287150,0x003b3366,0x00030005,0x00000013,0x00000079,
0x00070005,0x0000001a,0x656e6f74,0x76727543,0x31662865,0x3b31663b,0x00000000,0x00030005,
0x00000018,0x00000078,0x00040005,0x00000019,0x6b616570,0x00000000,0x00060005,0x00000021,
0x64487369,0x78695072,0x76286c65,0x003b3266,0x00030005,0x00000020,0x00000070,0x00030005,
0x00000023,0x00006f6c,0x00030005,0x00000028,0x00006968,0x00030005,0x0000003c,0x00006f6c,
0x00030005,0x0000003f,0x00006968,0x00030005,0x00000050,0x00000070,0x00030005,0x0000006f,
0x00000070,0x00040005,0x0000008c,0x6e617073,0x00000000,0x00040005,0x00000091,0x65746172,
0x00000000,0x00040005,0x000000a2,0x6b636170,0x00006465,0x00030005,0x000000a7,0x00004350,
0x00040006,0x000000a7,0x00000000,0x0063646e,0x00050006,0x000000a7,0x00000001,0x61726170,
0x0000736d,0x00050006,0x000000a7,0x00000002,0x74636572,0x00000073,0x00030005,0x000000a9,
0x00006370,0x00040005,0x000000b0,0x6e756f63,0x00000074,0x00040005,0x000000b4,0x6b73616d,
0x00000000,0x00030005,0x000000b9,0x00000069,0x00030005,0x000000cd,0x00000072,0x00030005,
0x000000f5,0x00746962,0x00030005,0x00000106,0x00000063,0x00040005,0x0000010a,0x6578694d,
0x00000064,0x00060005,0x0000010d,0x465f6c67,0x43676172,0x64726f6f,0x00000000,0x00030005,
0x00000116,0x00726468,0x00040005,0x00000117,0x61726170,0x0000006d,0x00050005,0x0000011b,
0x57726473,0x65746968,0x00000000,0x00040005,0x00000127,0x6374756f,0x00000000,0x00040005,
0x0000012a,0x7374696e,0x00000000,0x00040005,0x00000139,0x61726170,0x0000006d,0x00040005,
0x00000143,0x61726170,0x0000006d,0x00030005,0x0000014c,0x006c6572,0x00040005,0x0000015a,
0x61726170,0x0000006d,0x00030005,0x00000164,0x0000006d,0x00040005,0x00000177,0x61726170,
0x0000006d,0x00040005,0x00000179,0x61726170,0x0000006d,0x00040005,0x00000183,0x61726170,
0x0000006d,0x00050005,0x00000186,0x4374756f,0x726f6c6f,0x00000000,0x00060005,0x0000018d,
0x67617266,0x43786554,0x64726f6f,0x00000000,0x00040047,0x000000a6,0x00000006,0x00000010,
0x00030047,0x000000a7,0x00000002,0x00050048,0x000000a7,0x00000000,0x00000023,0x00000000,
0x00050048,0x000000a7,0x00000001,0x00000023,0x00000010,0x00050048,0x000000a7,0x00000002,
0x00000023,0x00000020,0x00040047,0x0000010a,0x00000021,0x00000000,0x00040047,0x0000010a,
0x00000022,0x00000000,0x00040047,0x0000010d,0x0000000b,0x0000000f,0x00040047,0x00000186,
0x0000001e,0x00000000,0x00040047,0x0000018d,0x0000001e,0x00000000,0x00020013,0x00000002,
0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,
0x00000006,0x00000003,0x00040020,0x00000008,0x00000007,0x00000007,0x00040021,0x00000009,
0x00000007,0x00000008,0x00040020,0x00000016,0x00000007,0x00000006,0x00050021,0x00000017,
0x00000006,0x00000016,0x00000016,0x00040017,0x0000001c,0x00000006,0x00000002,0x00040020,
0x0000001d,0x00000007,0x0000001c,0x00020014,0x0000001e,0x00040021,0x0000001f,0x0000001e,
0x0000001d,0x0004002b,0x00000006,0x00000025,0x414eb852,0x0004002b,0x00000006,0x0000002a,
0x3d6147ae,0x0004002b,0x00000006,0x0000002d,0x3f870a3d,0x0004002b,0x00000006,0x00000030,
0x4019999a,0x0006002c,0x00000007,0x00000031,0x00000030,0x00000030,0x00000030,0x0004002b,
0x00000006,0x00000035,0x3d25aee6,0x0006002c,0x00000007,0x00000036,0x00000035,0x00000035,
0x00000035,0x0004002b,0x00000006,0x00000041,0x3ed55555,0x0006002c,0x00000007,0x00000042,
0x00000041,0x00000041,0x00000041,0x0004002b,0x00000006,0x00000049,0x3b4d2e1c,0x0006002c,
0x00000007,0x0000004a,0x00000049,0x00000049,0x00000049,0x0004002b,0x00000006,0x00000052,
0x00000000,0x0004002b,0x00000006,0x00000053,0x3f800000,0x0004002b,0x00000006,0x00000057,
0x3c4fcdac,0x0006002c,0x00000007,0x00000058,0x00000057,0x00000057,0x00000057,0x0004002b,
0x00000006,0x0000005b,0x3f560000,0x0004002b,0x00000006,0x00000060,0x4196d000,0x0004002b,
0x00000006,0x00000061,0x41958000,0x0004002b,0x00000006,0x00000066,0x358637bd,0x0004002b,
0x00000006,0x0000006a,0x40c8e06b,0x0006002c,0x00000007,0x0000006b,0x0000006a,0x0000006a,
0x0000006a,0x0004002b,0x00000006,0x00000074,0x3e232000,0x0006002c,0x00000007,0x00000075,
0x00000074,0x00000074,0x00000074,0x0004002b,0x00000006,0x00000080,0x429db000,0x0006002c,
0x00000007,0x00000081,0x00000080,0x00000080,0x00000080,0x0004002b,0x00000006,0x00000086,
0x3f4ccccd,0x0004002b,0x00000006,0x0000008f,0x3d4ccccd,0x0004002b,0x00000006,0x00000093,
0x407a5e35,0x0004002b,0x00000006,0x00000095,0x3e4ccccd,0x00040017,0x000000a3,0x00000006,
0x00000004,0x00040015,0x000000a4,0x00000020,0x00000000,0x0004002b,0x000000a4,0x000000a5,
0x00000006,0x0004001c,0x000000a6,0x000000a3,0x000000a5,0x0005001e,0x000000a7,0x000000a3,
0x000000a3,0x000000a6,0x00040020,0x000000a8,0x00000009,0x000000a7,0x0004003b,0x000000a8,
0x000000a9,0x00000009,0x00040015,0x000000aa,0x00000020,0x00000001,0x0004002b,0x000000aa,
0x000000ab,0x00000001,0x0004002b,0x000000a4,0x000000ac,0x00000003,0x00040020,0x000000ad,
0x00000009,0x00000006,0x0004002b,0x00000006,0x000000b2,0x41800000,0x00040020,0x000000b8,
0x00000007,0x000000aa,0x0004002b,0x000000aa,0x000000ba,0x00000000,0x0004002b,0x000000aa,
0x000000c1,0x00000006,0x0004002b,0x00000006,0x000000c6,0x3f000000,0x00040020,0x000000cc,
0x00000007,0x000000a3,0x0004002b,0x000000aa,0x000000ce,0x00000002,0x00040020,0x000000d0,
0x00000009,0x000000a3,0x0004002b,0x000000a4,0x000000d3,0x00000000,0x0004002b,0x000000a4,
0x000000db,0x00000001,0x0004002b,0x000000a4,0x000000e6,0x00000002,0x0004002b,0x00000006,
0x000000fc,0x40000000,0x0003002a,0x0000001e,0x00000103,0x00090019,0x00000107,0x00000006,
0x00000001,0x00000000,0x00000000,0x00000000,0x00000001,0x00000000,0x0003001b,0x00000108,
0x00000107,0x00040020,0x00000109,0x00000000,0x00000108,0x0004003b,0x00000109,0x0000010a,
0x00000000,0x00040020,0x0000010c,0x00000001,0x000000a3,0x0004003b,0x0000010c,0x0000010d,
0x00000001,0x00040017,0x00000110,0x000000aa,0x00000002,0x00040020,0x00000115,0x00000007,
0x0000001e,0x00040018,0x0000012b,0x00000007,0x00000003,0x0004002b,0x00000006,0x0000012c,
0x3f209d49,0x0004002b,0x00000006,0x0000012d,0x3d8d844d,0x0004002b,0x00000006,0x0000012e,
0x3c86594b,0x0006002c,0x00000007,0x0000012f,0x0000012c,0x0000012d,0x0000012e,0x0004002b,
0x00000006,0x00000130,0x3ea89a02,0x0004002b,0x00000006,0x00000131,0x3f6b645a,0x0004002b,
0x00000006,0x00000132,0x3db43958,0x0006002c,0x00000007,0x00000133,0x00000130,0x00000131,
0x00000132,0x0004002b,0x00000006,0x00000134,0x3d315b57,0x0004002b,0x00000006,0x00000135,
0x3c3ac711,0x0004002b,0x00000006,0x00000136,0x3f65460b,0x0006002c,0x00000007,0x00000137,
0x00000134,0x00000135,0x00000136,0x0006002c,0x0000012b,0x00000138,0x0000012f,0x00000133,
0x00000137,0x0004002b,0x00000006,0x00000140,0x461c4000,0x0004002b,0x00000006,0x0000014d,
0x3fd48b44,0x0004002b,0x00000006,0x0000014e,0xbdff2e49,0x0004002b,0x00000006,0x0000014f,
0xbc95182b,0x0006002c,0x00000007,0x00000150,0x0000014d,0x0000014e,0x0000014f,0x0004002b,
0x00000006,0x00000151,0xbf166cf4,0x0004002b,0x00000006,0x00000152,0x3f9102de,0x0004002b,
0x00000006,0x00000153,0xbdce075f,0x0006002c,0x00000007,0x00000154,0x00000151,0x00000152,
0x00000153,0x0004002b,0x00000006,0x00000155,0xbd95182b,0x0004002b,0x00000006,0x00000156,
0xbc07fcb9,0x0004002b,0x00000006,0x00000157,0x3f8f3190,0x0006002c,0x00000007,0x00000158,
0x00000155,0x00000156,0x00000157,0x0006002c,0x0000012b,0x00000159,0x00000150,0x00000154,
0x00000158,0x00040020,0x00000185,0x00000003,0x000000a3,0x0004003b,0x00000185,0x00000186,
0x00000003,0x00040020,0x0000018c,0x00000001,0x0000001c,0x0004003b,0x0000018c,0x0000018d,
0x00000018,0x00000078,0x00040005,0x00000019,0x6b616570,0x00000000,0x00050005,0x00000021,
0x74636572,0x76287441,0x003b3266,0x00030005,0x00000020,0x00000070,0x00060005,0x00000028,
0x4f746962,0x31662866,0x3b31693b,0x00000000,0x00040005,0x00000026,0x6b73616d,0x00000000,
0x00030005,0x00000027,0x00000069,0x00070005,0x0000002b,0x766e6f63,0x65747265,0x74694e64,
0x66762873,0x00003b33,0x00030005,0x0000002a,0x00000063,0x00030005,0x0000002d,0x00006f6c,
0x00030005,0x00000032,0x00006968,0x00030005,0x00000046,0x00006f6c,0x00030005,0x00000049,
0x00006968,0x00030005,0x0000005a,0x00000070,0x00030005,0x00000079,0x00000070,0x00040005,
0x00000096,0x6e617073,0x00000000,0x00040005,0x0000009b,0x65746172,0x00000000,0x00040005,
0x000000ac,0x6e756f63,0x00000074,0x00030005,0x000000b4,0x00004350,0x00040006,0x000000b4,
0x00000000,0x0063646e,0x00050006,0x000000b4,0x00000001,0x61726170,0x0000736d,0x00050006,
0x000000b4,0x00000002,0x74636572,0x00000073,0x00050006,0x000000b4,0x00000003,0x766e6f63,
0x00000000,0x00030005,0x000000b6,0x00006370,0x00030005,0x000000bd,0x00000069,0x00030005,
0x000000d1,0x00000072,0x00030005,0x000000d7,0x00006f6c,0x00030005,0x000000e5,0x00006968,
0x00030005,0x00000126,0x006e696c,0x00040005,0x00000130,0x61726170,0x0000006d,0x00030005,
0x0000014a,0x00000063,0x00040005,0x0000014e,0x6578694d,0x00000064,0x00060005,0x00000151,
0x465f6c67,0x43676172,0x64726f6f,0x00000000,0x00030005,0x00000159,0x00007461,0x00040005,
0x0000015a,0x61726170,0x0000006d,0x00030005,0x0000015f,0x00726468,0x00040005,0x00000164,
0x61726170,0x0000006d,0x00040005,0x00000165,0x61726170,0x0000006d,0x00040005,0x00000168,
0x766e6f63,0x00000000,0x00040005,0x0000016c,0x61726170,0x0000006d,0x00040005,0x0000016f,
0x61726170,0x0000006d,0x00050005,0x00000173,0x57726473,0x65746968,0x00000000,0x00040005,
0x00000180,0x6374756f,0x00000000,0x00040005,0x00000181,0x61726170,0x0000006d,0x00040005,
0x00000189,0x61726170,0x0000006d,0x00040005,0x00000191,0x7374696e,0x00000000,0x00040005,
0x000001a0,0x61726170,0x0000006d,0x00040005,0x000001a9,0x61726170,0x0000006d,0x00040005,
0x000001b2,0x7374696e,0x00000000,0x00040005,0x000001b7,0x61726170,0x0000006d,0x00040005,
0x000001bb,0x61726170,0x0000006d,0x00030005,0x000001c0,0x006c6572,0x00030005,0x000001d5,
0x0000006d,0x00040005,0x000001e8,0x61726170,0x0000006d,0x00040005,0x000001ea,0x61726170,
0x0000006d,0x00040005,0x000001f4,0x61726170,0x0000006d,0x00050005,0x000001f7,0x4374756f,
0x726f6c6f,0x00000000,0x00060005,0x000001fe,0x67617266,0x43786554,0x64726f6f,0x00000000,
0x00040047,0x000000b1,0x00000006,0x00000008,0x00040047,0x000000b3,0x00000006,0x00000010,
0x00030047,0x000000b4,0x00000002,0x00050048,0x000000b4,0x00000000,0x00000023,0x00000000,
0x00050048,0x000000b4,0x00000001,0x00000023,0x00000010,0x00050048,0x000000b4,0x00000002,
0x00000023,0x00000020,0x00050048,0x000000b4,0x00000003,0x00000023,0x00000050,0x00040047,
0x0000014e,0x00000021,0x00000000,0x00040047,0x0000014e,0x00000022,0x00000000,0x00040047,
0x00000151,0x0000000b,0x0000000f,0x00040047,0x000001f7,0x0000001e,0x00000000,0x00040047,
0x000001fe,0x0000001e,0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,
0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000003,0x00040020,
0x00000008,0x00000007,0x00000007,0x00040021,0x00000009,0x00000007,0x00000008,0x00040020,
0x00000016,0x00000007,0x00000006,0x00050021,0x00000017,0x00000006,0x00000016,0x00000016,
0x00040017,0x0000001c,0x00000006,0x00000002,0x00040020,0x0000001d,0x00000007,0x0000001c,
0x00040015,0x0000001e,0x00000020,0x00000001,0x00040021,0x0000001f,0x0000001e,0x0000001d,
0x00040020,0x00000023,0x00000007,0x0000001e,0x00020014,0x00000024,0x00050021,0x00000025,
0x00000024,0x00000016,0x00000023,0x0004002b,0x00000006,0x0000002f,0x414eb852,0x0004002b,
0x00000006,0x00000034,0x3d6147ae,0x0004002b,0x00000006,0x00000037,0x3f870a3d,0x0004002b,
0x00000006,0x0000003a,0x4019999a,0x0006002c,0x00000007,0x0000003b,0x0000003a,0x0000003a,
0x0000003a,0x0004002b,0x00000006,0x0000003f,0x3d25aee6,0x0006002c,0x00000007,0x00000040,
0x0000003f,0x0000003f,0x0000003f,0x0004002b,0x00000006,0x0000004b,0x3ed55555,0x0006002c,
0x00000007,0x0000004c,0x0000004b,0x0000004b,0x0000004b,0x0004002b,0x00000006,0x00000053,
0x3b4d2e1c,0x0006002c,0x00000007,0x00000054,0x00000053,0x00000053,0x00000053,0x0004002b,
0x00000006,0x0000005c,0x00000000,0x0004002b,0x00000006,0x0000005d,0x3f800000,0x0004002b,
0x00000006,0x00000061,0x3c4fcdac,0x0006002c,0x00000007,0x00000062,0x00000061,0x00000061,
0x00000061,0x0004002b,0x00000006,0x00000065,0x3f560000,0x0004002b,0x00000006,0x0000006a,
0x4196d000,0x0004002b,0x00000006,0x0000006b,0x41958000,0x0004002b,0x00000006,0x00000070,
0x358637bd,0x0004002b,0x00000006,0x00000074,0x40c8e06b,0x0006002c,0x00000007,0x00000075,
0x00000074,0x00000074,0x00000074,0x0004002b,0x00000006,0x0000007e,0x3e232000,0x0006002c,
0x00000007,0x0000007f,0x0000007e,0x0000007e,0x0000007e,0x0004002b,0x00000006,0x0000008a,
0x429db000,0x0006002c,0x00000007,0x0000008b,0x0000008a,0x0000008a,0x0000008a,0x0004002b,
0x00000006,0x00000090,0x3f4ccccd,0x0004002b,0x00000006,0x00000099,0x3d4ccccd,0x0004002b,
0x00000006,0x0000009d,0x407a5e35,0x0004002b,0x00000006,0x0000009f,0x3e4ccccd,0x00040017,
0x000000ad,0x00000006,0x00000004,0x00040015,0x000000ae,0x00000020,0x00000000,0x00040017,
0x000000af,0x000000ae,0x00000002,0x0004002b,0x000000ae,0x000000b0,0x00000006,0x0004001c,
0x000000b1,0x000000af,0x000000b0,0x0004002b,0x000000ae,0x000000b2,0x00000003,0x0004001c,
0x000000b3,0x000000ad,0x000000b2,0x0006001e,0x000000b4,0x000000ad,0x000000ad,0x000000b1,
0x000000b3,0x00040020,0x000000b5,0x00000009,0x000000b4,0x0004003b,0x000000b5,0x000000b6,
0x00000009,0x0004002b,0x0000001e,0x000000b7,0x00000001,0x00040020,0x000000b8,0x00000009,
0x00000006,0x0004002b,0x00000006,0x000000bb,0x41800000,0x0004002b,0x0000001e,0x000000be,
0x00000000,0x0004002b,0x0000001e,0x000000c5,0x00000006,0x0004002b,0x00000006,0x000000ca,
0x3f000000,0x00040020,0x000000d0,0x00000007,0x000000af,0x0004002b,0x0000001e,0x000000d2,
0x00000002,0x00040020,0x000000d4,0x00000009,0x000000af,0x0004002b,0x000000ae,0x000000d8,
0x00000000,0x00040020,0x000000d9,0x00000007,0x000000ae,0x0004002b,0x000000ae,0x000000dc,
0x0000ffff,0x0004002b,0x0000001e,0x000000e1,0x00000010,0x0004002b,0x000000ae,0x000000e6,
0x00000001,0x0004002b,0x0000001e,0x00000113,0xffffffff,0x0004002b,0x00000006,0x00000120,
0x40000000,0x0004002b,0x0000001e,0x00000127,0x00000003,0x00040020,0x00000134,0x00000009,
0x000000ad,0x00090019,0x0000014b,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,
0x00000001,0x00000000,0x0003001b,0x0000014c,0x0000014b,0x00040020,0x0000014d,0x00000000,
0x0000014c,0x0004003b,0x0000014d,0x0000014e,0x00000000,0x00040020,0x00000150,0x00000001,
0x000000ad,0x0004003b,0x00000150,0x00000151,0x00000001,0x00040017,0x00000154,0x0000001e,
0x00000002,0x00040020,0x0000015e,0x00000007,0x00000024,0x0004002b,0x000000ae,0x00000177,
0x00000002,0x0004002b,0x00000006,0x00000186,0x461c4000,0x00040018,0x00000192,0x00000007,
0x00000003,0x0004002b,0x00000006,0x00000193,0x3f209d49,0x0004002b,0x00000006,0x00000194,
0x3d8d844d,0x0004002b,0x00000006,0x00000195,0x3c86594b,0x0006002c,0x00000007,0x00000196,
0x00000193,0x00000194,0x00000195,0x0004002b,0x00000006,0x00000197,0x3ea89a02,0x0004002b,
0x00000006,0x00000198,0x3f6b645a,0x0004002b,0x00000006,0x00000199,0x3db43958,0x0006002c,
0x00000007,0x0000019a,0x00000197,0x00000198,0x00000199,0x0004002b,0x00000006,0x0000019b,
0x3d315b57,0x0004002b,0x00000006,0x0000019c,0x3c3ac711,0x0004002b,0x00000006,0x0000019d,
0x3f65460b,0x0006002c,0x00000007,0x0000019e,0x0000019b,0x0000019c,0x0000019d,0x0006002c,
0x00000192,0x0000019f,0x00000196,0x0000019a,0x0000019e,0x0004002b,0x00000006,0x000001c1,
0x3fd48b44,0x0004002b,0x00000006,0x000001c2,0xbdff2e49,0x0004002b,0x00000006,0x000001c3,
0xbc95182b,0x0006002c,0x00000007,0x000001c4,0x000001c1,0x000001c2,0x000001c3,0x0004002b,
0x00000006,0x000001c5,0xbf166cf4,0x0004002b,0x00000006,0x000001c6,0x3f9102de,0x0004002b,
0x00000006,0x000001c7,0xbdce075f,0x0006002c,0x00000007,0x000001c8,0x000001c5,0x000001c6,
0x000001c7,0x0004002b,0x00000006,0x000001c9,0xbd95182b,0x0004002b,0x00000006,0x000001ca,
0xbc07fcb9,0x0004002b,0x00000006,0x000001cb,0x3f8f3190,0x0006002c,0x00000007,0x000001cc,
0x000001c9,0x000001ca,0x000001cb,0x0006002c,0x00000192,0x000001cd,0x000001c4,0x000001c8,
0x000001cc,0x00040020,0x000001f6,0x00000003,0x000000ad,0x0004003b,0x000001f6,0x000001f7,
0x00000003,0x00040020,0x000001fd,0x00000001,0x0000001c,0x0004003b,0x000001fd,0x000001fe,
0x00000001,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,
0x0004003b,0x00000008,0x00000106,0x00000007,0x0004003b,0x00000115,0x00000116,0x00000007,
0x0004003b,0x0000001d,0x00000117,0x00000007,0x0004003b,0x00000016,0x0000011b,0x00000007,
0x0004003b,0x00000008,0x00000127,0x00000007,0x0004003b,0x00000008,0x0000012a,0x00000007,
0x0004003b,0x00000008,0x00000139,0x00000007,0x0004003b,0x00000008,0x00000143,0x00000007,
0x0004003b,0x00000008,0x0000014c,0x00000007,0x0004003b,0x00000008,0x0000015a,0x00000007,
0x0004003b,0x00000016,0x00000164,0x00000007,0x0004003b,0x00000016,0x00000177,0x00000007,
0x0004003b,0x00000016,0x00000179,0x00000007,0x0004003b,0x00000008,0x00000183,0x00000007,
0x0004003d,0x00000108,0x0000010b,0x0000010a,0x0004003d,0x000000a3,0x0000010e,0x0000010d,
0x0007004f,0x0000001c,0x0000010f,0x0000010e,0x0000010e,0x00000000,0x00000001,0x0004006e,
0x00000110,0x00000111,0x0000010f,0x00040064,0x00000107,0x00000112,0x0000010b,0x0007005f,
0x000000a3,0x00000113,0x00000112,0x00000111,0x00000002,0x000000ba,0x0008004f,0x00000007,
0x00000114,0x00000113,0x00000113,0x00000000,0x00000001,0x00000002,0x0003003e,0x00000106,
0x00000114,0x0004003d,0x000000a3,0x00000118,0x0000010d,0x0007004f,0x0000001c,0x00000119,
0x00000118,0x00000118,0x00000000,0x00000001,0x0003003e,0x00000117,0x00000119,0x00050039,
0x0000001e,0x0000011a,0x00000021,0x00000117,0x0003003e,0x00000116,0x0000011a,0x00060041,
0x000000ad,0x0000011c,0x000000a9,0x000000ab,0x000000d3,0x0004003d,0x00000006,0x0000011d,
0x0000011c,0x0007000c,0x00000006,0x0000011e,0x00000001,0x00000028,0x0000011d,0x00000053,
0x0003003e,0x0000011b,0x0000011e,0x00060041,0x000000ad,0x0000011f,0x000000a9,0x000000ab,
0x000000e6,0x0004003d,0x00000006,0x00000120,0x0000011f,0x000500b8,0x0000001e,0x00000121,
0x00000120,0x000000c6,0x000300f7,0x00000123,0x00000000,0x000400fa,0x00000121,0x00000122,
0x00000145,0x000200f8,0x00000122,0x0004003d,0x0000001e,0x00000124,0x00000116,0x000300f7,
0x00000126,0x00000000,0x000400fa,0x00000124,0x00000125,0x00000129,0x000200f8,0x00000125,
0x0004003d,0x00000007,0x00000128,0x00000106,0x0003003e,0x00000127,0x00000128,0x000200f9,
0x00000126,0x000200f8,0x00000129,0x0004003d,0x00000007,0x0000013a,0x00000106,0x0003003e,
0x00000139,0x0000013a,0x00050039,0x00000007,0x0000013b,0x0000000b,0x00000139,0x00050091,
0x00000007,0x0000013c,0x00000138,0x0000013b,0x0004003d,0x00000006,0x0000013d,0x0000011b,
0x0005008e,0x00000007,0x0000013e,0x0000013c,0x0000013d,0x0003003e,0x0000012a,0x0000013e,
0x0004003d,0x00000007,0x0000013f,0x0000012a,0x00060050,0x00000007,0x00000141,0x00000140,
0x00000140,0x00000140,0x00050088,0x00000007,0x00000142,0x0000013f,0x00000141,0x0003003e,
0x00000143,0x00000142,0x00050039,0x00000007,0x00000144,0x00000014,0x00000143,0x0003003e,
0x00000127,0x00000144,0x000200f9,0x00000126,0x000200f8,0x00000126,0x000200f9,0x00000123,
0x000200f8,0x00000145,0x0004003d,0x0000001e,0x00000146,0x00000116,0x000400a8,0x0000001e,
0x00000147,0x00000146,0x000300f7,0x00000149,0x00000000,0x000400fa,0x00000147,0x00000148,
0x0000014b,0x000200f8,0x00000148,0x0004003d,0x00000007,0x0000014a,0x00000106,0x0003003e,
0x00000127,0x0000014a,0x000200f9,0x00000149,0x000200f8,0x0000014b,0x0004003d,0x00000007,
0x0000015b,0x00000106,0x0003003e,0x0000015a,0x0000015b,0x00050039,0x00000007,0x0000015c,
0x00000011,0x0000015a,0x0005008e,0x00000007,0x0000015d,0x0000015c,0x00000140,0x00050091,
0x00000007,0x0000015e,0x00000159,0x0000015d,0x00060050,0x00000007,0x0000015f,0x00000052,
0x00000052,0x00000052,0x0007000c,0x00000007,0x00000160,0x00000001,0x00000028,0x0000015e,
0x0000015f,0x0004003d,0x00000006,0x00000161,0x0000011b,0x00060050,0x00000007,0x00000162,
0x00000161,0x00000161,0x00000161,0x00050088,0x00000007,0x00000163,0x00000160,0x00000162,
0x0003003e,0x0000014c,0x00000163,0x00050041,0x00000016,0x00000165,0x0000014c,0x000000d3,
0x0004003d,0x00000006,0x00000166,0x00000165,0x00050041,0x00000016,0x00000167,0x0000014c,
0x000000db,0x0004003d,0x00000006,0x00000168,0x00000167,0x0007000c,0x00000006,0x00000169,
0x00000001,0x00000028,0x00000166,0x00000168,0x00050041,0x00000016,0x0000016a,0x0000014c,
0x000000e6,0x0004003d,0x00000006,0x0000016b,0x0000016a,0x0007000c,0x00000006,0x0000016c,
0x00000001,0x00000028,0x00000169,0x0000016b,0x0003003e,0x00000164,0x0000016c,0x0004003d,
0x00000006,0x0000016d,0x00000164,0x000500ba,0x0000001e,0x0000016e,0x0000016d,0x00000066,
0x000300f7,0x00000170,0x00000000,0x000400fa,0x0000016e,0x0000016f,0x00000170,0x000200f8,
0x0000016f,0x00060041,0x000000ad,0x00000171,0x000000a9,0x000000ab,0x000000db,0x0004003d,
0x00000006,0x00000172,0x00000171,0x0004003d,0x00000006,0x00000173,0x0000011b,0x0007000c,
0x00000006,0x00000174,0x00000001,0x00000028,0x00000172,0x00000173,0x0004003d,0x00000006,
0x00000175,0x0000011b,0x00050088,0x00000006,0x00000176,0x00000174,0x00000175,0x0004003d,
0x00000006,0x00000178,0x00000164,0x0003003e,0x00000177,0x00000178,0x0003003e,0x00000179,
0x00000176,0x00060039,0x00000006,0x0000017a,0x0000001a,0x00000177,0x00000179,0x0004003d,
0x00000006,0x0000017b,0x00000164,0x00050088,0x00000006,0x0000017c,0x0000017a,0x0000017b,
0x0004003d,0x00000007,0x0000017d,0x0000014c,0x0005008e,0x00000007,0x0000017e,0x0000017d,
0x0000017c,0x0003003e,0x0000014c,0x0000017e,0x000200f9,0x00000170,0x000200f8,0x00000170,
0x0004003d,0x00000007,0x0000017f,0x0000014c,0x00060050,0x00000007,0x00000180,0x00000052,
0x00000052,0x00000052,0x00060050,0x00000007,0x00000181,0x00000053,0x00000053,0x00000053,
0x0008000c,0x00000007,0x00000182,0x00000001,0x0000002b,0x0000017f,0x00000180,0x00000181,
0x0003003e,0x00000183,0x00000182,0x00050039,0x00000007,0x00000184,0x0000000e,0x00000183,
0x0003003e,0x00000127,0x00000184,0x000200f9,0x00000149,0x000200f8,0x00000149,0x000200f9,
0x00000123,0x000200f8,0x00000123,0x0004003d,0x00000007,0x00000187,0x00000127,0x00050051,
0x00000006,0x00000188,0x00000187,0x00000000,0x00050051,0x00000006,0x00000189,0x00000187,
0x00000001,0x00050051,0x00000006,0x0000018a,0x00000187,0x00000002,0x00070050,0x000000a3,
0x0000018b,0x00000188,0x00000189,0x0000018a,0x00000053,0x0003003e,0x00000186,0x0000018b,
0x0004003b,0x00000008,0x0000014a,0x00000007,0x0004003b,0x00000023,0x00000159,0x00000007,
0x0004003b,0x0000001d,0x0000015a,0x00000007,0x0004003b,0x0000015e,0x0000015f,0x00000007,
0x0004003b,0x00000016,0x00000164,0x00000007,0x0004003b,0x00000023,0x00000165,0x00000007,
0x0004003b,0x0000015e,0x00000168,0x00000007,0x0004003b,0x00000016,0x0000016c,0x00000007,
0x0004003b,0x00000023,0x0000016f,0x00000007,0x0004003b,0x00000016,0x00000173,0x00000007,
0x0004003b,0x00000008,0x00000180,0x00000007,0x0004003b,0x00000008,0x00000181,0x00000007,
0x0004003b,0x00000008,0x00000189,0x00000007,0x0004003b,0x00000008,0x00000191,0x00000007,
0x0004003b,0x00000008,0x000001a0,0x00000007,0x0004003b,0x00000008,0x000001a9,0x00000007,
0x0004003b,0x00000008,0x000001b2,0x00000007,0x0004003b,0x00000008,0x000001b4,0x00000007,
0x0004003b,0x00000008,0x000001b7,0x00000007,0x0004003b,0x00000008,0x000001bb,0x00000007,
0x0004003b,0x00000008,0x000001c0,0x00000007,0x0004003b,0x00000016,0x000001d5,0x00000007,
0x0004003b,0x00000016,0x000001e8,0x00000007,0x0004003b,0x00000016,0x000001ea,0x00000007,
0x0004003b,0x00000008,0x000001f4,0x00000007,0x0004003d,0x0000014c,0x0000014f,0x0000014e,
0x0004003d,0x000000ad,0x00000152,0x00000151,0x0007004f,0x0000001c,0x00000153,0x00000152,
0x00000152,0x00000000,0x00000001,0x0004006e,0x00000154,0x00000155,0x00000153,0x00040064,
0x0000014b,0x00000156,0x0000014f,0x0007005f,0x000000ad,0x00000157,0x00000156,0x00000155,
0x00000002,0x000000be,0x0008004f,0x00000007,0x00000158,0x00000157,0x00000157,0x00000000,
0x00000001,0x00000002,0x0003003e,0x0000014a,0x00000158,0x0004003d,0x000000ad,0x0000015b,
0x00000151,0x0007004f,0x0000001c,0x0000015c,0x0000015b,0x0000015b,0x00000000,0x00000001,
0x0003003e,0x0000015a,0x0000015c,0x00050039,0x0000001e,0x0000015d,0x00000021,0x0000015a,
0x0003003e,0x00000159,0x0000015d,0x00060041,0x000000b8,0x00000160,0x000000b6,0x000000b7,
0x000000b2,0x0004003d,0x00000006,0x00000161,0x00000160,0x00050088,0x00000006,0x00000162,
0x00000161,0x000000bb,0x0006000c,0x00000006,0x00000163,0x00000001,0x00000008,0x00000162,
0x0003003e,0x00000164,0x00000163,0x0004003d,0x0000001e,0x00000166,0x00000159,0x0003003e,
0x00000165,0x00000166,0x00060039,0x00000024,0x00000167,0x00000028,0x00000164,0x00000165,
0x0003003e,0x0000015f,0x00000167,0x0004003d,0x00000024,0x00000169,0x0000015f,0x000300f7,
0x0000016b,0x00000000,0x000400fa,0x00000169,0x0000016a,0x0000016b,0x000200f8,0x0000016a,
0x00070041,0x000000b8,0x0000016d,0x000000b6,0x00000127,0x000000be,0x000000b2,0x0004003d,
0x00000006,0x0000016e,0x0000016d,0x0003003e,0x0000016c,0x0000016e,0x0004003d,0x0000001e,
0x00000170,0x00000159,0x0003003e,0x0000016f,0x00000170,0x00060039,0x00000024,0x00000171,
0x00000028,0x0000016c,0x0000016f,0x000200f9,0x0000016b,0x000200f8,0x0000016b,0x000700f5,
0x00000024,0x00000172,0x00000169,0x00000005,0x00000171,0x0000016a,0x0003003e,0x00000168,
0x00000172,0x00060041,0x000000b8,0x00000174,0x000000b6,0x000000b7,0x000000d8,0x0004003d,
0x00000006,0x00000175,0x00000174,0x0007000c,0x00000006,0x00000176,0x00000001,0x00000028,
0x00000175,0x0000005d,0x0003003e,0x00000173,0x00000176,0x00060041,0x000000b8,0x00000178,
0x000000b6,0x000000b7,0x00000177,0x0004003d,0x00000006,0x00000179,0x00000178,0x000500b8,
0x00000024,0x0000017a,0x00000179,0x000000ca,0x000300f7,0x0000017c,0x00000000,0x000400fa,
0x0000017a,0x0000017b,0x000001ab,0x000200f8,0x0000017b,0x0004003d,0x00000024,0x0000017d,
0x00000168,0x000300f7,0x0000017f,0x00000000,0x000400fa,0x0000017d,0x0000017e,0x0000018b,
0x000200f8,0x0000017e,0x0004003d,0x00000007,0x00000182,0x0000014a,0x0003003e,0x00000181,
0x00000182,0x00050039,0x00000007,0x00000183,0x0000002b,0x00000181,0x00060050,0x00000007,
0x00000184,0x0000005c,0x0000005c,0x0000005c,0x0007000c,0x00000007,0x00000185,0x00000001,
0x00000028,0x00000183,0x00000184,0x00060050,0x00000007,0x00000187,0x00000186,0x00000186,
0x00000186,0x00050088,0x00000007,0x00000188,0x00000185,0x00000187,0x0003003e,0x00000189,
0x00000188,0x00050039,0x00000007,0x0000018a,0x00000014,0x00000189,0x0003003e,0x00000180,
0x0000018a,0x000200f9,0x0000017f,0x000200f8,0x0000018b,0x0004003d,0x00000024,0x0000018c,
0x0000015f,0x000300f7,0x0000018e,0x00000000,0x000400fa,0x0000018c,0x0000018d,0x00000190,
0x000200f8,0x0000018d,0x0004003d,0x00000007,0x0000018f,0x0000014a,0x0003003e,0x00000180,
0x0000018f,0x000200f9,0x0000018e,0x000200f8,0x00000190,0x0004003d,0x00000007,0x000001a1,
0x0000014a,0x0003003e,0x000001a0,0x000001a1,0x00050039,0x00000007,0x000001a2,0x0000000b,
0x000001a0,0x00050091,0x00000007,0x000001a3,0x0000019f,0x000001a2,0x0004003d,0x00000006,
0x000001a4,0x00000173,0x0005008e,0x00000007,0x000001a5,0x000001a3,0x000001a4,0x0003003e,
0x00000191,0x000001a5,0x0004003d,0x00000007,0x000001a6,0x00000191,0x00060050,0x00000007,
0x000001a7,0x00000186,0x00000186,0x00000186,0x00050088,0x00000007,0x000001a8,0x000001a6,
0x000001a7,0x0003003e,0x000001a9,0x000001a8,0x00050039,0x00000007,0x000001aa,0x00000014,
0x000001a9,0x0003003e,0x00000180,0x000001aa,0x000200f9,0x0000018e,0x000200f8,0x0000018e,
0x000200f9,0x0000017f,0x000200f8,0x0000017f,0x000200f9,0x0000017c,0x000200f8,0x000001ab,
0x0004003d,0x00000024,0x000001ac,0x0000015f,0x000400a8,0x00000024,0x000001ad,0x000001ac,
0x000300f7,0x000001af,0x00000000,0x000400fa,0x000001ad,0x000001ae,0x000001b1,0x000200f8,
0x000001ae,0x0004003d,0x00000007,0x000001b0,0x0000014a,0x0003003e,0x00000180,0x000001b0,
0x000200f9,0x000001af,0x000200f8,0x000001b1,0x0004003d,0x00000024,0x000001b3,0x00000168,
0x000300f7,0x000001b6,0x00000000,0x000400fa,0x000001b3,0x000001b5,0x000001ba,0x000200f8,
0x000001b5,0x0004003d,0x00000007,0x000001b8,0x0000014a,0x0003003e,0x000001b7,0x000001b8,
0x00050039,0x00000007,0x000001b9,0x0000002b,0x000001b7,0x0003003e,0x000001b4,0x000001b9,
0x000200f9,0x000001b6,0x000200f8,0x000001ba,0x0004003d,0x00000007,0x000001bc,0x0000014a,
0x0003003e,0x000001bb,0x000001bc,0x00050039,0x00000007,0x000001bd,0x00000011,0x000001bb,
0x0005008e,0x00000007,0x000001be,0x000001bd,0x00000186,0x0003003e,0x000001b4,0x000001be,
0x000200f9,0x000001b6,0x000200f8,0x000001b6,0x0004003d,0x00000007,0x000001bf,0x000001b4,
0x0003003e,0x000001b2,0x000001bf,0x0004003d,0x00000007,0x000001ce,0x000001b2,0x00050091,
0x00000007,0x000001cf,0x000001cd,0x000001ce,0x00060050,0x00000007,0x000001d0,0x0000005c,
0x0000005c,0x0000005c,0x0007000c,0x00000007,0x000001d1,0x00000001,0x00000028,0x000001cf,
0x000001d0,0x0004003d,0x00000006,0x000001d2,0x00000173,0x00060050,0x00000007,0x000001d3,
0x000001d2,0x000001d2,0x000001d2,0x00050088,0x00000007,0x000001d4,0x000001d1,0x000001d3,
0x0003003e,0x000001c0,0x000001d4,0x00050041,0x00000016,0x000001d6,0x000001c0,0x000000d8,
0x0004003d,0x00000006,0x000001d7,0x000001d6,0x00050041,0x00000016,0x000001d8,0x000001c0,
0x000000e6,0x0004003d,0x00000006,0x000001d9,0x000001d8,0x0007000c,0x00000006,0x000001da,
0x00000001,0x00000028,0x000001d7,0x000001d9,0x00050041,0x00000016,0x000001db,0x000001c0,
0x00000177,0x0004003d,0x00000006,0x000001dc,0x000001db,0x0007000c,0x00000006,0x000001dd,
0x00000001,0x00000028,0x000001da,0x000001dc,0x0003003e,0x000001d5,0x000001dd,0x0004003d,
0x00000006,0x000001de,0x000001d5,0x000500ba,0x00000024,0x000001df,0x000001de,0x00000070,
0x000300f7,0x000001e1,0x00000000,0x000400fa,0x000001df,0x000001e0,0x000001e1,0x000200f8,
0x000001e0,0x00060041,0x000000b8,0x000001e2,0x000000b6,0x000000b7,0x000000e6,0x0004003d,
0x00000006,0x000001e3,0x000001e2,0x0004003d,0x00000006,0x000001e4,0x00000173,0x0007000c,
0x00000006,0x000001e5,0x00000001,0x00000028,0x000001e3,0x000001e4,0x0004003d,0x00000006,
0x000001e6,0x00000173,0x00050088,0x00000006,0x000001e7,0x000001e5,0x000001e6,0x0004003d,
0x00000006,0x000001e9,0x000001d5,0x0003003e,0x000001e8,0x000001e9,0x0003003e,0x000001ea,
0x000001e7,0x00060039,0x00000006,0x000001eb,0x0000001a,0x000001e8,0x000001ea,0x0004003d,
0x00000006,0x000001ec,0x000001d5,0x00050088,0x00000006,0x000001ed,0x000001eb,0x000001ec,
0x0004003d,0x00000007,0x000001ee,0x000001c0,0x0005008e,0x00000007,0x000001ef,0x000001ee,
0x000001ed,0x0003003e,0x000001c0,0x000001ef,0x000200f9,0x000001e1,0x000200f8,0x000001e1,
0x0004003d,0x00000007,0x000001f0,0x000001c0,0x00060050,0x00000007,0x000001f1,0x0000005c,
0x0000005c,0x0000005c,0x00060050,0x00000007,0x000001f2,0x0000005d,0x0000005d,0x0000005d,
0x0008000c,0x00000007,0x000001f3,0x00000001,0x0000002b,0x000001f0,0x000001f1,0x000001f2,
0x0003003e,0x000001f4,0x000001f3,0x00050039,0x00000007,0x000001f5,0x0000000e,0x000001f4,
0x0003003e,0x00000180,0x000001f5,0x000200f9,0x000001af,0x000200f8,0x000001af,0x000200f9,
0x0000017c,0x000200f8,0x0000017c,0x0004003d,0x00000007,0x000001f8,0x00000180,0x00050051,
0x00000006,0x000001f9,0x000001f8,0x00000000,0x00050051,0x00000006,0x000001fa,0x000001f8,
0x00000001,0x00050051,0x00000006,0x000001fb,0x000001f8,0x00000002,0x00070050,0x000000ad,
0x000001fc,0x000001f9,0x000001fa,0x000001fb,0x0000005d,0x0003003e,0x000001f7,0x000001fc,
0x000100fd,0x00010038,0x00050036,0x00000007,0x0000000b,0x00000000,0x00000009,0x00030037,
0x00000008,0x0000000a,0x000200f8,0x0000000c,0x0004003b,0x00000008,0x00000023,0x00000007,
0x0004003b,0x00000008,0x00000028,0x00000007,0x0004003d,0x00000007,0x00000024,0x0000000a,
0x00060050,0x00000007,0x00000026,0x00000025,0x00000025,0x00000025,0x00050088,0x00000007,
0x00000027,0x00000024,0x00000026,0x0003003e,0x00000023,0x00000027,0x0004003d,0x00000007,
0x00000029,0x0000000a,0x00060050,0x00000007,0x0000002b,0x0000002a,0x0000002a,0x0000002a,
0x00050081,0x00000007,0x0000002c,0x00000029,0x0000002b,0x00060050,0x00000007,0x0000002e,
0x0000002d,0x0000002d,0x0000002d,0x00050088,0x00000007,0x0000002f,0x0000002c,0x0000002e,
0x0007000c,0x00000007,0x00000032,0x00000001,0x0000001a,0x0000002f,0x00000031,0x0003003e,
0x00000028,0x00000032,0x0004003d,0x00000007,0x00000033,0x00000023,0x0004003d,0x00000007,
0x00000034,0x00000028,0x0004003d,0x00000007,0x00000037,0x0000000a,0x0007000c,0x00000007,
0x00000038,0x00000001,0x00000030,0x00000036,0x00000037,0x0008000c,0x00000007,0x00000039,
0x00000001,0x0000002e,0x00000033,0x00000034,0x00000038,0x000200fe,0x00000039,0x00010038,
0x00000008,0x0000000a,0x000200f8,0x0000000c,0x0004003b,0x00000008,0x0000002d,0x00000007,
0x0004003b,0x00000008,0x00000032,0x00000007,0x0004003d,0x00000007,0x0000002e,0x0000000a,
0x00060050,0x00000007,0x00000030,0x0000002f,0x0000002f,0x0000002f,0x00050088,0x00000007,
0x00000031,0x0000002e,0x00000030,0x0003003e,0x0000002d,0x00000031,0x0004003d,0x00000007,
0x00000033,0x0000000a,0x00060050,0x00000007,0x00000035,0x00000034,0x00000034,0x00000034,
0x00050081,0x00000007,0x00000036,0x00000033,0x00000035,0x00060050,0x00000007,0x00000038,
0x00000037,0x00000037,0x00000037,0x00050088,0x00000007,0x00000039,0x00000036,0x00000038,
0x0007000c,0x00000007,0x0000003c,0x00000001,0x0000001a,0x00000039,0x0000003b,0x0003003e,
0x00000032,0x0000003c,0x0004003d,0x00000007,0x0000003d,0x0000002d,0x0004003d,0x00000007,
0x0000003e,0x00000032,0x0004003d,0x00000007,0x00000041,0x0000000a,0x0007000c,0x00000007,
0x00000042,0x00000001,0x00000030,0x00000040,0x00000041,0x0008000c,0x00000007,0x00000043,
0x00000001,0x0000002e,0x0000003d,0x0000003e,0x00000042,0x000200fe,0x00000043,0x00010038,
0x00050036,0x00000007,0x0000000e,0x00000000,0x00000009,0x00030037,0x00000008,0x0000000d,
0x000200f8,0x0000000f,0x0004003b,0x00000008,0x0000003c,0x00000007,0x0004003b,0x00000008,
0x0000003f,0x00000007,0x0004003d,0x00000007,0x0000003d,0x0000000d,0x0005008e,0x00000007,
0x0000003e,0x0000003d,0x00000025,0x0003003e,0x0000003c,0x0000003e,0x0004003d,0x00000007,
0x00000040,0x0000000d,0x0007000c,0x00000007,0x00000043,0x00000001,0x0000001a,0x00000040,
0x00000042,0x0005008e,0x00000007,0x00000044,0x00000043,0x0000002d,0x00060050,0x00000007,
0x00000045,0x0000002a,0x0000002a,0x0000002a,0x00050083,0x00000007,0x00000046,0x00000044,
0x00000045,0x0003003e,0x0000003f,0x00000046,0x0004003d,0x00000007,0x00000047,0x0000003c,
0x0004003d,0x00000007,0x00000048,0x0000003f,0x0004003d,0x00000007,0x0000004b,0x0000000d,
0x0007000c,0x00000007,0x0000004c,0x00000001,0x00000030,0x0000004a,0x0000004b,0x0008000c,
0x00000007,0x0000004d,0x00000001,0x0000002e,0x00000047,0x00000048,0x0000004c,0x000200fe,
0x0000004d,0x00010038,0x00050036,0x00000007,0x00000011,0x00000000,0x00000009,0x00030037,
0x00000008,0x00000010,0x000200f8,0x00000012,0x0004003b,0x00000008,0x00000050,0x00000007,
0x0004003d,0x00000007,0x00000051,0x00000010,0x00060050,0x00000007,0x00000054,0x00000052,
0x00000052,0x00000052,0x00060050,0x00000007,0x00000055,0x00000053,0x00000053,0x00000053,
0x0008000c,0x00000007,0x00000056,0x00000001,0x0000002b,0x00000051,0x00000054,0x00000055,
0x0007000c,0x00000007,0x00000059,0x00000001,0x0000001a,0x00000056,0x00000058,0x0003003e,
0x00000050,0x00000059,0x0004003d,0x00000007,0x0000005a,0x00000050,0x00060050,0x00000007,
0x0000005c,0x0000005b,0x0000005b,0x0000005b,0x00050083,0x00000007,0x0000005d,0x0000005a,
0x0000005c,0x00060050,0x00000007,0x0000005e,0x00000052,0x00000052,0x00000052,0x0007000c,
0x00000007,0x0000005f,0x00000001,0x00000028,0x0000005d,0x0000005e,0x0004003d,0x00000007,
0x00000062,0x00000050,0x0005008e,0x00000007,0x00000063,0x00000062,0x00000061,0x00060050,
0x00000007,0x00000064,0x00000060,0x00000060,0x00000060,0x00050083,0x00000007,0x00000065,
0x00000064,0x00000063,0x00060050,0x00000007,0x00000067,0x00000066,0x00000066,0x00000066,
0x0007000c,0x00000007,0x00000068,0x00000001,0x00000028,0x00000065,0x00000067,0x00050088,
0x00000007,0x00000069,0x0000005f,0x00000068,0x0007000c,0x00000007,0x0000006c,0x00000001,
0x0000001a,0x00000069,0x0000006b,0x000200fe,0x0000006c,0x00010038,0x00050036,0x00000007,
0x000200f8,0x0000000f,0x0004003b,0x00000008,0x00000046,0x00000007,0x0004003b,0x00000008,
0x00000049,0x00000007,0x0004003d,0x00000007,0x00000047,0x0000000d,0x0005008e,0x00000007,
0x00000048,0x00000047,0x0000002f,0x0003003e,0x00000046,0x00000048,0x0004003d,0x00000007,
0x0000004a,0x0000000d,0x0007000c,0x00000007,0x0000004d,0x00000001,0x0000001a,0x0000004a,
0x0000004c,0x0005008e,0x00000007,0x0000004e,0x0000004d,0x00000037,0x00060050,0x00000007,
0x0000004f,0x00000034,0x00000034,0x00000034,0x00050083,0x00000007,0x00000050,0x0000004e,
0x0000004f,0x0003003e,0x00000049,0x00000050,0x0004003d,0x00000007,0x00000051,0x00000046,
0x0004003d,0x00000007,0x00000052,0x00000049,0x0004003d,0x00000007,0x00000055,0x0000000d,
0x0007000c,0x00000007,0x00000056,0x00000001,0x00000030,0x00000054,0x00000055,0x0008000c,
0x00000007,0x00000057,0x00000001,0x0000002e,0x00000051,0x00000052,0x00000056,0x000200fe,
0x00000057,0x00010038,0x00050036,0x00000007,0x00000011,0x00000000,0x00000009,0x00030037,
0x00000008,0x00000010,0x000200f8,0x00000012,0x0004003b,0x00000008,0x0000005a,0x00000007,
0x0004003d,0x00000007,0x0000005b,0x00000010,0x00060050,0x00000007,0x0000005e,0x0000005c,
0x0000005c,0x0000005c,0x00060050,0x00000007,0x0000005f,0x0000005d,0x0000005d,0x0000005d,
0x0008000c,0x00000007,0x00000060,0x00000001,0x0000002b,0x0000005b,0x0000005e,0x0000005f,
0x0007000c,0x00000007,0x00000063,0x00000001,0x0000001a,0x00000060,0x00000062,0x0003003e,
0x0000005a,0x00000063,0x0004003d,0x00000007,0x00000064,0x0000005a,0x00060050,0x00000007,
0x00000066,0x00000065,0x00000065,0x00000065,0x00050083,0x00000007,0x00000067,0x00000064,
0x00000066,0x00060050,0x00000007,0x00000068,0x0000005c,0x0000005c,0x0000005c,0x0007000c,
0x00000007,0x00000069,0x00000001,0x00000028,0x00000067,0x00000068,0x0004003d,0x00000007,
0x0000006c,0x0000005a,0x0005008e,0x00000007,0x0000006d,0x0000006c,0x0000006b,0x00060050,
0x00000007,0x0000006e,0x0000006a,0x0000006a,0x0000006a,0x00050083,0x00000007,0x0000006f,
0x0000006e,0x0000006d,0x00060050,0x00000007,0x00000071,0x00000070,0x00000070,0x00000070,
0x0007000c,0x00000007,0x00000072,0x00000001,0x00000028,0x0000006f,0x00000071,0x00050088,
0x00000007,0x00000073,0x00000069,0x00000072,0x0007000c,0x00000007,0x00000076,0x00000001,
0x0000001a,0x00000073,0x00000075,0x000200fe,0x00000076,0x00010038,0x00050036,0x00000007,
0x00000014,0x00000000,0x00000009,0x00030037,0x00000008,0x00000013,0x000200f8,0x00000015,
0x0004003b,0x00000008,0x0000006f,0x00000007,0x0004003d,0x00000007,0x00000070,0x00000013,
0x00060050,0x00000007,0x00000071,0x00000052,0x00000052,0x00000052,0x00060050,0x00000007,
0x00000072,0x00000053,0x00000053,0x00000053,0x0008000c,0x00000007,0x00000073,0x00000001,
0x0000002b,0x00000070,0x00000071,0x00000072,0x0007000c,0x00000007,0x00000076,0x00000001,
0x0000001a,0x00000073,0x00000075,0x0003003e,0x0000006f,0x00000076,0x0004003d,0x00000007,
0x00000077,0x0000006f,0x0005008e,0x00000007,0x00000078,0x00000077,0x00000060,0x00060050,
0x00000007,0x00000079,0x0000005b,0x0000005b,0x0000005b,0x00050081,0x00000007,0x0000007a,
0x00000079,0x00000078,0x0004003d,0x00000007,0x0000007b,0x0000006f,0x0005008e,0x00000007,
0x0000007c,0x0000007b,0x00000061,0x00060050,0x00000007,0x0000007d,0x00000053,0x00000053,
0x00000053,0x00050081,0x00000007,0x0000007e,0x0000007d,0x0000007c,0x00050088,0x00000007,
0x0000007f,0x0000007a,0x0000007e,0x0007000c,0x00000007,0x00000082,0x00000001,0x0000001a,
0x0000007f,0x00000081,0x000200fe,0x00000082,0x00010038,0x00050036,0x00000006,0x0000001a,
0x0004003b,0x00000008,0x00000079,0x00000007,0x0004003d,0x00000007,0x0000007a,0x00000013,
0x00060050,0x00000007,0x0000007b,0x0000005c,0x0000005c,0x0000005c,0x00060050,0x00000007,
0x0000007c,0x0000005d,0x0000005d,0x0000005d,0x0008000c,0x00000007,0x0000007d,0x00000001,
0x0000002b,0x0000007a,0x0000007b,0x0000007c,0x0007000c,0x00000007,0x00000080,0x00000001,
0x0000001a,0x0000007d,0x0000007f,0x0003003e,0x00000079,0x00000080,0x0004003d,0x00000007,
0x00000081,0x00000079,0x0005008e,0x00000007,0x00000082,0x00000081,0x0000006a,0x00060050,
0x00000007,0x00000083,0x00000065,0x00000065,0x00000065,0x00050081,0x00000007,0x00000084,
0x00000083,0x00000082,0x0004003d,0x00000007,0x00000085,0x00000079,0x0005008e,0x00000007,
0x00000086,0x00000085,0x0000006b,0x00060050,0x00000007,0x00000087,0x0000005d,0x0000005d,
0x0000005d,0x00050081,0x00000007,0x00000088,0x00000087,0x00000086,0x00050088,0x00000007,
0x00000089,0x00000084,0x00000088,0x0007000c,0x00000007,0x0000008c,0x00000001,0x0000001a,
0x00000089,0x0000008b,0x000200fe,0x0000008c,0x00010038,0x00050036,0x00000006,0x0000001a,
0x00000000,0x00000017,0x00030037,0x00000016,0x00000018,0x00030037,0x00000016,0x00000019,
0x000200f8,0x0000001b,0x0004003b,0x00000016,0x0000008c,0x00000007,0x0004003b,0x00000016,
0x00000091,0x00000007,0x0004003d,0x00000006,0x00000085,0x00000018,0x000500bc,0x0000001e,
0x00000087,0x00000085,0x00000086,0x000300f7,0x00000089,0x00000000,0x000400fa,0x00000087,
0x00000088,0x00000089,0x000200f8,0x00000088,0x0004003d,0x00000006,0x0000008a,0x00000018,
0x000200fe,0x0000008a,0x000200f8,0x00000089,0x0004003d,0x00000006,0x0000008d,0x00000019,
0x00050083,0x00000006,0x0000008e,0x0000008d,0x00000086,0x0007000c,0x00000006,0x00000090,
0x00000001,0x00000028,0x0000008e,0x0000008f,0x0003003e,0x0000008c,0x00000090,0x0004003d,
0x00000006,0x00000092,0x0000008c,0x00050088,0x00000006,0x00000094,0x00000092,0x00000093,
0x0007000c,0x00000006,0x00000096,0x00000001,0x00000028,0x00000094,0x00000095,0x0003003e,
0x00000091,0x00000096,0x0004003d,0x00000006,0x00000097,0x00000018,0x00050083,0x00000006,
0x00000098,0x00000097,0x00000086,0x0004007f,0x00000006,0x00000099,0x00000098,0x0004003d,
0x00000006,0x0000009a,0x00000091,0x00050088,0x00000006,0x0000009b,0x00000099,0x0000009a,
0x0006000c,0x00000006,0x0000009c,0x00000001,0x0000001b,0x0000009b,0x00050083,0x00000006,
0x0000009d,0x00000053,0x0000009c,0x00050085,0x00000006,0x0000009e,0x00000095,0x0000009d,
0x00050081,0x00000006,0x0000009f,0x00000086,0x0000009e,0x000200fe,0x0000009f,0x00010038,
0x000200f8,0x0000001b,0x0004003b,0x00000016,0x00000096,0x00000007,0x0004003b,0x00000016,
0x0000009b,0x00000007,0x0004003d,0x00000006,0x0000008f,0x00000018,0x000500bc,0x00000024,
0x00000091,0x0000008f,0x00000090,0x000300f7,0x00000093,0x00000000,0x000400fa,0x00000091,
0x00000092,0x00000093,0x000200f8,0x00000092,0x0004003d,0x00000006,0x00000094,0x00000018,
0x000200fe,0x00000094,0x000200f8,0x00000093,0x0004003d,0x00000006,0x00000097,0x00000019,
0x00050083,0x00000006,0x00000098,0x00000097,0x00000090,0x0007000c,0x00000006,0x0000009a,
0x00000001,0x00000028,0x00000098,0x00000099,0x0003003e,0x00000096,0x0000009a,0x0004003d,
0x00000006,0x0000009c,0x00000096,0x00050088,0x00000006,0x0000009e,0x0000009c,0x0000009d,
0x0007000c,0x00000006,0x000000a0,0x00000001,0x00000028,0x0000009e,0x0000009f,0x0003003e,
0x0000009b,0x000000a0,0x0004003d,0x00000006,0x000000a1,0x00000018,0x00050083,0x00000006,
0x000000a2,0x000000a1,0x00000090,0x0004007f,0x00000006,0x000000a3,0x000000a2,0x0004003d,
0x00000006,0x000000a4,0x0000009b,0x00050088,0x00000006,0x000000a5,0x000000a3,0x000000a4,
0x0006000c,0x00000006,0x000000a6,0x00000001,0x0000001b,0x000000a5,0x00050083,0x00000006,
0x000000a7,0x0000005d,0x000000a6,0x00050085,0x00000006,0x000000a8,0x0000009f,0x000000a7,
0x00050081,0x00000006,0x000000a9,0x00000090,0x000000a8,0x000200fe,0x000000a9,0x00010038,
0x00050036,0x0000001e,0x00000021,0x00000000,0x0000001f,0x00030037,0x0000001d,0x00000020,
0x000200f8,0x00000022,0x0004003b,0x00000016,0x000000a2,0x00000007,0x0004003b,0x00000016,
0x000000b0,0x00000007,0x0004003b,0x00000016,0x000000b4,0x00000007,0x0004003b,0x000000b8,
0x000000b9,0x00000007,0x0004003b,0x000000cc,0x000000cd,0x00000007,0x0004003b,0x00000016,
0x000000f5,0x00000007,0x00060041,0x000000ad,0x000000ae,0x000000a9,0x000000ab,0x000000ac,
0x0004003d,0x00000006,0x000000af,0x000000ae,0x0003003e,0x000000a2,0x000000af,0x0004003d,
0x00000006,0x000000b1,0x000000a2,0x0005008d,0x00000006,0x000000b3,0x000000b1,0x000000b2,
0x0003003e,0x000000b0,0x000000b3,0x0004003d,0x00000006,0x000000b5,0x000000a2,0x00050088,
0x00000006,0x000000b6,0x000000b5,0x000000b2,0x0006000c,0x00000006,0x000000b7,0x00000001,
0x00000008,0x000000b6,0x0003003e,0x000000b4,0x000000b7,0x0003003e,0x000000b9,0x000000ba,
0x000200f9,0x000000bb,0x000200f8,0x000000bb,0x000400f6,0x000000bd,0x000000be,0x00000000,
0x000200f9,0x000000bf,0x000200f8,0x000000bf,0x0004003d,0x000000aa,0x000000c0,0x000000b9,
0x000500b1,0x0000001e,0x000000c2,0x000000c0,0x000000c1,0x000400fa,0x000000c2,0x000000bc,
0x000000bd,0x000200f8,0x000000bc,0x0004003d,0x000000aa,0x000000c3,0x000000b9,0x0004006f,
0x00000006,0x000000c4,0x000000c3,0x0004003d,0x00000006,0x000000c5,0x000000b0,0x00050083,
0x00000006,0x000000c7,0x000000c5,0x000000c6,0x000500be,0x0000001e,0x000000c8,0x000000c4,
0x000000c7,0x000300f7,0x000000ca,0x00000000,0x000400fa,0x000000c8,0x000000c9,0x000000ca,
0x000200f8,0x000000c9,0x000200f9,0x000000bd,0x000200f8,0x000000ca,0x0004003d,0x000000aa,
0x000000cf,0x000000b9,0x00060041,0x000000d0,0x000000d1,0x000000a9,0x000000ce,0x000000cf,
0x0004003d,0x000000a3,0x000000d2,0x000000d1,0x0003003e,0x000000cd,0x000000d2,0x00050041,
0x00000016,0x000000d4,0x00000020,0x000000d3,0x0004003d,0x00000006,0x000000d5,0x000000d4,
0x00050041,0x00000016,0x000000d6,0x000000cd,0x000000d3,0x0004003d,0x00000006,0x000000d7,
0x000000d6,0x000500be,0x0000001e,0x000000d8,0x000000d5,0x000000d7,0x000300f7,0x000000da,
0x00000000,0x000400fa,0x000000d8,0x000000d9,0x000000da,0x000200f8,0x000000d9,0x00050041,
0x00000016,0x000000dc,0x00000020,0x000000db,0x0004003d,0x00000006,0x000000dd,0x000000dc,
0x00050041,0x00000016,0x000000de,0x000000cd,0x000000db,0x0004003d,0x00000006,0x000000df,
0x000000de,0x000500be,0x0000001e,0x000000e0,0x000000dd,0x000000df,0x000200f9,0x000000da,
0x000200f8,0x000000da,0x000700f5,0x0000001e,0x000000e1,0x000000d8,0x000000ca,0x000000e0,
0x000000d9,0x000300f7,0x000000e3,0x00000000,0x000400fa,0x000000e1,0x000000e2,0x000000e3,
0x000200f8,0x000000e2,0x00050041,0x00000016,0x000000e4,0x00000020,0x000000d3,0x0004003d,
0x00000006,0x000000e5,0x000000e4,0x00050041,0x00000016,0x000000e7,0x000000cd,0x000000e6,
0x0004003d,0x00000006,0x000000e8,0x000000e7,0x000500b8,0x0000001e,0x000000e9,0x000000e5,
0x000000e8,0x000200f9,0x000000e3,0x000200f8,0x000000e3,0x000700f5,0x0000001e,0x000000ea,
0x000000e1,0x000000da,0x000000e9,0x000000e2,0x000300f7,0x000000ec,0x00000000,0x000400fa,
0x000000ea,0x000000eb,0x000000ec,0x000200f8,0x000000eb,0x00050041,0x00000016,0x000000ed,
0x00000020,0x000000db,0x0004003d,0x00000006,0x000000ee,0x000000ed,0x00050041,0x00000016,
0x000000ef,0x000000cd,0x000000ac,0x0004003d,0x00000006,0x000000f0,0x000000ef,0x000500b8,
0x0000001e,0x000000f1,0x000000ee,0x000000f0,0x000200f9,0x000000ec,0x000200f8,0x000000ec,
0x000700f5,0x0000001e,0x000000f2,0x000000ea,0x000000e3,0x000000f1,0x000000eb,0x000300f7,
0x000000f4,0x00000000,0x000400fa,0x000000f2,0x000000f3,0x000000f4,0x000200f8,0x000000f3,
0x0004003d,0x00000006,0x000000f6,0x000000b4,0x0004003d,0x000000aa,0x000000f7,0x000000b9,
0x0004006f,0x00000006,0x000000f8,0x000000f7,0x0006000c,0x00000006,0x000000f9,0x00000001,
0x0000001d,0x000000f8,0x00050088,0x00000006,0x000000fa,0x000000f6,0x000000f9,0x0006000c,
0x00000006,0x000000fb,0x00000001,0x00000008,0x000000fa,0x0005008d,0x00000006,0x000000fd,
0x000000fb,0x000000fc,0x0003003e,0x000000f5,0x000000fd,0x0004003d,0x00000006,0x000000fe,
0x000000f5,0x000500ba,0x0000001e,0x000000ff,0x000000fe,0x000000c6,0x000200fe,0x000000ff,
0x000200f8,0x000000f4,0x000200f9,0x000000be,0x000200f8,0x000000be,0x0004003d,0x000000aa,
0x00000101,0x000000b9,0x00050080,0x000000aa,0x00000102,0x00000101,0x000000ab,0x0003003e,
0x000000b9,0x00000102,0x000200f9,0x000000bb,0x000200f8,0x000000bd,0x000200fe,0x00000103,
0x00010038
0x000200f8,0x00000022,0x0004003b,0x00000016,0x000000ac,0x00000007,0x0004003b,0x00000023,
0x000000bd,0x00000007,0x0004003b,0x000000d0,0x000000d1,0x00000007,0x0004003b,0x0000001d,
0x000000d7,0x00000007,0x0004003b,0x0000001d,0x000000e5,0x00000007,0x00060041,0x000000b8,
0x000000b9,0x000000b6,0x000000b7,0x000000b2,0x0004003d,0x00000006,0x000000ba,0x000000b9,
0x0005008d,0x00000006,0x000000bc,0x000000ba,0x000000bb,0x0003003e,0x000000ac,0x000000bc,
0x0003003e,0x000000bd,0x000000be,0x000200f9,0x000000bf,0x000200f8,0x000000bf,0x000400f6,
0x000000c1,0x000000c2,0x00000000,0x000200f9,0x000000c3,0x000200f8,0x000000c3,0x0004003d,
0x0000001e,0x000000c4,0x000000bd,0x000500b1,0x00000024,0x000000c6,0x000000c4,0x000000c5,
0x000400fa,0x000000c6,0x000000c0,0x000000c1,0x000200f8,0x000000c0,0x0004003d,0x0000001e,
0x000000c7,0x000000bd,0x0004006f,0x00000006,0x000000c8,0x000000c7,0x0004003d,0x00000006,
0x000000c9,0x000000ac,0x00050083,0x00000006,0x000000cb,0x000000c9,0x000000ca,0x000500be,
0x00000024,0x000000cc,0x000000c8,0x000000cb,0x000300f7,0x000000ce,0x00000000,0x000400fa,
0x000000cc,0x000000cd,0x000000ce,0x000200f8,0x000000cd,0x000200f9,0x000000c1,0x000200f8,
0x000000ce,0x0004003d,0x0000001e,0x000000d3,0x000000bd,0x00060041,0x000000d4,0x000000d5,
0x000000b6,0x000000d2,0x000000d3,0x0004003d,0x000000af,0x000000d6,0x000000d5,0x0003003e,
0x000000d1,0x000000d6,0x00050041,0x000000d9,0x000000da,0x000000d1,0x000000d8,0x0004003d,
0x000000ae,0x000000db,0x000000da,0x000500c7,0x000000ae,0x000000dd,0x000000db,0x000000dc,
0x00040070,0x00000006,0x000000de,0x000000dd,0x00050041,0x000000d9,0x000000df,0x000000d1,
0x000000d8,0x0004003d,0x000000ae,0x000000e0,0x000000df,0x000500c2,0x000000ae,0x000000e2,
0x000000e0,0x000000e1,0x00040070,0x00000006,0x000000e3,0x000000e2,0x00050050,0x0000001c,
0x000000e4,0x000000de,0x000000e3,0x0003003e,0x000000d7,0x000000e4,0x00050041,0x000000d9,
0x000000e7,0x000000d1,0x000000e6,0x0004003d,0x000000ae,0x000000e8,0x000000e7,0x000500c7,
0x000000ae,0x000000e9,0x000000e8,0x000000dc,0x00040070,0x00000006,0x000000ea,0x000000e9,
0x00050041,0x000000d9,0x000000eb,0x000000d1,0x000000e6,0x0004003d,0x000000ae,0x000000ec,
0x000000eb,0x000500c2,0x000000ae,0x000000ed,0x000000ec,0x000000e1,0x00040070,0x00000006,
0x000000ee,0x000000ed,0x00050050,0x0000001c,0x000000ef,0x000000ea,0x000000ee,0x0003003e,
0x000000e5,0x000000ef,0x00050041,0x00000016,0x000000f0,0x00000020,0x000000d8,0x0004003d,
0x00000006,0x000000f1,0x000000f0,0x00050041,0x00000016,0x000000f2,0x000000d7,0x000000d8,
0x0004003d,0x00000006,0x000000f3,0x000000f2,0x000500be,0x00000024,0x000000f4,0x000000f1,
0x000000f3,0x000300f7,0x000000f6,0x00000000,0x000400fa,0x000000f4,0x000000f5,0x000000f6,
0x000200f8,0x000000f5,0x00050041,0x00000016,0x000000f7,0x00000020,0x000000e6,0x0004003d,
0x00000006,0x000000f8,0x000000f7,0x00050041,0x00000016,0x000000f9,0x000000d7,0x000000e6,
0x0004003d,0x00000006,0x000000fa,0x000000f9,0x000500be,0x00000024,0x000000fb,0x000000f8,
0x000000fa,0x000200f9,0x000000f6,0x000200f8,0x000000f6,0x000700f5,0x00000024,0x000000fc,
0x000000f4,0x000000ce,0x000000fb,0x000000f5,0x000300f7,0x000000fe,0x00000000,0x000400fa,
0x000000fc,0x000000fd,0x000000fe,0x000200f8,0x000000fd,0x00050041,0x00000016,0x000000ff,
0x00000020,0x000000d8,0x0004003d,0x00000006,0x00000100,0x000000ff,0x00050041,0x00000016,
0x00000101,0x000000e5,0x000000d8,0x0004003d,0x00000006,0x00000102,0x00000101,0x000500b8,
0x00000024,0x00000103,0x00000100,0x00000102,0x000200f9,0x000000fe,0x000200f8,0x000000fe,
0x000700f5,0x00000024,0x00000104,0x000000fc,0x000000f6,0x00000103,0x000000fd,0x000300f7,
0x00000106,0x00000000,0x000400fa,0x00000104,0x00000105,0x00000106,0x000200f8,0x00000105,
0x00050041,0x00000016,0x00000107,0x00000020,0x000000e6,0x0004003d,0x00000006,0x00000108,
0x00000107,0x00050041,0x00000016,0x00000109,0x000000e5,0x000000e6,0x0004003d,0x00000006,
0x0000010a,0x00000109,0x000500b8,0x00000024,0x0000010b,0x00000108,0x0000010a,0x000200f9,
0x00000106,0x000200f8,0x00000106,0x000700f5,0x00000024,0x0000010c,0x00000104,0x000000fe,
0x0000010b,0x00000105,0x000300f7,0x0000010e,0x00000000,0x000400fa,0x0000010c,0x0000010d,
0x0000010e,0x000200f8,0x0000010d,0x0004003d,0x0000001e,0x0000010f,0x000000bd,0x000200fe,
0x0000010f,0x000200f8,0x0000010e,0x000200f9,0x000000c2,0x000200f8,0x000000c2,0x0004003d,
0x0000001e,0x00000111,0x000000bd,0x00050080,0x0000001e,0x00000112,0x00000111,0x000000b7,
0x0003003e,0x000000bd,0x00000112,0x000200f9,0x000000bf,0x000200f8,0x000000c1,0x000200fe,
0x00000113,0x00010038,0x00050036,0x00000024,0x00000028,0x00000000,0x00000025,0x00030037,
0x00000016,0x00000026,0x00030037,0x00000023,0x00000027,0x000200f8,0x00000029,0x0004003d,
0x0000001e,0x00000116,0x00000027,0x000500af,0x00000024,0x00000117,0x00000116,0x000000be,
0x000300f7,0x00000119,0x00000000,0x000400fa,0x00000117,0x00000118,0x00000119,0x000200f8,
0x00000118,0x0004003d,0x00000006,0x0000011a,0x00000026,0x0004003d,0x0000001e,0x0000011b,
0x00000027,0x0004006f,0x00000006,0x0000011c,0x0000011b,0x0006000c,0x00000006,0x0000011d,
0x00000001,0x0000001d,0x0000011c,0x00050088,0x00000006,0x0000011e,0x0000011a,0x0000011d,
0x0006000c,0x00000006,0x0000011f,0x00000001,0x00000008,0x0000011e,0x0005008d,0x00000006,
0x00000121,0x0000011f,0x00000120,0x000500ba,0x00000024,0x00000122,0x00000121,0x000000ca,
0x000200f9,0x00000119,0x000200f8,0x00000119,0x000700f5,0x00000024,0x00000123,0x00000117,
0x00000029,0x00000122,0x00000118,0x000200fe,0x00000123,0x00010038,0x00050036,0x00000007,
0x0000002b,0x00000000,0x00000009,0x00030037,0x00000008,0x0000002a,0x000200f8,0x0000002c,
0x0004003b,0x00000008,0x00000126,0x00000007,0x0004003b,0x00000008,0x0000012b,0x00000007,
0x0004003b,0x00000008,0x00000130,0x00000007,0x00070041,0x000000b8,0x00000128,0x000000b6,
0x00000127,0x000000b7,0x000000b2,0x0004003d,0x00000006,0x00000129,0x00000128,0x000500ba,
0x00000024,0x0000012a,0x00000129,0x000000ca,0x000300f7,0x0000012d,0x00000000,0x000400fa,
0x0000012a,0x0000012c,0x0000012f,0x000200f8,0x0000012c,0x0004003d,0x00000007,0x0000012e,
0x0000002a,0x0003003e,0x0000012b,0x0000012e,0x000200f9,0x0000012d,0x000200f8,0x0000012f,
0x0004003d,0x00000007,0x00000131,0x0000002a,0x0003003e,0x00000130,0x00000131,0x00050039,
0x00000007,0x00000132,0x00000011,0x00000130,0x0003003e,0x0000012b,0x00000132,0x000200f9,
0x0000012d,0x000200f8,0x0000012d,0x0004003d,0x00000007,0x00000133,0x0000012b,0x0003003e,
0x00000126,0x00000133,0x00060041,0x00000134,0x00000135,0x000000b6,0x00000127,0x000000be,
0x0004003d,0x000000ad,0x00000136,0x00000135,0x0008004f,0x00000007,0x00000137,0x00000136,
0x00000136,0x00000000,0x00000001,0x00000002,0x0004003d,0x00000007,0x00000138,0x00000126,
0x00050094,0x00000006,0x00000139,0x00000137,0x00000138,0x00060041,0x00000134,0x0000013a,
0x000000b6,0x00000127,0x000000b7,0x0004003d,0x000000ad,0x0000013b,0x0000013a,0x0008004f,
0x00000007,0x0000013c,0x0000013b,0x0000013b,0x00000000,0x00000001,0x00000002,0x0004003d,
0x00000007,0x0000013d,0x00000126,0x00050094,0x00000006,0x0000013e,0x0000013c,0x0000013d,
0x00060041,0x00000134,0x0000013f,0x000000b6,0x00000127,0x000000d2,0x0004003d,0x000000ad,
0x00000140,0x0000013f,0x0008004f,0x00000007,0x00000141,0x00000140,0x00000140,0x00000000,
0x00000001,0x00000002,0x0004003d,0x00000007,0x00000142,0x00000126,0x00050094,0x00000006,
0x00000143,0x00000141,0x00000142,0x00060050,0x00000007,0x00000144,0x00000139,0x0000013e,
0x00000143,0x00070041,0x000000b8,0x00000145,0x000000b6,0x00000127,0x000000d2,0x000000b2,
0x0004003d,0x00000006,0x00000146,0x00000145,0x0005008e,0x00000007,0x00000147,0x00000144,
0x00000146,0x000200fe,0x00000147,0x00010038
};
+223 -45
View File
@@ -3,6 +3,7 @@
#include "ahb_swapchain.h"
#include "droiddeck_color.h"
#include "vk_present.h"
#include "framegen_bridge.h"
#include <android/hardware_buffer.h>
#include <android/native_window.h>
#include <android/rect.h>
@@ -64,6 +65,8 @@ static struct {
void (*setHdrMetadata_cta861_3)(ASurfaceTransaction *, ASurfaceControl *, const struct droiddeck_hdr_cta861_3 *);
const void *(*getNativeHandle)(const AHardwareBuffer *);
void (*setDesiredHdrHeadroom)(ASurfaceTransaction *, ASurfaceControl *, float);
void (*setEnableBackPressure)(ASurfaceTransaction *, ASurfaceControl *, bool);
void (*setDesiredPresentTime)(ASurfaceTransaction *, int64_t);
int state;
} api;
@@ -105,6 +108,8 @@ static int load_api(void) {
SYM(setHdrMetadata_smpte2086, "ASurfaceTransaction_setHdrMetadata_smpte2086");
SYM(setHdrMetadata_cta861_3, "ASurfaceTransaction_setHdrMetadata_cta861_3");
SYM(setDesiredHdrHeadroom, "ASurfaceTransaction_setDesiredHdrHeadroom");
SYM(setEnableBackPressure, "ASurfaceTransaction_setEnableBackPressure");
SYM(setDesiredPresentTime, "ASurfaceTransaction_setDesiredPresentTime");
#undef SYM
if (!api.createFromWindow || !api.release || !api.txCreate || !api.txDelete || !api.txApply ||
!api.setBuffer || !api.setZOrder || !api.setVisibility || !api.setGeometry ||
@@ -134,7 +139,7 @@ void sc_layer_set_frame_rate(float fps) {
}
#define POOL_MAX 5
#define POOL_MAX 8
struct slot {
AHardwareBuffer *ahb;
@@ -158,6 +163,7 @@ struct layer {
ARect geo_src, geo_dst;
int geo_valid;
int alloc_tier;
unsigned import_failed_fmts;
uint64_t pool_modifier;
int first_logged;
int64_t drop_logged_ns;
@@ -183,6 +189,12 @@ static int g_layers_ready;
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static int g_pending_cb;
static unsigned g_stat_layer_frames;
static pthread_mutex_t g_timeline_lock = PTHREAD_MUTEX_INITIALIZER;
static int64_t g_timeline_present_ns, g_timeline_deadline_ns, g_timeline_period_ns;
static int g_timeline_late;
static int64_t g_cadence_seen_ns, g_cadence_gap_ns, g_cadence_target_ns;
static int g_group_frames = 1, g_group_index;
static unsigned g_stat_aimed_next, g_stat_aimed_later, g_stat_aimed_even;
static int g_two_logged;
static AHardwareBuffer *g_blank;
static ASurfaceControl *g_base_sc;
@@ -219,6 +231,58 @@ static int64_t now_ns(void) {
return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns) {
pthread_mutex_lock(&g_timeline_lock);
g_timeline_present_ns = present_ns;
g_timeline_deadline_ns = deadline_ns;
g_timeline_period_ns = period_ns;
pthread_mutex_unlock(&g_timeline_lock);
}
static int64_t cadence_target(int64_t now, int64_t earliest, int64_t period) {
const int64_t gap = now - g_cadence_seen_ns;
g_cadence_seen_ns = now;
if (gap <= 0 || gap > 8 * period) {
g_cadence_gap_ns = 0;
g_cadence_target_ns = earliest;
return earliest;
}
g_cadence_gap_ns = g_cadence_gap_ns ? (g_cadence_gap_ns * 15 + gap) / 16 : gap;
const int64_t steps = (g_cadence_gap_ns + period / 2) / period;
const int64_t even = g_cadence_target_ns + steps * period;
int64_t target = earliest;
if (steps >= 1 && llabs(g_cadence_gap_ns - steps * period) < period / 8 &&
even > earliest + period / 2 && even < earliest + steps * period + period / 2) {
target = even;
g_stat_aimed_even++;
}
g_cadence_target_ns = target;
return target;
}
static void apply_present_time(ASurfaceTransaction *tx, int game) {
if (!api.setDesiredPresentTime) return;
pthread_mutex_lock(&g_timeline_lock);
const int64_t present = g_timeline_present_ns, deadline = g_timeline_deadline_ns, period = g_timeline_period_ns;
pthread_mutex_unlock(&g_timeline_lock);
const int64_t now = now_ns();
if (period <= 0 || now - deadline > 4 * period) return;
int64_t ahead = now > deadline ? (now - deadline + period - 1) / period : -((deadline - now) / period);
const int64_t slack = deadline + ahead * period - now;
g_timeline_late = slack < (g_timeline_late ? period * 5 / 8 : period / 8);
if (g_timeline_late) { ahead++; g_stat_aimed_later++; } else g_stat_aimed_next++;
int64_t target = present + ahead * period;
if (game && g_group_index > 0) {
int64_t steps = (g_group_index * g_cadence_gap_ns / g_group_frames + period / 2) / period;
if (steps < g_group_index) steps = g_group_index;
if (target < g_cadence_target_ns + steps * period) target = g_cadence_target_ns + steps * period;
} else if (game) {
target = cadence_target(now, target, period);
}
if (game && g_group_frames > 1 && ++g_group_index >= g_group_frames) { g_group_index = 0; g_group_frames = 1; }
api.setDesiredPresentTime(tx, target - period / 2);
}
static void on_complete(void *context, ASurfaceTransactionStats *stats) {
struct complete_ctx *ctx = context;
pthread_mutex_lock(&g_lock);
@@ -401,10 +465,22 @@ static void describe_handle(const struct droiddeck_native_handle *h, char *out,
o += (size_t)snprintf(out + o, n - o, " %#x", (unsigned)h->data[h->numFds + i]);
}
static int handle_fd(const struct droiddeck_native_handle *h, off_t need, int *which) {
for (int i = 0; h && i < h->numFds; i++) {
off_t sz = lseek(h->data[i], 0, SEEK_END);
if (sz >= 0) lseek(h->data[i], 0, SEEK_SET);
if (sz >= need) { if (which) *which = i; return h->data[i]; }
}
return -1;
}
int sc_layer_ahb_fd(AHardwareBuffer *ahb, uint64_t need) {
return load_api() == 0 ? handle_fd(api.getNativeHandle(ahb), (off_t)need, NULL) : -1;
}
static int g_alloc_failed;
enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR };
#define DROIDDECK_AHB_USAGE_VENDOR_UBWC (1ULL << 28)
static const char *tier_name(int tier) {
return tier == TIER_UBWC ? "asked for UBWC" : tier == TIER_PLAIN ? "no UBWC request" : "linear by request (CPU bit)";
@@ -412,14 +488,15 @@ static const char *tier_name(int tier) {
static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) {
g_alloc_failed = 0;
while (l->alloc_tier <= TIER_LINEAR) {
const unsigned fmt_bit = fmt == AHB_RGB10A2 ? 2u : 1u;
while (l->alloc_tier <= TIER_LINEAR && !(l->import_failed_fmts & fmt_bit)) {
const int tier = l->alloc_tier;
AHardwareBuffer_Desc d = {
.width = (uint32_t)w, .height = (uint32_t)h, .layers = 1,
.format = fmt,
.usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY |
(tier == TIER_UBWC ? DROIDDECK_AHB_USAGE_VENDOR_UBWC : 0) |
(tier == TIER_UBWC ? SC_LAYER_AHB_USAGE_VENDOR_UBWC : 0) |
(tier == TIER_LINEAR ? AHARDWAREBUFFER_USAGE_CPU_READ_RARELY : 0)};
AHardwareBuffer *ahb = NULL;
if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) {
@@ -443,6 +520,10 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
img = vkp_image_import_dmabuf(nh->data[0], fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888, mod, w, h,
got.stride * 4, 0, 1);
path = "dma-buf (QTI handle)";
if (!img && mod == MOD_LINEAR && vkp_can_import_ahb()) {
img = vkp_image_import_ahb(ahb, info, sizeof(info));
if (img) { mod = SC_MOD_GRALLOC; path = "AHardwareBuffer"; }
}
} else {
if (tier == TIER_UBWC) {
char hd[256];
@@ -459,13 +540,8 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
path = "AHardwareBuffer";
img = vkp_image_import_ahb(ahb, info, sizeof(info));
if (!img && tier == TIER_LINEAR) {
const off_t need = (off_t)got.stride * 4 * h;
int fd = -1, which = -1;
for (int i = 0; nh && i < nh->numFds; i++) {
off_t sz = lseek(nh->data[i], 0, SEEK_END);
if (sz >= 0) lseek(nh->data[i], 0, SEEK_SET);
if (sz >= need) { fd = nh->data[i]; which = i; break; }
}
int which = -1;
int fd = handle_fd(nh, (off_t)got.stride * 4 * h, &which);
if (fd < 0 && nh && nh->numFds > 0) { fd = nh->data[0]; which = 0; }
mod = MOD_LINEAR;
path = "linear dma-buf";
@@ -486,6 +562,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd);
AHardwareBuffer_release(ahb);
if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; }
l->import_failed_fmts |= fmt_bit;
g_alloc_failed = 1;
return -1;
}
@@ -506,16 +583,27 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
return -1;
}
static int fence_signalled(int fd) {
static int fence_wait(int fd, int timeout_ms) {
struct pollfd p = {.fd = fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 0); } while (r < 0 && errno == EINTR);
return r > 0;
do { r = poll(&p, 1, timeout_ms); } while (r < 0 && errno == EINTR);
return r;
}
static int fence_signalled(int fd) {
return fence_wait(fd, 0) > 0;
}
static void slot_keep_fence(struct slot *s, int fd) {
pthread_mutex_lock(&g_lock);
if (s->release_fd < 0) s->release_fd = fd; else close(fd);
pthread_mutex_unlock(&g_lock);
}
static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait_fd) {
int idx = -1, pending = -1, fd = -1;
*wait_fd = -1;
g_alloc_failed = 0;
pthread_mutex_lock(&g_lock);
for (int i = 0; i < l->pool_n; i++) {
if (i == l->cur_slot || l->slots[i].busy) continue;
@@ -535,15 +623,7 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait
memset(s, 0, sizeof(*s)); s->release_fd = -1;
}
if (fd >= 0 && !vkp_can_wait_sync_fd()) {
struct pollfd p = {.fd = fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
if (r == 0) {
pthread_mutex_lock(&g_lock);
if (s->release_fd < 0) s->release_fd = fd; else close(fd);
pthread_mutex_unlock(&g_lock);
return -1;
}
if (fence_wait(fd, 100) == 0) { slot_keep_fence(s, fd); return -1; }
close(fd);
fd = -1;
}
@@ -558,6 +638,8 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait
int sc_layer_available(void) { return load_api() == 0; }
int sc_layer_queues(void) { return load_api() == 0 && api.setEnableBackPressure != NULL; }
void sc_layer_probe_dmabuf_fd(int fd) {
static int done;
if (done || fd < 0) return;
@@ -595,9 +677,10 @@ static int ensure_sc(struct layer *l) {
return 0;
}
static int layer_geometry(int w, int h, int scene_w, int scene_h, int r[8]) {
static int layer_geometry(int w, int h, int scene_w, int scene_h, const struct vkp_draw *draw, int r[8]) {
if (vkp_update_map(scene_w, scene_h) != 0) return -1;
return vkp_map_rect(w, h, scene_w, scene_h, r) ? 1 : 0;
if (draw) return vkp_map_draw(draw, r) ? 1 : 0;
return vkp_map_rect(w, h, (const int[4]){0, 0, scene_w, scene_h}, r) ? 1 : 0;
}
static ARect g_game_src, g_game_dst;
@@ -757,6 +840,7 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d
ASurfaceControl *old = swap_sc_begin(l);
if (old) api.setZOrder(tx, l->sc, l->z);
api.setBuffer(tx, l->sc, s->ahb, -1);
if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true);
api.setBufferTransparency(tx, l->sc,
translucent ? ASC_TRANSPARENCY_TRANSLUCENT : ASC_TRANSPARENCY_OPAQUE);
apply_geometry(tx, l, r);
@@ -769,6 +853,7 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d
pthread_mutex_lock(&g_lock);
s->busy = 1;
pthread_mutex_unlock(&g_lock);
apply_present_time(tx, l == &g_layers[SC_LAYER_GAME]);
api.txApply(tx);
api.txDelete(tx);
l->cur_slot = idx;
@@ -799,11 +884,12 @@ unsigned sc_layer_drops_take(void) {
}
int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token, int scene_w, int scene_h,
const struct vkp_draw *draw,
const struct droiddeck_color *color, uint32_t ahb_format) {
struct layer *l = layer_of(SC_LAYER_GAME);
int r[8];
if (!ahb || !token || ensure_sc(l) != 0) goto unavailable;
int g = layer_geometry(w, h, scene_w, scene_h, r);
int g = layer_geometry(w, h, scene_w, scene_h, draw, r);
if (g < 0) goto unavailable;
if (g == 0) { if (acquire_fd >= 0) close(acquire_fd); sc_layer_hide(); return 1; }
if (token == l->cur_token && l->shown && !l->recreate_pending) {
@@ -821,6 +907,7 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi
ASurfaceControl *old = swap_sc_begin(l);
if (old) api.setZOrder(tx, l->sc, l->z);
api.setBuffer(tx, l->sc, ahb, acquire_fd);
if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true);
api.setBufferTransparency(tx, l->sc, ASC_TRANSPARENCY_OPAQUE);
apply_geometry(tx, l, r);
apply_frame_rate(tx, l);
@@ -834,6 +921,7 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi
l->ds_applied = -1; l->md_applied = 0; l->hr_applied = -1.0f;
return -1;
}
apply_present_time(tx, 1);
api.txApply(tx);
api.txDelete(tx);
l->cur_slot = -1;
@@ -848,18 +936,19 @@ unavailable:
return -1;
}
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color) {
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color) {
struct layer *l = layer_of(SC_LAYER_GAME);
if (!src || ensure_sc(l) != 0) return -1;
int sw = vkp_image_width(src), sh = vkp_image_height(src);
int r[8];
int g = layer_geometry(sw, sh, scene_w, scene_h, r);
int g = layer_geometry(sw, sh, scene_w, scene_h, draw, r);
if (g < 0) return -1;
if (g == 0) { sc_layer_hide(); return 0; }
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return 0; }
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, r, color, 0) != 0) return -1;
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8);
@@ -879,10 +968,10 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int
if (!draws || n <= 0 || ensure_sc(l) != 0) return -1;
if (vkp_update_map(scene_w, scene_h) != 0) return -1;
if (vkp_pass_begin(scene_w, scene_h, draws, n, &rw, &rh) != 0) return -1;
if (!vkp_map_rect(rw, rh, scene_w, scene_h, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; }
if (!vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; }
int wait_fd;
int idx = take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd);
if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; }
if (idx < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, r, NULL, 0) != 0) return -1;
if (!l->first_logged) {
@@ -895,8 +984,97 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int
return 0;
}
static void slots_idle(struct layer *l, const int *idx, int from, int to) {
pthread_mutex_lock(&g_lock);
for (int i = from; i < to; i++) l->slots[idx[i]].busy = 0;
pthread_mutex_unlock(&g_lock);
}
static uint32_t g_hdr_pool_fmt = AHB_RGB10A2;
static int take_hdr_slot(struct layer *l, int w, int h, int *wait_fd) {
int idx = take_free_slot(l, w, h, g_hdr_pool_fmt, wait_fd);
if (idx < 0 && g_alloc_failed && g_hdr_pool_fmt == AHB_RGB10A2) {
g_hdr_pool_fmt = AHB_RGBA8;
droiddeck_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes "
"on 8-bit buffers instead (still tagged BT2020_PQ; less precision)", l->name);
idx = take_free_slot(l, w, h, g_hdr_pool_fmt, wait_fd);
}
return idx;
}
int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf,
int scene_w, int scene_h, int composed, const struct droiddeck_color *color) {
struct layer *l = layer_of(SC_LAYER_GAME);
int rw = 0, rh = 0, r[8], idx[VKP_FG_MAX_GENERATIONS + 1], m = 0, first_fd = -1, have_fd = 0;
struct vkp_image *dst[VKP_FG_MAX_GENERATIONS], *real = NULL;
g_group_index = 0;
g_group_frames = 1;
if (!draws || n_draws <= 0 || ensure_sc(l) != 0) return -1;
if (vkp_update_map(scene_w, scene_h) != 0) return -1;
const int deep = hf && !hf->tonemap;
if (hf) composed = 1;
if (hf && hf->tonemap) color = NULL;
int n = vkp_pass_begin_generate(scene_w, scene_h, draws, n_draws, hf, &rw, &rh);
if (n < 0) return -1;
const int mapped = vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r);
if (!mapped) n = 0;
if (composed) {
if (!mapped) { vkp_pass_abort(); sc_layer_hide(); return 0; }
idx[VKP_FG_MAX_GENERATIONS] = deep ? take_hdr_slot(l, rw, rh, &first_fd)
: take_free_slot(l, rw, rh, AHB_RGBA8, &first_fd);
if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; }
pthread_mutex_lock(&g_lock);
l->slots[idx[VKP_FG_MAX_GENERATIONS]].busy = 1;
pthread_mutex_unlock(&g_lock);
real = l->slots[idx[VKP_FG_MAX_GENERATIONS]].img;
have_fd = 1;
}
for (; m < n; m++) {
int fd;
idx[m] = take_free_slot(l, rw, rh, deep ? g_hdr_pool_fmt : AHB_RGBA8, &fd);
if (idx[m] < 0) { log_drop(l); break; }
if (have_fd && fd >= 0) {
if (fence_wait(fd, 100) == 0) { slot_keep_fence(&l->slots[idx[m]], fd); log_drop(l); break; }
close(fd);
}
pthread_mutex_lock(&g_lock);
l->slots[idx[m]].busy = 1;
pthread_mutex_unlock(&g_lock);
dst[m] = l->slots[idx[m]].img;
if (!have_fd) { first_fd = fd; have_fd = 1; }
}
if (vkp_pass_copy_generated(dst, m, real, first_fd) != 0) {
slots_idle(l, idx, 0, m);
if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1);
return -1;
}
g_group_frames = m + 1;
for (int k = 0; k < m; k++) {
if (present_slot(l, idx[k], r, color, 0) == 0) continue;
slots_idle(l, idx, k, m);
if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1);
g_group_index = 0;
g_group_frames = 1;
return -1;
}
vkp_framegen_presented(m);
if (real) {
if (present_slot(l, idx[VKP_FG_MAX_GENERATIONS], r, color, 0) != 0) {
slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1);
g_group_index = 0;
g_group_frames = 1;
return -1;
}
l->first_logged = 1;
vkp_signal_first_frame();
}
if (hf && hf->color && hf->color->dataspace)
droiddeck_color_frame_shown(hf->color, deep ? DROIDDECK_HDR_COMPOSED : DROIDDECK_HDR_TONEMAPPED,
deep ? g_hdr_pool_fmt : AHB_RGBA8);
return m;
}
int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf,
int scene_w, int scene_h, const struct droiddeck_color *color) {
struct layer *l = layer_of(SC_LAYER_GAME);
@@ -904,19 +1082,11 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct
if (!draws || n <= 0 || !hf || ensure_sc(l) != 0) return -1;
if (vkp_update_map(scene_w, scene_h) != 0) return -1;
if (vkp_pass_begin_hdr(scene_w, scene_h, draws, n, hf, &rw, &rh) != 0) return -1;
if (!vkp_map_rect(rw, rh, scene_w, scene_h, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; }
if (!vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; }
const int tm = hf->tonemap;
const uint32_t fmt = tm ? AHB_RGBA8 : g_hdr_pool_fmt;
g_alloc_failed = 0;
int wait_fd;
int idx = take_free_slot(l, rw, rh, fmt, &wait_fd);
if (idx < 0 && g_alloc_failed && fmt == AHB_RGB10A2) {
g_hdr_pool_fmt = AHB_RGBA8;
droiddeck_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes "
"on 8-bit buffers instead (still tagged BT2020_PQ; less precision)", l->name);
idx = take_free_slot(l, rw, rh, g_hdr_pool_fmt, &wait_fd);
}
if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; }
int idx = tm ? take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd) : take_hdr_slot(l, rw, rh, &wait_fd);
if (idx < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, r, tm ? NULL : color, 0) != 0) return -1;
if (color && color->dataspace)
@@ -967,8 +1137,9 @@ int sc_layer_overlay_affordable(void) {
if (want)
droiddeck_log("layer", "overlay layer declined: this display rotates every layer %d° and the game "
"layer is scaled %dx%d -> %dx%d, and on that combination a second layer drops the "
"whole frame to GPU composition for the rest of the session (measured). The window "
"above the game goes on the copy path instead - same picture, one blit.",
"whole frame to GPU composition for the rest of the session (measured). A nested "
"compositor is asked to compose its own overlays into the game picture; any other "
"window above the game goes on the copy path instead.",
deg, sr[0], sr[1], ds[0], ds[1]);
else if (!first)
droiddeck_log("layer", "overlay layer allowed again: the game layer is no longer both rotated and "
@@ -986,7 +1157,7 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl
if (sw <= 0 || sh <= 0) return -1;
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return 0; }
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
if (!l->first_logged) {
@@ -1033,6 +1204,13 @@ void sc_layer_window_gone(void) {
drain_and_free_pools();
}
void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even) {
*next = g_stat_aimed_next;
*later = g_stat_aimed_later;
*even = g_stat_aimed_even;
g_stat_aimed_next = g_stat_aimed_later = g_stat_aimed_even = 0;
}
unsigned sc_layer_frames_take(void) {
unsigned n = g_stat_layer_frames;
g_stat_layer_frames = 0;
+12 -3
View File
@@ -7,10 +7,13 @@
struct vkp_image;
struct vkp_draw;
struct droiddeck_color;
struct vkp_hdr_frame;
enum sc_layer_id { SC_LAYER_GAME = 0, SC_LAYER_OVERLAY = 1, SC_LAYER_COUNT = 2 };
int sc_layer_available(void);
#define SC_LAYER_AHB_USAGE_VENDOR_UBWC (1ULL << 28)
int sc_layer_ahb_fd(AHardwareBuffer *ahb, uint64_t need);
void sc_layer_probe_dmabuf_fd(int fd);
@@ -18,21 +21,25 @@ int sc_layer_can_tag_hdr(void);
void sc_layer_hdr_symbols(char *out, size_t size);
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color);
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color);
int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int scene_h);
int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf,
int scene_w, int scene_h, int composed, const struct droiddeck_color *color);
struct vkp_hdr_frame;
int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf,
int scene_w, int scene_h, const struct droiddeck_color *color);
int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token,
int scene_w, int scene_h, const struct droiddeck_color *color, uint32_t ahb_format);
int scene_w, int scene_h, const struct vkp_draw *draw, const struct droiddeck_color *color, uint32_t ahb_format);
void sc_layer_set_frame_rate(float fps);
int sc_layer_overlay_affordable(void);
int sc_layer_queues(void);
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent);
void sc_layer_hide(void);
@@ -42,6 +49,8 @@ void sc_layer_hide_overlay(void);
void sc_layer_window_gone(void);
void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns);
void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even);
unsigned sc_layer_frames_take(void);
unsigned sc_layer_drops_take(void);
@@ -0,0 +1,61 @@
#ifndef VK_LINEAR_DMABUF_H
#define VK_LINEAR_DMABUF_H
#include <stdint.h>
#include <vulkan/vulkan.h>
static inline int vkp_linear_dmabuf_through_buffer(int drm_modifiers, uint64_t modifier, int blit_dst) {
return !drm_modifiers && modifier == 0 && !blit_dst;
}
static inline int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) {
return dmabuf && !staged;
}
static inline VkPipelineStageFlags vkp_linear_dmabuf_readback_stage(int in_general) {
return in_general ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
}
static inline VkAccessFlags vkp_linear_dmabuf_readback_access(int in_general) {
return in_general ? VK_ACCESS_TRANSFER_WRITE_BIT : 0;
}
static inline uint32_t vkp_linear_dmabuf_texel_bytes(VkFormat fmt) {
return fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? 8u : 4u;
}
static inline int vkp_padded_linear_target_needs_layout(int drm_modifiers, uint64_t modifier, VkFormat fmt,
int w, uint32_t stride, uint32_t offset) {
return !drm_modifiers && modifier == 0 &&
(offset != 0 || (uint64_t)stride != (uint64_t)w * vkp_linear_dmabuf_texel_bytes(fmt));
}
static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, uint32_t stride, uint32_t offset,
VkBufferImageCopy *copy) {
const uint32_t texel = vkp_linear_dmabuf_texel_bytes(fmt);
if (!copy || w <= 0 || h <= 0 || stride % texel || offset % texel || stride / texel < (uint32_t)w) return 0;
*copy = (VkBufferImageCopy){
.bufferOffset = offset,
.bufferRowLength = stride / texel,
.bufferImageHeight = (uint32_t)h,
.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.imageExtent = {(uint32_t)w, (uint32_t)h, 1},
};
return (VkDeviceSize)offset + (VkDeviceSize)stride * (VkDeviceSize)(h - 1) + (VkDeviceSize)w * texel;
}
static inline VkBufferMemoryBarrier vkp_linear_dmabuf_ownership(VkBuffer buffer, uint32_t queue_family,
VkAccessFlags access, int acquire) {
return (VkBufferMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
.srcAccessMask = acquire ? 0 : access,
.dstAccessMask = acquire ? access : 0,
.srcQueueFamilyIndex = acquire ? VK_QUEUE_FAMILY_FOREIGN_EXT : queue_family,
.dstQueueFamilyIndex = acquire ? queue_family : VK_QUEUE_FAMILY_FOREIGN_EXT,
.buffer = buffer,
.offset = 0,
.size = VK_WHOLE_SIZE,
};
}
#endif
+3 -1
View File
@@ -22,7 +22,9 @@
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) X(CmdCopyImageToBuffer) \
X(CreateBuffer) X(DestroyBuffer) X(GetBufferMemoryRequirements) X(BindBufferMemory) \
X(CmdCopyBufferToImage) \
\
X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \
X(CreateGraphicsPipelines) X(DestroyPipeline) X(CreateRenderPass) X(DestroyRenderPass) \
+318 -75
View File
@@ -2,6 +2,7 @@
#include "vk_present.h"
#include "vk_loader.h"
#include "vk_external_image_sync.h"
#include "vk_linear_dmabuf.h"
#include "sc_layer.h"
#include "effects_chain.h"
#include "cardboard.h"
@@ -42,10 +43,15 @@ struct vkp_image {
VkFormat fmt;
int sampled;
AHardwareBuffer *android_buffer;
int staged;
VkBuffer linear_buf;
VkDeviceMemory linear_mem;
VkBufferImageCopy linear_copy;
};
static ANativeWindow *g_window;
static int g_ahb_import;
static int g_drm_modifiers;
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
static int g_allow_driver_fallback;
static int g_dev_state;
@@ -628,6 +634,7 @@ static int dev_init(void) {
if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
}
g_drm_modifiers = has_ext(exts, ne, "VK_EXT_image_drm_format_modifier");
int want_hdr_md = 0;
if (droiddeck_color_requested()) {
want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME);
@@ -1088,6 +1095,10 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0);
}
static int foreign_image(const struct vkp_image *img) {
return vkp_linear_dmabuf_foreign_image(img->dmabuf, img->staged);
}
/* Return client sources to FOREIGN after their final read. The consuming paths
* wait for our fence before Wayland can release an ordinary dma-buf or an
* android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from
@@ -1095,7 +1106,7 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) {
struct vkp_external_client_barrier_pair pair;
if (!img || !vkp_external_client_barrier_pair(
img->image, g_qfam, img->dmabuf, img->blit_dst, &pair))
img->image, g_qfam, foreign_image(img), img->blit_dst, &pair))
return;
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release);
@@ -1109,6 +1120,37 @@ static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_
}
}
static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img) {
if (!img || !img->linear_buf) return;
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 1);
VkImageMemoryBarrier write = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = img->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
0, NULL, 1, &acquire, 1, &write);
g_vk.CmdCopyBufferToImage(cmd, img->linear_buf, img->image, VK_IMAGE_LAYOUT_GENERAL, 1, &img->linear_copy);
VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 0);
VkImageMemoryBarrier read = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = img->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0,
0, NULL, 1, &release, 1, &read);
}
static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) {
for (int i = 0; i < count; i++) {
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; }
if (!seen) stage_linear_dmabuf(cmd, draws[i].img);
}
}
int vkp_image_is_dmabuf(const struct vkp_image *img) {
return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst);
}
@@ -1181,18 +1223,122 @@ fail:
return NULL;
}
static int optimal_sampled(VkFormat fmt) {
if (!g_vk.GetPhysicalDeviceFormatProperties2) return 0;
VkFormatProperties2 fp = {.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2};
g_vk.GetPhysicalDeviceFormatProperties2(g_pd, fmt, &fp);
const VkFormatFeatureFlags need = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
return (fp.formatProperties.optimalTilingFeatures & need) == need;
}
static void destroy_image_objects(struct vkp_image *img) {
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
if (img->linear_buf) g_vk.DestroyBuffer(g_dev, img->linear_buf, NULL);
if (img->linear_mem) g_vk.FreeMemory(g_dev, img->linear_mem, NULL);
img->image = VK_NULL_HANDLE; img->mem = VK_NULL_HANDLE;
img->linear_buf = VK_NULL_HANDLE; img->linear_mem = VK_NULL_HANDLE;
img->staged = 0; img->in_general = 0;
}
static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferImageCopy *copy, VkDeviceSize need) {
int dupfd = dup(fd);
if (dupfd < 0) return -1;
VkDeviceSize size = need;
off_t end = lseek(dupfd, 0, SEEK_END);
if (end > 0 && (VkDeviceSize)end >= need) size = (VkDeviceSize)end;
lseek(dupfd, 0, SEEK_SET);
if (end > 0 && (VkDeviceSize)end < need) {
LOGE("dmabuf: the linear %dx%d buffer holds %lld bytes, its row pitch needs %llu", img->w, img->h,
(long long)end, (unsigned long long)need);
close(dupfd);
return -1;
}
VkExternalMemoryBufferCreateInfo ext = {
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
VkBufferCreateInfo bci = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = &ext, .size = size,
.usage = img->blit_dst ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE};
VkResult r = g_vk.CreateBuffer(g_dev, &bci, NULL, &img->linear_buf);
if (r != VK_SUCCESS) goto fail;
uint32_t allowed = 0xffffffff;
if (g_vk.GetMemoryFdPropertiesKHR) {
VkMemoryFdPropertiesKHR fp = {.sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR};
if (g_vk.GetMemoryFdPropertiesKHR(g_dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
dupfd, &fp) == VK_SUCCESS)
allowed = fp.memoryTypeBits;
}
VkMemoryRequirements breq;
g_vk.GetBufferMemoryRequirements(g_dev, img->linear_buf, &breq);
int bidx = memory_type(breq.memoryTypeBits & allowed, 0);
r = VK_ERROR_FORMAT_NOT_SUPPORTED;
if (bidx < 0) goto fail;
VkImportMemoryFdInfoKHR imp = {.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, .fd = dupfd};
VkMemoryDedicatedAllocateInfo ded = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &imp, .buffer = img->linear_buf};
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &ded,
.allocationSize = breq.size, .memoryTypeIndex = (uint32_t)bidx};
r = g_vk.AllocateMemory(g_dev, &mai, NULL, &img->linear_mem);
if (r != VK_SUCCESS) goto fail;
dupfd = -1;
r = g_vk.BindBufferMemory(g_dev, img->linear_buf, img->linear_mem, 0);
if (r != VK_SUCCESS) goto fail;
VkImageCreateInfo ici = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = img->fmt,
.extent = {(uint32_t)img->w, (uint32_t)img->h, 1}, .mipLevels = 1, .arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
(img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
r = g_vk.CreateImage(g_dev, &ici, NULL, &img->image);
if (r != VK_SUCCESS) goto fail;
VkMemoryRequirements ireq;
g_vk.GetImageMemoryRequirements(g_dev, img->image, &ireq);
int iidx = memory_type(ireq.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
if (iidx < 0) iidx = memory_type(ireq.memoryTypeBits, 0);
r = VK_ERROR_FORMAT_NOT_SUPPORTED;
if (iidx < 0) goto fail;
VkMemoryAllocateInfo iai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.allocationSize = ireq.size, .memoryTypeIndex = (uint32_t)iidx};
r = g_vk.AllocateMemory(g_dev, &iai, NULL, &img->mem);
if (r != VK_SUCCESS) goto fail;
r = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
if (r != VK_SUCCESS) goto fail;
img->linear_copy = *copy;
img->staged = 1;
img->in_general = 1;
return 0;
fail:
LOGE("dmabuf: %s the linear %dx%d buffer at its row pitch failed (%s)",
img->blit_dst ? "writing" : "reading", img->w, img->h, vk_result_name(r));
if (dupfd >= 0) close(dupfd);
destroy_image_objects(img);
return -1;
}
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
uint32_t stride, uint32_t offset, int as_blit_dst) {
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
if (dev_init() != 0) return NULL;
const VkFormat format = drm_to_vk(drm_format);
const int padded_target = as_blit_dst &&
vkp_padded_linear_target_needs_layout(g_drm_modifiers, modifier, format, w, stride, offset);
if (padded_target && !g_vk.CmdCopyImageToBuffer) return NULL;
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0;
img->fmt = drm_to_vk(drm_format);
img->fmt = format;
const int through_buffer = padded_target || vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst);
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
modifier_importable(img->fmt, modifier, sampled_usage);
const int modifier_sampled = !as_blit_dst && g_drm_modifiers && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
modifier_importable(img->fmt, modifier, sampled_usage);
img->sampled = !as_blit_dst && (through_buffer ? optimal_sampled(img->fmt) : modifier_sampled);
/* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
* or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
{
@@ -1203,10 +1349,11 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
if (seen[i].fmt == drm_format && seen[i].mod == modifier && seen[i].w == w && seen[i].h == h) known = 1;
if (!known && nseen < 32) {
seen[nseen].fmt = drm_format; seen[nseen].mod = modifier; seen[nseen].w = w; seen[nseen].h = h; nseen++;
droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s",
droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s%s",
drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff, (drm_format >> 24) & 0xff,
vkp_modifier_name(modifier), w, h, stride, offset, (int)img->fmt,
img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : "");
img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : "",
through_buffer ? ", trying a copy at its row pitch (no VK_EXT_image_drm_format_modifier)" : "");
}
}
@@ -1214,6 +1361,17 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
* vkCreateImage, which left the whole window unshown (David Cimo). One packed, 64-byte aligned
* row is what a linear buffer that small holds. */
if (stride == 0 && modifier == 0) stride = ((uint32_t)w * 4 + 63) & ~63u;
if (through_buffer) {
VkBufferImageCopy linear_copy;
const VkDeviceSize linear_size = vkp_linear_dmabuf_copy(img->fmt, w, h, stride, offset, &linear_copy);
if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) {
if (padded_target) droiddeck_log("gpu", "linear layer target %dx%d writes at pitch %u via DMA-BUF",
w, h, stride);
return img;
}
if (padded_target) { free(img); return NULL; }
img->sampled = modifier_sampled;
}
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
@@ -1336,7 +1494,7 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
}
int vkp_can_import_ahb(void) {
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && g_ahb_import &&
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && !g_library_name && g_ahb_import &&
g_vk.GetAndroidHardwareBufferPropertiesANDROID;
}
@@ -1501,8 +1659,7 @@ void vkp_image_destroy(struct vkp_image *img) {
if (g_dev) {
blendp_forget_image(img->image);
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
destroy_image_objects(img);
}
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
free(img);
@@ -1600,7 +1757,7 @@ static void effects_source_note(int scene_w, int scene_h, const struct vkp_draw
static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
const struct vkp_image *im = d->img;
const int external_client = vkp_image_is_dmabuf(im);
const int external_client = vkp_is_external_client_image(foreign_image(im), im->blit_dst);
if (d->blend && im->sampled &&
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client,
target, target_fmt, target_w, target_h,
@@ -1734,6 +1891,11 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
struct hdrc_params p = {.mode = mode, .sdr_white_nits = droiddeck_color_sdr_white(),
.peak_nits = hf->peak_nits > 0.0f ? hf->peak_nits : 1000.0f};
if (hf->convert) {
p.conv_linear = hf->convert->convert == 2;
p.conv_gain = hf->convert->gain;
memcpy(p.conv, hf->convert->to2020, sizeof(p.conv));
}
int lowest_hdr = -1;
for (int i = 0; i < n; i++) {
VkImageBlit blit;
@@ -1750,6 +1912,7 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
p.rects[p.count][0] = (float)blit.dstOffsets[0].x; p.rects[p.count][1] = (float)blit.dstOffsets[0].y;
p.rects[p.count][2] = (float)blit.dstOffsets[1].x; p.rects[p.count][3] = (float)blit.dstOffsets[1].y;
if (hf->is_hdr[i]) p.hdr_mask |= 1u << p.count;
if (hf->is_hdr[i] == 2 && hf->convert) p.conv_mask |= 1u << p.count;
p.count++;
}
if (i >= lowest_hdr && !truncated_said) {
@@ -2084,6 +2247,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi);
blendp_begin_frame();
stage_linear_dmabufs(cmd, draws, n);
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageMemoryBarrier *bars = calloc((size_t)n + 1, sizeof(*bars));
@@ -2101,7 +2265,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
if (seen || !im) continue;
struct vkp_external_client_barrier_pair pair;
if (vkp_external_client_barrier_pair(
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
im->image, g_qfam, foreign_image(im), im->blit_dst, &pair)) {
bars[nb++] = pair.acquire;
} else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
@@ -2179,7 +2343,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,
@@ -2353,9 +2517,9 @@ int vkp_update_map(int scene_w, int scene_h) {
return g_map.valid ? 0 : -1;
}
int vkp_map_rect(int img_w, int img_h, int scene_w, int scene_h, int out[8]) {
int vkp_map_rect(int img_w, int img_h, const int dst[4], int out[8]) {
struct vkp_image tmp = {.w = img_w, .h = img_h};
struct vkp_draw d = {&tmp, 0, 0, (float)img_w, (float)img_h, 0, 0, scene_w, scene_h};
struct vkp_draw d = {&tmp, 0, 0, (float)img_w, (float)img_h, dst[0], dst[1], dst[2], dst[3]};
return vkp_map_draw(&d, out);
}
@@ -2369,6 +2533,48 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
return 1;
}
static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_layout, struct vkp_image *dst,
const VkImageBlit *blit, VkFilter filter) {
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
const VkImageMemoryBarrier acquire = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &acquire);
g_vk.CmdBlitImage(cmd, src, src_layout, dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
if (dst->staged) {
const VkImageMemoryBarrier read = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = dst->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &read);
const VkBufferMemoryBarrier write = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 1);
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 1, &write, 0, NULL);
VkBufferImageCopy copy = dst->linear_copy;
copy.imageExtent.width = (uint32_t)blit->dstOffsets[1].x;
copy.imageExtent.height = (uint32_t)blit->dstOffsets[1].y;
g_vk.CmdCopyImageToBuffer(cmd, dst->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->linear_buf, 1, &copy);
const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 0);
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 1, &release, 0, NULL);
return;
}
const VkImageMemoryBarrier release = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &release);
}
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
@@ -2383,44 +2589,32 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi);
stage_linear_dmabuf(g_cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 2, acq);
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
g_vk.CmdBlitImage(g_cmd, src->image,
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &rel);
g_vk.EndCommandBuffer(g_cmd);
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
@@ -2489,22 +2683,26 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi);
stage_linear_dmabuf(cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
.image = src->image, .subresourceRange = range,
.srcAccessMask = vkp_linear_dmabuf_readback_access(src->in_general),
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 2, acq);
g_vk.CmdPipelineBarrier(cmd, vkp_linear_dmabuf_readback_stage(src->in_general),
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 2, acq);
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {src->w, src->h, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
@@ -2551,24 +2749,33 @@ static struct {
int active;
VkImage result;
int rw, rh;
int ngen;
VkImage gens[VKP_FG_MAX_GENERATIONS];
} g_pass;
static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *rw, int *rh);
const struct vkp_hdr_frame *hf, int generate, int *rw, int *rh);
int vkp_pass_begin(int scene_w, int scene_h, const struct vkp_draw *draws, int n, int *rw, int *rh) {
return pass_begin_impl(scene_w, scene_h, draws, n, NULL, rw, rh);
return pass_begin_impl(scene_w, scene_h, draws, n, NULL, 0, rw, rh);
}
int vkp_pass_begin_generate(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *rw, int *rh) {
if (pass_begin_impl(scene_w, scene_h, draws, n, hf, 1, rw, rh) != 0) return -1;
return g_pass.ngen;
}
int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *rw, int *rh) {
if (!hf) return -1;
return pass_begin_impl(scene_w, scene_h, draws, n, hf, rw, rh);
return pass_begin_impl(scene_w, scene_h, draws, n, hf, 0, rw, rh);
}
static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *rw, int *rh) {
const struct vkp_hdr_frame *hf, int generate, int *rw, int *rh) {
if (g_pass.active) vkp_pass_abort();
g_pass.ngen = 0;
if (vkp_update_map(scene_w, scene_h) != 0) return -1;
int input_w = scene_w, input_h = scene_h;
int pass_n = n, overlay_start = n;
@@ -2588,13 +2795,31 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
effects_source_note(scene_w, scene_h, draws, n, input_w, input_h,
(int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f));
}
if (hf) {
const int deep = hf && generate && !hf->tonemap && vkp_framegen_format_ok(FG_HDR_FMT) &&
ensure_img(&g_fgscene, scene_w, scene_h, FG_HDR_FMT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
"HDR frame generation (scene)") == 0;
const int narrow = hf && generate && !deep;
if (hf && !deep && !narrow) {
if (ensure_img(&g_hdrscene, scene_w, scene_h, HDR_FMT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
"HDR composition (picture)") != 0)
return -1;
} else if (ensure_scene_image(input_w, input_h) != 0) return -1;
} else if (!deep && ensure_scene_image(input_w, input_h) != 0) return -1;
const VkFormat scene_fmt = deep ? FG_HDR_FMT : narrow || !hf ? SCENE_FMT : HDR_FMT;
if (hf && generate) {
static int said = -1;
if (said != deep + 2 * hf->tonemap) {
said = deep + 2 * hf->tonemap;
droiddeck_log("color", hf->tonemap
? "frame generation runs on the tone-mapped picture in 8 bits, onto the game's display layer"
: deep ? "frame generation runs on the HDR picture in FP16 (RGBA16F), onto the game's display layer"
: "frame generation runs on the HDR picture in 8 bits (the engine cannot take FP16 here), onto "
"the game's display layer: banding possible in smooth gradients");
}
}
VkCommandBuffer cmd = g_cmds[0];
g_vk.ResetCommandBuffer(cmd, 0);
@@ -2602,12 +2827,13 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi);
blendp_begin_frame();
stage_linear_dmabufs(cmd, draws, n);
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageMemoryBarrier *bars = calloc((size_t)n + 1, sizeof(*bars));
if (!bars) { g_vk.EndCommandBuffer(cmd); return -1; }
int nb = 0;
VkImage scene_img = hf ? g_hdrscene.img : g_scene.img;
VkImage scene_img = deep ? g_fgscene.img : narrow || !hf ? g_scene.img : g_hdrscene.img;
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
@@ -2620,7 +2846,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
if (seen || !im) continue;
struct vkp_external_client_barrier_pair pair;
if (vkp_external_client_barrier_pair(
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
im->image, g_qfam, foreign_image(im), im->blit_dst, &pair)) {
bars[nb++] = pair.acquire;
} else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
@@ -2638,12 +2864,12 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
free(bars);
if (hf) {
if (compose_hdr(cmd, draws, n, hf, scene_w, scene_h, g_hdrscene.img, HDR_FMT,
if (compose_hdr(cmd, draws, n, hf, scene_w, scene_h, scene_img, scene_fmt,
hf->tonemap ? HDRC_OUT_SDR : HDRC_OUT_PQ) != 0) {
g_vk.EndCommandBuffer(cmd);
return -1;
}
if (vkp_effects_active()) vkp_effects_set_formats(HDR_FMT, HDR_FMT);
if (vkp_effects_active()) vkp_effects_set_formats(scene_fmt, scene_fmt);
} else {
VkClearColorValue black = {.float32 = {0.0f, 0.0f, 0.0f, 1.0f}};
g_vk.CmdClearColorImage(cmd, g_scene.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range);
@@ -2662,53 +2888,57 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
}
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
if (generate && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; }
g_pass.rw = input_w; g_pass.rh = input_h;
g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h,
&g_pass.rw, &g_pass.rh);
effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h,
draws ? draws + overlay_start : NULL, n - overlay_start);
release_external_client_draws(cmd, draws, n);
if (generate) {
VkImageMemoryBarrier b = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = g_pass.result, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0, 0, NULL, 0, NULL, 1, &b);
int ngen = vkp_framegen_run(cmd, g_pass.result, VK_NULL_HANDLE, g_pass.rw, g_pass.rh, scene_fmt, g_pass.gens);
if (ngen < 0) ngen = 0;
g_pass.ngen = ngen > VKP_FG_MAX_GENERATIONS ? VKP_FG_MAX_GENERATIONS : ngen;
}
g_pass.active = 1;
if (rw) *rw = g_pass.rw;
if (rh) *rh = g_pass.rh;
return 0;
}
int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp_image *const *dsts, int n,
int wait_fd) {
if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; }
g_pass.active = 0;
if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; }
VkCommandBuffer cmd = g_cmds[0];
if (!dst || !dst->blit_dst) {
for (int i = 0; i < n; i++) {
if (dsts[i] && dsts[i]->blit_dst) continue;
if (wait_fd >= 0) close(wait_fd);
g_vk.EndCommandBuffer(cmd);
return -1;
}
const int gpu_wait = take_wait_fd(wait_fd);
if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; }
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageMemoryBarrier acq = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range,
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &acq);
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}};
g_vk.CmdBlitImage(cmd, g_pass.result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
for (int i = 0; i < n; i++) {
struct vkp_image *dst = dsts[i];
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}};
blit_to_layer(cmd, srcs[i], src_layout, dst, &blit,
(g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &rel);
}
g_vk.EndCommandBuffer(cmd);
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
@@ -2728,6 +2958,19 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
return 0;
}
int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
return pass_finish(&g_pass.result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, &dst, 1, wait_fd);
}
int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_image *real, int wait_fd) {
VkImage srcs[VKP_FG_MAX_GENERATIONS + 1];
struct vkp_image *all[VKP_FG_MAX_GENERATIONS + 1];
if (n > g_pass.ngen) n = g_pass.ngen;
for (int i = 0; i < n; i++) { srcs[i] = g_pass.gens[i]; all[i] = dsts[i]; }
if (real) { srcs[n] = g_pass.result; all[n] = real; }
return pass_finish(srcs, VK_IMAGE_LAYOUT_GENERAL, all, n + (real ? 1 : 0), wait_fd);
}
void vkp_pass_abort(void) {
if (!g_pass.active) return;
g_pass.active = 0;
@@ -96,6 +96,7 @@ struct vkp_hdr_frame {
float peak_nits;
int tonemap;
const struct droiddeck_color *color;
const struct droiddeck_color *convert;
};
int vkp_render_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *how);
@@ -106,7 +107,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd);
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px);
int vkp_update_map(int scene_w, int scene_h);
int vkp_map_draw(const struct vkp_draw *d, int out[8]);
int vkp_map_rect(int img_w, int img_h, int scene_w, int scene_h, int out[8]);
int vkp_map_rect(int img_w, int img_h, const int dst[4], int out[8]);
int vkp_surface_rotation_degrees(void);
ANativeWindow *vkp_window(void);
@@ -114,6 +115,9 @@ void vkp_signal_first_frame(void);
int vkp_pass_begin(int scene_w, int scene_h, const struct vkp_draw *draws, int n, int *rw, int *rh);
int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd);
int vkp_pass_begin_generate(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *rw, int *rh);
int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_image *real, int wait_fd);
void vkp_pass_abort(void);
void droiddeck_log(const char *tag, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
@@ -34,11 +34,13 @@ extern int droiddeck_cursor_input_pos(int *x, int *y);
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
extern void droiddeck_wayland_set_cursor_composite(int on);
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
extern void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns);
extern void droiddeck_stream_set(int on);
extern void droiddeck_stream_frame(AHardwareBuffer *ahb);
extern unsigned droiddeck_stream_frames(void);
extern void droiddeck_wayland_output_resized(void);
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
extern void droiddeck_wayland_set_panel_rates(const int *rates, int count);
extern volatile int g_fps_limit;
extern volatile int g_release_unpaced;
extern volatile int g_render_on_commit;
@@ -48,6 +50,8 @@ extern volatile int g_hide_shell;
extern volatile int g_zero_copy;
extern volatile unsigned g_zero_copy_last;
extern volatile int g_ubwc;
extern volatile int g_display_buffer_driver;
void droiddeck_dmabuf_formats_stale(void);
extern volatile int g_no_render_node;
extern volatile int g_output_w, g_output_h;
@@ -59,10 +63,14 @@ static jclass g_compositor_cls;
static jmethodID g_on_first_frame;
static jmethodID g_on_game_surface;
static jmethodID g_on_game_frame;
static jmethodID g_on_compositor_frame;
static jmethodID g_on_game_program;
static jmethodID g_on_pointer_lock;
static jmethodID g_on_clipboard;
static jmethodID g_on_text_input;
static jmethodID g_on_overlay_planes;
static jmethodID g_on_refresh_target;
static jmethodID g_on_content_rate;
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
(void)reserved;
@@ -77,6 +85,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
g_on_game_surface = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameSurface",
"(Ljava/lang/String;Ljava/lang/String;)V");
g_on_game_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameFrame", "()V");
g_on_compositor_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onCompositorFrame", "()V");
g_on_game_program = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameProgram",
"(ILjava/lang/String;)V");
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; }
@@ -84,6 +93,9 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
g_on_clipboard = (*env)->GetStaticMethodID(env, g_compositor_cls, "onClipboardText", "([B)V");
g_on_text_input = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInput",
"(ZLjava/lang/String;IIII)V");
g_on_overlay_planes = (*env)->GetStaticMethodID(env, g_compositor_cls, "onOverlayPlanes", "(I)V");
g_on_refresh_target = (*env)->GetStaticMethodID(env, g_compositor_cls, "onRefreshTarget", "(II)V");
g_on_content_rate = (*env)->GetStaticMethodID(env, g_compositor_cls, "onContentRate", "(I)V");
}
}
return JNI_VERSION_1_6;
@@ -144,6 +156,34 @@ void droiddeck_on_game_frame(void) {
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
}
void droiddeck_on_compositor_frame(void) {
JNIEnv *env;
if (!g_compositor_cls || !g_on_compositor_frame || !(env = thread_env())) return;
(*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_compositor_frame);
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
}
void droiddeck_on_refresh_target(int refresh, int frame_rate) {
JNIEnv *env;
if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return;
(*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_refresh_target, (jint)refresh, (jint)frame_rate);
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
}
void droiddeck_on_content_rate(int fps) {
JNIEnv *env;
if (!g_compositor_cls || !g_on_content_rate || !(env = thread_env())) return;
(*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_content_rate, (jint)fps);
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
}
void droiddeck_on_overlay_planes(int planes) {
JNIEnv *env;
if (!g_compositor_cls || !g_on_overlay_planes || !(env = thread_env())) return;
(*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_overlay_planes, (jint)planes);
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
}
void droiddeck_on_pointer_lock(int locked, int x, int y) {
JNIEnv *env;
if (!g_compositor_cls || !g_on_pointer_lock || !(env = thread_env())) return;
@@ -365,6 +405,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeVsync(JNIEnv *env, j
droiddeck_wayland_vsync((int64_t)frameTimeNanos);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameTimeline(JNIEnv *env, jclass clazz, jlong presentNanos,
jlong deadlineNanos, jlong periodNanos) {
sc_layer_frame_timeline((int64_t)presentNanos, (int64_t)deadlineNanos, (int64_t)periodNanos);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetClockControl(JNIEnv *env, jclass clazz, jstring path) {
const char *value = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL;
@@ -380,11 +426,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHideShell(JNIEnv
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *env, jclass clazz, jboolean on) {
int live = droiddeck_get_display() != NULL;
if (!live) g_zero_copy = on ? 1 : 0;
if (!live) { g_zero_copy = on ? 1 : 0; droiddeck_dmabuf_formats_stale(); }
droiddeck_host_zero_copy(on ? 1 : 0, live);
__android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : "");
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) {
g_display_buffer_driver = on ? 1 : 0;
droiddeck_dmabuf_formats_stale();
__android_log_print(ANDROID_LOG_INFO, TAG, "session driver %s for display buffers", on ? "asks" : "does not ask");
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeZeroCopyLastFrameAgeMs(JNIEnv *env, jclass clazz) {
return (jint)ahb_swapchain_last_frame_age_ms();
@@ -418,6 +471,16 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetOutputRefreshRate
droiddeck_wayland_set_output_refresh_rate(hz > 1.0f ? (int)(hz * 1000.0f + 0.5f) : 0);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetPanelRates(JNIEnv *env, jclass clazz, jintArray rates) {
(void)clazz;
jint values[16];
jsize count = rates ? (*env)->GetArrayLength(env, rates) : 0;
if (count > 16) count = 16;
if (count > 0) (*env)->GetIntArrayRegion(env, rates, 0, count, values);
droiddeck_wayland_set_panel_rates((const int *)values, (int)count);
}
extern void vkp_reset_first_frame(void);
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeResetFirstFrame(JNIEnv *env, jclass clazz) {
@@ -497,8 +560,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
+176 -31
View File
@@ -84,15 +84,18 @@ static struct {
static _Atomic int g_gate = -1;
static char g_gate_why[320];
static _Atomic int g_output_on = 1;
static _Atomic int g_output_wanted = 1;
static pthread_mutex_t g_output_mu = PTHREAD_MUTEX_INITIALIZER;
void droiddeck_color_set_request(int mode, const char *source, int dxvk_hdr, int zero_copy_forced) {
pthread_mutex_lock(&g_mu);
g_req.mode = mode < 0 ? 0 : mode > 2 ? 2 : mode;
g_req.mode = mode < 0 ? 0 : mode > 3 ? 3 : mode;
snprintf(g_req.source, sizeof(g_req.source), "%s", source ? source : "environment");
g_req.dxvk_hdr = dxvk_hdr ? 1 : 0;
g_req.zero_copy_forced = zero_copy_forced ? 1 : 0;
pthread_mutex_unlock(&g_mu);
atomic_store(&g_output_on, 1);
atomic_store(&g_output_wanted, 1);
}
void droiddeck_color_set_display(int id, const char *name, const char *formats, int hdr10, float max_lum,
@@ -610,11 +613,23 @@ int droiddeck_color_tonemapped_on_screen(void) {
void droiddeck_color_set_output(int on) {
on = on ? 1 : 0;
if (atomic_load(&g_gate) != 1) {
droiddeck_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off");
pthread_mutex_lock(&g_mu);
const int tonemap_only = g_req.mode == 3;
pthread_mutex_unlock(&g_mu);
pthread_mutex_lock(&g_output_mu);
atomic_store(&g_output_wanted, on);
const int gate = atomic_load(&g_gate);
const int changed = gate == 1 && !(on && tonemap_only) && atomic_exchange(&g_output_on, on) != on;
pthread_mutex_unlock(&g_output_mu);
if (gate != 1) {
if (gate == 0) droiddeck_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off");
return;
}
if (atomic_exchange(&g_output_on, on) == on) return;
if (on && tonemap_only) {
droiddeck_log(TAG, "HDR output switch (on) ignored: this display cannot show HDR10, HDR frames stay tone-mapped");
return;
}
if (!changed) return;
char who[160];
int age = droiddeck_color_last_frame_age_ms(), tm = droiddeck_color_tonemapped_on_screen();
pthread_mutex_lock(&g_mu);
@@ -658,6 +673,8 @@ static void desc_unref(struct cm_desc *d) { if (d && --d->refs <= 0) free(d); }
struct cm_params {
uint32_t tf, primaries;
int has_prim; int32_t prim[8];
int has_lum; uint32_t lum_ref;
int has_mprim; int32_t mprim[8];
int has_mlum; uint32_t mlum_min, mlum_max;
int has_cll; uint32_t cll;
@@ -730,9 +747,83 @@ static void make_output_description(struct wl_client *c, struct wl_resource *par
droiddeck_client_name(c), what, col->text);
}
static const float BT709_XY[8] = {0.64f, 0.33f, 0.30f, 0.60f, 0.15f, 0.06f, 0.3127f, 0.3290f};
static const float BT2020_XY[8] = {0.708f, 0.292f, 0.170f, 0.797f, 0.131f, 0.046f, 0.3127f, 0.3290f};
static void mat_mul(const double a[9], const double b[9], double out[9]) {
double m[9];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
m[3 * i + j] = a[3 * i] * b[j] + a[3 * i + 1] * b[3 + j] + a[3 * i + 2] * b[6 + j];
memcpy(out, m, sizeof(m));
}
static int mat_invert(const double m[9], double out[9]) {
const double det = m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) +
m[2] * (m[3] * m[7] - m[4] * m[6]);
if (det > -1e-12 && det < 1e-12) return -1;
const double k = 1.0 / det;
double r[9] = {(m[4] * m[8] - m[5] * m[7]) * k, (m[2] * m[7] - m[1] * m[8]) * k, (m[1] * m[5] - m[2] * m[4]) * k,
(m[5] * m[6] - m[3] * m[8]) * k, (m[0] * m[8] - m[2] * m[6]) * k, (m[2] * m[3] - m[0] * m[5]) * k,
(m[3] * m[7] - m[4] * m[6]) * k, (m[1] * m[6] - m[0] * m[7]) * k, (m[0] * m[4] - m[1] * m[3]) * k};
memcpy(out, r, sizeof(r));
return 0;
}
static int rgb_to_xyz(const float xy[8], double out[9], double white[3]) {
for (int i = 0; i < 4; i++)
if (xy[2 * i + 1] < 1e-4f) return -1;
double p[9], inv[9];
for (int i = 0; i < 3; i++) {
const double x = xy[2 * i], y = xy[2 * i + 1];
p[i] = x / y; p[3 + i] = 1.0; p[6 + i] = (1.0 - x - y) / y;
}
white[0] = xy[6] / xy[7]; white[1] = 1.0; white[2] = (1.0 - xy[6] - xy[7]) / xy[7];
if (mat_invert(p, inv) != 0) return -1;
for (int i = 0; i < 3; i++) {
const double scale = inv[3 * i] * white[0] + inv[3 * i + 1] * white[1] + inv[3 * i + 2] * white[2];
out[i] = p[i] * scale; out[3 + i] = p[3 + i] * scale; out[6 + i] = p[6 + i] * scale;
}
return 0;
}
static int matrix_to_bt2020(const float xy[8], float out[9]) {
static const double bradford[9] = {0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296};
double src[9], dst[9], dst_inv[9], sw[3], dw[3], cone_inv[9], adapt[9], m[9];
if (rgb_to_xyz(xy, src, sw) != 0 || rgb_to_xyz(BT2020_XY, dst, dw) != 0) return -1;
if (mat_invert(dst, dst_inv) != 0 || mat_invert(bradford, cone_inv) != 0) return -1;
double scale[9] = {0};
for (int i = 0; i < 3; i++) {
const double from = bradford[3 * i] * sw[0] + bradford[3 * i + 1] * sw[1] + bradford[3 * i + 2] * sw[2];
const double to = bradford[3 * i] * dw[0] + bradford[3 * i + 1] * dw[1] + bradford[3 * i + 2] * dw[2];
if (from > -1e-9 && from < 1e-9) return -1;
scale[4 * i] = to / from;
}
mat_mul(scale, bradford, adapt);
mat_mul(cone_inv, adapt, adapt);
mat_mul(adapt, src, m);
mat_mul(dst_inv, m, m);
for (int i = 0; i < 9; i++) out[i] = (float)m[i];
return 0;
}
static struct wl_resource *publish_description(struct wl_client *client, struct wl_resource *parent, uint32_t id,
struct cm_desc *d) {
struct wl_resource *out = wl_resource_create(client, &wp_image_description_v1_interface,
wl_resource_get_version(parent), id);
if (!out) { free(d); wl_client_post_no_memory(client); return NULL; }
d->refs = 1;
wl_resource_set_implementation(out, &image_description_impl, d, image_description_resource_destroy);
wp_image_description_v1_send_ready(out, d->c.identity);
pthread_mutex_lock(&g_mu);
g_hdr.descs++;
pthread_mutex_unlock(&g_mu);
return out;
}
static void params_create(struct wl_client *client, struct wl_resource *r, uint32_t id) {
struct cm_params *p = wl_resource_get_user_data(r);
if (!p->tf || !p->primaries) {
if (!p->tf || (!p->primaries && !p->has_prim)) {
wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INCOMPLETE_SET,
"transfer function and primaries must both be set");
return;
@@ -744,10 +835,29 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3
if (!g_next_identity) g_next_identity = 1;
c->primaries = p->primaries;
c->tf = p->tf;
if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ)
const float ref = p->has_lum ? (float)p->lum_ref : 203.0f;
float xy[8];
for (int i = 0; i < 8; i++)
xy[i] = p->has_prim ? p->prim[i] / 1e6f
: p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_SRGB ? BT709_XY[i] : BT2020_XY[i];
if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && ref == 203.0f) {
c->dataspace = DROIDDECK_ADATASPACE_BT2020_PQ;
else if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_HLG)
c->dataspace = DROIDDECK_ADATASPACE_BT2020_HLG;
} else if (matrix_to_bt2020(xy, c->to2020) == 0) {
c->convert = 1;
c->gain = 10000.0f * 203.0f / ref;
} else {
struct wl_resource *bad = wl_resource_create(client, &wp_image_description_v1_interface,
wl_resource_get_version(r), id);
free(d);
if (!bad) { wl_client_post_no_memory(client); return; }
wl_resource_set_implementation(bad, &image_description_impl, NULL, NULL);
wp_image_description_v1_send_failed(bad, WP_IMAGE_DESCRIPTION_V1_CAUSE_UNSUPPORTED,
"the primaries do not form a colour space");
droiddeck_log(TAG, "image description from %s refused: its primaries do not form a colour space",
droiddeck_client_name(client));
wl_resource_destroy(r);
return;
}
char dropped[160] = "";
float mlum_min = 0.005f, mlum_max = 10000.0f;
@@ -781,7 +891,12 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3
}
if (cll > 0.0f || fall > 0.0f) { c->has_cta861 = 1; c->max_cll = cll; c->max_fall = fall; }
int n = snprintf(c->text, sizeof(c->text), "%s, %s", primaries_name(c->primaries), tf_name(c->tf));
int n = snprintf(c->text, sizeof(c->text), "%s, %s", p->has_prim ? "custom primaries" : primaries_name(c->primaries),
tf_name(c->tf));
if (c->convert && n < (int)sizeof(c->text))
n += snprintf(c->text + n, sizeof(c->text) - (size_t)n,
"; R %.4f,%.4f G %.4f,%.4f B %.4f,%.4f W %.4f,%.4f, reference white %.0f nits",
xy[0], xy[1], xy[2], xy[3], xy[4], xy[5], xy[6], xy[7], ref);
if (c->has_st2086 && n < (int)sizeof(c->text))
n += snprintf(c->text + n, sizeof(c->text) - (size_t)n,
"; mastering R %.4f,%.4f G %.4f,%.4f B %.4f,%.4f W %.4f,%.4f, %.4f-%.0f nits%s",
@@ -793,19 +908,13 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3
if (!c->has_st2086 && !c->has_cta861 && n < (int)sizeof(c->text))
snprintf(c->text + n, sizeof(c->text) - (size_t)n, " (no HDR metadata: the game has not called vkSetHdrMetadataEXT)");
struct wl_resource *out = wl_resource_create(client, &wp_image_description_v1_interface,
wl_resource_get_version(r), id);
if (!out) { free(d); wl_client_post_no_memory(client); return; }
d->refs = 1;
wl_resource_set_implementation(out, &image_description_impl, d, image_description_resource_destroy);
wp_image_description_v1_send_ready(out, c->identity);
if (c->dataspace) {
pthread_mutex_lock(&g_mu);
g_hdr.descs++;
pthread_mutex_unlock(&g_mu);
}
droiddeck_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity,
droiddeck_client_name(client), c->text, dataspace_name(c->dataspace));
if (!publish_description(client, r, id, d)) return;
if (c->convert)
droiddeck_log(TAG, "image description #%u from %s: %s -> ready (converted to BT.2020 PQ when the scene is "
"composed)", c->identity, droiddeck_client_name(client), c->text);
else
droiddeck_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity,
droiddeck_client_name(client), c->text, dataspace_name(c->dataspace));
if (dropped[0]) {
size_t l = strlen(dropped);
if (l && dropped[l - 1] == ',') dropped[l - 1] = 0;
@@ -840,8 +949,8 @@ static void params_set_tf_power(struct wl_client *c, struct wl_resource *r, uint
}
static void params_set_primaries_named(struct wl_client *c, struct wl_resource *r, uint32_t primaries) {
struct cm_params *p = wl_resource_get_user_data(r);
PARAMS_ONCE(p->primaries, "primaries");
if (primaries != WP_COLOR_MANAGER_V1_PRIMARIES_BT2020) {
PARAMS_ONCE(p->primaries || p->has_prim, "primaries");
if (primaries != WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && primaries != WP_COLOR_MANAGER_V1_PRIMARIES_SRGB) {
wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_PRIMARIES_NAMED,
"primaries %u were not advertised", primaries);
return;
@@ -850,12 +959,21 @@ static void params_set_primaries_named(struct wl_client *c, struct wl_resource *
}
static void params_set_primaries(struct wl_client *c, struct wl_resource *r, int32_t rx, int32_t ry, int32_t gx,
int32_t gy, int32_t bx, int32_t by, int32_t wx, int32_t wy) {
wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE,
"set_primaries is not supported");
struct cm_params *p = wl_resource_get_user_data(r);
PARAMS_ONCE(p->primaries || p->has_prim, "primaries");
p->has_prim = 1;
p->prim[0] = rx; p->prim[1] = ry; p->prim[2] = gx; p->prim[3] = gy;
p->prim[4] = bx; p->prim[5] = by; p->prim[6] = wx; p->prim[7] = wy;
}
static void params_set_luminances(struct wl_client *c, struct wl_resource *r, uint32_t mn, uint32_t mx, uint32_t ref) {
wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE,
"set_luminances is not supported");
struct cm_params *p = wl_resource_get_user_data(r);
PARAMS_ONCE(p->has_lum, "luminances");
if ((uint64_t)mx * 10000u <= mn || (uint64_t)ref * 10000u <= mn) {
wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_LUMINANCE,
"maximum and reference luminance must be above the minimum");
return;
}
p->has_lum = 1; p->lum_ref = ref;
}
static void params_set_mastering_display_primaries(struct wl_client *c, struct wl_resource *r, int32_t rx, int32_t ry,
int32_t gx, int32_t gy, int32_t bx, int32_t by, int32_t wx, int32_t wy) {
@@ -1083,7 +1201,20 @@ static void cm_create_parametric_creator(struct wl_client *c, struct wl_resource
}
static void cm_create_windows_scrgb(struct wl_client *c, struct wl_resource *r, uint32_t id) {
wl_resource_post_error(r, WP_COLOR_MANAGER_V1_ERROR_UNSUPPORTED_FEATURE, "windows_scrgb is not supported");
struct cm_desc *d = calloc(1, sizeof(*d));
if (!d) { wl_client_post_no_memory(c); return; }
struct droiddeck_color *col = &d->c;
col->identity = g_next_identity++;
if (!g_next_identity) g_next_identity = 1;
col->primaries = WP_COLOR_MANAGER_V1_PRIMARIES_SRGB;
col->tf = WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_EXT_LINEAR;
col->convert = 2;
col->gain = 80.0f;
matrix_to_bt2020(BT709_XY, col->to2020);
snprintf(col->text, sizeof(col->text), "%s, %s (1.0 = 80 nits)", primaries_name(col->primaries), tf_name(col->tf));
if (!publish_description(c, r, id, d)) return;
droiddeck_log(TAG, "image description #%u from %s: %s -> ready (converted to BT.2020 PQ when the scene is composed)",
col->identity, droiddeck_client_name(c), col->text);
}
static const struct wp_color_manager_v1_interface cm_impl = {
@@ -1103,14 +1234,20 @@ static void bind_cm(struct wl_client *c, void *data, uint32_t ver, uint32_t id)
wl_resource_set_implementation(r, &cm_impl, NULL, NULL);
wp_color_manager_v1_send_supported_intent(r, WP_COLOR_MANAGER_V1_RENDER_INTENT_PERCEPTUAL);
wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_PARAMETRIC);
wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_PRIMARIES);
wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_LUMINANCES);
wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_MASTERING_DISPLAY_PRIMARIES);
wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_EXTENDED_TARGET_VOLUME);
wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_WINDOWS_SCRGB);
wp_color_manager_v1_send_supported_primaries_named(r, WP_COLOR_MANAGER_V1_PRIMARIES_SRGB);
wp_color_manager_v1_send_supported_primaries_named(r, WP_COLOR_MANAGER_V1_PRIMARIES_BT2020);
wp_color_manager_v1_send_supported_tf_named(r, WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ);
wp_color_manager_v1_send_done(r);
if (last_named != c) {
last_named = c;
droiddeck_log(TAG, "%s bound wp_color_manager_v1 version %u (offered: perceptual intent; parametric descriptions "
"with mastering metadata; BT.2020 primaries; ST 2084 PQ) - its Vulkan driver can now list "
"with custom primaries, luminances and mastering metadata; Windows scRGB; sRGB and BT.2020 primaries; "
"ST 2084 PQ) - its Vulkan driver can now list "
"VK_COLOR_SPACE_HDR10_ST2084_EXT", droiddeck_client_name(c), ver > 1 ? 1u : ver);
}
}
@@ -1150,6 +1287,7 @@ void droiddeck_color_init(struct wl_display *display) {
char asked[128];
if (mode == 2) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=force (%s)", source);
else if (mode == 3) snprintf(asked, sizeof(asked), "HDR is on, tone-mapped for this display (%s)", source);
else if (strstr(source, "env")) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=1 (%s)", source);
else snprintf(asked, sizeof(asked), "HDR output is on (%s)", source);
@@ -1168,7 +1306,7 @@ void droiddeck_color_init(struct wl_display *display) {
snprintf(why, sizeof(why), "this Android has no display layers with dataspace control "
"(ASurfaceControl + ASurfaceTransaction_setBufferDataSpace, Android 10+)");
else if (!ahb_ok)
snprintf(why, sizeof(why), "zero-copy presentation is unavailable here (banner_ahb_v1 not advertised), and an "
snprintf(why, sizeof(why), "zero-copy presentation is unavailable here (droiddeck_ahb_v1 not advertised), and an "
"HDR frame is only honest on the game's own display layer");
if (why[0]) {
@@ -1198,13 +1336,20 @@ void droiddeck_color_init(struct wl_display *display) {
log_verdict(1);
return;
}
pthread_mutex_lock(&g_output_mu);
atomic_store(&g_gate, 1);
if (mode == 3 || !atomic_load(&g_output_wanted)) atomic_store(&g_output_on, 0);
pthread_mutex_unlock(&g_output_mu);
char syms[160];
sc_layer_hdr_symbols(syms, sizeof(syms));
droiddeck_log(TAG, "HDR gate %s: %s and %s. Offering games HDR10: wp_color_manager_v1 version 1 (BT.2020 primaries "
"+ ST 2084 PQ, parametric descriptions with mastering metadata) and 10-bit AB30/XB30 dma-buf formats; HDR "
"frames go on the game's own display layer as BT2020_PQ (%s)",
mode == 2 ? "FORCED OPEN (testing)" : "OPEN", asked, disp, syms);
if (mode == 3) {
droiddeck_log(TAG, "this display cannot show HDR10: games still render HDR and every HDR frame is tone-mapped to "
"SDR on the game's display layer");
}
if (mode == 2 && !hdr10)
droiddeck_log(TAG, "DROIDDECK_WAYLAND_HDR=force on a display without HDR10 - testing only: SurfaceFlinger will tone-map "
"the game layer for this panel (expect GPU/CLIENT composition for it), nothing looks HDR");
+18 -3
View File
@@ -14,6 +14,7 @@
#include "droiddeck_ext.h"
#include "droiddeck_color.h"
#include "compositor_internal.h"
#include "display_buffers.h"
static void dbuf_buffer_resource_destroy(struct wl_resource *r) {
@@ -58,6 +59,7 @@ static struct wl_resource *params_do_create(struct wl_client *c, struct wl_resou
wl_resource_set_implementation(buf, &dbuf_buffer_impl, b, dbuf_buffer_resource_destroy);
struct client_info *ci = client_info_of(c);
if (ci) ci->dmabuf_buffers++;
display_buffers_match(c, buf, b);
return buf;
}
static void params_create(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h,
@@ -111,13 +113,16 @@ static const struct zwp_linux_dmabuf_v1_interface dmabuf_impl = {
static struct { uint32_t fmt; uint64_t mods[DMABUF_NMOD]; int n; } g_dmabuf_fmts[DMABUF_NFMT_MAX] = {
{DRM_ARGB8888}, {DRM_XRGB8888}, {DRM_ABGR8888}, {DRM_XBGR8888}, {DRM_ABGR2101010}, {DRM_XBGR2101010}};
static int g_dmabuf_nfmt = DMABUF_NFMT_SDR;
static int g_dmabuf_fmts_ready;
static volatile int g_dmabuf_fmts_ready;
static void dmabuf_build_feedback(void);
void droiddeck_dmabuf_formats_stale(void) { g_dmabuf_fmts_ready = 0; }
static void dmabuf_build_formats(void) {
char line[320];
int pos = 0, compressed = 0;
int pos = 0, compressed = 0, backed = 0;
g_dmabuf_fmts_ready = 1;
display_buffers_withdraw_ubwc();
g_dmabuf_nfmt = droiddeck_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR;
for (int f = 0; f < g_dmabuf_nfmt; f++) {
uint64_t got[DMABUF_NMOD];
@@ -129,6 +134,12 @@ static void dmabuf_build_formats(void) {
g_dmabuf_fmts[f].mods[k++] = got[i];
if (got[i] == VKP_MOD_QCOM_COMPRESSED) compressed++;
}
int listed = 0;
for (int i = 0; i < k; i++) if (g_dmabuf_fmts[f].mods[i] == VKP_MOD_QCOM_COMPRESSED) listed = 1;
if (display_buffers_offer_ubwc(g_dmabuf_fmts[f].fmt) && !listed) {
g_dmabuf_fmts[f].mods[k++] = VKP_MOD_QCOM_COMPRESSED;
backed++;
}
g_dmabuf_fmts[f].mods[k++] = MOD_INVALID;
g_dmabuf_fmts[f].n = k;
uint32_t fmt = g_dmabuf_fmts[f].fmt;
@@ -141,7 +152,10 @@ static void dmabuf_build_formats(void) {
}
droiddeck_log("dmabuf", "formats: %s%s", line,
!g_ubwc ? " (DROIDDECK_WAYLAND_UBWC=0: qcom_compressed not advertised)" : "");
if (g_ubwc && !compressed)
if (backed)
droiddeck_log("dmabuf", "qcom_compressed is advertised for %d formats the compositor's driver (%s) does not "
"import as dma-bufs: this session's driver renders them into gralloc buffers", backed, vkp_gpu_name());
else if (g_ubwc && !compressed)
droiddeck_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: "
"game swapchains stay linear", vkp_gpu_name());
if (g_dmabuf_nfmt > DMABUF_NFMT_SDR) {
@@ -212,6 +226,7 @@ static void dmabuf_build_feedback(void) {
return;
}
fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
if (g_fmt_table_fd >= 0) close(g_fmt_table_fd);
g_fmt_table_fd = fd;
g_fmt_table_size = size;
g_fmt_table_n = (uint16_t)n;
@@ -21,6 +21,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
@@ -43,15 +44,18 @@ 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.DrawerPages.load(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
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)
@@ -94,6 +98,8 @@ class App : Application() {
com.droiddeck.launcher.session.SessionFiles.ensureUbisoftService(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.ROCKSTAR) != null)
com.droiddeck.launcher.session.SessionFiles.ensureRockstarService(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.EPIC) != null)
com.droiddeck.launcher.session.SessionFiles.ensureEpicParent(app)
com.droiddeck.launcher.handtracking.HandTracking.load(app)
}.onFailure { android.util.Log.w("App", "add-on pack prefetch failed", it) }
}, "addon-packs").start()
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
checkAgain = null
checkComponentUpdates(again)
}
if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; "))
refreshComponents()
}
}, "component-updates").start()
@@ -6,6 +6,7 @@ import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.runtime.DeckyStore
import com.droiddeck.launcher.session.SessionState
import java.io.File
@@ -21,6 +22,59 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
var deckySupervisor by mutableStateOf(false)
var deckyPendingZip by mutableStateOf<File?>(null)
var deckyReleaseRequest = 0
var deckyPlugins by mutableStateOf<List<DeckyStore.Installed>>(emptyList())
var deckyStore by mutableStateOf<List<DeckyStore.Plugin>?>(null)
var deckyStoreFailed by mutableStateOf(false)
private var storeRequest = 0
fun refreshPlugins() {
Thread({
val found = DeckyStore.installed(activity)
ui.post { deckyPlugins = found }
}, "decky-plugins").start()
}
fun refreshStore() {
val request = ++storeRequest
deckyStore = null; deckyStoreFailed = false
Thread({
val listing = DeckyStore.fetch()
ui.post {
if (request != storeRequest) return@post
deckyStore = listing.orEmpty(); deckyStoreFailed = listing == null
}
}, "decky-store").start()
}
fun installStorePlugin(plugin: DeckyStore.Plugin) {
val version = plugin.latest ?: return
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1
Thread({
val problem = runCatching {
DeckyStore.install(activity, plugin, version) { label, value ->
val binary = DeckyManager.downloadingBinary
ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary }
}
}.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) }
ui.post {
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.decky_plugin_installed), android.widget.Toast.LENGTH_LONG).show()
refreshPlugins()
}
}, "install-decky-store").start()
}
fun removePlugin(plugin: DeckyStore.Installed) {
if (deckyStage != null || SessionState.running) return
Thread({
val problem = DeckyStore.remove(activity, plugin)
ui.post {
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
refreshPlugins()
}
}, "remove-decky-plugin").start()
}
fun refreshDecky() {
val request = ++deckyReleaseRequest
@@ -90,6 +144,7 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
val message = problem ?: activity.getString(R.string.decky_plugin_installed)
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
refreshPlugins()
}
}, "import-decky-plugin").start()
}
@@ -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()
}
File diff suppressed because it is too large. Load diff
@@ -118,12 +118,18 @@ object HomeWidgets {
if (live.size != parsed.size) save(context)
}
private val listeners: MutableSet<Any> = java.util.Collections.newSetFromMap(java.util.IdentityHashMap())
fun startListening(context: Context) {
listeners.add(context)
load(context)
runCatching { host(context).startListening() }
}
// A restarted launcher starts before the old one stops; the host keeps listening until the last owner stops.
fun stopListening(context: Context) {
listeners.remove(context)
if (listeners.isNotEmpty()) return
runCatching { host(context).stopListening() }
}
@@ -0,0 +1,27 @@
package com.droiddeck.launcher
import android.os.Bundle
import android.os.SystemClock
/**
* State a restarting launcher passes to its replacement inside this process. Intent extras are not used
* because FrontEndActivity is exported and any app could fill them.
*/
internal object LauncherHandoff {
private const val LIFETIME_MS = 10_000L
private var state: Bundle? = null
private var at = 0L
@Synchronized
fun put(carried: Bundle) {
state = carried
at = SystemClock.elapsedRealtime()
}
@Synchronized
fun take(): Bundle? {
val carried = state
state = null
return carried?.takeIf { SystemClock.elapsedRealtime() - at <= LIFETIME_MS }
}
}
@@ -93,6 +93,14 @@ class PairingGuideActivity : ComponentActivity() {
launchPending = true
}
override fun onDestroy() {
super.onDestroy()
val stage = WirelessAdbPairingService.stage.value
if (isFinishing && (stage is WirelessAdbPairingService.Stage.Waiting || stage is WirelessAdbPairingService.Stage.CodeNeeded)) {
WirelessAdbPairingService.cancel(this)
}
}
override fun onResume() {
super.onResume()
if (!launchPending) return
@@ -7,7 +7,10 @@ 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.Onboarding
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.SteamClientPrefetch
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SessionPhase
@@ -19,6 +22,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,15 +31,25 @@ 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) }
{ tool, progress -> ProtonExtras.install(activity, tool, onProgress = progress) }
fun installProton(id: String, automatic: Boolean = false) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
@@ -48,10 +62,15 @@ internal class ProtonMenu(
Thread({
val problem = runCatching {
installer(tool) { label, value ->
if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value)
ui.post { protonStage = label; protonPercent = value }
}
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
if (tool.id == ProtonExtras.OWN) {
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
}
ui.post {
protonProblem = problem
protonBusyId = null
@@ -86,29 +105,118 @@ 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()
ensureSteamClient()
}
if (!published) Operation.checking.set(false)
}, "proton-updates").start()
}
/** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */
fun prefetchOwn() {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() ||
ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return
Thread({
val problem = runCatching {
ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) }
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
ui.post { ensureAutoUpdates() }
}, "proton-prefetch").start()
}
/** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */
fun ensureSteamClient() {
if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) ||
!AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return
SteamClientPrefetch.start(
activity,
{ mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) },
activity.getString(R.string.onboarding_steam_failed),
)
}
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return
val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty()
if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
protonBusyId = ProtonExtras.OWN
protonProblem = null
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
}
@@ -230,6 +230,20 @@ object AgentGuest {
call(context, JSONObject().put("kind", "cdp").put("expression", expression).put("timeout", timeoutMs / 1000.0),
timeoutMs + 2_000, trusted = true)
fun setGamescopeConvar(context: Context, name: String, value: Int): Boolean {
val request = JSONObject()
.put("kind", "exec")
.put("argv", org.json.JSONArray(listOf("gamescopectl", name, value.toString())))
.put("timeout", 5.0)
val result = runCatching { call(context, request, 8_000, trusted = true) }
val answer = result.getOrNull()
val applied = answer?.optBoolean("ok") == true
&& answer.optInt("exitCode", -1) == 0
&& !answer.optBoolean("timedOut")
if (!applied) Log.w(TAG, "gamescope did not take $name $value: ${result.exceptionOrNull() ?: answer}")
return applied
}
fun call(context: Context, request: JSONObject, timeoutMs: Long, trusted: Boolean = false): JSONObject {
if (!trusted && request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context)
if (!SessionState.running) throw AgentException("NO_ACTIVE_SESSION", "There is no running session")
@@ -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 -o APT::Update::Error-Mode=any update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
"apt -f install -y --fix-missing; " +
"apt install -y --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();
}
}
@@ -175,5 +175,6 @@ internal class AddonPack(
val ROCKSTAR = AddonPack("rockstar", BuildConfig.PACK_ROCKSTAR_SHA256, BuildConfig.PACK_ROCKSTAR_SIZE,
listOf("Launcher32.exe", "Launcher64.exe"))
val DIRT = AddonPack("dirt", BuildConfig.PACK_DIRT_SHA256, BuildConfig.PACK_DIRT_SIZE, listOf("ws2_32.dll"))
val EPIC = AddonPack("epic", BuildConfig.PACK_EPIC_SHA256, BuildConfig.PACK_EPIC_SIZE, listOf("EpicGamesLauncher.exe"))
}
}
@@ -53,6 +53,13 @@ object AppUiPrefs {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply()
}
fun pageSwipe(context: Context): Boolean =
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("page-swipe", true)
fun setPageSwipe(context: Context, on: Boolean) {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("page-swipe", on).apply()
}
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
fun scale(context: Context): Int = normalizeScale(
@@ -207,9 +207,11 @@ object DeviceReport {
k("refresh_rate_mode", runCatching { Settings.Secure.getString(context.contentResolver, "refresh_rate_mode") }.getOrNull() ?: "not set")
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context)
for ((label, mode) in listOf("Resolution (Steam)" to SessionService.MODE_STEAM, "Resolution (Desktop)" to SessionService.MODE_DESKTOP)) {
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize)
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice)
k(label, "$choice (${size.first}x${size.second})")
for ((suffix, portrait) in listOf("landscape" to false, "portrait" to true)) {
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize, portrait)
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice, portrait)
k("$label $suffix", "$choice (${size.first}x${size.second})")
}
}
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
@@ -281,9 +283,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))
@@ -292,7 +291,9 @@ object DeviceReport {
k("Guest host name", SessionPrefs.guestHostname(context))
k("DirectAudio for games", SessionPrefs.directAudio(context))
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
k("Avoid notch", SessionPrefs.avoidNotch(context))
k("Return to launcher after a game", SessionPrefs.returnAfterGame(context))
k("Valve Proton only when needed", SessionPrefs.valveProtonOnDemand(context))
k("Microphone", SessionPrefs.micEnabled(context))
k("On-screen controls", SessionPrefs.oscMode(context))
k("Touch mode", SessionPrefs.touchMode(context))
@@ -28,7 +28,9 @@ object DeviceSupport {
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
}
fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists()
fun bridgeUsable(): Boolean = bridgeUsable(adreno(), SystemVulkanDriver.isAvailable())
internal fun bridgeUsable(adreno: Boolean, systemDriverReady: Boolean): Boolean = !adreno && !systemDriverReady
fun openDriverActive(context: Context): Boolean {
if (adreno()) return false
@@ -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(),
@@ -16,7 +16,7 @@ object SteamIntegration {
const val EXTRA_FEATURE = "integration_feature"
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
private const val SHORTCUTS_ASSET = "shortcuts.apk"
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH }
data class State(
val wifi: Boolean = false,
@@ -28,6 +28,7 @@ object SteamIntegration {
val shortcuts: Boolean = false,
val shortcutsRestricted: Boolean = false,
val shortcutsTried: Boolean = false,
val bluetooth: Boolean = false,
val suggested: Boolean = true,
)
@@ -37,11 +38,18 @@ 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),
bluetooth = bluetoothAllowed(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
)
fun bluetoothAllowed(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S ||
context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
private fun restrictedSettings(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
val mode = runCatching {
@@ -61,6 +69,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")
}
@@ -38,6 +38,8 @@ class WirelessAdbPairingService : Service() {
private var pairingHost: String? = null
private var pairingPort: Int? = null
@Volatile private var working = false
@Volatile private var limitEnabled = false
@Volatile private var session = 0
private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) }
override fun onBind(intent: Intent?): IBinder? = null
@@ -50,12 +52,15 @@ class WirelessAdbPairingService : Service() {
onCode(code)
}
ACTION_CANCEL -> finish(Stage.Idle)
else -> begin()
else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true)
}
return START_NOT_STICKY
}
private fun begin() {
private fun begin(enableLimit: Boolean) {
if (working) return
session++
limitEnabled = enableLimit
pairingHost = null
pairingPort = null
working = false
@@ -68,12 +73,13 @@ class WirelessAdbPairingService : Service() {
private fun startDiscovery() {
stopDiscovery()
val owner = session
val manager = getSystemService(Context.NSD_SERVICE) as NsdManager
val listener = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String) = Unit
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return
runCatching { manager.resolveService(serviceInfo, resolveListener()) }
runCatching { manager.resolveService(serviceInfo, resolveListener(owner)) }
}
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
override fun onDiscoveryStopped(serviceType: String) = Unit
@@ -87,18 +93,20 @@ class WirelessAdbPairingService : Service() {
.onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) }
}
private fun resolveListener() = object : NsdManager.ResolveListener {
private fun resolveListener(owner: Int): NsdManager.ResolveListener {
return object : NsdManager.ResolveListener {
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
val address = serviceInfo.host ?: return
if (!WirelessAdbFix.isLocalAddress(address)) return
main.post {
if (working || current.value == Stage.Done) return@post
if (owner != session || working || current.value == Stage.Done) return@post
pairingHost = address.hostAddress
pairingPort = serviceInfo.port
if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded())
}
}
}
}
private fun onCode(code: String) {
@@ -114,29 +122,34 @@ class WirelessAdbPairingService : Service() {
return
}
working = true
val owner = session
val enable = limitEnabled
show(Stage.Working(getString(R.string.adbpair_pairing)))
Thread({
val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
if (paired.isFailure) {
main.post {
working = false
if (owner != session) return@post
pairingPort = null
show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected)))
}
return@Thread
}
main.post {
if (owner != session) return@post
stopDiscovery()
show(Stage.Working(getString(R.string.adbpair_connecting)))
}
val result = runCatching {
val connectPort = WirelessAdbFix.localConnectPort(this)
?: error(getString(R.string.adbpair_port_not_found))
main.post { show(Stage.Working(getString(R.string.adbpair_applying))) }
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
main.post { if (owner == session) show(Stage.Working(getString(R.string.adbpair_applying))) }
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, enable)
}
main.post {
working = false
if (owner != session) return@post
finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_command_failed)) } ?: Stage.Done)
}
}, "wireless-adb-pairing").start()
@@ -148,6 +161,7 @@ class WirelessAdbPairingService : Service() {
}
private fun finish(stage: Stage) {
session++
main.removeCallbacks(timeout)
stopDiscovery()
publish(stage)
@@ -248,6 +262,7 @@ class WirelessAdbPairingService : Service() {
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
private const val KEY_CODE = "code"
private const val EXTRA_ENABLE_LIMIT = "enable_limit"
private const val TIMEOUT_MS = 5 * 60_000L
private val current = MutableStateFlow<Stage>(Stage.Idle)
@@ -255,10 +270,10 @@ class WirelessAdbPairingService : Service() {
private fun publish(stage: Stage) { current.value = stage }
fun start(context: Context) {
fun start(context: Context, enableLimit: Boolean = false) {
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
publish(Stage.Waiting)
val intent = Intent(context, WirelessAdbPairingService::class.java)
val intent = Intent(context, WirelessAdbPairingService::class.java).putExtra(EXTRA_ENABLE_LIMIT, enableLimit)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
}
@@ -271,6 +286,12 @@ class WirelessAdbPairingService : Service() {
}
fun notificationsEnabled(context: Context): Boolean =
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false && !channelBlocked(context)
/** The code is typed into a notification on this channel; a channel the user switched off leaves pairing with nothing to type into. */
fun channelBlocked(context: Context): Boolean =
context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
fun channelId(): String = CHANNEL_ID
}
}
@@ -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
}
@@ -28,6 +28,7 @@ import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.FileCopy
import androidx.compose.material.icons.filled.FileOpen
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.InsertDriveFile
@@ -101,8 +102,18 @@ private fun FileContextMenuItems(
onToggleFavorite: () -> Unit,
onProperties: () -> Unit,
onDismissMenu: () -> Unit,
onOpen: () -> Unit,
) {
val isDir = file.isDirectory
if (!isDir) {
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_edit_open)) },
leadingIcon = { Icon(Icons.Filled.FileOpen, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onOpen() },
modifier = Modifier.focusGlide(),
)
MenuItemDivider()
}
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_select)) },
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
@@ -180,6 +191,7 @@ internal fun FileItemRow(
onCut: () -> Unit,
onDelete: () -> Unit,
onRename: () -> Unit,
onOpen: () -> Unit = {},
isFavorite: Boolean = false,
onToggleFavorite: () -> Unit = {},
onProperties: () -> Unit = {},
@@ -291,6 +303,7 @@ internal fun FileItemRow(
file = file,
isFavorite = isFavorite,
onSelect = onSelect,
onOpen = onOpen,
onRename = onRename,
onCopy = onCopy,
onCut = onCut,
@@ -517,6 +530,7 @@ internal fun FileGridTile(
isFavorite: Boolean = false,
onSelect: () -> Unit = {},
onRename: () -> Unit = {},
onOpen: () -> Unit = {},
onCopy: () -> Unit = {},
onCut: () -> Unit = {},
onDelete: () -> Unit = {},
@@ -605,6 +619,7 @@ internal fun FileGridTile(
file = file,
isFavorite = isFavorite,
onSelect = onSelect,
onOpen = onOpen,
onRename = onRename,
onCopy = onCopy,
onCut = onCut,
@@ -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
@@ -193,6 +191,7 @@ fun FileManagerScreen(
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
var showNewFolderDialog by remember { mutableStateOf(false) }
var renameTarget by remember { mutableStateOf<File?>(null) }
var editingTarget by remember { mutableStateOf<File?>(null) }
var propertiesTarget by remember { mutableStateOf<File?>(null) }
var isOperationRunning by remember { mutableStateOf(false) }
var operationLabel by remember { mutableStateOf("") }
@@ -296,7 +295,7 @@ fun FileManagerScreen(
if (isOperationActive()) pendingNavigation = action else navigate(action)
}
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) {
requestNavigation(FileManagerNavigation.BACK)
}
@@ -698,6 +697,14 @@ fun FileManagerScreen(
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
Column(modifier = Modifier.fillMaxSize()) {
editingTarget?.let { target ->
TextEditorScreen(
file = target,
onExit = { editingTarget = null },
modifier = Modifier.fillMaxSize(),
)
return@Column
}
if (pickMode && !pickerTitle.isNullOrEmpty()) {
Text(
text = pickerTitle,
@@ -727,11 +734,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 +805,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) {
@@ -1186,6 +1203,8 @@ fun FileManagerScreen(
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
onPick?.invoke(file)
}
} else {
editingTarget = file
}
},
onMenu = { showMenuFor = file },
@@ -1197,6 +1216,7 @@ fun FileManagerScreen(
selectedPaths = selectedPaths + file.absolutePath
showMenuFor = null
},
onOpen = { editingTarget = file; showMenuFor = null },
onRename = { renameTarget = file; showMenuFor = null },
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
@@ -1265,6 +1285,8 @@ fun FileManagerScreen(
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
onPick?.invoke(file)
}
} else {
editingTarget = file
}
},
onMenu = { showMenuFor = file },
@@ -1278,6 +1300,7 @@ fun FileManagerScreen(
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
onDelete = { selectedEntry = file; showMenuFor = null },
onOpen = { editingTarget = file; showMenuFor = null },
onRename = { renameTarget = file; showMenuFor = null },
isFavorite = isFav,
onToggleFavorite = {
@@ -0,0 +1,726 @@
package com.droiddeck.launcher.files
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Save
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.ui.focusGlide
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.charset.CharacterCodingException
import java.nio.charset.Charset
import java.nio.charset.CodingErrorAction
import java.nio.file.Files
import kotlin.math.roundToInt
internal const val EDITOR_FONT_SIZE_SP = 13
internal const val EDITOR_LINE_HEIGHT_SP = 18
internal const val EDITOR_TAB_WIDTH = 4
internal const val EDITOR_MAX_OPEN_BYTES = 4L * 1024 * 1024
internal const val EDITOR_MAX_EDIT_BYTES = 512L * 1024
internal enum class EditorCharset(val label: String, private val charsetName: String) {
UTF8("UTF-8", "UTF-8"),
GB18030("GB18030", "GB18030"),
;
val charset: Charset get() = Charset.forName(charsetName)
}
internal enum class EditorLock { NONE, BINARY, TOO_LARGE, PERMISSION, LOSSY }
internal enum class EditorLoadState { LOADING, READY, TOO_LARGE, UNREADABLE }
internal data class DecodedEditorText(val text: String, val charset: EditorCharset, val lossy: Boolean)
internal fun editorIsBinary(bytes: ByteArray, sample: Int = 8192): Boolean {
val limit = minOf(bytes.size, sample)
for (i in 0 until limit) if (bytes[i].toInt() == 0) return true
return false
}
private fun strictDecode(bytes: ByteArray, charset: Charset): String? = try {
charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString()
} catch (e: CharacterCodingException) {
null
}
internal fun decodeEditorText(bytes: ByteArray): DecodedEditorText {
strictDecode(bytes, Charsets.UTF_8)?.let { return DecodedEditorText(it, EditorCharset.UTF8, false) }
strictDecode(bytes, EditorCharset.GB18030.charset)?.let { return DecodedEditorText(it, EditorCharset.GB18030, false) }
return DecodedEditorText(String(bytes, Charsets.UTF_8), EditorCharset.UTF8, true)
}
internal fun resolveEditorSaveTarget(file: File): File {
val isLink = runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false)
if (!isLink) return file
// rename(2) replaces the link itself, so stage next to and rename onto the real target
return runCatching { file.canonicalFile }.getOrDefault(file)
}
internal fun readCapped(input: InputStream, limit: Long): ByteArray? {
val out = ByteArrayOutputStream()
val buffer = ByteArray(64 * 1024)
var total = 0L
while (true) {
val n = input.read(buffer)
if (n < 0) return out.toByteArray()
total += n
if (total > limit) return null
out.write(buffer, 0, n)
}
}
internal fun expandEditorTabs(text: String, width: Int = EDITOR_TAB_WIDTH): String {
if (text.indexOf('\t') < 0) return text
val out = StringBuilder(text.length)
var column = 0
for (c in text) {
when (c) {
'\n' -> {
out.append(c)
column = 0
}
'\t' -> {
val pad = width - (column % width)
repeat(pad) { out.append(' ') }
column += pad
}
else -> {
out.append(c)
column++
}
}
}
return out.toString()
}
internal fun lineCountOf(text: String): Int {
var lines = 1
for (i in text.indices) if (text[i] == '\n') lines++
return lines
}
internal fun lineIndexOfOffset(text: String, offset: Int): Int {
val end = offset.coerceIn(0, text.length)
var line = 0
var i = 0
while (i < end) {
if (text[i] == '\n') line++
i++
}
return line
}
internal fun columnOfOffset(text: String, offset: Int): Int {
val end = offset.coerceIn(0, text.length)
var start = end
while (start > 0 && text[start - 1] != '\n') start--
return end - start + 1
}
internal fun findEditorMatches(
text: String,
query: String,
matchCase: Boolean = false,
limit: Int = 10000,
): List<IntRange> {
if (query.isEmpty()) return emptyList()
val out = ArrayList<IntRange>()
var at = 0
while (out.size < limit) {
val found = text.indexOf(query, at, ignoreCase = !matchCase)
if (found < 0) break
out.add(found until found + query.length)
at = found + query.length
}
return out
}
internal fun replaceEditorMatches(text: String, matches: List<IntRange>, replacement: String): String {
if (matches.isEmpty()) return text
val out = StringBuilder(text.length)
var cursor = 0
for (m in matches) {
if (m.first < cursor || m.last >= text.length) continue
out.append(text, cursor, m.first).append(replacement)
cursor = m.last + 1
}
out.append(text, cursor, text.length)
return out.toString()
}
@Composable
internal fun TextEditorScreen(
file: File,
onExit: () -> Unit,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val density = LocalDensity.current
var text by remember { mutableStateOf("") }
var selection by remember { mutableStateOf(TextRange.Zero) }
var composing by remember { mutableStateOf<TextRange?>(null) }
var loadState by remember { mutableStateOf(EditorLoadState.LOADING) }
var lock by remember { mutableStateOf(EditorLock.NONE) }
var charset by remember { mutableStateOf(EditorCharset.UTF8) }
var dirty by remember { mutableStateOf(false) }
var saving by remember { mutableStateOf(false) }
var showDiscard by remember { mutableStateOf(false) }
var showSearch by remember { mutableStateOf(false) }
var query by remember { mutableStateOf("") }
var replacement by remember { mutableStateOf("") }
var matchCase by remember { mutableStateOf(false) }
var matchIndex by remember { mutableIntStateOf(0) }
val scrollState = rememberScrollState()
val textHorizontalState = rememberScrollState()
var viewportHeight by remember { mutableIntStateOf(0) }
var viewportWidth by remember { mutableIntStateOf(0) }
val lineHeightDp = with(density) { EDITOR_LINE_HEIGHT_SP.sp.toDp() }
val lineHeightPx = with(density) { lineHeightDp.toPx() }
val totalLines = remember(text) { lineCountOf(text) }
val cursorLine = lineIndexOfOffset(text, selection.end)
val cursorColumn = columnOfOffset(text, selection.end)
val matches = remember(text, query, matchCase) { findEditorMatches(text, query, matchCase) }
val readOnly = lock != EditorLock.NONE
val bodyStyle = TextStyle(
fontFamily = FontFamily.Monospace,
fontSize = EDITOR_FONT_SIZE_SP.sp,
lineHeight = EDITOR_LINE_HEIGHT_SP.sp,
color = MaterialTheme.colorScheme.onBackground,
)
val textMeasurer = rememberTextMeasurer()
val charWidthPx = remember(bodyStyle) { textMeasurer.measure(text = "0", style = bodyStyle).size.width.toFloat() }
LaunchedEffect(file) {
loadState = EditorLoadState.LOADING
val size = withContext(Dispatchers.IO) { file.length() }
if (size > EDITOR_MAX_OPEN_BYTES) {
loadState = EditorLoadState.TOO_LARGE
return@LaunchedEffect
}
val read = withContext(Dispatchers.IO) {
runCatching { file.inputStream().use { readCapped(it, EDITOR_MAX_OPEN_BYTES) } }
}
val bytes = read.getOrNull()
if (bytes == null) {
loadState = if (read.isFailure) EditorLoadState.UNREADABLE else EditorLoadState.TOO_LARGE
return@LaunchedEffect
}
val decoded = decodeEditorText(bytes)
text = expandEditorTabs(decoded.text)
charset = decoded.charset
lock = when {
editorIsBinary(bytes) -> EditorLock.BINARY
decoded.lossy -> EditorLock.LOSSY
bytes.size > EDITOR_MAX_EDIT_BYTES -> EditorLock.TOO_LARGE
!file.canWrite() -> EditorLock.PERMISSION
else -> EditorLock.NONE
}
selection = TextRange.Zero
loadState = EditorLoadState.READY
}
suspend fun revealLine(line: Int) {
val current = scrollState.value
val top = line * lineHeightPx
val target = when {
top < current -> top
top + lineHeightPx > current + viewportHeight -> top + lineHeightPx - viewportHeight
else -> return
}
val clamped = target.roundToInt().coerceIn(0, scrollState.maxValue)
if (clamped != current) scrollState.scrollTo(clamped)
}
LaunchedEffect(text, selection.end, viewportHeight, viewportWidth) {
if (loadState != EditorLoadState.READY) return@LaunchedEffect
revealLine(lineIndexOfOffset(text, selection.end))
if (viewportWidth > 0 && charWidthPx > 0) {
val x = (columnOfOffset(text, selection.end) - 1) * charWidthPx
val current = textHorizontalState.value
val target = when {
x < current -> x
x + charWidthPx > current + viewportWidth -> x + charWidthPx - viewportWidth
else -> null
}
if (target != null) {
val clamped = target.roundToInt().coerceIn(0, textHorizontalState.maxValue)
if (clamped != current) textHorizontalState.scrollTo(clamped)
}
}
}
LaunchedEffect(query, matchCase) {
if (query.isEmpty()) return@LaunchedEffect
matchIndex = 0
val first = matches.firstOrNull() ?: return@LaunchedEffect
selection = TextRange(first.first, first.last + 1)
composing = TextRange.Zero
}
LaunchedEffect(text) { matchIndex = 0 }
fun gotoMatch(delta: Int) {
if (matches.isEmpty()) return
matchIndex = Math.floorMod(matchIndex + delta, matches.size)
val m = matches[matchIndex]
selection = TextRange(m.first, m.last + 1)
composing = TextRange.Zero
}
fun replaceCurrent() {
if (readOnly) return
val m = matches.getOrNull(matchIndex) ?: return
text = text.replaceRange(m.first, m.last + 1, replacement)
dirty = true
matchIndex = 0
selection = TextRange(m.first + replacement.length)
composing = TextRange.Zero
}
fun replaceAll() {
if (readOnly || matches.isEmpty()) return
val all = findEditorMatches(text, query, matchCase, limit = Int.MAX_VALUE)
text = replaceEditorMatches(text, all, replacement)
dirty = true
matchIndex = 0
selection = TextRange.Zero
composing = TextRange.Zero
}
fun save() {
if (readOnly || saving || loadState != EditorLoadState.READY) return
val snapshot = text
val bytes = snapshot.toByteArray(charset.charset)
saving = true
scope.launch {
val ok = withContext(Dispatchers.IO) {
runCatching {
val target = resolveEditorSaveTarget(file)
val parent = target.parentFile
if (parent == null) {
target.writeBytes(bytes)
} else {
val tmp = File.createTempFile(".${target.name}.", ".droiddeck-tmp", parent)
try {
tmp.writeBytes(bytes)
runCatching {
Files.setPosixFilePermissions(tmp.toPath(), Files.getPosixFilePermissions(target.toPath()))
}
if (!tmp.renameTo(target)) error("rename to ${target.name} failed")
} finally {
tmp.delete()
}
}
}.isSuccess
}
saving = false
if (ok) {
if (text == snapshot) dirty = false
} else {
Toast.makeText(context, context.getString(R.string.fm_edit_save_failed, file.name), Toast.LENGTH_SHORT).show()
}
}
}
fun tryExit() {
if (saving) return
if (dirty && !readOnly) showDiscard = true else onExit()
}
BackHandler { tryExit() }
if (showDiscard) {
OutlinedAlertDialog(
onDismissRequest = { showDiscard = false },
title = { Text(stringResource(R.string.fm_edit_discard_title)) },
text = { Text(stringResource(R.string.fm_edit_discard_text, file.name)) },
confirmButton = {
TextButton(onClick = onExit, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.fm_edit_discard))
}
},
dismissButton = {
TextButton(onClick = { showDiscard = false }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.common_cancel))
}
},
)
}
Column(
modifier = modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainer)
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
IconButton(onClick = { tryExit() }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
Icons.Filled.ArrowBack,
stringResource(R.string.fm_back),
tint = MaterialTheme.colorScheme.primary,
)
}
Column(modifier = Modifier.weight(1f).padding(horizontal = 4.dp)) {
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (dirty) {
Text(
text = "\u2022 " + stringResource(R.string.fm_edit_modified),
color = MaterialTheme.colorScheme.primary,
fontSize = 11.sp,
maxLines = 1,
)
}
}
if (loadState == EditorLoadState.READY && lock != EditorLock.NONE) {
Text(
text = stringResource(
if (lock == EditorLock.BINARY) R.string.fm_edit_binary else R.string.fm_edit_read_only,
),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 10.sp,
maxLines = 1,
modifier = Modifier
.background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.small)
.padding(horizontal = 6.dp, vertical = 2.dp),
)
Spacer(Modifier.width(6.dp))
}
IconButton(
onClick = { showSearch = !showSearch },
enabled = loadState == EditorLoadState.READY,
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.Search,
stringResource(R.string.fm_edit_find),
tint = if (showSearch) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(
onClick = { save() },
enabled = loadState == EditorLoadState.READY && !readOnly && dirty && !saving,
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.Save,
stringResource(R.string.fm_edit_save),
tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (showSearch && loadState == EditorLoadState.READY) {
Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainer)) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp, top = 4.dp),
) {
OutlinedTextField(
value = query,
onValueChange = { query = it; matchIndex = 0 },
singleLine = true,
placeholder = { Text(stringResource(R.string.fm_edit_find), fontSize = 13.sp) },
textStyle = MaterialTheme.typography.bodySmall,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { gotoMatch(1) }),
modifier = Modifier.weight(1f).focusGlide(),
)
Text(
text = if (matches.isEmpty()) "0/${matches.size}" else "${matchIndex.coerceAtMost(matches.size - 1) + 1}/${matches.size}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 6.dp).widthIn(min = 44.dp, max = 80.dp),
)
IconButton(
onClick = { gotoMatch(-1) },
enabled = matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.KeyboardArrowUp,
stringResource(R.string.fm_edit_find_previous),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
}
IconButton(
onClick = { gotoMatch(1) },
enabled = matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.KeyboardArrowDown,
stringResource(R.string.fm_edit_find_next),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
}
TextButton(onClick = { matchCase = !matchCase }, modifier = Modifier.focusGlide(CircleShape)) {
Text(
text = "Aa",
color = if (matchCase) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 13.sp,
)
}
IconButton(onClick = { showSearch = false }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
Icons.Filled.Close,
stringResource(R.string.common_cancel),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 2.dp, end = 4.dp, bottom = 2.dp),
) {
OutlinedTextField(
value = replacement,
onValueChange = { replacement = it },
singleLine = true,
placeholder = { Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) },
textStyle = MaterialTheme.typography.bodySmall,
modifier = Modifier.weight(1f).focusGlide(),
)
TextButton(
onClick = { replaceCurrent() },
enabled = !readOnly && matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp)
}
TextButton(
onClick = { replaceAll() },
enabled = !readOnly && matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Text(stringResource(R.string.fm_edit_replace_all), fontSize = 13.sp)
}
}
}
}
Box(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.onSizeChanged { viewportHeight = it.height },
) {
when (loadState) {
EditorLoadState.LOADING -> CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center),
)
EditorLoadState.TOO_LARGE, EditorLoadState.UNREADABLE -> Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.align(Alignment.Center).padding(24.dp),
) {
Text(
text = stringResource(
if (loadState == EditorLoadState.TOO_LARGE) R.string.fm_edit_too_large
else R.string.fm_edit_open_failed,
if (loadState == EditorLoadState.TOO_LARGE) FileOps.formatBytes(context, file.length())
else file.name,
),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 14.sp,
textAlign = TextAlign.Center,
)
}
EditorLoadState.READY -> Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(scrollState),
) {
Row(modifier = Modifier.fillMaxWidth().height(lineHeightDp * totalLines.toFloat())) {
LineNumbers(
scrollState = scrollState,
viewportHeight = viewportHeight,
lineHeightDp = lineHeightDp,
lineHeightPx = lineHeightPx,
totalLines = totalLines,
cursorLine = cursorLine,
style = bodyStyle,
mutedColor = MaterialTheme.colorScheme.onSurfaceVariant,
cursorColor = MaterialTheme.colorScheme.primary,
)
Box(modifier = Modifier.weight(1f).onSizeChanged { viewportWidth = it.width }.horizontalScroll(textHorizontalState)) {
BasicTextField(
value = TextFieldValue(text = text, selection = selection, composition = composing),
onValueChange = { next ->
val changed = next.text != text
text = next.text
selection = next.selection
composing = next.composition
if (changed) dirty = true
},
readOnly = readOnly,
textStyle = bodyStyle,
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
capitalization = KeyboardCapitalization.None,
),
modifier = Modifier.fillMaxHeight().focusGlide(),
)
}
}
}
}
}
if (loadState == EditorLoadState.READY) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
) {
Text(
text = stringResource(R.string.fm_edit_position, cursorLine + 1, cursorColumn),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
)
Spacer(Modifier.weight(1f))
Text(
text = charset.label + " \u2022 " + FileOps.formatBytes(context, file.length()),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
)
}
}
}
}
@Composable
private fun LineNumbers(
scrollState: ScrollState,
viewportHeight: Int,
lineHeightDp: Dp,
lineHeightPx: Float,
totalLines: Int,
cursorLine: Int,
style: TextStyle,
mutedColor: Color,
cursorColor: Color,
modifier: Modifier = Modifier,
) {
val firstLine = (scrollState.value / lineHeightPx).toInt().coerceIn(0, totalLines - 1)
val lastLine = ((scrollState.value + viewportHeight) / lineHeightPx)
.toInt()
.coerceIn(firstLine, totalLines - 1)
Column(
horizontalAlignment = Alignment.End,
modifier = modifier
.width(IntrinsicSize.Min)
.padding(top = lineHeightDp * firstLine.toFloat()),
) {
for (line in firstLine..lastLine) {
Text(
text = (line + 1).toString(),
color = if (line == cursorLine) cursorColor else mutedColor,
textAlign = TextAlign.End,
maxLines = 1,
style = style,
modifier = Modifier.fillMaxWidth().height(lineHeightDp),
)
}
}
}
@@ -31,6 +31,7 @@ object AddedGames {
val exeUncertain: Boolean = false,
val launchOptions: String = "",
val single: Boolean = false,
val steamProgram: Boolean = true,
) {
fun folderName(): String = folder.name
}
@@ -238,6 +239,7 @@ object AddedGames {
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
scanGame(context, folder, out, single = entry, reuse = true)
}
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
@@ -335,7 +337,14 @@ 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 {
val keep = listOf(it.exe, exe).firstOrNull { f -> guestPath(app, f) != null }
if (keep != null) {
SessionPrefs.setAddedGameExe(app, owner.path, keep.path)
AddedExes.put(app, AddedExes.Entry(owner.path, keep.path))
}
return AddResult.Existing(it)
}
}
if (guestPath(app, exe) == null) {
(owner ?: exe.parentFile)?.takeIf { guestPath(app, it) == null }?.let { bindFolder(app, it) }
@@ -344,7 +353,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")
@@ -439,9 +448,9 @@ object AddedGames {
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
val epicLauncher = sidecar?.takeIf { it.store == Store.EPIC && (chosen == null || canonical(chosen) == canonical(it.exeFile(folder))) }
val storeLauncher = sidecar?.takeIf { chosen == null || canonical(chosen) == canonical(it.exeFile(folder)) }
?.launcherFile(folder)?.takeIf { it.isFile }
val launch = epicLauncher ?: if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
val launch = storeLauncher ?: found
val foundGuest = guestPath(context, launch)
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
@@ -467,7 +476,13 @@ object AddedGames {
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
?: sidecarDir
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
val steamId = config?.let { steamRoute(it, appId) }
if (adopted == null && SessionPrefs.addedGameAdopted(context, folder.path, "Exe") == null &&
guestPath(context, folder)?.let { steamEditedTo(it, record, guestExe) } == true) {
SessionPrefs.setAddedGameAdopted(context, folder.path, "Exe", exe.path)
}
val steamProgram = candidates.firstOrNull()?.let { canonical(it) == canonical(exe) } ?: true ||
SessionPrefs.addedGameAdopted(context, folder.path, "Exe")?.let { canonical(File(it)) == canonical(exe) } == true
val steamId = config?.takeIf { steamProgram }?.let { steamRoute(it, appId) }
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
@@ -477,7 +492,7 @@ object AddedGames {
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
else -> ""
},
single = single != null))
single = single != null, steamProgram = steamProgram))
}
}
@@ -517,6 +532,11 @@ object AddedGames {
return file.takeIf { inside && it.isFile }
}
internal fun steamEditedTo(folderGuest: String, record: JSONObject?, guestExe: String): Boolean {
val steam = unquote(record?.optJSONObject("steam")?.optString("Exe"))
return steam == guestExe && steam != unquote(record?.optJSONObject("app")?.optString("Exe")) && steam.startsWith("$folderGuest/")
}
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
@@ -565,6 +585,7 @@ object AddedGames {
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions))
if (g.source != Library.ADDED) json.append(",\"store\":").append(quote(g.source))
if (!g.steamProgram) json.append(",\"route\":false")
val art = AddedGameArt.resolve(context, g)
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
@@ -47,6 +47,7 @@ object AutoComponents {
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
@VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) }
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
@VisibleForTesting @Volatile internal var runNow = false
@@ -533,6 +534,10 @@ object AutoComponents {
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
fun powerSaveOrMetered(context: Context): Boolean =
context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true ||
context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
fun constrained(context: Context): Boolean {
val power = context.getSystemService(PowerManager::class.java)
if (power?.isPowerSaveMode == true) return true
@@ -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)
}
}
@@ -13,6 +13,7 @@ object GamesFolderMigration {
@Synchronized
fun run(context: Context) {
repathInternalGuest(context)
val dirs = SessionPrefs.addedGamesDirs(context)
if (dirs.isEmpty()) return
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
@@ -58,12 +59,30 @@ object GamesFolderMigration {
SessionPrefs.setGamesFoldersMigrated(context)
}
private fun repathInternalGuest(context: Context) {
val binds = SessionPrefs.gameFolderBinds(context)
if (binds.none { it.second == StoreInstallRoot.INTERNAL_GUEST }) return
val hosts = binds.map { it.first }
val roots = legacyRoots(hosts).associateBy { it.host.path }
val taken = binds.map { it.second }.filter { it != StoreInstallRoot.INTERNAL_GUEST }.toMutableSet()
SessionPrefs.setGameFolderBinds(context, binds.map { (host, guest) ->
if (guest != StoreInstallRoot.INTERNAL_GUEST) return@map host to guest
val base = roots.getValue(host).guest
var next = base
var n = 2
while (next in taken) next = "$base-${n++}"
taken.add(next)
host to next
})
}
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
val hosts = paths.distinct().map { File(it) }
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
return hosts.map { host ->
val name = host.name.ifEmpty { "games" }
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
val clash = (names[name.lowercase()] ?: 0) > 1 || "${AddedGames.GUEST_DIR}/$name" == StoreInstallRoot.INTERNAL_GUEST
val guestName = if (clash) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
AddedGames.Root(host, "${AddedGames.GUEST_DIR}/$guestName")
}
}
@@ -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
}
}
@@ -20,6 +20,12 @@ object SteamRedists {
val SCRIPTED = mapOf(
72850 to listOf("xact" to "DirectX XACT audio"),
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
// Warband compiles its postFX .fx effects at launch through d3dx9_42; Wine's own d3dcompiler_42 stops with E5017/E5033 on fx_2_0.
48700 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_42" to "D3DCompiler 42"),
// DST's bundled ANGLE compiles SM3 shaders through d3dcompiler_43; DXVK's SM3 parser asserts on what Wine's own one emits.
322330 to listOf("d3dcompiler_43" to "D3DCompiler 43"),
// EU4 builds its map effects through native d3dx9_43, which calls d3dcompiler_43; Wine's own one fails them with E5005, so the map draws black.
236850 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_43" to "D3DCompiler 43"),
)
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
@@ -45,9 +45,8 @@ internal class XrealLink internal constructor(
if (msgId == VitureProtocol.MSG_GET_IMU) return true
val valid = when (msgId) {
VitureProtocol.MSG_GET_DISPLAY -> true
VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ
else value in 2..5 || value == XrealModel.NATIVE_60HZ
VitureProtocol.MSG_BRIGHTNESS -> !model.stereoOnlyControl && value in 0..9
VitureProtocol.MSG_DISPLAY -> model.supportsDisplayMode(value)
VitureProtocol.MSG_BRIGHTNESS -> model.hardwareControls && value in 0..model.brightnessMax
VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1
else -> false
}
@@ -64,12 +63,12 @@ internal class XrealLink internal constructor(
channels = connector.connect()
connection.set(channels)
if (!running) break
val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl)
val control = XrealControl(channels, model = model)
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
val current = channels
reports = Thread({
try {
var filter = XrealOrientationFilter(model.flipsYz)
var filter = XrealOrientationFilter(model)
var wasTracking = false
var lastSensor = System.nanoTime()
while (running && connection.get() === current) {
@@ -78,7 +77,7 @@ internal class XrealLink internal constructor(
if (sample != null) {
lastSensor = System.nanoTime()
val enabled = tracking
if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz)
if (enabled && !wasTracking) filter = XrealOrientationFilter(model)
wasTracking = enabled
if (enabled) filter.update(sample)?.let {
if (running && ready && tracking && connection.get() === current)
@@ -155,8 +154,9 @@ internal class XrealLink internal constructor(
internal class XrealControl(
private val channels: XrealChannels,
private val settleDelayMs: Long = 150,
private val stereoOnly: Boolean = false,
private val model: XrealModel = XrealModel.ONE_S,
) {
private val stereoOnly get() = model.stereoOnlyControl
private var transaction = 0
private fun exchange(command: Int, value: Int? = null): ByteArray {
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
@@ -172,7 +172,7 @@ internal class XrealControl(
fun display(): Int {
if (stereoOnly) return stereoDisplay()
val reply = exchange(XrealProtocol.GET_DISPLAY)
return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ }
return XrealProtocol.numeric(reply)?.takeIf(model::supportsDisplayMode)
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
}
private fun stereoDisplay(): Int {
@@ -187,6 +187,7 @@ internal class XrealControl(
}
}
fun changeDisplay(mode: Int): Int {
require(model.supportsDisplayMode(mode))
val stereo = mode == 5
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
val current = awaitDisplay { (it == 5) == stereo }
@@ -4,6 +4,7 @@ internal class XrealModel private constructor(
override val name: String,
val family: Family,
override val diagonalFovDeg: Float,
private val native60Hz: Int = NATIVE_60HZ,
) : GlassesModel {
enum class Family {
ONE_S,
@@ -14,23 +15,25 @@ internal class XrealModel private constructor(
override val controllable = true
override val brightnessMax = 9
override val volumeMax = 0
override val hasSunblock get() = family == Family.ONE_S
override val hardwareControls get() = family == Family.ONE_S
override val hasSunblock get() = !stereoOnlyControl
override val hardwareControls get() = !stereoOnlyControl
override val sbs90 = false
override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60)
override val rates2d get() = if (stereoOnlyControl) listOf(60) else super.rates2d
// Only the 1S has been exercised with SET_DISPLAY; the Aura is known to reboot on an unexpected index.
val stereoOnlyControl get() = family != Family.ONE_S
val stereoOnlyControl get() = family != Family.ONE_S && this !== ONE_PRO_PLUS
internal fun supportsDisplayMode(mode: Int) = if (stereoOnlyControl) mode == 5 || mode == native60Hz
else mode in 3..5 || mode == native60Hz || (this === ONE_S && mode == 2)
// The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it.
val flipsYz get() = family != Family.AURA
override fun mode(hz: Int, sbs: Boolean) = when {
sbs -> 5
stereoOnlyControl -> NATIVE_60HZ
stereoOnlyControl -> native60Hz
hz >= 120 -> 4
hz >= 90 -> 3
else -> NATIVE_60HZ
else -> native60Hz
}
override fun modeForStep(step: Int): Int? = null
@@ -44,7 +47,7 @@ internal class XrealModel private constructor(
val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f)
val ONE = XrealModel("XREAL One", Family.ONE, 50f)
val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f)
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f)
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f, 9)
val AURA = XrealModel("XREAL Aura", Family.AURA, 70f)
// The odd product ids one below these are the glasses' recovery mode.
@@ -2,13 +2,18 @@ package com.droiddeck.launcher.glasses
import kotlin.math.abs
internal class XrealOrientationFilter(private val flipYz: Boolean = true) {
internal class XrealOrientationFilter(private val model: XrealModel = XrealModel.ONE_S) {
private val fusion = ImuFusion()
private val sensorToDisplay = if (model === XrealModel.ONE_PRO_PLUS)
Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.toRadians(35.0).toFloat()) else null
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
sample.accel.headAxes(), sample.gyro.headAxes())
private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this
private fun Vec3.headAxes(): Vec3 {
val display = sensorToDisplay?.rotate(this) ?: this
return if (model.flipsYz) Vec3(display.x, -display.y, -display.z) else display
}
}
internal class ImuFusion {
Loaded 100 of 997 files, more files were not shown because too many files have changed in this diff. Show more