Compare commits

...
Author SHA1 Message Date
Kurt Himebauch eb2a3202c9 Run a session's programs as ordinary children when the child-process limit is off
Since #3338 every session hands its programs to :gN worker processes, so a
game runs as 40 or more processes of the app. Cocoon's enhanced access
(3.11 and 3.12) snapshots a player through its app processes and gives up
above 32 ("Too many player processes"), so Home no longer pauses a game it
launched: no Resume or Close, no game frame, and play logging stops.

The workers only matter while Android counts the session's children. With
the limit off, which Steam required before #3338, the session runs as one
app process again. Producer acquire fences still get their worker, as they
need gamescope in one.
2026-12-04 21:46:24 -05:00
Kurt Himebauch b072cedd16 Fix black bottom-screen Mirror with HDR enabled (#3710)
* Keep Mirror frames readable with HDR enabled

* Exercise mirror capture messages in the native host queue test

* Preserve the HDR display fallback while Mirror is open
2026-12-04 14:01:37 -05:00
Kurt Himebauch 77fffa7592 Show recent photos in place of the keyboard when attaching to the agent (#3702)
* Show recent photos in place of the keyboard in the agent composer

The attach button opens a tray, at the keyboard's height, of the device's
recent pictures; a tap attaches or detaches one. The tray also opens the
system file picker and asks for photo access when the app has none.

* Agent instructions: manifest needs an APK; the agent resumes after a Lab build restart

* Skip the tray's back handler where the host has no back dispatcher

* Offer the photo tray in windows that cannot open pickers, such as the floating pet

* Fix the tray's permission request for windows without a registry

* Move the game screenshot button into the photo tray

* Name only the model in the agent's compact chip

* Keep the session drawer open while the tray's picker or photo permission prompt is up

* Address review: tray height on short screens, denied photo access, kept photo marks, tile labels, Lab build refusals

* Keep tray photos being copied across the tray closing

* Let a tray photo copy clear only its own in-progress marker

* Review: one attachment file per copy, photo tile labels, superseded copies attach nothing

* Drop tray photo copies still running when the message is sent
2026-12-04 13:42:17 -05:00
Kurt Himebauch de3ed8b986 Keep the followed channel's offer off the Tests list while browsing it (#3707)
* Show the followed channel's update offer above the test list only when following a test

* Keep install progress and errors on the Tests list while following Stable or Preview
2026-12-04 13:25:24 -05:00
JRAlmonte 86b8ae3c99 fix(nativeguest): do not apply a realtime limit of zero (#3704)
Flatpak emulators that use SDL (Flycast, Rosalie's Mupen GUI, xemu) were
killed with status 137 a second or two after a game started. Without a
RealtimeKit, xdg-desktop-portal reports RTTimeUSecMax 0, and SDL sets that
as RLIMIT_RTTIME before asking for a realtime thread. The kernel checks the
limit on a thread that is realtime or has a CPU-time timer armed, and a
limit of 0 is reached at once: SIGKILL at the hard limit.

Fixes #3672
2026-12-04 13:02:07 -05:00
Kurt Himebauch fe6f8638c6 Lay wide session drawer pages out in two columns (#3694)
Keep drawer content composed when changing width, and keep component notes within their groups so columns stay balanced.
2026-12-04 12:15:50 -05:00
Kurt Himebauch 26b11c6838 Keep the session drawer open while the agent's file picker is up (#3696)
Preserve the Agent page and its result handler while the system picker covers the session, including on a docked second screen.
2026-12-04 11:00:09 -05:00
Kurt Himebauch a9f2017aa3 Draw the outline of enabled secondary buttons under the agent's latest reply (#3697)
* Draw the outline of enabled secondary buttons under the agent's latest reply

* Count only the index fetch's own connections in DesktopLanguageIndexSourceTest
2026-12-04 10:25:37 -05:00
Kurt Himebauch bc8a970520 Stop re-arming frame generation after repeated GPU loss (#3659)
Disable frame generation after repeated startup device losses, while preserving recovery for engines that had been working. Keep the current ZeroFG-compatible submission path.
2026-12-04 09:41:39 -05:00
Kurt Himebauch eefd8088dc Merge original Snapdragon X detection contribution (#524)
Retain the implementation and tests already merged in #3671. This merge preserves the original contribution history without changing the current source tree.
2026-12-04 09:38:53 -05:00
Kurt Himebauch 442f1f83bf Resolve Snapdragon X conflicts against main
Keep the implementation and tests from #3671 while retaining the original contributor branch history.
2026-12-04 09:38:36 -05:00
Kurt Himebauch 1d1c29517a Revert "Feat:Add Snapdragon X Elite and Adreno X1 GPU detection" (#3695)
Revert "Feat:Add Snapdragon X Elite and Adreno X1 GPU detection (#3671)"

This reverts commit be98982cfc.
2026-12-04 09:30:22 -05:00
LunaDL be98982cfc Feat:Add Snapdragon X Elite and Adreno X1 GPU detection (#3671)
* feat(gpu): add Snapdragon X and Adreno X1 detection

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* test: preserve current SoC mappings and cover QTI X1 fallback

* test: preserve current SoC mappings and cover QTI X1 fallback

* test: preserve current SoC mappings and cover QTI X1 fallback

* fix: keep session TU_DEBUG policy authoritative

* test: preserve explicit TU_DEBUG environment overrides

* chore: remove unused GPU detection import

* test: verify TU_DEBUG defaults stay session-owned

* chore: restart PR CI

* fix: remove duplicate game environment resolver

* fix: preserve session TU_DEBUG defaults for Flatpak and Snap

* fix: only export explicit game TU_DEBUG overrides

* test: correct SoC platform fallback assertions

* test: cover inherited session TU_DEBUG defaults

* test: remove redundant GameEnvironment comment

* fix: preserve Venus game sysmem setting

* test: cover persisted Venus sysmem setting
2026-12-04 09:29:44 -05:00
Kurt Himebauch ed763ecb9b Let the session drawer expand to the screen's left edge (#3691)
Keep the resize grip usable at full width and reserve its touch area from Android Back gestures.
2026-12-04 09:22:27 -05:00
Kurt Himebauch ecbda604e2 ci: save the Robolectric jar cache from main only (#3604)
A pull request's cache entry is visible only to that pull request, so each
PR stored its own ~830 MB copy that no other PR could restore, while new
PRs started from main's incomplete set and downloaded the rest from Maven
Central, where the 429s come from. The copies also kept the repository at
its 10 GB cache limit and pushed out other caches.
2026-12-04 08:56:53 -05:00
Kurt Himebauch c514c59018 Settings search: open the result's row, scroll to it and flash it (#3657)
* Settings search: open the result's row, scroll to it and flash it

* Opt in to the foundation API the search target uses
2026-12-04 08:56:05 -05:00
Kurt Himebauch b6efc4d44a Updates: Lab builds under the installed build, two panes in landscape (#3667)
* feat(updates): Lab builds under the installed build, two panes in landscape

Lab builds sit under the installed build instead of below the test list,
with kept builds folded behind a toggle while one runs. In landscape the
page splits into two panes that scroll on their own: the installed build,
checks, Lab builds and tester options on the left, the channel picker and
its status on the right. The selected test build expands in place with its
status, notes and install button.

* fix(updates): stack the fallback status above the test list
2026-12-04 08:55:44 -05:00
Kurt Himebauch b61f766b66 fix(session): sleep freezes the programs that run in worker processes (#3665)
With the native session, gamescope, Xwayland, wineserver and the game each run
in a worker process of their own: none descends from the session root, so the
freeze on sleep left them running. On wake the resume still added the frozen
time to the guest clock shift, and every one of them saw its monotonic clock
jump back by the length of the sleep. Unreal games abort on that:
KINGDOM HEARTS III failed with "Detected negative delta time" (DeltaTime
-10.05 s after a 13 s sleep).

The freeze now treats the session's worker programs as helper roots, as the
teardown already does.
2026-12-04 08:54:51 -05:00
Kurt Himebauch 01c8991049 Fix initial controller focus in the frame generation picker (#3689)
Keep engine choices in the session drawer focus tree so the selected engine receives focus on open and the Engine control regains focus on close.
2026-12-04 07:43:45 -05:00
Kurt Himebauch bf8faf06e1 Make frame generation and game zoom controller-friendly (#3669)
Add the session engine picker and the stepped Game zoom slider. Keep Frame Generation in its own tab and use the standard controller focus ring on its buttons.
2026-12-04 07:20:03 -05:00
LunaDL a6ffbe7d81 Add ZeroFG and optional ZeroPacer (#3552)
Add ZeroFG as a frame generation engine with its opt-in pacer. Keep frame generation in the dedicated session tab and keep manual DLL import removed.
2026-12-03 22:29:39 -05:00
Kurt Himebauch 34b78e2e42 Agent chat: open pictures full screen (#3668)
feat(agent): open chat pictures full screen

Tapping a picture in the agent chat, or an attached image, opens it over
the whole window. Pinch or double-tap zooms and dragging pans; a tap, a
swipe down, Back or B, or the close button closes it. It is a popup so it
also works in the pet's chat, which lives in an overlay window.
2026-12-03 22:27:31 -05:00
Kurt Himebauch bd016858c7 fix(agent): keys reach the pet's editor after its chat closes and opens again (#3666)
The pet's chat panel absorbed taps with a clickable disabled while the
chat was closed. A disabled clickable drops its focus node, so closing the
chat removed a node above the still-focused editor and reopening put back a
new, unfocused one in its place. Compose then found no focus target for key
events: backspace and other key presses were dropped, and with the pet's
view focused, DroidDeck crashed with "Event can't be processed because we
do not have an active focus target".
2026-12-03 21:49:50 -05:00
Kurt Himebauch f761e5f1db Change Steam picture position live from the session menu (#3661)
Use independent portrait and landscape alignment, with Top and 1280×800 as the default in Steam portrait. Keep explicit resolutions and existing controls modes.
2026-12-03 21:13:55 -05:00
Kurt Himebauch ebb3bb6373 Default to visible sticks and add live on-screen controls opacity (#3662)
Keep existing settings and touch targets unchanged. Let users dim the touch controls from 100 to 10 percent.
2026-12-03 20:52:28 -05:00
Kurt Himebauch 2aad4fbb1b Keep oversized floating HUD panels from clipping (#3663)
Fit the entire floating panel to its viewport without changing saved HUD scale.
2026-12-03 20:52:15 -05:00
Kurt Himebauch b81d7d796f Default the DroidDeck HUD to FPS and 1% low (#3660)
Keep 0.1% and 0.01% lows opt-in without changing saved choices.
2026-12-03 20:51:53 -05:00
Kurt Himebauch 54e1dcb5a4 Trim own file page cache during sessions under memory pressure (#3439) 2026-12-03 20:38:11 -05:00
The412Banner 10d3b801fa Run original Xbox games from the Xbox store (#3638)
Original Xbox games sold for PC through the Xbox store (Xbox360BackwardCompatibil.* packages: Fuzion Frenzy, BLiNX, Conker, Crimson Skies, Grabbed by the Ghoulies, Morrowind, Red Faction II, ...) now start and play on DroidDeck-Bionic.

- droiddeck-xbox: keep the GameInput redistributable, remove its service class; run install actions with FEX's safe settings; find MicrosoftGame.config in any case and skip one that does not parse.
- droiddeck-game-env: fix rule for these games turns on the emulator fixes in the Wine, FEX and VKD3D-Proton builds made for them.
- Components: each installed game gets the Xbox FEX, VKD3D-Proton and DXVK builds, never over a player's choice (also not one made during the download).
- Xbox store: these games show the size of their console package.
- DroidDeck-Bionic launch.sh keeps the Wine and VKD3D-Proton switches; bionic pack uses the v18 layer with the fixes (released as DroidDeck-Bionic 14.1 r104).
- Xbox backend: purchases that name a legacy marketplace offer reach the library.
2026-12-04 07:57:43 +08:00
Kurt Himebauch 00b354a40a Fix portrait game tabs and compact Library and Store filters (#3658)
Keep About, Launch, and Install in the game detail strip. Use dropdowns for top-level sources in portrait and narrow panes. Default Library title and size overlays to off without overriding saved choices.
2026-12-03 18:38:15 -05:00
Kurt Himebauch 5a18f69c7e Controls below the game: drop the second-screen bar, Steam and Quick Access under the pad (#3653)
* Controls below the game: drop the second-screen bar, Steam and Quick Access under the pad

* Test the keys under the unfolded pad instead of the removed bar

* Keep a touch drawer button below the game
2026-12-03 16:54:04 -05:00
Kurt Himebauch 68af03ac74 Negotiate verified producer fences for Steam game frames (#3651)
Use the verified Gamescope component and preserve the safe copy fallback. Direct game frames remains experimental and off by default.
2026-12-03 16:29:52 -05:00
MaxsTechReview d8bb4a8751 fix(ea): signing out forgets the EA web session so another account can sign in (#3652)
EA keeps its sign-in session in cookies scoped under the sign-in paths
(/connect on accounts.ea.com, /p on signin.ea.com). Sign-out and the
fresh sign-in only listed and expired cookies at /, so the old session
survived and EA signed the previous account straight back in.

Cookie expiry now also covers every path prefix of each sign-in URL, and
the EA sign-in URLs name those paths.

Closes #2457
2026-12-03 16:26:00 -05:00
Kurt Himebauch 312069603a Put the VR session page in More by default (#3655) 2026-12-03 15:54:27 -05:00
Kurt Himebauch 3988f52480 feat(updates): lead with the installed build, one-row channel picker, clearer offer; agent images in chat (#3643) 2026-12-03 15:53:59 -05:00
Kurt Himebauch 59eaa0eb06 fix(agent): after agent setup, Gradle and git work on the device (#3642) 2026-12-03 15:53:28 -05:00
Kurt Himebauch 811e285834 Remove manual Lossless Scaling DLL import (#3654)
Remove the picker and import paths. Ignore manually imported caches; keep LSFG from Steam installations.
2026-12-03 15:45:14 -05:00
Kurt Himebauch f75cb387eb Render the Steam home tab at 60 FPS (#3647)
Raise the shared Steam home idle animation cadence from 30 to 60 FPS without changing mixed-refresh displays or in-game frame limits.
2026-12-03 14:21:26 -05:00
Kurt Himebauch 18d735b4c4 feat(ui): tabs that do not fit a narrow page open as a dropdown (#3640)
* feat(ui): tabs that do not fit a narrow page open as a dropdown

In portrait or on a narrow page, a row of section pills that would scroll
sideways becomes one chip naming the shown section, which opens the list of
sections, as the second screen's picker does. Covers the sheets' pills
(Steam, desktop, glasses, Settings and the others on SheetChips), TabStrip,
the game page's tabs and the Stores chips.

* fix(stores): the compact store picker takes controller focus, survives a hidden store and keeps the signed-out status

* fix(ui): picking the shown tab from the tab menu still activates it
2026-12-03 13:49:09 -05:00
Kurt Himebauch 7138f95c90 fix(onboarding): no wireless-debugging step on first run when the session runs outside the child-process count (#3639)
Before the runtime is installed, the rootfs has no native hook yet, so the
child-process check assumed the next session would be counted and showed
"Finish setup" for wireless debugging. The session stages the hook from the
APK before it starts, so predict the next session from the setting and the
rootfs loader instead; a runtime still to be installed will have one.
2026-12-03 12:45:41 -05:00
Kurt Himebauch 8b3cc7eb15 Wire XR keyboard text into the session input queue (#3631)
Initialize KeyboardHost with the updated key and text callbacks. Keep XR physical-key routing and use the regular ordered compositor queue for text.
2026-12-03 09:54:26 -05:00
Ben Pfeiffer 2f16ea63aa fix(gpu): distinguish Adreno X1-45 and remove generic renderD128 check
- Distinguish Adreno X1-45 (Snapdragon X Plus / purwa) from Adreno X1-85
  (Snapdragon X Elite / hamoa) in GpuInfo, falling back to neutral 'Adreno X1'
  when the exact variant is unspecified.
- Remove generic /sys/class/drm/renderD128 check from DeviceSupport.adreno()
  so non-Qualcomm DRM GPUs are not erroneously marked as Adreno.
- Add unit tests verifying X1 variant name resolution.
2026-10-24 00:31:49 +00:00
Kurt Himebauch 151b2c304f Merge current main into PR #524 2026-10-22 13:11:01 -04:00
Kurt Himebauch b3e9ea5620 Merge current main into PR #524 2026-10-22 12:13:45 -04:00
Kurt Himebauch a4a5a88ab2 Merge remote-tracking branch 'origin/main' into fix/pr-524-authorship-conflict 2026-10-22 11:36:38 -04:00
Kurt Himebauch 839a00a8aa Merge remote-tracking branch 'origin/main' into fix/pr-524-authorship-conflict
# Conflicts:
#	app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt
2026-10-22 11:36:01 -04:00
xXJsonDeruloXx a7f7a17a69 Merge main into Adreno X1 detection PR 2026-10-22 10:04:51 -04:00
xXJsonDeruloXx 74a77c1402 fix: keep the GPU hardware fallback non-null when Build.HARDWARE is unset 2026-10-18 17:49:52 -04:00
xXJsonDeruloXx 673c9869f8 chore: merge main to catch up with 0.5.0 2026-10-18 16:49:16 -04:00
BenPfeiffer-TX 215ed5aaed Merge branch 'main' into feat/adreno-x185-detection 2026-10-11 15:11:04 -05:00
BenPfeiffer-TX 7b91aea0fc Merge branch 'main' into feat/adreno-x185-detection 2026-10-11 09:22:07 -05:00
Ben Pfeiffer 2b424bdfe7 feat(gpu): default to nolrz and nolrzfc on Adreno X1-85 to prevent depth dithering
Turnip's Low-Resolution Z (LRZ / early-Z) depth tile cache can desynchronize
on Adreno 741 (X1-85 / X1-45), leading to checkerboard or dithering depth
artifacts in 3D titles and Vulkan presentation.

Default TU_DEBUG to 'nolrz,nolrzfc' on GPU model 741 in both GameEnvironment
defaults (Proton games) and SessionService (Gamescope/Steam session), while
preserving user overrides.
2026-10-10 17:22:07 +00:00
Ben Pfeiffer a4e6279a8d feat(gpu): add Snapdragon X Elite and Adreno X1-85 detection 2026-10-09 02:51:29 +00:00
211 changed files with 7814 additions and 1197 deletions

No files matched your search

+3 -1
View File
@@ -178,8 +178,10 @@ jobs:
PY
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
# A pull request's cache is visible only to that pull request, and each copy is hundreds of megabytes against the
# repository's 10 GB cache limit. Only main saves, so every pull request restores main's set.
- name: Store Robolectric's Android jars
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
if: always() && github.event_name != 'pull_request' && steps.robolectric-jars-final.outputs.save == 'true'
uses: actions/cache/save@v4
with:
path: ${{ steps.robolectric-jars.outputs.path }}
+1 -1
View File
@@ -113,7 +113,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Steam audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink`.
- The DroidDeck HUD is [@The412Banner](https://github.com/The412Banner)'s [FusionHUD](https://github.com/The412Banner/FusionHUD) (GPL-3.0 with an attribution term). Its readings match Valve's [MangoHud](https://github.com/flightlessmango/MangoHud) build (MIT), with frame times from gamescope patch 0125.
- The HUD's CPU, GPU load, thermal and battery readers come from [@xXJSONDeruloXx](https://github.com/xXJSONDeruloXx)'s work.
- LSFG frame generation comes from Camille LaVey and the [Eden](https://eden-emu.dev) project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported by [@maxjivi05](https://github.com/maxjivi05). It needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders.
- LSFG frame generation comes from Camille LaVey and the [Eden](https://eden-emu.dev) project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported by [@maxjivi05](https://github.com/maxjivi05). It requires [Lossless Scaling](https://store.steampowered.com/app/993090/) installed through Steam and ships none of its shaders.
- Black frame insertion follows the design of [@artzox](https://github.com/artzox)'s [BFI Presenter](https://github.com/artzox/BFI-Presenter) (GPL-3.0): the strobe runs on the display's refresh clock and the game is paced to the lit refresh. Both build on [Blur Busters](https://blurbusters.com)' research on MPRT and motion blur. No BFI Presenter code is used.
- Remote Play decodes through Android's MediaCodec or the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) in Steam's runtime. Qualcomm low latency settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0).
- [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) sockets use the settings in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions.
@@ -59,7 +59,7 @@ internal fun sampleState(
internal val sampleActions: FrontEndActions = FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {},
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
onFrameGenPick = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
onFiles = {}, onLogs = {}, onOffline = {},
onSetPhantomProcessLimit = { _, _ -> },
)
@@ -82,7 +82,7 @@ internal fun sampleDrawerActions(
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 = {},
onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = if (steam) ({}) else null, onQam = if (steam) ({}) else null,
onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {},
)
+2
View File
@@ -40,6 +40,8 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />
+17
View File
@@ -28,6 +28,19 @@ float_code() {
[ "$result" = ok ]
}
# git pushes through gh's sign-in and commits as the signed-in account, with its no-reply address.
configure_git() {
gh auth setup-git || return 1
[ -n "$(git config --global user.name)" ] && [ -n "$(git config --global user.email)" ] && return 0
local user id login name
user=$(gh api user -q '"\(.id) \(.login) \(.name // .login)"') || return 1
read -r id login name <<<"$user"
[ -n "$id" ] && [ -n "$login" ] || return 1
[ -n "$(git config --global user.name)" ] || git config --global user.name "${name:-$login}"
[ -n "$(git config --global user.email)" ] || git config --global user.email "$id+$login@users.noreply.github.com"
}
if [ "${1:-}" = --git ]; then configure_git; exit; fi
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
gh_pid=$GH_PID
exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}"
@@ -48,5 +61,9 @@ while IFS= read -r line <&"$ghout"; do
done
wait "$gh_pid"
status=$?
if [ $status = 0 ] && ! configure_git; then
echo "Signed in, but git could not be set up: run dd-gh-login --git"
status=1
fi
[ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code"
exit $status
+11
View File
@@ -10,6 +10,17 @@ add_subdirectory(adrenotools)
add_subdirectory(thirdparty/dxbc)
# Pin ZeroFG to a fixed revision instead of vendoring thousands of generated shader lines.
include(FetchContent)
set(ZEROFG_VULKAN_HEADERS_DIR "${CMAKE_SYSROOT}/usr/include" CACHE PATH "" FORCE)
set(ZEROFG_PREBUILT_SHADERS ON CACHE STRING "" FORCE)
FetchContent_Declare(zerofg
GIT_REPOSITORY https://github.com/hy300leosquizz-ctrl/ZeroFG.git
GIT_TAG e6ca7ef9f9765db89847b6d8eed352e458f1a8bb
GIT_PROGRESS TRUE
)
FetchContent_MakeAvailable(zerofg)
set(DDFG_UPSTREAM "v0.3.0")
set(DDFG_CHAIN_SRC
framegen/ddfg/framegen.cpp
+14
View File
@@ -1,4 +1,5 @@
#include <errno.h>
#include <fcntl.h>
#include <jni.h>
#include <limits.h>
#include <linux/futex.h>
@@ -27,3 +28,16 @@ Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass cla
(void)clazz;
return syscall(SYS_tgkill, tgid, tid, signal) == 0 ? 0 : errno;
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_session_PageCacheNative_fadviseDontNeed(JNIEnv *env, jclass clazz, jstring path) {
(void)clazz;
const char *chars = (*env)->GetStringUTFChars(env, path, NULL);
if (!chars) return ENOMEM;
int fd = open(chars, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
(*env)->ReleaseStringUTFChars(env, path, chars);
if (fd < 0) return errno;
int rc = posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
close(fd);
return rc;
}
@@ -0,0 +1 @@
ZeroFG is fetched by CMake from hy300leosquizz-ctrl/ZeroFG (the upstream repository) at pinned commit e6ca7ef9f9765db89847b6d8eed352e458f1a8bb. DroidDeck keeps ownership of presentation; the independent presenter is not used. License: Apache-2.0 OR GPL-2.0-or-later; see the fetched ZeroFG source tree for the license text.
+8 -2
View File
@@ -42,6 +42,11 @@ add_library(droiddeckwayland SHARED
src/hudframes.c
src/hudframes_jni.c
)
option(DROIDDECK_FRAME_ACQUIRE_PROBE "Build opt-in signaled producer acquire protocol support" ON)
if (DROIDDECK_FRAME_ACQUIRE_PROBE)
target_sources(droiddeckwayland PRIVATE generated/droiddeck-frame-acquire-v1-protocol.c)
target_compile_definitions(droiddeckwayland PRIVATE DROIDDECK_FRAME_ACQUIRE_PROBE=1)
endif()
target_compile_options(droiddeckwayland PRIVATE
$<$<COMPILE_LANGUAGE:C>:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>)
target_include_directories(droiddeckwayland PRIVATE
@@ -59,6 +64,7 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
message(STATUS "droiddeckwayland: frame-generation engines built in (LSFG Native, DD-FG Native)")
target_sources(droiddeckwayland PRIVATE
src/framegen_engine.cpp
src/framegen_zerofg.cpp
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_probe.cpp
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dll.cpp
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dxbc.cpp
@@ -85,12 +91,12 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../framegen
)
target_compile_options(droiddeckwayland PRIVATE
$<$<COMPILE_LANGUAGE:CXX>:-std=c++17 -fvisibility=hidden>)
$<$<COMPILE_LANGUAGE:CXX>:-std=c++20 -fvisibility=hidden>)
target_compile_definitions(droiddeckwayland PRIVATE
DDFG_UPSTREAM="${DDFG_UPSTREAM}"
DDFG_CHAIN_HASH="${DDFG_CHAIN_HASH}"
)
target_link_libraries(droiddeckwayland dxbc atomic)
target_link_libraries(droiddeckwayland dxbc atomic zerofg::zerofg)
else()
message(STATUS "droiddeckwayland: frame-generation engines NOT built in (standalone build): stub")
target_sources(droiddeckwayland PRIVATE src/framegen_engine_stub.c)
@@ -0,0 +1,35 @@
/* Generated by wayland-scanner 1.22.0 */
#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
extern const struct wl_interface wl_buffer_interface;
extern const struct wl_interface wl_surface_interface;
static const struct wl_interface *droiddeck_frame_acquire_v1_types[] = {
&wl_surface_interface,
&wl_buffer_interface,
NULL,
};
static const struct wl_message droiddeck_frame_acquire_v1_requests[] = {
{ "destroy", "", droiddeck_frame_acquire_v1_types + 0 },
{ "set_acquire_fence", "ooh", droiddeck_frame_acquire_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface droiddeck_frame_acquire_v1_interface = {
"droiddeck_frame_acquire_v1", 1,
2, droiddeck_frame_acquire_v1_requests,
0, NULL,
};
@@ -0,0 +1,128 @@
/* Generated by wayland-scanner 1.22.0 */
#ifndef DROIDDECK_FRAME_ACQUIRE_V1_SERVER_PROTOCOL_H
#define DROIDDECK_FRAME_ACQUIRE_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_frame_acquire_v1 The droiddeck_frame_acquire_v1 protocol
* @section page_ifaces_droiddeck_frame_acquire_v1 Interfaces
* - @subpage page_iface_droiddeck_frame_acquire_v1 - DroidDeck producer write completion for a single Wayland attachment
*/
struct droiddeck_frame_acquire_v1;
struct wl_buffer;
struct wl_surface;
#ifndef DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE
#define DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE
/**
* @page page_iface_droiddeck_frame_acquire_v1 droiddeck_frame_acquire_v1
* @section page_iface_droiddeck_frame_acquire_v1_desc Description
*
* Optional explicit acquire sideband independent of DRM syncobj and buffer
* allocation. Binding does not opt the client out of ordinary wl_buffer
* release or existing synchronization protocols. The server advertises it
* only when it implements all semantics for the selected display path.
* @section page_iface_droiddeck_frame_acquire_v1_api API
* See @ref iface_droiddeck_frame_acquire_v1.
*/
/**
* @defgroup iface_droiddeck_frame_acquire_v1 The droiddeck_frame_acquire_v1 interface
*
* Optional explicit acquire sideband independent of DRM syncobj and buffer
* allocation. Binding does not opt the client out of ordinary wl_buffer
* release or existing synchronization protocols. The server advertises it
* only when it implements all semantics for the selected display path.
*/
extern const struct wl_interface droiddeck_frame_acquire_v1_interface;
#endif
#ifndef DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM
#define DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM
enum droiddeck_frame_acquire_v1_error {
/**
* not the same client's pending DMA-BUF attachment
*/
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT = 0,
/**
* that attachment already has an acquire fence
*/
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE = 1,
/**
* not a real successfully signaled Linux sync_file
*/
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE = 2,
/**
* not the paired test peer
*/
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER = 3,
};
#endif /* DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM */
/**
* @ingroup iface_droiddeck_frame_acquire_v1
* @struct droiddeck_frame_acquire_v1_interface
*/
struct droiddeck_frame_acquire_v1_interface {
/**
*/
void (*destroy)(struct wl_client *client,
struct wl_resource *resource);
/**
* set a one-shot kernel sync_file for the pending attachment
*
* After wl_surface.attach of a non-null buffer, and before its
* next wl_surface.commit, send the producer's final writer fence
* for that exact attachment. This outer probe requires that fence
* to have already successfully signaled. The fence must be a real
* Linux sync_file, not a dma-buf, eventfd, or Vulkan OPAQUE_FD.
* The server consumes its received descriptor once for that
* attachment; the caller closes its local FD after marshalling.
*
* The receiver validates the matching pending surface and buffer
* and validates the descriptor. A duplicate, invalid, pending or
* mismatched request is a protocol error; it is never downgraded
* to implicit sync. Another attach (even the same wl_buffer),
* detach, surface/resource loss or supersession makes the old
* proof inapplicable. Metadata-only commits may amend
* receiver-side still-pending state but cannot introduce or re-use
* a fence themselves. If no request was made, the receiver keeps
* its established safe path. If a valid fence has been accepted
* and later the layer is ineligible, the buffer must not be
* copied/read before that fence is satisfied or imported as the
* source dependency. Transport never implies readiness on missed
* deadlines and never changes release/retirement requirements.
* @param fence producer's native acquire sync_file
*/
void (*set_acquire_fence)(struct wl_client *client,
struct wl_resource *resource,
struct wl_resource *surface,
struct wl_resource *buffer,
int32_t fence);
};
/**
* @ingroup iface_droiddeck_frame_acquire_v1
*/
#define DROIDDECK_FRAME_ACQUIRE_V1_DESTROY_SINCE_VERSION 1
/**
* @ingroup iface_droiddeck_frame_acquire_v1
*/
#define DROIDDECK_FRAME_ACQUIRE_V1_SET_ACQUIRE_FENCE_SINCE_VERSION 1
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="droiddeck_frame_acquire_v1">
<interface name="droiddeck_frame_acquire_v1" version="1">
<description summary="DroidDeck producer write completion for a single Wayland attachment">
Optional explicit acquire sideband independent of DRM syncobj and buffer
allocation. Binding does not opt the client out of ordinary wl_buffer
release or existing synchronization protocols. The server advertises it
only when it implements all semantics for the selected display path and
only to the test fixture's app-authorized Gamescope worker.
</description>
<request name="destroy" type="destructor"/>
<enum name="error">
<entry name="invalid_attachment" value="0" summary="not the same client's pending DMA-BUF attachment"/>
<entry name="duplicate_fence" value="1" summary="that attachment already has an acquire fence"/>
<entry name="invalid_fence" value="2" summary="not a real successfully signaled Linux sync_file"/>
<entry name="unauthorized_peer" value="3" summary="not the paired test peer"/>
</enum>
<request name="set_acquire_fence">
<description summary="set a one-shot kernel sync_file for the pending attachment">
After wl_surface.attach of a non-null buffer, and before its next
wl_surface.commit, send the producer's final writer fence for that
exact attachment. This outer probe requires that fence to have already
successfully signaled. The fence must be a real Linux sync_file, not a
dma-buf, eventfd, or Vulkan OPAQUE_FD. The server consumes its received
descriptor once for that attachment; the caller closes its local FD
after marshalling.
The receiver validates the matching pending surface and buffer and
validates the descriptor. A duplicate, invalid, pending or mismatched
request is a protocol error; it is never downgraded to implicit sync. Another attach (even the same
wl_buffer), detach, surface/resource loss or supersession makes the
old proof inapplicable. Metadata-only commits may amend receiver-side
still-pending state but cannot introduce or re-use a fence themselves.
If no request was made, the receiver keeps its established safe path.
If a valid fence has been accepted and later the layer is ineligible,
the buffer must not be copied/read before that fence is satisfied or
imported as the source dependency. Transport never implies readiness
on missed deadlines and never changes release/retirement requirements.
</description>
<arg name="surface" type="object" interface="wl_surface"/>
<arg name="buffer" type="object" interface="wl_buffer"/>
<arg name="fence" type="fd" summary="producer's native acquire sync_file"/>
</request>
</interface>
</protocol>
@@ -54,6 +54,7 @@ static struct wl_list g_clients;
static uint64_t g_next_id = 1;
static struct wl_event_loop *g_loop;
static unsigned g_stat_zero_copy;
static unsigned g_stat_producer_fence;
static int g_export_failed_logged, g_import_failed_logged;
static int g_advertised;
static int g_mode_sent = -1;
@@ -201,31 +202,47 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL;
if (!ab) return -1;
int dmabuf_fd = droiddeck_dmabuf_fd(b);
int acquire = -1;
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
acquire = exp.fd;
} else {
if (!g_export_failed_logged) {
g_export_failed_logged = 1;
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
int acquire = droiddeck_surface_dup_acquire(s, b);
if (acquire == -2) return -1;
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
const int explicit_acquire = acquire >= 0;
#endif
if (acquire < 0) {
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
acquire = exp.fd;
} else {
if (!g_export_failed_logged) {
g_export_failed_logged = 1;
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
}
if (dmabuf_fd >= 0) {
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
if (draw) return -1;
}
if (dmabuf_fd >= 0) {
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
if (draw) return -1;
}
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;
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
static int explicit_logged;
if (explicit_acquire && !explicit_logged) {
explicit_logged = 1;
droiddeck_log("layer", "probe: SurfaceControl accepted a verified producer acquire fence");
}
#endif
if (!ab->on_layer) {
ab->on_layer = 1;
g_stat_zero_copy++;
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
if (explicit_acquire) g_stat_producer_fence++;
#endif
g_last_zero_copy_ns = now_ns();
}
if (s && g_announced != s) {
@@ -265,6 +282,12 @@ unsigned ahb_swapchain_stats_take(void) {
return n;
}
unsigned ahb_swapchain_producer_fence_stats_take(void) {
unsigned n = g_stat_producer_fence;
g_stat_producer_fence = 0;
return n;
}
int ahb_swapchain_advertised(void) { return g_advertised; }
uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b) {
@@ -20,7 +20,9 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
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);
unsigned ahb_swapchain_producer_fence_stats_take(void);
int ahb_swapchain_advertised(void);
int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b);
uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b);
void ahb_swapchain_layer_released(void *token, int release_fd);
+258 -5
View File
@@ -24,6 +24,14 @@
#include "linux-dmabuf-v1-server-protocol.h"
#include "sc_layer.h"
#include "ahb_swapchain.h"
#include "frame_acquire.h"
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
#include "droiddeck-frame-acquire-v1-server-protocol.h"
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/stat.h>
#include "frame_worker_peer.h"
#endif
#include "display_buffers.h"
#include "viewporter-server-protocol.h"
#include "droiddeck-desktop-v1-server-protocol.h"
@@ -211,6 +219,7 @@ struct surface {
struct wl_list link;
struct wl_resource *pending_buffer;
struct dd_frame_acquire pending_frame_acquire, frame_acquire;
struct wl_listener pending_buffer_destroy;
int pending_attach;
int pending_src_set, pending_dst_set;
@@ -334,6 +343,7 @@ volatile int g_hide_shell;
volatile int g_zero_copy;
static int g_zero_copy_paused;
static int g_mirror_capture;
extern volatile int g_display_buffer_driver;
extern void droiddeck_on_overlay_planes(int planes);
static int g_overlay_planes_told = -1;
@@ -827,6 +837,7 @@ static void unmap_toplevel(struct surface *s) {
}
static void drop_dmabuf(struct surface *s, int paced) {
dd_frame_acquire_clear(&s->frame_acquire);
if (s->dmabuf) {
wl_list_remove(&s->dmabuf_destroy.link);
if (buffer_shown_elsewhere(s->dmabuf, s)) {
@@ -842,18 +853,21 @@ static void drop_dmabuf(struct surface *s, int paced) {
static void on_dmabuf_destroyed(struct wl_listener *l, void *data) {
struct surface *s = wl_container_of(l, s, dmabuf_destroy);
dd_frame_acquire_clear(&s->frame_acquire);
wl_list_remove(&s->dmabuf_destroy.link);
s->dmabuf = NULL;
}
static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) {
struct surface *s = wl_container_of(l, s, pending_buffer_destroy);
dd_frame_acquire_clear(&s->pending_frame_acquire);
wl_list_remove(&s->pending_buffer_destroy.link);
wl_list_init(&s->pending_buffer_destroy.link);
s->pending_buffer = NULL;
}
struct surface_state {
struct dd_frame_acquire frame_acquire;
struct wl_resource *buffer;
struct wl_listener buffer_destroy;
int attach;
@@ -866,6 +880,7 @@ struct surface_state {
static void on_state_buffer_destroyed(struct wl_listener *l, void *data) {
struct surface_state *st = wl_container_of(l, st, buffer_destroy);
dd_frame_acquire_clear(&st->frame_acquire);
wl_list_remove(&st->buffer_destroy.link);
wl_list_init(&st->buffer_destroy.link);
st->buffer = NULL;
@@ -874,6 +889,8 @@ static void on_state_buffer_destroyed(struct wl_listener *l, void *data) {
static void surface_state_take(struct surface *s, struct surface_state *st) {
st->attach = s->pending_attach;
st->frame_acquire = s->pending_frame_acquire;
s->pending_frame_acquire.fd_plus_one = 0;
st->buffer = s->pending_buffer;
wl_list_init(&st->buffer_destroy.link);
if (st->buffer) {
@@ -1186,6 +1203,7 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r,
if (s->pending_buffer) wl_list_remove(&s->pending_buffer_destroy.link);
wl_list_init(&s->pending_buffer_destroy.link);
s->pending_buffer = buffer;
dd_frame_acquire_clear(&s->pending_frame_acquire);
s->pending_attach = 1;
if (buffer) {
s->pending_buffer_destroy.notify = on_pending_buffer_destroyed;
@@ -1451,6 +1469,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
surface_drop_idle(s);
buf_trace_attach(buffer);
dd_frame_acquire_clear(&s->frame_acquire);
if (s->role == ROLE_CURSOR) {
if (!buffer) {
cursor_publish_hidden();
@@ -1462,6 +1481,8 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
if (buffer) surface_hold_idle(s, buffer);
} else if (db) {
take_dmabuf(s, db, buffer);
s->frame_acquire = st->frame_acquire;
st->frame_acquire.fd_plus_one = 0;
} else if (shm) {
drop_dmabuf(s, 1);
take_shm(s, shm, buffer);
@@ -1474,6 +1495,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
if (buffer) send_buffer_release(buffer);
}
}
dd_frame_acquire_clear(&st->frame_acquire);
pending_releases_apply(s);
wl_list_for_each(child, &s->children, child_link) {
@@ -1538,6 +1560,7 @@ static void settle_unwaited(void) {
}
static void surface_state_discard(struct surface_state *st) {
dd_frame_acquire_clear(&st->frame_acquire);
struct wl_resource *cb, *tmp;
wl_list_remove(&st->buffer_destroy.link);
wl_resource_for_each_safe(cb, tmp, &st->frames) wl_resource_destroy(cb);
@@ -1549,6 +1572,8 @@ static void surface_state_merge(struct surface_state *older, struct surface_stat
if (older->attach && !newer->attach) {
newer->attach = 1;
newer->buffer = older->buffer;
newer->frame_acquire = older->frame_acquire;
older->frame_acquire.fd_plus_one = 0;
wl_list_remove(&older->buffer_destroy.link);
wl_list_init(&older->buffer_destroy.link);
if (newer->buffer) {
@@ -1700,6 +1725,210 @@ static const struct wl_surface_interface surface_impl = {
.offset = surface_offset,
};
int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b) {
return s && s->dmabuf && s->dmabuf_buf == b ? dd_frame_acquire_dup(&s->frame_acquire) : -1;
}
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
// Private signed fixture: only the app-owned worker decision may issue a grant.
static pthread_mutex_t frame_worker_lock = PTHREAD_MUTEX_INITIALIZER;
static char frame_worker_file[PATH_MAX];
static struct dd_worker_grant frame_worker_grant;
static int frame_worker_pidfd = -1;
static bool frame_worker_map_reported;
static enum dd_worker_stat_result frame_worker_starttime(pid_t pid, uint64_t *out) {
char proc[64], line[4096];
snprintf(proc, sizeof(proc), "/proc/%d/stat", pid);
FILE *f = fopen(proc, "re");
if (!f) return dd_worker_open_failure(errno);
// Proc writes one bounded line; truncation is a read failure, not invisibility.
bool read = fgets(line, sizeof(line), f) != NULL && strchr(line, '\n') != NULL;
fclose(f);
return read ? dd_worker_parse_start(line, out) : DD_WORKER_STAT_READ;
}
void droiddeck_frame_worker_revoke(int owner, int pid) {
pthread_mutex_lock(&frame_worker_lock);
if (frame_worker_grant.owner == (uint32_t)owner &&
(!pid || frame_worker_grant.pid == (uint32_t)pid)) {
if (frame_worker_pidfd >= 0) close(frame_worker_pidfd);
frame_worker_pidfd = -1;
frame_worker_grant = (struct dd_worker_grant){0};
}
pthread_mutex_unlock(&frame_worker_lock);
}
int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path,
uint64_t expected_dev, uint64_t expected_ino, uint64_t receipt) {
struct stat st;
if (owner <= 0 || pid <= 1 || !receipt || !path ||
strlen(path) >= sizeof(frame_worker_file) || lstat(path, &st) < 0 || !S_ISREG(st.st_mode) ||
(uint64_t)st.st_dev != expected_dev || (uint64_t)st.st_ino != expected_ino ||
st.st_uid != getuid()) {
droiddeck_log("probe", "worker_admission=NATIVE_FILE");
return 0;
}
int pidfd = syscall(__NR_pidfd_open, pid, 0);
if (pidfd < 0) {
droiddeck_log("probe", "worker_admission=NATIVE_PIDFD");
return 0; // No fallback to a recyclable PID.
}
struct pollfd alive = {.fd = pidfd, .events = POLLIN};
uint64_t raw_start = 0;
enum dd_worker_stat_result stat = frame_worker_starttime(pid, &raw_start);
switch (stat) {
case DD_WORKER_STAT_OK:
if (raw_start != receipt) droiddeck_log("probe", "worker_admission=NATIVE_STAT_MISMATCH");
break;
case DD_WORKER_STAT_DENIED: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_DENIED"); break;
case DD_WORKER_STAT_HIDDEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_HIDDEN"); break;
case DD_WORKER_STAT_OPEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_OTHER"); break;
case DD_WORKER_STAT_READ: droiddeck_log("probe", "worker_admission=NATIVE_STAT_READ"); break;
case DD_WORKER_STAT_PARSE: droiddeck_log("probe", "worker_admission=NATIVE_STAT_PARSE"); break;
case DD_WORKER_STAT_ZERO: droiddeck_log("probe", "worker_admission=NATIVE_STAT_ZERO"); break;
}
if (!dd_worker_receipt_allows_reserve(stat, raw_start, receipt)) { close(pidfd); return 0; }
if (poll(&alive, 1, 0) != 0) {
droiddeck_log("probe", "worker_admission=NATIVE_PIDFD_NOT_LIVE");
close(pidfd);
return 0;
}
pthread_mutex_lock(&frame_worker_lock);
if (frame_worker_pidfd < 0) {
strcpy(frame_worker_file, path);
frame_worker_grant = (struct dd_worker_grant){
.owner = owner, .uid = getuid(), .pid = pid, .start_ticks = receipt, .expires = expires,
.dev_major = major(st.st_dev), .dev_minor = minor(st.st_dev), .ino = st.st_ino,
.canonical_file = frame_worker_file, .app_launch_verified = true, .final_go = true,
};
frame_worker_map_reported = false;
frame_worker_pidfd = pidfd;
pidfd = -1;
}
pthread_mutex_unlock(&frame_worker_lock);
if (pidfd >= 0) {
droiddeck_log("probe", "worker_admission=NATIVE_ALREADY_RESERVED");
close(pidfd);
return 0;
}
droiddeck_log("probe", "frame acquire reserved one app-verified worker");
return 1;
}
static bool frame_worker_verified_exec_locked(const struct dd_worker_grant *g, uint64_t now) {
char proc[64], line[PATH_MAX + 128];
const char *failure = "worker_admission=MAP_STARTTIME";
uint64_t raw_start = 0;
if (frame_worker_starttime(g->pid, &raw_start) != DD_WORKER_STAT_OK || raw_start != g->start_ticks)
goto reject;
snprintf(proc, sizeof(proc), "/proc/%u/maps", g->pid);
FILE *f = fopen(proc, "re");
failure = "worker_admission=MAP_OPEN";
if (!f) goto reject;
bool matched = false;
size_t budget = 2 * 1024 * 1024;
while (budget && fgets(line, sizeof(line), f)) {
size_t n = strlen(line);
if (!n || line[n - 1] != '\n' || n > budget) break;
budget -= n;
if (dd_worker_grant_matches(g, g->owner, g->uid, g->pid, raw_start, now, line)) {
matched = true;
break;
}
}
fclose(f);
if (matched) return true;
failure = "worker_admission=MAP_IDENTITY";
reject:
if (!frame_worker_map_reported) {
frame_worker_map_reported = true;
droiddeck_log("probe", "%s", failure);
}
return false;
}
static int frame_acquire_peer_allowed(const struct wl_client *client, bool verify_exec, bool bind) {
pid_t pid = 0;
uid_t uid = (uid_t)-1;
wl_client_get_credentials(client, &pid, &uid, NULL);
struct timespec t;
if (clock_gettime(CLOCK_BOOTTIME, &t) < 0) return 0;
uint64_t now = (uint64_t)t.tv_sec * 1000 + (uint64_t)t.tv_nsec / 1000000;
pthread_mutex_lock(&frame_worker_lock);
const struct dd_worker_grant *g = &frame_worker_grant;
struct pollfd alive = {.fd = frame_worker_pidfd, .events = POLLIN};
bool allowed = frame_worker_pidfd >= 0 && uid == getuid() && pid > 1 &&
g->pid == (uint32_t)pid && g->uid == uid && now < g->expires &&
poll(&alive, 1, 0) == 0 && (!verify_exec ||
(frame_worker_verified_exec_locked(g, now) && poll(&alive, 1, 0) == 0));
// The short startup authorization may not be renewed by registry enumeration.
// Only an authenticated bind activates the grant for the lifetime of this live,
// unreplaced worker; session teardown revokes it independently of process exit.
if (allowed && bind) frame_worker_grant.expires = UINT64_MAX;
pthread_mutex_unlock(&frame_worker_lock);
return allowed;
}
static bool frame_acquire_global_filter(const struct wl_client *client, const struct wl_global *global, void *data) {
return wl_global_get_interface(global) != &droiddeck_frame_acquire_v1_interface ||
frame_acquire_peer_allowed(client, true, false);
}
static void frame_acquire_destroy(struct wl_client *client, struct wl_resource *resource) {
wl_resource_destroy(resource);
}
static void frame_acquire_set(struct wl_client *client, struct wl_resource *resource,
struct wl_resource *surface, struct wl_resource *buffer, int32_t fd) {
if (!frame_acquire_peer_allowed(client, false, false)) {
close(fd);
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER,
"paired capture peer is not authorized");
return;
}
struct surface *s = NULL;
if (surface && buffer && wl_resource_get_client(surface) == client &&
wl_resource_get_client(buffer) == client &&
wl_resource_instance_of(surface, &wl_surface_interface, &surface_impl) &&
get_dmabuf(buffer))
s = wl_resource_get_user_data(surface);
if (!s || !s->pending_attach || s->pending_buffer != buffer) {
close(fd);
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT,
"fence does not match pending DMA-BUF attachment");
return;
}
enum dd_frame_acquire_result result = dd_frame_acquire_set(&s->pending_frame_acquire, fd);
if (result == DD_ACQUIRE_DUPLICATE)
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE,
"pending attachment already has a fence");
else if (result == DD_ACQUIRE_INVALID)
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE,
"expected an already signaled Linux sync_file");
}
static const struct droiddeck_frame_acquire_v1_interface frame_acquire_impl = {
.destroy = frame_acquire_destroy,
.set_acquire_fence = frame_acquire_set,
};
static void bind_frame_acquire(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
if (!frame_acquire_peer_allowed(client, true, true)) {
wl_client_post_implementation_error(client, "paired capture peer is not authorized");
return;
}
struct wl_resource *resource =
wl_resource_create(client, &droiddeck_frame_acquire_v1_interface, 1, id);
if (!resource) {
wl_client_post_no_memory(client);
return;
}
wl_resource_set_implementation(resource, &frame_acquire_impl, NULL, NULL);
droiddeck_log("probe", "frame acquire bound to app-issued worker and exact executable map");
}
#endif
static void detach_from_parent(struct surface *s) {
if (!s->parent) return;
wl_list_remove(&s->child_link);
@@ -1709,6 +1938,7 @@ static void detach_from_parent(struct surface *s) {
static void surface_resource_destroy(struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
dd_frame_acquire_clear(&s->pending_frame_acquire);
struct surface *child, *tmp;
struct wl_resource *cb, *cbtmp;
@@ -2732,7 +2962,7 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
static int said = -1, said_tm = -1;
static const char *said_why;
const int tm = route != 0 && !droiddeck_color_output();
if (route == said && tm == said_tm && (route != 1 || hs->why == said_why)) return;
if (route == said && tm == said_tm && (route < 1 || route > 2 || hs->why == said_why)) return;
int was = said;
said = route; said_why = hs->why; said_tm = tm;
char name[160] = "the HDR game";
@@ -2749,6 +2979,10 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
"BT2020_PQ", name, hs->why ? hs->why : "?", droiddeck_color_sdr_white());
break;
case 2:
if (g_mirror_capture) {
droiddeck_log("color", "Mirror: %s is composed through the screen swapchain", name);
break;
}
if (tm)
droiddeck_log("color", "HDR with frame generation for %s, HDR output switched off: the scene is tone-mapped to "
"SDR and presented through an SDR screen swapchain", name);
@@ -2969,6 +3203,11 @@ static void render_scene(void) {
const int cardboard = vkp_cardboard_active();
struct hdr_scene hs;
int hdr_route = hdr_plan(&dl, w, h, fx_on, framegen, &hs);
/* Mirror's PixelCopy cannot see the separate game layer. Keep unimportable frames visible on top. */
if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {
hdr_route = 2;
hs.why = "Mirror needs the screen swapchain";
}
const char *hdr_copy = NULL;
if (droiddeck_color_hdr_open()) {
hdr_note_route(hdr_route, &hs);
@@ -3034,16 +3273,16 @@ static void render_scene(void) {
else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0);
else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver";
}
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
if (hdr_route == 0 && !g_mirror_capture && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
!ahb_only) {
settle_unwaited();
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;
tell_overlay_planes();
const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer();
const int fg_layer = framegen && !g_mirror_capture && 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 li = (g_zero_copy && !g_mirror_capture && (!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; }
@@ -4773,6 +5012,12 @@ const char *droiddeck_client_name(struct wl_client *client) { return client_name
struct wl_display *droiddeck_get_display(void) { return g_display; }
void droiddeck_request_redraw(void) { schedule_render(); }
void droiddeck_set_mirror_capture(int on) {
if (g_mirror_capture == on) return;
g_mirror_capture = on;
schedule_render();
}
struct wl_resource *droiddeck_ime_target(void) {
struct surface *s;
if (g_ime_click && g_ime_click->mapped) return g_ime_click->resource;
@@ -4804,6 +5049,7 @@ static int on_stats_timer(void *data) {
struct surface *s;
wl_list_for_each(s, &g_toplevels, toplevel_link) windows++;
unsigned zero_copy = ahb_swapchain_stats_take();
unsigned verified = ahb_swapchain_producer_fence_stats_take();
unsigned layer_frames = sc_layer_frames_take();
g_zero_copy_last = zero_copy;
unsigned generated = vkp_framegen_stats_take();
@@ -4812,7 +5058,8 @@ static int on_stats_timer(void *data) {
int off = 0;
if (g_zero_copy || zero_copy) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u zero-copy frames", zero_copy);
if (layer_frames) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u layer frames", layer_frames);
if (generated) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated);
if (generated) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated);
if (verified) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u verified acquire frames", verified);
droiddeck_log("stats", "last 10 s: %u frames on screen (%.1f fps) | %u GPU frames from games | %u window redraws | %d windows open%s",
g_stat_frames + generated, (g_stat_frames + generated) / 10.0, g_stat_dmabuf, g_stat_shm, windows, extra);
}
@@ -5013,6 +5260,12 @@ int droiddeck_wayland_run(void) {
wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager);
droiddeck_ext_init(display);
ahb_swapchain_init(display);
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
if (ahb_swapchain_advertised()) {
wl_display_set_global_filter(display, frame_acquire_global_filter, NULL);
wl_global_create(display, &droiddeck_frame_acquire_v1_interface, 1, NULL, bind_frame_acquire);
}
#endif
display_buffers_init(display);
@@ -11,7 +11,7 @@
#include "ahb_swapchain.h"
#include "droiddeck_color.h"
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD };
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD, HOST_MIRROR_CAPTURE };
struct host_msg {
enum host_kind kind;
@@ -91,6 +91,9 @@ void droiddeck_host_text_delete(int before, int after) {
void droiddeck_host_zero_copy(int on, int live) {
host_post(HOST_ZERO_COPY, NULL, 0, on, live);
}
void droiddeck_host_mirror_capture(int on) {
host_post(HOST_MIRROR_CAPTURE, NULL, 0, on, 0);
}
void droiddeck_host_hdr_output(int on) {
host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0);
}
@@ -271,6 +274,9 @@ static int on_wake(int fd, uint32_t mask, void *data) {
case HOST_ZERO_COPY:
ahb_swapchain_set_mode(m->a, m->b);
break;
case HOST_MIRROR_CAPTURE:
droiddeck_set_mirror_capture(m->a);
break;
case HOST_HDR_OUTPUT:
droiddeck_color_set_output(m->a);
break;
@@ -29,6 +29,8 @@ void droiddeck_host_text_commit_and_submit(const char *utf8, int len);
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end);
void droiddeck_host_text_delete(int before, int after);
void droiddeck_host_zero_copy(int on, int live);
void droiddeck_host_mirror_capture(int on);
void droiddeck_set_mirror_capture(int on);
void droiddeck_host_hdr_output(int on);
void droiddeck_host_key(int evdev, int state);
void droiddeck_host_select_game_field(int copy);
@@ -366,6 +366,44 @@ void vkp_effects_forget_image(VkImage img) {
g_context = saved;
}
VkImageView vkp_effects_framegen_image_view(VkImage img, int w, int h, VkFormat fmt) {
if (!g_dev || !img || w <= 0 || h <= 0 || fmt == VK_FORMAT_UNDEFINED) return VK_NULL_HANDLE;
for (int i = 0; i < FX_CONTEXTS; ++i) {
struct fx_context *ctx = &g_contexts[i];
if (ctx->scene.img == img && ctx->scene.view) return ctx->scene.view;
for (int j = 0; j < 2; ++j)
if (ctx->targets[j].img == img && ctx->targets[j].view) return ctx->targets[j].view;
if (ctx->mid.img == img && ctx->mid.view) return ctx->mid.view;
if (ctx->nissrc.img == img && ctx->nissrc.view) return ctx->nissrc.view;
}
if (g_smaa_edges.img == img && g_smaa_edges.view) return g_smaa_edges.view;
if (g_smaa_weights.img == img && g_smaa_weights.view) return g_smaa_weights.view;
/* The effects chain can bypass every pass and return the compositor's scene image
* directly. Keep a view for that image in the existing per-context cache so the
* normal image-forget path destroys it before the image itself. */
int saved = g_context;
g_context = 0;
if (g_scene.img != img || g_scene.view == VK_NULL_HANDLE ||
g_scene.w != w || g_scene.h != h) {
scene_release();
VkImageView view = make_view(img, fmt);
if (!view) {
g_context = saved;
return VK_NULL_HANDLE;
}
g_scene.img = img;
g_scene.view = view;
g_scene.w = w;
g_scene.h = h;
g_scene.ds = VK_NULL_HANDLE;
}
VkImageView result = g_scene.view;
g_context = saved;
return result;
}
void vkp_effects_release_generated_sources(void) {
for (g_context = 1; g_context < FX_CONTEXTS; g_context++) scene_release();
g_context = 0;
@@ -1026,13 +1064,18 @@ VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_
struct fx_source_state source_state = {0};
VkImage result = effects_run(cmd, scene, scene_w, scene_h, out_w, out_h, res_w, res_h,
VK_IMAGE_LAYOUT_GENERAL, &g_generated_settings, &source_state);
barrier(cmd, result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);
if (result != scene)
if (result != scene) {
barrier(cmd, result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);
barrier(cmd, scene, source_state.layout, VK_IMAGE_LAYOUT_GENERAL,
source_state.stage, source_state.access,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
} else if (source_state.layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);
}
g_context = 0;
return result;
}
@@ -28,6 +28,7 @@ VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_
void vkp_effects_destroy(void);
void vkp_effects_forget_image(VkImage img);
VkImageView vkp_effects_framegen_image_view(VkImage img, int w, int h, VkFormat fmt);
void vkp_effects_set_formats(VkFormat scene_fmt, VkFormat target_fmt, int scene_is_pq);
@@ -0,0 +1,39 @@
#ifndef DD_FRAME_ACQUIRE_H
#define DD_FRAME_ACQUIRE_H
#include <fcntl.h>
#include <limits.h>
#include <linux/sync_file.h>
#include <sys/ioctl.h>
#include <unistd.h>
/* A zero-initialized slot owns no descriptor. Only an already successful
* sync_file can enter this slot; display-side release ownership is separate. */
struct dd_frame_acquire { int fd_plus_one; };
enum dd_frame_acquire_result { DD_ACQUIRE_OK, DD_ACQUIRE_DUPLICATE, DD_ACQUIRE_INVALID };
static inline void dd_frame_acquire_clear(struct dd_frame_acquire *f) {
if (f->fd_plus_one) close(f->fd_plus_one - 1);
f->fd_plus_one = 0;
}
static inline enum dd_frame_acquire_result
dd_frame_acquire_set(struct dd_frame_acquire *f, int fd) {
enum dd_frame_acquire_result result;
struct sync_file_info info = {0};
if (f->fd_plus_one) result = DD_ACQUIRE_DUPLICATE;
else if (fd < 0 || fd == INT_MAX || ioctl(fd, SYNC_IOC_FILE_INFO, &info) != 0 ||
info.status != 1 || info.num_fences == 0) result = DD_ACQUIRE_INVALID;
else {
f->fd_plus_one = fd + 1;
return DD_ACQUIRE_OK;
}
if (fd >= 0) close(fd);
return result;
}
static inline int dd_frame_acquire_dup(const struct dd_frame_acquire *f) {
if (!f->fd_plus_one) return -1; /* Legacy: no explicit attachment proof. */
int fd = fcntl(f->fd_plus_one - 1, F_DUPFD_CLOEXEC, 0);
return fd < 0 ? -2 : fd; /* Do not re-enter the legacy direct path. */
}
#endif
@@ -0,0 +1,81 @@
#ifndef DD_WORKER_PEER_H
#define DD_WORKER_PEER_H
#include <stdbool.h>
#include <stdint.h>
#include <inttypes.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* Model of one app-issued, session-bound authorization record. No callers,
* property access, proc traversal, or authorization is installed by this file. */
struct dd_worker_grant {
uint32_t owner, uid, pid, dev_major, dev_minor;
uint64_t start_ticks, ino, expires;
const char *canonical_file;
bool app_launch_verified, final_go;
};
enum dd_worker_stat_result {
DD_WORKER_STAT_OK, DD_WORKER_STAT_DENIED, DD_WORKER_STAT_HIDDEN, DD_WORKER_STAT_OPEN,
DD_WORKER_STAT_READ, DD_WORKER_STAT_PARSE, DD_WORKER_STAT_ZERO,
};
static inline enum dd_worker_stat_result dd_worker_parse_start(const char *line, uint64_t *out) {
const char *p = strrchr(line, ')');
if (!p || p[1] != ' ' || !p[2] || p[3] != ' ') return DD_WORKER_STAT_PARSE;
p += 2;
// State is field 3. The starttime (22) is always followed by vsize (23).
for (int field = 3; field < 22; ++field) {
p = strchr(p, ' ');
if (!p) return DD_WORKER_STAT_PARSE;
while (*p == ' ') ++p;
}
char *end;
if (*p < '0' || *p > '9') return DD_WORKER_STAT_PARSE;
errno = 0;
uint64_t value = strtoull(p, &end, 10);
if (errno || end == p || *end != ' ') return DD_WORKER_STAT_PARSE;
if (!value) return DD_WORKER_STAT_ZERO;
*out = value;
return DD_WORKER_STAT_OK;
}
static inline enum dd_worker_stat_result dd_worker_open_failure(int error) {
if (error == EACCES || error == EPERM) return DD_WORKER_STAT_DENIED;
if (error == ENOENT || error == ESRCH) return DD_WORKER_STAT_HIDDEN;
return DD_WORKER_STAT_OPEN;
}
static inline bool dd_worker_receipt_allows_reserve(enum dd_worker_stat_result stat,
uint64_t raw, uint64_t receipt) {
if (!receipt) return false;
if (stat == DD_WORKER_STAT_OK) return raw == receipt;
// Only a visibility denial can defer the broker-side stat check, not any
// bad read, malformed record, mismatched timestamp, or other open error.
return stat == DD_WORKER_STAT_DENIED || stat == DD_WORKER_STAT_HIDDEN;
}
static inline bool dd_worker_map_matches(const struct dd_worker_grant *g, const char *line) {
unsigned major, minor;
uint64_t lo, hi, off, ino;
int prefix = 0;
char mode[5];
if (!g->canonical_file || !*g->canonical_file ||
sscanf(line, "%" SCNx64 "-%" SCNx64 " %4s %" SCNx64 " %x:%x %" SCNu64 " %n",
&lo,&hi,mode,&off,&major,&minor,&ino,&prefix)!=7 ||
prefix <= 0 || hi <= lo || strlen(mode)!=4 || mode[2]!='x' ||
major!=g->dev_major || minor!=g->dev_minor || !ino || ino!=g->ino)
return false;
size_t path_len=strcspn(line+prefix,"\r\n");
return strlen(g->canonical_file)==path_len && !memcmp(line+prefix,g->canonical_file,path_len);
}
static inline bool dd_worker_grant_matches(const struct dd_worker_grant *g, uint32_t owner,
uint32_t uid, uint32_t pid, uint64_t start, uint64_t now, const char *executable_map) {
return g && g->app_launch_verified && g->final_go && owner && owner==g->owner &&
uid==g->uid && pid>1 && pid==g->pid && start && start==g->start_ticks &&
now<g->expires && executable_map && dd_worker_map_matches(g,executable_map);
}
#endif
@@ -3,6 +3,7 @@
#include "framegen_engine.h"
#include "effects_chain.h"
#include "vk_loader.h"
#include "sc_layer.h"
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
@@ -36,7 +37,7 @@ static VkQueue g_queue;
static uint32_t g_qfam;
static _Atomic int g_dev_ready, g_dev_lost;
static int g_features_enabled;
static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok;
static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok, g_caps_zero_ok;
static VkPhysicalDeviceMemoryProperties g_memprops;
static struct {
PFN_vkCreateImage CreateImage;
@@ -78,6 +79,24 @@ static int format_refused(VkFormat f) {
static _Atomic unsigned g_stat_generated;
static uint64_t g_total_generated;
#define FG_PROVEN_FRAMES 120
#define FG_HANG_STRIKES 2
static _Atomic int g_hang_strikes;
static int g_submitted_since_ready;
static uint64_t g_generated_at_ready;
// A driver that hangs on the engine's shaders loses the device on its first generated frame after every
// recovery, so the compositor would recover and hang again for as long as frame generation stays armed.
static int framegen_loss_strike(int submitted, uint64_t completed_since_ready) {
if (!submitted || completed_since_ready >= FG_PROVEN_FRAMES) {
atomic_store(&g_hang_strikes, 0);
return 0;
}
if (atomic_fetch_add(&g_hang_strikes, 1) + 1 < FG_HANG_STRIKES) return 0;
atomic_store(&g_hang_strikes, 0);
return 1;
}
static float g_presented_rate, g_source_rate;
static uint32_t g_present_accum, g_source_accum;
static int64_t g_window_start_ns;
@@ -87,12 +106,48 @@ static int64_t now_ns(void) {
return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
/* The pair the last run made, for the display probe and the pacer: when its real frame reached the
* compositor, the game moment each generated frame shows, and the refresh the pacer timed each for. */
static _Atomic int g_pacer_on;
static int g_layer_path;
static int g_out_gens;
static int64_t g_out_planned[VKP_FG_MAX_GENERATIONS + 1];
static int64_t g_completion_issue;
void vkp_framegen_set_pacer(int on) {
if (atomic_exchange(&g_pacer_on, on ? 1 : 0) != (on ? 1 : 0)) {
fge_pacer_reset();
FGLOG("ZeroFG pacer %s", on ? "on: frame generation times its frames itself" : "off: the display layer times them");
}
}
static int pacer_wanted(void) { return atomic_load(&g_pacer_on); }
void vkp_framegen_pacer_abort(void) {
g_completion_issue = 0;
fge_pacer_reset();
}
void vkp_framegen_output_planned(int k, int gens, int64_t *planned) {
*planned = (k < 0 || k >= gens || k >= g_out_gens)
? g_out_planned[g_out_gens] : g_out_planned[k];
}
void vkp_framegen_completed(void) {
if (!g_completion_issue) return;
fge_pacer_completed(g_completion_issue, now_ns());
g_completion_issue = 0;
}
void vkp_framegen_real_shown(int64_t planned_ns, int64_t shown_ns) { fge_pacer_shown(planned_ns, shown_ns); }
void vkp_framegen_set_engine(int kind) {
if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_DDFG) kind = VKP_FG_ENGINE_LSFG;
if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_DDFG && kind != VKP_FG_ENGINE_ZEROFG) kind = VKP_FG_ENGINE_LSFG;
atomic_store(&g_kind, kind);
atomic_store(&g_failed_kind, -1);
atomic_store(&g_cfg_dirty, 1);
atomic_store(&g_hang_strikes, 0);
}
void vkp_framegen_set_armed(int armed, int multiplier, int target_fps) {
@@ -118,6 +173,11 @@ void vkp_framegen_set_lsfg_cache_path(const char *path) {
pthread_mutex_unlock(&g_lock);
}
void vkp_framegen_set_layer_timing(int layer) {
g_layer_path = layer;
fge_set_layer_timing(layer);
}
void vkp_framegen_set_tuning(float flow_scale, float refresh_hz) {
if (flow_scale < 0.25f) flow_scale = 0.25f;
if (flow_scale > 1.0f) flow_scale = 1.0f;
@@ -146,15 +206,15 @@ static void mark_failed(int kind) {
int vkp_framegen_problem(void) {
if (!atomic_load(&g_dev_ready)) return -1;
int kind = atomic_load(&g_kind);
int caps_ok = kind == VKP_FG_ENGINE_DDFG
? atomic_load(&g_caps_ddfg_ok)
: atomic_load(&g_caps_lsfg_ok);
int caps_ok = kind == VKP_FG_ENGINE_ZEROFG ? atomic_load(&g_caps_zero_ok) :
kind == VKP_FG_ENGINE_DDFG ? atomic_load(&g_caps_ddfg_ok) :
atomic_load(&g_caps_lsfg_ok);
if (!caps_ok) return 1;
if (start_failed_for(kind)) return 2;
if (g_engine_ok && g_engine_kind == kind && fge_unavailable()) return 2;
return 0;
}
const char *vkp_framegen_caps_reason(void) { return fge_caps_reason(); }
const char *vkp_framegen_caps_reason(void) { return fge_caps_reason(atomic_load(&g_kind)); }
void vkp_framegen_stats(float out[6]) {
float accepted = 0.0f, src = 0.0f, thermal = -1.0f;
@@ -187,16 +247,33 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f
fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled);
atomic_store(&g_caps_lsfg_ok, fge_caps_ok(VKP_FG_ENGINE_LSFG));
atomic_store(&g_caps_ddfg_ok, fge_caps_ok(VKP_FG_ENGINE_DDFG));
atomic_store(&g_caps_zero_ok, fge_caps_ok(VKP_FG_ENGINE_ZEROFG));
atomic_store(&g_dev_lost, 0);
g_submitted_since_ready = 0;
g_generated_at_ready = g_total_generated;
atomic_store(&g_dev_ready,
vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier);
FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), DD-FG Native %s",
fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(),
fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable");
FGLOG("engines ready on compositor device: LSFG %s, DD-FG %s, ZeroFG %s",
fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable",
fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable",
fge_caps_ok(VKP_FG_ENGINE_ZEROFG) ? "available" : "unavailable");
}
// The compositor reports one loss twice: when it happens and again while releasing the lost device.
static int framegen_count_loss(void) {
if (atomic_exchange(&g_dev_lost, 1)) return 0;
int failed = framegen_loss_strike(g_submitted_since_ready, g_total_generated - g_generated_at_ready);
g_submitted_since_ready = 0;
return failed;
}
void vkp_framegen_device_lost(void) {
atomic_store(&g_dev_lost, 1);
if (framegen_count_loss()) {
int kind = atomic_load(&g_kind);
mark_failed(kind);
FGLOG("%s lost the GPU %d times in a row before its frames completed; frame generation stays off "
"until it is set again", fge_engine_name(kind), FG_HANG_STRIKES);
}
atomic_store(&g_dev_ready, 0);
fge_device_lost();
if (g_dev) {
@@ -283,16 +360,18 @@ static int engine_usable(void) {
int kind = atomic_load(&g_kind);
int ready = atomic_load(&g_dev_ready);
int lost = atomic_load(&g_dev_lost);
int caps_ok = kind == VKP_FG_ENGINE_DDFG
? atomic_load(&g_caps_ddfg_ok)
: atomic_load(&g_caps_lsfg_ok);
int caps_ok = kind == VKP_FG_ENGINE_ZEROFG ? atomic_load(&g_caps_zero_ok) :
kind == VKP_FG_ENGINE_DDFG ? atomic_load(&g_caps_ddfg_ok) :
atomic_load(&g_caps_lsfg_ok);
return ready && !lost && caps_ok && !start_failed_for(kind);
}
int vkp_framegen_format_ok(VkFormat fmt) {
if (fmt == VK_FORMAT_R8G8B8A8_UNORM) return 1;
if (!g_dev_ready || g_dev_lost || format_refused(fmt)) return 0;
return fge_format_ok(fmt);
int kind = atomic_load(&g_kind);
if (kind == VKP_FG_ENGINE_ZEROFG) return fge_format_ok(VKP_FG_ENGINE_ZEROFG, fmt);
if (fmt == VK_FORMAT_R8G8B8A8_UNORM) return 1;
return fge_format_ok(kind, fmt);
}
static void refuse_format(VkFormat fmt, int kind, int w, int h, const char *what) {
@@ -377,11 +456,14 @@ static void log_arm_transition(int armed, int kind, int mult) {
int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, int w, int h,
VkFormat fmt, VkImage gens[VKP_FG_MAX_GENERATIONS]) {
(void)scene_view;
int kind = atomic_load(&g_kind);
int armed = atomic_load(&g_armed);
int mult = atomic_load(&g_mult);
g_planned = 0;
const int64_t issue = now_ns();
g_out_gens = 0;
memset(g_out_planned, 0, sizeof(g_out_planned));
g_completion_issue = 0;
if (!armed || !engine_usable() || w <= 0 || h <= 0) { log_arm_transition(0, kind, mult); return 0; }
if (!ensure_engine(kind)) { log_arm_transition(0, kind, mult); return 0; }
log_arm_transition(1, kind, mult);
@@ -423,8 +505,31 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
++g_source_frames;
const uint64_t game_frames = droiddeck_game_frames();
uint32_t n_gen = fge_plan(g_ring_n, game_frames ? game_frames : g_source_frames, g_presented_rate);
const uint64_t planning_sequence = game_frames ? game_frames : g_source_frames;
uint32_t n_gen = fge_plan(g_ring_n, planning_sequence, g_presented_rate);
if (n_gen > g_ring_n) n_gen = g_ring_n;
if (kind == VKP_FG_ENGINE_ZEROFG && n_gen > 0 && !scene_view) {
scene_view = vkp_effects_framegen_image_view(scene, w, h, fmt);
if (!scene_view) {
static int view_warning;
if (!view_warning++) FGLOG("ZeroFG could not create a view for the source image; showing real frames only");
n_gen = 0;
}
}
fge_set_phases(NULL, 0);
if (kind == VKP_FG_ENGINE_ZEROFG && pacer_wanted() && g_layer_path) {
int64_t vsync = 0, period = 0;
sc_layer_timeline(&vsync, &period);
int64_t planned[VKP_FG_MAX_GENERATIONS + 1];
float phases[VKP_FG_MAX_GENERATIONS + 1];
const uint32_t count = period > 0
? fge_pacer_plan((uint32_t)mult, period, vsync, issue, n_gen, planned, phases) : 0;
if (count >= 1 && count - 1 <= n_gen) {
n_gen = count - 1;
for (uint32_t i = 0; i < count; i++) g_out_planned[i] = planned[i];
fge_set_phases(phases, n_gen);
}
}
g_planned = n_gen;
VkImageMemoryBarrier bars[1 + VKP_FG_MAX_GENERATIONS];
@@ -452,21 +557,26 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0, 0, NULL, 0, NULL, nb, bars);
fge_process(cmd, scene, (uint32_t)w, (uint32_t)h, n_gen);
if (n_gen) g_submitted_since_ready = 1;
fge_process(cmd, scene, scene_view, (uint32_t)w, (uint32_t)h, fmt, planning_sequence, n_gen);
for (uint32_t g = 0; g < n_gen; g++) {
fge_generate(cmd, g, n_gen, g_ring[g].img, g_ring[g].view, (uint32_t)w, (uint32_t)h);
gens[g] = g_ring[g].img;
}
if (n_gen) {
nb = 0;
const VkAccessFlags generated_access = kind == VKP_FG_ENGINE_ZEROFG
? VK_ACCESS_MEMORY_WRITE_BIT : VK_ACCESS_SHADER_WRITE_BIT;
const VkPipelineStageFlags generated_stage = kind == VKP_FG_ENGINE_ZEROFG
? VK_PIPELINE_STAGE_ALL_COMMANDS_BIT : VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
for (uint32_t g = 0; g < n_gen; g++)
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
.srcAccessMask = generated_access, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_GENERAL, .newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = g_ring[g].img, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
vk.CmdPipelineBarrier(cmd, generated_stage, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, nb, bars);
if (!g_generating_logged) {
g_generating_logged = 1;
@@ -476,6 +586,8 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? ", FP16: the HDR picture" : "");
}
}
g_out_gens = (int)n_gen;
if (n_gen > 0) g_completion_issue = issue;
return (int)n_gen;
}
@@ -6,7 +6,7 @@
#endif
#include <vulkan/vulkan.h>
enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_DDFG = 1 };
enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_DDFG = 1, VKP_FG_ENGINE_ZEROFG = 2 };
#define VKP_FG_MAX_GENERATIONS 3
void vkp_framegen_set_engine(int kind);
@@ -26,6 +26,18 @@ void vkp_framegen_device_lost(void);
int vkp_framegen_active(void);
int vkp_framegen_extra_images(void);
/* 1 when the next run's frames are shown through the scene layer's timed group, 0 through the swapchain's FIFO. */
void vkp_framegen_set_layer_timing(int layer);
/* ZeroFG's pacer (include/zerofg/inline_pacer.h) times the layer's frames instead of the layer's own spacing. */
void vkp_framegen_set_pacer(int on);
/* Reset pacing history when a planned real-frame pair is aborted before presentation. */
void vkp_framegen_pacer_abort(void);
/* Refresh planned for output k of the last run (k == gens: its real frame; 0: use layer timing). */
void vkp_framegen_output_planned(int k, int gens, int64_t *planned);
/* The last run's GPU work finished (the compositor's fence signalled). */
void vkp_framegen_completed(void);
/* A real frame the pacer timed for planned_ns was shown at shown_ns. */
void vkp_framegen_real_shown(int64_t planned_ns, int64_t shown_ns);
int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, int w, int h,
VkFormat fmt, VkImage gens[VKP_FG_MAX_GENERATIONS]);
void vkp_framegen_presented(int generated);
@@ -3,6 +3,7 @@
#include <cstdio>
#include <cstring>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
@@ -13,6 +14,9 @@
#include "lsfg/lsfg_probe.h"
#include "lsfg/lsfg_vkd.h"
#include "ddfg/ddfg_engine.h"
#include "framegen_zerofg.h"
#include <zerofg/inline_pacer.h>
#define ELOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "framegen: " __VA_ARGS__)
#define ELOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "framegen: " __VA_ARGS__)
@@ -22,12 +26,17 @@ namespace {
VkTable g_table{};
lsfg::Caps g_caps{};
VkPhysicalDeviceVulkan12Features g_v12{};
VkPhysicalDeviceVulkan13Features g_v13{};
VkPhysicalDeviceFeatures2 g_f2{};
VkPhysicalDevice g_pd = VK_NULL_HANDLE;
VkDevice g_dev = VK_NULL_HANDLE;
VkQueue g_queue = VK_NULL_HANDLE;
uint32_t g_qfam = 0;
bool g_probed = false, g_ready = false;
bool g_zero_supported = false, g_zero_enabled = false;
zerofg::InlinePacer g_pacer;
zerofg::InlineReadiness g_readiness;
std::mutex g_pacer_mutex;
std::unique_ptr<lsfg::Engine> g_lsfg;
std::unique_ptr<ddfg::Engine> g_ddfg;
@@ -88,30 +97,57 @@ const void *fge_probe(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica
if (n) enumExts(pd, nullptr, &n, exts.data());
}
g_caps = lsfg::Caps{};
g_caps.features = lsfg::queryFeatures(g_table, pd, exts, false);
g_caps.features = lsfg::queryFeatures(g_table, pd, exts, false);
g_caps.probedFormat = ring_fmt;
g_caps.storageOnSwapchainFormat = g_table.GetPhysicalDeviceFormatProperties
? lsfg::probeStorageFormat(g_table, pd, ring_fmt) : false;
g_caps.linearBlitOnSwapchainFormat = g_table.GetPhysicalDeviceFormatProperties
? lsfg::probeLinearBlit(g_table, pd, ring_fmt) : false;
g_probed = true;
if (!g_caps.features.deviceGatesPass()) {
VkPhysicalDeviceProperties props{};
if (g_table.GetPhysicalDeviceProperties) g_table.GetPhysicalDeviceProperties(pd, &props);
VkPhysicalDeviceVulkan13Features supported13{};
supported13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;
VkPhysicalDeviceFeatures2 supported2{};
supported2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
if (props.apiVersion >= VK_API_VERSION_1_3) supported2.pNext = &supported13;
if (g_table.GetPhysicalDeviceFeatures2) g_table.GetPhysicalDeviceFeatures2(pd, &supported2);
g_zero_supported = props.apiVersion >= VK_API_VERSION_1_3 &&
supported13.synchronization2 == VK_TRUE &&
supported2.features.shaderStorageImageExtendedFormats == VK_TRUE;
g_zero_enabled = false;
const bool lsfg_supported = g_caps.features.deviceGatesPass();
if (!lsfg_supported) {
lsfg::explain(g_caps);
ELOG("device gates for the LSFG chain fail: %s", g_caps.reason);
}
if (!lsfg_supported && !g_zero_supported) {
g_v12 = {};
g_v13 = {};
g_f2 = {};
return nullptr;
}
g_v12 = VkPhysicalDeviceVulkan12Features{};
g_v12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
g_v12.vulkanMemoryModel = VK_TRUE;
g_v12.vulkanMemoryModel =
g_caps.features.vulkanMemoryModel ? VK_TRUE : VK_FALSE;
g_v12.vulkanMemoryModelDeviceScope =
g_caps.features.vulkanMemoryModelDeviceScope ? VK_TRUE : VK_FALSE;
g_v13 = VkPhysicalDeviceVulkan13Features{};
g_v13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;
g_v13.synchronization2 = g_zero_supported ? VK_TRUE : VK_FALSE;
if (g_zero_supported) g_v12.pNext = &g_v13;
g_f2 = VkPhysicalDeviceFeatures2{};
g_f2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
g_f2.pNext = &g_v12;
g_f2.features.shaderStorageImageWriteWithoutFormat = VK_TRUE;
g_f2.features.shaderStorageImageExtendedFormats = VK_TRUE;
g_f2.features.shaderStorageImageWriteWithoutFormat =
supported2.features.shaderStorageImageWriteWithoutFormat ? VK_TRUE : VK_FALSE;
g_f2.features.shaderStorageImageExtendedFormats =
supported2.features.shaderStorageImageExtendedFormats ? VK_TRUE : VK_FALSE;
return &g_f2;
}
@@ -122,9 +158,17 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica
fill_device(dev);
g_caps.featuresEnabled = features_enabled != 0;
lsfg::explain(g_caps);
VkPhysicalDeviceProperties props{};
if (g_table.GetPhysicalDeviceProperties) g_table.GetPhysicalDeviceProperties(pd, &props);
g_zero_enabled = g_zero_supported && features_enabled != 0;
zfg_device_ready(gipa, inst, pd, dev,
props.apiVersion > VK_API_VERSION_1_3 ? VK_API_VERSION_1_3 : props.apiVersion,
g_zero_enabled,
g_zero_enabled && g_f2.features.shaderStorageImageExtendedFormats == VK_TRUE);
g_ready = true;
ELOG("device ready: lsfg caps '%s', storage on ring format %d", g_caps.reason,
(int)g_caps.storageOnSwapchainFormat);
ELOG("device ready: lsfg caps '%s', storage on ring format %d, ZeroFG %s",
g_caps.reason, (int)g_caps.storageOnSwapchainFormat,
g_zero_enabled ? "available" : "unavailable");
}
void fge_device_lost(void) {
@@ -149,24 +193,45 @@ void fge_device_lost(void) {
g_v12 = {};
g_f2 = {};
g_build[0] = 0;
g_zero_supported = g_zero_enabled = false;
zfg_device_lost();
}
int fge_caps_ok(int kind) {
if (!g_ready) return 0;
if (kind == 2) return g_zero_enabled && zfg_caps_ok();
if (kind == 1) return g_caps.storageOnSwapchainFormat ? 1 : 0;
return g_caps.supported() ? 1 : 0;
}
const char *fge_caps_reason(void) { return g_caps.reason; }
int fge_engine_available(int kind) { return fge_caps_ok(kind); }
int fge_format_ok(VkFormat fmt) {
const char *fge_caps_reason(int kind) {
if (kind == 2 && !g_zero_enabled)
return "ZeroFG requires Vulkan 1.3, synchronization2 and extended storage-image formats";
if (kind == 2) return zfg_caps_reason();
return g_caps.reason;
}
int fge_format_ok(int kind, VkFormat fmt) {
if (kind == 2) return zfg_format_ok(fmt);
if (!g_ready || !g_table.GetPhysicalDeviceFormatProperties || fmt == VK_FORMAT_UNDEFINED) return 0;
return lsfg::probeStorageFormat(g_table, g_pd, fmt) && lsfg::probeLinearBlit(g_table, g_pd, fmt) ? 1 : 0;
}
int fge_start(int kind, const char *cache_path) {
fge_stop();
fge_pacer_reset();
if (!g_ready) return -1;
if (kind == 2) {
if (!g_zero_enabled || !zfg_start()) {
ELOGE("ZeroFG engine init failed");
return -1;
}
g_kind = 2;
std::snprintf(g_build, sizeof(g_build), "ZeroFG ReallyZero, Vulkan 1.3 Compat");
return 0;
}
if (kind == 1) {
auto e = std::make_unique<ddfg::Engine>();
if (!e->init(g_table, g_pd, g_dev, g_qfam, g_queue)) {
@@ -201,14 +266,16 @@ int fge_start(int kind, const char *cache_path) {
}
void fge_stop(void) {
if (g_lsfg) {
if (g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev);
g_lsfg.reset();
}
if ((g_kind == 0 || g_kind == 2) && g_table.DeviceWaitIdle && g_dev)
g_table.DeviceWaitIdle(g_dev);
g_lsfg.reset();
for (auto it = g_retained_ddfg.begin(); it != g_retained_ddfg.end();) {
if ((*it)->destroy()) it = g_retained_ddfg.erase(it);
else ++it;
}
if (g_ddfg) {
if (g_ddfg->destroy()) g_ddfg.reset();
else {
@@ -216,10 +283,13 @@ void fge_stop(void) {
g_retained_ddfg.push_back(std::move(g_ddfg));
}
}
zfg_stop();
g_kind = -1;
}
int fge_unavailable(void) {
if (g_kind == 2) return zfg_unavailable();
if (g_kind == 1) return g_ddfg && g_ddfg->unavailable() ? 1 : 0;
return g_lsfg && g_lsfg->unavailable() ? 1 : 0;
}
@@ -227,11 +297,13 @@ int fge_unavailable(void) {
void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz,
int model, int perf_preset) {
if (multiplier < 2) multiplier = 2;
if (g_kind == 2) { zfg_configure(multiplier, refresh_hz); return; }
if (g_kind == 1 && g_ddfg) g_ddfg->configure(multiplier, model, perf_preset, flow_scale);
else if (g_lsfg) g_lsfg->configure(multiplier, target_fps, flow_scale, refresh_hz);
}
int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) {
if (g_kind == 2) return zfg_prepare(w, h, fmt);
if (g_kind == 1) return g_ddfg && g_ddfg->prepare(w, h, fmt) ? 1 : 0;
if (!g_lsfg) return 0;
g_lsfg->setGuestExtent(w, h);
@@ -239,24 +311,74 @@ int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) {
}
uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) {
if (g_kind == 2) return zfg_plan(capacity, source_frames);
if (g_kind == 1) return g_ddfg ? g_ddfg->plan(capacity) : 0;
if (!g_lsfg) return 0;
g_lsfg->setPresentedRate(presented_rate);
return g_lsfg->plan(capacity, source_frames);
}
void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) {
void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view,
uint32_t w, uint32_t h, VkFormat fmt, uint64_t sequence, uint32_t gens) {
if (g_kind == 2) {
zfg_process(cmd, source, source_view, w, h, fmt, sequence, gens);
return;
}
if (g_kind == 1) { if (g_ddfg) g_ddfg->process(cmd, source, w, h, gens); return; }
if (g_lsfg) g_lsfg->process(cmd, source, w, h, gens);
}
void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view,
uint32_t w, uint32_t h) {
if (g_kind == 2) { zfg_generate(cmd, g, count, img, view, w, h); return; }
if (g_kind == 1) { if (g_ddfg) g_ddfg->generateInto(cmd, g, count, img, view, w, h); return; }
if (g_lsfg) g_lsfg->generateInto(cmd, g, g, img, view, w, h);
}
void fge_set_layer_timing(int layer) { zfg_set_layer_timing(layer); }
void fge_set_phases(const float *phases, uint32_t count) { zfg_set_phases(phases, count); }
float fge_phase(uint32_t index, uint32_t count) {
if (g_kind == 2) return zfg_phase(index, count);
return static_cast<float>(index + 1) / static_cast<float>(count + 1);
}
uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated,
int64_t *present_ns, float *phases) {
if (period_ns <= 0 || issue_ns <= 0) return 0;
std::lock_guard<std::mutex> lock(g_pacer_mutex);
g_pacer.SetMultiplier(multiplier);
g_pacer.ObserveVsync(static_cast<uint64_t>(period_ns), static_cast<uint64_t>(vsync_ns > 0 ? vsync_ns : 0));
const uint64_t issue = static_cast<uint64_t>(issue_ns);
const zerofg::InlinePacer::Plan plan =
g_pacer.PlanPair(issue, issue + g_readiness.MarginNs(static_cast<uint64_t>(period_ns)), max_generated + 1);
for (uint32_t i = 0; i < plan.count; i++) {
present_ns[i] = static_cast<int64_t>(plan.outputs[i].present_ns);
phases[i] = plan.outputs[i].phase;
}
return plan.count;
}
void fge_pacer_completed(int64_t issue_ns, int64_t done_ns) {
std::lock_guard<std::mutex> lock(g_pacer_mutex);
if (issue_ns > 0 && done_ns > issue_ns)
g_readiness.ObserveCompleted(static_cast<uint64_t>(issue_ns), static_cast<uint64_t>(done_ns));
}
void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns) {
std::lock_guard<std::mutex> lock(g_pacer_mutex);
if (planned_ns > 0 && shown_ns > 0)
g_pacer.ObserveRealShown(static_cast<uint64_t>(planned_ns), static_cast<uint64_t>(shown_ns));
}
void fge_pacer_reset(void) {
std::lock_guard<std::mutex> lock(g_pacer_mutex);
g_pacer.Reset();
}
void fge_forget_targets(void) {
if (g_kind == 2) { zfg_forget_targets(); return; }
if (g_lsfg) g_lsfg->forgetTargets();
}
@@ -266,10 +388,14 @@ void fge_telemetry(float *accepted, float *source_rate, float *thermal) {
*accepted = (float)g_lsfg->acceptedGenerations();
*source_rate = g_lsfg->sourceRate();
*thermal = (float)g_lsfg->thermalStatus();
} else if (g_kind == 2) {
zfg_telemetry(accepted, source_rate);
}
}
const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; }
const char *fge_engine_name(int kind) {
return kind == 2 ? "ZeroFG" : kind == 1 ? "DD-FG Native" : "LSFG Native";
}
const char *fge_build_info(void) { return g_build; }
}
@@ -16,8 +16,9 @@ void fge_device_lost(void);
void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysicalDevice pd,
VkDevice dev, VkQueue queue, uint32_t qfam, int features_enabled);
int fge_caps_ok(int kind);
const char *fge_caps_reason(void);
int fge_format_ok(VkFormat fmt);
const char *fge_caps_reason(int kind);
int fge_format_ok(int kind, VkFormat fmt);
int fge_engine_available(int kind);
int fge_start(int kind, const char *cache_path);
void fge_stop(void);
@@ -26,10 +27,22 @@ void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, f
int model, int perf_preset);
int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt);
uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate);
void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens);
void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view,
uint32_t w, uint32_t h, VkFormat fmt, uint64_t sequence, uint32_t gens);
void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view,
uint32_t w, uint32_t h);
void fge_forget_targets(void);
void fge_set_layer_timing(int layer);
/* The phases the pacer chose for the next pair's generated frames (engines that can take any phase). */
void fge_set_phases(const float *phases, uint32_t count);
/* The phase generated frame [index] of [count] shows. */
float fge_phase(uint32_t index, uint32_t count);
uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated,
int64_t *present_ns, float *phases);
void fge_pacer_completed(int64_t issue_ns, int64_t done_ns);
void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns);
void fge_pacer_reset(void);
void fge_telemetry(float *accepted, float *source_rate, float *thermal);
const char *fge_engine_name(int kind);
const char *fge_build_info(void);
@@ -10,9 +10,12 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica
(void)gipa; (void)inst; (void)pd; (void)dev; (void)queue; (void)qfam; (void)features_enabled;
}
void fge_device_lost(void) {}
void zfg_discard_history_update(void) {}
void zfg_commit_history_update(void) {}
int fge_caps_ok(int kind) { (void)kind; return 0; }
const char *fge_caps_reason(void) { return "frame-generation engines not built into this compositor"; }
int fge_format_ok(VkFormat fmt) { (void)fmt; return 0; }
const char *fge_caps_reason(int kind) { (void)kind; return "frame-generation engines not built into this compositor"; }
int fge_format_ok(int kind, VkFormat fmt) { (void)kind; (void)fmt; return 0; }
int fge_engine_available(int kind) { (void)kind; return 0; }
int fge_start(int kind, const char *cache_path) { (void)kind; (void)cache_path; return -1; }
void fge_stop(void) {}
int fge_unavailable(void) { return 1; }
@@ -24,16 +27,28 @@ int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { (void)w; (void)h; (void)
uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) {
(void)capacity; (void)source_frames; (void)presented_rate; return 0;
}
void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) {
(void)cmd; (void)source; (void)w; (void)h; (void)gens;
void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, uint32_t w, uint32_t h,
VkFormat fmt, uint64_t sequence, uint32_t gens) {
(void)cmd; (void)source; (void)source_view; (void)w; (void)h; (void)fmt; (void)sequence; (void)gens;
}
void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view,
uint32_t w, uint32_t h) {
(void)cmd; (void)g; (void)count; (void)img; (void)view; (void)w; (void)h;
}
void fge_forget_targets(void) {}
void fge_set_layer_timing(int layer) { (void)layer; }
void fge_set_phases(const float *phases, uint32_t count) { (void)phases; (void)count; }
float fge_phase(uint32_t index, uint32_t count) { return (float)(index + 1) / (float)(count + 1); }
uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated,
int64_t *present_ns, float *phases) {
(void)multiplier; (void)period_ns; (void)vsync_ns; (void)issue_ns; (void)max_generated; (void)present_ns; (void)phases;
return 0;
}
void fge_pacer_completed(int64_t issue_ns, int64_t done_ns) { (void)issue_ns; (void)done_ns; }
void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns) { (void)planned_ns; (void)shown_ns; }
void fge_pacer_reset(void) {}
void fge_telemetry(float *accepted, float *source_rate, float *thermal) {
*accepted = 0.0f; *source_rate = 0.0f; *thermal = -1.0f;
}
const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; }
const char *fge_engine_name(int kind) { return kind == 2 ? "ZeroFG" : kind == 1 ? "DD-FG Native" : "LSFG Native"; }
const char *fge_build_info(void) { return "stub"; }
@@ -14,6 +14,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenArmed(JNI
vkp_framegen_set_armed(armed ? 1 : 0, (int)multiplier, (int)targetFps);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenPacer(JNIEnv *env, jclass clazz, jboolean on) {
(void)env; (void)clazz;
vkp_framegen_set_pacer(on ? 1 : 0);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLsfgCachePath(JNIEnv *env, jclass clazz, jstring path) {
(void)clazz;
@@ -0,0 +1,602 @@
#include "framegen_zerofg.h"
#include "sc_layer.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <memory>
#include <android/log.h>
#include <zerofg/zerofg.h>
#define ZFG_LOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "ZeroFG: " __VA_ARGS__)
#define ZFG_ERR(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "ZeroFG: " __VA_ARGS__)
namespace {
PFN_vkGetInstanceProcAddr g_gipa = nullptr;
PFN_vkGetDeviceProcAddr g_gdpa = nullptr;
VkInstance g_instance = VK_NULL_HANDLE;
VkPhysicalDevice g_physical = VK_NULL_HANDLE;
VkDevice g_device = VK_NULL_HANDLE;
uint32_t g_api_version = VK_API_VERSION_1_0;
bool g_synchronization2 = false, g_extended_formats = false;
bool g_ready = false, g_supported = false, g_failed = false;
char g_reason[160] = "device has not been checked";
PFN_vkGetPhysicalDeviceMemoryProperties g_GetPhysicalDeviceMemoryProperties = nullptr;
PFN_vkGetPhysicalDeviceFormatProperties g_GetPhysicalDeviceFormatProperties = nullptr;
PFN_vkCreateImage g_CreateImage = nullptr;
PFN_vkDestroyImage g_DestroyImage = nullptr;
PFN_vkCreateImageView g_CreateImageView = nullptr;
PFN_vkDestroyImageView g_DestroyImageView = nullptr;
PFN_vkGetImageMemoryRequirements g_GetImageMemoryRequirements = nullptr;
PFN_vkAllocateMemory g_AllocateMemory = nullptr;
PFN_vkFreeMemory g_FreeMemory = nullptr;
PFN_vkBindImageMemory g_BindImageMemory = nullptr;
PFN_vkCmdPipelineBarrier g_CmdPipelineBarrier = nullptr;
PFN_vkCmdCopyImage g_CmdCopyImage = nullptr;
PFN_vkDeviceWaitIdle g_DeviceWaitIdle = nullptr;
VkPhysicalDeviceMemoryProperties g_memory_properties{};
std::unique_ptr<zerofg::Interpolator> g_interpolator;
VkImage g_history = VK_NULL_HANDLE;
VkImageView g_history_view = VK_NULL_HANDLE;
VkDeviceMemory g_history_memory = VK_NULL_HANDLE;
uint32_t g_width = 0, g_height = 0;
VkFormat g_format = VK_FORMAT_UNDEFINED;
bool g_history_layout_defined = false, g_history_valid = false;
uint64_t g_history_sequence = 0;
bool g_history_recorded_pending = false;
uint64_t g_history_recorded_sequence = 0;
std::array<bool, 4> g_fallback_outputs{};
VkImage g_current = VK_NULL_HANDLE;
VkImageView g_current_view = VK_NULL_HANDLE;
uint64_t g_current_sequence = 0;
bool g_pair_pending = false;
// Pacing. The compositor presents a pair's generated frames and its real frame back to back in FIFO,
// so they reach the panel on consecutive refreshes right after the tick that drew them.
constexpr uint64_t kBreakNs = 250000000ull;
constexpr size_t kIntervalWindow = 8;
constexpr size_t kMinIntervals = 4;
constexpr double kSlotTolerance = 0.15;
uint32_t g_multiplier = 2;
float g_refresh_hz = 0.0f;
bool g_layer_timing = false;
// The phases the pacer chose for this pair (count 0: none, the timing above decides).
std::array<float, 4> g_external_phases{};
uint32_t g_external_count = 0;
uint64_t g_last_sequence = 0;
uint64_t g_last_issue_ns = 0;
uint64_t g_pair_interval_ns = 0;
uint32_t g_prev_count = 0, g_pair_count = 0;
std::array<uint64_t, kIntervalWindow> g_intervals{};
size_t g_interval_count = 0, g_interval_next = 0;
uint64_t now_ns() {
return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count());
}
void reset_pacing() {
g_last_issue_ns = 0;
g_pair_interval_ns = 0;
g_prev_count = g_pair_count = 0;
g_interval_count = g_interval_next = 0;
}
uint64_t period_ns() {
return g_refresh_hz > 1.0f ? static_cast<uint64_t>(1e9 / static_cast<double>(g_refresh_hz)) : 0;
}
uint64_t typical_interval_ns() {
if (g_interval_count < kMinIntervals) return 0;
std::array<uint64_t, kIntervalWindow> sorted = g_intervals;
std::sort(sorted.begin(), sorted.begin() + g_interval_count);
return sorted[g_interval_count / 2];
}
void note_sequence(uint64_t sequence) {
if (sequence == g_last_sequence) return;
const uint64_t now = now_ns();
if (sequence < g_last_sequence) {
// The frame counter changed source (game frames vs compositor scenes): no pair across it.
g_history_valid = false;
g_history_sequence = 0;
reset_pacing();
} else if (g_last_issue_ns && now > g_last_issue_ns) {
const uint64_t interval = now - g_last_issue_ns;
if (interval > kBreakNs) {
reset_pacing();
} else {
g_pair_interval_ns = interval;
g_intervals[g_interval_next] = interval;
g_interval_next = (g_interval_next + 1) % kIntervalWindow;
g_interval_count = std::min(g_interval_count + 1, kIntervalWindow);
}
}
g_last_sequence = sequence;
g_last_issue_ns = now;
}
// Generated frames a pair can show without its presents queueing past the next game frame:
// one refresh each, the real frame one more, all inside the game's typical frame interval.
uint32_t pair_capacity(uint32_t wanted) {
const uint64_t period = period_ns();
const uint64_t typical = typical_interval_ns();
if (!period || !typical) return wanted;
const double slots = std::floor(static_cast<double>(typical) / static_cast<double>(period) + kSlotTolerance);
return slots < 2.0 ? 0u : std::min<uint32_t>(wanted, static_cast<uint32_t>(slots) - 1u);
}
// The scene layer (sc_layer.c) shows a group of [count] generated frames and then B, frame k of the group
// max(k, round(k * gap / (count + 1))) refreshes after the first, a group every game frame interval.
float layer_phase(uint32_t index, uint32_t count, uint64_t period) {
const float even = static_cast<float>(index + 1) / static_cast<float>(count + 1);
int64_t cadence_gap = 0;
int cadence_frames = 0;
sc_layer_cadence_info(&cadence_gap, &cadence_frames);
const uint64_t gap = cadence_gap > 0 ? static_cast<uint64_t>(cadence_gap) : typical_interval_ns();
const uint32_t group_frames = cadence_frames > static_cast<int>(count)
? static_cast<uint32_t>(cadence_frames) : count + 1;
if (!gap) return even;
const int64_t slots = static_cast<int64_t>((gap + period / 2) / period);
if (slots < static_cast<int64_t>(group_frames)) return even;
const auto step = [&](uint32_t k) {
const int64_t s = static_cast<int64_t>((static_cast<uint64_t>(k) * gap / group_frames + period / 2) / period);
return std::max<int64_t>(s, k);
};
const double phase = static_cast<double>(step(index) - step(count) + slots) / static_cast<double>(slots);
return static_cast<float>(std::clamp(phase, 0.05, 0.95));
}
// FIFO presents the generated group and B back-to-back; phase uses the measured real-frame span.
float pair_phase(uint32_t index, uint32_t count) {
if (g_external_count == count && index < count) return std::clamp(g_external_phases[index], 0.01f, 0.99f);
const float even = static_cast<float>(index + 1) / static_cast<float>(count + 1);
const uint64_t period = period_ns();
if (!period) return even;
if (g_layer_timing) return layer_phase(index, count, period);
if (!g_pair_interval_ns) return even;
const double span = static_cast<double>(g_pair_interval_ns) +
(static_cast<double>(count) - static_cast<double>(g_prev_count)) * static_cast<double>(period);
if (span <= static_cast<double>(period) * (count + 1)) return even;
const double phase = 1.0 - static_cast<double>(count - index) * static_cast<double>(period) / span;
return static_cast<float>(std::clamp(phase, 0.05, 0.95));
}
void load_device_functions() {
if (g_gipa && g_instance) {
g_GetPhysicalDeviceMemoryProperties =
reinterpret_cast<PFN_vkGetPhysicalDeviceMemoryProperties>(
g_gipa(g_instance, "vkGetPhysicalDeviceMemoryProperties"));
g_GetPhysicalDeviceFormatProperties =
reinterpret_cast<PFN_vkGetPhysicalDeviceFormatProperties>(
g_gipa(g_instance, "vkGetPhysicalDeviceFormatProperties"));
}
if (!g_gdpa || !g_device) return;
#define LOAD(name) g_##name = reinterpret_cast<PFN_vk##name>(g_gdpa(g_device, "vk" #name))
LOAD(CreateImage);
LOAD(DestroyImage);
LOAD(CreateImageView);
LOAD(DestroyImageView);
LOAD(GetImageMemoryRequirements);
LOAD(AllocateMemory);
LOAD(FreeMemory);
LOAD(BindImageMemory);
LOAD(CmdPipelineBarrier);
LOAD(CmdCopyImage);
LOAD(DeviceWaitIdle);
#undef LOAD
}
void clear_history_state() {
g_history_valid = false;
g_history_sequence = 0;
g_pair_pending = false;
g_current = VK_NULL_HANDLE;
g_current_view = VK_NULL_HANDLE;
g_current_sequence = 0;
}
void destroy_history() {
if (g_device) {
if (g_history_view && g_DestroyImageView) g_DestroyImageView(g_device, g_history_view, nullptr);
if (g_history && g_DestroyImage) g_DestroyImage(g_device, g_history, nullptr);
if (g_history_memory && g_FreeMemory) g_FreeMemory(g_device, g_history_memory, nullptr);
}
g_history = VK_NULL_HANDLE;
g_history_view = VK_NULL_HANDLE;
g_history_memory = VK_NULL_HANDLE;
g_width = g_height = 0;
g_format = VK_FORMAT_UNDEFINED;
g_history_layout_defined = false;
clear_history_state();
}
uint32_t find_memory_type(uint32_t bits) {
uint32_t fallback = UINT32_MAX;
for (uint32_t i = 0; i < g_memory_properties.memoryTypeCount; ++i) {
if ((bits & (1u << i)) == 0) continue;
const auto flags = g_memory_properties.memoryTypes[i].propertyFlags;
if (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) return i;
if (fallback == UINT32_MAX) fallback = i;
}
return fallback;
}
bool make_history(uint32_t width, uint32_t height, VkFormat format) {
if (!g_CreateImage || !g_GetImageMemoryRequirements || !g_AllocateMemory ||
!g_BindImageMemory || !g_CreateImageView || !g_GetPhysicalDeviceMemoryProperties) {
std::snprintf(g_reason, sizeof(g_reason), "Vulkan image functions unavailable");
return false;
}
VkImageCreateInfo image_info{};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.format = format;
image_info.extent = {width, height, 1};
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
if (g_CreateImage(g_device, &image_info, nullptr, &g_history) != VK_SUCCESS) {
std::snprintf(g_reason, sizeof(g_reason), "could not create temporal history image");
return false;
}
VkMemoryRequirements requirements{};
g_GetImageMemoryRequirements(g_device, g_history, &requirements);
const uint32_t memory_index = find_memory_type(requirements.memoryTypeBits);
if (memory_index == UINT32_MAX) {
std::snprintf(g_reason, sizeof(g_reason), "no compatible memory for temporal history");
destroy_history();
return false;
}
VkMemoryAllocateInfo allocation{};
allocation.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocation.allocationSize = requirements.size;
allocation.memoryTypeIndex = memory_index;
if (g_AllocateMemory(g_device, &allocation, nullptr, &g_history_memory) != VK_SUCCESS ||
g_BindImageMemory(g_device, g_history, g_history_memory, 0) != VK_SUCCESS) {
std::snprintf(g_reason, sizeof(g_reason), "could not allocate temporal history memory");
destroy_history();
return false;
}
VkImageViewCreateInfo view_info{};
view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
view_info.image = g_history;
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
view_info.format = format;
view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
if (g_CreateImageView(g_device, &view_info, nullptr, &g_history_view) != VK_SUCCESS) {
std::snprintf(g_reason, sizeof(g_reason), "could not create temporal history view");
destroy_history();
return false;
}
g_width = width;
g_height = height;
g_format = format;
g_history_layout_defined = false;
g_history_recorded_pending = false;
g_history_recorded_sequence = 0;
clear_history_state();
return true;
}
void copy_current_to_history(VkCommandBuffer cmd, VkImage source,
uint32_t width, uint32_t height, uint64_t sequence) {
if (!g_history || !source || !g_CmdPipelineBarrier || !g_CmdCopyImage) return;
VkImageMemoryBarrier before{};
before.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
const bool layout_defined = g_history_layout_defined || g_history_recorded_pending;
before.srcAccessMask = layout_defined ? VK_ACCESS_SHADER_READ_BIT : 0;
before.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
before.oldLayout = layout_defined ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED;
before.newLayout = VK_IMAGE_LAYOUT_GENERAL;
before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
before.image = g_history;
before.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
g_CmdPipelineBarrier(cmd,
layout_defined ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &before);
VkImageCopy region{};
region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.extent = {width, height, 1};
g_CmdCopyImage(cmd, source, VK_IMAGE_LAYOUT_GENERAL, g_history, VK_IMAGE_LAYOUT_GENERAL, 1, &region);
VkImageMemoryBarrier after{};
after.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
after.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
after.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
after.newLayout = VK_IMAGE_LAYOUT_GENERAL;
after.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
after.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
after.image = g_history;
after.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0, 0, nullptr, 0, nullptr, 1, &after);
g_history_recorded_pending = true;
g_history_recorded_sequence = sequence;
g_pair_pending = false;
}
void copy_current_to_output(VkCommandBuffer cmd, VkImage output, uint32_t width, uint32_t height) {
if (!g_current || !output || !g_CmdPipelineBarrier || !g_CmdCopyImage) return;
VkImageMemoryBarrier before{};
before.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT;
before.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
before.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
before.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
before.image = output;
before.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, nullptr, 0, nullptr, 1, &before);
VkImageCopy region{};
region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.extent = {width, height, 1};
g_CmdCopyImage(cmd, g_current, VK_IMAGE_LAYOUT_GENERAL,
output, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
VkImageMemoryBarrier after{};
after.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT;
after.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
after.newLayout = VK_IMAGE_LAYOUT_GENERAL;
after.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
after.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
after.image = output;
after.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0, 0, nullptr, 0, nullptr, 1, &after);
}
} // namespace
extern "C" {
void zfg_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance instance,
VkPhysicalDevice physical_device, VkDevice device,
uint32_t api_version, int synchronization2_enabled,
int extended_storage_formats_enabled) {
g_gipa = gipa;
g_instance = instance;
g_physical = physical_device;
g_device = device;
g_api_version = api_version;
g_synchronization2 = synchronization2_enabled != 0;
g_extended_formats = extended_storage_formats_enabled != 0;
g_gdpa = g_gipa && g_instance
? reinterpret_cast<PFN_vkGetDeviceProcAddr>(g_gipa(g_instance, "vkGetDeviceProcAddr"))
: nullptr;
load_device_functions();
if (g_GetPhysicalDeviceMemoryProperties && g_physical)
g_GetPhysicalDeviceMemoryProperties(g_physical, &g_memory_properties);
g_ready = g_device != VK_NULL_HANDLE;
g_supported = g_ready && g_api_version >= VK_API_VERSION_1_3 &&
g_synchronization2 && g_extended_formats;
g_failed = false;
std::snprintf(g_reason, sizeof(g_reason), "%s", g_supported ? "available" :
"requires Vulkan 1.3, synchronization2 and shaderStorageImageExtendedFormats");
}
void zfg_device_lost(void) {
g_interpolator.reset();
destroy_history();
g_gipa = nullptr; g_gdpa = nullptr;
g_instance = VK_NULL_HANDLE; g_physical = VK_NULL_HANDLE; g_device = VK_NULL_HANDLE;
g_ready = g_supported = g_failed = false;
g_synchronization2 = g_extended_formats = false;
g_api_version = VK_API_VERSION_1_0;
g_GetPhysicalDeviceMemoryProperties = nullptr;
g_GetPhysicalDeviceFormatProperties = nullptr;
g_CreateImage = nullptr; g_DestroyImage = nullptr;
g_CreateImageView = nullptr; g_DestroyImageView = nullptr;
g_GetImageMemoryRequirements = nullptr; g_AllocateMemory = nullptr;
g_FreeMemory = nullptr; g_BindImageMemory = nullptr;
g_CmdPipelineBarrier = nullptr; g_CmdCopyImage = nullptr; g_DeviceWaitIdle = nullptr;
g_memory_properties = {};
std::snprintf(g_reason, sizeof(g_reason), "device lost");
}
int zfg_caps_ok(void) { return g_supported ? 1 : 0; }
const char *zfg_caps_reason(void) { return g_reason; }
int zfg_start(void) {
if (!g_supported || !g_ready) return 0;
if (g_interpolator) return 1;
zerofg::CreateInfo info{};
info.vulkan.instance = g_instance;
info.vulkan.physical_device = g_physical;
info.vulkan.device = g_device;
info.vulkan.get_instance_proc_addr = g_gipa;
info.mode = zerofg::Mode::kReallyZero;
info.backend = zerofg::Backend::kCompat;
info.frame_context_count = 4;
info.capabilities.effective_api_version = g_api_version;
info.capabilities.synchronization2_enabled = g_synchronization2;
info.capabilities.shader_storage_image_extended_formats_enabled = g_extended_formats;
zerofg::Status status = zerofg::Status::kSuccess;
g_interpolator = zerofg::Interpolator::Create(info, &status);
if (!g_interpolator) {
std::snprintf(g_reason, sizeof(g_reason), "interpolator creation failed (%d)", (int)status);
g_failed = true;
ZFG_ERR("%s", g_reason);
return 0;
}
g_failed = false;
ZFG_LOG("ReallyZero engine ready (Compat backend)");
return 1;
}
void zfg_stop(void) {
g_interpolator.reset();
destroy_history();
reset_pacing();
g_last_sequence = 0;
g_failed = false;
}
int zfg_unavailable(void) { return g_failed || !g_interpolator ? 1 : 0; }
int zfg_format_ok(VkFormat format) {
if (!g_supported || !g_GetPhysicalDeviceFormatProperties || format == VK_FORMAT_UNDEFINED) return 0;
VkFormatProperties input{};
g_GetPhysicalDeviceFormatProperties(g_physical, format, &input);
const VkFormatFeatureFlags sampled =
VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
if ((input.optimalTilingFeatures & sampled) != sampled) return 0;
if (format == VK_FORMAT_A2B10G10R10_UNORM_PACK32)
return (input.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0;
VkFormatProperties internal{};
g_GetPhysicalDeviceFormatProperties(g_physical, VK_FORMAT_A2B10G10R10_UNORM_PACK32, &internal);
const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT | VK_FORMAT_FEATURE_BLIT_SRC_BIT;
return (input.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT) != 0 &&
(internal.optimalTilingFeatures & needed) == needed;
}
int zfg_prepare(uint32_t width, uint32_t height, VkFormat format) {
if (!g_interpolator || g_failed || !width || !height) return 0;
if (!zfg_format_ok(format)) {
std::snprintf(g_reason, sizeof(g_reason), "unsupported input/output format %d", (int)format);
g_failed = true;
ZFG_ERR("%s", g_reason);
return 0;
}
if (g_width == width && g_height == height && g_format == format && g_history) return 1;
if (g_DeviceWaitIdle) g_DeviceWaitIdle(g_device);
destroy_history();
const zerofg::Status resized = g_interpolator->Resize(width, height, format, format);
if (resized != zerofg::Status::kSuccess) {
std::snprintf(g_reason, sizeof(g_reason), "resize failed (%d)", (int)resized);
g_failed = true;
ZFG_ERR("%s", g_reason);
return 0;
}
if (!make_history(width, height, format)) {
g_failed = true;
ZFG_ERR("%s", g_reason);
return 0;
}
ZFG_LOG("prepared %ux%u format %d", width, height, (int)format);
return 1;
}
void zfg_configure(uint32_t multiplier, float refresh_hz) {
g_multiplier = std::clamp<uint32_t>(multiplier, 2, 4);
g_refresh_hz = refresh_hz > 1.0f ? refresh_hz : 0.0f;
}
void zfg_set_layer_timing(int layer) { g_layer_timing = layer != 0; }
void zfg_set_phases(const float *phases, uint32_t count) {
g_external_count = phases ? std::min<uint32_t>(count, static_cast<uint32_t>(g_external_phases.size())) : 0;
for (uint32_t i = 0; i < g_external_count; i++) g_external_phases[i] = phases[i];
}
float zfg_phase(uint32_t index, uint32_t count) { return pair_phase(index, count); }
uint32_t zfg_plan(uint32_t capacity, uint64_t sequence) {
if (!g_interpolator || g_failed) return 0;
note_sequence(sequence);
if (!g_history_valid || sequence <= g_history_sequence || !g_pair_interval_ns) return 0;
return pair_capacity(std::min<uint32_t>({capacity, 3u, g_multiplier - 1}));
}
void zfg_telemetry(float *generated, float *source_rate) {
const uint64_t typical = typical_interval_ns();
*generated = static_cast<float>(g_pair_count);
*source_rate = typical ? static_cast<float>(1e9 / static_cast<double>(typical)) : 0.0f;
}
void zfg_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view,
uint32_t width, uint32_t height, VkFormat format,
uint64_t sequence, uint32_t generations) {
g_pair_pending = false;
g_fallback_outputs.fill(false);
if (!g_interpolator || g_failed || !source || !g_history ||
format != g_format || width != g_width || height != g_height) return;
if (sequence > g_history_sequence) {
g_prev_count = g_pair_count;
g_pair_count = generations;
}
if (generations == 0 || !g_history_valid || sequence <= g_history_sequence) {
copy_current_to_history(cmd, source, width, height, sequence);
return;
}
if (!source_view) return;
g_current = source;
g_current_view = source_view;
g_current_sequence = sequence;
g_pair_pending = true;
}
void zfg_generate(VkCommandBuffer cmd, uint32_t index, uint32_t count,
VkImage output, VkImageView output_view, uint32_t width, uint32_t height) {
if (!g_pair_pending || !g_interpolator || !g_history_valid || index >= count || !output || !output_view) return;
const float phase = pair_phase(index, count);
zerofg::Image previous{};
previous.image = g_history; previous.view = g_history_view;
previous.layout = VK_IMAGE_LAYOUT_GENERAL; previous.format = g_format;
previous.width = g_width; previous.height = g_height;
previous.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
previous.sequence = g_history_sequence;
zerofg::Image current{};
current.image = g_current; current.view = g_current_view;
current.layout = VK_IMAGE_LAYOUT_GENERAL; current.format = g_format;
current.width = g_width; current.height = g_height;
current.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
current.sequence = g_current_sequence;
zerofg::Image result{};
result.image = output; result.view = output_view;
result.layout = VK_IMAGE_LAYOUT_GENERAL; result.format = g_format;
result.width = width; result.height = height;
result.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
const zerofg::Status status =
g_interpolator->Interpolate(cmd, index, previous, current, phase, result);
if (status != zerofg::Status::kSuccess) {
ZFG_ERR("interpolation status %d; copying the real frame as fallback", (int)status);
g_fallback_outputs[index] = true;
copy_current_to_output(cmd, output, width, height);
}
if (index + 1 >= count) {
copy_current_to_history(cmd, g_current, width, height, g_current_sequence);
g_pair_pending = false;
}
}
void zfg_commit_history_update(void) {
if (!g_history_recorded_pending) return;
g_history_layout_defined = true;
g_history_valid = true;
g_history_sequence = g_history_recorded_sequence;
g_history_recorded_pending = false;
}
void zfg_discard_history_update(void) {
g_history_recorded_pending = false;
g_history_recorded_sequence = 0;
}
void zfg_forget_targets(void) {
g_pair_pending = false;
g_history_recorded_pending = false;
g_history_recorded_sequence = 0;
g_history_valid = false;
g_history_sequence = 0;
reset_pacing();
}
} // extern "C"
@@ -0,0 +1,38 @@
#ifndef FRAMEGEN_ZEROFG_H
#define FRAMEGEN_ZEROFG_H
#include <stdint.h>
#include <vulkan/vulkan.h>
#ifdef __cplusplus
extern "C" {
#endif
void zfg_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance instance,
VkPhysicalDevice physical_device, VkDevice device,
uint32_t api_version, int synchronization2_enabled,
int extended_storage_formats_enabled);
void zfg_device_lost(void);
int zfg_caps_ok(void);
const char *zfg_caps_reason(void);
int zfg_start(void);
void zfg_stop(void);
int zfg_unavailable(void);
int zfg_format_ok(VkFormat format);
int zfg_prepare(uint32_t width, uint32_t height, VkFormat format);
void zfg_configure(uint32_t multiplier, float refresh_hz);
void zfg_set_layer_timing(int layer);
void zfg_set_phases(const float *phases, uint32_t count);
float zfg_phase(uint32_t index, uint32_t count);
uint32_t zfg_plan(uint32_t capacity, uint64_t sequence);
void zfg_telemetry(float *generated, float *source_rate);
void zfg_process(VkCommandBuffer command_buffer, VkImage source, VkImageView source_view,
uint32_t width, uint32_t height, VkFormat format,
uint64_t sequence, uint32_t generations);
void zfg_generate(VkCommandBuffer command_buffer, uint32_t index, uint32_t count,
VkImage output, VkImageView output_view,
uint32_t width, uint32_t height);
void zfg_forget_targets(void);
void zfg_commit_history_update(void);
void zfg_discard_history_update(void);
#ifdef __cplusplus
}
#endif
#endif
+44 -2
View File
@@ -58,6 +58,7 @@ static struct {
void (*reparent)(ASurfaceTransaction *, ASurfaceControl *, ASurfaceControl *);
void (*setOnComplete)(ASurfaceTransaction *, void *, sc_complete_fn);
int (*prevReleaseFence)(ASurfaceTransactionStats *, ASurfaceControl *);
int (*presentFence)(ASurfaceTransactionStats *);
void (*setFrameRate)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t);
void (*setFrameRateStrategy)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t, int8_t);
void (*setBufferDataSpace)(ASurfaceTransaction *, ASurfaceControl *, int32_t);
@@ -102,6 +103,7 @@ static int load_api(void) {
SYM(reparent, "ASurfaceTransaction_reparent");
SYM(setOnComplete, "ASurfaceTransaction_setOnComplete");
SYM(prevReleaseFence, "ASurfaceTransactionStats_getPreviousReleaseFenceFd");
SYM(presentFence, "ASurfaceTransactionStats_getPresentFenceFd");
SYM(setFrameRate, "ASurfaceTransaction_setFrameRate");
SYM(setFrameRateStrategy, "ASurfaceTransaction_setFrameRateWithChangeStrategy");
SYM(setBufferDataSpace, "ASurfaceTransaction_setBufferDataSpace");
@@ -265,7 +267,33 @@ static int64_t cadence_target(int64_t now, int64_t earliest, int64_t period) {
return target;
}
static int64_t g_planned_next_ns;
void sc_layer_set_planned(int64_t present_ns) {
pthread_mutex_lock(&g_lock);
g_planned_next_ns = present_ns;
pthread_mutex_unlock(&g_lock);
}
void sc_layer_timeline(int64_t *present_ns, int64_t *period_ns) {
pthread_mutex_lock(&g_timeline_lock);
*present_ns = g_timeline_present_ns;
*period_ns = g_timeline_period_ns;
pthread_mutex_unlock(&g_timeline_lock);
}
void sc_layer_cadence_info(int64_t *gap_ns, int *group_frames) {
if (gap_ns) *gap_ns = g_cadence_gap_ns;
if (group_frames) *group_frames = g_group_frames;
}
static void apply_present_time(ASurfaceTransaction *tx, int game) {
pthread_mutex_lock(&g_lock);
const int64_t planned = game ? g_planned_next_ns : 0;
if (game) {
g_planned_next_ns = 0;
}
pthread_mutex_unlock(&g_lock);
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;
@@ -285,6 +313,9 @@ static void apply_present_time(ASurfaceTransaction *tx, int 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; }
if (planned > 0) {
target = planned;
}
api.setDesiredPresentTime(tx, target - period / 2);
}
@@ -893,7 +924,9 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d
int translucent) {
struct slot *s = &l->slots[idx];
ASurfaceTransaction *tx = api.txCreate();
if (!tx) return -1;
if (!tx) {
return -1;
}
const int was_shown = l->shown;
const int32_t ds_applied = l->ds_applied;
const uint32_t md_applied = l->md_applied;
@@ -1114,7 +1147,7 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const
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; }
if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); vkp_framegen_pacer_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);
@@ -1136,13 +1169,18 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const
if (!have_fd) { first_fd = fd; have_fd = 1; }
}
if (vkp_pass_copy_generated(dst, m, real, first_fd) != 0) {
vkp_framegen_pacer_abort();
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++) {
int64_t planned;
vkp_framegen_output_planned(k, m, &planned);
sc_layer_set_planned(planned);
if (present_slot(l, idx[k], r, color, 0) == 0) continue;
vkp_framegen_pacer_abort();
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;
@@ -1151,7 +1189,11 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const
}
vkp_framegen_presented(m);
if (real) {
int64_t planned;
vkp_framegen_output_planned(m, m, &planned);
sc_layer_set_planned(planned);
if (present_slot(l, idx[VKP_FG_MAX_GENERATIONS], r, color, 0) != 0) {
vkp_framegen_pacer_abort();
slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1);
g_group_index = 0;
g_group_frames = 1;
@@ -4,6 +4,10 @@
#include <stdint.h>
#include <android/hardware_buffer.h>
#ifdef __cplusplus
extern "C" {
#endif
struct vkp_image;
struct vkp_draw;
struct droiddeck_color;
@@ -51,7 +55,16 @@ 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);
/* The refresh the next game-layer frame is timed for, instead of the layer's own spacing (0: the layer's). */
void sc_layer_set_planned(int64_t present_ns);
/* The display's frame timeline: the next expected present and the refresh period (0 until known). */
void sc_layer_timeline(int64_t *present_ns, int64_t *period_ns);
void sc_layer_cadence_info(int64_t *gap_ns, int *group_frames);
unsigned sc_layer_frames_take(void);
unsigned sc_layer_drops_take(void);
#ifdef __cplusplus
}
#endif
#endif
+81 -14
View File
@@ -7,6 +7,7 @@
#include "effects_chain.h"
#include "cardboard.h"
#include "framegen_bridge.h"
#include "framegen_zerofg.h"
#include "hdr_compose.h"
#include "blend_pass.h"
#include "gpu_busy.h"
@@ -604,6 +605,10 @@ static void update_map(int scene_w, int scene_h) {
float min_y = (float)g_map.ry + g_map.rh - image_h;
if (g_map.off_y < min_y) g_map.off_y = min_y;
if (g_map.off_y > g_map.ry) g_map.off_y = (float)g_map.ry;
} else if (align == VKP_ALIGN_PICTURE_TOP) {
g_map.off_y = 0;
} else if (align == VKP_ALIGN_PICTURE_BOTTOM) {
g_map.off_y = H - image_h;
} else {
g_map.off_y = (float)g_map.ry + (g_map.rh - image_h) * 0.5f;
}
@@ -2895,6 +2900,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
if (!(pass && fx)) release_external_client_draws(cmd, draws, n);
int ngen = 0;
int history_staged = 0;
VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE};
VkImage result = scene_img;
int rw = input_w, rh = input_h;
@@ -2933,6 +2939,8 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
0, 0, NULL, 0, NULL, 1, &b_general);
if (fg) {
vkp_framegen_set_layer_timing(0);
history_staged = 1;
ngen = vkp_framegen_run(cmd, result, VK_NULL_HANDLE, rw, rh, scene_fmt, gens);
if (ngen < 0) ngen = 0;
if (ngen > VKP_FG_MAX_GENERATIONS) ngen = VKP_FG_MAX_GENERATIONS;
@@ -2958,7 +2966,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
/* Teardown may have retained this frame's pending work, or
* acquire may have reported real device loss. Neither permits
* a completion-marker submit or another fence wait. */
if (g_dev_state != 1) return -1;
if (g_dev_state != 1) {
if (history_staged) zfg_discard_history_update();
return -1;
}
droiddeck_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents);
pr = VK_ERROR_OUT_OF_DATE_KHR;
break;
@@ -2982,6 +2993,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
if (img >= g_rnd_count || !g_rnds[img]) {
droiddeck_log("error", "present: image index %u exceeds semaphore count %u",
img, g_rnd_count);
if (history_staged) zfg_discard_history_update();
destroy_swapchain();
return -1;
}
@@ -2990,12 +3002,17 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
.pCommandBuffers = &g_cmds[k], .signalSemaphoreCount = 1, .pSignalSemaphores = &g_rnds[img]};
VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, last ? g_fence : VK_NULL_HANDLE);
if (qr != VK_SUCCESS) {
if (history_staged) zfg_discard_history_update();
if (qr == VK_ERROR_DEVICE_LOST) device_lost("submit");
else LOGE("present: submit %d/%d failed (%d)", k + 1, presents, (int)qr);
if (g_dev_state != -2) destroy_swapchain();
return -1;
}
fence_submitted = last;
if (k == 0 && history_staged) {
zfg_commit_history_update();
history_staged = 0;
}
VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .waitSemaphoreCount = 1,
.pWaitSemaphores = &g_rnds[img], .swapchainCount = 1,
.pSwapchains = &g_swapchain, .pImageIndices = &img};
@@ -3003,21 +3020,37 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
pr = g_vk.QueuePresentKHR(g_queue, &pi);
perf_add(&g_perf.present_ns, &g_perf.present_max_ns, &g_perf.presents, perf_now() - t_pres);
if (k < ngen) presented_gen++;
if (pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
if (pr == VK_ERROR_DEVICE_LOST) {
if (history_staged) zfg_discard_history_update();
device_lost("present");
return -1;
}
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) break;
}
if (!fence_submitted) {
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO};
VkResult marker = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
if (marker != VK_SUCCESS) {
if (history_staged) zfg_discard_history_update();
if (marker == VK_ERROR_DEVICE_LOST) device_lost("frame completion submit");
else quarantine_pending_work(marker, "frame completion submit");
return -1; /* no fence was submitted; never wait on its unsignalled state */
}
if (history_staged) {
zfg_discard_history_update();
history_staged = 0;
}
}
VkResult fr = timed_wait(g_fence, UINT64_MAX);
if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
if (fr != VK_SUCCESS) return -1;
if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) {
if (history_staged) zfg_discard_history_update();
device_lost("present");
return -1;
}
if (fr != VK_SUCCESS) {
if (history_staged) zfg_discard_history_update();
return -1;
}
vkp_effects_release_generated_sources();
if (fg) vkp_framegen_presented(presented_gen);
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) {
@@ -3369,6 +3402,9 @@ static struct {
int active;
VkImage result;
int rw, rh;
/* The layer buffers' size: rw x rh, or the spatial filter's output when it runs on each frame after generation. */
int ow, oh;
int post_upscale;
int ngen;
VkImage gens[VKP_FG_MAX_GENERATIONS];
} g_pass;
@@ -3508,10 +3544,29 @@ 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);
g_pass.post_upscale = generate && !hf && vkp_effects_active() && vkp_effects_upscaling() &&
vkp_effects_prepare_generated() && (mapped_w > input_w || mapped_h > input_h);
if (g_pass.post_upscale) {
static int last_input_w, last_input_h, last_output_w, last_output_h;
if (input_w != last_input_w || input_h != last_input_h || mapped_w != last_output_w || mapped_h != last_output_h) {
droiddeck_log("framegen", "post-upscale on the display layer: interpolate %dx%d, spatial filter each "
"frame to %dx%d", input_w, input_h, mapped_w, mapped_h);
last_input_w = input_w; last_input_h = input_h;
last_output_w = mapped_w; last_output_h = mapped_h;
}
}
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);
if (g_pass.post_upscale) {
g_pass.ow = (int)(scene_w * g_map.kx + 0.5f);
g_pass.oh = (int)(scene_h * g_map.ky + 0.5f);
g_pass.result = vkp_effects_run_before_generated(cmd, scene_img, input_w, input_h, &g_pass.rw, &g_pass.rh);
} else {
g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h,
&g_pass.rw, &g_pass.rh);
g_pass.ow = g_pass.rw;
g_pass.oh = 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);
@@ -3526,38 +3581,45 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
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);
vkp_framegen_set_layer_timing(1);
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;
if (rw) *rw = g_pass.ow;
if (rh) *rh = g_pass.oh;
return 0;
}
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; }
if (!g_pass.active) { zfg_discard_history_update(); 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; }
if (g_dev_state != 1) { zfg_discard_history_update(); if (wait_fd >= 0) close(wait_fd); return -1; }
VkCommandBuffer cmd = g_cmds[0];
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);
zfg_discard_history_update();
return -1;
}
const int gpu_wait = take_wait_fd(wait_fd);
if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; }
if (gpu_wait < 0) { zfg_discard_history_update(); g_vk.EndCommandBuffer(cmd); return -1; }
const int post_upscale = g_pass.post_upscale && src_layout == VK_IMAGE_LAYOUT_GENERAL;
for (int i = 0; i < n; i++) {
struct vkp_image *dst = dsts[i];
VkImage src = srcs[i];
int sw = g_pass.rw, sh = g_pass.rh;
if (post_upscale)
src = vkp_effects_run_generated(cmd, src, g_pass.rw, g_pass.rh, g_pass.ow, g_pass.oh, i, &sw, &sh);
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}},
.srcOffsets = {{0, 0, 0}, {sw, sh, 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);
blit_to_layer(cmd, src, src_layout, dst, &blit,
(sw == dst->w && sh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
}
g_vk.EndCommandBuffer(cmd);
@@ -3568,13 +3630,17 @@ static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp
g_vk.ResetFences(g_dev, 1, &g_fence);
VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
if (qr != VK_SUCCESS) {
zfg_discard_history_update();
if (qr == VK_ERROR_DEVICE_LOST) device_lost("layer pass");
else LOGE("layer: effects pass submit failed (%d)", (int)qr);
return -1;
}
zfg_commit_history_update();
VkResult fr = timed_wait(g_fence, 1000000000ULL);
if (fr == VK_ERROR_DEVICE_LOST) { device_lost("layer pass"); return -1; }
if (fr != VK_SUCCESS) { LOGE("layer: effects pass fence wait -> %s", vk_result_name(fr)); return -1; }
if (post_upscale) vkp_effects_release_generated_sources();
vkp_framegen_completed();
return 0;
}
@@ -3592,6 +3658,7 @@ int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_ima
}
void vkp_pass_abort(void) {
zfg_discard_history_update();
if (!g_pass.active) return;
g_pass.active = 0;
if (g_dev_state == 1)
@@ -461,6 +461,11 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *
__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_nativeSetMirrorCapture(JNIEnv *env, jclass clazz, jboolean on) {
droiddeck_host_mirror_capture(on ? 1 : 0);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) {
g_display_buffer_driver = on ? 1 : 0;
@@ -916,3 +921,42 @@ JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) {
return (jint)droiddeck_stream_frames();
}
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
extern int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path,
uint64_t dev, uint64_t ino, uint64_t receipt);
extern void droiddeck_frame_worker_revoke(int owner, int pid);
#endif
JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeEnabled(JNIEnv *env, jclass c) {
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
return JNI_TRUE;
#else
return JNI_FALSE;
#endif
}
JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeGrant(JNIEnv *env, jclass c,
jint owner, jint pid, jlong expires, jstring path, jlong dev, jlong ino, jlong start_ticks) {
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
if (!path || expires <= 0 || ino <= 0 || start_ticks <= 0) return JNI_FALSE;
const char *name = (*env)->GetStringUTFChars(env, path, NULL);
if (!name) return JNI_FALSE;
int granted = droiddeck_frame_worker_grant(owner, pid, (uint64_t)expires, name, (uint64_t)dev, (uint64_t)ino, (uint64_t)start_ticks);
(*env)->ReleaseStringUTFChars(env, path, name);
return granted ? JNI_TRUE : JNI_FALSE;
#else
return JNI_FALSE;
#endif
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeRevoke(JNIEnv *env, jclass c,
jint owner, jint pid) {
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
droiddeck_frame_worker_revoke(owner, pid);
#endif
}
@@ -200,7 +200,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false)
private var picturePosition by mutableStateOf("center")
private var picturePositionLandscape by mutableStateOf("center")
private var picturePositionPortrait by mutableStateOf("top")
private var integerScaling by mutableStateOf(false)
private var stretch16x9 by mutableStateOf(false)
private var avoidNotch by mutableStateOf(false)
@@ -304,9 +305,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
protons.installExperimental { progress -> com.droiddeck.launcher.session.ExperimentalProtons.installFromFile(this, zip, progress) }
}
}
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
private val pickSaveZip = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
@@ -517,17 +515,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
bootMovieCustomName = com.droiddeck.launcher.session.BootMovie.customName(this)
}
private fun importLossless(dll: File) {
Thread({
val message = Lossless.message(this, Lossless.import(this, dll))
val state = Lossless.state(this)
ui.post {
lossless = state
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
}
}, "lossless-import").start()
}
private fun importSaves(name: String, game: () -> GameSaves.Game) {
if (SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_saves_close_session, android.widget.Toast.LENGTH_LONG).show()
@@ -625,6 +612,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
private var hdrOn by mutableStateOf(false)
private var zeroCopyOn by mutableStateOf(true)
private var producerAcquireFences by mutableStateOf(false)
private var upscaler by mutableStateOf(0)
private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf<String?>(null)
@@ -1100,6 +1088,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} else {
putExtra(SessionService.EXTRA_STEAM_URL,
com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(game.gameIdString))
putExtra(SessionService.EXTRA_FRONTEND_STEAM_GAME, true)
}
}
.playing(game), steamSession = true)
@@ -1658,9 +1647,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
FrameGen.set(this, mode)
frameGenLabel = FrameGen.label(this)
},
onImportLossless = {
pickLossless.launch(InAppFilePicker.buildIntent(this, listOf("dll"), getString(R.string.lsfg_pick_title)))
},
onProtons = { openProtons() },
onComponents = { focusContent -> openComponents(focusContent) },
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
@@ -2380,7 +2366,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
refreshHomeAppState()
}
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
settingsMode?.let { hdrOn = SessionPrefs.hdr(this, it) }
settingsMode?.let { mode ->
hdrOn = SessionPrefs.hdr(this, mode)
if (mode == SessionService.MODE_STEAM) loadPicturePositions()
}
compatLaunchVisible = true
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false)
@@ -2921,6 +2910,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn,
producerAcquireFences = producerAcquireFences.takeIf {
mode == SessionService.MODE_STEAM &&
com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe.available(this)
},
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
@@ -2935,7 +2928,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backHold = backHold,
backActionsInverted = backActionsInverted,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null,
picturePositionLandscape = picturePositionLandscape.takeIf { mode == SessionService.MODE_STEAM },
picturePositionPortrait = picturePositionPortrait.takeIf { mode == SessionService.MODE_STEAM },
integerScaling = if (mode == SessionService.MODE_STEAM) integerScaling else null,
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
avoidNotch = if (mode == SessionService.MODE_STEAM) avoidNotch else null,
@@ -2985,6 +2979,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.prefMode(SessionState.mode) == SessionPrefs.prefMode(mode))
com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetZeroCopy(on)
},
onProducerAcquireFences = {
SessionPrefs.setProducerAcquireFences(this, it)
producerAcquireFences = it
},
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
@@ -3008,7 +3006,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backActionsInverted = inverted
},
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
onPicturePosition = { value -> SessionPrefs.setPicturePosition(this, value); picturePosition = value },
onPicturePosition = { portrait, value ->
SessionPrefs.setPicturePosition(this, portrait, value)
if (portrait) picturePositionPortrait = value else picturePositionLandscape = value
},
onIntegerScaling = { on -> SessionPrefs.setIntegerScaling(this, on); integerScaling = on },
onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on },
onAvoidNotch = { on -> SessionPrefs.setAvoidNotch(this, on); avoidNotch = on },
@@ -3325,6 +3326,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
resolutionPortrait = SessionPrefs.resolutionStored(this, mode, panel, true)
}
private fun loadPicturePositions() {
picturePositionLandscape = SessionPrefs.picturePosition(this, portrait = false)
picturePositionPortrait = SessionPrefs.picturePosition(this, portrait = true)
}
private fun loadModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
@@ -3346,6 +3352,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
loadBootMovie()
hdrOn = SessionPrefs.hdr(this, mode)
zeroCopyOn = SessionPrefs.zeroCopy(this, mode)
producerAcquireFences = SessionPrefs.producerAcquireFences(this)
upscaler = SessionPrefs.upscaler(this)
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.blocked(this)
@@ -3359,7 +3366,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backHold = SessionPrefs.backHold(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
directAudio = SessionPrefs.directAudio(this)
picturePosition = SessionPrefs.picturePosition(this)
loadPicturePositions()
integerScaling = SessionPrefs.integerScaling(this)
stretch16x9 = SessionPrefs.stretch16x9(this)
avoidNotch = SessionPrefs.avoidNotch(this)
@@ -180,6 +180,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var adaptiveSticks by mutableStateOf<Boolean?>(null)
private var quickButtons by mutableStateOf<Map<InputCommand, Boolean>>(emptyMap())
private var picturePosition by mutableStateOf("center")
private fun picturePortrait(config: android.content.res.Configuration = resources.configuration): Boolean =
config.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
private var integerScaling by mutableStateOf(false)
private var gameZoom by mutableStateOf(SessionState.gameZoom)
private var avoidNotch = false
@@ -230,6 +233,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private var unfoldedPanel by mutableStateOf<OnScreenControls?>(null)
private var unfoldedColumn: android.widget.LinearLayout? = null
private var unfoldedKeys: View? = null
private var unfoldedDeckSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null
private var swappedInputSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null
private var unfoldedDeckPanel by mutableStateOf<com.droiddeck.launcher.input.DeckPanel?>(null)
@@ -717,9 +721,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var drawerTextureAnisotropy by mutableStateOf<Int?>(null)
private var drawerTextureLodBias by mutableStateOf<String?>(null)
private var lossless by mutableStateOf(Lossless.State.NONE)
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
private var frameGenActiveGameId by mutableStateOf<Long?>(null)
private var frameGenActiveGameName by mutableStateOf<String?>(null)
@@ -995,6 +996,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
openDeckRing("activity created")
bridge.setOnPlayerInput(::onPadInput)
onScreenControls = OnScreenControls(this, bridge).also { controls ->
controls.alpha = onScreenOpacityAlpha()
controls.updateLayout(primaryInputLayout)
controls.onTouchMiss = miss@{ event ->
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
@@ -1605,10 +1607,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
/** The VR keyboard's keys go straight to the game, past the menu and pad handling a real key passes through. */
private val xrKeys by lazy {
com.droiddeck.launcher.input.KeyboardHost(this) { event ->
CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) &&
com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) }
}
KeyboardHost(
this,
sendKeyEvent = { event ->
CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) &&
com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) }
},
sendText = { text -> if (CompositorHost.isStarted) WaylandCompositor.textInputCommit(text) },
)
}
@androidx.compose.runtime.Composable
@@ -1714,6 +1720,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionState.gameZoom = gameZoom
runCatching { WaylandCompositor.nativeSetZoom(gameZoom) }
},
picturePosition = picturePosition,
onPicturePosition = { position ->
SessionPrefs.setPicturePosition(this@SessionActivity, picturePortrait(), position)
picturePosition = position
},
integerScaling = integerScaling,
onIntegerScaling = { enabled ->
SessionPrefs.setIntegerScaling(this@SessionActivity, enabled)
@@ -1898,10 +1909,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
readPrefs()
applyFrameGen(force = true)
},
onImportLossless = {
pickLossless.launch(InAppFilePicker.buildIntent(
this@SessionActivity, listOf("dll"), getString(R.string.lsfg_pick_title)))
},
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; togglePrimaryKeyboard() },
onHardwareKeyboard = ::togglePcKeyboard,
wowChatShown = com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram),
@@ -1909,6 +1916,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onWowChat = wowChat::choose,
controller = controllerSettings,
onControllerSize = { percent -> updateControllerPrefs { ControllerPrefs.setSize(this@SessionActivity, percent) } },
onControllerOpacity = { percent ->
ControllerPrefs.setOnScreenOpacity(this@SessionActivity, percent)
controllerSettings = ControllerPrefs.read(this@SessionActivity)
applyOnScreenOpacity()
},
onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
@@ -2052,6 +2064,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
},
unfoldedControls = unfoldedControls,
onUnfoldedControls = ::chooseUnfoldedControls,
deckPanel = unfoldedDeckPanel,
onDeckPanel = ::selectDeckPanel,
adaptiveSticks = adaptiveSticks.takeIf {
unfoldedPanel != null || oscMode != SessionPrefs.OSC_NEVER && oscMode != SessionPrefs.OSC_STEAM_QAM && !steamTouchInUse
},
@@ -2265,6 +2279,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (fieldKeyboardOnPrimary) hidePrimaryKeyboard()
}
private fun onScreenOpacityAlpha() = ControllerPrefs.onScreenOpacity(this) / 100f
private fun applyOnScreenOpacity() {
val alpha = onScreenOpacityAlpha()
onScreenControls?.alpha = alpha
bottomInputControls?.alpha = alpha
unfoldedColumn?.alpha = alpha
swappedInputSurface?.alpha = alpha
secondScreenPresentation?.controlsView?.alpha = alpha
steamTouchControls?.let { it.alpha = if (it.isEditing) 1f else alpha }
}
private fun updateControllerPrefs(change: () -> Unit) {
change()
controllerSettings = ControllerPrefs.read(this)
@@ -2775,7 +2801,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
picturePosition = SessionPrefs.picturePosition(this)
picturePosition = SessionPrefs.picturePosition(this, picturePortrait())
integerScaling = SessionPrefs.integerScaling(this)
avoidNotch = SessionPrefs.avoidNotch(this)
applyNotchInset()
@@ -3115,6 +3141,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS),
intent.getStringExtra(SessionService.EXTRA_GAME_ID),
sessionActivityDisplayId,
frontendSteamGame = intent.getBooleanExtra(SessionService.EXTRA_FRONTEND_STEAM_GAME, false),
)
intent.getStringExtra(EXTRA_PLAYED_GAME)?.let { com.droiddeck.launcher.frontend.Library.recordPlayed(this, it) }
}
@@ -3211,6 +3238,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
picturePosition = SessionPrefs.picturePosition(this, picturePortrait(newConfig))
if (refreshActivityDisplayId() && started) {
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
}
@@ -3583,19 +3611,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}, "lossless-sync").start()
}
private fun importLossless(dll: File) {
Thread({
val result = Lossless.import(this, dll)
val message = Lossless.message(this, result)
val state = Lossless.state(this)
runOnUiThread {
lossless = state
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
applyFrameGen(force = result == Lossless.ImportResult.UPDATED)
}
}, "lossless-import").start()
}
private fun watchSession() {
val handler = Handler(Looper.getMainLooper())
@@ -4073,7 +4088,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
steamTouchControls?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedPanel?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedDeckSurface?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedColumn?.getChildAt(0)?.let { takes(it) { _, _ -> true } } == true
unfoldedKeys?.let { takes(it) { _, _ -> true } } == true
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
@@ -5117,12 +5132,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val width = rootContentWidth()
val height = rootContentHeight()
val wanted = controlsBelowWanted()
val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let {
it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()
} ?: 0
val outputAspect = if (!wanted || SessionState.followScreen) 0f
else outputSize().let { it.first.toFloat() / it.second.coerceAtLeast(1) }
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, outputAspect)
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, aspect = outputAspect)
else FrameLayout.LayoutParams.MATCH_PARENT
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
if (params.height != gameHeight) {
@@ -5139,6 +5151,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (panel != null && (!wanted || panel.dock != dock)) {
sessionRoot.removeView(unfoldedColumn)
unfoldedColumn = null
unfoldedKeys = null
unfoldedDeckSurface = null
unfoldedDeckPanel = null
unfoldedPanel = null
@@ -5149,14 +5162,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (panel == null) {
panel = OnScreenControls(this, padBridge, dock).also { it.updateLayout(primaryInputLayout) }
val column = android.widget.LinearLayout(this).apply {
alpha = onScreenOpacityAlpha()
orientation = android.widget.LinearLayout.VERTICAL
addView(unfoldedBar().apply {
addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom ->
if (bottom - top != oldBottom - oldTop) post { applyUnfoldedControls() }
}
}, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT))
addView(panel, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
unfoldedKeys = com.droiddeck.launcher.ui.padKeysView(
this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM,
{ releasePads(); drawerOpen = true }, ::tapSteamButton, ::tapQam,
).also {
addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT))
}
}
sessionRoot.addView(column, sessionRoot.indexOfChild(surfaceView) + 1)
unfoldedColumn = column
@@ -5167,13 +5182,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
unfoldedColumn?.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM)
}
private fun unfoldedBar(): View = com.droiddeck.launcher.ui.bottomScreenBarView(this) {
val deck = unfoldedDeckPanel
com.droiddeck.launcher.ui.sessionBarModel(getString(if (deck != null) R.string.second_mode_deck_controls else R.string.deck_tab_gamepad),
{ chooseUnfoldedControls(false) }, { drawerOpen = true }, ::tapSteamButton, ::tapQam,
tabs = deck?.let { com.droiddeck.launcher.ui.deckPanelTabs(this, it, ::selectDeckPanel) })
}
private fun showUnfoldedDeckPanel() {
val column = unfoldedColumn
val panel = unfoldedPanel
@@ -5189,7 +5197,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
panel.visibility = View.GONE
unfoldedDeckSurface = com.droiddeck.launcher.ui.InputSurfaceView(this, padBridge, layout.elements, InputRole.PRIMARY, layout.style, haptics = true).also {
it.tag = layout
column.addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
column.addView(it, column.indexOfChild(panel) + 1, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
}
}
@@ -6000,7 +6008,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val view = com.droiddeck.launcher.input.SteamTouchControls(this, device,
onMenu = { drawerOpen = true }, onKeyboard = ::togglePcKeyboard)
view.visibility = View.GONE
view.onEditingChanged = { touchEditorChanged() }
view.alpha = onScreenOpacityAlpha()
view.onEditingChanged = { editing ->
view.alpha = if (editing) 1f else onScreenOpacityAlpha()
touchEditorChanged()
}
view.onOptions = { options ->
steamTouchOptions = options
applyTouchRouting()
@@ -6105,6 +6117,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (bottom?.parent !== bottomRoot) {
(bottom?.parent as? android.view.ViewGroup)?.removeView(bottom)
bottom = OnScreenControls(bottomRoot.context, padBridge).also { view ->
view.alpha = onScreenOpacityAlpha()
view.onTouchMiss = { event -> onBottomGameTouch(event) }
bottomRoot.addView(view, android.view.ViewGroup.LayoutParams(-1, -1))
}
@@ -6335,7 +6348,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun holdComposedOutput(hold: Boolean) {
val wasHeld = composedHolds > 0
composedHolds = (composedHolds + if (hold) 1 else -1).coerceAtLeast(0)
val held = composedHolds > 0
if (held == wasHeld) return
WaylandCompositor.nativeSetMirrorCapture(held)
// Importable HDR is redirected by the compositor hold. Keep its layer-only fallback available.
if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
}
@@ -6482,7 +6500,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
displayManager.unregisterDisplayListener(displayListener)
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
contentResolver.unregisterContentObserver(refreshSettingObserver)
if (!screenIsOff()) closeSecondScreen(reset = false)
// Closing the presentation removes the docked Agent page and unregisters its picker.
if (com.droiddeck.launcher.session.SessionVisibilityPolicy.shouldCloseSecondScreenOnStop(
screenOff = screenIsOff(),
dockedDrawerOpen = menuShownOnBottom(),
attachmentPickerOpen = com.droiddeck.launcher.agent.AgentAttachments.picking,
)
) closeSecondScreen(reset = false)
sessionTextInput.stop()
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
@@ -6519,6 +6543,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onResume() {
super.onResume()
com.droiddeck.launcher.agent.AgentAttachments.picking = false
drawerGameInventoryRevision++
com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event ->
com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) }
@@ -6548,6 +6573,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
joyConVr?.refresh()
onScreenControls?.reload()
controllerSettings = ControllerPrefs.read(this)
applyOnScreenOpacity()
resumed = true
boostGpuClock(panelOverGame)
updateKeyboardRoute()
@@ -6631,7 +6657,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldButtons.clear()
if (!screenOff) {
val menuUp = menuShownOnBottom()
drawerOpen = false
if (!com.droiddeck.launcher.agent.AgentAttachments.picking) drawerOpen = false
if (menuUp) SessionState.bottomMenu = true
pcKeyboardOpen = false
achievementsOpen = false
@@ -7056,7 +7082,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
androidx.compose.runtime.key(profileLayout) {
androidx.compose.ui.viewinterop.AndroidView(
factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(),
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { swappedInputSurface = it } },
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also {
it.alpha = onScreenOpacityAlpha()
swappedInputSurface = it
} },
modifier = Modifier.fillMaxWidth().weight(1f),
onRelease = { if (swappedInputSurface === it) swappedInputSurface = null },
)
@@ -19,6 +19,15 @@ object AgentAttachments {
/** Guest paths waiting to go with the next message. */
val pending = mutableStateListOf<String>()
/** True while the file picker is open over a session: it answers the drawer's agent page, so the drawer must stay. */
@Volatile var picking = false
/** Launches a system screen that answers the agent page, keeping the drawer for it; the result callback clears [picking]. */
fun pick(launch: () -> Unit) {
picking = true
if (runCatching(launch).isFailure) picking = false
}
private const val NEW = "new"
private const val GUEST_DIR = "/root/.cache/droiddeck/attachments"
private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp")
@@ -35,14 +44,17 @@ object AgentAttachments {
val folder = chat ?: NEW
val dir = File(hostDir(app), folder).apply { mkdirs() }
return uris.mapNotNull { uri ->
var target: File? = null
runCatching {
val name = displayName(app, uri).replace(Regex("[^A-Za-z0-9._-]"), "_").ifEmpty { "file" }
var target = File(dir, name)
var candidate = File(dir, name)
var n = 1
while (target.exists()) target = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
app.contentResolver.openInputStream(uri)!!.use { input -> target.outputStream().use { input.copyTo(it) } }
"$GUEST_DIR/$folder/${target.name}"
}.getOrNull()
// Created atomically, so copies running side by side never pick the same name.
while (!candidate.createNewFile()) candidate = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
target = candidate
app.contentResolver.openInputStream(uri)!!.use { input -> candidate.outputStream().use { input.copyTo(it) } }
"$GUEST_DIR/$folder/${candidate.name}"
}.onFailure { target?.delete() }.getOrNull()
}
}
@@ -75,7 +75,9 @@ object AgentHost {
"Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " +
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " +
"To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " +
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message."
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message. " +
"To show the user an image (a screenshot, a mockup, a chart), put ![what it shows](/absolute/path.png) on a line of its own: " +
"DroidDeck draws the file in the chat."
val entries = mutableStateListOf<Entry>()
val queue = mutableStateListOf<Queued>()
@@ -226,7 +226,18 @@ object AgentSetup {
/** The whole output of a step's last run; the card shows only its last line. */
fun logFile(app: Context, step: Step) = File(app.filesDir, "agent/setup-${step.name.lowercase()}.log")
fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git")
/**
* An install set up before setup wrote the Gradle init script gets the step again, but only
* once the checkout's setup writes it: the step runs that script, and an older one never would.
*/
fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git") &&
(AgentHost.guestFileExists(app, GRADLE_INIT) || !setupWritesGradleInit(app))
private const val GRADLE_INIT = "/root/.gradle/init.d/droiddeck-device.gradle"
private fun setupWritesGradleInit(app: Context) = runCatching {
File(LinuxRuntime.rootDir(app), "$CHECKOUT/tools/agent/setup".removePrefix("/")).readText().contains(GRADLE_INIT.substringAfterLast('/'))
}.getOrDefault(false)
/** dd-lab-build compiled this install's commit, so a Lab build compiles only what changed. */
private fun prepared(app: Context) = runCatching {
@@ -64,6 +64,19 @@ object PhantomProcessLimit {
PhantomProcessStatus.UNCOUNTED else status
}
/** The limit as the device sets it, whether or not the session keeps its programs out of the count. */
fun setting(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus =
if (sdk < Build.VERSION_CODES.S) PhantomProcessStatus.NOT_APPLICABLE else readSetting(context, sdk)
/**
* Whether the session should run its programs in worker processes. Each worker is a process of
* the app, and frontends that track the app's processes (Cocoon gives up above 32) lose a game
* that runs in dozens, so with the limit off they run as ordinary children. Producer acquire
* fences need gamescope in a worker.
*/
fun workersWanted(setting: PhantomProcessStatus, producerFences: Boolean): Boolean =
setting != PhantomProcessStatus.DISABLED || producerFences
private fun readSetting(context: Context, sdk: Int): PhantomProcessStatus {
if (usesDeviceConfig(sdk)) {
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
@@ -10,11 +10,13 @@ object FrameGen {
const val ENGINE_DDFG = "ddfg"
private const val LEGACY_ENGINE_WINFG = "winfg"
const val ENGINE_LSFG = "lsfg"
const val ENGINE_ZEROFG = "zerofg"
private const val DDFG_PERF_PRESET = 2
private const val DDFG_MODEL = 4
private const val FLOW_SCALE_DDFG = 0.60f
private const val FLOW_SCALE_LSFG = 0.80f
private const val FLOW_SCALE_ZEROFG = 1.0f
val ADAPTIVE_TARGETS = listOf(120, 90, 60)
@@ -69,6 +71,14 @@ object FrameGen {
.putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply()
}
fun pacerEnabled(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean("pacer", false)
fun setPacer(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("pacer", enabled).apply()
WaylandCompositor.nativeSetFrameGenPacer(enabled)
}
fun clearGlobal(context: Context) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove("engine").remove("multiplier").remove("target").apply()
@@ -80,6 +90,7 @@ object FrameGen {
mode.engine == ENGINE_DDFG -> context.getString(R.string.frame_gen_ddfg, mode.multiplier)
mode.engine == ENGINE_LSFG && mode.target > 0 -> context.getString(R.string.frame_gen_lsfg_adaptive, mode.target)
mode.engine == ENGINE_LSFG -> context.getString(R.string.frame_gen_lsfg, mode.multiplier)
mode.engine == ENGINE_ZEROFG -> context.getString(R.string.frame_gen_zerofg, mode.multiplier)
else -> context.getString(R.string.frame_gen_off)
}
@@ -104,6 +115,7 @@ object FrameGen {
fun applyPrepared(context: Context, prepared: PreparedApply, refreshHz: Float): String? {
val mode = prepared.mode
WaylandCompositor.nativeSetFrameGenPacer(pacerEnabled(context))
when (mode.engine) {
ENGINE_LSFG -> {
val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED
@@ -111,7 +123,7 @@ object FrameGen {
if (status != LsfgNative.STATUS_OK || cachePath == null) {
WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
val problem = context.getString(
if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed,
if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_needs_steam else R.string.lsfg_problem_failed,
)
Log.w(TAG, "$problem (status $status)")
return problem
@@ -127,6 +139,11 @@ object FrameGen {
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_DDFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0)
}
ENGINE_ZEROFG -> {
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_ZEROFG)
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_ZEROFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0)
}
else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
}
Log.i(TAG, "frame generation: $mode at ${refreshHz}Hz")
@@ -2,22 +2,16 @@ package com.droiddeck.launcher.gpu
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.DigestOutputStream
import java.security.MessageDigest
object Lossless {
enum class Source { NONE, STEAM, IMPORT }
enum class ImportResult { UPDATED, UNCHANGED, NOT_OWNED, INVALID, FAILED }
data class State(val owned: Boolean, val ready: Boolean, val source: Source) {
data class State(val owned: Boolean, val ready: Boolean) {
companion object {
val NONE = State(owned = false, ready = false, source = Source.NONE)
val NONE = State(owned = false, ready = false)
}
}
@@ -26,15 +20,13 @@ object Lossless {
private const val KEY_OWNED = "owned"
private const val KEY_ID = "id"
private const val KEY_SOURCE = "source"
private const val SOURCE_STEAM = "STEAM"
private const val KEY_STEAM_STAMP = "steamStamp"
private const val STEAM_MANIFEST = "steamapps/appmanifest_993090.acf"
private const val STEAM_DLL = "steamapps/common/Lossless Scaling/Lossless.dll"
private const val UNCHANGED = -1
fun state(context: Context): State {
val source = prefs(context).getString(KEY_SOURCE, null)
?.let { name -> Source.entries.firstOrNull { it.name == name } } ?: Source.NONE
return State(owned(context), cacheFile(context)?.isFile == true, source)
}
fun state(context: Context) = State(owned(context), cacheFile(context)?.isFile == true)
fun owned(context: Context): Boolean {
if (prefs(context).getBoolean(KEY_OWNED, false)) return true
@@ -43,61 +35,46 @@ object Lossless {
return true
}
fun cacheFile(context: Context): File? = prefs(context).getString(KEY_ID, null)?.let { cacheFor(context, it) }
fun cacheFile(context: Context): File? = steamCacheId(context)?.let { cacheFor(context, it) }
private fun steamCacheId(context: Context): String? = prefs(context).let {
if (it.getString(KEY_SOURCE, null) == SOURCE_STEAM) it.getString(KEY_ID, null) else null
}
@Synchronized
fun sync(context: Context): Int {
val settings = prefs(context)
if (steamCacheId(context) == null && settings.contains(KEY_ID)) {
settings.edit().remove(KEY_ID).remove(KEY_SOURCE).remove(KEY_STEAM_STAMP).apply()
}
val steam = steamDll(context)
if (steam != null) {
markOwned(context)
val stamp = "${steam.length()}:${steam.lastModified()}"
if (stamp != prefs(context).getString(KEY_STEAM_STAMP, null)) {
val status = adopt(context, steam, Source.STEAM)
if (stamp != settings.getString(KEY_STEAM_STAMP, null)) {
val status = adoptSteamDll(context, steam)
if (status != LsfgNative.STATUS_OK && status != UNCHANGED) {
Log.w(TAG, "Steam copy $steam not taken: ${statusName(status)}")
}
prefs(context).edit().putString(KEY_STEAM_STAMP, stamp).apply()
settings.edit().putString(KEY_STEAM_STAMP, stamp).apply()
}
}
return ensureBuilt(context)
}
@Synchronized
fun import(context: Context, dll: File): ImportResult {
if (!owned(context)) return ImportResult.NOT_OWNED
return when (adopt(context, dll, Source.IMPORT)) {
UNCHANGED -> ImportResult.UNCHANGED
LsfgNative.STATUS_OK -> ImportResult.UPDATED
LsfgNative.STATUS_UNREADABLE_FILE, LsfgNative.STATUS_NOT_PORTABLE_EXECUTABLE,
LsfgNative.STATUS_MISSING_SHADERS -> ImportResult.INVALID
else -> ImportResult.FAILED
}
}
fun message(context: Context, result: ImportResult): String = context.getString(
when (result) {
ImportResult.UPDATED -> R.string.lsfg_imported
ImportResult.UNCHANGED -> R.string.lsfg_import_unchanged
ImportResult.NOT_OWNED -> R.string.lsfg_import_not_owned
ImportResult.INVALID -> R.string.lsfg_import_invalid
ImportResult.FAILED -> R.string.lsfg_import_failed
},
)
private fun ensureBuilt(context: Context): Int {
val id = prefs(context).getString(KEY_ID, null) ?: return LsfgNative.STATUS_NOT_INSTALLED
val cache = cacheFor(context, id)
val cache = cacheFile(context) ?: return LsfgNative.STATUS_NOT_INSTALLED
if (usable(cache)) return LsfgNative.STATUS_OK
val dll = storedDll(context)
if (!dll.isFile) return LsfgNative.STATUS_NOT_INSTALLED
return build(dll, cache)
}
private fun adopt(context: Context, source: File, from: Source): Int {
private fun adoptSteamDll(context: Context, source: File): Int {
val staged = File(dir(context).apply { mkdirs() }, "Lossless.dll.staged")
try {
val id = copyHashing(source, staged)
if (id == prefs(context).getString(KEY_ID, null) && usable(cacheFor(context, id))) return UNCHANGED
if (id == steamCacheId(context) && usable(cacheFor(context, id))) return UNCHANGED
val cache = cacheFor(context, id)
var status = LsfgNative.nativeValidateDll(staged.path)
if (status == LsfgNative.STATUS_OK) status = build(staged, cache)
@@ -109,9 +86,9 @@ object Lossless {
cache.delete()
return LsfgNative.STATUS_CACHE_UNUSABLE
}
prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, from.name).apply()
prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, SOURCE_STEAM).apply()
removeStale(context, id)
Log.i(TAG, "Lossless.dll from $source ($from) ready as $id")
Log.i(TAG, "Steam Lossless.dll from $source ready as $id")
return LsfgNative.STATUS_OK
} catch (e: java.io.IOException) {
Log.w(TAG, "could not copy $source", e)
@@ -158,9 +135,13 @@ object Lossless {
GameStorage.effective(context)?.path?.let(::File),
GameStorage.x64CardLibrary(context),
) + com.droiddeck.launcher.frontend.AddedGames.roots(context).map { it.host }
return libraries.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() }
return installedSteamDll(libraries)
}
internal fun installedSteamDll(libraries: List<File>): File? =
libraries.asSequence().filter { File(it, STEAM_MANIFEST).isFile }
.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() }
private fun markOwned(context: Context) {
if (!prefs(context).getBoolean(KEY_OWNED, false)) prefs(context).edit().putBoolean(KEY_OWNED, true).apply()
}
@@ -11,7 +11,7 @@ internal object DroidDeckHudConfig {
"showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0",
"showVram" to "1", "showRAM" to "1", "showSwap" to "1", "showBattery" to "0", "showBatteryTime" to "0", "showPower" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "fpsDecimal" to "1",
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1",
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "0", "showLow001" to "0",
"showEngine" to "1", "showRenderer" to "1",
"showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1",
"showProton" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
@@ -92,8 +92,8 @@ class DroidDeckHudView(context: Context) : View(context) {
private var showBatteryTemp = false
private var showGraph = false
private var showLow1 = true
private var showLow01 = true
private var showLow001 = true
private var showLow01 = false
private var showLow001 = false
private var fpsDecimal = true
private var showClockTime = true
private var showLatency = true
@@ -187,6 +187,12 @@ class DroidDeckHudView(context: Context) : View(context) {
private var graphRect: RectF? = null
private var contentW = 0f
private var contentH = 0f
private var viewportW = Float.POSITIVE_INFINITY
private var viewportH = Float.POSITIVE_INFINITY
private val panelFit: Float
get() = if (dPanel == null || contentW <= 0f || contentH <= 0f) 1f
else minOf(1f, viewportW / contentW, viewportH / contentH)
private var onMovedListener: BiConsumer<Float, Float>? = null
private var onSizeCycledListener: Consumer<String>? = null
@@ -993,13 +999,20 @@ class DroidDeckHudView(context: Context) : View(context) {
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
viewportW = viewportLimit(widthMeasureSpec)
viewportH = viewportLimit(heightMeasureSpec)
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
val fit = panelFit
setMeasuredDimension(
resolveSize(contentW.roundToInt(), widthMeasureSpec),
resolveSize(contentH.roundToInt(), heightMeasureSpec),
resolveSize((contentW * fit).roundToInt(), widthMeasureSpec),
resolveSize((contentH * fit).roundToInt(), heightMeasureSpec),
)
}
private fun viewportLimit(spec: Int): Float =
if (MeasureSpec.getMode(spec) == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY
else MeasureSpec.getSize(spec).toFloat()
override fun onDraw(canvas: Canvas) {
if (contentW <= 0f || contentH <= 0f) { lockController.drawBadge(canvas); return }
val blend = if (dock == DroidDeckHudDock.NONE && previewEdge != DroidDeckHudDock.NONE) previewBlend else 0f
@@ -1034,8 +1047,10 @@ class DroidDeckHudView(context: Context) : View(context) {
}
private fun drawContent(canvas: Canvas) {
dPanel?.let { panel -> panelFrame(panel)?.let { canvas.drawBitmap(it, 0f, 0f, null) } }
val fit = panelFit
dPanel?.let { panel -> panelFrame(panel, fit)?.let { canvas.drawBitmap(it, 0f, 0f, null) } }
val saved = canvas.save()
if (fit != 1f) canvas.scale(fit, fit)
if (tileRects.isNotEmpty()) {
tilePaint.color = Color.argb((14 * bgOpacity).roundToInt().coerceIn(8, 40), 255, 255, 255)
@@ -1065,6 +1080,7 @@ class DroidDeckHudView(context: Context) : View(context) {
if (stripRect != null && layerType != LAYER_TYPE_SOFTWARE) drawCachedGraph(canvas, it) else drawGraph(canvas, it)
}
canvas.restoreToCount(saved)
lockController.drawBadge(canvas)
}
@@ -1177,13 +1193,14 @@ class DroidDeckHudView(context: Context) : View(context) {
return if (dy <= 0f) p.right - stroke else if (dy >= r) cx else cx + sqrt(r * r - dy * dy)
}
private fun panelFrame(panel: RectF): Bitmap? {
private fun panelFrame(panel: RectF, fit: Float): Bitmap? {
if (width <= 0 || height <= 0) return null
val stroke = outlineWidth()
val key = "$width,$height,$panel,$dRadius,$dDividerTop,$stroke,$accent,$surfaceRgb,$bgOpacity,${outlineColor()}"
val key = "$width,$height,$fit,$panel,$dRadius,$dDividerTop,$stroke,$accent,$surfaceRgb,$bgOpacity,${outlineColor()}"
if (key == dFrameKey) dFrame?.let { return it }
val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val c = Canvas(bmp)
c.scale(fit, fit)
val corner = sp(6f)
val body = dShape(panel.left, panel.top, panel.right, panel.bottom, dRadius, corner)
bgPaint.color = panelColor()
@@ -1256,8 +1273,8 @@ class DroidDeckHudView(context: Context) : View(context) {
internal val isStrip: Boolean get() = stripRect != null
internal val contentWidth: Float get() = contentW
internal val contentHeight: Float get() = contentH
internal val contentWidth: Float get() = contentW * panelFit
internal val contentHeight: Float get() = contentH * panelFit
internal val isDragging: Boolean get() = lockController.isDragging() || tabDragging
@@ -46,7 +46,14 @@ internal class ControllerPortraitGeometry(
}
row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit)
var bodyTop = top + pad + buttonHeight + gap
if (presented.any { it.control in REAR && isStock(it) }) {
if (presented.any { it.control in REAR && isStock(it) } && docked) {
val chipHeight = 36f * unit
val cell = (w - 2f * pad - 5f * gap) / 6f
listOf(0, 1, 4, 5).zip(REAR).forEach { (index, control) ->
put(control, Box(safe.left + pad + cell / 2f + index * (cell + gap), bodyTop + chipHeight / 2f, cell, chipHeight))
}
bodyTop += chipHeight + gap
} else if (presented.any { it.control in REAR && isStock(it) }) {
val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight)
row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap)
bodyTop += rearHeight + gap
@@ -19,6 +19,7 @@ object ControllerPrefs {
)
val opacities = listOf(40, 60, 80, 100)
val onScreenOpacityRange = 10..100
val sizes = listOf(80, 85, 90, 95, 100, 105, 110, 115, 120, 125)
@@ -45,6 +46,7 @@ object ControllerPrefs {
val size: Int,
val stickClick: Boolean,
val adaptiveSticks: Boolean,
val onScreenOpacity: Int,
val rumble: Boolean,
val steamButton: Boolean,
val qamButton: Boolean,
@@ -66,7 +68,8 @@ object ControllerPrefs {
opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100,
size = p.getInt("size", 100).takeIf { it in sizes } ?: 100,
stickClick = p.getBoolean("stickClick", true),
adaptiveSticks = p.getBoolean("adaptiveSticks", true),
adaptiveSticks = p.getBoolean("adaptiveSticks", false),
onScreenOpacity = onScreenOpacity(context),
rumble = rumbleEnabled(context),
steamButton = p.getBoolean("steamButton", true),
qamButton = p.getBoolean("qamButton", true),
@@ -103,6 +106,13 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("stickClick", on).apply()
}
fun onScreenOpacity(context: Context): Int =
prefs(context).getInt("onScreenOpacity", 100).coerceIn(onScreenOpacityRange)
fun setOnScreenOpacity(context: Context, percent: Int) {
prefs(context).edit().putInt("onScreenOpacity", percent.coerceIn(onScreenOpacityRange)).apply()
}
fun setAdaptiveSticks(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
}
@@ -36,6 +36,13 @@ object OnScreenLayout {
fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
trackpads: Boolean? = null): List<InputSurfaceElement> {
val placed = placeElements(context, saved, width, height, safe, buttonsOnly, dock, rearButtons, trackpads)
// Below the game a stick covers nothing, so it keeps its base in view instead of appearing only under the thumb.
return if (dock == null) placed else placed.map { if (it.kind == InputElementKind.STICK) it.copy(hideWhenIdle = false) else it }
}
private fun placeElements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean, dock: Dock?, rearButtons: Boolean?, trackpads: Boolean?): List<InputSurfaceElement> {
if (saved == null) return emptyList()
if (width <= 0 || height <= 0) return saved.elements
val layout = oriented(saved, dock?.portrait ?: (height > width))
@@ -0,0 +1,271 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.SystemClock
import android.system.Os
import android.system.OsConstants
import android.util.Log
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.security.MessageDigest
/** One app-issued Steam session and one attested Gamescope worker. This is not an
* isolation boundary against arbitrary code already running as the Android app UID. */
internal object FrameAcquireWorkerProbe {
private const val SESSION_SCRIPT = "/usr/local/bin/droiddeck-session"
private const val PATH = "/usr/local/bin/gamescope"
private const val CAPABILITY = "linuxfs/usr/local/share/droiddeck/gamescope-producer-acquire-v1"
internal const val GAMESCOPE_ENABLE = "GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE=1"
internal const val GAME_ENABLE = "DROIDDECK_GAME_DROIDDECK_GAME_FRAME_ACQUIRE=1"
private const val MAX_BINARY_BYTES = 32L * 1024L * 1024L
internal const val RECEIPT_TAG = 0x44445046
internal const val RECEIPT_BYTES = Int.SIZE_BYTES + Long.SIZE_BYTES
private const val TTL_MS = 90_000L
internal data class Ticket(
val owner: Int, val root: File, val configuredRoot: File, val binary: File,
val expected: ByteArray, val expires: Long, val steamGameUrl: String?,
)
internal data class Qualified(val ticket: Ticket, val dev: Long, val ino: Long, val mtime: Long, val ctime: Long)
private var intent: Ticket? = null
private var nativeOwner = 0
private var nativePid = 0
private enum class Stage { ARM, MATCH, PUBLISH }
private enum class Reason {
ENABLED, MATCH_ACK, MATCH_OWNER, MATCH_EXPIRED, MATCH_PATH, MATCH_ROOT,
MATCH_ARGV, MATCH_FILE, MATCH_DIGEST, QUALIFIED, PUBLISH_TICKET, PUBLISH_RESTAT,
PUBLISH_NATIVE, PUBLISH_RECEIPT, RESERVED
}
private val reported = mutableSetOf<Stage>()
@Synchronized private fun breadcrumb(stage: Stage, reason: Reason) {
if (reported.add(stage)) Log.i("FrameAcquireWorkerProbe", "worker_admission=" + reason.name)
}
internal fun validEnvironment(agentEnvironment: List<String>, customEnvironment: List<String>): Boolean {
// AgentEnv supplies a replacement PATH whenever any executable override is staged.
// Custom env is user-editable, including names not known to this build; it is not a trust root.
return agentEnvironment.isEmpty() && customEnvironment.isEmpty()
}
fun available(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.core.DeviceSupport.adreno() &&
runCatching { context.assets.open(CAPABILITY).use { it.readBytes().decodeToString() } }
.getOrNull() == "droiddeck-producer-acquire-v1\n"
private fun digest(input: InputStream, maxBytes: Long): ByteArray {
val out = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(64 * 1024)
var size = 0L
while (true) {
val n = input.read(buffer)
if (n == -1) break
require(n > 0)
size += n
require(size <= maxBytes)
out.update(buffer, 0, n)
}
require(size > 0)
return out.digest()
}
// Compute asset identity outside SessionService's stop lock and before a worker
// exists. The resulting ticket still has to be assigned to that exact owner.
private const val STEAM_RUN_PREFIX = "steam://rungameid/"
internal fun permittedLaunch(url: String?, frontendGame: Boolean): Boolean =
if (url == null) !frontendGame else frontendGame && url.startsWith(STEAM_RUN_PREFIX) &&
com.droiddeck.launcher.frontend.GameLaunchLink.validId(url.removePrefix(STEAM_RUN_PREFIX))
internal fun prepare(context: Context, steamGameUrl: String?, frontendGame: Boolean): Ticket? {
if (!permittedLaunch(steamGameUrl, frontendGame) ||
!available(context) || !WaylandCompositor.frameWorkerProbeEnabled()) return null
return runCatching {
val configuredRoot = LinuxRuntime.rootDir(context).absoluteFile
val root = configuredRoot.canonicalFile
val file = File(root.path + PATH)
require(file.canonicalFile == file && Files.isRegularFile(file.toPath(), NOFOLLOW_LINKS))
val script = File(root.path + SESSION_SCRIPT)
require(exactSteamScript(SESSION_SCRIPT, root, configuredRoot))
val stagedScript = script.inputStream().use { digest(it, 1024L * 1024L) }
val signedScript = context.assets.open("linuxfs" + SESSION_SCRIPT).use { digest(it, 1024L * 1024L) }
require(MessageDigest.isEqual(stagedScript, signedScript))
val expected = context.assets.open("linuxfs" + PATH).use { digest(it, MAX_BINARY_BYTES) }
Ticket(0, root, configuredRoot, file, expected, SystemClock.elapsedRealtime() + TTL_MS, steamGameUrl)
}.getOrNull()
}
@Synchronized fun arm(owner: Int, prepared: Ticket): Boolean {
if (owner <= 0 || SystemClock.elapsedRealtime() >= prepared.expires) return false
reported.clear()
intent = prepared.copy(owner = owner)
breadcrumb(Stage.ARM, Reason.ENABLED)
return true
}
/** Native shebang handling can give Bash the staged host filename as its $0. */
internal fun exactSteamScript(token: String, root: File, configuredRoot: File): Boolean {
if (token != SESSION_SCRIPT && token != root.path + SESSION_SCRIPT &&
token != configuredRoot.path + SESSION_SCRIPT) return false
return runCatching {
val expected = File(root.path + SESSION_SCRIPT)
val supplied = if (token == SESSION_SCRIPT) expected else File(token)
// Reject symlinks within the authorized root, including a symlink replacing the script.
// Android's configured root itself may be an alias of its app-issued canonical root.
require(configuredRoot.canonicalFile == root && expected.canonicalFile == expected &&
supplied.canonicalFile == expected &&
Files.isRegularFile(expected.toPath(), NOFOLLOW_LINKS) &&
Files.isRegularFile(supplied.toPath(), NOFOLLOW_LINKS))
Files.isSameFile(supplied.toPath(), expected.toPath())
}.getOrDefault(false)
}
internal fun exactGamescopeArgs(
argv: List<String>, steamGameUrl: String? = null, script: (String) -> Boolean,
): Boolean {
if (argv.firstOrNull() !in listOf("gamescope", PATH)) return false
val delimiter = argv.indexOf("--")
val tailSize = if (steamGameUrl == null) 3 else 4
if (delimiter < 4 || argv.size != delimiter + tailSize || argv[delimiter + 2] != "steam" ||
!script(argv[delimiter + 1]) ||
(steamGameUrl != null && (!permittedLaunch(steamGameUrl, true) || argv.last() != steamGameUrl))) return false
val opts = argv.subList(1, delimiter)
if (opts.take(4) != listOf("--backend", "wayland", "--expose-wayland", "-f")) return false
val dimensions = setOf("-W", "-H", "-w", "-h")
val seen = mutableSetOf<String>()
var i = 4
while (i < opts.size) {
val option = opts[i++]
if (!seen.add(option)) return false
when (option) {
"-e", "--hdr-enabled", "--mangoapp" -> Unit
"-S" -> if (opts.getOrNull(i++) != "stretch") return false
"--default-touch-mode" -> if (opts.getOrNull(i++) != "4") return false
"-W", "-H", "-w", "-h", "-r", "--xwayland-count" -> {
val value = opts.getOrNull(i++) ?: return false
if (value.length !in 1..6 || value.any { it !in '0'..'9' } ||
value.toIntOrNull()?.let { it > 0 } != true) return false
}
else -> return false
}
}
return seen.containsAll(dimensions)
}
fun match(owner: Int, root: File, file: String, argv: List<String>, ack: Boolean): Qualified? {
val t = synchronized(this) { intent } ?: return null
// Startup's --version worker and unrelated workers must not consume the one diagnostic.
val candidate = "--version" !in argv && (file.substringAfterLast('/') == "gamescope" ||
argv.firstOrNull()?.substringAfterLast('/') == "gamescope")
val rejection = when {
!ack -> Reason.MATCH_ACK
t.owner != owner -> Reason.MATCH_OWNER
SystemClock.elapsedRealtime() >= t.expires -> Reason.MATCH_EXPIRED
file != PATH -> Reason.MATCH_PATH
runCatching { root.canonicalFile }.getOrNull() != t.root -> Reason.MATCH_ROOT
!exactGamescopeArgs(argv, t.steamGameUrl) { exactSteamScript(it, t.root, t.configuredRoot) } -> Reason.MATCH_ARGV
else -> null
}
if (rejection != null) {
if (candidate) breadcrumb(Stage.MATCH, rejection)
return null
}
// Hash an actual descriptor rather than two pathname opens. Check both the
// descriptor and pathname identity; a race or substituted executable denies the grant.
val qualified = runCatching {
require(t.binary.canonicalFile == t.binary)
val before = Os.lstat(t.binary.path)
require(OsConstants.S_ISREG(before.st_mode) && before.st_size in 1..MAX_BINARY_BYTES)
val fd = Os.open(t.binary.path, OsConstants.O_RDONLY or OsConstants.O_NOFOLLOW or OsConstants.O_CLOEXEC, 0)
val sum = try {
require(stillSame(before, Os.fstat(fd)))
android.os.ParcelFileDescriptor.AutoCloseInputStream(android.os.ParcelFileDescriptor.dup(fd)).use {
digest(it, MAX_BINARY_BYTES)
}.also { require(stillSame(before, Os.fstat(fd))) }
} finally {
Os.close(fd)
}
val after = Os.lstat(t.binary.path)
require(stillSame(before, after))
if (!MessageDigest.isEqual(sum, t.expected)) {
breadcrumb(Stage.MATCH, Reason.MATCH_DIGEST)
return null
}
Qualified(t, after.st_dev, after.st_ino, after.st_mtime, after.st_ctime)
}.getOrNull()
breadcrumb(Stage.MATCH, if (qualified == null) Reason.MATCH_FILE else Reason.QUALIFIED)
return qualified
}
private fun stillSame(a: android.system.StructStat, b: android.system.StructStat): Boolean =
a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_size == b.st_size &&
a.st_mtime == b.st_mtime && a.st_ctime == b.st_ctime &&
OsConstants.S_ISREG(b.st_mode)
internal fun validReceipt(pid: Int, workerPid: Int, ticks: Long, bytes: Int): Long =
if (pid > 1 && pid == workerPid && ticks > 0 && bytes == RECEIPT_BYTES) ticks else 0L
internal fun parseSelfStat(stat: String, pid: Int): Long {
if (pid <= 1 || !stat.startsWith("$pid (")) return 0L
val comm = stat.lastIndexOf(')')
if (comm < 3 || stat.getOrNull(comm + 1) != ' ') return 0L
val fields = stat.substring(comm + 2).split(' ').filter { it.isNotEmpty() }
if (fields.firstOrNull()?.length != 1 || fields.size < 21) return 0L
val value = fields[19] // field 22 from field 3 (the single-character task state).
return value.takeIf { it.isNotEmpty() && it.all { ch -> ch in '0'..'9' } }
?.toLongOrNull()?.takeIf { it > 0 } ?: 0L
}
internal fun selfStartTicks(pid: Int): Long = runCatching {
File("/proc/self/stat").inputStream().use { input ->
val bytes = ByteArray(4096)
var used = 0
while (used < bytes.size) {
val n = input.read(bytes, used, bytes.size - used)
if (n < 0) break
if (n == 0) return@runCatching 0L
used += n
}
if (used == bytes.size || used == 0 || bytes[used-1] != '\n'.code.toByte()) 0L
else parseSelfStat(String(bytes, 0, used, Charsets.US_ASCII), pid)
}
}.getOrDefault(0L)
/** Runs just before the final GO byte. Failure never changes ordinary launch. */
@Synchronized fun publish(q: Qualified, pid: Int, startTicks: Long) {
val t = q.ticket
if (intent !== t || pid <= 1 || SystemClock.elapsedRealtime() >= t.expires) {
if (intent === t) breadcrumb(Stage.PUBLISH, Reason.PUBLISH_TICKET)
return
}
intent = null // At most one candidate per explicitly armed session.
if (startTicks <= 0L) {
breadcrumb(Stage.PUBLISH, Reason.PUBLISH_RECEIPT)
return
}
val status = runCatching {
val st = Os.lstat(t.binary.path)
require(OsConstants.S_ISREG(st.st_mode) && st.st_dev == q.dev && st.st_ino == q.ino &&
st.st_mtime == q.mtime && st.st_ctime == q.ctime)
if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino, startTicks)) {
nativeOwner = t.owner
nativePid = pid
Reason.RESERVED
} else Reason.PUBLISH_NATIVE
}.getOrDefault(Reason.PUBLISH_RESTAT)
breadcrumb(Stage.PUBLISH, status)
}
@Synchronized fun revoke(owner: Int, pid: Int = 0) {
if (owner <= 0) return
if (pid == 0 && intent?.owner == owner) intent = null
if (nativeOwner == owner && (pid == 0 || pid == nativePid)) {
WaylandCompositor.frameWorkerProbeRevoke(owner, pid)
nativeOwner = 0
nativePid = 0
}
}
}
@@ -45,7 +45,16 @@ open class GuestWorker : Service() {
val fillBinderFd = data.readInt() != 0
val go = data.readFileDescriptor()
val nice = data.readInt()
reply?.writeInt(Process.myPid())
val pid = Process.myPid()
reply?.writeInt(pid)
// Optional fixed-size receipt, on the exact local, non-exported worker's Binder.
// Nothing in the guest socket request populates these fields.
if (reply != null &&
Binder.getCallingUid() == Process.myUid() &&
data.dataAvail() == Int.SIZE_BYTES && data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG) {
reply.writeInt(pid)
reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid))
}
Handler(Looper.getMainLooper()).post {
// The app writes a byte once it has the reply and has taken the launch on: an exec
// before then would end this process with the reply undelivered, and with none (the
@@ -395,9 +404,13 @@ object GuestWorkers {
private set
/** Whether the session runs its programs in workers: the native userland, and not turned off. */
fun enabled(context: Context): Boolean =
fun enabled(context: Context): Boolean = handoffAllowed(context) && NativeGuest.enabled(context)
private fun handoffAllowed(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context) &&
NativeGuest.enabled(context)
com.droiddeck.launcher.core.PhantomProcessLimit.workersWanted(
com.droiddeck.launcher.core.PhantomProcessLimit.setting(context),
com.droiddeck.launcher.session.SessionPrefs.producerAcquireFences(context))
/** How the running session's root was started: in a worker (true) or counted (false); null with none running. */
@Volatile var sessionRootUncounted: Boolean? = null
@@ -408,7 +421,7 @@ object GuestWorkers {
* the next one would start.
*/
fun limitHandled(context: Context): Boolean =
sessionRootUncounted ?: (NativeGuest.sessionMode != false && enabled(context))
sessionRootUncounted ?: (NativeGuest.sessionMode != false && handoffAllowed(context) && NativeGuest.nextSession(context))
/** Whether pid is a program running in one of the workers. */
fun runsInWorker(pid: Int): Boolean = pid > 0 && synchronized(slots) { slots.any { it != null && it.started && it.pid == pid } }
@@ -436,7 +449,8 @@ object GuestWorkers {
private fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true },
confirmed: () -> Boolean = { true }, owner: Int = session,
nice: Int = Process.getThreadPriority(Process.myTid())): Int {
nice: Int = Process.getThreadPriority(Process.myTid()),
testWorker: FrameAcquireWorkerProbe.Qualified? = null): Int {
val app = context.applicationContext
if (guest && owner <= stopped) {
Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") +
@@ -472,13 +486,21 @@ object GuestWorkers {
data.writeInt(if (guest) 0 else 1)
data.writeFileDescriptor(go[0].fileDescriptor)
data.writeInt(nice)
slot.service!!.transact(GuestWorker.RUN, data, reply, 0)
val service = checkNotNull(slot.service)
if (testWorker != null) data.writeInt(FrameAcquireWorkerProbe.RECEIPT_TAG)
check(service.transact(GuestWorker.RUN, data, reply, 0))
// The worker has its own copy: with ours closed (and the request's, which holds one too),
// a worker that gave up leaves no reader
data.recycle()
data = null
go[0].close()
val pid = reply.readInt()
val startTicks = if (testWorker != null) {
val size = reply.dataAvail()
if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES)
FrameAcquireWorkerProbe.validReceipt(pid, reply.readInt(), reply.readLong(), size)
else 0L
} else 0L
// Once a session's teardown has begun (stopGuests), none of its programs may start: it
// would not find them.
val stopping = { guest && owner <= stopped }
@@ -507,7 +529,12 @@ object GuestWorkers {
// launching slot), or never.
val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1
val accepted = answered && synchronized(authorizing) {
!stopping() && confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
if (stopping() || !confirmed()) false
else {
if (testWorker != null) FrameAcquireWorkerProbe.publish(testWorker, pid,
if (slot.service === service) startTicks else 0L)
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
}
}
val endedRunning = synchronized(slots) {
slot.launching = false
@@ -684,6 +711,7 @@ object GuestWorkers {
}
}
context?.let { app -> drained.forEach { release(app, it) } }
FrameAcquireWorkerProbe.revoke(of)
val pids = guestPids(of)
if (pids.isEmpty()) return
pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) }
@@ -901,16 +929,19 @@ object GuestWorkers {
val owner = request.optInt("session", 0).coerceAtLeast(0)
// The sender is the forked child (or droiddeck-spawn): its priority is the one the program would inherit
val nice = runCatching { Process.getThreadPriority(client.peerCredentials.pid) }.getOrDefault(Process.THREAD_PRIORITY_DEFAULT)
val testWorker = FrameAcquireWorkerProbe.match(owner, root, file, argv, ack)
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, nice = nice, onExit = { code ->
if (testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker)
status = code
if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker)
exited.countDown()
}, confirmed = {
!ack || runCatching {
val confirmed = !ack || runCatching {
out.write("ok\n".toByteArray())
out.flush()
confirmedToHook = true
}.isSuccess
confirmed
}, commit = { started ->
worker = started
if (!ack) return@start true
@@ -929,7 +960,8 @@ object GuestWorkers {
}
ended && line.toString() == "go"
}.getOrDefault(false)
})
}, testWorker = testWorker)
if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker)
handedOver = true
programFds.filter { it !== table }.forEach { runCatching { it.close() } }
if (pid <= 0) table?.let { runCatching { it.close() } }
@@ -24,6 +24,16 @@ object NativeGuest {
fun enabled(context: Context): Boolean =
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
/**
* Whether the next session will start natively. The session stages the hook from the APK before
* it starts, so only the setting and the rootfs's loader decide, and a runtime still to be
* installed will have one.
*/
fun nextSession(context: Context): Boolean =
SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null
/** The mode the running session started in; null between sessions. */
@Volatile var sessionMode: Boolean? = null
@@ -30,6 +30,8 @@ object ComponentsManager {
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
internal const val DD_NIGHTLY = "linux-nightly"
internal const val DD_BIONIC = "bionic-stable"
/** FEX for original Xbox games on DroidDeck-Bionic: kept apart from [DD_BIONIC] so automatic FEX updates never pick it. */
internal const val DD_XBOX = "bionic-xbox"
private val RELEASES = linkedMapOf(
"FexCore-Linux" to "fex",
"Dxvk-Linux" to "dxvk",
@@ -38,7 +40,8 @@ object ComponentsManager {
"Vkd3d-proton-Linux" to "vkd3d",
)
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC) +
(DD_COMPONENTS to DD_XBOX)
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
@@ -253,6 +256,28 @@ object ComponentsManager {
saveState(context, state)
}
internal enum class Assigned { SET, NOT_LISTED, CHANGED }
/**
* Sets a game's component to a listed package, fetching it first when it is not stored. [expected] is the component
* the caller read when it decided: if the game's component is something else once the package is ready (the player
* chose one during the download), nothing is written. [onSet] runs under the same lock as the write.
*/
internal fun assignGameComponent(context: Context, scope: String, comp: String, file: String, release: String,
expected: String?, onSet: () -> Unit = {}): Assigned {
val wcp = File(packagesDir(context), safeName(file))
if (!wcp.isFile || runCatching { packageInfo(context, wcp) }.isFailure) {
wcp.delete()
download(context, catalogItem(context, file, release) ?: return Assigned.NOT_LISTED) {}
}
synchronized(lock) {
if (gameComponents(context, scope)[comp] != expected) return Assigned.CHANGED
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
onSet()
}
return Assigned.SET
}
fun clearGameComponents(context: Context, scope: String) = synchronized(lock) {
require(GameEnvironment.validScope(scope))
val state = loadState(context)
@@ -1124,7 +1149,7 @@ object ComponentsManager {
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
DD_BIONIC -> "fex"
DD_BIONIC, DD_XBOX -> "fex"
else -> null
}
@@ -0,0 +1,70 @@
package com.droiddeck.launcher.session
import android.util.Log
import java.io.File
internal object PageCacheTrim {
private const val TAG = "PageCacheTrim"
private const val MIN_FILE_BYTES = 8L shl 20
private const val POLL_MS = 3000L
private const val RESCAN_MS = 120_000L
data class Mem(val freeKb: Long, val fileKb: Long)
fun parse(meminfo: String): Mem? {
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(meminfo)?.groupValues?.get(1)?.toLongOrNull()
val free = field("MemFree") ?: return null
val file = (field("Active\\(file\\)") ?: return null) + (field("Inactive\\(file\\)") ?: return null)
return Mem(free, file)
}
fun shouldTrim(mem: Mem, baselineFileKb: Long): Boolean {
val built = mem.fileKb - baselineFileKb
return (mem.freeKb < 2560 * 1024 && built >= 768 * 1024) ||
(mem.freeKb < 1024 * 1024 && built >= 128 * 1024)
}
fun start(roots: () -> List<File>, alive: () -> Boolean) {
Thread({
var baseline = 0L
var files = emptyList<File>()
var scanned = 0L
var trims = 0
var failureLogged = false
while (alive()) {
runCatching {
val mem = parse(File("/proc/meminfo").readText())
if (mem != null && shouldTrim(mem, baseline)) {
val now = System.currentTimeMillis()
if (now - scanned > RESCAN_MS) {
files = roots().flatMap { root -> root.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }.filter { it.isFile && it.length() >= MIN_FILE_BYTES }.toList() }
scanned = now
}
val began = System.nanoTime()
files.forEach(::drop)
val after = parse(File("/proc/meminfo").readText())
baseline = after?.fileKb ?: mem.fileKb
trims++
Log.i(TAG, "trim #$trims: free ${mem.freeKb / 1024} -> ${after?.freeKb?.div(1024)} MB, file cache ${mem.fileKb / 1024} -> ${after?.fileKb?.div(1024)} MB, ${files.size} files, ${(System.nanoTime() - began) / 1_000_000} ms")
}
}.onFailure {
if (!failureLogged) Log.w(TAG, "trim failed: $it")
failureLogged = true
}
Thread.sleep(POLL_MS)
}
}, "page-cache-trim").apply { isDaemon = true }.start()
}
private fun drop(file: File) {
PageCacheNative.fadviseDontNeed(file.path)
}
}
internal object PageCacheNative {
init {
System.loadLibrary("sdnative")
}
@JvmStatic external fun fadviseDontNeed(path: String): Int
}
@@ -16,6 +16,7 @@ object SessionDisplay {
const val LINK_PORTRAIT = "link/portrait"
const val DEFAULT_RESOLUTION = "720p"
const val DEFAULT_STEAM_PORTRAIT_RESOLUTION = "1280x800"
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
fun presetHeight(choice: String): Int? =
@@ -364,13 +364,13 @@ object SessionPrefs {
prefs(context).edit().putInt("libraryCardLevel", level).apply()
}
fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", true)
fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", false)
fun setLibraryShowTitle(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowTitle", show).apply()
}
fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", true)
fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", false)
fun setLibraryShowSize(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowSize", show).apply()
@@ -946,13 +946,21 @@ object SessionPrefs {
}
fun picturePosition(context: Context): String =
prefs(context).getString("picturePosition", "center")
?.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center"
private val picturePositions = setOf("center", "top", "bottom", "left", "right")
fun setPicturePosition(context: Context, position: String) {
prefs(context).edit().putString("picturePosition",
position.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center").apply()
private fun picturePositionKey(portrait: Boolean) =
if (portrait) "picturePosition.portrait" else "picturePosition.landscape"
fun picturePosition(context: Context, portrait: Boolean): String {
val preferences = prefs(context)
return preferences.getString(picturePositionKey(portrait), null)?.takeIf { it in picturePositions }
?: preferences.getString("picturePosition", null)?.takeIf { it in picturePositions }
?: if (portrait) "top" else "center"
}
fun setPicturePosition(context: Context, portrait: Boolean, position: String) {
require(position in picturePositions)
prefs(context).edit().putString(picturePositionKey(portrait), position).apply()
}
fun integerScaling(context: Context): Boolean =
@@ -1513,10 +1521,12 @@ object SessionPrefs {
fun resolutionStored(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean): String {
if (!portrait) return landscapeResolutionStored(context, mode, panel)
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE
val fallback = if (mode == SessionService.MODE_STEAM) SessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION
else SessionDisplay.LINK_LANDSCAPE
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return fallback
if (value == SessionDisplay.LINK_LANDSCAPE || value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) ||
SessionDisplay.presetHeight(value) != null) return value
return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE
return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: fallback
}
fun parseOrientedResolution(text: String): Pair<Int, Int>? =
@@ -1778,6 +1788,9 @@ object SessionPrefs {
name.removeSuffix(from) + to to moved
}
fun storedAddedGameAppId(context: Context, folderPath: String): Long? =
prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
fun addedGameAppId(context: Context, folderPath: String, first: Long): Long = synchronized(addedGameLock) {
val p = prefs(context)
p.getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
@@ -1874,6 +1887,13 @@ object SessionPrefs {
prefs(context).edit().putBoolean(hdrKey(mode), on).apply()
}
/** Restart-scoped opt-in; not inferred from Zero-copy (which defaults on). */
fun producerAcquireFences(context: Context): Boolean = prefs(context).getBoolean("producerAcquireFences", false)
fun setProducerAcquireFences(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("producerAcquireFences", on).apply()
}
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.${prefMode(mode)}", true)
fun setZeroCopy(context: Context, mode: String, on: Boolean) {
@@ -394,8 +394,10 @@ class SessionService : Service() {
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
val steamUrlGameId = SessionState.steamUrl
val launchSteamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
val frontendSteamGame = intent?.getBooleanExtra(EXTRA_FRONTEND_STEAM_GAME, false) == true
SessionState.steamUrl = launchSteamUrl
val steamUrlGameId = launchSteamUrl
?.let { url ->
when {
url.startsWith(GAME_URL_PREFIX) ->
@@ -426,6 +428,11 @@ class SessionService : Service() {
++sessionGen
}
}
val trimGen = gen
PageCacheTrim.start(
roots = { listOfNotNull(File(filesDir, "linuxfs"), GameStorage.effective(applicationContext)?.let { File(it.path) }).filter(File::isDirectory) },
alive = { SessionState.running && sessionGen == trimGen },
)
if (SessionState.stopRequested) {
stopSession(0)
return START_NOT_STICKY
@@ -447,7 +454,7 @@ class SessionService : Service() {
Thread({
OrphanReaper.reap("session starting")
ProtonExtras.awaitReplacement(120_000)
runSession(gen)
runSession(gen, launchSteamUrl, frontendSteamGame)
}, "session-start").start()
return START_NOT_STICKY
}
@@ -500,7 +507,7 @@ class SessionService : Service() {
}
private fun runSession(gen: Int) {
private fun runSession(gen: Int, launchSteamUrl: String?, frontendSteamGame: Boolean) {
SessionPrefs.ensurePowerVrAutoDriversAfterGpuQuery(this)
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
@@ -555,9 +562,10 @@ class SessionService : Service() {
return
}
}
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
val nextAgentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList())
val customEnvironment = extraEnv()
try {
if (systemVulkan) {
SystemVulkanDriver.prepare(this)
@@ -614,6 +622,9 @@ class SessionService : Service() {
val size = SessionState.outputSize
val guest = ArrayList<String>()
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
runCatching { SessionEvents.step("components-xbox") { XboxBackCompatComponents.ensure(this) } }
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "original Xbox components", it) }
runCatching { SessionEvents.step("components-republish") { ComponentsManager.republish(this) } }
.onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") }
.onFailure { Log.w(TAG, "component selections", it) }
@@ -623,7 +634,7 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "forced components", it) }
}
try {
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment) }
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment, customEnvironment) }
} catch (e: IllegalStateException) {
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
@@ -708,15 +719,28 @@ class SessionService : Service() {
// this session's worker number: the shared field may be a newer session's by the time it is used
var ownWorkers = 0
if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) {
val fenceWorker = com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe
val preparedFence = if (steamHere && !systemVulkan && !VenusComponent.wanted(this) &&
SessionPrefs.zeroCopy(this, MODE_STEAM) && SessionPrefs.producerAcquireFences(this) &&
nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment(agentEnvironment, customEnvironment)
) fenceWorker.prepare(this, launchSteamUrl, frontendSteamGame) else null
var fenceArmed = false
// Under the lock a stop takes its number with: a stop either comes first (and this session
// starts no workers) or owns them
ownWorkers = synchronized(stopLock) {
if (gen != sessionGen || !SessionState.running) 0
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { guestWorkerSession = it }
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also {
guestWorkerSession = it
if (preparedFence != null) fenceArmed = fenceWorker.arm(it, preparedFence)
}
}
if (ownWorkers > 0) {
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
guest.add("DD_SPAWN_SESSION=$ownWorkers")
if (fenceArmed) {
guest.add(fenceWorker.GAMESCOPE_ENABLE)
guest.add(fenceWorker.GAME_ENABLE)
}
}
}
// Proton builds up to 11.12 report X11 text fields under this name.
@@ -738,7 +762,7 @@ class SessionService : Service() {
val desktopGuest = ArrayList(guest)
guest.add(LinuxRuntime.SESSION_SCRIPT)
guest.add(SessionState.mode)
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl?.takeIf { it.startsWith("steam://") }?.let {
if (SessionState.mode == MODE_STEAM) launchSteamUrl?.takeIf { it.startsWith("steam://") }?.let {
guest.add(it)
Log.i(TAG, "steam: handing the client $it")
}
@@ -921,11 +945,15 @@ class SessionService : Service() {
return
}
if (gen == sessionGen && SessionState.running) {
val workers = ownWorkers
suspendController = SessionSuspendController(
sessionRoot = { sessionPid },
// Programs handed off to worker processes are not descendants of the session root, and
// the clock shift applied at resume would move their monotonic time backwards.
helperRoots = {
components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } +
listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 })
listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 }) +
(if (workers > 0) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workers) else emptyList())
},
suspendAudio = {
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
@@ -1017,7 +1045,8 @@ class SessionService : Service() {
return com.droiddeck.launcher.input.GesturePrefs.read(this, game).relativeMouseMode
}
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean, agentEnvironment: List<String>) {
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean,
agentEnvironment: List<String>, customEnvironment: List<String>) {
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
@@ -1135,7 +1164,7 @@ class SessionService : Service() {
guest.add("DD_ZRAM=1")
}
guest.add("AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + agentEnvironment
val extra = customEnvironment + agentEnvironment
guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra))
if (extra.none { it.startsWith("MESA_NO_ERROR=") }) guest.add("${GAME_PREFIX}MESA_NO_ERROR=")
extra.forEach { guest.add(it) }
@@ -2755,6 +2784,9 @@ class SessionService : Service() {
const val EXTRA_PROGRAM_ARGS = "programArgs"
const val EXTRA_STEAM_UI = "steamUi"
const val EXTRA_STEAM_URL = "steamUrl"
// Set by the first-party Library play action on the private SessionActivity/Service path.
// Never copied from an exported intent or Agent command.
internal const val EXTRA_FRONTEND_STEAM_GAME = "com.droiddeck.launcher.FRONTEND_STEAM_GAME"
const val EXTRA_GAME_ID = "gameId"
fun start(
@@ -2762,6 +2794,7 @@ class SessionService : Service() {
steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null,
gameId: String? = null,
displayId: Int = Display.DEFAULT_DISPLAY,
frontendSteamGame: Boolean = false,
) {
SteamClientPrefetch.cancel()
SessionState.activityDisplayId = displayId
@@ -2772,6 +2805,7 @@ class SessionService : Service() {
if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs)
if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi)
if (steamUrl != null) intent.putExtra(EXTRA_STEAM_URL, steamUrl)
if (frontendSteamGame) intent.putExtra(EXTRA_FRONTEND_STEAM_GAME, true)
if (gameId != null) intent.putExtra(EXTRA_GAME_ID, gameId)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent)
else context.startService(intent)
@@ -1,6 +1,12 @@
package com.droiddeck.launcher.session
internal object SessionVisibilityPolicy {
fun shouldCloseSecondScreenOnStop(
screenOff: Boolean,
dockedDrawerOpen: Boolean,
attachmentPickerOpen: Boolean,
): Boolean = !screenOff && !(dockedDrawerOpen && attachmentPickerOpen)
fun isHidden(
activityStarted: Boolean,
defaultDisplayOn: Boolean,
@@ -18,9 +18,9 @@ object SettingsReset {
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "avoidNotch", "picturePosition", "picturePosition.portrait", "picturePosition.landscape", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "producerAcquireFences", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite", "mountSharedStorage",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.xbox.XboxManifest
/**
* Microsoft's original Xbox releases for PC run its emulator, which needs FEX and VKD3D-Proton builds with fixes of
* their own (each off unless droiddeck-game-env turns it on for these games) and a newer DXVK than some Protons carry.
* Each installed one gets them as its game components. A component the player chose for the game is never replaced;
* one set here follows this list, so a newer build replaces it, and one the player cleared stays cleared.
*/
internal object XboxBackCompatComponents {
private const val TAG = "XboxBackCompat"
private const val PREFS = "xbox-backcompat-components"
internal data class Wanted(val comp: String, val file: String, val release: String)
internal fun wanted(family: GpuInfo.Family?): List<Wanted> = listOf(
Wanted("fex", "FEXCore-2611.1-xbox-bionic.wcp", ComponentsManager.DD_XBOX),
Wanted("vkd3d", "vkd3d-proton-arm64ec-3.1-xbox-linux.wcp", "Vkd3d-proton-Linux"),
Wanted("dxvk", if (family == GpuInfo.Family.A6XX) "dxvk-gplasync-3.2-a6xx-1-linux.wcp" else "dxvk-gplasync-3.2-1-linux.wcp",
"Dxvk-gplasync-Linux"),
)
/** The file to set for one component of a game, or null to leave it as it is. */
internal fun decide(current: String?, assigned: String?, wanted: String): String? = when {
current == null && assigned == null -> wanted
current != null && current == assigned && current != wanted -> wanted
else -> null
}
internal class Game(val scope: String, val title: String)
internal fun installed(context: Context): List<Game> = StoreInstallRoot.gameFolders(context).mapNotNull { folder ->
val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.store == Store.XBOX && it.isInstalled } ?: return@mapNotNull null
if (!XboxManifest.backCompat(folder)) return@mapNotNull null
val appId = SessionPrefs.storedAddedGameAppId(context, folder.path) ?: return@mapNotNull null
Game(appId.toString(), sidecar.title)
}
fun ensure(context: Context): String? {
val games = installed(context)
if (games.isEmpty()) return null
val marks = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val wanted = wanted(runCatching { GpuInfo.detect().family }.getOrNull())
val lines = mutableListOf<String>()
for (game in games) {
val current = ComponentsManager.gameComponents(context, game.scope)
for (w in wanted) {
val key = "${game.scope}/${w.comp}"
val file = decide(current[w.comp], marks.getString(key, null), w.file) ?: continue
val label = ComponentsManager.LABEL[w.comp]
runCatching {
ComponentsManager.assignGameComponent(context, game.scope, w.comp, file, w.release, expected = current[w.comp]) {
marks.edit().putString(key, file).apply()
}
}
.onSuccess { result ->
lines += when (result) {
ComponentsManager.Assigned.SET -> "${game.title}: $label ${file.removeSuffix(".wcp")}"
ComponentsManager.Assigned.NOT_LISTED -> "${game.title}: $file is not listed; $label unchanged"
ComponentsManager.Assigned.CHANGED -> "${game.title}: $label was chosen during the download; kept"
}
}
.onFailure { e ->
Log.w(TAG, "${game.title}: $file", e)
lines += "${game.title}: $label unchanged (${e.message ?: e.javaClass.simpleName})"
}
}
}
return lines.joinToString("; ").ifEmpty { null }
}
}
@@ -14,9 +14,14 @@ internal object WebCookies {
}
}
fun scopes(url: String, paths: List<String>): List<String> {
val segments = runCatching { java.net.URI(url).path }.getOrNull().orEmpty().split('/').filter { it.isNotEmpty() }
return (paths + segments.indices.map { i -> "/" + segments.take(i + 1).joinToString("/") }).distinct()
}
fun expire(urls: List<String>, domain: String, paths: List<String>, done: (Int) -> Unit) {
val cookies = CookieManager.getInstance()
val lines = urls.flatMap { url -> expired(cookies.getCookie(url), domain, paths, Uri.parse(url).host).map { url to it } }
val lines = urls.flatMap { url -> expired(cookies.getCookie(url), domain, scopes(url, paths), Uri.parse(url).host).map { url to it } }
if (lines.isEmpty()) {
done(0)
return
@@ -44,7 +44,7 @@ object EaBackend : StoreBackend {
signOuts.incrementAndGet()
StoresState.post { StoresState.shelves.remove(store) }
EaUpdates.available.clear()
runCatching { WebCookies.expire(EaLogin.SIGN_IN_URLS, ".ea.com", listOf("/")) {} }
EaLogin.forget {}
}
override fun syncLibrary(context: Context, force: Boolean) {
@@ -100,9 +100,7 @@ internal class EaLogin(private val pending: EaAuth.Pending, override val userAge
override fun isRedirect(url: String): Boolean = url.startsWith("qrc:", ignoreCase = true)
override fun forgetSignIn(done: () -> Unit) {
runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() }
}
override fun forgetSignIn(done: () -> Unit) = forget(done)
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
val code = EaAuth.redirectValue(url, "code") ?: return activity.getString(R.string.stores_login_error_verification)
@@ -116,7 +114,11 @@ internal class EaLogin(private val pending: EaAuth.Pending, override val userAge
}
companion object {
val SIGN_IN_URLS = listOf("https://accounts.ea.com", "https://signin.ea.com", "https://www.ea.com")
val SIGN_IN_URLS = listOf(EaAuth.AUTH_URL, "https://signin.ea.com/p/juno/login", "https://www.ea.com")
fun forget(done: () -> Unit) {
runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() }
}
}
}
@@ -8,6 +8,9 @@ import org.json.JSONObject
import java.time.Instant
internal object XboxCatalog {
/** Package identity prefix of Microsoft's original Xbox releases for PC. */
internal const val BACK_COMPAT_IDENTITY = "Xbox360BackwardCompatibil"
private val productId = Regex("[A-Z0-9]{12}")
private val plans = setOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD")
private val pcPlans = mapOf(
@@ -148,6 +151,13 @@ internal object XboxCatalog {
.flatMap { objects(it.optJSONArray("Packages")) }
val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
val installable = pc.any { installableFormat(it.optString("PackageFormat")) }
// An original Xbox game: its PC package is only Microsoft's emulator and an
// index; the game data comes from the console package, so that is its size.
val backCompat = pc.any { it.optString("PackageFamilyName").startsWith(BACK_COMPAT_IDENTITY, ignoreCase = true) }
val console = packages.filter { pkg ->
pkg.optString("PackageFormat").equals("XVC", true) ||
objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Xbox" }
}
// The installer needs the format, not just the fact that one exists: a
// legacy container takes a different subcommand from a streamed package.
val format = pc.firstOrNull { installableFormat(it.optString("PackageFormat")) }?.optString("PackageFormat").orEmpty()
@@ -172,7 +182,8 @@ internal object XboxCatalog {
storeUrl = "https://www.xbox.com/games/store/$id",
publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"),
description = localized.optString("ProductDescription"),
sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L,
sizeBytes = if (!installable) 0L else (if (backCompat) console.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } else null)
?.takeIf { it > 0 } ?: pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L,
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable),
"cloud" to flag(streams), "format" to format),
)
@@ -106,7 +106,7 @@ private fun PanelContent(
onChange(settings.copy(frameGen = it))
}
Text("Native engine (experimental): Google's WebRTC and DroidDeck's own compositor, so DroidDeck frame generation " +
"(DDFG) or LSFG can add frames. LSFG uses the Lossless.dll DroidDeck already uses for games. Screen effects " +
"(DDFG) or LSFG can add frames. LSFG requires Lossless Scaling installed through Steam. Screen effects " +
"apply to the web engine.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 8.dp, bottom = 6.dp))
}
@@ -80,6 +80,10 @@ internal object XboxManifest {
dependencies.singleOrNull().orEmpty(), ids, entries, entry.singleOrNull().orEmpty(), behavior.singleOrNull().orEmpty())
}
/** Microsoft's original Xbox releases for PC, which run its emulator. */
fun backCompat(folder: File): Boolean =
runCatching { read(folder).name.startsWith(XboxCatalog.BACK_COMPAT_IDENTITY, ignoreCase = true) }.getOrDefault(false)
/**
* A full trust package starts its executable directly. Anything else is activated
* through the Windows app model, which this runtime has no host for, so starting
@@ -623,11 +623,11 @@ class XboxNativePlayerActivity : ComponentActivity() {
XboxMenuEntry((if (current.frameGen == mode) "✓ " else "") + fgName(mode), when (mode) {
XboxNativeVideo.FG_DDFG -> "DroidDeck's own frame generation (DDFG); doubles the shown frame rate"
XboxNativeVideo.FG_LSFG, XboxNativeVideo.FG_LSFG3, XboxNativeVideo.FG_LSFG4 ->
"Lossless Scaling frame generation (the Lossless.dll DroidDeck uses for games); the frame-rate target caps the output"
"Lossless Scaling frame generation from the Steam installation; the frame-rate target caps the output"
else -> "Show the stream's own frames only"
}, choices[i]) { current = current.copy(frameGen = mode); setFrameGen(mode) }
}
if (!lsfg) androidx.compose.material3.Text("LSFG appears here once DroidDeck has the Lossless.dll (frame generation settings).",
if (!lsfg) androidx.compose.material3.Text("LSFG appears here once Lossless Scaling is installed through Steam.",
style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = cs.onSurfaceVariant,
modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
if (current.zeroCopy) androidx.compose.material3.Text(
@@ -78,7 +78,7 @@ internal fun AgentEntry(
is Entry.Said -> {
val reply = remember(entry.text) { choices(entry.text) }
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (reply.text.isNotBlank()) SelectionContainer { AgentMarkdown(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
if (reply.text.isNotBlank()) SelectionContainer { AgentReply(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
if (reply.options.isNotEmpty()) AgentChoices(reply.options, answerable, onSent)
}
}
@@ -377,10 +377,11 @@ private fun CodeBox(label: String, text: String, color: Color) {
internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) {
val context = LocalContext.current
val pal = LocalPalette.current
var viewing by remember(path) { mutableStateOf(false) }
Box {
if (AgentAttachments.isImage(path)) AsyncImage(
model = AgentAttachments.host(context, path), contentDescription = path.substringAfterLast('/'), contentScale = ContentScale.Crop,
modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant),
modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant).clickable { viewing = true },
) else Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.heightIn(min = 40.dp).clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 10.dp, vertical = 8.dp),
@@ -396,4 +397,5 @@ internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) {
Icon(Icons.Outlined.Close, stringResource(R.string.agent_remove_attachment), tint = pal.onSurfaceVariant, modifier = Modifier.size(14.dp))
}
}
if (viewing) PictureViewer(AgentAttachments.host(context, path), path.substringAfterLast('/')) { viewing = false }
}
@@ -37,6 +37,106 @@ import org.commonmark.ext.gfm.tables.TableRow
import org.commonmark.node.AbstractVisitor
import org.commonmark.node.CustomNode
import org.commonmark.node.Node
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/** Part of an agent's reply: Markdown text, or an image the agent named on a line of its own. */
internal sealed interface ReplyPart {
data class Prose(val text: String) : ReplyPart
data class Picture(val alt: String, val path: String) : ReplyPart
}
private val PICTURE_LINE = Regex("""^\s*!\[([^\]]*)]\(\s*(?:<(?:file://)?(/[^>]*)>|(?:file://)?(/[^)<>]*?))\s*\)\s*$""")
private val FENCE = Regex("""^ {0,3}(`{3,}|~{3,})(.*)$""")
/** Splits [text] at lines that hold only an image of a local absolute path, outside code fences. */
internal fun replyParts(text: String): List<ReplyPart> {
val parts = mutableListOf<ReplyPart>()
val prose = StringBuilder()
fun flush() {
if (prose.isNotBlank()) parts += ReplyPart.Prose(prose.toString().trimEnd('\n'))
prose.clear()
}
var fence: String? = null
for (line in text.lines()) {
val marker = FENCE.matchEntire(line)
val picture = if (fence == null) PICTURE_LINE.matchEntire(line) else null
val open = fence
when {
picture != null -> {
flush()
val path = picture.groupValues[2].ifEmpty { picture.groupValues[3] }
parts += ReplyPart.Picture(picture.groupValues[1].trim(), path.trim())
continue
}
marker == null -> Unit
open == null -> fence = marker.groupValues[1]
marker.groupValues[1].let { it[0] == open[0] && it.length >= open.length } && marker.groupValues[2].isBlank() -> fence = null
}
prose.append(line).append('\n')
}
flush()
return parts
}
/**
* Where the app reads a file the agent named by its guest path: the app's own folders and shared
* storage are bound at the same paths in the guest, everything else lives in the rootfs.
*/
internal fun agentHostFile(context: Context, guestPath: String): File {
val app = context.applicationContext
val same = listOfNotNull(app.filesDir.path, app.cacheDir.path, LinuxRuntime.sharedStorage(app)?.path)
return if (same.any { guestPath == it || guestPath.startsWith("$it/") }) File(guestPath)
else File(LinuxRuntime.rootDir(app), guestPath.removePrefix("/"))
}
/** An agent's reply, with the images it names shown in place. */
@Composable
internal fun AgentReply(text: String, modifier: Modifier) {
val parts = remember(text) { replyParts(text) }
if (parts.size == 1 && parts[0] is ReplyPart.Prose) {
AgentMarkdown(text, modifier)
return
}
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
parts.forEach { part ->
when (part) {
is ReplyPart.Prose -> AgentMarkdown(part.text, Modifier)
is ReplyPart.Picture -> AgentPicture(part)
}
}
}
}
@Composable
private fun AgentPicture(picture: ReplyPart.Picture) {
val context = LocalContext.current
val file = remember(picture.path) { agentHostFile(context, picture.path) }
var viewing by remember(picture.path) { mutableStateOf(false) }
if (!file.isFile) {
Text(stringResource(R.string.agent_image_missing, picture.alt.ifBlank { picture.path }), color = MaterialTheme.colorScheme.onSurfaceVariant)
return
}
AsyncImage(
model = file, contentDescription = picture.alt.ifBlank { file.name }, contentScale = ContentScale.Fit,
modifier = Modifier.widthIn(max = 560.dp).heightIn(max = 420.dp).clip(Shape12).clickable { viewing = true },
)
if (viewing) PictureViewer(file, picture.alt.ifBlank { file.name }) { viewing = false }
}
@Composable
internal fun AgentMarkdown(text: String, modifier: Modifier) {
@@ -5,7 +5,9 @@ import android.content.ContextWrapper
import android.os.Build
import android.view.KeyEvent
import android.view.WindowManager
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.expandVertically
@@ -50,12 +52,12 @@ import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.outlined.Extension
import androidx.compose.material.icons.outlined.PhotoCamera
import androidx.compose.material.icons.outlined.MicOff
import androidx.compose.material.icons.outlined.Mic
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowDownward
import androidx.compose.material.icons.outlined.AttachFile
import androidx.compose.material.icons.outlined.Keyboard
import androidx.compose.material.icons.outlined.Terminal
import androidx.compose.material.icons.outlined.Build
import androidx.compose.material.icons.outlined.Close
@@ -79,6 +81,7 @@ import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -108,6 +111,7 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.testTag
@@ -301,7 +305,7 @@ private fun AgentPageContent(
readingBack = false
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
}
val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
val hidden = !composer.focused && !composer.tray && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
AgentHost.approvals.isEmpty()
var listHeight by remember { mutableIntStateOf(0) }
Box(
@@ -319,6 +323,7 @@ private fun AgentPageContent(
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
composer.tray = false
// Forced: the unforced path walks the focus chain and throws ("ActiveParent with no focused child") when a tap lands while focus is moving.
if (composer.focused) focusManager.clearFocus(force = true)
}
@@ -344,6 +349,12 @@ private fun AgentPageContent(
@Stable
private class ComposerState {
var focused by mutableStateOf(false)
/** The photo tray stands in for the keyboard, at the height the keyboard last had. */
var tray by mutableStateOf(false)
var keyboardHeight by mutableStateOf(0.dp)
/** Tray photos copied, or being copied, for this conversation, so reopening the tray keeps their marks and copies nothing twice. */
val photoCopies = mutableStateMapOf<android.net.Uri, String>()
val photosCopying = mutableStateMapOf<android.net.Uri, Any>()
var focusRequests by mutableIntStateOf(0)
private set
private var consumedFocusRequests by mutableIntStateOf(0)
@@ -390,7 +401,7 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon
.clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) }
val parts = if (compact) listOfNotNull(mode ?: model)
val parts = if (compact) listOf(model)
else listOfNotNull(
AgentHost.harness.name, model, AgentHost.effort, mode,
stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans },
@@ -532,7 +543,7 @@ private fun AgentLive() {
val pal = LocalPalette.current
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (AgentHost.liveThinking.isNotBlank()) AgentThought(AgentHost.liveThinking, live = true)
if (AgentHost.live.isNotBlank()) AgentMarkdown(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp))
if (AgentHost.live.isNotBlank()) AgentReply(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp))
val running = AgentHost.running()
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(4.dp)) {
CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp, color = pal.primary)
@@ -748,6 +759,8 @@ private fun AgentComposer(
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
AgentHost.send(context, text, AgentAttachments.pending.toList())
AgentAttachments.pending.clear()
composer.photosCopying.clear()
composer.tray = false
onSent()
}
}
@@ -813,7 +826,34 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
var focused by remember { mutableStateOf(false) }
val field = remember { FocusRequester() }
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
val attach = LocalActivityResultRegistryOwner.current != null
val picks = LocalActivityResultRegistryOwner.current != null
val density = LocalDensity.current
val imeHeight = WindowInsets.ime.getBottom(density)
LaunchedEffect(imeHeight) {
val height = with(density) { imeHeight.toDp() }
if (height > composer.keyboardHeight) composer.keyboardHeight = height
}
LaunchedEffect(hideAttach) { if (hideAttach) composer.tray = false }
LaunchedEffect(AgentHost.chat) {
composer.photoCopies.clear()
composer.photosCopying.clear()
}
// BackHandler throws where the host provides no back dispatcher: the front end and the floating pet.
if (LocalOnBackPressedDispatcherOwner.current != null) BackHandler(composer.tray) { composer.tray = false }
val focusManager = LocalFocusManager.current
val files = if (picks) rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) {
AgentAttachments.picking = false
attachUris(context, it)
} else null
val toggleTray = {
if (composer.tray) {
composer.tray = false
composer.open()
} else {
focusManager.clearFocus(force = true)
composer.tray = true
}
}
BoxWithConstraints(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
@@ -841,6 +881,7 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
focused = it.isFocused
composer.focused = it.isFocused
if (it.isFocused) composer.tray = false
if (it.isFocused) composer.consumeFocusRequest()
}.testTag("agent-input"),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
@@ -866,19 +907,22 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
if (stacked) Column {
text(Modifier.fillMaxWidth())
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() }
actions()
}
} else Row(verticalAlignment = Alignment.Bottom) {
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
text(Modifier.weight(1f))
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
actions()
}
}
AnimatedVisibility(composer.tray, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
val most = LocalConfiguration.current.screenHeightDp.dp * 0.45f
val height = (if (composer.keyboardHeight > 0.dp) composer.keyboardHeight else 280.dp).coerceAtLeast(160.dp).coerceAtMost(most)
AgentPhotoTray(height, composer.photoCopies, composer.photosCopying, files?.let { { AgentAttachments.pick { it.launch(arrayOf("*/*")) } } })
}
}
/**
@@ -974,51 +1018,15 @@ private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit, onSend: () -> Un
}
}
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
/** Opens the photo tray in place of the keyboard; while it is open, brings the keyboard back. */
@Composable
private fun GameFrameButton() {
val context = LocalContext.current
private fun AttachButton(trayOpen: Boolean, onClick: () -> Unit) {
val pal = LocalPalette.current
RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") {
val grab = AgentAttachments.gameFrame ?: return@RoundButton
val chat = AgentHost.chat
grab frame@{ frame ->
if (frame == null) {
android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
return@frame
}
Thread({
val path = AgentAttachments.saveFrame(context, chat, frame)
frame.recycle()
android.os.Handler(android.os.Looper.getMainLooper()).post {
when {
path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
else -> AgentAttachments.discard(context, listOf(path))
}
}
}, "agent-game-frame").start()
}
}
}
@Composable
private fun AttachButton() {
val context = LocalContext.current
val pal = LocalPalette.current
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
if (uris.isEmpty()) return@rememberLauncherForActivityResult
val chat = AgentHost.chat
Thread({
val paths = AgentAttachments.copy(context, chat, uris)
android.os.Handler(android.os.Looper.getMainLooper()).post {
if (AgentHost.chat == chat) AgentAttachments.pending.addAll(paths) else AgentAttachments.discard(context, paths)
}
}, "agent-attach").start()
}
RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") {
runCatching { picker.launch(arrayOf("*/*")) }
}
RoundButton(
if (trayOpen) Icons.Outlined.Keyboard else Icons.Outlined.AttachFile,
stringResource(if (trayOpen) R.string.agent_keyboard else R.string.agent_attach),
if (trayOpen) pal.primary else pal.surfaceVariant, if (trayOpen) pal.onPrimary else pal.onBackground, "agent-attach", onClick = onClick,
)
}
@Composable
@@ -21,6 +21,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
@@ -495,7 +496,13 @@ internal class PetWindows(private val context: Context) {
* under it. Its contents are built while it is closed, so opening only animates.
*/
@Composable
internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onClosed: () -> Unit) {
internal fun PetChat(
open: Boolean, motion: PetMotion, onClose: () -> Unit,
page: @Composable ColumnScope.(AgentMenuSlot) -> Unit = { slot ->
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = slot)
},
onClosed: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val density = androidx.compose.ui.platform.LocalDensity.current
@@ -552,14 +559,16 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl
alpha = fade.value
}
.clip(Shape16).background(colors.background).border(1.dp, pal.line, Shape16)
.clickable(remember { MutableInteractionSource() }, null, enabled = open) {}
// Never disabled: a disabled clickable leaves the focus tree, and the one it puts back on reopening
// sits unfocused above the still-focused editor, where key events then find no focus target.
.clickable(remember { MutableInteractionSource() }, null) {}
.padding(start = 12.dp, end = 12.dp, top = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
Box(Modifier.weight(1f)) { menuSlot.content?.invoke() }
HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose)
}
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = menuSlot)
page(menuSlot)
}
}
}
@@ -0,0 +1,280 @@
package com.droiddeck.launcher.ui
import android.Manifest
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.widget.Toast
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Check
import androidx.compose.material.icons.outlined.FolderOpen
import androidx.compose.material.icons.outlined.PhotoCamera
import androidx.compose.material.icons.outlined.PhotoLibrary
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.res.stringResource
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 androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentHost
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/** The device's photos, newest first, as MediaStore lets the app see them. */
internal object AgentPhotos {
enum class Access { NONE, SELECTED, ALL }
/** Android stops showing the request after repeated denials and answers it at once, so a denied request sends later ones to Settings. */
var refused = false
fun permissions(sdk: Int = Build.VERSION.SDK_INT): Array<String> = when {
sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)
sdk >= Build.VERSION_CODES.TIRAMISU -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
}
fun access(context: Context): Access {
fun granted(permission: String) = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
val all = permissions().first()
return when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager() -> Access.ALL
granted(all) -> Access.ALL
Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && granted(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) -> Access.SELECTED
else -> Access.NONE
}
}
class Photo(val uri: Uri, val name: String)
fun recent(context: Context, limit: Int = 300): List<Photo> = runCatching {
val images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
context.contentResolver.query(
images, arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME), null, null, "${MediaStore.Images.Media.DATE_ADDED} DESC",
)?.use { c ->
buildList {
while (size < limit && c.moveToNext()) add(Photo(ContentUris.withAppendedId(images, c.getLong(0)), c.getString(1).orEmpty()))
}
}.orEmpty()
}.getOrDefault(emptyList())
}
/**
* Copies [uris] into the conversation's attachments off the main thread, then hands [onCopied] what was attached: nothing if the
* conversation changed meanwhile or [current] says the copy was superseded.
*/
internal fun attachUris(context: Context, uris: List<Uri>, current: () -> Boolean = { true }, onCopied: (List<Pair<Uri, String>>) -> Unit = {}) {
if (uris.isEmpty()) return
val chat = AgentHost.chat
Thread({
val copied = uris.mapNotNull { uri -> AgentAttachments.copy(context, chat, listOf(uri)).firstOrNull()?.let { uri to it } }
android.os.Handler(android.os.Looper.getMainLooper()).post {
val paths = copied.map { it.second }
if (AgentHost.chat == chat && current()) {
AgentAttachments.pending.addAll(paths)
onCopied(copied)
} else {
AgentAttachments.discard(context, paths)
onCopied(emptyList())
}
}
}, "agent-attach").start()
}
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
private fun attachGameFrame(context: Context) {
val grab = AgentAttachments.gameFrame ?: return
val chat = AgentHost.chat
grab frame@{ frame ->
if (frame == null) {
Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
return@frame
}
Thread({
val path = AgentAttachments.saveFrame(context, chat, frame)
frame.recycle()
android.os.Handler(android.os.Looper.getMainLooper()).post {
when {
path == null -> Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
else -> AgentAttachments.discard(context, listOf(path))
}
}
}, "agent-game-frame").start()
}
}
/** Shown in place of the keyboard: recent photos to tap onto the message, and the system picker for anything else. */
@Composable
internal fun AgentPhotoTray(height: Dp, copies: SnapshotStateMap<Uri, String>, copying: SnapshotStateMap<Uri, Any>, onFiles: (() -> Unit)?) {
val context = LocalContext.current
val pal = LocalPalette.current
var access by remember { mutableStateOf(AgentPhotos.access(context)) }
var photos by remember { mutableStateOf<List<AgentPhotos.Photo>?>(null) }
var reloads by remember { mutableStateOf(0) }
// A window no activity owns (the floating pet's chat) cannot ask for a permission, so it sends the user to the app's settings.
val launcher = if (LocalActivityResultRegistryOwner.current != null) {
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
AgentAttachments.picking = false
access = AgentPhotos.access(context)
if (access == AgentPhotos.Access.NONE) AgentPhotos.refused = true
reloads++
}
} else null
val request = {
if (launcher != null && !AgentPhotos.refused) {
AgentAttachments.pick { launcher.launch(AgentPhotos.permissions()) }
} else {
val details = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.packageName)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
runCatching { context.startActivity(details) }
}
Unit
}
// Access can change in Settings, and new pictures arrive, while the app is in the background.
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
access = AgentPhotos.access(context)
reloads++
}
}
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
LaunchedEffect(access, reloads) {
photos = if (access == AgentPhotos.Access.NONE) emptyList() else withContext(Dispatchers.IO) { AgentPhotos.recent(context) }
}
LazyVerticalGrid(
GridCells.Adaptive(96.dp),
Modifier.fillMaxWidth().height(height).padding(top = 8.dp).testTag("agent-photo-tray"),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
if (AgentAttachments.gameFrame != null) item {
TrayTile(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), "agent-game-frame") { attachGameFrame(context) }
}
if (onFiles != null) item { TrayTile(Icons.Outlined.FolderOpen, stringResource(R.string.agent_attach_files), "agent-attach-files", onFiles) }
if (access != AgentPhotos.Access.ALL) item {
TrayTile(
Icons.Outlined.PhotoLibrary,
stringResource(if (access == AgentPhotos.Access.NONE) R.string.agent_photos_allow else R.string.agent_photos_more),
"agent-photos-allow",
onClick = request,
)
}
val list = photos
if (list != null && list.isEmpty() && access != AgentPhotos.Access.NONE) item(span = { GridItemSpan(maxLineSpan) }) {
Text(
stringResource(R.string.agent_photos_empty), fontSize = 13.sp, color = pal.onSurfaceVariant, textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth().padding(16.dp),
)
}
items(list.orEmpty(), key = { it.uri.toString() }) { photo ->
val uri = photo.uri
val path = copies[uri]
val selected = path != null && path in AgentAttachments.pending
Box(
Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant)
.then(if (selected) Modifier.border(3.dp, pal.primary, Shape12) else Modifier)
.clickable {
when {
selected -> AgentAttachments.pending.remove(path)
path != null && AgentAttachments.host(context, path).exists() -> AgentAttachments.pending.add(path)
uri in copying -> Unit
else -> {
// Leaving the conversation clears the markers, so a copy started before that is no longer current even back in it.
val copy = Any()
copying[uri] = copy
attachUris(context, listOf(uri), current = { copying[uri] === copy }) { copied ->
copied.forEach { (u, p) -> copies[u] = p }
if (copying[uri] === copy) copying.remove(uri)
}
}
}
}.semantics {
contentDescription = photo.name
this.selected = selected
}.testTag("agent-photo"),
) {
AsyncImage(
model = ImageRequest.Builder(context).data(uri).size(320).build(), contentDescription = null,
contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(),
)
if (selected) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.align(Alignment.TopEnd).padding(6.dp).size(22.dp).clip(CircleShape).background(pal.primary),
) {
Icon(Icons.Outlined.Check, null, tint = pal.onPrimary, modifier = Modifier.size(16.dp))
}
}
}
}
}
@Composable
private fun TrayTile(icon: ImageVector, label: String, tag: String, onClick: () -> Unit) {
val pal = LocalPalette.current
Column(
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center,
modifier = Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant).clickable(onClick = onClick).padding(8.dp).testTag(tag),
) {
Icon(icon, null, tint = pal.onBackground, modifier = Modifier.size(26.dp))
Text(
label, fontSize = 12.sp, color = pal.onBackground, textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 6.dp),
)
}
}
@@ -0,0 +1,113 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.calculatePan
import androidx.compose.foundation.gestures.calculateZoom
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChanged
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import kotlin.math.abs
private const val MAX_ZOOM = 5f
private const val TAP_ZOOM = 2.5f
/**
* A picture over the whole window: pinch or double-tap to zoom, drag to pan. A tap, a swipe down,
* Back or B close it. It is a popup, not a dialog, because the pet's chat lives in an overlay window,
* which has no activity token to show a dialog with.
*/
@Composable
internal fun PictureViewer(model: Any, description: String?, onDismiss: () -> Unit) {
Popup(
alignment = Alignment.Center, onDismissRequest = onDismiss,
properties = PopupProperties(focusable = true, dismissOnBackPress = true, dismissOnClickOutside = false),
) {
var size by remember { mutableStateOf(IntSize.Zero) }
var scale by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
fun clamp(o: Offset, s: Float): Offset {
val x = size.width * (s - 1f) / 2f
val y = size.height * (s - 1f) / 2f
return Offset(o.x.coerceIn(-x, x), o.y.coerceIn(-y, y))
}
val fade = if (scale == 1f && size.height > 0) (1f - abs(offset.y) / size.height * 2f).coerceIn(0.3f, 1f) else 1f
Box(
Modifier.fillMaxSize().onSizeChanged { size = it }.background(Color.Black.copy(alpha = 0.94f * fade))
.pointerInput(Unit) {
detectTapGestures(
onDoubleTap = { at ->
if (scale > 1f) { scale = 1f; offset = Offset.Zero } else {
scale = TAP_ZOOM
offset = clamp((Offset(size.width / 2f, size.height / 2f) - at) * (TAP_ZOOM - 1f), TAP_ZOOM)
}
},
onTap = { if (scale == 1f) onDismiss() },
)
}
.pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false)
do {
val event = awaitPointerEvent()
val zoom = event.calculateZoom()
val pan = event.calculatePan()
if (zoom != 1f || pan != Offset.Zero) {
val next = (scale * zoom).coerceIn(1f, MAX_ZOOM)
offset = if (next > 1f) clamp(offset * (next / scale) + pan, next) else Offset(0f, offset.y + pan.y)
scale = next
event.changes.forEach { if (it.positionChanged()) it.consume() }
}
} while (event.changes.any { it.pressed })
if (scale == 1f) {
if (abs(offset.y) > size.height / 6f) onDismiss() else offset = Offset.Zero
}
}
},
) {
AsyncImage(
model = model, contentDescription = description, contentScale = ContentScale.Fit,
modifier = Modifier.fillMaxSize().graphicsLayer {
scaleX = scale; scaleY = scale; translationX = offset.x; translationY = offset.y
},
)
IconButton(
onClick = onDismiss,
modifier = Modifier.align(Alignment.TopEnd).padding(12.dp).size(44.dp).clip(CircleShape).background(Color.Black.copy(alpha = 0.5f)),
) {
Icon(Icons.Outlined.Close, stringResource(R.string.common_close), tint = Color.White)
}
}
}
}
@@ -338,6 +338,24 @@ internal fun sessionBarModel(
internal fun deckPanelTabs(context: Context, selected: DeckPanel, onSelect: (DeckPanel) -> Unit) =
BarTabs(DeckPanel.entries.map { context.getString(it.label) }, selected.ordinal) { onSelect(DeckPanel.entries[it]) }
internal fun padKeysView(
context: Context, steam: Boolean, onMenu: () -> Unit, onSteam: () -> Unit, onQam: () -> Unit,
): ComposeView = ComposeView(context).apply {
setContent { DroidDeckTheme { PadKeys(steam, onMenu, onSteam, onQam) } }
}
@Composable
internal fun PadKeys(steam: Boolean, onMenu: () -> Unit, onSteam: () -> Unit, onQam: () -> Unit) {
Row(
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = if (steam) Arrangement.SpaceBetween else Arrangement.Center,
) {
if (steam) BarActions(null, false, onSteam, null)
BarActions(onMenu, false, null, null)
if (steam) BarActions(null, false, null, onQam)
}
}
internal fun bottomScreenBarView(context: Context, model: () -> BottomBarModel): ComposeView = ComposeView(context).apply {
setContent { DroidDeckTheme { BottomScreenBar(model()) } }
}
@@ -199,7 +199,6 @@ internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) {
secondScreenDisplays = secondScreens,
selectedSecondScreenDisplay = secondScreens.firstOrNull()?.id ?: -1,
onSecondScreenDisplay = {},
onImportLossless = {},
onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = if (steam) ({}) else null,
onQam = if (steam) ({}) else null,
@@ -5,13 +5,30 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.withFrameNanos
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
@@ -24,28 +41,29 @@ internal fun FrameGenMenu(
mode: FrameGen.Mode,
lossless: Lossless.State,
onPick: (FrameGen.Mode) -> Unit,
onImportLossless: () -> Unit,
gameProfileId: String? = null,
hasGameOverride: Boolean = false,
onResetGame: () -> Unit = {},
focusModifier: Modifier = Modifier,
legacyButtons: Boolean = false,
listLayout: Boolean = false,
sessionHost: MenuHost? = null,
) {
val need = when {
lossless.ready -> null
lossless.owned -> stringResource(R.string.lsfg_needs_install)
else -> stringResource(R.string.lsfg_needs_steam)
}
val sessionEngineAnchor = remember { FocusRequester() }
val need = stringResource(R.string.lsfg_needs_steam)
val selectedEngine = mode.engine.takeIf { it != FrameGen.ENGINE_OFF }
val offLabel = FrameGen.label(LocalContext.current, FrameGen.Mode.OFF)
val colors = MaterialTheme.colorScheme
val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG")
val context = LocalContext.current
var pacerEnabled by remember { mutableStateOf(FrameGen.pacerEnabled(context)) }
val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG", FrameGen.ENGINE_ZEROFG to "ZeroFG")
if (legacyButtons) {
val context = LocalContext.current
val options = buildList {
add(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier))
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_DDFG, it)) }
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, it)) }
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, it)) }
FrameGen.ADAPTIVE_TARGETS.forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it)) }
}
@@ -70,7 +88,7 @@ internal fun FrameGenMenu(
}
if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(
need.orEmpty(),
need,
color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 6.dp),
@@ -87,80 +105,111 @@ internal fun FrameGenMenu(
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
}
}
if (lossless.owned) {
val using = when (lossless.source) {
Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam)
Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import)
Lossless.Source.NONE -> null
}
OutlinedButton(
onClick = onImportLossless,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
.controllerConfirm(onClick = onImportLossless),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: ""))
}
}
}
return
}
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
OutlinedButton(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
modifier = Modifier.fillMaxWidth().controllerConfirm(
if (sessionHost != null) {
SessionFrameGenEngine(
sessionHost, mode, listOf(FrameGen.ENGINE_OFF to offLabel) + engines,
lossless.ready, need, focusModifier, sessionEngineAnchor, onPick,
)
} else {
OutlinedButton(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selectedEngine == null) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selectedEngine == null) colors.primary else colors.onSurface,
),
) { Text(offLabel) }
modifier = Modifier.fillMaxWidth().controllerConfirm(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selectedEngine == null) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selectedEngine == null) colors.primary else colors.onSurface,
),
) { Text(offLabel) }
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val focusIndex = engines.indexOfFirst { (engine, _) ->
selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready
}
engines.forEachIndexed { index, (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
if (listLayout) {
Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
engines.forEach { (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
}
} else {
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val focusIndex = engines.indexOfFirst { (engine, _) ->
selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready
}
engines.forEachIndexed { index, (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = (if (index == focusIndex) focusModifier else Modifier)
.weight(1f).controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = (if (index == focusIndex) focusModifier else Modifier)
.weight(1f).controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
}
if (selectedEngine != null) {
val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready
val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready
if (listLayout) {
Column(
Modifier.fillMaxWidth().padding(top = 8.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
(2..4).forEach { multiplier ->
val selected = mode.multiplier == multiplier && mode.target == 0
val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) }
OutlinedButton(
onClick = pickMultiplier,
enabled = multiplierEnabled,
modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier)
.frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
contentColor = if (selected) colors.secondary else colors.onSurface,
),
) { Text("${multiplier}×") }
}
}
} else {
Row(
Modifier.fillMaxWidth().padding(top = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
(2..4).forEach { multiplier ->
val selected = mode.multiplier == multiplier && mode.target == 0
val pickMultiplier = {
onPick(mode.copy(multiplier = multiplier, target = 0))
}
val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) }
OutlinedButton(
onClick = pickMultiplier,
enabled = multiplierEnabled,
modifier = Modifier.weight(1f).controllerConfirm(
enabled = multiplierEnabled,
onClick = pickMultiplier,
),
modifier = Modifier.weight(1f).controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier)
.frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
@@ -171,6 +220,25 @@ internal fun FrameGenMenu(
}
}
val togglePacer = {
val enabled = !pacerEnabled
FrameGen.setPacer(context, enabled)
pacerEnabled = enabled
}
OutlinedButton(
onClick = togglePacer,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
.controllerConfirm(onClick = togglePacer).frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (pacerEnabled) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (pacerEnabled) colors.primary else colors.onSurface,
),
) {
Text("ZeroPacer" + if (pacerEnabled) " ✓" else "")
}
if (selectedEngine == FrameGen.ENGINE_LSFG) {
Row(
Modifier.fillMaxWidth().padding(top = 8.dp),
@@ -186,7 +254,7 @@ internal fun FrameGenMenu(
modifier = Modifier.weight(1f).controllerConfirm(
enabled = lossless.ready,
onClick = pickTarget,
),
).frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
@@ -199,37 +267,104 @@ internal fun FrameGenMenu(
}
}
if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(need.orEmpty(), color = colors.onSurfaceVariant,
if (sessionHost == null && selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(need, color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 6.dp))
}
if (gameProfileId != null) {
val resetGame = onResetGame
if (gameProfileId != null && (sessionHost == null || hasGameOverride)) {
val input = LocalInputModeManager.current
val resetGame = {
if (sessionHost != null && input.inputMode == InputMode.Keyboard) {
sessionEngineAnchor.requestFocus()
}
onResetGame()
}
OutlinedButton(
onClick = resetGame,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
.controllerConfirm(onClick = resetGame),
.testTag("framegen-use-global").controllerConfirm(onClick = resetGame)
.frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
Text(if (sessionHost != null) stringResource(R.string.frame_gen_use_global)
else stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
}
}
}
}
if (lossless.owned) {
val using = when (lossless.source) {
Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam)
Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import)
Lossless.Source.NONE -> null
@Composable
private fun Modifier.frameGenFocus(sessionHost: MenuHost?): Modifier =
if (sessionHost != null) focusGlide(RoundedCornerShape(percent = 50)) else this
@Composable
private fun SessionFrameGenEngine(
host: MenuHost,
mode: FrameGen.Mode,
options: List<Pair<String, String>>,
losslessReady: Boolean,
losslessNote: String,
focusModifier: Modifier,
anchor: FocusRequester,
onPick: (FrameGen.Mode) -> Unit,
) {
val label = stringResource(R.string.frame_gen_engine)
val selectedLabel = options.firstOrNull { (engine, _) -> engine == mode.engine }?.second
?: options.first().second
val key = "frame-generation-engine"
val open = host.open == key
val input = LocalInputModeManager.current
var anchorFocused by remember { mutableStateOf(false) }
val selectedOption = remember { FocusRequester() }
var keyboardOpened by remember { mutableStateOf(false) }
val initial = options.firstOrNull { (engine, _) -> engine == mode.engine }?.first
?: FrameGen.ENGINE_OFF
val close = { if (host.open == key) host.open = null }
// Keep the options in the drawer's focus tree. A separate popup window can
// steal focus from the controller before Compose can focus the selected row.
LaunchedEffect(open) {
if (!keyboardOpened || (!open && host.open != null)) return@LaunchedEffect
val target = if (open) selectedOption else anchor
withFrameNanos { }
target.requestFocus()
if (!open) keyboardOpened = false
}
val blockedSelection = !losslessReady && mode.engine == FrameGen.ENGINE_LSFG
SettingsRow(label, losslessNote.takeIf { blockedSelection && !open }, highlighted = open) {
ValueChip(
selectedLabel, open,
modifier = focusModifier.focusRequester(anchor).onFocusChanged { anchorFocused = it.isFocused }
.heightIn(min = 48.dp).testTag("setting-$key")
.semantics { contentDescription = label; stateDescription = selectedLabel },
) {
if (open) close()
else {
keyboardOpened = anchorFocused || input.inputMode == InputMode.Keyboard
host.open = key
}
OutlinedButton(
onClick = onImportLossless,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
.controllerConfirm(onClick = onImportLossless),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: ""))
}
}
if (open) {
Column(Modifier.fillMaxWidth().padding(horizontal = 8.dp).controllerBack(close)) {
options.forEach { (engine, text) ->
val selected = engine == mode.engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || losslessReady
MenuItem(
label = text, checked = selected, enabled = enabled,
detail = losslessNote.takeIf { engine == FrameGen.ENGINE_LSFG && !losslessReady },
focusRequester = selectedOption.takeIf { engine == initial },
modifier = Modifier.heightIn(min = 48.dp).testTag("framegen-engine:$engine"),
) {
close()
if (!selected) {
onPick(if (engine == FrameGen.ENGINE_OFF) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)
else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
}
}
}
}
@@ -246,7 +246,6 @@ class FrontEndActions(
val onVkBridgeSafe: (Boolean) -> Unit = {},
val onBridgeProtonDxvk: (Boolean) -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
val onImportLossless: () -> Unit,
val onProtons: () -> Unit,
val onComponents: (focusContent: Boolean) -> Unit,
val onGameComponents: (Library.SteamGame) -> Unit = { onComponents(true) },
@@ -860,7 +860,7 @@ internal fun ReadinessCard(
@Composable
private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless, legacyButtons = true)
FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, legacyButtons = true)
}
@Composable
@@ -901,7 +901,6 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
gameFrameGenOverride = true
}
},
onImportLossless = a.onImportLossless,
legacyButtons = true,
gameProfileId = frameGenProfileKey,
hasGameOverride = gameFrameGenOverride,
@@ -308,7 +308,8 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo
Box(
contentAlignment = Alignment.Center,
modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (pill) 40.dp else if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(shape).background(fill).glideBorder(hot, shape, pal.signal, if (pill) Color.White.copy(alpha = 0.14f) else pal.line2)
.alpha(if (enabled) 1f else 0.5f)
// The label always gets a layer of its own: sharing one with the fill and outline, they did not draw under the agent's latest reply.
.graphicsLayer { alpha = if (enabled) 1f else 0.5f }
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = if (pill) 16.dp else if (compact) 10.dp else 16.dp, vertical = if (pill) 8.dp else if (compact) 7.dp else 11.dp),
@@ -396,7 +396,7 @@ private fun GameCapsule(scores: GameScores?, actions: @Composable () -> Unit) {
}
@Composable
private fun GameTabBar(
internal fun GameTabBar(
tabs: List<String>, selected: Int, onSelect: (Int) -> Unit,
modifier: Modifier = Modifier, focusRequesters: List<FocusRequester>? = null,
bumpers: Boolean = true, compact: Boolean = false,
@@ -3,6 +3,9 @@ package com.droiddeck.launcher.ui
import android.text.format.DateUtils
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -26,8 +29,11 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -41,7 +47,7 @@ import com.droiddeck.launcher.lab.LabOverlay
* [onRebuild] offers to build a kept one again for this install, when something can.
*/
@Composable
internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.Info) -> Unit)? = null) {
internal fun LabBuilds(sessionRunning: Boolean = false, header: (@Composable () -> Unit)? = null, onRebuild: ((LabOverlay.Info) -> Unit)? = null) {
val context = LocalContext.current
var version by remember { mutableIntStateOf(0) }
var busy by remember { mutableStateOf(false) }
@@ -54,6 +60,7 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.
val paused = active == null && current != null && LabOverlay.skipped == LabOverlay.SKIPPED_APP_IMAGE
val restartFailed = stringResource(R.string.lab_restart_failed)
val canRestart = !busy && !sessionRunning
var showKept by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf(false) }
/** Android may have given the APK an app image again, which a Lab build cannot load over. */
fun restart() {
@@ -73,8 +80,8 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {
Text(
Column(Modifier.fillMaxWidth().padding(top = if (header == null) 18.dp else 0.dp)) {
if (header != null) header() else Text(
stringResource(R.string.lab_builds).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp),
)
@@ -99,7 +106,29 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.
PrimaryButton(stringResource(R.string.lab_restart), compact = true, enabled = canRestart) { restart() }
}
}
for (build in saved) rows += {
val foldKept = (current != null || pending != null) && saved.isNotEmpty()
if (foldKept) rows += {
val src = remember { MutableInteractionSource() }
val toggle = { showKept = !showKept }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().paneItem("lab:kept")
.background(if (rememberHot(src)) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle)
.controllerConfirm(onClick = toggle)
.padding(horizontal = 14.dp, vertical = 12.dp),
) {
Text(
pluralStringResource(R.plurals.lab_kept_count, saved.size, saved.size), fontSize = 14.sp,
color = colors.onSurfaceVariant, modifier = Modifier.weight(1f),
)
Text(
stringResource(if (showKept) R.string.common_hide else R.string.common_show), fontSize = 13.5.sp,
fontWeight = FontWeight.SemiBold, color = pal.signal,
)
}
}
if (!foldKept || showKept) for (build in saved) rows += {
var armed by remember(build.dir) { mutableStateOf(false) }
val info = build.info
BuildRow(
@@ -17,6 +17,7 @@ import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
@@ -204,9 +205,9 @@ internal object LibraryDisplay {
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
var level by mutableIntStateOf(DEFAULT_LEVEL)
private set
var title by mutableStateOf(true)
var title by mutableStateOf(false)
private set
var size by mutableStateOf(true)
var size by mutableStateOf(false)
private set
fun load(context: android.content.Context) {
@@ -914,7 +915,7 @@ private fun sourceChipsShown(sources: List<String>, manage: Boolean): Boolean =
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit, manage: Boolean) {
internal fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit, manage: Boolean) {
val chips = sourceChipsShown(sources, manage)
if (!chips && !manage) return
val pal = LocalPalette.current
@@ -931,42 +932,54 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp),
) {
Box(Modifier.weight(1f).edgeFade(scroll).horizontalScroll(scroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (id in keys) {
val store = Store.byId(id)
val dot = sourceDot(id)
val label = when (id) {
LIBRARY_ALL -> stringResource(R.string.stores_tab_all)
Library.ADDED -> stringResource(R.string.library_custom_games)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> store?.shortLabel ?: sourceLabel(id)
}
androidx.compose.runtime.key(id) {
val reveal = remember { BringIntoViewRequester() }
LaunchedEffect(source) { if (source == id) reveal.bringIntoView() }
StoreChip(
label = label, on = source == id, under = fillShown && highlighted == id, key = id, mark = dot ?: pal.signal,
modifier = Modifier.bringIntoViewRequester(reveal).testTag("library-source-$id")
.onGloballyPositioned { bounds[id] = it.boundsInParent() },
lead = {
if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape))
else Icon(Icons.Filled.GridView, null, modifier = Modifier.size(14.dp))
},
onFocused = { focused = it },
paneKey = "libchip:$id",
) { onSource(id) }
BoxWithConstraints(Modifier.weight(1f)) {
if (sourceTabsAsMenu(maxWidth, keys.size)) {
TabMenu(
keys.map { librarySourceChipLabel(it) }, keys.indexOf(source), { onSource(keys[it]) },
chipModifier = Modifier.paneItem("libchip:$source"),
leading = { i, _ -> LibrarySourceMark(sourceDot(keys[i])) },
)
} else Box(Modifier.edgeFade(scroll).horizontalScroll(scroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (id in keys) {
val dot = sourceDot(id)
androidx.compose.runtime.key(id) {
val reveal = remember { BringIntoViewRequester() }
LaunchedEffect(source) { if (source == id) reveal.bringIntoView() }
StoreChip(
label = librarySourceChipLabel(id), on = source == id, under = fillShown && highlighted == id, key = id, mark = dot ?: pal.signal,
modifier = Modifier.bringIntoViewRequester(reveal).testTag("library-source-$id")
.onGloballyPositioned { bounds[id] = it.boundsInParent() },
lead = { LibrarySourceMark(dot) },
onFocused = { focused = it },
paneKey = "libchip:$id",
) { onSource(id) }
}
}
}
if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
if (manage) ManageStoresChip()
}
}
}
@Composable
private fun librarySourceChipLabel(id: String): String = when (id) {
LIBRARY_ALL -> stringResource(R.string.stores_tab_all)
Library.ADDED -> stringResource(R.string.library_custom_games)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> Store.byId(id)?.shortLabel ?: sourceLabel(id)
}
@Composable
private fun LibrarySourceMark(dot: Color?) {
if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape))
else Icon(Icons.Filled.GridView, null, modifier = Modifier.size(14.dp))
}
@Composable
private fun sourceTitle(src: String): String = when (src) {
LIBRARY_ALL -> stringResource(R.string.library_all_games)
@@ -711,6 +711,10 @@ internal fun SheetChips(
Modifier.fillMaxWidth().onFocusChanged { within = it.hasFocus },
contentAlignment = Alignment.CenterStart,
) {
if (tabsAsMenu(maxWidth, labels.size)) {
TabMenu(labels, selected, onPick, focus = chips)
return@BoxWithConstraints
}
val equal = !width.isSpecified && maxWidth / labels.size.coerceAtLeast(1) >= 96.dp
val least = if (width.isSpecified) maxOf(width, 64.dp) else 64.dp
val scroll = rememberScrollState()
@@ -62,6 +62,7 @@ class ModeSettings(
val hdrReason: String?,
val hdrDisplay: Boolean = true,
val zeroCopy: Boolean = true,
val producerAcquireFences: Boolean? = null,
val gpuDrivers: String? = null,
val upscaler: Int = 0,
val upscaleSharpness: Int = 75,
@@ -86,7 +87,8 @@ class ModeSettings(
val fexPreset: String? = null,
val forceSsbs: Boolean = false,
val syncBackend: String? = null,
val picturePosition: String? = null,
val picturePositionLandscape: String? = null,
val picturePositionPortrait: String? = null,
val integerScaling: Boolean? = null,
val stretch16x9: Boolean? = null,
val avoidNotch: Boolean? = null,
@@ -125,6 +127,7 @@ class ModeSettingsActions(
val onResolutionPortrait: (String) -> Unit = {},
val onHdr: (Boolean) -> Unit,
val onZeroCopy: (Boolean) -> Unit = {},
val onProducerAcquireFences: (Boolean) -> Unit = {},
val onGpuDrivers: () -> Unit = {},
val onUpscaler: (Int) -> Unit = {},
val onUpscaleSharpness: (Int) -> Unit = {},
@@ -150,7 +153,7 @@ class ModeSettingsActions(
val onFexPreset: (String) -> Unit = {},
val onForceSsbs: (Boolean) -> Unit = {},
val onSyncBackend: (String) -> Unit = {},
val onPicturePosition: (String) -> Unit = {},
val onPicturePosition: (Boolean, String) -> Unit = { _, _ -> },
val onIntegerScaling: (Boolean) -> Unit = {},
val onStretch16x9: (Boolean) -> Unit = {},
val onAvoidNotch: (Boolean) -> Unit = {},
@@ -260,15 +263,16 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
ResolutionRow(host, "resolution-portrait", stringResource(R.string.display_resolution_portrait), s.resolutionPortrait, portraitChoice,
com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE,
if (sessionDisplay.isLink(s.resolution)) portraitChoice else sessionDisplay.orientCustom(s.resolution, true),
s.panelSize, a.onResolutionPortrait, portrait = true)
s.picturePosition?.let { position ->
ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null,
listOf("top" to stringResource(R.string.display_position_top),
"bottom" to stringResource(R.string.display_position_bottom),
"left" to stringResource(R.string.display_position_left),
"right" to stringResource(R.string.display_position_right),
"center" to stringResource(R.string.display_position_center)),
position, onPick = a.onPicturePosition)
s.panelSize, a.onResolutionPortrait, portrait = true,
defaultChoice = if (s.mode == SessionService.MODE_STEAM) sessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION
else sessionDisplay.DEFAULT_RESOLUTION)
s.picturePositionLandscape?.let { position ->
PicturePositionRow(host, position, key = "picture-position-landscape",
labelRes = R.string.display_picture_position_landscape) { a.onPicturePosition(false, it) }
}
s.picturePositionPortrait?.let { position ->
PicturePositionRow(host, position, key = "picture-position-portrait",
labelRes = R.string.display_picture_position_portrait) { a.onPicturePosition(true, it) }
}
if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) ||
com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) {
@@ -284,6 +288,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.display_avoid_notch_hint), checked = enabled, onChange = a.onAvoidNotch)
}
ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy)
s.producerAcquireFences?.let { enabled ->
ToggleRow(host, "producer-acquire-fences", stringResource(R.string.producer_acquire_fences),
stringResource(R.string.producer_acquire_fences_summary), checked = enabled,
onChange = a.onProducerAcquireFences)
}
}
SettingsGroup(stringResource(R.string.display_image_scaling)) {
s.integerScaling?.let { enabled ->
@@ -735,3 +744,22 @@ internal fun CustomFollowScaleDialog(initial: Float?, onSave: (Float) -> Unit, o
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@Composable
internal fun PicturePositionRow(
host: MenuHost, position: String,
chipModifier: Modifier = Modifier,
key: String = "picture-position",
@androidx.annotation.StringRes labelRes: Int = R.string.display_picture_position,
onPick: (String) -> Unit,
) {
ChoiceRow(host, key, stringResource(labelRes), null,
listOf(
"center" to stringResource(R.string.display_position_center),
"top" to stringResource(R.string.display_position_top),
"bottom" to stringResource(R.string.display_position_bottom),
"left" to stringResource(R.string.display_position_left),
"right" to stringResource(R.string.display_position_right),
),
position, chipModifier = chipModifier, onPick = onPick)
}
@@ -16,12 +16,14 @@ fun ResolutionRow(
panel: Pair<Int, Int>, onPick: (String) -> Unit,
chipModifier: Modifier = Modifier,
portrait: Boolean = false,
defaultChoice: String = SessionDisplay.DEFAULT_RESOLUTION,
) {
val custom = "custom"
val linked = stored == link
val size = SessionDisplay.resolveChoice(panel, choice, portrait)
val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait)
val choices = SessionDisplay.resolutionOptions(panel)
val presets = SessionDisplay.resolutionOptions(panel)
val choices = if (defaultChoice == SessionDisplay.DEFAULT_RESOLUTION) presets else listOf(defaultChoice) + presets
val customFollow = !linked && SessionDisplay.isFollow(choice) && choice !in choices
val selected = if (linked) link else if (SessionDisplay.isFollow(choice)) choice
else if (size == screen) SessionDisplay.MATCH_SCREEN else choice
@@ -36,7 +38,7 @@ fun ResolutionRow(
else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen)
else if (SessionDisplay.isFollow(value)) stringResource(R.string.display_follow_screen_scaled,
SessionDisplay.formatScale(SessionDisplay.followScale(value) ?: 1f)) + " (${dimensions.first}×${dimensions.second})"
else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
else if (value == defaultChoice) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
else "${dimensions.first}×${dimensions.second}"
} + listOf(SessionDisplay.FOLLOW_CUSTOM to stringResource(R.string.display_follow_screen_scaled,
if (customFollow) SessionDisplay.formatScale(SessionDisplay.followScale(choice) ?: 1f) else "…"
@@ -22,6 +22,7 @@ import androidx.compose.material.icons.outlined.Tune
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.PadBridge
@@ -397,6 +398,7 @@ class SecondScreenPresentation(
val layout = panelLayout(mode)
val controls = InputSurfaceView(context, pad, layout?.elements.orEmpty(),
surfaceStyle = layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
controls.alpha = ControllerPrefs.onScreenOpacity(context) / 100f
controlsView = controls
root.addView(controls, weightParams())
attachKeyboard()
@@ -22,7 +22,12 @@ internal enum class SessionDrawerPage(val firstControl: String) {
}
internal object DrawerPages {
var order by mutableStateOf(SessionDrawerPage.entries.toList())
private val defaultOrder = SessionDrawerPage.entries.toMutableList().apply {
remove(SessionDrawerPage.VR)
add(indexOf(SessionDrawerPage.MORE) + 1, SessionDrawerPage.VR)
}.toList()
var order by mutableStateOf(defaultOrder)
private set
var hidden by mutableStateOf(emptySet<SessionDrawerPage>())
private set
@@ -39,6 +44,7 @@ internal object DrawerPages {
}
fun arrange(saved: List<String>): List<SessionDrawerPage> {
if (saved.isEmpty()) return defaultOrder
val all = SessionDrawerPage.entries
val out = saved.mapNotNull { name -> all.firstOrNull { it.name == name } }.distinct().toMutableList()
for (page in all.filterNot { it in out }) {
@@ -62,14 +68,14 @@ internal object DrawerPages {
}
fun reset(context: Context) {
order = SessionDrawerPage.entries.toList()
order = defaultOrder
hidden = emptySet()
if (DevPreview.drawer != null) return
SessionPrefs.setDrawerPageOrder(context, order.map { it.name })
SessionPrefs.setDrawerPageHidden(context, emptySet())
}
fun isDefault() = order == SessionDrawerPage.entries.toList() && hidden.isEmpty()
fun isDefault() = order == defaultOrder && hidden.isEmpty()
}
internal fun offeredDrawerPages(
@@ -16,11 +16,15 @@ import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import kotlin.math.roundToInt
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
@@ -73,6 +77,7 @@ import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
@@ -82,6 +87,7 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.systemGestureExclusion
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.rememberScrollState
@@ -89,6 +95,7 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@@ -109,6 +116,7 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.input.ControllerPrefs
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring
@@ -269,6 +277,8 @@ class DrawerActions(
val upscaleSharpness: Int = 75,
val integerScaling: Boolean = false,
val onIntegerScaling: (Boolean) -> Unit = {},
val picturePosition: String = "center",
val onPicturePosition: (String) -> Unit = {},
val gameZoomAvailable: Boolean = false,
val gameZoom: Float = 1.0f,
val onGameZoom: (Float) -> Unit = {},
@@ -316,7 +326,6 @@ class DrawerActions(
val hdr: Boolean = false,
val hdrAvailable: Boolean = false,
val onHdr: (Boolean) -> Unit = {},
val onImportLossless: () -> Unit,
val onKeyboard: () -> Unit,
val onHardwareKeyboard: () -> Unit,
val wowChatShown: Boolean = false,
@@ -332,6 +341,7 @@ class DrawerActions(
val onEditSteamTouch: (() -> Unit)? = null,
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val onControllerSize: (Int) -> Unit = {},
val onControllerOpacity: (Int) -> Unit = {},
val onRumble: (Boolean) -> Unit = {},
val onSuspendPolicy: (String) -> Unit,
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
@@ -391,6 +401,8 @@ class DrawerActions(
val quickButtons: Map<com.droiddeck.launcher.input.InputCommand, Boolean> = emptyMap(),
val onQuickButton: (com.droiddeck.launcher.input.InputCommand, Boolean) -> Unit = { _, _ -> },
val onUnfoldedControls: (Boolean) -> Unit = {},
val deckPanel: com.droiddeck.launcher.input.DeckPanel? = null,
val onDeckPanel: (com.droiddeck.launcher.input.DeckPanel) -> Unit = {},
val unfoldedControlsWithController: Boolean = false,
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
val onShareLogs: () -> Unit,
@@ -477,6 +489,13 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false }
LaunchedEffect(host.open) {
if (host.open == "frame-generation") repeat(24) {
androidx.compose.runtime.withFrameNanos { }
focus.request("frame-generation")
if (focus.focused == "frame-generation") return@LaunchedEffect
}
}
LaunchedEffect(a.selectedGameProfileId) {
if (host.open == "fex") host.open = null
}
@@ -533,8 +552,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
val short = maxHeight < 440.dp
// The handle keeps a strip on the left free, so a sheet dragged wide can always be dragged back.
val maxSheet = (maxWidth - DRAWER_EDGE_GAP).coerceAtLeast(0.dp)
// At full width the handle's strip sits on the screen's left edge, so the sheet can still be dragged back.
val maxSheet = (maxWidth - DRAWER_HANDLE_STRIP).coerceAtLeast(0.dp)
val minSheet = minOf(DRAWER_MIN_WIDTH, maxSheet)
val defaultSheet = minOf(420.dp, maxWidth * 0.92f)
val sheetWidth = if (docked) maxWidth else (savedWidth?.dp ?: defaultSheet).coerceIn(minSheet, maxSheet)
@@ -650,6 +669,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
val track: (String) -> Modifier = { key -> focus.track(page, key) }
val sections = remember(page) { DrawerSections(drawerContext, track) }
CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true, LocalDrawerSections provides sections) {
DrawerColumns(two = sheetWidth >= DRAWER_TWO_COLUMN_WIDTH && page.inColumns) {
when (page) {
SessionDrawerPage.CONTROLLER -> DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track)
SessionDrawerPage.HUD -> DrawerPerformancePage(host, a, track)
@@ -666,6 +686,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SessionDrawerPage.ACHIEVEMENTS -> a.achievementsGame?.let { DrawerAchievementsPage(it, a.achievementsTitle, track) }
SessionDrawerPage.AGENT -> Unit
}
}
} }
}
}
@@ -746,6 +767,9 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected:
c?.let {
SliderRow(stringResource(R.string.ctrl_size), null, it.size, 80..125, step = 5,
format = { v -> "$v%" }, modifier = track("controller-size"), onChange = a.onControllerSize)
SliderRow(stringResource(R.string.ctrl_opacity), null, it.onScreenOpacity, ControllerPrefs.onScreenOpacityRange, step = 5,
format = { v -> "$v%" }, modifier = track("controller-opacity").testTag("controller-opacity"),
onChange = a.onControllerOpacity)
}
a.adaptiveSticks?.let { adaptive ->
ToggleRow(host, "adaptive-sticks", stringResource(R.string.ctrl_adaptive), null, adaptive,
@@ -769,6 +793,11 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected:
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
stringResource(R.string.unfolded_controls_hint), a.unfoldedControls,
chipModifier = track("unfolded-controls"), onChange = a.onUnfoldedControls)
a.deckPanel?.let { panel ->
ChoiceRow(host, "deck-panel", stringResource(R.string.ctrl_layout), null,
com.droiddeck.launcher.input.DeckPanel.entries.map { it to stringResource(it.label) }, panel,
chipModifier = track("deck-panel"), onPick = a.onDeckPanel)
}
if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller",
stringResource(R.string.unfolded_controls_with_controller),
stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController,
@@ -897,33 +926,42 @@ private fun DrawerPerformancePage(host: MenuHost, a: DrawerActions, track: (Stri
@Composable
private fun DrawerFrameGenPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
private fun DrawerFrameGenSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val fgLabel = FrameGen.label(LocalContext.current, a.frameGen)
val scope = if (a.frameGenTargetGameId != null)
"${stringResource(R.string.frame_gen_scope_game)} · ${a.frameGenTargetGameName ?: "ID ${a.frameGenTargetGameId}"}"
else stringResource(R.string.frame_gen_scope_global)
SettingsGroup(stringResource(R.string.frame_gen_title), compact = true, key = "frame-generation", detail = summary(fgLabel, scope)) {
SettingsRow(stringResource(R.string.frame_gen_title), scope, stacked = true, tightControlSpacing = true) {
FrameGenMenu(
a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless,
gameProfileId = a.frameGenTargetGameId,
hasGameOverride = a.hasGameOverride,
onResetGame = a.onFrameGenReset,
)
}
FrameGenMenu(
mode = a.frameGen,
lossless = a.lossless,
onPick = a.onFrameGenPick,
gameProfileId = a.frameGenTargetGameId,
hasGameOverride = a.hasGameOverride,
onResetGame = a.onFrameGenReset,
focusModifier = track("frame-generation"),
sessionHost = host,
)
}
}
@Composable
private fun DrawerFrameGenPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
DrawerFrameGenSettings(host, a, track)
}
@Composable
private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val orientations = SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }
SettingsGroup(stringResource(R.string.drawer_page_display), key = "display",
detail = summary(if (a.gameZoomAvailable) "${(a.gameZoom * 100.0f).toInt()}%" else null, orientations.labelOf(a.orientation))) {
if (a.gameZoomAvailable) GameZoomRow(a, track)
if (a.gameZoomAvailable) GameZoomRow(a.gameZoom, track, a.onGameZoom)
ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null,
orientations, a.orientation, chipModifier = track("orientation"), onPick = a.onOrientation)
if (a.steam) PicturePositionRow(host, a.picturePosition, track("picture-position"), onPick = a.onPicturePosition)
}
val filters = SessionPrefs.upscalerChoices(LocalContext.current)
val integer = stringResource(if (a.integerScaling) R.string.display_scaling_integer else R.string.display_scaling_fit)
@@ -942,27 +980,66 @@ private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String)
SecondScreenGroup(host, a, track)
}
private const val GAME_ZOOM_MIN = 100
private const val GAME_ZOOM_MAX = 300
private const val GAME_ZOOM_STEP = 25
private const val GAME_ZOOM_INTERVALS = (GAME_ZOOM_MAX - GAME_ZOOM_MIN) / GAME_ZOOM_STEP
@Composable
private fun GameZoomRow(a: DrawerActions, track: (String) -> Modifier) {
SettingsRow(stringResource(R.string.game_zoom_title), stringResource(R.string.game_zoom_hint)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
val zoomOutEnabled = a.gameZoom > 1.0f
val zoomInEnabled = a.gameZoom < 3.0f
val zoomOut = { a.onGameZoom((a.gameZoom - 0.25f).coerceAtLeast(1.0f)) }
val zoomIn = { a.onGameZoom((a.gameZoom + 0.25f).coerceAtMost(3.0f)) }
val zoomReset = { a.onGameZoom(1.0f) }
OutlinedButton(onClick = zoomOut, enabled = zoomOutEnabled,
modifier = track("game-zoom-out").width(42.dp).controllerConfirm(enabled = zoomOutEnabled, onClick = zoomOut),
contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)) { Text("−") }
Text("${(a.gameZoom * 100.0f).toInt()}%", fontSize = 12.sp)
OutlinedButton(onClick = zoomIn, enabled = zoomInEnabled,
modifier = track("game-zoom-in").width(42.dp).controllerConfirm(enabled = zoomInEnabled, onClick = zoomIn),
contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)) { Text("+") }
OutlinedButton(onClick = zoomReset, enabled = zoomOutEnabled,
modifier = track("game-zoom-reset").width(48.dp).controllerConfirm(enabled = zoomOutEnabled, onClick = zoomReset),
contentPadding = PaddingValues(horizontal = 2.dp, vertical = 0.dp)) { Text("1×") }
}
internal fun GameZoomRow(
zoom: Float,
track: (String) -> Modifier,
onZoom: (Float) -> Unit,
) {
val source = remember { MutableInteractionSource() }
val focused by source.collectIsFocusedAsState()
val label = stringResource(R.string.game_zoom_title)
val percent = (zoom * 100f).roundToInt().coerceIn(GAME_ZOOM_MIN, GAME_ZOOM_MAX)
val value = stringResource(R.string.game_zoom_value, percent)
fun detent(value: Float): Int = ((value - GAME_ZOOM_MIN) / GAME_ZOOM_STEP).roundToInt()
val selectedDetent = detent(percent.toFloat())
val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
fun chooseDetent(index: Int) {
val next = GAME_ZOOM_MIN + index.coerceIn(0, GAME_ZOOM_INTERVALS) * GAME_ZOOM_STEP
if (next != percent) onZoom(next / 100f)
}
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(value, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold,
color = colors.onSurface, modifier = Modifier.testTag("game-zoom-value"))
}
Slider(
value = (GAME_ZOOM_MIN + selectedDetent * GAME_ZOOM_STEP).toFloat(),
onValueChange = { chooseDetent(detent(it)) },
valueRange = GAME_ZOOM_MIN.toFloat()..GAME_ZOOM_MAX.toFloat(),
steps = GAME_ZOOM_INTERVALS - 1,
interactionSource = source,
modifier = track("game-zoom-slider").fillMaxWidth().heightIn(min = 48.dp)
.glideBorder(focused, RoundedCornerShape(10.dp), pal.signal)
.testTag("game-zoom-slider")
.semantics { contentDescription = label; stateDescription = value }
.onPreviewKeyEvent { event ->
val delta = when (event.key) {
Key.DirectionLeft -> if (rtl) 1 else -1
Key.DirectionRight -> if (rtl) -1 else 1
else -> return@onPreviewKeyEvent false
}
if (event.type == KeyEventType.KeyDown && event.nativeKeyEvent.repeatCount == 0) {
chooseDetent(selectedDetent + delta)
}
true
},
)
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
@Composable
@@ -1485,7 +1562,44 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole
private val DRAWER_MIN_WIDTH = 300.dp
private val DRAWER_HANDLE_STRIP = 24.dp
private val DRAWER_EDGE_GAP = 80.dp
private val DRAWER_COLUMN_GAP = 10.dp
// Two columns once each would be as wide as the narrowest single-column sheet.
private val DRAWER_TWO_COLUMN_WIDTH = DRAWER_MIN_WIDTH * 2 + DRAWER_COLUMN_GAP
private val SessionDrawerPage.inColumns: Boolean
get() = this != SessionDrawerPage.MORE && this != SessionDrawerPage.ACHIEVEMENTS
/**
* On a wide sheet, lays a page's groups out in two columns, the first half on the left. The split is by count, not
* height, so a group keeps its column while others fold and unfold.
*/
@Composable
internal fun DrawerColumns(two: Boolean, content: @Composable () -> Unit) {
// Keep a single composition so resizing only remeasures existing children.
Layout(content, Modifier.fillMaxWidth()) { measurables, constraints ->
val width = constraints.maxWidth
if (!two || measurables.size < 2) {
val placeables = measurables.map { it.measure(constraints.copy(minWidth = 0, minHeight = 0)) }
return@Layout layout(width, placeables.sumOf { it.height }) {
var y = 0
placeables.forEach { it.placeRelative(0, y); y += it.height }
}
}
val gap = DRAWER_COLUMN_GAP.roundToPx()
val column = ((width - gap) / 2).coerceAtLeast(0)
val child = Constraints(maxWidth = column)
val placeables = measurables.map { it.measure(child) }
val half = (placeables.size + 1) / 2
val left = placeables.take(half)
val right = placeables.drop(half)
layout(width, maxOf(left.sumOf { it.height }, right.sumOf { it.height })) {
var y = 0
left.forEach { it.placeRelative(0, y); y += it.height }
y = 0
right.forEach { it.placeRelative(column + gap, y); y += it.height }
}
}
}
/** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */
@Composable
@@ -1507,6 +1621,8 @@ private fun DrawerResizeHandle(width: Dp, min: Dp, max: Dp, onWidth: (Dp) -> Uni
contentAlignment = Alignment.Center,
modifier = modifier.width(24.dp).height(96.dp)
.onGloballyPositioned { coords = it }
// On the screen's edge, Android's back swipe would take the drag.
.systemGestureExclusion()
.focusable(true, source)
.onPreviewKeyEvent { event ->
val key = event.nativeKeyEvent
@@ -1820,7 +1936,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
}
return
}
SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") {
DrawerComponentSettingsGroup(stringResource(R.string.drawer_game_components_note, gameProfile.name)) {
DrawerStackedChoice(
host = host,
key = "game-cmp-proton",
@@ -1863,12 +1979,6 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
)
}
}
Text(
stringResource(R.string.drawer_game_components_note, gameProfile.name),
fontSize = 12.sp,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
)
return
}
val running = snap.protons.filter { it.inUseByGame }
@@ -1909,7 +2019,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
return
}
val p = view.proton
SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") {
DrawerComponentSettingsGroup(stringResource(R.string.drawer_components_note)) {
DrawerStackedChoice(
host, "cmp-proton", stringResource(R.string.comp_proton),
listOfNotNull(
@@ -1945,10 +2055,16 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
)
}
}
Text(
stringResource(R.string.drawer_components_note),
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
)
}
@Composable
internal fun DrawerComponentSettingsGroup(note: String, content: @Composable ColumnScope.() -> Unit) {
// The note stays visible when collapsed, but both belong to one drawer column item.
Column(Modifier.fillMaxWidth()) {
SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components", content = content)
Text(note, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp))
}
}
@Composable
@@ -0,0 +1,62 @@
package com.droiddeck.launcher.ui
import android.os.SystemClock
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
/** The row a settings search result opens, so the page it lands on can scroll to it and flash it. */
internal object SettingsJump {
class Target(val label: String, val at: Long = SystemClock.uptimeMillis())
var target: Target? by mutableStateOf(null)
fun to(label: String) { target = Target(label) }
}
private const val JUMP_WINDOW_MS = 5_000L
/** False in the search results, whose rows carry the same labels as the rows they open. */
internal val LocalSearchTargets = staticCompositionLocalOf { true }
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
internal fun Modifier.searchTarget(label: String): Modifier {
val pal = LocalPalette.current
val flash = remember { Animatable(0f) }
val reveal = remember { BringIntoViewRequester() }
var claimed by remember { mutableStateOf<SettingsJump.Target?>(null) }
val target = SettingsJump.target.takeIf { LocalSearchTargets.current }
if (target != null && target.label == label) SideEffect {
if (SettingsJump.target === target) {
SettingsJump.target = null
if (SystemClock.uptimeMillis() - target.at <= JUMP_WINDOW_MS) claimed = target
}
}
claimed?.let { mine ->
LaunchedEffect(mine) {
withFrameNanos { }
reveal.bringIntoView()
repeat(2) {
flash.animateTo(1f, tween(220))
flash.animateTo(0f, tween(420))
}
claimed = null
}
}
return bringIntoViewRequester(reveal).drawBehind {
if (flash.value > 0f) drawRect(pal.signal.copy(alpha = 0.28f * flash.value))
}
}
@@ -103,7 +103,7 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (Setti
Note(stringResource(R.string.settings_search_none, query.trim()))
return
}
Column {
androidx.compose.runtime.CompositionLocalProvider(LocalSearchTargets provides false) { Column {
found.groupBy { it.place }.forEach { (place, entries) ->
SettingsGroup(stringResource(place.title)) {
entries.forEach { entry ->
@@ -112,9 +112,10 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (Setti
val section = entry.section
val tab = entry.tab
if (section != null) {
ActionRow(title, within, stringResource(R.string.store_open), onClick = { onOpen(section) })
ActionRow(title, within, stringResource(R.string.store_open), onClick = { SettingsJump.to(title); onOpen(section) })
} else if (tab != null) {
ActionRow(title, within, stringResource(R.string.store_open), onClick = {
SettingsJump.to(title)
if (tab == NavTabs.MORE) MoreTabs.editing = true
if (tab == "downloads") DownloadsNav.showSettings = true
RailRequest.key = tab
@@ -125,5 +126,5 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (Setti
}
}
}
}
} }
}
@@ -212,7 +212,8 @@ internal fun TabStrip(
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier) {
if (bumpers) BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) }
// Centred, the bumpers sit at the edges and the tabs in the middle, as in the bottom bar.
Box(if (centered) Modifier.weight(1f) else Modifier.weight(1f, fill = false), contentAlignment = Alignment.Center) { Row(
Box(if (centered) Modifier.weight(1f) else Modifier.weight(1f, fill = false), contentAlignment = Alignment.Center) { androidx.compose.foundation.layout.BoxWithConstraints {
if (tabsAsMenu(maxWidth, tabs.size)) TabMenu(tabs, selected, onSelect, focus = focusRequesters) else Row(
modifier = Modifier.clip(shape).background(colors.surfaceVariant).border(1.dp, pal.line2, shape)
.horizontalScroll(scroll).selectableGroup().padding(3.dp),
) {
@@ -239,7 +240,7 @@ internal fun TabStrip(
.padding(horizontal = tabPadding, vertical = if (compact) 6.dp else 12.dp),
)
}
} }
} } }
if (bumpers) BumperKey("RB", stringResource(R.string.widgets_next_tab)) { onSelect((selected + 1) % tabs.size) }
}
}
@@ -535,7 +536,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
minLines = hintLines ?: 1, maxLines = hintLines ?: Int.MAX_VALUE, overflow = TextOverflow.Ellipsis)
}
if (compact && !stacked) Column(
modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp),
modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(label, fontSize = 13.sp, lineHeight = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
@@ -544,7 +545,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
}
if (hint != null || hintLines != null) hintText(11.sp)
} else if (stacked || LocalNarrowPane.current) Column(
modifier = Modifier.fillMaxWidth().background(bg).padding(
modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(
horizontal = if (compact) 10.dp else 14.dp,
vertical = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 12.dp),
) {
@@ -555,7 +556,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
Box(Modifier.padding(top = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 8.dp)) { control() }
} else Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp),
modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp),
) {
Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
@@ -659,7 +660,7 @@ fun SliderRow(
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth()) {
Column(Modifier.searchTarget(label).fillMaxWidth()) {
ValueSlider(value, range, step, enabled, label, format,
modifier = modifier.padding(horizontal = 6.dp, vertical = 3.dp), onChange = onChange)
if (hint != null) Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant,
@@ -31,10 +31,6 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) {
a.onFrameGenPick(mode)
host.open = null
},
onImportLossless = {
a.onImportLossless()
host.open = null
},
focusModifier = Modifier.focusRequester(firstItemFocus),
legacyButtons = true,
)
@@ -82,17 +82,25 @@ import kotlinx.coroutines.withContext
private const val WALL_MIN_GAMES = 4
private const val WALL_DISTINCT = 40
private const val IDLE_FRAME_NS = 30_000_000L
internal val IdleFrames = IdleFrameGate()
internal object IdleFrames {
private var shown = 0L
internal class IdleFrameGate {
private var next = Long.MIN_VALUE
private var shown = Long.MIN_VALUE
fun due(nanos: Long): Boolean {
if (nanos == shown) return true
if (nanos - shown < IDLE_FRAME_NS) return false
// Allow sub-ms vsync jitter; carry the phase on panels whose refresh isn't a multiple of 60.
if (nanos + VSYNC_TOLERANCE_NS < next) return false
next = if (next == Long.MIN_VALUE || nanos - next >= FRAME_NS) nanos + FRAME_NS else next + FRAME_NS
shown = nanos
return true
}
private companion object {
const val FRAME_NS = 1_000_000_000L / 60
const val VSYNC_TOLERANCE_NS = 500_000L
}
}
@Composable
@@ -453,7 +453,7 @@ private fun StoreDot(store: Store, signedIn: Boolean) {
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun StoreChips(
internal fun StoreChips(
selected: String, focused: String?, tabs: List<StoreTab>,
onStore: (Store) -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit,
) {
@@ -470,27 +470,42 @@ private fun StoreChips(
val tabScroll = rememberScrollState()
Box(Modifier.fillMaxWidth()) {
Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Box(Modifier.weight(1f).edgeFade(tabScroll).horizontalScroll(tabScroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (tab in tabs) {
val store = tab.store
if (tab.shown) {
val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true
key(store) {
val reveal = remember { BringIntoViewRequester() }
LaunchedEffect(selected) { if (selected == store.id) reveal.bringIntoView() }
StoreChip(
label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot,
modifier = Modifier.bringIntoViewRequester(reveal).onGloballyPositioned { bounds[store.id] = it.boundsInParent() },
lead = { StoreDot(store, signedIn) },
description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out),
onFocused = onFocusChip,
) { onStore(store) }
val shown = tabs.filter { it.shown }.map { it.store }
BoxWithConstraints(Modifier.weight(1f)) {
if (sourceTabsAsMenu(maxWidth, shown.size)) TabMenu(
shown.map { it.shortLabel }, shown.indexOfFirst { it.id == selected }, { onStore(shown[it]) },
chipModifier = shown.fold(Modifier as Modifier) { m, st -> key(st) { m.paneItem("storechip:${st.id}") } },
descriptions = shown.map { st ->
val signedIn = StoresState.isSignedIn(st) && StoresState.expired[st] != true
st.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out)
},
leading = { i, inList ->
val signedIn = StoresState.isSignedIn(shown[i]) && StoresState.expired[shown[i]] != true
if (inList) Box(Modifier.size(12.dp).background(sourceColours(shown[i].id).dot.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape))
else StoreDot(shown[i], signedIn)
},
) else Box(Modifier.edgeFade(tabScroll).horizontalScroll(tabScroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (tab in tabs) {
val store = tab.store
if (tab.shown) {
val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true
key(store) {
val reveal = remember { BringIntoViewRequester() }
LaunchedEffect(selected) { if (selected == store.id) reveal.bringIntoView() }
StoreChip(
label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot,
modifier = Modifier.bringIntoViewRequester(reveal).onGloballyPositioned { bounds[store.id] = it.boundsInParent() },
lead = { StoreDot(store, signedIn) },
description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out),
onFocused = onFocusChip,
) { onStore(store) }
}
}
}
}
ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
var cogAt by remember { mutableStateOf<Rect?>(null) }
Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) {
@@ -0,0 +1,109 @@
package com.droiddeck.launcher.ui
import android.content.res.Configuration
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ExpandLess
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
private val TAB_MENU_BELOW = 600.dp
private val TAB_MIN_WIDTH = 96.dp
/** Whether [count] tabs in [width] become a [TabMenu]: on a narrow page, when they would not fit side by side. */
internal fun tabsAsMenu(width: Dp, count: Int): Boolean =
count > 2 && width < TAB_MENU_BELOW && width / count < TAB_MIN_WIDTH
@Composable
internal fun sourceTabsAsMenu(width: Dp, count: Int): Boolean =
count > 1 && (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT ||
(width < TAB_MENU_BELOW && width / count < TAB_MIN_WIDTH))
/**
* Tabs as one chip naming the shown tab, which opens the list of them, as the second screen's
* picker does. Each of [focus] lands on the chip, so callers that focus a tab still reach it.
*/
@Composable
internal fun TabMenu(
labels: List<String>, selected: Int, onPick: (Int) -> Unit,
modifier: Modifier = Modifier, focus: List<FocusRequester>? = null,
chipModifier: Modifier = Modifier, descriptions: List<String>? = null,
leading: (@Composable (index: Int, inList: Boolean) -> Unit)? = null,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by remember { mutableStateOf(false) }
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val shape = RoundedCornerShape(22.dp)
val label = labels.getOrNull(selected).orEmpty()
val description = descriptions?.getOrNull(selected) ?: label
val toggle = { open = !open }
Box(modifier) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = focus.orEmpty().fold(chipModifier.height(44.dp)) { m, r -> m.focusRequester(r) }
.testTag("tab-menu")
.semantics { contentDescription = description }
.clip(shape).background(if (hot || open) pal.signal.copy(alpha = 0.14f) else colors.surfaceVariant)
.glideBorder(hot || open, shape, pal.signal, pal.line2)
.hoverable(source)
.clickable(role = Role.Button, interactionSource = source, indication = LocalIndication.current, onClick = toggle)
.controllerConfirm(onClick = toggle)
.padding(start = 14.dp, end = 10.dp),
) {
if (selected in labels.indices) leading?.invoke(selected, false)
Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, contentDescription = null,
tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
}
AnchoredMenu(open, { open = false }, compact = true, minWidth = 200.dp) { first ->
labels.forEachIndexed { i, item ->
MenuItem(
item, checked = i == selected,
leading = leading?.let { { it(i, true) } },
focusRequester = first.takeIf { i == selected || (i == 0 && selected !in labels.indices) },
modifier = Modifier.testTag("tab-menu:$i")
.then(descriptions?.getOrNull(i)?.let { d -> Modifier.semantics { contentDescription = d } } ?: Modifier),
) { open = false; onPick(i) }
}
}
}
}
@@ -9,7 +9,6 @@ import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
@@ -21,10 +20,14 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
@@ -44,6 +47,7 @@ import androidx.compose.material.icons.outlined.Science
import androidx.compose.material.icons.outlined.SwapHoriz
import androidx.compose.material.icons.outlined.Sync
import androidx.compose.material.icons.outlined.Verified
import androidx.compose.material.icons.outlined.WarningAmber
import androidx.compose.material3.Icon
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.vector.ImageVector
@@ -109,49 +113,49 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
val me = remember { AppUpdates.installed() }
val colors = MaterialTheme.colorScheme
Column(modifier = modifier) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp),
) {
Text(
stringResource(R.string.upd_build, me.version, s.buildLabel), fontSize = 12.5.sp, color = colors.onSurfaceVariant,
maxLines = 1, modifier = Modifier.weight(1f)
.basicMarquee(iterations = Int.MAX_VALUE, initialDelayMillis = 700, velocity = 40.dp),
)
val checked = u.catalog?.checkedAt?.takeIf { it > 0 }
if (!LocalNarrowPane.current) Text(
if (u.checking) stringResource(R.string.common_checking) else if (checked != null) stringResource(R.string.upd_checked, ago(checked).replaceFirstChar { it.lowercase() }) else stringResource(R.string.upd_not_checked),
fontSize = 13.sp, color = colors.onSurfaceVariant,
)
val clipboard = LocalClipboardManager.current
val context = LocalContext.current
val details = buildDetails(me, s.buildLabel)
ToolIcon(Icons.Outlined.ContentCopy, stringResource(R.string.upd_copy_build)) {
clipboard.setText(AnnotatedString(details))
android.widget.Toast.makeText(context, context.getString(R.string.upd_copied), android.widget.Toast.LENGTH_SHORT).show()
}
ToolIcon(Icons.Outlined.Refresh, stringResource(R.string.store_check_updates), busy = u.checking, enabled = !u.checking && u.stage == null, onClick = ua.onCheck)
}
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
val stacked = LocalNarrowPane.current || maxWidth < 600.dp
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
if (stacked) {
StatusPanel(s, u, ua, me)
val context = LocalContext.current
val agentReady = com.droiddeck.launcher.agent.AgentHost.installed &&
(com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context))
val installed: @Composable () -> Unit = {
SectionLabel(stringResource(R.string.upd_installed_label))
InstalledCard(s, u, me)
CheckRow(u, ua)
LabBuilds(s.sessionRunning, header = { SectionLabel(stringResource(R.string.lab_builds)) }, onRebuild = if (agentReady) { info ->
com.droiddeck.launcher.agent.AgentHost.send(context, context.getString(R.string.agent_rebuild_lab, info.label))
context.startActivity(android.content.Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent")
.addFlags(android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP or android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
} else null)
}
val channel: @Composable () -> Unit = {
SectionLabel(stringResource(R.string.upd_channel))
ChannelPicker(u, ua) { StatusPanel(s, u, ua, me, embedded = it) }
}
val testers: @Composable () -> Unit = {
SectionLabel(stringResource(R.string.upd_testers), top = 22.dp)
ToggleRow(
host, "build-watermark", stringResource(R.string.setup_build_watermark),
stringResource(R.string.setup_build_watermark_hint), s.buildWatermark,
) { a.onBuildWatermark() }
}
if (stacked) {
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
installed()
Box(Modifier.height(18.dp))
ChannelLabel()
ChannelPicker(u, ua, s.sessionRunning)
} else {
ChannelLabel()
Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) {
Box(Modifier.weight(1f)) { ChannelPicker(u, ua, s.sessionRunning) }
Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) }
}
channel()
testers()
}
Box(Modifier.padding(top = 18.dp)) {
ToggleRow(
host, "build-watermark", stringResource(R.string.setup_build_watermark),
stringResource(R.string.setup_build_watermark_hint), s.buildWatermark,
) { a.onBuildWatermark() }
} else {
Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(24.dp)) {
Column(Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
installed()
testers()
}
Column(Modifier.weight(1.15f).fillMaxHeight().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
channel()
}
}
}
}
@@ -169,8 +173,114 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
)
}
private val TEST_TINT = Color(0xFF9B6CFF)
@Composable
private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed) {
private fun SectionLabel(text: String, top: androidx.compose.ui.unit.Dp = 4.dp) {
Text(
text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = top, bottom = 10.dp),
)
}
/** What is installed: which kind of build, its version and versionCode, and its commit, as the first thing on the page. */
@Composable
private fun InstalledCard(s: FrontEndState, u: UpdatesState, me: AppUpdates.Installed) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val catalog = u.catalog
val lab = com.droiddeck.launcher.lab.LabOverlay.active
val basePr = if (me.pr > 0) me.pr else Regex("""\bpr(\d+)\b""").find(s.buildLabel)?.groupValues?.get(1)?.toIntOrNull() ?: 0
val kind = when {
lab != null -> stringResource(R.string.upd_kind_lab)
me.pr > 0 -> stringResource(R.string.upd_kind_test)
catalog?.stable?.let { AppUpdates.isRunning(it, me) } == true -> stringResource(R.string.upd_stable)
catalog?.preview?.let { AppUpdates.isRunning(it, me) } == true -> stringResource(R.string.upd_preview)
else -> null
}
val tint = if (lab != null || me.pr > 0) TEST_TINT else pal.signal
val title = when {
lab != null -> lab.label
me.pr > 0 -> stringResource(R.string.upd_pr, me.pr)
else -> stringResource(R.string.upd_droiddeck_version, me.version)
}
val subtitle = when {
lab != null && basePr > 0 -> stringResource(R.string.upd_lab_on_pr, basePr)
lab != null -> stringResource(R.string.upd_lab_on_version, me.version)
me.pr > 0 -> catalog?.tests?.firstOrNull { it.pr == me.pr }?.title?.takeIf { it.isNotBlank() }?.let(::changeTitle)
else -> null
}
val built = lab?.built?.takeIf { it > 0 } ?: me.committedAt
val meta = listOfNotNull(
me.version.takeIf { lab != null || me.pr > 0 },
stringResource(R.string.upd_version_code, me.versionCode),
me.commit.take(7).takeIf { it.length == 7 },
built.takeIf { it > 0 }?.let { stringResource(R.string.upd_built_ago, ago(it).replaceFirstChar { c -> c.lowercase() }) },
).joinToString(" · ")
val clipboard = LocalClipboardManager.current
val context = LocalContext.current
val details = buildDetails(me, s.buildLabel)
Row(
verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(start = 18.dp, end = 12.dp, top = 14.dp, bottom = 16.dp),
) {
Column(Modifier.weight(1f).padding(top = 2.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
if (kind != null) Text(
kind.uppercase(), fontSize = 10.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.6.sp, color = tint, maxLines = 1,
modifier = Modifier.clip(CircleShape).background(tint.copy(alpha = 0.16f)).padding(horizontal = 8.dp, vertical = 3.dp),
)
Text(title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (subtitle != null) Text(subtitle, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = colors.onBackground, maxLines = 2,
overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 6.dp))
Text(meta, fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))
}
ToolIcon(Icons.Outlined.ContentCopy, stringResource(R.string.upd_copy_build)) {
clipboard.setText(AnnotatedString(details))
android.widget.Toast.makeText(context, context.getString(R.string.upd_copied), android.widget.Toast.LENGTH_SHORT).show()
}
}
}
@Composable
private fun CheckRow(u: UpdatesState, ua: UpdatesActions) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val enabled = !u.checking && u.stage == null
val checked = u.catalog?.checkedAt?.takeIf { it > 0 }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 14.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.offset(x = (-6).dp).paneItem("updates:check").heightIn(min = 40.dp).clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, Shape12, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.Button, onClick = ua.onCheck)
.controllerConfirm(enabled = enabled, onClick = ua.onCheck)
.padding(horizontal = 6.dp),
) {
if (u.checking) androidx.compose.material3.CircularProgressIndicator(Modifier.size(16.dp), color = pal.signal, strokeWidth = 2.dp)
else Icon(Icons.Outlined.Refresh, contentDescription = null, tint = pal.signal.copy(alpha = if (enabled) 1f else 0.5f), modifier = Modifier.size(18.dp))
Text(
if (u.checking) stringResource(R.string.common_checking) else stringResource(R.string.upd_check_now),
fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = pal.signal.copy(alpha = if (enabled || u.checking) 1f else 0.5f),
)
}
Box(Modifier.weight(1f))
Text(
if (checked != null) stringResource(R.string.upd_checked, ago(checked).replaceFirstChar { it.lowercase() }) else stringResource(R.string.upd_not_checked),
fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1,
)
}
}
@Composable
private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed, embedded: Boolean = false) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val catalog = u.catalog
@@ -196,17 +306,24 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
else -> Look(pal.good, stringResource(R.string.upd_current_status), stringResource(R.string.upd_current_headline, name), null)
}
Column(
modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp),
modifier = if (embedded) Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 14.dp)
else Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {
Box(Modifier.size(7.dp).clip(CircleShape).background(look.tint))
Text(look.status, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = look.tint)
if (offered) Text(stringResource(R.string.upd_dot_ago, ago(release!!.publishedAt)), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
Text(look.headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp))
if (!embedded) Text(look.headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp))
if (offered) {
ReleaseNotes(changeTitle(release!!.title.ifBlank { release.tag }), release.summary, release.tag)
ReleaseFacts(release)
val size = release!!.apk?.size?.takeIf { it > 0 }?.let { megabytes(it) }
Text(
listOfNotNull(stringResource(R.string.upd_released_ago, ago(release.publishedAt)), size).joinToString(" · "),
fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp),
)
val older = (release.committedAt.takeIf { it > 0 } ?: release.publishedAt).let { it > 0 && me.committedAt > 0 && it < me.committedAt }
if (offer == Offer.SWITCH && older) OlderNote(me.committedAt)
val title = changeTitle(release.title.ifBlank { release.tag })
ReleaseNotes(title.takeUnless { it == look.headline || (release.version != null && it.endsWith(release.version)) }, release.summary, release.tag)
}
if (release != null && u.follow.channel == Channel.TEST && catalog != null) {
androidx.compose.runtime.LaunchedEffect(release.tag, release.commit, release.apk?.sha256) { ua.onSeen(release) }
@@ -228,8 +345,10 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(6.dp).clip(CircleShape))
}
offered && installBlock != null -> Unit
offer == Offer.UPDATE -> PrimaryButton(stringResource(R.string.upd_update_button, button), enabled = installable, main = true) { ua.onInstall(release!!) }
offer == Offer.SWITCH -> PrimaryButton(stringResource(R.string.upd_install_button, button), enabled = installable, main = true) { ua.onInstall(release!!) }
offer == Offer.UPDATE -> PrimaryButton(stringResource(R.string.upd_update_button, button), enabled = installable, main = true, fill = true,
modifier = Modifier.fillMaxWidth()) { ua.onInstall(release!!) }
offer == Offer.SWITCH -> PrimaryButton(stringResource(R.string.upd_switch_to_button, channelTitle(u.follow), button), enabled = installable, main = true,
fill = true, modifier = Modifier.fillMaxWidth()) { ua.onInstall(release!!) }
offer == Offer.AHEAD && u.follow.channel == Channel.STABLE && installBlock == null ->
SecondaryButton(stringResource(R.string.upd_install_anyway, release?.version.orEmpty()), enabled = installable) { ua.onInstall(release!!) }
offer == Offer.GONE -> PrimaryButton(stringResource(R.string.upd_follow_preview), main = true) { ua.onFollow(Follow(Channel.NIGHTLY)) }
@@ -238,25 +357,53 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
if (s.sessionRunning && (offered || offer == Offer.AHEAD)) {
Text(stringResource(R.string.upd_stop_session), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp))
}
if (offered) ReleaseFacts(release!!)
if (u.follow.channel == Channel.NIGHTLY) {
PreviewHistory(catalog, me, s, u, ua)
}
}
}
/** A switch that installs a build made before the installed one; Android keeps the app's data across it. */
@Composable
private fun ReleaseNotes(title: String, notes: String, key: String) {
private fun OlderNote(installedAt: Long) {
val context = LocalContext.current
val date = android.text.format.DateUtils.formatDateTime(context, installedAt,
android.text.format.DateUtils.FORMAT_SHOW_DATE or android.text.format.DateUtils.FORMAT_ABBREV_MONTH)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.padding(top = 12.dp).fillMaxWidth().clip(Shape12).background(AttentionAmber.copy(alpha = 0.12f))
.padding(horizontal = 12.dp, vertical = 10.dp),
) {
Icon(Icons.Outlined.WarningAmber, contentDescription = null, tint = AttentionAmber, modifier = Modifier.size(20.dp))
Column {
Text(stringResource(R.string.upd_older_than_installed, date), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = AttentionAmber)
Text(stringResource(R.string.upd_data_stays), fontSize = 12.5.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
@Composable
private fun channelTitle(f: Follow) = when (f.channel) {
Channel.STABLE -> stringResource(R.string.upd_stable)
Channel.NIGHTLY -> stringResource(R.string.upd_preview)
Channel.TEST -> stringResource(R.string.upd_pr, f.pr)
}
@Composable
private fun ReleaseNotes(title: String?, notes: String, key: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable(key) { mutableStateOf(false) }
var cut by remember(key) { mutableStateOf(false) }
Text(
if (title != null) Text(
title, fontSize = 15.sp, color = colors.onBackground, maxLines = if (open) Int.MAX_VALUE else 2, overflow = TextOverflow.Ellipsis,
onTextLayout = { if (it.hasVisualOverflow) cut = true }, modifier = Modifier.padding(top = 10.dp),
)
if (notes.isNotBlank()) Text(
notes, fontSize = 13.5.sp, color = colors.onSurfaceVariant, maxLines = if (open) Int.MAX_VALUE else 1, overflow = TextOverflow.Ellipsis,
onTextLayout = { if (it.hasVisualOverflow) cut = true }, modifier = Modifier.padding(top = 4.dp),
notes, fontSize = 13.5.sp, color = colors.onSurfaceVariant, maxLines = if (open) Int.MAX_VALUE else if (title == null) 3 else 1,
overflow = TextOverflow.Ellipsis, onTextLayout = { if (it.hasVisualOverflow) cut = true },
modifier = Modifier.padding(top = if (title == null) 10.dp else 4.dp),
)
if (cut || open) {
val src = remember { MutableInteractionSource() }
@@ -287,47 +434,77 @@ private fun changeTitle(t: String): String =
private fun megabytes(bytes: Long) = stringResource(R.string.upd_mb, ((bytes + 524_288) / 1_048_576).toInt())
@Composable
private fun ChannelLabel() {
Text(
stringResource(R.string.upd_channel), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp),
)
}
@Composable
private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions, sessionRunning: Boolean) {
private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions, status: @Composable (embedded: Boolean) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val catalog = u.catalog
val tests = catalog?.tests.orEmpty()
val me = remember { AppUpdates.installed() }
val ready = tests.count { AppUpdates.installable(it, me) }
var showTests by rememberSaveable { mutableStateOf(false) }
val listing = (showTests || u.follow.channel == Channel.TEST) && tests.isNotEmpty()
val shown = if (listing || showTests) Channel.TEST else u.follow.channel
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
ChannelCard(
Icons.Outlined.Verified, stringResource(R.string.upd_stable), stringResource(R.string.upd_stable_hint),
catalog?.stable?.let { stringResource(R.string.upd_version_ago, it.version ?: it.tag, ago(it.publishedAt)) }, u.follow.channel == Channel.STABLE,
) { ua.onFollow(Follow(Channel.STABLE)) }
ChannelCard(
Icons.Outlined.Bolt, stringResource(R.string.upd_preview), stringResource(R.string.upd_preview_hint),
catalog?.preview?.let { ago(it.publishedAt) }, u.follow.channel == Channel.NIGHTLY,
) { ua.onFollow(Follow(Channel.NIGHTLY)) }
ChannelCard(
Icons.Outlined.Science, stringResource(R.string.upd_tests), stringResource(R.string.upd_tests_hint),
if (tests.isEmpty()) stringResource(R.string.upd_tests_none) else pluralStringResource(R.plurals.upd_tests_count, ready, ready),
u.follow.channel == Channel.TEST, enabled = tests.isNotEmpty() || u.follow.channel == Channel.TEST,
) { showTests = !showTests }
AnimatedVisibility((showTests || u.follow.channel == Channel.TEST) && tests.isNotEmpty(), enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
TestList(tests, me, u, ua)
Row(
horizontalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.fillMaxWidth().clip(CircleShape).background(colors.surface).border(1.dp, pal.line, CircleShape)
.padding(4.dp).selectableGroup(),
) {
ChannelSegment(Icons.Outlined.Verified, stringResource(R.string.upd_stable), null, shown == Channel.STABLE) {
showTests = false; ua.onFollow(Follow(Channel.STABLE))
}
ChannelSegment(Icons.Outlined.Bolt, stringResource(R.string.upd_preview), null, shown == Channel.NIGHTLY) {
showTests = false; ua.onFollow(Follow(Channel.NIGHTLY))
}
ChannelSegment(
Icons.Outlined.Science, stringResource(R.string.upd_tests_short), ready.takeIf { it > 0 }?.toString(),
shown == Channel.TEST, enabled = tests.isNotEmpty() || u.follow.channel == Channel.TEST,
) { showTests = !showTests }
}
val context = androidx.compose.ui.platform.LocalContext.current
val agentReady = com.droiddeck.launcher.agent.AgentHost.installed &&
(com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context))
LabBuilds(sessionRunning, onRebuild = if (agentReady) { info ->
com.droiddeck.launcher.agent.AgentHost.send(context, context.getString(R.string.agent_rebuild_lab, info.label))
context.startActivity(android.content.Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent")
.addFlags(android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP or android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
} else null)
val hint = when {
listing || u.follow.channel == Channel.TEST -> stringResource(R.string.upd_tests_hint)
u.follow.channel == Channel.NIGHTLY -> stringResource(R.string.upd_preview_hint) +
(catalog?.preview?.let { " · " + stringResource(R.string.upd_latest_ago, ago(it.publishedAt)) } ?: "")
else -> stringResource(R.string.upd_stable_hint) +
(catalog?.stable?.let { " · " + stringResource(R.string.upd_version_ago, it.version ?: it.tag, ago(it.publishedAt)) } ?: "")
}
Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
if (tests.isEmpty() && catalog != null && showTests) Text(stringResource(R.string.upd_tests_none), fontSize = 12.5.sp, color = colors.onSurfaceVariant)
if (!listing) status(false)
AnimatedVisibility(listing, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
TestList(tests, me, u, ua, status)
}
}
}
@Composable
private fun RowScope.ChannelSegment(
icon: ImageVector, title: String, badge: String?, selected: Boolean,
enabled: Boolean = true, onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally),
modifier = Modifier.weight(1f).heightIn(min = 44.dp).paneItem("channel:$title")
.clip(CircleShape)
.background(if (selected) pal.signal.copy(alpha = 0.16f) else if (hot) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
.glideBorder(hot, CircleShape, pal.signal, if (selected) pal.signal else Color.Transparent)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src)
.selectable(selected = selected, interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 6.dp),
) {
Icon(icon, contentDescription = null, tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(18.dp))
Text(title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (selected) colors.onBackground else colors.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
if (badge != null) Text(
badge, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant,
modifier = Modifier.clip(CircleShape).background(colors.surfaceVariant).padding(horizontal = 6.dp, vertical = 1.dp),
)
}
}
@@ -514,7 +691,7 @@ private fun LinkPill(label: String, url: String) {
}
@Composable
private fun TestList(tests: List<Release>, me: AppUpdates.Installed, u: UpdatesState, ua: UpdatesActions) {
private fun TestList(tests: List<Release>, me: AppUpdates.Installed, u: UpdatesState, ua: UpdatesActions, status: @Composable (embedded: Boolean) -> Unit) {
val colors = MaterialTheme.colorScheme
var query by rememberSaveable { mutableStateOf("") }
val needle = query.trim().removePrefix("#").removePrefix("@")
@@ -525,58 +702,30 @@ private fun TestList(tests: List<Release>, me: AppUpdates.Installed, u: UpdatesS
val (ready, old) = matches.partition { it.versionCode >= me.versionCode }
val followedOld = u.follow.channel == Channel.TEST && old.any { it.pr == u.follow.pr }
var showOld by rememberSaveable { mutableStateOf(false) }
Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (tests.size > 5 || query.isNotEmpty()) AdbTextField(
value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find),
keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, compact = true, showLabel = false,
placeholder = stringResource(R.string.upd_tests_find), modifier = Modifier.fillMaxWidth(),
)
if (matches.isEmpty()) Text(stringResource(R.string.upd_tests_no_match), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(4.dp))
ready.forEach { t -> TestRow(t, u.follow.pr == t.pr && u.follow.channel == Channel.TEST) { ua.onFollow(Follow(Channel.TEST, t.pr)) } }
if (old.isNotEmpty()) {
MoreLink(stringResource(R.string.upd_tests_old, old.size, me.versionCode), "tests:old") { showOld = !showOld }
if (showOld || followedOld || needle.isNotEmpty()) old.forEach { t ->
TestRow(t, u.follow.pr == t.pr && u.follow.channel == Channel.TEST, tooOld = true) { ua.onFollow(Follow(Channel.TEST, t.pr)) }
val oldShown = showOld || followedOld || needle.isNotEmpty()
val followed = u.follow.pr.takeIf { u.follow.channel == Channel.TEST }
val rowShown = followed != null && (ready.any { it.pr == followed } || (oldShown && old.any { it.pr == followed }))
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
// A followed test's row carries the status; browsing Tests while following Stable or Preview shows it only for an install running or failed.
if (if (followed != null) !rowShown else u.stage != null || u.error != null) status(false)
Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (tests.size > 5 || query.isNotEmpty()) AdbTextField(
value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find),
keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, compact = true, showLabel = false,
placeholder = stringResource(R.string.upd_tests_find), modifier = Modifier.fillMaxWidth(),
)
if (matches.isEmpty()) Text(stringResource(R.string.upd_tests_no_match), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(4.dp))
ready.forEach { t -> TestRow(t, followed == t.pr, status = status) { ua.onFollow(Follow(Channel.TEST, t.pr)) } }
if (old.isNotEmpty()) {
MoreLink(stringResource(R.string.upd_tests_old, old.size, me.versionCode), "tests:old") { showOld = !showOld }
if (oldShown) old.forEach { t ->
TestRow(t, followed == t.pr, tooOld = true, status = status) { ua.onFollow(Follow(Channel.TEST, t.pr)) }
}
}
}
}
}
@Composable
private fun ChannelCard(
icon: ImageVector, title: String, hint: String, latest: String?, selected: Boolean,
enabled: Boolean = true, onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val fill = if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxWidth().paneItem("channel:$title")
.clip(Shape14).background(colors.surface).background(fill).glideBorder(hot, Shape14, pal.signal, pal.line)
.alpha(if (enabled) 1f else 0.55f)
.hoverable(src)
.clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 14.dp, vertical = 10.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(38.dp).clip(Shape12).background(if (selected) pal.signal.copy(alpha = 0.18f) else colors.surfaceVariant)) {
Icon(icon, contentDescription = null, tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
}
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
if (latest != null) Text(latest, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = if (selected) pal.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
RadioDot(selected)
}
}
@Composable
private fun RadioDot(selected: Boolean, size: androidx.compose.ui.unit.Dp = 22.dp) {
val pal = LocalPalette.current
@@ -586,40 +735,46 @@ private fun RadioDot(selected: Boolean, size: androidx.compose.ui.unit.Dp = 22.d
}
@Composable
private fun TestRow(t: Release, selected: Boolean, tooOld: Boolean = false, onClick: () -> Unit) {
private fun TestRow(t: Release, selected: Boolean, tooOld: Boolean = false, status: @Composable (embedded: Boolean) -> Unit, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().paneItem("test:${t.pr}")
.heightIn(min = 52.dp)
.clip(Shape12)
.background(colors.surface).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, Shape12, pal.signal, pal.line)
.alpha(if (tooOld && !selected) 0.6f else 1f)
.hoverable(src)
.clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp),
Column(
Modifier.fillMaxWidth().clip(Shape12).background(colors.surface)
.glideBorder(hot, Shape12, pal.signal, if (selected) pal.signal.copy(alpha = 0.5f) else pal.line),
) {
Text("#${t.pr}", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (selected) pal.signal else colors.onSurfaceVariant)
Column(Modifier.weight(1f)) {
Text(changeTitle(t.title.ifBlank { stringResource(R.string.upd_pr, t.pr) }), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val detail = when {
t.apk == null -> stringResource(R.string.upd_not_built)
tooOld -> stringResource(R.string.upd_tests_old_row, t.versionCode)
else -> stringResource(R.string.upd_updated, ago(t.builtAt.takeIf { it > 0 } ?: t.publishedAt))
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().paneItem("test:${t.pr}")
.heightIn(min = 52.dp)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.alpha(if (tooOld && !selected) 0.6f else 1f)
.hoverable(src)
.clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
Text("#${t.pr}", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (selected) pal.signal else colors.onSurfaceVariant)
Column(Modifier.weight(1f)) {
Text(changeTitle(t.title.ifBlank { stringResource(R.string.upd_pr, t.pr) }), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val detail = when {
t.apk == null -> stringResource(R.string.upd_not_built)
tooOld -> stringResource(R.string.upd_tests_old_row, t.versionCode)
else -> stringResource(R.string.upd_updated, ago(t.builtAt.takeIf { it > 0 } ?: t.publishedAt))
}
Text(
listOfNotNull(detail, t.author.takeIf { it.isNotEmpty() }?.let { "@$it" }, t.shortCommit).joinToString(" · "),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
if (t.newerCommitPushed) Text(stringResource(R.string.upd_newer_commit_short), fontSize = 12.sp, color = AttentionAmber, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text(
listOfNotNull(detail, t.author.takeIf { it.isNotEmpty() }?.let { "@$it" }, t.shortCommit).joinToString(" · "),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
if (t.newerCommitPushed) Text(stringResource(R.string.upd_newer_commit_short), fontSize = 12.sp, color = AttentionAmber, maxLines = 1, overflow = TextOverflow.Ellipsis)
RadioDot(selected, 20.dp)
}
AnimatedVisibility(selected, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
status(true)
}
RadioDot(selected, 20.dp)
}
}
@@ -9,6 +9,10 @@ public final class WaylandCompositor {
private WaylandCompositor() {}
public static native boolean frameWorkerProbeEnabled();
public static native boolean frameWorkerProbeGrant(int owner, int pid, long expires, String path, long dev, long ino, long startTicks);
public static native void frameWorkerProbeRevoke(int owner, int pid);
private static volatile Runnable firstFrameListener;
public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; }
@@ -329,6 +333,8 @@ public final class WaylandCompositor {
public static native void nativeSetZeroCopy(boolean on);
public static native void nativeSetMirrorCapture(boolean on);
public static native void nativeSetDisplayBufferDriver(boolean on);
public static native int nativeZeroCopyFrames();
@@ -456,12 +462,14 @@ public final class WaylandCompositor {
public static final int SCENE_BUTTON = 3, SCENE_WHEEL = 4, SCENE_POINTER_DELTA = 6, SCENE_AXIS = 11, SCENE_AXIS_FINGER = 12;
public static final int WHEEL_STEP_UNITS = 120, POINTER_DELTA_SCALE = 256;
public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1;
public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1, FG_ENGINE_ZEROFG = 2;
public static native void nativeSetFrameGenEngine(int kind);
public static native void nativeSetFrameGenArmed(boolean armed, int multiplier, int targetFps);
public static native void nativeSetFrameGenPacer(boolean on);
public static native void nativeSetLsfgCachePath(String path);
public static native void nativeSetFrameGenTuning(float flowScale, float refreshHz);
@@ -2,7 +2,13 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="512"
android:viewportHeight="512">
<path android:fillColor="#FFFFFFFF" android:fillType="evenOdd" android:pathData="M 142 335 L 148 343 L 148 345 L 155 352 L 165 365 L 166 368 L 169 370 L 171 374 L 176 379 L 177 382 L 179 383 L 181 387 L 187 393 L 187 395 L 193 401 L 196 400 L 200 392 L 206 386 L 259 419 L 262 418 L 266 411 L 264 406 L 250 398 L 249 396 L 242 391 L 237 389 L 236 387 L 231 385 L 227 381 L 215 374 L 215 371 L 222 361 L 222 356 L 220 353 Z M 472 198 L 463 195 L 446 195 L 436 198 L 431 198 L 426 200 L 418 201 L 415 203 L 382 209 L 375 212 L 361 214 L 353 217 L 349 224 L 349 226 L 346 229 L 339 245 L 336 248 L 281 354 L 274 365 L 275 370 L 279 376 L 279 379 L 311 450 L 311 453 L 317 465 L 325 473 L 327 474 L 339 474 L 348 470 L 353 465 L 360 454 L 369 436 L 369 434 L 372 430 L 374 424 L 385 404 L 388 396 L 399 376 L 463 246 L 466 243 L 470 232 L 480 214 L 479 205 Z M 444 224 L 445 226 L 337 439 L 334 435 L 332 428 L 316 393 L 315 388 L 312 384 L 312 381 L 305 367 L 305 364 L 307 362 L 348 282 L 369 244 L 369 242 L 372 239 L 381 238 L 386 236 L 390 236 L 395 234 L 409 232 L 423 228 L 432 227 L 440 224 Z M 211 187 L 201 192 L 201 194 L 203 196 L 203 198 L 228 249 L 225 251 L 166 265 L 165 266 L 169 280 L 234 264 L 242 278 L 242 280 L 265 327 L 278 321 L 278 319 L 250 261 L 252 259 L 313 244 L 310 229 L 244 246 L 235 230 L 235 228 L 226 211 L 226 209 L 224 207 L 215 186 Z M 233 127 L 233 129 L 235 131 L 240 133 L 243 136 L 248 138 L 287 162 L 287 165 L 279 178 L 281 181 L 288 183 L 290 182 L 304 186 L 310 186 L 313 188 L 316 187 L 320 189 L 343 192 L 350 195 L 352 194 L 357 196 L 362 196 L 354 186 L 351 184 L 350 181 L 347 179 L 339 168 L 335 165 L 335 163 L 324 152 L 323 149 L 320 147 L 311 135 L 307 134 L 302 136 L 302 138 L 297 144 L 297 146 L 295 148 L 292 148 L 282 141 L 276 139 L 266 132 L 264 132 L 253 125 L 247 123 L 242 119 L 237 120 Z M 221 73 L 212 70 L 195 70 L 175 75 L 170 75 L 154 80 L 140 82 L 135 84 L 130 84 L 123 87 L 103 91 L 95 103 L 88 119 L 86 121 L 79 136 L 75 141 L 73 147 L 66 158 L 59 174 L 56 177 L 23 240 L 24 245 L 34 266 L 34 269 L 44 289 L 44 292 L 60 326 L 63 335 L 67 342 L 72 347 L 76 349 L 91 348 L 95 346 L 106 334 L 118 310 L 118 308 L 120 306 L 229 88 L 228 80 Z M 193 99 L 194 100 L 190 107 L 190 109 L 183 121 L 183 123 L 181 125 L 176 137 L 174 139 L 132 224 L 130 226 L 123 242 L 112 261 L 89 307 L 88 311 L 85 314 L 58 250 L 53 241 L 62 223 L 74 202 L 118 117 L 121 114 L 129 113 L 134 111 L 139 111 L 162 105 L 167 105 L 188 99 Z" />
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M4.5,7.5 H13.8 Q15.5,7.5 15.5,9.2 V18.8 Q15.5,20.5 13.8,20.5 H4.5 Q2.8,20.5 2.8,18.8 V9.2 Q2.8,7.5 4.5,7.5 Z M7.2,4 H18.2 Q20,4 20,5.8 V9 M20,12.2 V18.2 M17,15.2 H23"
android:fillColor="@android:color/transparent"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="1.75"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+8 -12
View File
@@ -55,17 +55,6 @@
<string name="frame_gen_lsfg">LSFG %1$d×</string>
<string name="frame_gen_lsfg_adaptive">LSFG تكيّفي %1$d</string>
<string name="lsfg_needs_steam">يتطلب Lossless Scaling على Steam</string>
<string name="lsfg_needs_install">ثبّت Lossless Scaling في Steam أو استورد Lossless.dll</string>
<string name="lsfg_import">استيراد Lossless.dll…</string>
<string name="lsfg_using_steam">يتم استخدام النسخة الموجودة في Steam</string>
<string name="lsfg_using_import">يتم استخدام نسخة مستوردة</string>
<string name="lsfg_pick_title">اختر Lossless.dll</string>
<string name="lsfg_imported">تم استيراد Lossless.dll</string>
<string name="lsfg_import_unchanged">ملف Lossless.dll هذا قيد الاستخدام بالفعل</string>
<string name="lsfg_import_not_owned">حساب Steam هذا لا يملك Lossless Scaling</string>
<string name="lsfg_import_invalid">هذا الملف ليس Lossless.dll الخاص بـ Lossless Scaling</string>
<string name="lsfg_import_failed">تعذّر تجهيز LSFG من ملف Lossless.dll هذا</string>
<string name="lsfg_problem_missing">يتطلب LSFG برنامج Lossless Scaling من Steam أو ملف Lossless.dll مستوردًا</string>
<string name="lsfg_problem_failed">تعذّر على LSFG تجهيز أدوات التظليل من Lossless.dll</string>
<string name="hud_fg_unsupported">%1$s: غير مدعوم</string>
<string name="hud_fg_failed">%1$s: فشل المحرك</string>
@@ -1191,6 +1180,11 @@
<string name="agent_tools_missing">أدوات الوكيل غير مثبتة: %1$s</string>
<string name="agent_unqueue">لا تُرسل</string>
<string name="agent_attach">إرفاق</string>
<string name="agent_attach_files">الملفات</string>
<string name="agent_photos_allow">السماح بالوصول إلى الصور</string>
<string name="agent_photos_more">اختيار المزيد من الصور</string>
<string name="agent_photos_empty">لا توجد صور بعد</string>
<string name="agent_keyboard">لوحة المفاتيح</string>
<string name="agent_remove_attachment">إزالة</string>
<string name="agent_model_default">الافتراضي</string>
<string name="agent_effort">جهد الاستدلال</string>
@@ -3340,9 +3334,11 @@
<string name="stores_hltb_hours">%1$s س</string>
<string name="stores_hltb_minutes">%1$d د</string>
<string name="display_picture_position">موضع الصورة</string>
<string name="display_picture_position_landscape">موضع الصورة (أفقي)</string>
<string name="display_picture_position_portrait">موضع الصورة (عمودي)</string>
<string name="display_position_top">أعلى</string>
<string name="display_position_bottom">أسفل</string>
<string name="display_position_center">الوسط (افتراضي)</string>
<string name="display_position_center">الوسط</string>
<string name="display_position_left">يسار</string>
<string name="display_position_right">يمين</string>
<string name="setup_tab_storage">التخزين</string>
+8 -12
View File
@@ -55,17 +55,6 @@
<string name="frame_gen_lsfg">LSFG %1$d×</string>
<string name="frame_gen_lsfg_adaptive">LSFG adaptativo %1$d</string>
<string name="lsfg_needs_steam">Requiere Lossless Scaling en Steam</string>
<string name="lsfg_needs_install">Instala Lossless Scaling en Steam o importa Lossless.dll</string>
<string name="lsfg_import">Importar Lossless.dll…</string>
<string name="lsfg_using_steam">Usando la copia de Steam</string>
<string name="lsfg_using_import">Usando una copia importada</string>
<string name="lsfg_pick_title">Elegir Lossless.dll</string>
<string name="lsfg_imported">Lossless.dll importado</string>
<string name="lsfg_import_unchanged">Este Lossless.dll ya está en uso</string>
<string name="lsfg_import_not_owned">Lossless Scaling no está en esta cuenta de Steam</string>
<string name="lsfg_import_invalid">Este archivo no es el Lossless.dll de Lossless Scaling</string>
<string name="lsfg_import_failed">No se pudo preparar LSFG con este Lossless.dll</string>
<string name="lsfg_problem_missing">LSFG necesita Lossless Scaling de Steam o un Lossless.dll importado</string>
<string name="lsfg_problem_failed">LSFG no pudo preparar sus shaders desde Lossless.dll</string>
<string name="hud_fg_unsupported">%1$s: no compatible</string>
<string name="hud_fg_failed">%1$s: falló el motor</string>
@@ -1209,6 +1198,11 @@
<string name="agent_tools_missing">Herramientas del agente sin instalar: %1$s</string>
<string name="agent_unqueue">No enviar</string>
<string name="agent_attach">Adjuntar</string>
<string name="agent_attach_files">Archivos</string>
<string name="agent_photos_allow">Permitir acceso a fotos</string>
<string name="agent_photos_more">Elegir más fotos</string>
<string name="agent_photos_empty">Aún no hay fotos</string>
<string name="agent_keyboard">Teclado</string>
<string name="agent_remove_attachment">Quitar</string>
<string name="agent_model_default">Predeterminado</string>
<string name="agent_effort">Esfuerzo de razonamiento</string>
@@ -3216,9 +3210,11 @@
<string name="hand_camera_group">Seguimiento de manos</string>
<string name="hand_camera_prompt_title">¿Rastrear las manos o los mandos Joy-Con con la cámara del teléfono?</string>
<string name="display_picture_position">Posición de la imagen</string>
<string name="display_picture_position_landscape">Posición de la imagen (Horizontal)</string>
<string name="display_picture_position_portrait">Posición de la imagen (Vertical)</string>
<string name="display_position_top">Arriba</string>
<string name="display_position_bottom">Abajo</string>
<string name="display_position_center">Centro (predeterminado)</string>
<string name="display_position_center">Centro</string>
<string name="display_position_left">Izquierda</string>
<string name="display_position_right">Derecha</string>
<string name="setup_tab_storage">Almacenamiento</string>
+8 -12
View File
@@ -55,17 +55,6 @@
<string name="frame_gen_lsfg">LSFG %1$d×</string>
<string name="frame_gen_lsfg_adaptive">LSFG Адаптивно %1$d</string>
<string name="lsfg_needs_steam">Изисква Lossless Scaling в Steam</string>
<string name="lsfg_needs_install">Инсталирайте Lossless Scaling в Steam или импортирайте Lossless.dll</string>
<string name="lsfg_import">Импортиране на Lossless.dll…</string>
<string name="lsfg_using_steam">Използва се копието от Steam</string>
<string name="lsfg_using_import">Използва се импортирано копие</string>
<string name="lsfg_pick_title">Изберете Lossless.dll</string>
<string name="lsfg_imported">Lossless.dll е импортиран</string>
<string name="lsfg_import_unchanged">Този Lossless.dll вече се използва</string>
<string name="lsfg_import_not_owned">Lossless Scaling не е закупен за този акаунт в Steam</string>
<string name="lsfg_import_invalid">Този файл не е Lossless.dll на Lossless Scaling</string>
<string name="lsfg_import_failed">LSFG не можа да се подготви от този Lossless.dll</string>
<string name="lsfg_problem_missing">LSFG изисква Lossless Scaling от Steam или импортиран Lossless.dll</string>
<string name="lsfg_problem_failed">LSFG не можа да подготви шейдърите си от Lossless.dll</string>
<string name="hud_fg_unsupported">%1$s: не се поддържа</string>
<string name="hud_fg_failed">%1$s: грешка в двигателя</string>
@@ -1179,6 +1168,11 @@
<string name="agent_tools_missing">Инструментите на агента не са инсталирани: %1$s</string>
<string name="agent_unqueue">Не изпращай</string>
<string name="agent_attach">Прикачи</string>
<string name="agent_attach_files">Файлове</string>
<string name="agent_photos_allow">Разрешаване на достъп до снимки</string>
<string name="agent_photos_more">Избор на още снимки</string>
<string name="agent_photos_empty">Все още няма снимки</string>
<string name="agent_keyboard">Клавиатура</string>
<string name="agent_remove_attachment">Премахни</string>
<string name="agent_model_default">По подразбиране</string>
<string name="agent_effort">Усилие за разсъждение</string>
@@ -3220,9 +3214,11 @@
<string name="stores_hltb_hours">%1$s ч</string>
<string name="stores_hltb_minutes">%1$d мин</string>
<string name="display_picture_position">Позиция на картината</string>
<string name="display_picture_position_landscape">Позиция на картината (Хоризонтална)</string>
<string name="display_picture_position_portrait">Позиция на картината (Вертикална)</string>
<string name="display_position_top">Горе</string>
<string name="display_position_bottom">Долу</string>
<string name="display_position_center">В средата (по подразбиране)</string>
<string name="display_position_center">В средата</string>
<string name="display_position_left">Наляво</string>
<string name="display_position_right">Надясно</string>
<string name="setup_tab_storage">Съхранение</string>
+8 -12
View File
@@ -55,17 +55,6 @@
<string name="frame_gen_lsfg">LSFG %1$d×</string>
<string name="frame_gen_lsfg_adaptive">LSFG Adaptivní %1$d</string>
<string name="lsfg_needs_steam">Vyžaduje Lossless Scaling na Steamu</string>
<string name="lsfg_needs_install">Nainstalujte Lossless Scaling ve Steamu nebo naimportujte Lossless.dll</string>
<string name="lsfg_import">Importovat Lossless.dll…</string>
<string name="lsfg_using_steam">Používá se kopie ze Steamu</string>
<string name="lsfg_using_import">Používá se importovaná kopie</string>
<string name="lsfg_pick_title">Vyberte Lossless.dll</string>
<string name="lsfg_imported">Lossless.dll byl importován</string>
<string name="lsfg_import_unchanged">Tento Lossless.dll se už používá</string>
<string name="lsfg_import_not_owned">Tento účet Steamu nevlastní Lossless Scaling</string>
<string name="lsfg_import_invalid">Tento soubor není Lossless.dll aplikace Lossless Scaling</string>
<string name="lsfg_import_failed">Z tohoto souboru Lossless.dll se nepodařilo připravit LSFG</string>
<string name="lsfg_problem_missing">LSFG vyžaduje Lossless Scaling ze Steamu nebo importovaný Lossless.dll</string>
<string name="lsfg_problem_failed">LSFG se nepodařilo připravit shadery z Lossless.dll</string>
<string name="hud_fg_unsupported">%1$s: nepodporováno</string>
<string name="hud_fg_failed">%1$s: chyba enginu</string>
@@ -1185,6 +1174,11 @@
<string name="agent_tools_missing">Nástroje agenta nejsou nainstalované: %1$s</string>
<string name="agent_unqueue">Neposílat</string>
<string name="agent_attach">Přiložit</string>
<string name="agent_attach_files">Soubory</string>
<string name="agent_photos_allow">Povolit přístup k fotkám</string>
<string name="agent_photos_more">Vybrat další fotky</string>
<string name="agent_photos_empty">Zatím žádné fotky</string>
<string name="agent_keyboard">Klávesnice</string>
<string name="agent_remove_attachment">Odebrat</string>
<string name="agent_model_default">Výchozí</string>
<string name="agent_effort">Náročnost uvažování</string>
@@ -3280,9 +3274,11 @@
<string name="stores_hltb_hours">%1$s h</string>
<string name="stores_hltb_minutes">%1$d min</string>
<string name="display_picture_position">Poloha obrázku</string>
<string name="display_picture_position_landscape">Poloha obrázku (Na šířku)</string>
<string name="display_picture_position_portrait">Poloha obrázku (Na výšku)</string>
<string name="display_position_top">Nahoře</string>
<string name="display_position_bottom">Dole</string>
<string name="display_position_center">Uprostřed (výchozí)</string>
<string name="display_position_center">Uprostřed</string>
<string name="display_position_left">Vlevo</string>
<string name="display_position_right">Vpravo</string>
<string name="setup_tab_storage">Úložiště</string>
+8 -12
View File
@@ -55,17 +55,6 @@
<string name="frame_gen_lsfg">LSFG %1$d×</string>
<string name="frame_gen_lsfg_adaptive">LSFG Adaptiv %1$d</string>
<string name="lsfg_needs_steam">Kræver Lossless Scaling på Steam</string>
<string name="lsfg_needs_install">Installer Lossless Scaling via Steam, eller importer Lossless.dll</string>
<string name="lsfg_import">Importer Lossless.dll…</string>
<string name="lsfg_using_steam">Bruger kopien fra Steam</string>
<string name="lsfg_using_import">Bruger en importeret kopi</string>
<string name="lsfg_pick_title">Vælg Lossless.dll</string>
<string name="lsfg_imported">Lossless.dll importeret</string>
<string name="lsfg_import_unchanged">Denne Lossless.dll er allerede i brug</string>
<string name="lsfg_import_not_owned">Lossless Scaling ejes ikke på denne Steam-konto</string>
<string name="lsfg_import_invalid">Denne fil er ikke Lossless Scalings Lossless.dll</string>
<string name="lsfg_import_failed">Kunne ikke forberede LSFG fra denne Lossless.dll</string>
<string name="lsfg_problem_missing">LSFG kræver Lossless Scaling fra Steam eller en importeret Lossless.dll</string>
<string name="lsfg_problem_failed">LSFG kunne ikke forberede sine shadere fra Lossless.dll</string>
<string name="hud_fg_unsupported">%1$s: ikke understøttet</string>
<string name="hud_fg_failed">%1$s: motoren fejlede</string>
@@ -1179,6 +1168,11 @@
<string name="agent_tools_missing">Agentens værktøjer er ikke installeret: %1$s</string>
<string name="agent_unqueue">Send ikke</string>
<string name="agent_attach">Vedhæft</string>
<string name="agent_attach_files">Filer</string>
<string name="agent_photos_allow">Tillad adgang til billeder</string>
<string name="agent_photos_more">Vælg flere billeder</string>
<string name="agent_photos_empty">Ingen billeder endnu</string>
<string name="agent_keyboard">Tastatur</string>
<string name="agent_remove_attachment">Fjern</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Ræsonneringsindsats</string>
@@ -3220,9 +3214,11 @@
<string name="stores_hltb_hours">%1$s t</string>
<string name="stores_hltb_minutes">%1$d min</string>
<string name="display_picture_position">Billedets placering</string>
<string name="display_picture_position_landscape">Billedets placering (Liggende)</string>
<string name="display_picture_position_portrait">Billedets placering (Stående)</string>
<string name="display_position_top">Øverst</string>
<string name="display_position_bottom">Nederst</string>
<string name="display_position_center">Midten (standard)</string>
<string name="display_position_center">Midten</string>
<string name="display_position_left">Venstre</string>
<string name="display_position_right">Højre</string>
<string name="setup_tab_storage">Lager</string>
+8 -12
View File
@@ -55,17 +55,6 @@
<string name="frame_gen_lsfg">LSFG %1$d×</string>
<string name="frame_gen_lsfg_adaptive">LSFG Adaptiv %1$d</string>
<string name="lsfg_needs_steam">Benötigt Lossless Scaling auf Steam</string>
<string name="lsfg_needs_install">Installiere Lossless Scaling in Steam oder importiere Lossless.dll</string>
<string name="lsfg_import">Lossless.dll importieren…</string>
<string name="lsfg_using_steam">Kopie aus Steam wird verwendet</string>
<string name="lsfg_using_import">Importierte Kopie wird verwendet</string>
<string name="lsfg_pick_title">Lossless.dll auswählen</string>
<string name="lsfg_imported">Lossless.dll importiert</string>
<string name="lsfg_import_unchanged">Diese Lossless.dll wird bereits verwendet</string>
<string name="lsfg_import_not_owned">Dieses Steam-Konto besitzt Lossless Scaling nicht</string>
<string name="lsfg_import_invalid">Diese Datei ist nicht die Lossless.dll von Lossless Scaling</string>
<string name="lsfg_import_failed">LSFG konnte aus dieser Lossless.dll nicht vorbereitet werden</string>
<string name="lsfg_problem_missing">LSFG benötigt Lossless Scaling aus Steam oder eine importierte Lossless.dll</string>
<string name="lsfg_problem_failed">LSFG konnte seine Shader nicht aus Lossless.dll vorbereiten</string>
<string name="hud_fg_unsupported">%1$s: nicht unterstützt</string>
<string name="hud_fg_failed">%1$s: Engine-Fehler</string>
@@ -1171,6 +1160,11 @@
<string name="agent_tools_missing">Agent-Werkzeuge nicht installiert: %1$s</string>
<string name="agent_unqueue">Nicht senden</string>
<string name="agent_attach">Anhängen</string>
<string name="agent_attach_files">Dateien</string>
<string name="agent_photos_allow">Zugriff auf Fotos erlauben</string>
<string name="agent_photos_more">Weitere Fotos auswählen</string>
<string name="agent_photos_empty">Noch keine Fotos</string>
<string name="agent_keyboard">Tastatur</string>
<string name="agent_remove_attachment">Entfernen</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Denkaufwand</string>
@@ -3220,9 +3214,11 @@
<string name="stores_storage_low">Zu wenig Speicher (%1$s frei, %2$s benötigt)</string>
<string name="stores_target_free_unknown">Freier Speicher unbekannt</string>
<string name="display_picture_position">Bildposition</string>
<string name="display_picture_position_landscape">Bildposition (Querformat)</string>
<string name="display_picture_position_portrait">Bildposition (Hochformat)</string>
<string name="display_position_top">Oben</string>
<string name="display_position_bottom">Unten</string>
<string name="display_position_center">Mitte (Standard)</string>
<string name="display_position_center">Mitte</string>
<string name="display_position_left">Links</string>
<string name="display_position_right">Rechts</string>
<string name="setup_tab_storage">Speicher</string>
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff. Show more