mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
78
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d7aa0e96c | ||
|
|
ad4db36fc0 | ||
|
|
a93e36045d | ||
|
|
9e680e9d65 | ||
|
|
04c5c44794 | ||
|
|
6835bc4841 | ||
|
|
98305d41bb | ||
|
|
66193d530f | ||
|
|
2a870817f3 | ||
|
|
493ef137fd | ||
|
|
028a020377 | ||
|
|
d7f0f90d29 | ||
|
|
cb571a0e0d | ||
|
|
0012f9e104 | ||
|
|
cd2177a1cb | ||
|
|
40be175d27 | ||
|
|
4a7dd76e07 | ||
|
|
0627b7afca | ||
|
|
86b8ae3c99 | ||
|
|
fe6f8638c6 | ||
|
|
26b11c6838 | ||
|
|
a9f2017aa3 | ||
|
|
bc8a970520 | ||
|
|
eefd8088dc | ||
|
|
442f1f83bf | ||
|
|
1d1c29517a | ||
|
|
be98982cfc | ||
|
|
ed763ecb9b | ||
|
|
ecbda604e2 | ||
|
|
c514c59018 | ||
|
|
b6efc4d44a | ||
|
|
b61f766b66 | ||
|
|
01c8991049 | ||
|
|
bf8faf06e1 | ||
|
|
a6ffbe7d81 | ||
|
|
34b78e2e42 | ||
|
|
bd016858c7 | ||
|
|
f761e5f1db | ||
|
|
ebb3bb6373 | ||
|
|
2aad4fbb1b | ||
|
|
b81d7d796f | ||
|
|
54e1dcb5a4 | ||
|
|
10d3b801fa | ||
|
|
00b354a40a | ||
|
|
5a18f69c7e | ||
|
|
68af03ac74 | ||
|
|
d8bb4a8751 | ||
|
|
312069603a | ||
|
|
3988f52480 | ||
|
|
59eaa0eb06 | ||
|
|
811e285834 | ||
|
|
f75cb387eb | ||
|
|
18d735b4c4 | ||
|
|
7138f95c90 | ||
|
|
8b3cc7eb15 | ||
|
|
f9eeef44ed | ||
|
|
eeb10e02fd | ||
|
|
e935263ccb | ||
|
|
673675b45e | ||
|
|
153c873898 | ||
|
|
cec2e4ed70 | ||
|
|
affb0da37f | ||
|
|
8cf1e60cc2 | ||
|
|
e3faee459f | ||
|
|
20df8b1858 | ||
|
|
4ab9635ceb | ||
|
|
2f16ea63aa | ||
|
|
151b2c304f | ||
|
|
b3e9ea5620 | ||
|
|
a4a5a88ab2 | ||
|
|
839a00a8aa | ||
|
|
a7f7a17a69 | ||
|
|
74a77c1402 | ||
|
|
673c9869f8 | ||
|
|
215ed5aaed | ||
|
|
7b91aea0fc | ||
|
|
2b424bdfe7 | ||
|
|
a4e6279a8d |
No files matched your search
@@ -128,14 +128,32 @@ jobs:
|
||||
run: |
|
||||
set -o pipefail
|
||||
mkdir -p app/build
|
||||
log=app/build/unit-tests.log
|
||||
attempt_log=app/build/unit-tests-attempt.log
|
||||
: > "$log"
|
||||
mirror=()
|
||||
central='https://(repo1\.maven\.org|repo\.maven\.apache\.org)/maven2/org/robolectric/'
|
||||
gradle_error='((Caused by: )?org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: |>[[:space:]]+)?'
|
||||
java_error='((Caused by: )?java\.io\.IOException: )?'
|
||||
# A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next.
|
||||
for wait in 60 180 0; do
|
||||
status=0
|
||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PunitTestsOnly=true -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$?
|
||||
if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://(repo\.maven\.apache\.org|repo1\.maven\.org)/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://(repo\.maven\.apache\.org|repo1\.maven\.org)/)' app/build/unit-tests.log; then
|
||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PunitTestsOnly=true -PndkVersion="$NDK_VERSION" "${mirror[@]}" 2>&1 | tee "$attempt_log" || status=$?
|
||||
cat "$attempt_log" >> "$log"
|
||||
if [ "$status" = 0 ] || [ "$wait" = 0 ]; then
|
||||
exit "$status"
|
||||
fi
|
||||
echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s"
|
||||
if [ "${#mirror[@]}" = 0 ] && grep -qE \
|
||||
-e "^[[:space:]]*${gradle_error}Could not (GET|HEAD) '?${central}[^'[:space:]]+'?\. Received status code 429([[:space:]]|$)" \
|
||||
-e "^[[:space:]]*${java_error}Server returned HTTP response code: 429 for URL: ${central}[^[:space:]]+" "$attempt_log"; then
|
||||
mirror=(-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2)
|
||||
echo "::notice::Maven Central rate limited Robolectric. Retrying unit tests with the Google Cloud mirror." | tee -a "$log"
|
||||
continue
|
||||
fi
|
||||
if ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://(repo\.maven\.apache\.org|repo1\.maven\.org)/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://(repo\.maven\.apache\.org|repo1\.maven\.org)/)' "$attempt_log"; then
|
||||
exit "$status"
|
||||
fi
|
||||
echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" | tee -a "$log"
|
||||
sleep "$wait"
|
||||
done
|
||||
|
||||
@@ -160,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 }}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -242,6 +242,9 @@ android {
|
||||
doFirst { jvmTemp.mkdirs() }
|
||||
def logTarget = providers.systemProperty('robolectric.logging').orNull
|
||||
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
|
||||
// Robolectric resolves Android SDK jars inside the test JVM independently of Gradle.
|
||||
def robolectricMirror = providers.gradleProperty('robolectricMavenMirror').orNull
|
||||
if (robolectricMirror) systemProperty 'robolectric.dependency.repo.url', robolectricMirror
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 = {},
|
||||
)
|
||||
@@ -277,6 +277,17 @@
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".agent.AgentChatActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity="${applicationId}.agentchat"
|
||||
android:resizeableActivity="true"
|
||||
android:theme="@style/AppTheme"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density">
|
||||
<layout android:defaultWidth="720dp" android:defaultHeight="800dp" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".agent.AgentStartActivity"
|
||||
android:exported="true"
|
||||
@@ -481,5 +492,69 @@
|
||||
<service android:name=".runtime.GuestWorker61" android:exported="false" android:process=":g61" />
|
||||
<service android:name=".runtime.GuestWorker62" android:exported="false" android:process=":g62" />
|
||||
<service android:name=".runtime.GuestWorker63" android:exported="false" android:process=":g63" />
|
||||
<service android:name=".runtime.GuestWorker64" android:exported="false" android:process=":g64" />
|
||||
<service android:name=".runtime.GuestWorker65" android:exported="false" android:process=":g65" />
|
||||
<service android:name=".runtime.GuestWorker66" android:exported="false" android:process=":g66" />
|
||||
<service android:name=".runtime.GuestWorker67" android:exported="false" android:process=":g67" />
|
||||
<service android:name=".runtime.GuestWorker68" android:exported="false" android:process=":g68" />
|
||||
<service android:name=".runtime.GuestWorker69" android:exported="false" android:process=":g69" />
|
||||
<service android:name=".runtime.GuestWorker70" android:exported="false" android:process=":g70" />
|
||||
<service android:name=".runtime.GuestWorker71" android:exported="false" android:process=":g71" />
|
||||
<service android:name=".runtime.GuestWorker72" android:exported="false" android:process=":g72" />
|
||||
<service android:name=".runtime.GuestWorker73" android:exported="false" android:process=":g73" />
|
||||
<service android:name=".runtime.GuestWorker74" android:exported="false" android:process=":g74" />
|
||||
<service android:name=".runtime.GuestWorker75" android:exported="false" android:process=":g75" />
|
||||
<service android:name=".runtime.GuestWorker76" android:exported="false" android:process=":g76" />
|
||||
<service android:name=".runtime.GuestWorker77" android:exported="false" android:process=":g77" />
|
||||
<service android:name=".runtime.GuestWorker78" android:exported="false" android:process=":g78" />
|
||||
<service android:name=".runtime.GuestWorker79" android:exported="false" android:process=":g79" />
|
||||
<service android:name=".runtime.GuestWorker80" android:exported="false" android:process=":g80" />
|
||||
<service android:name=".runtime.GuestWorker81" android:exported="false" android:process=":g81" />
|
||||
<service android:name=".runtime.GuestWorker82" android:exported="false" android:process=":g82" />
|
||||
<service android:name=".runtime.GuestWorker83" android:exported="false" android:process=":g83" />
|
||||
<service android:name=".runtime.GuestWorker84" android:exported="false" android:process=":g84" />
|
||||
<service android:name=".runtime.GuestWorker85" android:exported="false" android:process=":g85" />
|
||||
<service android:name=".runtime.GuestWorker86" android:exported="false" android:process=":g86" />
|
||||
<service android:name=".runtime.GuestWorker87" android:exported="false" android:process=":g87" />
|
||||
<service android:name=".runtime.GuestWorker88" android:exported="false" android:process=":g88" />
|
||||
<service android:name=".runtime.GuestWorker89" android:exported="false" android:process=":g89" />
|
||||
<service android:name=".runtime.GuestWorker90" android:exported="false" android:process=":g90" />
|
||||
<service android:name=".runtime.GuestWorker91" android:exported="false" android:process=":g91" />
|
||||
<service android:name=".runtime.GuestWorker92" android:exported="false" android:process=":g92" />
|
||||
<service android:name=".runtime.GuestWorker93" android:exported="false" android:process=":g93" />
|
||||
<service android:name=".runtime.GuestWorker94" android:exported="false" android:process=":g94" />
|
||||
<service android:name=".runtime.GuestWorker95" android:exported="false" android:process=":g95" />
|
||||
<service android:name=".runtime.GuestWorker96" android:exported="false" android:process=":g96" />
|
||||
<service android:name=".runtime.GuestWorker97" android:exported="false" android:process=":g97" />
|
||||
<service android:name=".runtime.GuestWorker98" android:exported="false" android:process=":g98" />
|
||||
<service android:name=".runtime.GuestWorker99" android:exported="false" android:process=":g99" />
|
||||
<service android:name=".runtime.GuestWorker100" android:exported="false" android:process=":g100" />
|
||||
<service android:name=".runtime.GuestWorker101" android:exported="false" android:process=":g101" />
|
||||
<service android:name=".runtime.GuestWorker102" android:exported="false" android:process=":g102" />
|
||||
<service android:name=".runtime.GuestWorker103" android:exported="false" android:process=":g103" />
|
||||
<service android:name=".runtime.GuestWorker104" android:exported="false" android:process=":g104" />
|
||||
<service android:name=".runtime.GuestWorker105" android:exported="false" android:process=":g105" />
|
||||
<service android:name=".runtime.GuestWorker106" android:exported="false" android:process=":g106" />
|
||||
<service android:name=".runtime.GuestWorker107" android:exported="false" android:process=":g107" />
|
||||
<service android:name=".runtime.GuestWorker108" android:exported="false" android:process=":g108" />
|
||||
<service android:name=".runtime.GuestWorker109" android:exported="false" android:process=":g109" />
|
||||
<service android:name=".runtime.GuestWorker110" android:exported="false" android:process=":g110" />
|
||||
<service android:name=".runtime.GuestWorker111" android:exported="false" android:process=":g111" />
|
||||
<service android:name=".runtime.GuestWorker112" android:exported="false" android:process=":g112" />
|
||||
<service android:name=".runtime.GuestWorker113" android:exported="false" android:process=":g113" />
|
||||
<service android:name=".runtime.GuestWorker114" android:exported="false" android:process=":g114" />
|
||||
<service android:name=".runtime.GuestWorker115" android:exported="false" android:process=":g115" />
|
||||
<service android:name=".runtime.GuestWorker116" android:exported="false" android:process=":g116" />
|
||||
<service android:name=".runtime.GuestWorker117" android:exported="false" android:process=":g117" />
|
||||
<service android:name=".runtime.GuestWorker118" android:exported="false" android:process=":g118" />
|
||||
<service android:name=".runtime.GuestWorker119" android:exported="false" android:process=":g119" />
|
||||
<service android:name=".runtime.GuestWorker120" android:exported="false" android:process=":g120" />
|
||||
<service android:name=".runtime.GuestWorker121" android:exported="false" android:process=":g121" />
|
||||
<service android:name=".runtime.GuestWorker122" android:exported="false" android:process=":g122" />
|
||||
<service android:name=".runtime.GuestWorker123" android:exported="false" android:process=":g123" />
|
||||
<service android:name=".runtime.GuestWorker124" android:exported="false" android:process=":g124" />
|
||||
<service android:name=".runtime.GuestWorker125" android:exported="false" android:process=":g125" />
|
||||
<service android:name=".runtime.GuestWorker126" android:exported="false" android:process=":g126" />
|
||||
<service android:name=".runtime.GuestWorker127" android:exported="false" android:process=":g127" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -8,6 +8,6 @@ target_compile_features(droiddeckxr PRIVATE cxx_std_17)
|
||||
target_compile_definitions(droiddeckxr PRIVATE XR_USE_PLATFORM_ANDROID XR_USE_GRAPHICS_API_OPENGL_ES XR_USE_TIMESPEC)
|
||||
target_compile_options(droiddeckxr PRIVATE -Wall -Wextra -Wno-missing-field-initializers -Werror=return-type)
|
||||
target_link_options(droiddeckxr PRIVATE -Wl,-z,max-page-size=16384 -uANativeActivity_onCreate)
|
||||
target_link_libraries(droiddeckxr PRIVATE droiddeckxr_glue OpenXR::openxr_loader EGL GLESv3 android log)
|
||||
target_link_libraries(droiddeckxr PRIVATE droiddeckxr_glue OpenXR::openxr_loader EGL GLESv3 android jnigraphics log)
|
||||
|
||||
target_include_directories(droiddeckxr PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../tools/vr/src)
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <jni.h>
|
||||
#include <EGL/egl.h>
|
||||
#include <GLES3/gl3.h>
|
||||
#include <android/bitmap.h>
|
||||
#include <android/log.h>
|
||||
#include <android_native_app_glue.h>
|
||||
#include <time.h>
|
||||
@@ -22,10 +23,14 @@
|
||||
#include <cerrno>
|
||||
#include <cstddef>
|
||||
#include <ctime>
|
||||
#include <pthread.h>
|
||||
#include <algorithm>
|
||||
#include "xr_tracking.h"
|
||||
#include "xr_frame_channel.h"
|
||||
#include "xr_frame_math.h"
|
||||
#include "gpu_frames.h"
|
||||
#include "xr_host.h"
|
||||
#include "xr_overlay.h"
|
||||
|
||||
static void check(XrResult result, const char *operation) {
|
||||
if (XR_FAILED(result)) throw std::runtime_error(std::string(operation) + ": " + std::to_string(result));
|
||||
@@ -37,6 +42,15 @@ struct Eye {
|
||||
std::vector<XrSwapchainImageOpenGLESKHR> images;
|
||||
};
|
||||
|
||||
struct SurfaceLayer {
|
||||
XrSwapchain swapchain = XR_NULL_HANDLE;
|
||||
jobject surface = nullptr;
|
||||
int width = 0, height = 0;
|
||||
};
|
||||
|
||||
class QuestXR;
|
||||
static QuestXR *g_runtime = nullptr;
|
||||
|
||||
class QuestXR {
|
||||
public:
|
||||
explicit QuestXR(android_app *app) : app_(app) {}
|
||||
@@ -76,21 +90,74 @@ public:
|
||||
"\"headPosition\":[%.6f,%.6f,%.6f],\"controllersActive\":[%s,%s],"
|
||||
"\"periodNs\":%lld,\"surfaceSwapchain\":%s,\"source\":\"%s\",\"guestFrames\":%lld,\"steamvrState\":%d,"
|
||||
"\"receivedFrames\":%llu,\"rejectedFrames\":%llu,\"uploadedFrames\":%llu,\"sourceFrameId\":%llu,"
|
||||
"\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u,\"error\":\"%s\"}\n",
|
||||
"\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u,"
|
||||
"\"hostVersion\":%u,\"visibleLayers\":%d,\"overlay\":%s,\"error\":\"%s\"}\n",
|
||||
(unsigned long long)frames_, (unsigned long long)rendered_, state_,
|
||||
(unsigned long long)head_.locationFlags,
|
||||
head_.pose.position.x, head_.pose.position.y, head_.pose.position.z,
|
||||
handActive_[0] ? "true" : "false", handActive_[1] ? "true" : "false",
|
||||
(long long)period_, "false", "frames",
|
||||
(long long)period_, surfaceSupported_ ? "true" : "false", "frames",
|
||||
0LL, steamvrState, (unsigned long long)(receiver_.Received() + gpuFrames_.Received()),
|
||||
(unsigned long long)(receiver_.Rejected() + gpuFrames_.Rejected()),
|
||||
(unsigned long long)uploadedFrames_, (unsigned long long)sourceHeader_.frame_id,
|
||||
(unsigned long long)gpuFrames_.Received(), (unsigned long long)gpuFrames_.Dropped(),
|
||||
(unsigned long long)verifiedFrame_, gpuChecksum_, error);
|
||||
(unsigned long long)verifiedFrame_, gpuChecksum_,
|
||||
hostBuffers_ ? DROIDDECK_XR_HOST_VERSION : 0u, visibleLayers_,
|
||||
XrOverlay::active(hostControl_) ? "true" : "false", error);
|
||||
std::fclose(file);
|
||||
std::rename(temp.c_str(), path.c_str());
|
||||
}
|
||||
|
||||
bool onXrThread() const { return pthread_equal(pthread_self(), xrThread_); }
|
||||
|
||||
int createLayer(JNIEnv *env, int width, int height) {
|
||||
if (!onXrThread() || !createSurfaceSwapchain_ || session_ == XR_NULL_HANDLE || width <= 0 || height <= 0) return -1;
|
||||
for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) {
|
||||
SurfaceLayer &layer = layers_[index];
|
||||
if (layer.swapchain) continue;
|
||||
XrSwapchainCreateInfo create{XR_TYPE_SWAPCHAIN_CREATE_INFO};
|
||||
create.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT;
|
||||
create.width = width; create.height = height;
|
||||
jobject surface = nullptr;
|
||||
XrResult result = createSurfaceSwapchain_(session_, &create, &layer.swapchain, &surface);
|
||||
if (XR_FAILED(result) || !surface) {
|
||||
__android_log_print(ANDROID_LOG_ERROR, "DroidDeckXR", "surface layer %dx%d failed: %d", width, height, result);
|
||||
if (layer.swapchain) xrDestroySwapchain(layer.swapchain);
|
||||
layer = {};
|
||||
return -1;
|
||||
}
|
||||
layer.surface = env->NewGlobalRef(surface);
|
||||
layer.width = width; layer.height = height;
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface layer %d created %dx%d", index, width, height);
|
||||
return index;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
jobject layerSurface(JNIEnv *env, int index) {
|
||||
if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS || !layers_[index].surface) return nullptr;
|
||||
return env->NewLocalRef(layers_[index].surface);
|
||||
}
|
||||
|
||||
void setOrbImage(JNIEnv *env, jobject bitmap) {
|
||||
if (!onXrThread() || !bitmap) return;
|
||||
AndroidBitmapInfo info{};
|
||||
void *pixels = nullptr;
|
||||
if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS
|
||||
|| info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) return;
|
||||
if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS) return;
|
||||
overlay_.setLogo(pixels, (int)info.width, (int)info.height, (int)info.stride);
|
||||
AndroidBitmap_unlockPixels(env, bitmap);
|
||||
}
|
||||
|
||||
void destroyLayer(JNIEnv *env, int index) {
|
||||
if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS) return;
|
||||
SurfaceLayer &layer = layers_[index];
|
||||
if (layer.swapchain) xrDestroySwapchain(layer.swapchain);
|
||||
if (layer.surface) env->DeleteGlobalRef(layer.surface);
|
||||
layer = {};
|
||||
}
|
||||
|
||||
private:
|
||||
android_app *app_;
|
||||
JNIEnv *env_ = nullptr;
|
||||
@@ -104,6 +171,20 @@ private:
|
||||
XrAction primary_ = XR_NULL_HANDLE, secondary_ = XR_NULL_HANDLE, menu_ = XR_NULL_HANDLE;
|
||||
XrAction triggerTouch_ = XR_NULL_HANDLE, stickTouch_ = XR_NULL_HANDLE, primaryTouch_ = XR_NULL_HANDLE;
|
||||
XrAction secondaryTouch_ = XR_NULL_HANDLE, thumbrestTouch_ = XR_NULL_HANDLE;
|
||||
PFN_xrCreateSwapchainAndroidSurfaceKHR createSurfaceSwapchain_ = nullptr;
|
||||
bool surfaceSupported_ = false;
|
||||
bool imageLayoutSupported_ = false;
|
||||
pthread_t xrThread_{};
|
||||
SurfaceLayer layers_[DROIDDECK_XR_HOST_LAYERS];
|
||||
DroidDeckXrHostState hostState_{};
|
||||
DroidDeckXrHostControl hostControl_{};
|
||||
bool hostBuffers_ = false;
|
||||
jmethodID hostFrameCallback_ = nullptr;
|
||||
uint64_t hostPulse_[2]{};
|
||||
int visibleLayers_ = 0;
|
||||
XrOverlay overlay_;
|
||||
Eye overlayEyes_[2];
|
||||
GLuint overlayDepth_[2]{};
|
||||
DroidDeckXrHand inputs_[2]{};
|
||||
PFN_xrConvertTimeToTimespecTimeKHR convertTime_ = nullptr;
|
||||
bool timespecSupported_ = false;
|
||||
@@ -220,6 +301,8 @@ private:
|
||||
|
||||
void initialize() {
|
||||
app_->userData = this;
|
||||
xrThread_ = pthread_self();
|
||||
g_runtime = this;
|
||||
app_->onInputEvent = [](android_app *app, AInputEvent *event) -> int32_t {
|
||||
if (AInputEvent_getType(event) != AINPUT_EVENT_TYPE_KEY || AKeyEvent_getKeyCode(event) != AKEYCODE_BACK
|
||||
|| AKeyEvent_getAction(event) != AKEY_EVENT_ACTION_UP) return 0;
|
||||
@@ -244,6 +327,10 @@ private:
|
||||
frameCallback_ = env_->GetMethodID(activityClass, "onXrFrame", "(J)V");
|
||||
statusCallback_ = env_->GetMethodID(activityClass, "onXrStatus", "()I");
|
||||
if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("XR activity bridge methods unavailable"); }
|
||||
hostFrameCallback_ = env_->GetMethodID(activityClass, "onXrHostFrame", "()V");
|
||||
jmethodID hostBuffersCallback = hostFrameCallback_ ?
|
||||
env_->GetMethodID(activityClass, "onXrHostBuffers", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V") : nullptr;
|
||||
if (env_->ExceptionCheck()) { env_->ExceptionClear(); hostFrameCallback_ = nullptr; hostBuffersCallback = nullptr; }
|
||||
env_->DeleteLocalRef(intentClass); env_->DeleteLocalRef(intent); env_->DeleteLocalRef(activityClass);
|
||||
PFN_xrInitializeLoaderKHR initializeLoader = nullptr;
|
||||
check(xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR",
|
||||
@@ -261,10 +348,21 @@ private:
|
||||
timespecSupported_ = true;
|
||||
if (!std::strcmp(extension.extensionName, XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME))
|
||||
performanceSupported_ = true;
|
||||
if (!std::strcmp(extension.extensionName, XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME))
|
||||
surfaceSupported_ = true;
|
||||
if (!std::strcmp(extension.extensionName, XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME))
|
||||
imageLayoutSupported_ = true;
|
||||
}
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface swapchain available=%d image layout=%d",
|
||||
surfaceSupported_, imageLayoutSupported_);
|
||||
// A surface swapchain's image arrives upside down, and a quad's back face is not drawn, so
|
||||
// panels need the layout flag to flip it.
|
||||
surfaceSupported_ = surfaceSupported_ && imageLayoutSupported_;
|
||||
std::vector<const char *> enabled{XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME, XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME};
|
||||
if (timespecSupported_) enabled.push_back(XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME);
|
||||
if (performanceSupported_) enabled.push_back(XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME);
|
||||
if (surfaceSupported_) enabled.push_back(XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME);
|
||||
if (surfaceSupported_) enabled.push_back(XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME);
|
||||
XrInstanceCreateInfoAndroidKHR androidInfo{XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR};
|
||||
androidInfo.applicationVM = app_->activity->vm;
|
||||
androidInfo.applicationActivity = app_->activity->clazz;
|
||||
@@ -281,6 +379,11 @@ private:
|
||||
reinterpret_cast<PFN_xrVoidFunction *>(&setPerformance_));
|
||||
if (XR_FAILED(result)) setPerformance_ = nullptr;
|
||||
}
|
||||
if (surfaceSupported_ && XR_FAILED(xrGetInstanceProcAddr(instance_, "xrCreateSwapchainAndroidSurfaceKHR",
|
||||
reinterpret_cast<PFN_xrVoidFunction *>(&createSurfaceSwapchain_)))) {
|
||||
createSurfaceSwapchain_ = nullptr;
|
||||
surfaceSupported_ = false;
|
||||
}
|
||||
if (timespecSupported_) check(xrGetInstanceProcAddr(instance_, "xrConvertTimeToTimespecTimeKHR",
|
||||
reinterpret_cast<PFN_xrVoidFunction *>(&convertTime_)), "time conversion entrypoint");
|
||||
XrSystemGetInfo systemInfo{XR_TYPE_SYSTEM_GET_INFO};
|
||||
@@ -334,6 +437,16 @@ private:
|
||||
bool gpu = !verifyPixels_ && gpuFrames_.Start(std::string(app_->activity->internalDataPath) + "/.wayland-rt/" DROIDDECK_XR_GPU_SOCKET, display_);
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "GPU frame channel available=%d", gpu);
|
||||
}
|
||||
overlay_.initialize();
|
||||
hostState_.version = DROIDDECK_XR_HOST_VERSION;
|
||||
if (hostBuffersCallback) {
|
||||
jobject state = env_->NewDirectByteBuffer(&hostState_, sizeof(hostState_));
|
||||
jobject control = env_->NewDirectByteBuffer(&hostControl_, sizeof(hostControl_));
|
||||
env_->CallVoidMethod(app_->activity->clazz, hostBuffersCallback, state, control);
|
||||
if (env_->ExceptionCheck()) { env_->ExceptionDescribe(); env_->ExceptionClear(); hostFrameCallback_ = nullptr; }
|
||||
else hostBuffers_ = true;
|
||||
env_->DeleteLocalRef(state); env_->DeleteLocalRef(control);
|
||||
}
|
||||
health();
|
||||
}
|
||||
|
||||
@@ -422,6 +535,13 @@ private:
|
||||
target.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR});
|
||||
check(xrEnumerateSwapchainImages(target.swapchain, count, &count,
|
||||
reinterpret_cast<XrSwapchainImageBaseHeader *>(target.images.data())), "images");
|
||||
Eye &overlay = overlayEyes_[eye];
|
||||
overlay.width = target.width; overlay.height = target.height;
|
||||
check(xrCreateSwapchain(session_, &create, &overlay.swapchain), "overlay swapchain");
|
||||
check(xrEnumerateSwapchainImages(overlay.swapchain, 0, &count, nullptr), "overlay image count");
|
||||
overlay.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR});
|
||||
check(xrEnumerateSwapchainImages(overlay.swapchain, count, &count,
|
||||
reinterpret_cast<XrSwapchainImageBaseHeader *>(overlay.images.data())), "overlay images");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,6 +650,12 @@ private:
|
||||
|
||||
void initializeGraphics() {
|
||||
glGenFramebuffers(1, &framebuffer_);
|
||||
glGenRenderbuffers(2, overlayDepth_);
|
||||
for (int eye = 0; eye < 2; eye++) {
|
||||
glBindRenderbuffer(GL_RENDERBUFFER, overlayDepth_[eye]);
|
||||
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, overlayEyes_[eye].width, overlayEyes_[eye].height);
|
||||
}
|
||||
glBindRenderbuffer(GL_RENDERBUFFER, 0);
|
||||
glGenVertexArrays(1, &vertexArray_);
|
||||
GLuint vertex = shader(GL_VERTEX_SHADER,
|
||||
"#version 300 es\nout vec2 uv; uniform float eye; void main(){vec2 coordinate=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));uv=vec2(coordinate.x*0.5+eye*0.5,1.0-coordinate.y);gl_Position=vec4(coordinate*2.0-1.0,0.0,1.0);}");
|
||||
@@ -584,24 +710,46 @@ private:
|
||||
if (verifyPixels_ || uploadedFrames_ % 72 == 1) health();
|
||||
}
|
||||
|
||||
void render(Eye &eye, uint32_t image) {
|
||||
void render(Eye &eye, uint32_t image, bool source, const XrPosef &pose, const XrFovf &fov, float seconds) {
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0);
|
||||
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
||||
throw std::runtime_error("Incomplete eye framebuffer");
|
||||
{
|
||||
glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST);
|
||||
glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST);
|
||||
if (source) {
|
||||
glUseProgram(sourceProgram_); glBindVertexArray(vertexArray_);
|
||||
glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sourceTexture_);
|
||||
glUniform1i(glGetUniformLocation(sourceProgram_, "source"), 0);
|
||||
glUniform1f(glGetUniformLocation(sourceProgram_, "eye"), &eye == &eyes_[1] ? 1.f : 0.f);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 3);
|
||||
} else {
|
||||
glClearColor(0.f, 0.f, 0.f, 1.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
}
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL render error");
|
||||
glFlush();
|
||||
}
|
||||
|
||||
// Lasers and the orb go in their own layer above the panels, which only the panels' depth hides.
|
||||
void renderOverlay(int index, uint32_t image, const XrPosef &pose, const XrFovf &fov, float seconds) {
|
||||
Eye &eye = overlayEyes_[index];
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0);
|
||||
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, overlayDepth_[index]);
|
||||
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
||||
throw std::runtime_error("Incomplete overlay framebuffer");
|
||||
glViewport(0, 0, eye.width, eye.height);
|
||||
glClearColor(0.f, 0.f, 0.f, 0.f); glClearDepthf(1.f);
|
||||
glDepthMask(GL_TRUE);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
overlay_.draw(pose, fov, hostControl_, hostState_, seconds);
|
||||
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL overlay error");
|
||||
glFlush();
|
||||
}
|
||||
|
||||
void pollEvents() {
|
||||
XrEventDataBuffer event{XR_TYPE_EVENT_DATA_BUFFER};
|
||||
XrResult result;
|
||||
@@ -685,6 +833,7 @@ private:
|
||||
XrViewState viewState{XR_TYPE_VIEW_STATE}; uint32_t count = 0;
|
||||
XrView views[2]{{XR_TYPE_VIEW}, {XR_TYPE_VIEW}};
|
||||
check(xrLocateViews(session_, &locate, &viewState, 2, &count, views), "xrLocateViews");
|
||||
hostFrame(frameState.predictedDisplayTime);
|
||||
publishTracking(views, frameState.predictedDisplayTime);
|
||||
if (guestAttached_) {
|
||||
timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now);
|
||||
@@ -692,29 +841,34 @@ private:
|
||||
if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("Guest frame callback failed"); }
|
||||
}
|
||||
XrCompositionLayerProjectionView projection[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}};
|
||||
bool valid = frameState.shouldRender && count == 2 &&
|
||||
const bool viewsValid = frameState.shouldRender && count == 2 &&
|
||||
(viewState.viewStateFlags & (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT))
|
||||
== (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT);
|
||||
{
|
||||
valid = valid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL;
|
||||
if (valid) for (int eye = 0; eye < 2; eye++) {
|
||||
auto source = xr_frame_view(sourceHeader_, eye);
|
||||
views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]};
|
||||
views[eye].pose.position = {source.position[0], source.position[1], source.position[2]};
|
||||
views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]};
|
||||
}
|
||||
bool valid = viewsValid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL;
|
||||
if (valid) for (int eye = 0; eye < 2; eye++) {
|
||||
auto source = xr_frame_view(sourceHeader_, eye);
|
||||
views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]};
|
||||
views[eye].pose.position = {source.position[0], source.position[1], source.position[2]};
|
||||
views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]};
|
||||
}
|
||||
std::vector<XrCompositionLayerQuad> quads;
|
||||
std::vector<XrCompositionLayerImageLayoutFB> layouts;
|
||||
if (viewsValid) collectQuads(quads, layouts);
|
||||
const bool uiOnly = !valid && viewsValid && !quads.empty();
|
||||
const bool draw = valid || uiOnly;
|
||||
const std::string capture = captureRequest();
|
||||
bool captured = valid;
|
||||
if (!capture.empty() && valid)
|
||||
captured = captureTexture(sourceTexture_, sourceHeader_.width, sourceHeader_.height, "source");
|
||||
if (valid) for (int eye = 0; eye < 2; eye++) {
|
||||
timespec clock{}; clock_gettime(CLOCK_MONOTONIC, &clock);
|
||||
const float seconds = (float)(clock.tv_sec % 3600) + clock.tv_nsec * 1e-9f;
|
||||
if (draw) for (int eye = 0; eye < 2; eye++) {
|
||||
uint32_t image = 0;
|
||||
XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
|
||||
check(xrAcquireSwapchainImage(eyes_[eye].swapchain, &acquire, &image), "acquire image");
|
||||
XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION;
|
||||
check(xrWaitSwapchainImage(eyes_[eye].swapchain, &imageWait), "wait image");
|
||||
render(eyes_[eye], image);
|
||||
render(eyes_[eye], image, valid, views[eye].pose, views[eye].fov, seconds);
|
||||
if (!capture.empty()) captured = captureTexture(eyes_[eye].images[image].image, eyes_[eye].width, eyes_[eye].height, eye ? "right" : "left") && captured;
|
||||
XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
|
||||
check(xrReleaseSwapchainImage(eyes_[eye].swapchain, &release), "release image");
|
||||
@@ -722,19 +876,143 @@ private:
|
||||
projection[eye].subImage.swapchain = eyes_[eye].swapchain;
|
||||
projection[eye].subImage.imageRect.extent = {eyes_[eye].width, eyes_[eye].height};
|
||||
}
|
||||
const bool overlay = viewsValid && hostBuffers_ && XrOverlay::active(hostControl_);
|
||||
XrCompositionLayerProjectionView overlayViews[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}};
|
||||
if (overlay) for (int eye = 0; eye < 2; eye++) {
|
||||
uint32_t image = 0;
|
||||
XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
|
||||
check(xrAcquireSwapchainImage(overlayEyes_[eye].swapchain, &acquire, &image), "acquire overlay image");
|
||||
XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION;
|
||||
check(xrWaitSwapchainImage(overlayEyes_[eye].swapchain, &imageWait), "wait overlay image");
|
||||
renderOverlay(eye, image, views[eye].pose, views[eye].fov, seconds);
|
||||
XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
|
||||
check(xrReleaseSwapchainImage(overlayEyes_[eye].swapchain, &release), "release overlay image");
|
||||
overlayViews[eye].pose = views[eye].pose; overlayViews[eye].fov = views[eye].fov;
|
||||
overlayViews[eye].subImage.swapchain = overlayEyes_[eye].swapchain;
|
||||
overlayViews[eye].subImage.imageRect.extent = {overlayEyes_[eye].width, overlayEyes_[eye].height};
|
||||
}
|
||||
XrCompositionLayerProjection layer{XR_TYPE_COMPOSITION_LAYER_PROJECTION};
|
||||
layer.space = world_; layer.viewCount = 2; layer.views = projection;
|
||||
const XrCompositionLayerBaseHeader *layers[] = {reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer)};
|
||||
XrCompositionLayerProjection overlayLayer{XR_TYPE_COMPOSITION_LAYER_PROJECTION};
|
||||
overlayLayer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
|
||||
overlayLayer.space = world_; overlayLayer.viewCount = 2; overlayLayer.views = overlayViews;
|
||||
std::vector<const XrCompositionLayerBaseHeader *> layers;
|
||||
if (draw) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
|
||||
for (auto &quad : quads) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&quad));
|
||||
if (overlay) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&overlayLayer));
|
||||
visibleLayers_ = (int)quads.size();
|
||||
XrFrameEndInfo end{XR_TYPE_FRAME_END_INFO}; end.displayTime = frameState.predictedDisplayTime;
|
||||
end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; end.layerCount = valid ? 1 : 0; end.layers = layers;
|
||||
end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
|
||||
end.layerCount = (uint32_t)layers.size(); end.layers = layers.data();
|
||||
check(xrEndFrame(session_, &end), "xrEndFrame");
|
||||
if (!capture.empty()) captureResult(capture, captured, valid, projection, frameState.predictedDisplayTime);
|
||||
frames_++; if (valid) rendered_++;
|
||||
if (frames_ % 72 == 0) {
|
||||
health();
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld",
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld layers=%d",
|
||||
(unsigned long long)frames_, (unsigned long long)rendered_, (unsigned long long)head_.locationFlags,
|
||||
handActive_[0], handActive_[1], (long long)period_);
|
||||
handActive_[0], handActive_[1], (long long)period_, visibleLayers_);
|
||||
}
|
||||
}
|
||||
|
||||
// Android surfaces are stored top row first, while OpenXR samples images bottom row first.
|
||||
void collectQuads(std::vector<XrCompositionLayerQuad> &quads, std::vector<XrCompositionLayerImageLayoutFB> &layouts) {
|
||||
if (!hostBuffers_) return;
|
||||
quads.reserve(DROIDDECK_XR_HOST_LAYERS);
|
||||
layouts.reserve(DROIDDECK_XR_HOST_LAYERS);
|
||||
const DroidDeckXrHostLayer *ordered[DROIDDECK_XR_HOST_LAYERS];
|
||||
int visible = 0;
|
||||
for (const auto &layer : hostControl_.layers) {
|
||||
if (!layer.visible || layer.id < 0 || layer.id >= DROIDDECK_XR_HOST_LAYERS || !layers_[layer.id].swapchain) continue;
|
||||
if (!(layer.width > 0.f) || !(layer.height > 0.f)) continue;
|
||||
ordered[visible++] = &layer;
|
||||
}
|
||||
std::sort(ordered, ordered + visible, [](const DroidDeckXrHostLayer *a, const DroidDeckXrHostLayer *b) { return a->order < b->order; });
|
||||
for (int index = 0; index < visible; index++) {
|
||||
const auto &layer = *ordered[index];
|
||||
const SurfaceLayer &surface = layers_[layer.id];
|
||||
XrCompositionLayerQuad quad{XR_TYPE_COMPOSITION_LAYER_QUAD};
|
||||
quad.layerFlags = (layer.flags & DROIDDECK_XR_HOST_LAYER_ALPHA) ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT : 0;
|
||||
quad.space = (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) ? view_ : world_;
|
||||
quad.eyeVisibility = XR_EYE_VISIBILITY_BOTH;
|
||||
quad.subImage.swapchain = surface.swapchain;
|
||||
quad.subImage.imageRect.extent = {surface.width, surface.height};
|
||||
quad.pose.orientation = {layer.pose.orientation[0], layer.pose.orientation[1], layer.pose.orientation[2], layer.pose.orientation[3]};
|
||||
quad.pose.position = {layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]};
|
||||
quad.size = {layer.width, layer.height};
|
||||
layouts.push_back({XR_TYPE_COMPOSITION_LAYER_IMAGE_LAYOUT_FB, nullptr, XR_COMPOSITION_LAYER_IMAGE_LAYOUT_VERTICAL_FLIP_BIT_FB});
|
||||
quad.next = &layouts.back();
|
||||
quads.push_back(quad);
|
||||
}
|
||||
}
|
||||
|
||||
// SteamVR draws its laser from the "tip" of the Quest Touch render model the driver names
|
||||
// (resources/rendermodels/oculus_quest_plus_controller_*), placed on the raw grip pose; panels
|
||||
// use the same ray so there is one laser per controller.
|
||||
static DroidDeckXrPose steamVrPointer(const XrSpaceLocation &grip, int hand) {
|
||||
const float q[4] = {grip.pose.orientation.x, grip.pose.orientation.y, grip.pose.orientation.z, grip.pose.orientation.w};
|
||||
const XrVec3 tip{hand == 0 ? 0.016694f : -0.016694f, -0.02522f, 0.024687f};
|
||||
const XrVec3 at = XrVec3{grip.pose.position.x, grip.pose.position.y, grip.pose.position.z} + rotate(q, tip);
|
||||
const float tx = -0.320613f, tw = 0.947210f;
|
||||
DroidDeckXrPose pose{};
|
||||
pose.orientation[0] = q[3] * tx + q[0] * tw;
|
||||
pose.orientation[1] = q[1] * tw + q[2] * tx;
|
||||
pose.orientation[2] = q[2] * tw - q[1] * tx;
|
||||
pose.orientation[3] = q[3] * tw - q[0] * tx;
|
||||
pose.position[0] = at.x; pose.position[1] = at.y; pose.position[2] = at.z;
|
||||
pose.flags = (uint32_t)grip.locationFlags;
|
||||
return pose;
|
||||
}
|
||||
|
||||
void hostFrame(XrTime predicted) {
|
||||
if (!hostBuffers_ || !hostFrameCallback_) return;
|
||||
hostState_.version = DROIDDECK_XR_HOST_VERSION;
|
||||
hostState_.session_state = state_;
|
||||
hostState_.flags = (surfaceSupported_ ? DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN : 0u) |
|
||||
(state_ == XR_SESSION_STATE_FOCUSED ? DROIDDECK_XR_HOST_FOCUSED : 0u);
|
||||
hostState_.frame = (int64_t)frames_;
|
||||
hostState_.display_time_ns = 0;
|
||||
if (convertTime_) {
|
||||
timespec displayTime{};
|
||||
if (XR_SUCCEEDED(convertTime_(instance_, predicted, &displayTime)))
|
||||
hostState_.display_time_ns = (int64_t)displayTime.tv_sec * 1000000000LL + displayTime.tv_nsec;
|
||||
}
|
||||
hostState_.head = posePacket(head_.pose, head_.locationFlags);
|
||||
const XrSpaceLocationFlags tracked = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT;
|
||||
for (int hand = 0; hand < 2; hand++) {
|
||||
auto &out = hostState_.hands[hand];
|
||||
out.grip = posePacket(handLocations_[hand].pose, handLocations_[hand].locationFlags);
|
||||
out.aim = steamVrPointer(handLocations_[hand], hand);
|
||||
out.trigger = inputs_[hand].trigger; out.squeeze = inputs_[hand].squeeze;
|
||||
out.stick[0] = inputs_[hand].stick[0]; out.stick[1] = inputs_[hand].stick[1];
|
||||
out.buttons = inputs_[hand].buttons;
|
||||
out.active = handActive_[hand] && (handLocations_[hand].locationFlags & tracked) == tracked;
|
||||
}
|
||||
env_->CallVoidMethod(app_->activity->clazz, hostFrameCallback_);
|
||||
if (env_->ExceptionCheck()) {
|
||||
env_->ExceptionDescribe(); env_->ExceptionClear();
|
||||
hostControl_ = {};
|
||||
return;
|
||||
}
|
||||
if (hostControl_.version != DROIDDECK_XR_HOST_VERSION) { hostControl_ = {}; return; }
|
||||
for (int hand = 0; hand < 2; hand++) {
|
||||
const auto &control = hostControl_.hands[hand];
|
||||
if (control.mask & DROIDDECK_XR_HOST_MASK_INPUT) {
|
||||
inputs_[hand].trigger = 0; inputs_[hand].squeeze = 0;
|
||||
inputs_[hand].stick[0] = inputs_[hand].stick[1] = 0;
|
||||
inputs_[hand].buttons = 0;
|
||||
}
|
||||
const auto &pulse = control.haptic;
|
||||
if (pulse.id == hostPulse_[hand]) continue;
|
||||
hostPulse_[hand] = pulse.id;
|
||||
if (state_ != XR_SESSION_STATE_FOCUSED || !handActive_[hand]
|
||||
|| pulse.duration_ns < 1000000 || pulse.duration_ns > 1000000000
|
||||
|| !std::isfinite(pulse.amplitude) || pulse.amplitude < 0 || pulse.amplitude > 1
|
||||
|| !std::isfinite(pulse.frequency) || pulse.frequency < 0) continue;
|
||||
XrHapticActionInfo info{XR_TYPE_HAPTIC_ACTION_INFO}; info.action = vibration_; info.subactionPath = hands_[hand];
|
||||
XrHapticVibration vibration{XR_TYPE_HAPTIC_VIBRATION};
|
||||
vibration.duration = pulse.duration_ns; vibration.amplitude = pulse.amplitude; vibration.frequency = pulse.frequency;
|
||||
check(xrApplyHapticFeedback(session_, &info, reinterpret_cast<XrHapticBaseHeader *>(&vibration)), "host haptics");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -749,11 +1027,17 @@ private:
|
||||
munmap(tracking_, sizeof(DroidDeckXrTracking));
|
||||
}
|
||||
if (haptics_) munmap(haptics_, sizeof(DroidDeckXrHaptics));
|
||||
g_runtime = nullptr;
|
||||
hostBuffers_ = false;
|
||||
if (display_ != EGL_NO_DISPLAY && context_ != EGL_NO_CONTEXT) {
|
||||
glDeleteFramebuffers(1, &framebuffer_); glDeleteVertexArrays(1, &vertexArray_);
|
||||
glDeleteTextures(1, &cpuTexture_); glDeleteProgram(sourceProgram_);
|
||||
glDeleteRenderbuffers(2, overlayDepth_);
|
||||
overlay_.destroy();
|
||||
}
|
||||
if (env_) for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) destroyLayer(env_, index);
|
||||
for (auto &eye : eyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain);
|
||||
for (auto &eye : overlayEyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain);
|
||||
for (auto space : handSpaces_) if (space) xrDestroySpace(space);
|
||||
if (view_) xrDestroySpace(view_); if (world_) xrDestroySpace(world_);
|
||||
if (session_) xrDestroySession(session_);
|
||||
@@ -769,6 +1053,26 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_QuestXrActivity_nativeCreateLayer(JNIEnv *env, jobject, jint width, jint height) {
|
||||
return g_runtime ? g_runtime->createLayer(env, width, height) : -1;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jobject JNICALL
|
||||
Java_com_droiddeck_launcher_QuestXrActivity_nativeLayerSurface(JNIEnv *env, jobject, jint index) {
|
||||
return g_runtime ? g_runtime->layerSurface(env, index) : nullptr;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_QuestXrActivity_nativeDestroyLayer(JNIEnv *env, jobject, jint index) {
|
||||
if (g_runtime) g_runtime->destroyLayer(env, index);
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_QuestXrActivity_nativeSetOrbImage(JNIEnv *env, jobject, jobject bitmap) {
|
||||
if (g_runtime) g_runtime->setOrbImage(env, bitmap);
|
||||
}
|
||||
|
||||
void android_main(android_app *app) {
|
||||
QuestXR runtime(app);
|
||||
try { runtime.run(); }
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "xr_tracking.h"
|
||||
|
||||
// Shared with com.droiddeck.launcher.session.xr.XrHost, which reads and writes these through direct
|
||||
// ByteBuffers by fixed offset: any layout change must bump the version and update both sides.
|
||||
#define DROIDDECK_XR_HOST_VERSION 1u
|
||||
#define DROIDDECK_XR_HOST_LAYERS 6
|
||||
|
||||
#define DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN (1u << 0)
|
||||
#define DROIDDECK_XR_HOST_FOCUSED (1u << 1)
|
||||
|
||||
#define DROIDDECK_XR_HOST_MASK_INPUT (1u << 0)
|
||||
|
||||
#define DROIDDECK_XR_HOST_LAYER_ALPHA (1u << 0)
|
||||
#define DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED (1u << 1)
|
||||
|
||||
struct DroidDeckXrHostHand {
|
||||
DroidDeckXrPose grip;
|
||||
DroidDeckXrPose aim;
|
||||
float trigger, squeeze, stick[2];
|
||||
uint32_t buttons, active;
|
||||
uint32_t reserved[2];
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostState {
|
||||
uint32_t version, session_state, flags, reserved0;
|
||||
int64_t frame, display_time_ns;
|
||||
DroidDeckXrPose head;
|
||||
DroidDeckXrHostHand hands[2];
|
||||
uint32_t reserved[8];
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostHaptic {
|
||||
uint64_t id;
|
||||
int64_t duration_ns;
|
||||
float amplitude, frequency;
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostHandControl {
|
||||
uint32_t mask;
|
||||
float laser;
|
||||
DroidDeckXrHostHaptic haptic;
|
||||
uint32_t reserved[2];
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostOrb {
|
||||
uint32_t visible;
|
||||
float progress, burst, radius;
|
||||
DroidDeckXrPose pose;
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostLayer {
|
||||
int32_t id;
|
||||
uint32_t visible, flags;
|
||||
int32_t order;
|
||||
DroidDeckXrPose pose;
|
||||
float width, height;
|
||||
uint32_t reserved[2];
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostControl {
|
||||
uint32_t version, reserved0;
|
||||
DroidDeckXrHostHandControl hands[2];
|
||||
DroidDeckXrHostOrb orb;
|
||||
DroidDeckXrHostLayer layers[DROIDDECK_XR_HOST_LAYERS];
|
||||
uint32_t reserved[8];
|
||||
};
|
||||
|
||||
static_assert(sizeof(DroidDeckXrHostHand) == 96, "XR host hand layout");
|
||||
static_assert(offsetof(DroidDeckXrHostHand, aim) == 32 && offsetof(DroidDeckXrHostHand, trigger) == 64 &&
|
||||
offsetof(DroidDeckXrHostHand, stick) == 72 && offsetof(DroidDeckXrHostHand, buttons) == 80 &&
|
||||
offsetof(DroidDeckXrHostHand, active) == 84, "XR host hand layout");
|
||||
static_assert(offsetof(DroidDeckXrHostState, flags) == 8 && offsetof(DroidDeckXrHostState, frame) == 16 &&
|
||||
offsetof(DroidDeckXrHostState, head) == 32, "XR host state layout");
|
||||
static_assert(offsetof(DroidDeckXrHostHandControl, laser) == 4 && offsetof(DroidDeckXrHostHandControl, haptic) == 8,
|
||||
"XR host hand control layout");
|
||||
static_assert(offsetof(DroidDeckXrHostHaptic, duration_ns) == 8 && offsetof(DroidDeckXrHostHaptic, amplitude) == 16,
|
||||
"XR host haptic layout");
|
||||
static_assert(offsetof(DroidDeckXrHostOrb, progress) == 4 && offsetof(DroidDeckXrHostOrb, pose) == 16, "XR host orb layout");
|
||||
static_assert(offsetof(DroidDeckXrHostLayer, order) == 12 && offsetof(DroidDeckXrHostLayer, pose) == 16 &&
|
||||
offsetof(DroidDeckXrHostLayer, width) == 48, "XR host layer layout");
|
||||
static_assert(sizeof(DroidDeckXrHostState) == 288, "XR host state layout");
|
||||
static_assert(offsetof(DroidDeckXrHostState, hands) == 64, "XR host state layout");
|
||||
static_assert(sizeof(DroidDeckXrHostHandControl) == 40, "XR host hand control layout");
|
||||
static_assert(sizeof(DroidDeckXrHostOrb) == 48, "XR host orb layout");
|
||||
static_assert(sizeof(DroidDeckXrHostLayer) == 64, "XR host layer layout");
|
||||
static_assert(offsetof(DroidDeckXrHostControl, orb) == 88, "XR host control layout");
|
||||
static_assert(offsetof(DroidDeckXrHostControl, layers) == 136, "XR host control layout");
|
||||
static_assert(sizeof(DroidDeckXrHostControl) == 552, "XR host control layout");
|
||||
@@ -0,0 +1,229 @@
|
||||
#pragma once
|
||||
#include <GLES3/gl3.h>
|
||||
#include <openxr/openxr.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include "xr_host.h"
|
||||
|
||||
struct XrVec3 { float x, y, z; };
|
||||
|
||||
static inline XrVec3 xrv(float x, float y, float z) { return {x, y, z}; }
|
||||
static inline XrVec3 operator+(XrVec3 a, XrVec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
|
||||
static inline XrVec3 operator-(XrVec3 a, XrVec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
|
||||
static inline XrVec3 operator*(XrVec3 a, float s) { return {a.x * s, a.y * s, a.z * s}; }
|
||||
static inline float dot(XrVec3 a, XrVec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
|
||||
static inline XrVec3 cross(XrVec3 a, XrVec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
|
||||
static inline XrVec3 normalized(XrVec3 a) {
|
||||
float length = std::sqrt(dot(a, a));
|
||||
return length > 1e-6f ? a * (1.f / length) : xrv(0, 0, 0);
|
||||
}
|
||||
|
||||
static inline XrVec3 rotate(const float q[4], XrVec3 v) {
|
||||
XrVec3 u{q[0], q[1], q[2]};
|
||||
float s = q[3];
|
||||
return u * (2.f * dot(u, v)) + v * (s * s - dot(u, u)) + cross(u, v) * (2.f * s);
|
||||
}
|
||||
|
||||
class XrOverlay {
|
||||
public:
|
||||
void initialize() {
|
||||
GLuint vertex = compile(GL_VERTEX_SHADER,
|
||||
"#version 300 es\nlayout(location=0) in vec3 position; layout(location=1) in vec2 coordinate;"
|
||||
"uniform mat4 viewProjection; out vec2 uv;"
|
||||
"void main(){uv=coordinate;gl_Position=viewProjection*vec4(position,1.0);}");
|
||||
GLuint fragment = compile(GL_FRAGMENT_SHADER,
|
||||
"#version 300 es\nprecision highp float; in vec2 uv; uniform int mode; uniform float progress, burst, time;"
|
||||
"uniform vec3 color; uniform sampler2D logo; uniform int hasLogo; out vec4 outputColor;"
|
||||
"void main(){"
|
||||
" if(mode==0){float across=1.0-abs(uv.y); float a=smoothstep(0.0,0.7,across)*mix(0.95,0.35,uv.x);"
|
||||
" outputColor=vec4(color*a,a);return;}"
|
||||
" if(mode==1){float r=length(uv); float a=1.0-smoothstep(0.55,1.0,r); outputColor=vec4(vec3(1.0)*a,a);return;}"
|
||||
" float r=length(uv); vec3 c=vec3(0.0); float a=0.0;"
|
||||
" float pulse=0.5+0.5*sin(time*6.0);"
|
||||
" float glow=exp(-pow(max(r-0.45,0.0)*6.0,2.0))*(0.25+0.2*pulse)*step(0.5,r); c+=color*glow; a=max(a,glow*0.7);"
|
||||
" if(hasLogo==1&&r<0.52){vec4 l=texture(logo,vec2(0.5+uv.x/1.04,0.5-uv.y/1.04)); c=c*(1.0-l.a)+l.rgb; a=a*(1.0-l.a)+l.a;}"
|
||||
" else if(r<0.5){float core=1.0-smoothstep(0.46,0.5,r); c+=color*core; a=max(a,core);}"
|
||||
" float angle=atan(uv.x,uv.y); float sweep=(angle<0.0?angle+6.2831853:angle)/6.2831853;"
|
||||
" float band=1.0-smoothstep(0.0,0.03,abs(r-0.64));"
|
||||
" float track=band*0.25; float fill=band*step(sweep,progress);"
|
||||
" c+=vec3(1.0)*track+color*fill*1.4; a=max(a,max(track,fill));"
|
||||
" if(burst>0.0){float ring=(1.0-smoothstep(0.0,0.06,abs(r-(0.64+burst*0.3))))*(1.0-burst); c+=color*ring*2.0; a=max(a,ring);}"
|
||||
" a=clamp(a,0.0,1.0); outputColor=vec4(c*a,a);"
|
||||
"}");
|
||||
program_ = glCreateProgram();
|
||||
glAttachShader(program_, vertex); glAttachShader(program_, fragment);
|
||||
glLinkProgram(program_); glDeleteShader(vertex); glDeleteShader(fragment);
|
||||
GLint linked = 0; glGetProgramiv(program_, GL_LINK_STATUS, &linked);
|
||||
if (!linked) throw std::runtime_error("Overlay shader link failed");
|
||||
viewProjection_ = glGetUniformLocation(program_, "viewProjection");
|
||||
mode_ = glGetUniformLocation(program_, "mode");
|
||||
progress_ = glGetUniformLocation(program_, "progress");
|
||||
burst_ = glGetUniformLocation(program_, "burst");
|
||||
time_ = glGetUniformLocation(program_, "time");
|
||||
color_ = glGetUniformLocation(program_, "color");
|
||||
logoSampler_ = glGetUniformLocation(program_, "logo");
|
||||
hasLogo_ = glGetUniformLocation(program_, "hasLogo");
|
||||
glGenVertexArrays(1, &vertexArray_);
|
||||
glGenBuffers(1, &buffer_);
|
||||
glBindVertexArray(vertexArray_);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, buffer_);
|
||||
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 5 * 6, nullptr, GL_DYNAMIC_DRAW);
|
||||
glEnableVertexAttribArray(0);
|
||||
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, nullptr);
|
||||
glEnableVertexAttribArray(1);
|
||||
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, reinterpret_cast<void *>(sizeof(float) * 3));
|
||||
glBindVertexArray(0);
|
||||
}
|
||||
|
||||
/** [pixels] are premultiplied RGBA rows, top row first, as an Android ARGB_8888 bitmap holds them. */
|
||||
void setLogo(const void *pixels, int width, int height, int stride) {
|
||||
if (!logo_) glGenTextures(1, &logo_);
|
||||
glBindTexture(GL_TEXTURE_2D, logo_);
|
||||
glPixelStorei(GL_UNPACK_ROW_LENGTH, stride / 4);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
|
||||
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
|
||||
glGenerateMipmap(GL_TEXTURE_2D);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
}
|
||||
|
||||
void destroy() {
|
||||
if (logo_) glDeleteTextures(1, &logo_);
|
||||
logo_ = 0;
|
||||
if (program_) glDeleteProgram(program_);
|
||||
if (buffer_) glDeleteBuffers(1, &buffer_);
|
||||
if (vertexArray_) glDeleteVertexArrays(1, &vertexArray_);
|
||||
program_ = buffer_ = vertexArray_ = 0;
|
||||
}
|
||||
|
||||
static bool active(const DroidDeckXrHostControl &control) {
|
||||
return control.orb.visible || control.hands[0].laser > 0.f || control.hands[1].laser > 0.f;
|
||||
}
|
||||
|
||||
void draw(const XrPosef &eye, const XrFovf &fov, const DroidDeckXrHostControl &control,
|
||||
const DroidDeckXrHostState &state, float seconds) {
|
||||
if (!active(control)) return;
|
||||
float matrix[16];
|
||||
viewProjectionOf(eye, fov, matrix);
|
||||
const float eyeOrientation[4] = {eye.orientation.x, eye.orientation.y, eye.orientation.z, eye.orientation.w};
|
||||
const XrVec3 eyePosition{eye.position.x, eye.position.y, eye.position.z};
|
||||
glUseProgram(program_);
|
||||
glUniformMatrix4fv(viewProjection_, 1, GL_FALSE, matrix);
|
||||
glUniform3f(color_, 0.12f, 0.62f, 1.0f);
|
||||
glUniform1f(time_, seconds);
|
||||
glBindVertexArray(vertexArray_);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, buffer_);
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
glDepthFunc(GL_LEQUAL);
|
||||
glDepthMask(GL_TRUE);
|
||||
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
|
||||
glDisable(GL_BLEND);
|
||||
glUniform1i(mode_, 0);
|
||||
for (const auto &layer : control.layers) {
|
||||
if (!layer.visible || !(layer.width > 0.f) || !(layer.height > 0.f)) continue;
|
||||
if (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) continue;
|
||||
XrVec3 center{layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]};
|
||||
XrVec3 right = rotate(layer.pose.orientation, xrv(layer.width / 2.f, 0, 0));
|
||||
XrVec3 up = rotate(layer.pose.orientation, xrv(0, layer.height / 2.f, 0));
|
||||
quad(center - right - up, center + right - up, center - right + up, center + right + up, 0.f, 1.f);
|
||||
}
|
||||
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
|
||||
glDepthMask(GL_FALSE);
|
||||
glEnable(GL_BLEND);
|
||||
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
|
||||
for (int hand = 0; hand < 2; hand++) {
|
||||
float length = control.hands[hand].laser;
|
||||
if (!(length > 0.f) || !state.hands[hand].active) continue;
|
||||
const auto &aim = state.hands[hand].aim;
|
||||
XrVec3 start{aim.position[0], aim.position[1], aim.position[2]};
|
||||
XrVec3 direction = normalized(rotate(aim.orientation, xrv(0, 0, -1)));
|
||||
XrVec3 end = start + direction * std::max(length - 0.004f, 0.f);
|
||||
XrVec3 side = normalized(cross(direction, eyePosition - start)) * 0.0022f;
|
||||
glUniform1i(mode_, 0);
|
||||
quad(start - side, start + side, end - side, end + side, 0.f, 1.f);
|
||||
XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * 0.007f;
|
||||
XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * 0.007f;
|
||||
glUniform1i(mode_, 1);
|
||||
billboard(end + normalized(eyePosition - end) * 0.008f, right, up);
|
||||
}
|
||||
if (control.orb.visible) {
|
||||
const auto &pose = control.orb.pose;
|
||||
XrVec3 center{pose.position[0], pose.position[1], pose.position[2]};
|
||||
float size = control.orb.radius * 1.25f;
|
||||
XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * size;
|
||||
XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * size;
|
||||
glUniform1i(mode_, 2);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, logo_);
|
||||
glUniform1i(logoSampler_, 0);
|
||||
glUniform1i(hasLogo_, logo_ ? 1 : 0);
|
||||
glUniform1f(progress_, control.orb.progress);
|
||||
glUniform1f(burst_, control.orb.burst);
|
||||
billboard(center, right, up);
|
||||
}
|
||||
glBindVertexArray(0);
|
||||
glDisable(GL_BLEND);
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
glDepthMask(GL_TRUE);
|
||||
}
|
||||
|
||||
private:
|
||||
GLuint program_ = 0, buffer_ = 0, vertexArray_ = 0, logo_ = 0;
|
||||
GLint viewProjection_ = -1, mode_ = -1, progress_ = -1, burst_ = -1, time_ = -1, color_ = -1;
|
||||
GLint logoSampler_ = -1, hasLogo_ = -1;
|
||||
|
||||
static GLuint compile(GLenum type, const char *text) {
|
||||
GLuint handle = glCreateShader(type);
|
||||
glShaderSource(handle, 1, &text, nullptr); glCompileShader(handle);
|
||||
GLint success = 0; glGetShaderiv(handle, GL_COMPILE_STATUS, &success);
|
||||
if (!success) { glDeleteShader(handle); throw std::runtime_error("Overlay shader compile failed"); }
|
||||
return handle;
|
||||
}
|
||||
|
||||
void billboard(XrVec3 center, XrVec3 right, XrVec3 up) {
|
||||
quadUv(center - right - up, center + right - up, center - right + up, center + right + up);
|
||||
}
|
||||
|
||||
void quad(XrVec3 a0, XrVec3 a1, XrVec3 b0, XrVec3 b1, float from, float to) {
|
||||
const float vertices[] = {
|
||||
a0.x, a0.y, a0.z, from, -1, a1.x, a1.y, a1.z, from, 1, b0.x, b0.y, b0.z, to, -1,
|
||||
b0.x, b0.y, b0.z, to, -1, a1.x, a1.y, a1.z, from, 1, b1.x, b1.y, b1.z, to, 1};
|
||||
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 6);
|
||||
}
|
||||
|
||||
void quadUv(XrVec3 bottomLeft, XrVec3 bottomRight, XrVec3 topLeft, XrVec3 topRight) {
|
||||
const float vertices[] = {
|
||||
bottomLeft.x, bottomLeft.y, bottomLeft.z, -1, -1, bottomRight.x, bottomRight.y, bottomRight.z, 1, -1,
|
||||
topLeft.x, topLeft.y, topLeft.z, -1, 1, topLeft.x, topLeft.y, topLeft.z, -1, 1,
|
||||
bottomRight.x, bottomRight.y, bottomRight.z, 1, -1, topRight.x, topRight.y, topRight.z, 1, 1};
|
||||
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 6);
|
||||
}
|
||||
|
||||
static void viewProjectionOf(const XrPosef &pose, const XrFovf &fov, float out[16]) {
|
||||
const float q[4] = {pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w};
|
||||
XrVec3 xAxis = rotate(q, xrv(1, 0, 0)), yAxis = rotate(q, xrv(0, 1, 0)), zAxis = rotate(q, xrv(0, 0, 1));
|
||||
XrVec3 position{pose.position.x, pose.position.y, pose.position.z};
|
||||
float view[16] = {
|
||||
xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0,
|
||||
-dot(xAxis, position), -dot(yAxis, position), -dot(zAxis, position), 1};
|
||||
const float nearZ = 0.05f, farZ = 100.f;
|
||||
float left = std::tan(fov.angleLeft), right = std::tan(fov.angleRight);
|
||||
float up = std::tan(fov.angleUp), down = std::tan(fov.angleDown);
|
||||
float width = right - left, height = up - down;
|
||||
float projection[16] = {
|
||||
2.f / width, 0, 0, 0, 0, 2.f / height, 0, 0,
|
||||
(right + left) / width, (up + down) / height, -(farZ + nearZ) / (farZ - nearZ), -1,
|
||||
0, 0, -2.f * farZ * nearZ / (farZ - nearZ), 0};
|
||||
for (int column = 0; column < 4; column++)
|
||||
for (int row = 0; row < 4; row++) {
|
||||
float sum = 0;
|
||||
for (int k = 0; k < 4; k++) sum += projection[k * 4 + row] * view[column * 4 + k];
|
||||
out[column * 4 + row] = sum;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -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.
|
||||
@@ -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);
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <stdarg.h>
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/timerfd.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/sysmacros.h>
|
||||
@@ -23,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"
|
||||
@@ -210,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;
|
||||
@@ -826,6 +836,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)) {
|
||||
@@ -841,18 +852,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;
|
||||
@@ -865,6 +879,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;
|
||||
@@ -873,6 +888,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) {
|
||||
@@ -1185,6 +1202,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;
|
||||
@@ -1450,6 +1468,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();
|
||||
@@ -1461,6 +1480,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);
|
||||
@@ -1473,6 +1494,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) {
|
||||
@@ -1537,6 +1559,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);
|
||||
@@ -1548,6 +1571,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) {
|
||||
@@ -1699,6 +1724,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);
|
||||
@@ -1708,6 +1937,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;
|
||||
|
||||
@@ -4582,11 +4812,15 @@ static void output_resized(void) {
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
|
||||
static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
static void dispatch_input(int fd, int remaining) {
|
||||
struct input_msg m;
|
||||
int vsync = 0;
|
||||
int64_t vsync_ns = 0;
|
||||
while (read(fd, &m, sizeof(m)) == (ssize_t)sizeof(m)) {
|
||||
while (remaining != 0) {
|
||||
ssize_t n = read(fd, &m, sizeof(m));
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
if (n != (ssize_t)sizeof(m)) break;
|
||||
if (remaining > 0) --remaining;
|
||||
switch (m.type) {
|
||||
case 1: deliver_key(&m); break;
|
||||
case 2: pointer_event(m.p1, m.p2, 0, 0); break;
|
||||
@@ -4628,9 +4862,27 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
if (vsync) on_vsync(vsync_ns);
|
||||
}
|
||||
|
||||
static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
dispatch_input(fd, -1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void droiddeck_dispatch_pending_input(void) {
|
||||
int fd = g_input_pipe[0];
|
||||
if (fd < 0) return;
|
||||
|
||||
int bytes;
|
||||
int result;
|
||||
do {
|
||||
result = ioctl(fd, FIONREAD, &bytes);
|
||||
} while (result < 0 && errno == EINTR);
|
||||
if (result == 0 && bytes >= (int)sizeof(struct input_msg)) {
|
||||
dispatch_input(fd, bytes / (int)sizeof(struct input_msg));
|
||||
}
|
||||
}
|
||||
|
||||
void droiddeck_wayland_set_scale_mode(int mode, int alignment) {
|
||||
if (g_input_pipe[1] < 0) {
|
||||
vk_present_set_scale_mode(mode, alignment);
|
||||
@@ -4767,6 +5019,11 @@ void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y)
|
||||
|
||||
void droiddeck_inject_key(uint32_t evdev, int pressed) { key_event(evdev, pressed); }
|
||||
|
||||
int droiddeck_key_is_down(uint32_t evdev) {
|
||||
return evdev < sizeof(g_keys_down) * 8 &&
|
||||
(g_keys_down[evdev >> 3] & (1u << (evdev & 7))) != 0;
|
||||
}
|
||||
|
||||
|
||||
static struct wl_event_source *g_stats_timer;
|
||||
volatile unsigned g_zero_copy_last;
|
||||
@@ -4776,6 +5033,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();
|
||||
@@ -4784,7 +5042,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);
|
||||
}
|
||||
@@ -4985,6 +5244,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);
|
||||
|
||||
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <limits.h>
|
||||
#include <linux/input-event-codes.h>
|
||||
#include <android/log.h>
|
||||
#include "droiddeck_ext.h"
|
||||
#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 };
|
||||
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 };
|
||||
|
||||
struct host_msg {
|
||||
enum host_kind kind;
|
||||
@@ -23,6 +25,32 @@ static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct host_msg *g_head, *g_tail;
|
||||
static int g_wake[2] = {-1, -1};
|
||||
|
||||
/* Compositor-thread-only fallback ordering state. */
|
||||
static int g_pending_token, g_pending_submit;
|
||||
static int g_fallback_failed;
|
||||
static int g_next_token = 1;
|
||||
static struct host_msg *g_deferred_head, *g_deferred_tail;
|
||||
static size_t g_deferred_count, g_deferred_bytes;
|
||||
static int g_deferred_overflow;
|
||||
static int g_completed_token, g_completed_result;
|
||||
|
||||
#define DROIDDECK_EVDEV_KEY_MAX 768
|
||||
#define DROIDDECK_TEXT_DEFERRED_LIMIT 256
|
||||
#define DROIDDECK_TEXT_DEFERRED_BYTES (256 * 1024)
|
||||
static unsigned char g_ordered_key_down[DROIDDECK_EVDEV_KEY_MAX];
|
||||
|
||||
void droiddeck_host_text_input_fallback_complete(int token, int result) {
|
||||
pthread_mutex_lock(&g_mu);
|
||||
g_completed_token = token;
|
||||
g_completed_result = result;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (g_wake[1] >= 0) {
|
||||
char c = 1;
|
||||
ssize_t n = write(g_wake[1], &c, 1);
|
||||
(void)n;
|
||||
}
|
||||
}
|
||||
|
||||
static void host_post(enum host_kind kind, const char *text, size_t len, int a, int b) {
|
||||
struct host_msg *m = calloc(1, sizeof(*m));
|
||||
if (!m) return;
|
||||
@@ -51,6 +79,9 @@ void droiddeck_host_clipboard_text(const char *utf8, int len) {
|
||||
void droiddeck_host_text_commit(const char *utf8, int len) {
|
||||
host_post(HOST_TEXT_COMMIT, utf8, len > 0 ? (size_t)len : 0, 0, 0);
|
||||
}
|
||||
void droiddeck_host_text_commit_and_submit(const char *utf8, int len) {
|
||||
if (len > 0) host_post(HOST_TEXT_COMMIT, utf8, (size_t)len, 1, 0);
|
||||
}
|
||||
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end) {
|
||||
host_post(HOST_TEXT_PREEDIT, utf8, len > 0 ? (size_t)len : 0, cursor_begin, cursor_end);
|
||||
}
|
||||
@@ -63,23 +94,173 @@ void droiddeck_host_zero_copy(int on, int live) {
|
||||
void droiddeck_host_hdr_output(int on) {
|
||||
host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0);
|
||||
}
|
||||
void droiddeck_host_key(int evdev, int state) {
|
||||
host_post(HOST_KEY, NULL, 0, evdev, state);
|
||||
}
|
||||
|
||||
void droiddeck_host_select_game_field(int copy) {
|
||||
host_post(HOST_SELECT_GAME_FIELD, NULL, 0, copy, 0);
|
||||
}
|
||||
|
||||
static void tap_unheld_key(uint32_t key) {
|
||||
if (droiddeck_key_is_down(key)) return;
|
||||
droiddeck_inject_key(key, 1);
|
||||
droiddeck_inject_key(key, 0);
|
||||
}
|
||||
|
||||
static void select_game_field(int copy) {
|
||||
/* Apply pending raw releases before using the compositor's held-key state. */
|
||||
droiddeck_dispatch_pending_input();
|
||||
int temporary_ctrl = !droiddeck_key_is_down(KEY_LEFTCTRL) && !droiddeck_key_is_down(KEY_RIGHTCTRL);
|
||||
if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 1);
|
||||
tap_unheld_key(KEY_A);
|
||||
if (copy) tap_unheld_key(KEY_C);
|
||||
if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 0);
|
||||
}
|
||||
|
||||
static void restore_deferred_to_front(void) {
|
||||
if (g_deferred_head) {
|
||||
g_deferred_tail->next = g_head;
|
||||
if (!g_head) g_tail = g_deferred_tail;
|
||||
g_head = g_deferred_head;
|
||||
g_deferred_head = g_deferred_tail = NULL;
|
||||
g_deferred_count = g_deferred_bytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Only suppress the queued submit for this commit, not a later commit or a held-key release. */
|
||||
static void discard_queued_submit(void) {
|
||||
struct host_msg *prev = NULL;
|
||||
struct host_msg *m = g_head;
|
||||
int enter_held = g_ordered_key_down[KEY_ENTER];
|
||||
int key_pad_enter_held = g_ordered_key_down[KEY_KPENTER];
|
||||
while (m) {
|
||||
int soft_submit = 0;
|
||||
if (m->kind == HOST_TEXT_COMMIT) {
|
||||
if (m->a || m->len == 0) break;
|
||||
soft_submit = 1;
|
||||
size_t i = 0;
|
||||
for (; i < m->len; i++) {
|
||||
char c = m->text[i];
|
||||
if (c != '\r' && c != '\n') soft_submit = 0;
|
||||
if (c != '\r' && c != '\n' && c != '\b' && c != '\t' && c != 0x7f) break;
|
||||
}
|
||||
if (i != m->len) break;
|
||||
}
|
||||
struct host_msg *next = m->next;
|
||||
int *held = m->a == KEY_ENTER ? &enter_held : m->a == KEY_KPENTER ? &key_pad_enter_held : NULL;
|
||||
if (soft_submit || (m->kind == HOST_KEY && held && (m->b != 0 || !*held))) {
|
||||
if (prev) prev->next = next; else g_head = next;
|
||||
if (g_tail == m) g_tail = prev;
|
||||
free(m->text);
|
||||
free(m);
|
||||
} else {
|
||||
if (m->kind == HOST_KEY && held) *held = 0;
|
||||
prev = m;
|
||||
}
|
||||
m = next;
|
||||
}
|
||||
}
|
||||
|
||||
static int release_held_key(const struct host_msg *m) {
|
||||
int k = m->a;
|
||||
if (m->kind != HOST_KEY || m->b != 0 || k < 0 || k >= DROIDDECK_EVDEV_KEY_MAX ||
|
||||
!g_ordered_key_down[k]) return 0;
|
||||
g_ordered_key_down[k] = 0;
|
||||
droiddeck_inject_key((uint32_t)k, 0);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void discard_deferred_input(void) {
|
||||
struct host_msg *m = g_deferred_head;
|
||||
while (m) {
|
||||
struct host_msg *next = m->next;
|
||||
release_held_key(m);
|
||||
free(m->text);
|
||||
free(m);
|
||||
m = next;
|
||||
}
|
||||
g_deferred_head = g_deferred_tail = NULL;
|
||||
g_deferred_count = g_deferred_bytes = 0;
|
||||
}
|
||||
|
||||
static int on_wake(int fd, uint32_t mask, void *data) {
|
||||
char buf[64];
|
||||
while (read(fd, buf, sizeof(buf)) > 0) {}
|
||||
for (;;) {
|
||||
int deferred = 0, submit = 0;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
if (g_pending_token != 0 && g_completed_token == g_pending_token) {
|
||||
int result = g_completed_result;
|
||||
g_completed_token = 0;
|
||||
restore_deferred_to_front();
|
||||
if (result != DROIDDECK_TEXT_DELIVERED) discard_queued_submit();
|
||||
if (result == DROIDDECK_TEXT_UNRESOLVED) {
|
||||
g_fallback_failed = 1;
|
||||
} else {
|
||||
if (result == DROIDDECK_TEXT_DELIVERED) submit = g_pending_submit;
|
||||
g_pending_submit = 0;
|
||||
g_pending_token = 0;
|
||||
g_fallback_failed = 0;
|
||||
g_deferred_overflow = 0;
|
||||
}
|
||||
}
|
||||
struct host_msg *m = g_head;
|
||||
if (m) { g_head = m->next; if (!g_head) g_tail = NULL; }
|
||||
if (m) { g_head = m->next; if (!g_head) g_tail = NULL; m->next = NULL; }
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (submit) tap_unheld_key(KEY_ENTER);
|
||||
if (!m) break;
|
||||
if (g_pending_token != 0 &&
|
||||
(m->kind == HOST_TEXT_COMMIT || m->kind == HOST_TEXT_PREEDIT ||
|
||||
m->kind == HOST_TEXT_DELETE || m->kind == HOST_KEY ||
|
||||
m->kind == HOST_SELECT_GAME_FIELD)) {
|
||||
int released_during_recovery = g_fallback_failed && release_held_key(m);
|
||||
if (released_during_recovery || g_deferred_overflow ||
|
||||
g_deferred_count == DROIDDECK_TEXT_DEFERRED_LIMIT ||
|
||||
m->len > DROIDDECK_TEXT_DEFERRED_BYTES - g_deferred_bytes) {
|
||||
if (!released_during_recovery) {
|
||||
/* An incomplete queue could replay a submit or lose a paired release. */
|
||||
if (!g_deferred_overflow)
|
||||
droiddeck_log("text-input", "deferred input exceeded the recovery queue limit");
|
||||
discard_deferred_input();
|
||||
release_held_key(m);
|
||||
g_deferred_overflow = 1;
|
||||
}
|
||||
free(m->text);
|
||||
free(m);
|
||||
continue;
|
||||
}
|
||||
if (g_deferred_tail) g_deferred_tail->next = m; else g_deferred_head = m;
|
||||
g_deferred_tail = m;
|
||||
g_deferred_count++;
|
||||
g_deferred_bytes += m->len;
|
||||
deferred = 1;
|
||||
}
|
||||
if (deferred) continue;
|
||||
switch (m->kind) {
|
||||
case HOST_CLIPBOARD:
|
||||
clipboard_host_text(m->text, m->len);
|
||||
m->text = NULL;
|
||||
break;
|
||||
case HOST_TEXT_COMMIT:
|
||||
text_input_host_commit(m->text ? m->text : "", m->len);
|
||||
if (!text_input_host_commit(m->text ? m->text : "", m->len)) {
|
||||
int token = 0;
|
||||
if (g_next_token == INT_MAX) g_next_token = 1;
|
||||
else g_next_token++;
|
||||
token = g_next_token;
|
||||
g_pending_token = 0;
|
||||
if (droiddeck_on_text_input_fallback(m->text ? m->text : "", (int)m->len, token)) {
|
||||
g_pending_token = token;
|
||||
g_pending_submit = m->a;
|
||||
} else {
|
||||
droiddeck_log("text-input", "fallback had no accepting Android listener");
|
||||
pthread_mutex_lock(&g_mu);
|
||||
discard_queued_submit();
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
}
|
||||
} else if (m->a) {
|
||||
tap_unheld_key(KEY_ENTER);
|
||||
}
|
||||
break;
|
||||
case HOST_TEXT_PREEDIT:
|
||||
text_input_host_preedit(m->text ? m->text : "", m->len, m->a, m->b);
|
||||
@@ -93,6 +274,19 @@ static int on_wake(int fd, uint32_t mask, void *data) {
|
||||
case HOST_HDR_OUTPUT:
|
||||
droiddeck_color_set_output(m->a);
|
||||
break;
|
||||
case HOST_SELECT_GAME_FIELD:
|
||||
select_game_field(m->a);
|
||||
break;
|
||||
case HOST_KEY:
|
||||
if (m->b == 1) {
|
||||
int k = m->a;
|
||||
if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 1;
|
||||
} else if (m->b == 0) {
|
||||
int k = m->a;
|
||||
if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 0;
|
||||
}
|
||||
droiddeck_inject_key((uint32_t)m->a, m->b);
|
||||
break;
|
||||
}
|
||||
free(m->text);
|
||||
free(m);
|
||||
|
||||
@@ -15,22 +15,34 @@ struct wl_display *droiddeck_get_display(void);
|
||||
struct wl_resource *droiddeck_ime_target(void);
|
||||
void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y);
|
||||
void droiddeck_inject_key(uint32_t evdev, int pressed);
|
||||
int droiddeck_key_is_down(uint32_t evdev);
|
||||
void droiddeck_dispatch_pending_input(void);
|
||||
|
||||
void droiddeck_on_clipboard_text(const char *utf8, int len);
|
||||
int droiddeck_on_text_input_fallback(const char *utf8, int len, int token);
|
||||
void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h);
|
||||
|
||||
|
||||
void droiddeck_host_clipboard_text(const char *utf8, int len);
|
||||
void droiddeck_host_text_commit(const char *utf8, int len);
|
||||
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_hdr_output(int on);
|
||||
void droiddeck_host_key(int evdev, int state);
|
||||
void droiddeck_host_select_game_field(int copy);
|
||||
enum droiddeck_text_input_result {
|
||||
DROIDDECK_TEXT_NOT_DELIVERED = 0,
|
||||
DROIDDECK_TEXT_DELIVERED = 1,
|
||||
DROIDDECK_TEXT_UNRESOLVED = 2,
|
||||
};
|
||||
void droiddeck_host_text_input_fallback_complete(int token, int result);
|
||||
|
||||
void clipboard_init(struct wl_display *display);
|
||||
void clipboard_host_text(char *utf8, size_t len);
|
||||
void text_input_init(struct wl_display *display);
|
||||
void text_input_host_commit(const char *utf8, size_t len);
|
||||
int text_input_host_commit(const char *utf8, size_t len);
|
||||
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end);
|
||||
void text_input_host_delete(int before, int after);
|
||||
void toplevel_icon_init(struct wl_display *display);
|
||||
|
||||
@@ -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, ®ion);
|
||||
|
||||
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, ®ion);
|
||||
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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -68,6 +68,7 @@ static jmethodID g_on_compositor_frame;
|
||||
static jmethodID g_on_game_program;
|
||||
static jmethodID g_on_pointer_lock;
|
||||
static jmethodID g_on_clipboard;
|
||||
static jmethodID g_on_text_input_fallback;
|
||||
static jmethodID g_on_text_input;
|
||||
static jmethodID g_on_overlay_planes;
|
||||
static jmethodID g_on_refresh_target;
|
||||
@@ -92,6 +93,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
|
||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; }
|
||||
g_on_pointer_lock = (*env)->GetStaticMethodID(env, g_compositor_cls, "onPointerLock", "(ZII)V");
|
||||
g_on_clipboard = (*env)->GetStaticMethodID(env, g_compositor_cls, "onClipboardText", "([B)V");
|
||||
g_on_text_input_fallback = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInputFallback",
|
||||
"([BI)Z");
|
||||
g_on_text_input = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInput",
|
||||
"(ZLjava/lang/String;IIII)V");
|
||||
g_on_overlay_planes = (*env)->GetStaticMethodID(env, g_compositor_cls, "onOverlayPlanes", "(I)V");
|
||||
@@ -203,6 +206,20 @@ void droiddeck_on_clipboard_text(const char *utf8, int len) {
|
||||
(*env)->DeleteLocalRef(env, arr);
|
||||
}
|
||||
|
||||
int droiddeck_on_text_input_fallback(const char *utf8, int len, int token) {
|
||||
JNIEnv *env;
|
||||
if (len <= 0 || token <= 0 || !utf8 || !g_compositor_cls || !g_on_text_input_fallback || !(env = thread_env()))
|
||||
return 0;
|
||||
jbyteArray arr = (*env)->NewByteArray(env, len);
|
||||
if (!arr) { (*env)->ExceptionClear(env); return 0; }
|
||||
(*env)->SetByteArrayRegion(env, arr, 0, len, (const jbyte *)utf8);
|
||||
jboolean accepted = (*env)->CallStaticBooleanMethod(env, g_compositor_cls, g_on_text_input_fallback, arr,
|
||||
(jint)token);
|
||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); accepted = JNI_FALSE; }
|
||||
(*env)->DeleteLocalRef(env, arr);
|
||||
return accepted == JNI_TRUE ? 1 : 0;
|
||||
}
|
||||
|
||||
void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_text_input || !(env = thread_env())) return;
|
||||
@@ -376,6 +393,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
|
||||
droiddeck_wayland_send_key(evdev, state);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKeyOrdered(
|
||||
JNIEnv *env, jclass clazz, jint evdev, jint state) {
|
||||
droiddeck_host_key(evdev, state);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSelectGameField(
|
||||
JNIEnv *env, jclass clazz, jboolean copy) {
|
||||
droiddeck_host_select_game_field(copy);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFocusTakesTouch(
|
||||
JNIEnv *env, jclass clazz) {
|
||||
@@ -807,6 +836,15 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommit(JNIE
|
||||
free(buf);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommitAndSubmit(
|
||||
JNIEnv *env, jclass clazz, jbyteArray utf8) {
|
||||
int len;
|
||||
char *buf = dup_bytes(env, utf8, &len);
|
||||
if (buf && len) droiddeck_host_text_commit_and_submit(buf, len);
|
||||
free(buf);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputPreedit(JNIEnv *env, jclass clazz, jbyteArray utf8,
|
||||
jint cursorBegin, jint cursorEnd) {
|
||||
@@ -821,6 +859,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIE
|
||||
droiddeck_host_text_delete(before, after);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompleteTextInputFallback(
|
||||
JNIEnv *env, jclass clazz, jint token, jint result) {
|
||||
droiddeck_host_text_input_fallback_complete(token, result);
|
||||
}
|
||||
|
||||
extern void adrenotools_set_turbo(bool turbo);
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
@@ -872,3 +916,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
|
||||
}
|
||||
@@ -10,6 +10,12 @@
|
||||
#ifndef KEY_DELETE
|
||||
#define KEY_DELETE 111
|
||||
#endif
|
||||
#ifndef KEY_ENTER
|
||||
#define KEY_ENTER 28
|
||||
#endif
|
||||
#ifndef KEY_TAB
|
||||
#define KEY_TAB 15
|
||||
#endif
|
||||
|
||||
static struct wl_display *g_disp;
|
||||
|
||||
@@ -203,16 +209,43 @@ static int32_t utf8_offset(const char *s, size_t len, int chars) {
|
||||
return (int32_t)i;
|
||||
}
|
||||
|
||||
void text_input_host_commit(const char *utf8, size_t len) {
|
||||
static int control_evdev(unsigned char c) {
|
||||
switch (c) {
|
||||
case '\r': case '\n': return KEY_ENTER;
|
||||
case '\b': return KEY_BACKSPACE;
|
||||
case 0x7f: return KEY_DELETE;
|
||||
case '\t': return KEY_TAB;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
|
||||
static int all_controls(const char *utf8, size_t len) {
|
||||
for (size_t i = 0; i < len; i++)
|
||||
if (control_evdev((unsigned char)utf8[i]) < 0) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int text_input_host_commit(const char *utf8, size_t len) {
|
||||
struct text_input *ti = active_input();
|
||||
if (!ti) {
|
||||
droiddeck_log("text-input", "typed text (%zu chars) dropped: no program accepts text input", utf8_chars(utf8, len));
|
||||
return;
|
||||
droiddeck_log("text-input", "typed text (%zu chars): no program accepts Wayland text input", utf8_chars(utf8, len));
|
||||
return 0;
|
||||
}
|
||||
if (len > 0 && all_controls(utf8, len)) {
|
||||
/* Keep editing keys on the compositor queue so they cannot overtake text commits. */
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
int code = control_evdev((unsigned char)utf8[i]);
|
||||
droiddeck_inject_key(code, 1);
|
||||
droiddeck_inject_key(code, 0);
|
||||
}
|
||||
droiddeck_log("text-input", "injected %zu soft control(s) to %s", len, ti_program(ti));
|
||||
return 1;
|
||||
}
|
||||
if (ti->has_preedit) { zwp_text_input_v3_send_preedit_string(ti->res, "", 0, 0); ti->has_preedit = 0; }
|
||||
zwp_text_input_v3_send_commit_string(ti->res, utf8);
|
||||
zwp_text_input_v3_send_done(ti->res, ti->serial);
|
||||
droiddeck_log("text-input", "committed %zu chars to %s", utf8_chars(utf8, len), ti_program(ti));
|
||||
return 1;
|
||||
}
|
||||
|
||||
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end) {
|
||||
|
||||
@@ -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) },
|
||||
@@ -2247,7 +2233,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
return true
|
||||
}
|
||||
return try {
|
||||
super.dispatchKeyEvent(event)
|
||||
super.dispatchKeyEvent(event) || com.droiddeck.launcher.ui.PageBumpers.handle(event)
|
||||
} catch (e: IllegalStateException) {
|
||||
if (e.message?.contains("active focus target") != true) throw e
|
||||
android.util.Log.w("MainActivity", "key ${event.keyCode} dropped: ${e.message}")
|
||||
@@ -2256,6 +2242,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) }
|
||||
|
||||
internal fun onMenuMotion(event: MotionEvent) = triggerKeys.onMotion(event)
|
||||
|
||||
private val rightStickLayouts = HashMap<Int, Boolean>()
|
||||
private val rightStickScrollHandler = android.os.Handler(android.os.Looper.getMainLooper())
|
||||
private var rightStickScrollDeviceId = -1
|
||||
@@ -2377,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)
|
||||
@@ -2918,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,
|
||||
@@ -2932,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,
|
||||
@@ -2982,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 },
|
||||
@@ -3005,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 },
|
||||
@@ -3322,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)
|
||||
@@ -3343,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)
|
||||
@@ -3356,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)
|
||||
|
||||
@@ -4,25 +4,32 @@ import android.app.NativeActivity
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import android.widget.Toast
|
||||
import com.droiddeck.launcher.gpu.SteamVr
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.xr.XrLayerSource
|
||||
import com.droiddeck.launcher.session.xr.XrPanels
|
||||
import com.droiddeck.launcher.wayland.CompositorHost
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
|
||||
class QuestXrActivity : NativeActivity() {
|
||||
class QuestXrActivity : NativeActivity(), XrLayerSource {
|
||||
private var steamVrStarted = false
|
||||
@Volatile private var closing = false
|
||||
@Volatile private var steamVrStatus = SteamVr.Status.UNAVAILABLE
|
||||
private var sessionId: String? = null
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
// NativeActivity opens the library itself, but the layer host's JNI methods resolve only
|
||||
// through a System.loadLibrary.
|
||||
System.loadLibrary("droiddeckxr")
|
||||
sessionId = SessionState.sessionId
|
||||
SessionService.setXrActivityVisible(this, true)
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
|
||||
fun onXrActive(active: Boolean) {
|
||||
XrPanels.setDrawing(active)
|
||||
if (active) {
|
||||
check(CompositorHost.isStarted) { "DroidDeck compositor is not running" }
|
||||
SessionService.resume(this)
|
||||
@@ -100,8 +107,30 @@ class QuestXrActivity : NativeActivity() {
|
||||
|
||||
fun onXrStatus(): Int = steamVrStatus.ordinal
|
||||
|
||||
fun onXrHostBuffers(state: java.nio.ByteBuffer, control: java.nio.ByteBuffer) {
|
||||
runOnUiThread { if (!closing) XrPanels.attach(this, state, control) }
|
||||
}
|
||||
|
||||
fun onXrHostFrame() = XrPanels.frame()
|
||||
|
||||
override val context: android.content.Context get() = this
|
||||
override fun createLayer(width: Int, height: Int) = nativeCreateLayer(width, height)
|
||||
override fun layerSurface(id: Int) = nativeLayerSurface(id)
|
||||
override fun destroyLayer(id: Int) = nativeDestroyLayer(id)
|
||||
override fun setOrbImage(image: android.graphics.Bitmap) = nativeSetOrbImage(image)
|
||||
override fun leave() {
|
||||
closing = true
|
||||
finish()
|
||||
}
|
||||
|
||||
private external fun nativeCreateLayer(width: Int, height: Int): Int
|
||||
private external fun nativeLayerSurface(id: Int): Surface?
|
||||
private external fun nativeDestroyLayer(id: Int)
|
||||
private external fun nativeSetOrbImage(image: android.graphics.Bitmap)
|
||||
|
||||
override fun onDestroy() {
|
||||
closing = true
|
||||
XrPanels.detach()
|
||||
SessionService.setXrActivityVisible(this, false)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@ import com.droiddeck.launcher.input.InputSpace
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.input.SessionClipboard
|
||||
import com.droiddeck.launcher.input.SessionTextInput
|
||||
import com.droiddeck.launcher.input.OnScreenControls
|
||||
import com.droiddeck.launcher.input.OnScreenLayout
|
||||
import com.droiddeck.launcher.input.InputRouter
|
||||
@@ -162,7 +163,8 @@ import kotlin.math.abs
|
||||
private const val SCREEN_EFFECTS_TARGET_AUTO = "auto"
|
||||
private const val SCREEN_EFFECTS_TARGET_GLOBAL = "global"
|
||||
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost {
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost,
|
||||
com.droiddeck.launcher.session.xr.XrMenuHost {
|
||||
override fun attachBaseContext(newBase: android.content.Context) {
|
||||
super.attachBaseContext(newBase)
|
||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||
@@ -178,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
|
||||
@@ -228,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)
|
||||
@@ -348,6 +354,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
|
||||
}
|
||||
}
|
||||
private val sessionTextInput by lazy {
|
||||
SessionTextInput(this) {
|
||||
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
|
||||
}
|
||||
}
|
||||
private var watching = true
|
||||
private lateinit var touchpad: TouchpadGestures
|
||||
private lateinit var directTouchHold: DirectTouchHold
|
||||
@@ -546,6 +557,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var drawerOpenState by mutableStateOf(false)
|
||||
private var typingReturnMode: SecondScreenMode? = null
|
||||
private var drawerDocked by mutableStateOf(false)
|
||||
/** The menu is open as a floating panel in the immersive Quest view instead of over this window. */
|
||||
private var drawerXr by mutableStateOf(false)
|
||||
private var drawerPinned by mutableStateOf(false)
|
||||
private var drawerLayerOpen = false
|
||||
private var drawerBackRequests by mutableIntStateOf(0)
|
||||
@@ -563,9 +576,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
drawerPinned = false
|
||||
if (value) {
|
||||
releaseHeldKeys()
|
||||
drawerDocked = dockDrawer() && openDockedMenu()
|
||||
drawerXr = com.droiddeck.launcher.session.xr.XrPanels.showMenu()
|
||||
drawerDocked = !drawerXr && dockDrawer() && openDockedMenu()
|
||||
}
|
||||
drawerOpenState = value
|
||||
if (!value && drawerXr) {
|
||||
drawerXr = false
|
||||
com.droiddeck.launcher.session.xr.XrPanels.hideMenu()
|
||||
}
|
||||
if (!value && drawerDocked) closeDockedMenu()
|
||||
}
|
||||
private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController)
|
||||
@@ -703,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)
|
||||
@@ -850,6 +865,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
com.droiddeck.launcher.session.xr.XrPanels.setMenuHost(this)
|
||||
AgentGuest.readyListener = agentReadyListener
|
||||
com.droiddeck.launcher.agent.AgentAttachments.gameFrame = gameFrame
|
||||
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
|
||||
@@ -980,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
|
||||
@@ -988,7 +1005,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
root.addView(controls)
|
||||
}
|
||||
keyboard = KeyboardHost(this).also { host ->
|
||||
keyboard = KeyboardHost(this, sendKeyEvent = ::dispatchImeKeyEvent, sendText = WaylandCompositor::textInputCommit).also { host ->
|
||||
host.onImeChanged = ::onPrimaryImeChanged
|
||||
root.addView(host)
|
||||
}
|
||||
@@ -1193,7 +1210,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val cursorHidden = cursorHiddenByUi()
|
||||
androidx.compose.runtime.SideEffect {
|
||||
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
|
||||
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
|
||||
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && !drawerXr && steamVrStatus != SteamVr.Status.RUNNING)
|
||||
}
|
||||
androidx.compose.runtime.SideEffect { applyPlatformPointer(uiPointer) }
|
||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||
@@ -1272,6 +1289,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (!drawerOpen && !pcKeyboardOpen && !loading.visible) {
|
||||
com.droiddeck.launcher.ui.DrawerEntryHint(SessionState.mode == SessionService.MODE_STEAM, backActionsInverted) { drawerOpen = true }
|
||||
if (cornerTap) com.droiddeck.launcher.ui.DrawerCornerTap { drawerOpen = true }
|
||||
if (com.droiddeck.launcher.session.QuestExperimental.isSupported())
|
||||
com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() }
|
||||
}
|
||||
if (loading.visible) LoadingOverlay(
|
||||
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
|
||||
@@ -1475,11 +1494,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() },
|
||||
onClose = { pcKeyboardOpen = false },
|
||||
)
|
||||
if (!drawerDocked) SessionMenu(
|
||||
if (!drawerDocked && !drawerXr) SessionMenu(
|
||||
docked = false,
|
||||
effectsEditorProfileId = effectsEditorProfileId,
|
||||
effectsEditorTarget = effectsEditorTarget,
|
||||
)
|
||||
if (drawerOpen && !drawerDocked && !drawerXr && com.droiddeck.launcher.session.QuestExperimental.isSupported())
|
||||
com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() }
|
||||
LaunchedEffect(achievementsOpen) {
|
||||
if (achievementsOpen) {
|
||||
releasePads()
|
||||
@@ -1528,6 +1549,74 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
}
|
||||
|
||||
@androidx.compose.runtime.Composable
|
||||
override fun XrMenuContent() {
|
||||
val activeEffectsProfileId = currentScreenEffectsProfileId()
|
||||
val effectsEditorTarget = if (drawerOpen) screenEffectsTarget else null
|
||||
val effectsEditorProfileId = activeEffectsProfileId.takeIf { effectsEditorTarget == SCREEN_EFFECTS_TARGET_AUTO }
|
||||
androidx.compose.runtime.LaunchedEffect(effectsEditorTarget, effectsEditorProfileId) {
|
||||
when (effectsEditorTarget) {
|
||||
SCREEN_EFFECTS_TARGET_AUTO -> syncActiveScreenEffectsProfile()
|
||||
null -> Unit
|
||||
else -> syncScreenEffectsTarget(effectsEditorTarget)
|
||||
}
|
||||
}
|
||||
SessionMenu(docked = true, effectsEditorProfileId = effectsEditorProfileId, effectsEditorTarget = effectsEditorTarget)
|
||||
}
|
||||
|
||||
override fun xrSetMenuOpen(open: Boolean) {
|
||||
if (open != drawerOpen) drawerOpen = open
|
||||
}
|
||||
|
||||
/**
|
||||
* In the immersive Quest view, Stop takes the user back to this window with the session still
|
||||
* running, and Stop SteamVR leaves at once instead of after the stop is noticed.
|
||||
*/
|
||||
private fun leaveXrMenu() {
|
||||
if (!drawerXr) return
|
||||
drawerOpen = false
|
||||
com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive()
|
||||
}
|
||||
|
||||
override fun xrMenuBack() {
|
||||
if (drawerLayerOpen) drawerBackRequests++ else drawerOpen = false
|
||||
}
|
||||
|
||||
override fun xrSendKey(code: Int, down: Boolean) {
|
||||
if (CompositorHost.isStarted) sendGuestKey(code, down, 32)
|
||||
}
|
||||
|
||||
override fun xrTypeText(text: String) = xrKeys.type(text)
|
||||
|
||||
override fun xrImmersiveChanged(active: Boolean) {
|
||||
if (active) {
|
||||
if (immersiveFlatSize == null) immersiveFlatSize = SessionState.outputSize
|
||||
resizeOutputForWindow(surfaceW, surfaceH)
|
||||
return
|
||||
}
|
||||
val flat = immersiveFlatSize
|
||||
immersiveFlatSize = null
|
||||
if (windowOutputSize(surfaceW, surfaceH) == null && flat != null) applyOutputSize(flat)
|
||||
else resizeOutputForWindow(surfaceW, surfaceH)
|
||||
}
|
||||
|
||||
/** The output's size when the immersive view opened; this window may have no surface while it is up. */
|
||||
private var immersiveFlatSize: Pair<Int, Int>? = null
|
||||
|
||||
override fun xrTapKey(keyCode: Int) = xrKeys.tap(keyCode)
|
||||
|
||||
/** 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 {
|
||||
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
|
||||
private fun SessionMenu(
|
||||
docked: Boolean,
|
||||
@@ -1631,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)
|
||||
@@ -1815,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),
|
||||
@@ -1826,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,
|
||||
@@ -1906,9 +2001,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
SessionService.suspendPolicyChanged(this@SessionActivity)
|
||||
},
|
||||
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
||||
onInputSettings = { releasePads(); drawerOpen = false; inputSettingsOpen = true },
|
||||
onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputSettingsOpen = true },
|
||||
onInputSelection = { releasePads(); refreshInputProfile() },
|
||||
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
|
||||
onGestureSettings = { leaveImmersiveForDialog(); drawerOpen = false; gestureSettingsOpen = true },
|
||||
touchActive = drawerTouchMode(),
|
||||
directHoldBehavior = directHoldBehavior,
|
||||
onDirectHoldBehavior = { value ->
|
||||
@@ -1969,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
|
||||
},
|
||||
@@ -2005,18 +2102,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
|
||||
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
|
||||
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
||||
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
||||
onStop = {
|
||||
if (drawerXr) leaveXrMenu() else {
|
||||
drawerOpen = false
|
||||
SessionService.stop(this@SessionActivity)
|
||||
finish()
|
||||
}
|
||||
},
|
||||
onStopFrom = { onScreen ->
|
||||
drawerOpen = false
|
||||
if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) {
|
||||
if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() }
|
||||
} else {
|
||||
val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) }
|
||||
quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat())
|
||||
if (drawerXr) leaveXrMenu() else {
|
||||
drawerOpen = false
|
||||
if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) {
|
||||
if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() }
|
||||
} else {
|
||||
val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) }
|
||||
quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat())
|
||||
}
|
||||
}
|
||||
},
|
||||
onClose = { drawerOpen = false },
|
||||
onDismissScreen = if (docked) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null,
|
||||
onDismissScreen = if (docked && !drawerXr) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null,
|
||||
components = drawerComponents,
|
||||
onComponentsRefresh = {
|
||||
refreshDrawerComponents()
|
||||
@@ -2094,7 +2199,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}) else null,
|
||||
onKeyboard = { togglePrimaryKeyboard() },
|
||||
onSessionMenu = { drawerOpen = true },
|
||||
onStopSteamVr = if (vr) ({ steamVrAction("stop") }) else null,
|
||||
onStopSteamVr = if (vr) ({ leaveXrMenu(); steamVrAction("stop") }) else null,
|
||||
brightness = glasses.brightness,
|
||||
brightnessMax = glasses.brightnessMax,
|
||||
onBrightness = if (glasses.canControl && glasses.hardwareControls) Glasses::setBrightness else null,
|
||||
@@ -2133,6 +2238,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun togglePcKeyboard() {
|
||||
drawerOpen = false
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = true)) return
|
||||
hidePrimaryKeyboard()
|
||||
onScreenControls?.releaseAll()
|
||||
bottomInputControls?.releaseAll()
|
||||
@@ -2142,12 +2248,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private fun showPrimaryKeyboard() {
|
||||
pendingFieldKeyboard = false
|
||||
fieldKeyboardOnPrimary = false
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.showGameKeyboard(pc = false)) return
|
||||
keyboard?.show()
|
||||
}
|
||||
|
||||
private fun togglePrimaryKeyboard() {
|
||||
pendingFieldKeyboard = false
|
||||
fieldKeyboardOnPrimary = false
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = false)) return
|
||||
keyboard?.toggle()
|
||||
}
|
||||
|
||||
@@ -2171,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)
|
||||
@@ -2681,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()
|
||||
@@ -3021,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) }
|
||||
}
|
||||
@@ -3045,6 +3166,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) {
|
||||
val flat = immersiveFlatSize ?: SessionState.outputSize
|
||||
return if (steamScreenShown()) vrOutputSize(flat) else flat
|
||||
}
|
||||
if (width <= 0 || height <= 0 || isInPictureInPictureMode) return null
|
||||
if (bottomGame != null) return when {
|
||||
SessionState.followScreen ->
|
||||
@@ -3058,9 +3183,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
else if (glassesScreen == null) outputSize() else null
|
||||
}
|
||||
|
||||
/** These editors draw in this window, which the immersive view hides, so they open after leaving it. */
|
||||
private fun leaveImmersiveForDialog() {
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive()
|
||||
}
|
||||
|
||||
/** Steam's own screen is up with no game holding a window; with no focus report, a game may be running. */
|
||||
private fun steamScreenShown(): Boolean {
|
||||
if (SessionState.mode != SessionService.MODE_STEAM) return false
|
||||
val focus = com.droiddeck.launcher.agent.AgentGuest.focus(this) ?: return false
|
||||
return com.droiddeck.launcher.session.xr.XrSteamScreen.shown(
|
||||
focus.takeUnless { it.isNull("focusedApp") }?.optLong("focusedApp"),
|
||||
focus.optJSONArray("focusableApps")?.let { list -> (0 until list.length()).map { list.optLong(it) } },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* SteamVR shows Steam's own screen as its floating Steam window, so in the headset that screen is drawn
|
||||
* tall enough for the window to stay sharp. A flat game keeps the flat size, so the output keeps it
|
||||
* while one is running.
|
||||
*/
|
||||
private fun vrOutputSize(flat: Pair<Int, Int>): Pair<Int, Int> {
|
||||
if (flat.second >= VR_OUTPUT_HEIGHT) return flat
|
||||
val width = (flat.first.toLong() * VR_OUTPUT_HEIGHT / flat.second.coerceAtLeast(1)).toInt() and 1.inv()
|
||||
return width to VR_OUTPUT_HEIGHT
|
||||
}
|
||||
|
||||
private fun resizeOutputForWindow(width: Int, height: Int) {
|
||||
applyOutputSize(windowOutputSize(width, height) ?: return)
|
||||
}
|
||||
|
||||
private fun applyOutputSize(size: Pair<Int, Int>) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val size = windowOutputSize(width, height) ?: return
|
||||
if (size == SessionState.outputSize) return
|
||||
Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
|
||||
SessionState.outputSize = size
|
||||
@@ -3084,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)
|
||||
}
|
||||
@@ -3456,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())
|
||||
@@ -3680,16 +3822,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
internal fun dispatchImeKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = true)
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = false)
|
||||
|
||||
private fun dispatchKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
|
||||
val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event)
|
||||
if (normalized === event) return dispatchSessionKeyEvent(event)
|
||||
if (normalized === event) return dispatchSessionKeyEvent(event, orderedImeKey)
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}")
|
||||
}
|
||||
return dispatchSessionKeyEvent(normalized)
|
||||
return dispatchSessionKeyEvent(normalized, orderedImeKey)
|
||||
}
|
||||
|
||||
private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean {
|
||||
private fun dispatchSessionKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
|
||||
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
|
||||
@@ -3772,7 +3918,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
return true
|
||||
}
|
||||
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
|
||||
if (pad !== event) return dispatchKeyEvent(pad)
|
||||
if (pad !== event) return dispatchKeyEvent(pad, orderedImeKey)
|
||||
val fromController = PadBridge.isControllerKeyEvent(event)
|
||||
if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
|
||||
padBridge?.setInputEnabled(false)
|
||||
@@ -3855,7 +4001,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val down = event.action == KeyEvent.ACTION_DOWN
|
||||
if (down && event.repeatCount > 0) return true
|
||||
val owner = if (event.deviceId <= 0) 16 else 8
|
||||
if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner) }) return true
|
||||
if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner, orderedImeKey) }) return true
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
@@ -3942,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 {
|
||||
@@ -4986,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) {
|
||||
@@ -5008,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
|
||||
@@ -5018,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
|
||||
@@ -5036,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
|
||||
@@ -5058,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))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5149,27 +5288,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
} else {
|
||||
endGameField()
|
||||
}
|
||||
host.type(text)
|
||||
host.tap(KeyEvent.KEYCODE_ENTER)
|
||||
if (text.isEmpty()) host.tap(KeyEvent.KEYCODE_ENTER)
|
||||
else WaylandCompositor.textInputCommitAndSubmit(text)
|
||||
uiHandler.postDelayed({
|
||||
if (AgentGuest.gameTextField && com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) endGameField()
|
||||
}, FIELD_SETTLE_MS)
|
||||
}
|
||||
|
||||
private fun endGameField() {
|
||||
WaylandCompositor.nativeSendKey(KEY_END, 1)
|
||||
WaylandCompositor.nativeSendKey(KEY_END, 0)
|
||||
orderedImeKeySender(KEY_END, true)
|
||||
orderedImeKeySender(KEY_END, false)
|
||||
}
|
||||
|
||||
private fun selectGameField(vararg then: Int) {
|
||||
heldKeys.set(256, KEY_LEFTCTRL, true)
|
||||
try {
|
||||
for (key in intArrayOf(KEY_A) + then) {
|
||||
heldKeys.set(256, key, true)
|
||||
heldKeys.set(256, key, false)
|
||||
}
|
||||
} finally { heldKeys.release(256) }
|
||||
}
|
||||
private fun selectGameField(copy: Boolean = false) { WaylandCompositor.nativeSelectGameField(copy) }
|
||||
|
||||
private fun readGameField(done: (String?) -> Unit) {
|
||||
val opened = wowChat.request
|
||||
@@ -5178,7 +5309,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (text != null && stillOpen()) endGameField()
|
||||
done(text)
|
||||
}
|
||||
selectGameField(KEY_C)
|
||||
selectGameField(copy = true)
|
||||
}
|
||||
|
||||
private fun cancelWowChat() {
|
||||
@@ -5877,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()
|
||||
@@ -5982,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))
|
||||
}
|
||||
@@ -6081,11 +6217,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
releaseHeldKeys()
|
||||
}
|
||||
|
||||
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
|
||||
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1, orderedImeKey: Boolean = false) {
|
||||
if (down && pipUi) return
|
||||
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
|
||||
if (owner == 1) { if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) }
|
||||
heldKeys.set(owner, code, down)
|
||||
val orderedSender = if (orderedImeKey) orderedImeKeySender else null
|
||||
heldKeys.set(owner, code, down, orderedSender)
|
||||
}
|
||||
|
||||
private val orderedImeKeySender: (Int, Boolean) -> Unit = { code, down ->
|
||||
WaylandCompositor.nativeSendKeyOrdered(code, if (down) 1 else 0)
|
||||
}
|
||||
|
||||
private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) {
|
||||
@@ -6153,7 +6294,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val back = {
|
||||
if (restore.compareAndSet(false, true)) {
|
||||
pauseCaptures--
|
||||
if (!isDestroyed) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
|
||||
if (!isDestroyed && zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
|
||||
}
|
||||
}
|
||||
uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS)
|
||||
@@ -6268,6 +6409,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
heldButtons.clear()
|
||||
hidePrimaryKeyboard()
|
||||
sessionClipboard.stop()
|
||||
sessionTextInput.stop()
|
||||
padMotion?.stop()
|
||||
cursorVisible = false
|
||||
closeSecondScreen(reset = false)
|
||||
@@ -6283,7 +6425,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
} else if (!isFinishing && !isDestroyed) {
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
updateOnScreenControls()
|
||||
if (resumed) { sessionClipboard.start(); updatePadMotion() }
|
||||
if (resumed) { sessionClipboard.start(); sessionTextInput.start(); updatePadMotion() }
|
||||
if (started) {
|
||||
settleDualScreenControls()
|
||||
refreshSecondScreenDisplays()
|
||||
@@ -6353,7 +6495,14 @@ 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()
|
||||
updateBottomGame()
|
||||
@@ -6389,6 +6538,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) }
|
||||
@@ -6418,6 +6568,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
joyConVr?.refresh()
|
||||
onScreenControls?.reload()
|
||||
controllerSettings = ControllerPrefs.read(this)
|
||||
applyOnScreenOpacity()
|
||||
resumed = true
|
||||
boostGpuClock(panelOverGame)
|
||||
updateKeyboardRoute()
|
||||
@@ -6433,7 +6584,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
onCancel = { padBridge?.cancelHomeGuide() },
|
||||
)
|
||||
updatePointerCapture()
|
||||
if (!pipUi) sessionClipboard.start()
|
||||
if (!pipUi) { sessionClipboard.start(); sessionTextInput.start() }
|
||||
updatePadMotion()
|
||||
ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener)
|
||||
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener)
|
||||
@@ -6501,7 +6652,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
|
||||
@@ -6926,7 +7077,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 },
|
||||
)
|
||||
@@ -7150,6 +7304,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
com.droiddeck.launcher.session.xr.XrPanels.clearMenuHost(this)
|
||||
if (drawerXr) com.droiddeck.launcher.session.xr.XrPanels.hideMenu()
|
||||
uiHandler.removeCallbacks(panelHeldCheck)
|
||||
uiHandler.removeCallbacks(panelHeldRetry)
|
||||
synchronized(frameGenGlobalLock) {
|
||||
@@ -7162,6 +7318,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
gamescopeConvarRequests.shutdownNow()
|
||||
backQamInput.cancel()
|
||||
steamVrRecovery.close()
|
||||
sessionTextInput.stop()
|
||||
uiHandler.removeCallbacks(steamTouchRetry)
|
||||
uiHandler.removeCallbacks(cursorResync)
|
||||
uiHandler.removeCallbacks(usbMouseFallback)
|
||||
@@ -7274,6 +7431,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
const val EXTRA_RETURN_HOME = "returnHome"
|
||||
private const val BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT"
|
||||
private const val REQUEST_BLUETOOTH = 31
|
||||
private const val VR_OUTPUT_HEIGHT = 1080
|
||||
const val EXTRA_LINK_TASK = "linkTask"
|
||||
const val EXTRA_STEAMVR = "steamVr"
|
||||
const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME"
|
||||
|
||||
@@ -19,6 +19,9 @@ 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
|
||||
|
||||
private const val NEW = "new"
|
||||
private const val GUEST_DIR = "/root/.cache/droiddeck/attachments"
|
||||
private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp")
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.core.AppUiPrefs
|
||||
import com.droiddeck.launcher.ui.AgentPage
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
|
||||
/**
|
||||
* The agent's chat in a window of its own, for Quest's flat mode: opened in its own task, it is a
|
||||
* separate Horizon panel the user can move, resize and close like any other.
|
||||
*/
|
||||
class AgentChatActivity : ComponentActivity() {
|
||||
override fun attachBaseContext(newBase: Context) {
|
||||
super.attachBaseContext(newBase)
|
||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
|
||||
AgentPage(
|
||||
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
visible = true, startTyping = AgentHost.entries.isEmpty(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun open(context: Context) {
|
||||
context.startActivity(
|
||||
Intent(context, AgentChatActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import java.util.UUID
|
||||
object AgentGuest {
|
||||
private val main by lazy { Handler(Looper.getMainLooper()) }
|
||||
var focusRevision by mutableIntStateOf(0)
|
||||
private set
|
||||
@androidx.annotation.VisibleForTesting internal set
|
||||
var steamKeyboard by mutableStateOf(false)
|
||||
private set
|
||||
var desktopTextField by mutableStateOf(false)
|
||||
|
||||
@@ -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  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 {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -2,14 +2,24 @@ package com.droiddeck.launcher.input
|
||||
|
||||
class HeldInput(private val emit: (Int, Boolean) -> Unit) {
|
||||
private val owners = IntArray(768)
|
||||
private val ordered = arrayOfNulls<(Int, Boolean) -> Unit>(768)
|
||||
|
||||
@Synchronized
|
||||
fun set(source: Int, code: Int, down: Boolean) {
|
||||
fun set(source: Int, code: Int, down: Boolean, orderedEmit: ((Int, Boolean) -> Unit)? = null) {
|
||||
if (code !in owners.indices) return
|
||||
val before = owners[code]
|
||||
val after = if (down) before or source else before and source.inv()
|
||||
owners[code] = after
|
||||
if ((before == 0) != (after == 0)) emit(code, after != 0)
|
||||
if ((before == 0) != (after == 0)) {
|
||||
if (after != 0) {
|
||||
ordered[code] = orderedEmit
|
||||
orderedEmit?.invoke(code, true) ?: emit(code, true)
|
||||
} else {
|
||||
val fn = ordered[code]
|
||||
ordered[code] = null
|
||||
fn?.invoke(code, false) ?: emit(code, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
@@ -21,7 +31,9 @@ class HeldInput(private val emit: (Int, Boolean) -> Unit) {
|
||||
fun clear() {
|
||||
for (code in owners.indices) if (owners[code] != 0) {
|
||||
owners[code] = 0
|
||||
emit(code, false)
|
||||
val fn = ordered[code]
|
||||
ordered[code] = null
|
||||
fn?.invoke(code, false) ?: emit(code, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.text.InputType
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
@@ -12,15 +11,17 @@ import android.view.inputmethod.BaseInputConnection
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.view.inputmethod.InputConnection
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
|
||||
class KeyboardHost(
|
||||
context: Context,
|
||||
private val sendKeyEvent: (KeyEvent) -> Boolean,
|
||||
private val sendText: (String) -> Unit,
|
||||
) : View(context) {
|
||||
constructor(activity: Activity) : this(activity, { activity.dispatchKeyEvent(it) })
|
||||
constructor(activity: Activity) :
|
||||
this(activity, { activity.dispatchKeyEvent(it) }, { WaylandCompositor.textInputCommit(it) })
|
||||
|
||||
private val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
|
||||
var shown = false
|
||||
private set
|
||||
var imeShowing = false
|
||||
@@ -40,8 +41,7 @@ class KeyboardHost(
|
||||
|
||||
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
|
||||
if (!shown) return null
|
||||
outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
|
||||
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
|
||||
outAttrs.inputType = InputType.TYPE_CLASS_TEXT
|
||||
outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE or EditorInfo.IME_FLAG_NO_FULLSCREEN or
|
||||
EditorInfo.IME_FLAG_NO_EXTRACT_UI
|
||||
return KeyConnection()
|
||||
@@ -93,45 +93,153 @@ class KeyboardHost(
|
||||
|
||||
fun type(text: CharSequence?) {
|
||||
if (text.isNullOrEmpty()) return
|
||||
val events = map.getEvents(text.toString().toCharArray())
|
||||
if (events != null) {
|
||||
for (event in events) sendKeyEvent(event)
|
||||
} else {
|
||||
for (ch in text) {
|
||||
val t = System.currentTimeMillis()
|
||||
val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0,
|
||||
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0)
|
||||
sendKeyEvent(CharKeyEvent(down, ch))
|
||||
sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch))
|
||||
}
|
||||
}
|
||||
// Text and soft editing actions share this queue to preserve IME ordering.
|
||||
sendText(text.toString())
|
||||
}
|
||||
|
||||
fun tap(keyCode: Int) {
|
||||
val control = softControl(keyCode)
|
||||
if (control != null) {
|
||||
sendText(control.toString())
|
||||
return
|
||||
}
|
||||
val t = System.currentTimeMillis()
|
||||
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
|
||||
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
|
||||
}
|
||||
|
||||
private inner class KeyConnection : BaseInputConnection(this, false) {
|
||||
// A press keeps the route chosen on its first down across repeats and the matching up.
|
||||
private val controlRoutes = HashMap<Int, Boolean>()
|
||||
|
||||
private var composingText = ""
|
||||
private var composingCursor = 0
|
||||
|
||||
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||
composingText = ""
|
||||
composingCursor = 0
|
||||
type(text)
|
||||
return true
|
||||
}
|
||||
|
||||
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = true
|
||||
override fun finishComposingText(): Boolean = true
|
||||
|
||||
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
|
||||
repeat(beforeLength) { tap(KeyEvent.KEYCODE_DEL) }
|
||||
repeat(afterLength) { tap(KeyEvent.KEYCODE_FORWARD_DEL) }
|
||||
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||
composingText = text?.toString().orEmpty()
|
||||
val rawCursor = if (newCursorPosition > 0) {
|
||||
composingText.length.toLong() + newCursorPosition - 1L
|
||||
} else {
|
||||
newCursorPosition.toLong()
|
||||
}
|
||||
composingCursor = rawCursor.coerceIn(0L, composingText.length.toLong()).toInt()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun sendKeyEvent(event: KeyEvent): Boolean = this@KeyboardHost.sendKeyEvent(event)
|
||||
override fun finishComposingText(): Boolean {
|
||||
val text = composingText
|
||||
composingText = ""
|
||||
composingCursor = 0
|
||||
type(text)
|
||||
return true
|
||||
}
|
||||
|
||||
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
|
||||
val before = beforeLength.coerceAtLeast(0)
|
||||
val after = afterLength.coerceAtLeast(0)
|
||||
if (before == 0 && after == 0) return true
|
||||
val consumedBefore = minOf(before, composingCursor)
|
||||
val consumedAfter = minOf(after, composingText.length - composingCursor)
|
||||
val guestBefore = before - consumedBefore
|
||||
val guestAfter = after - consumedAfter
|
||||
if (guestBefore > 1 || guestAfter > 1) return false
|
||||
return applyDeletion(
|
||||
composingCursor - consumedBefore,
|
||||
composingCursor + consumedAfter,
|
||||
guestBefore,
|
||||
guestAfter,
|
||||
)
|
||||
}
|
||||
|
||||
override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean {
|
||||
val before = beforeLength.coerceAtLeast(0)
|
||||
val after = afterLength.coerceAtLeast(0)
|
||||
if (before == 0 && after == 0) return true
|
||||
if (splitsPair(composingCursor)) return false
|
||||
val text = composingText
|
||||
val beforePoints = Character.codePointCount(text, 0, composingCursor)
|
||||
val afterPoints = Character.codePointCount(text, composingCursor, text.length)
|
||||
val consumedBefore = minOf(before, beforePoints)
|
||||
val consumedAfter = minOf(after, afterPoints)
|
||||
val start = Character.offsetByCodePoints(text, composingCursor, -consumedBefore)
|
||||
val end = Character.offsetByCodePoints(text, composingCursor, consumedAfter)
|
||||
if (hasUnpairedSurrogate(text, start, end)) return false
|
||||
return applyDeletion(
|
||||
start,
|
||||
end,
|
||||
before - consumedBefore,
|
||||
after - consumedAfter,
|
||||
)
|
||||
}
|
||||
|
||||
private fun applyDeletion(start: Int, end: Int, guestBefore: Int, guestAfter: Int): Boolean {
|
||||
if (guestBefore > 64 || guestAfter > 64) return false
|
||||
if (splitsPair(start) || splitsPair(end)) return false
|
||||
if (start < end) {
|
||||
composingText = composingText.removeRange(start, end)
|
||||
composingCursor = start
|
||||
}
|
||||
val controls = StringBuilder()
|
||||
repeat(guestBefore) { controls.append(BACKSPACE) }
|
||||
repeat(guestAfter) { controls.append(FORWARD_DELETE) }
|
||||
if (controls.isNotEmpty()) sendText(controls.toString())
|
||||
return true
|
||||
}
|
||||
|
||||
private fun splitsPair(index: Int): Boolean =
|
||||
index > 0 && index < composingText.length &&
|
||||
composingText[index - 1].isHighSurrogate() && composingText[index].isLowSurrogate()
|
||||
|
||||
private fun hasUnpairedSurrogate(text: CharSequence, start: Int, end: Int): Boolean {
|
||||
var i = start
|
||||
while (i < end) {
|
||||
val c = text[i]
|
||||
if (c.isHighSurrogate()) {
|
||||
if (i + 1 >= end || !text[i + 1].isLowSurrogate()) return true
|
||||
i += 2
|
||||
} else if (c.isLowSurrogate()) {
|
||||
return true
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun sendKeyEvent(event: KeyEvent): Boolean {
|
||||
val control = softControl(event.keyCode)
|
||||
if (control == null) return this@KeyboardHost.sendKeyEvent(event)
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
val soft = if (event.repeatCount == 0) {
|
||||
val route = !event.isModified()
|
||||
controlRoutes[event.keyCode] = route
|
||||
route
|
||||
} else {
|
||||
controlRoutes[event.keyCode] ?: !event.isModified()
|
||||
}
|
||||
if (!soft) return this@KeyboardHost.sendKeyEvent(event)
|
||||
if (control == ENTER) finishComposingText()
|
||||
sendText(control.toString())
|
||||
return true
|
||||
}
|
||||
if (event.action == KeyEvent.ACTION_UP) {
|
||||
val soft = controlRoutes.remove(event.keyCode) ?: !event.isModified()
|
||||
if (soft) return true
|
||||
return this@KeyboardHost.sendKeyEvent(event)
|
||||
}
|
||||
return this@KeyboardHost.sendKeyEvent(event)
|
||||
}
|
||||
|
||||
override fun performEditorAction(actionCode: Int): Boolean {
|
||||
tap(KeyEvent.KEYCODE_ENTER)
|
||||
finishComposingText()
|
||||
sendText(ENTER.toString())
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -140,8 +248,22 @@ class KeyboardHost(
|
||||
override fun getSelectedText(flags: Int): CharSequence? = null
|
||||
}
|
||||
|
||||
private class CharKeyEvent(origin: KeyEvent, private val ch: Char) : KeyEvent(origin) {
|
||||
override fun getUnicodeChar(): Int = ch.code
|
||||
override fun getUnicodeChar(metaState: Int): Int = ch.code
|
||||
private fun softControl(keyCode: Int): Char? = when (keyCode) {
|
||||
KeyEvent.KEYCODE_DEL -> BACKSPACE
|
||||
KeyEvent.KEYCODE_FORWARD_DEL -> FORWARD_DELETE
|
||||
KeyEvent.KEYCODE_ENTER -> ENTER
|
||||
KeyEvent.KEYCODE_TAB -> TAB
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun KeyEvent.isModified(): Boolean =
|
||||
isCtrlPressed || isShiftPressed || isAltPressed || isMetaPressed
|
||||
|
||||
private companion object {
|
||||
// Control characters represent editing keys on the guest text channel.
|
||||
const val ENTER = '\r'
|
||||
const val BACKSPACE = '\b'
|
||||
const val FORWARD_DELETE = '\u007f'
|
||||
const val TAB = '\t'
|
||||
}
|
||||
}
|
||||
@@ -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,327 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.net.LocalSocket
|
||||
import android.net.LocalSocketAddress
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
private enum class TextDelivery(val result: Int) {
|
||||
NOT_DELIVERED(WaylandCompositor.TEXT_NOT_DELIVERED),
|
||||
DELIVERED(WaylandCompositor.TEXT_DELIVERED),
|
||||
UNRESOLVED(WaylandCompositor.TEXT_UNRESOLVED),
|
||||
}
|
||||
|
||||
class SessionTextInput(context: Context, private val hasFocus: () -> Boolean) {
|
||||
private val delivery = deliveryFor(context)
|
||||
private val owner = Any()
|
||||
|
||||
fun start() = delivery.start(owner, hasFocus)
|
||||
fun stop() = delivery.stop(owner)
|
||||
|
||||
private companion object {
|
||||
private var instance: SessionTextDelivery? = null
|
||||
|
||||
@Synchronized private fun deliveryFor(context: Context): SessionTextDelivery =
|
||||
instance ?: SessionTextDelivery(context.applicationContext).also { instance = it }
|
||||
}
|
||||
}
|
||||
|
||||
private class SessionTextDelivery(private val appContext: Context) {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val lock = Any()
|
||||
private var generation = 0L
|
||||
@Volatile private var active = false
|
||||
private var owner: Any? = null
|
||||
private var focusCheck: (() -> Boolean)? = null
|
||||
private var executor: ScheduledThreadPoolExecutor? = null
|
||||
private var socket: LocalSocket? = null
|
||||
private var pendingToken = 0
|
||||
private var runningToken = 0
|
||||
private var failedToken = 0
|
||||
private val guestListener = object : WaylandCompositor.TextInputFallbackListener {
|
||||
override fun onTextInputFallback(text: String, token: Int): Boolean {
|
||||
synchronized(lock) {
|
||||
if (!active || pendingToken != 0 || failedToken != 0 || token <= 0) return false
|
||||
val received = generation
|
||||
pendingToken = token
|
||||
val posted = try {
|
||||
handler.post { enqueue(text, received, token) }
|
||||
} catch (e: RuntimeException) {
|
||||
false
|
||||
}
|
||||
if (!posted) pendingToken = 0
|
||||
return posted
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun start(nextOwner: Any, hasFocus: () -> Boolean) {
|
||||
val previous = synchronized(lock) {
|
||||
if (owner === nextOwner) return
|
||||
owner
|
||||
}
|
||||
if (previous != null) stop(previous)
|
||||
val queue = ScheduledThreadPoolExecutor(1) { runnable ->
|
||||
Thread(runnable, "session-text-input").apply { isDaemon = true }
|
||||
}
|
||||
queue.executeExistingDelayedTasksAfterShutdownPolicy = false
|
||||
synchronized(lock) {
|
||||
this.owner = nextOwner
|
||||
focusCheck = hasFocus
|
||||
active = true
|
||||
executor = queue
|
||||
if (failedToken != 0) scheduleRetryLocked(failedToken, INITIAL_DELAY_MS)
|
||||
}
|
||||
WaylandCompositor.setTextInputFallbackListener(guestListener)
|
||||
}
|
||||
|
||||
fun stop(oldOwner: Any) {
|
||||
val detached = synchronized(lock) {
|
||||
if (owner !== oldOwner) return
|
||||
owner = null
|
||||
focusCheck = null
|
||||
active = false
|
||||
generation += 1
|
||||
val queue = executor
|
||||
val open = socket
|
||||
val token = if (runningToken == 0 && failedToken == 0) pendingToken else 0
|
||||
executor = null
|
||||
socket = null
|
||||
Triple(queue, open, token)
|
||||
}
|
||||
WaylandCompositor.clearTextInputFallbackListener(guestListener)
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
detached.second?.let { requestCancel(it) }
|
||||
detached.first?.shutdown()
|
||||
if (detached.third != 0) complete(detached.third)
|
||||
}
|
||||
|
||||
private fun enqueue(text: String, received: Long, token: Int) {
|
||||
val currentFocus = synchronized(lock) { if (active && generation == received) focusCheck else null }
|
||||
if (currentFocus == null || !currentFocus() || !WaylandCompositor.isTextInputFallbackListener(guestListener)) {
|
||||
Log.d(TAG, "guest text fallback skipped outside the active focused session")
|
||||
complete(token)
|
||||
return
|
||||
}
|
||||
val bytes = text.toByteArray(Charsets.UTF_8)
|
||||
if (bytes.isEmpty() || bytes.size > MAX_BYTES) {
|
||||
complete(token)
|
||||
return
|
||||
}
|
||||
val queue = synchronized(lock) {
|
||||
if (active && generation == received) executor else null
|
||||
}
|
||||
if (queue == null) {
|
||||
complete(token)
|
||||
return
|
||||
}
|
||||
try {
|
||||
queue.execute {
|
||||
try {
|
||||
val delivery = send(bytes, received, token)
|
||||
if (delivery == TextDelivery.UNRESOLVED) recover(token)
|
||||
else complete(token, delivery)
|
||||
} finally {
|
||||
releaseRunning(token)
|
||||
}
|
||||
}
|
||||
} catch (e: RejectedExecutionException) {
|
||||
complete(token)
|
||||
}
|
||||
}
|
||||
|
||||
private fun recover(token: Int) {
|
||||
if (probe()) {
|
||||
complete(token)
|
||||
return
|
||||
}
|
||||
val marked = synchronized(lock) {
|
||||
if (pendingToken == token && failedToken == 0) {
|
||||
failedToken = token
|
||||
WaylandCompositor.completeTextInputFallback(token, TextDelivery.UNRESOLVED.result)
|
||||
scheduleRetryLocked(token, INITIAL_DELAY_MS)
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
if (marked) Log.w(TAG, "text injection could not be confirmed")
|
||||
}
|
||||
|
||||
private fun scheduleRetryLocked(token: Int, delayMs: Long) {
|
||||
if (!active || failedToken != token || pendingToken != token) return
|
||||
val queue = executor ?: return
|
||||
val current = generation
|
||||
try {
|
||||
queue.schedule({ retryProbe(current, token, delayMs) }, delayMs, TimeUnit.MILLISECONDS)
|
||||
} catch (e: RejectedExecutionException) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun retryProbe(received: Long, token: Int, delayMs: Long) {
|
||||
val ready = synchronized(lock) {
|
||||
active && generation == received && failedToken == token && pendingToken == token
|
||||
}
|
||||
if (!ready) return
|
||||
val proven = probe()
|
||||
val owned = synchronized(lock) {
|
||||
if (proven) {
|
||||
if (active && generation == received && failedToken == token && pendingToken == token) {
|
||||
pendingToken = 0
|
||||
runningToken = 0
|
||||
failedToken = 0
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
if (active && generation == received && failedToken == token && pendingToken == token) {
|
||||
val next = (delayMs * 2).coerceAtMost(MAX_DELAY_MS)
|
||||
scheduleRetryLocked(token, next)
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
if (owned) WaylandCompositor.completeTextInputFallback(token, TextDelivery.NOT_DELIVERED.result)
|
||||
}
|
||||
|
||||
private fun probe(): Boolean {
|
||||
val live = LocalSocket()
|
||||
return try {
|
||||
live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM))
|
||||
live.soTimeout = TIMEOUT_MS
|
||||
val out = live.outputStream
|
||||
out.write(lengthPrefix(0))
|
||||
out.flush()
|
||||
live.inputStream.read() == 0
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "could not probe guest text input state", e)
|
||||
false
|
||||
} finally {
|
||||
close(live)
|
||||
}
|
||||
}
|
||||
|
||||
private fun complete(token: Int, delivery: TextDelivery = TextDelivery.NOT_DELIVERED) {
|
||||
val owned = synchronized(lock) {
|
||||
if (pendingToken == token) {
|
||||
pendingToken = 0
|
||||
runningToken = 0
|
||||
failedToken = 0
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
if (owned) WaylandCompositor.completeTextInputFallback(token, delivery.result)
|
||||
}
|
||||
|
||||
private fun releaseRunning(token: Int) {
|
||||
synchronized(lock) {
|
||||
if (runningToken == token) runningToken = 0
|
||||
}
|
||||
}
|
||||
|
||||
private fun send(bytes: ByteArray, received: Long, token: Int): TextDelivery {
|
||||
val live = LocalSocket()
|
||||
if (!claim(live, received, token)) {
|
||||
close(live)
|
||||
return TextDelivery.NOT_DELIVERED
|
||||
}
|
||||
var requested = false
|
||||
try {
|
||||
live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM))
|
||||
live.soTimeout = TIMEOUT_MS
|
||||
if (!isCurrent(received)) return TextDelivery.NOT_DELIVERED
|
||||
val out = live.outputStream
|
||||
out.write(lengthPrefix(bytes.size))
|
||||
requested = true
|
||||
out.write(bytes)
|
||||
out.flush()
|
||||
val input = live.inputStream
|
||||
val ack = try {
|
||||
input.read()
|
||||
} catch (e: IOException) {
|
||||
// Android may report a socket read timeout as a plain IOException.
|
||||
requestCancel(live)
|
||||
input.read()
|
||||
}
|
||||
if (ack == 0) Log.d(TAG, "guest did not complete text delivery")
|
||||
if (ack != 0 && ack != 1 && isCurrent(received)) Log.w(TAG, "guest did not acknowledge text delivery")
|
||||
return when (ack) {
|
||||
1 -> TextDelivery.DELIVERED
|
||||
0 -> TextDelivery.NOT_DELIVERED
|
||||
else -> TextDelivery.UNRESOLVED
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
if (isCurrent(received)) Log.w(TAG, "could not hand text to the guest", e)
|
||||
if (!requested) return TextDelivery.NOT_DELIVERED
|
||||
return TextDelivery.UNRESOLVED
|
||||
} finally {
|
||||
release(live)
|
||||
close(live)
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestCancel(live: LocalSocket) {
|
||||
try {
|
||||
live.shutdownOutput()
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "could not request guest text input cancellation", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isCurrent(received: Long) = synchronized(lock) { active && generation == received }
|
||||
|
||||
private fun claim(live: LocalSocket, received: Long, token: Int) = synchronized(lock) {
|
||||
if (!active || generation != received || pendingToken != token || runningToken != 0 || failedToken != 0) {
|
||||
false
|
||||
} else {
|
||||
runningToken = token
|
||||
socket = live
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
private fun release(live: LocalSocket) {
|
||||
synchronized(lock) {
|
||||
if (socket === live) socket = null
|
||||
}
|
||||
}
|
||||
|
||||
private fun endpoint(): File = File(LinuxRuntime.sessionRoot(appContext), "text-input.sock")
|
||||
|
||||
private fun lengthPrefix(size: Int): ByteArray {
|
||||
val flagged = if (size == 0) size else size or Int.MIN_VALUE
|
||||
return byteArrayOf(
|
||||
(flagged ushr 24).toByte(),
|
||||
(flagged ushr 16).toByte(),
|
||||
(flagged ushr 8).toByte(),
|
||||
flagged.toByte(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun close(sock: LocalSocket) {
|
||||
try {
|
||||
sock.close()
|
||||
} catch (e: IOException) {
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "SessionTextInput"
|
||||
const val MAX_BYTES = 65536
|
||||
const val TIMEOUT_MS = 3000
|
||||
const val INITIAL_DELAY_MS = 500L
|
||||
const val MAX_DELAY_MS = 5000L
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -224,6 +233,70 @@ class GuestWorker60 : GuestWorker()
|
||||
class GuestWorker61 : GuestWorker()
|
||||
class GuestWorker62 : GuestWorker()
|
||||
class GuestWorker63 : GuestWorker()
|
||||
class GuestWorker64 : GuestWorker()
|
||||
class GuestWorker65 : GuestWorker()
|
||||
class GuestWorker66 : GuestWorker()
|
||||
class GuestWorker67 : GuestWorker()
|
||||
class GuestWorker68 : GuestWorker()
|
||||
class GuestWorker69 : GuestWorker()
|
||||
class GuestWorker70 : GuestWorker()
|
||||
class GuestWorker71 : GuestWorker()
|
||||
class GuestWorker72 : GuestWorker()
|
||||
class GuestWorker73 : GuestWorker()
|
||||
class GuestWorker74 : GuestWorker()
|
||||
class GuestWorker75 : GuestWorker()
|
||||
class GuestWorker76 : GuestWorker()
|
||||
class GuestWorker77 : GuestWorker()
|
||||
class GuestWorker78 : GuestWorker()
|
||||
class GuestWorker79 : GuestWorker()
|
||||
class GuestWorker80 : GuestWorker()
|
||||
class GuestWorker81 : GuestWorker()
|
||||
class GuestWorker82 : GuestWorker()
|
||||
class GuestWorker83 : GuestWorker()
|
||||
class GuestWorker84 : GuestWorker()
|
||||
class GuestWorker85 : GuestWorker()
|
||||
class GuestWorker86 : GuestWorker()
|
||||
class GuestWorker87 : GuestWorker()
|
||||
class GuestWorker88 : GuestWorker()
|
||||
class GuestWorker89 : GuestWorker()
|
||||
class GuestWorker90 : GuestWorker()
|
||||
class GuestWorker91 : GuestWorker()
|
||||
class GuestWorker92 : GuestWorker()
|
||||
class GuestWorker93 : GuestWorker()
|
||||
class GuestWorker94 : GuestWorker()
|
||||
class GuestWorker95 : GuestWorker()
|
||||
class GuestWorker96 : GuestWorker()
|
||||
class GuestWorker97 : GuestWorker()
|
||||
class GuestWorker98 : GuestWorker()
|
||||
class GuestWorker99 : GuestWorker()
|
||||
class GuestWorker100 : GuestWorker()
|
||||
class GuestWorker101 : GuestWorker()
|
||||
class GuestWorker102 : GuestWorker()
|
||||
class GuestWorker103 : GuestWorker()
|
||||
class GuestWorker104 : GuestWorker()
|
||||
class GuestWorker105 : GuestWorker()
|
||||
class GuestWorker106 : GuestWorker()
|
||||
class GuestWorker107 : GuestWorker()
|
||||
class GuestWorker108 : GuestWorker()
|
||||
class GuestWorker109 : GuestWorker()
|
||||
class GuestWorker110 : GuestWorker()
|
||||
class GuestWorker111 : GuestWorker()
|
||||
class GuestWorker112 : GuestWorker()
|
||||
class GuestWorker113 : GuestWorker()
|
||||
class GuestWorker114 : GuestWorker()
|
||||
class GuestWorker115 : GuestWorker()
|
||||
class GuestWorker116 : GuestWorker()
|
||||
class GuestWorker117 : GuestWorker()
|
||||
class GuestWorker118 : GuestWorker()
|
||||
class GuestWorker119 : GuestWorker()
|
||||
class GuestWorker120 : GuestWorker()
|
||||
class GuestWorker121 : GuestWorker()
|
||||
class GuestWorker122 : GuestWorker()
|
||||
class GuestWorker123 : GuestWorker()
|
||||
class GuestWorker124 : GuestWorker()
|
||||
class GuestWorker125 : GuestWorker()
|
||||
class GuestWorker126 : GuestWorker()
|
||||
class GuestWorker127 : GuestWorker()
|
||||
|
||||
/** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */
|
||||
object GuestWorkers {
|
||||
@@ -250,7 +323,28 @@ object GuestWorkers {
|
||||
GuestWorker54::class.java, GuestWorker55::class.java, GuestWorker56::class.java,
|
||||
GuestWorker57::class.java, GuestWorker58::class.java, GuestWorker59::class.java,
|
||||
GuestWorker60::class.java, GuestWorker61::class.java, GuestWorker62::class.java,
|
||||
GuestWorker63::class.java,
|
||||
GuestWorker63::class.java, GuestWorker64::class.java, GuestWorker65::class.java,
|
||||
GuestWorker66::class.java, GuestWorker67::class.java, GuestWorker68::class.java,
|
||||
GuestWorker69::class.java, GuestWorker70::class.java, GuestWorker71::class.java,
|
||||
GuestWorker72::class.java, GuestWorker73::class.java, GuestWorker74::class.java,
|
||||
GuestWorker75::class.java, GuestWorker76::class.java, GuestWorker77::class.java,
|
||||
GuestWorker78::class.java, GuestWorker79::class.java, GuestWorker80::class.java,
|
||||
GuestWorker81::class.java, GuestWorker82::class.java, GuestWorker83::class.java,
|
||||
GuestWorker84::class.java, GuestWorker85::class.java, GuestWorker86::class.java,
|
||||
GuestWorker87::class.java, GuestWorker88::class.java, GuestWorker89::class.java,
|
||||
GuestWorker90::class.java, GuestWorker91::class.java, GuestWorker92::class.java,
|
||||
GuestWorker93::class.java, GuestWorker94::class.java, GuestWorker95::class.java,
|
||||
GuestWorker96::class.java, GuestWorker97::class.java, GuestWorker98::class.java,
|
||||
GuestWorker99::class.java, GuestWorker100::class.java, GuestWorker101::class.java,
|
||||
GuestWorker102::class.java, GuestWorker103::class.java, GuestWorker104::class.java,
|
||||
GuestWorker105::class.java, GuestWorker106::class.java, GuestWorker107::class.java,
|
||||
GuestWorker108::class.java, GuestWorker109::class.java, GuestWorker110::class.java,
|
||||
GuestWorker111::class.java, GuestWorker112::class.java, GuestWorker113::class.java,
|
||||
GuestWorker114::class.java, GuestWorker115::class.java, GuestWorker116::class.java,
|
||||
GuestWorker117::class.java, GuestWorker118::class.java, GuestWorker119::class.java,
|
||||
GuestWorker120::class.java, GuestWorker121::class.java, GuestWorker122::class.java,
|
||||
GuestWorker123::class.java, GuestWorker124::class.java, GuestWorker125::class.java,
|
||||
GuestWorker126::class.java, GuestWorker127::class.java,
|
||||
)
|
||||
|
||||
private class Slot(val index: Int) {
|
||||
@@ -310,9 +404,10 @@ object GuestWorkers {
|
||||
private set
|
||||
|
||||
/** Whether the session runs its programs in workers: the native userland, and not turned off. */
|
||||
fun enabled(context: Context): Boolean =
|
||||
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context) &&
|
||||
NativeGuest.enabled(context)
|
||||
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)
|
||||
|
||||
/** How the running session's root was started: in a worker (true) or counted (false); null with none running. */
|
||||
@Volatile var sessionRootUncounted: Boolean? = null
|
||||
@@ -323,7 +418,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 } }
|
||||
@@ -351,7 +446,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") +
|
||||
@@ -387,13 +483,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 }
|
||||
@@ -422,7 +526,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
|
||||
@@ -599,6 +708,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) }
|
||||
@@ -816,16 +926,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
|
||||
@@ -844,7 +957,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() } }
|
||||
|
||||
@@ -35,9 +35,40 @@ object LegacyNames {
|
||||
@Synchronized
|
||||
fun migrateEtc(root: File) {
|
||||
for ((old, new) in LINKED_DIRS) moveAndLink(File(root, old), File(root, new))
|
||||
File(root, "etc/droiddeck/empty").mkdirs()
|
||||
clearEmptyStandIn(root)
|
||||
File(root, NO_THERMAL).mkdirs()
|
||||
}
|
||||
|
||||
/**
|
||||
* It stands in for /sys/bus/pci/devices, and libpci exits the whole process on an entry it cannot
|
||||
* parse; older builds let thermal bind mount points leak into it. The guest can write here, so a
|
||||
* link is never followed: one in place of the folder is removed, and one above it stops the cleanup.
|
||||
*/
|
||||
private fun clearEmptyStandIn(root: File) {
|
||||
val linkedAbove = listOf("etc", "etc/droiddeck").firstOrNull { Files.isSymbolicLink(File(root, it).toPath()) }
|
||||
if (linkedAbove != null) {
|
||||
Log.w(TAG, "not clearing the empty stand-in: $linkedAbove is a link")
|
||||
return
|
||||
}
|
||||
val empty = File(root, "etc/droiddeck/empty")
|
||||
if (Files.isSymbolicLink(empty.toPath())) runCatching { Files.delete(empty.toPath()) }
|
||||
.onFailure { Log.w(TAG, "could not remove the link at $empty", it); return }
|
||||
empty.mkdirs()
|
||||
empty.listFiles()?.forEach { entry ->
|
||||
runCatching { deleteWithoutFollowing(entry.toPath()) }.onFailure { Log.w(TAG, "could not clear $entry", it) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun deleteWithoutFollowing(path: java.nio.file.Path) {
|
||||
if (Files.isDirectory(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
|
||||
Files.newDirectoryStream(path).use { entries -> entries.forEach(::deleteWithoutFollowing) }
|
||||
}
|
||||
Files.deleteIfExists(path)
|
||||
}
|
||||
|
||||
/** Stands in for a /sys/class/thermal the kernel won't list; proot adds the bound zones' mount points to it. */
|
||||
const val NO_THERMAL = "etc/droiddeck/no-thermal"
|
||||
|
||||
@Synchronized
|
||||
fun migrateRootfs(root: File) {
|
||||
migrateEtc(root)
|
||||
|
||||
@@ -248,7 +248,7 @@ public final class LinuxRuntime {
|
||||
// A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort
|
||||
// at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its
|
||||
// wrapper gave up: it lists the directory for CPU temperatures. Empty there instead.
|
||||
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal");
|
||||
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, LegacyNames.NO_THERMAL).getPath() + ":/sys/class/thermal");
|
||||
bind(cmd, context.getFilesDir().getPath());
|
||||
bind(cmd, context.getCacheDir().getPath());
|
||||
bind(cmd, liveDir(context).getPath());
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -219,6 +219,19 @@ object BottomDesktop {
|
||||
|
||||
fun sendText(text: String) {
|
||||
val target = service ?: return
|
||||
if (text.isNotEmpty() && text.all { it == '\r' || it == '\n' || it == '\b' || it == '\u007f' || it == '\t' }) {
|
||||
for (c in text) {
|
||||
val evdev = when (c) {
|
||||
'\r', '\n' -> 28
|
||||
'\b' -> 14
|
||||
'\u007f' -> 111
|
||||
else -> 15
|
||||
}
|
||||
sendKey(evdev, true)
|
||||
sendKey(evdev, false)
|
||||
}
|
||||
return
|
||||
}
|
||||
send(target, Message.obtain(null, Comp.MSG_TEXT).apply { data = Bundle().apply { putString(Comp.KEY_TEXT, text) } })
|
||||
}
|
||||
|
||||
|
||||
@@ -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? =
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
import com.droiddeck.launcher.runtime.LegacyNames
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object SessionFiles {
|
||||
@@ -21,6 +22,8 @@ object SessionFiles {
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
||||
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
|
||||
private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json"
|
||||
private const val IME_DEFAULT_MODE = 420
|
||||
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
|
||||
|
||||
internal val DESKTOP_FILES = arrayOf(
|
||||
@@ -133,6 +136,8 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn",
|
||||
"usr/local/bin/droiddeck-log-writer" to "usr/local/bin/droiddeck-log-writer",
|
||||
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
|
||||
"usr/local/bin/droiddeck-text-input" to "usr/local/bin/droiddeck-text-input",
|
||||
"usr/local/bin/droiddeck-steam-ime" to "usr/local/bin/droiddeck-steam-ime",
|
||||
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
|
||||
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
|
||||
"usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply",
|
||||
@@ -335,6 +340,7 @@ object SessionFiles {
|
||||
if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged")
|
||||
}
|
||||
for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger)
|
||||
stageImeFiles(context, root, ledger)
|
||||
ledger.save()
|
||||
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
|
||||
val preload = StringBuilder("/usr/local/lib/libddsession.so\n")
|
||||
@@ -421,6 +427,42 @@ object SessionFiles {
|
||||
seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
|
||||
}
|
||||
|
||||
private fun stageImeFiles(context: Context, root: File, ledger: StageLedger) {
|
||||
val entries = LinkedHashMap<String, Int>()
|
||||
try {
|
||||
val text = context.assets.open("linuxfs/$IME_MANIFEST").bufferedReader().use { it.readText() }
|
||||
val files = JSONObject(text).getJSONObject("files")
|
||||
for (name in files.keys()) {
|
||||
entries[name] = files.optJSONObject(name)?.optString("mode").orEmpty().toIntOrNull(8) ?: IME_DEFAULT_MODE
|
||||
}
|
||||
entries[IME_MANIFEST] = IME_DEFAULT_MODE
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "the Chinese input payload is not bundled; Steam sessions start without it", e)
|
||||
return
|
||||
}
|
||||
for ((relative, mode) in entries) {
|
||||
val target = File(root, relative)
|
||||
if (ledger.current(relative, target)) continue
|
||||
val staged = File(target.parentFile, target.name + ".staged")
|
||||
var installed = false
|
||||
try {
|
||||
target.parentFile?.mkdirs()
|
||||
context.assets.open("linuxfs/$relative").use { input ->
|
||||
staged.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
installed = staged.setReadable(true, false) &&
|
||||
staged.setWritable((mode and 0x80) != 0, true) &&
|
||||
staged.setExecutable((mode and 0x49) != 0, false) &&
|
||||
staged.renameTo(target)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not stage $relative", e)
|
||||
} finally {
|
||||
if (!installed) staged.delete()
|
||||
}
|
||||
if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
|
||||
synchronized(STEAM_CONFIG) {
|
||||
if (!config.isFile) return true
|
||||
|
||||
@@ -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,10 +1887,17 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean(hdrKey(mode), on).apply()
|
||||
}
|
||||
|
||||
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.$mode", true)
|
||||
/** 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) {
|
||||
prefs(context).edit().putBoolean("zeroCopy.$mode", on).apply()
|
||||
prefs(context).edit().putBoolean("zeroCopy.${prefMode(mode)}", on).apply()
|
||||
}
|
||||
|
||||
const val FPS_UNPACED = -1
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
/**
|
||||
* The menu gesture: both controllers held together. It arms when the two aim points come within
|
||||
* [ARM_METRES], cancels once they part beyond [CANCEL_METRES], and fires after [HOLD_MS] held.
|
||||
* It needs both controllers apart again before it can arm a second time.
|
||||
*/
|
||||
internal class XrGesture {
|
||||
enum class Phase { IDLE, ARMING, FIRED }
|
||||
|
||||
var phase = Phase.IDLE
|
||||
private set
|
||||
var progress = 0f
|
||||
private set
|
||||
var midpoint = Vec3.ZERO
|
||||
private set
|
||||
private var startedMs = 0L
|
||||
private var needsRelease = false
|
||||
|
||||
/** Returns true on the frame the gesture completes. */
|
||||
fun update(left: XrHand, right: XrHand, nowMs: Long): Boolean {
|
||||
if (!left.active || !right.active) {
|
||||
reset(release = false)
|
||||
return false
|
||||
}
|
||||
val a = left.aim.position
|
||||
val b = right.aim.position
|
||||
val distance = (a - b).length
|
||||
midpoint = Vec3.lerp(a, b, 0.5f)
|
||||
if (needsRelease) {
|
||||
if (distance > CANCEL_METRES) needsRelease = false
|
||||
phase = Phase.IDLE
|
||||
progress = 0f
|
||||
return false
|
||||
}
|
||||
when (phase) {
|
||||
Phase.IDLE, Phase.FIRED -> if (distance < ARM_METRES) {
|
||||
phase = Phase.ARMING
|
||||
startedMs = nowMs
|
||||
progress = 0f
|
||||
}
|
||||
Phase.ARMING -> if (distance > CANCEL_METRES) {
|
||||
phase = Phase.IDLE
|
||||
progress = 0f
|
||||
} else {
|
||||
progress = ((nowMs - startedMs).toFloat() / HOLD_MS).coerceIn(0f, 1f)
|
||||
if (progress >= 1f) {
|
||||
phase = Phase.FIRED
|
||||
needsRelease = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun reset(release: Boolean) {
|
||||
phase = Phase.IDLE
|
||||
progress = 0f
|
||||
if (release) needsRelease = true
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ARM_METRES = 0.09f
|
||||
const val CANCEL_METRES = 0.14f
|
||||
const val HOLD_MS = 1500L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* Typed access to the two buffers quest_xr.cpp shares each frame (app/src/main/cpp/questxr/xr_host.h).
|
||||
* The offsets here must match that header.
|
||||
*/
|
||||
internal object XrHostLayout {
|
||||
const val VERSION = 1
|
||||
const val LAYERS = 6
|
||||
const val STATE_SIZE = 288
|
||||
const val CONTROL_SIZE = 552
|
||||
const val POSE_SIZE = 32
|
||||
const val HAND_SIZE = 96
|
||||
const val STATE_HEAD = 32
|
||||
const val STATE_HANDS = 64
|
||||
const val HAND_GRIP = 0
|
||||
const val HAND_AIM = 32
|
||||
const val HAND_TRIGGER = 64
|
||||
const val HAND_SQUEEZE = 68
|
||||
const val HAND_STICK = 72
|
||||
const val HAND_BUTTONS = 80
|
||||
const val HAND_ACTIVE = 84
|
||||
const val CONTROL_HANDS = 8
|
||||
const val HAND_CONTROL_SIZE = 40
|
||||
const val HAND_CONTROL_MASK = 0
|
||||
const val HAND_CONTROL_LASER = 4
|
||||
const val HAND_CONTROL_HAPTIC = 8
|
||||
const val CONTROL_ORB = 88
|
||||
const val CONTROL_LAYERS = 136
|
||||
const val LAYER_SIZE = 64
|
||||
|
||||
const val FLAG_SURFACE_SWAPCHAIN = 1
|
||||
const val FLAG_FOCUSED = 2
|
||||
const val MASK_INPUT = 1
|
||||
const val LAYER_ALPHA = 1
|
||||
const val LAYER_HEAD_LOCKED = 2
|
||||
|
||||
const val SECONDARY_CLICK = 1 shl 2
|
||||
}
|
||||
|
||||
internal class XrHand(
|
||||
val grip: Pose,
|
||||
val aim: Pose,
|
||||
val trigger: Float,
|
||||
val squeeze: Float,
|
||||
val stickX: Float,
|
||||
val stickY: Float,
|
||||
val buttons: Int,
|
||||
val active: Boolean,
|
||||
) {
|
||||
val secondary: Boolean get() = buttons and XrHostLayout.SECONDARY_CLICK != 0
|
||||
|
||||
companion object {
|
||||
val IDLE = XrHand(Pose(), Pose(), 0f, 0f, 0f, 0f, 0, false)
|
||||
}
|
||||
}
|
||||
|
||||
internal class XrFrame(val flags: Int, val frame: Long, val displayTimeNs: Long, val head: Pose, val hands: List<XrHand>) {
|
||||
val focused: Boolean get() = flags and XrHostLayout.FLAG_FOCUSED != 0
|
||||
val surfaces: Boolean get() = flags and XrHostLayout.FLAG_SURFACE_SWAPCHAIN != 0
|
||||
}
|
||||
|
||||
internal class XrHaptic(val durationMs: Int, val amplitude: Float, val frequency: Float = 0f)
|
||||
|
||||
internal class XrLayerOut(
|
||||
val id: Int,
|
||||
val pose: Pose,
|
||||
val width: Float,
|
||||
val height: Float,
|
||||
val order: Int,
|
||||
val alpha: Boolean = true,
|
||||
)
|
||||
|
||||
internal class XrControlOut {
|
||||
val masks = BooleanArray(2)
|
||||
val lasers = FloatArray(2)
|
||||
val haptics = arrayOfNulls<XrHaptic>(2)
|
||||
var orb: Orb? = null
|
||||
val layers = mutableListOf<XrLayerOut>()
|
||||
|
||||
class Orb(val position: Vec3, val radius: Float, val progress: Float, val burst: Float)
|
||||
}
|
||||
|
||||
internal class XrHost(state: ByteBuffer, control: ByteBuffer) {
|
||||
private val state = state.order(ByteOrder.nativeOrder())
|
||||
private val control = control.order(ByteOrder.nativeOrder())
|
||||
private val hapticIds = LongArray(2)
|
||||
|
||||
init {
|
||||
require(state.capacity() >= XrHostLayout.STATE_SIZE && control.capacity() >= XrHostLayout.CONTROL_SIZE) { "XR host buffers too small" }
|
||||
}
|
||||
|
||||
fun read(): XrFrame = readFrame(state)
|
||||
|
||||
fun write(out: XrControlOut) = writeControl(control, out, hapticIds)
|
||||
|
||||
companion object {
|
||||
fun readPose(b: ByteBuffer, at: Int) = Pose(
|
||||
Quat(b.getFloat(at), b.getFloat(at + 4), b.getFloat(at + 8), b.getFloat(at + 12)),
|
||||
Vec3(b.getFloat(at + 16), b.getFloat(at + 20), b.getFloat(at + 24)),
|
||||
)
|
||||
|
||||
fun writePose(b: ByteBuffer, at: Int, pose: Pose) {
|
||||
b.putFloat(at, pose.orientation.x); b.putFloat(at + 4, pose.orientation.y)
|
||||
b.putFloat(at + 8, pose.orientation.z); b.putFloat(at + 12, pose.orientation.w)
|
||||
b.putFloat(at + 16, pose.position.x); b.putFloat(at + 20, pose.position.y); b.putFloat(at + 24, pose.position.z)
|
||||
b.putInt(at + 28, 0)
|
||||
}
|
||||
|
||||
fun readFrame(b: ByteBuffer): XrFrame {
|
||||
val hands = (0 until 2).map { hand ->
|
||||
val at = XrHostLayout.STATE_HANDS + hand * XrHostLayout.HAND_SIZE
|
||||
XrHand(
|
||||
readPose(b, at + XrHostLayout.HAND_GRIP), readPose(b, at + XrHostLayout.HAND_AIM),
|
||||
b.getFloat(at + XrHostLayout.HAND_TRIGGER), b.getFloat(at + XrHostLayout.HAND_SQUEEZE),
|
||||
b.getFloat(at + XrHostLayout.HAND_STICK), b.getFloat(at + XrHostLayout.HAND_STICK + 4),
|
||||
b.getInt(at + XrHostLayout.HAND_BUTTONS), b.getInt(at + XrHostLayout.HAND_ACTIVE) != 0,
|
||||
)
|
||||
}
|
||||
return XrFrame(b.getInt(8), b.getLong(16), b.getLong(24), readPose(b, XrHostLayout.STATE_HEAD), hands)
|
||||
}
|
||||
|
||||
fun writeControl(b: ByteBuffer, out: XrControlOut, hapticIds: LongArray) {
|
||||
for (i in 0 until XrHostLayout.CONTROL_SIZE step 4) b.putInt(i, 0)
|
||||
b.putInt(0, XrHostLayout.VERSION)
|
||||
for (hand in 0 until 2) {
|
||||
val at = XrHostLayout.CONTROL_HANDS + hand * XrHostLayout.HAND_CONTROL_SIZE
|
||||
b.putInt(at + XrHostLayout.HAND_CONTROL_MASK, if (out.masks[hand]) XrHostLayout.MASK_INPUT else 0)
|
||||
b.putFloat(at + XrHostLayout.HAND_CONTROL_LASER, out.lasers[hand])
|
||||
out.haptics[hand]?.let { hapticIds[hand]++ }
|
||||
val haptic = at + XrHostLayout.HAND_CONTROL_HAPTIC
|
||||
b.putLong(haptic, hapticIds[hand])
|
||||
out.haptics[hand]?.let {
|
||||
b.putLong(haptic + 8, it.durationMs * 1_000_000L)
|
||||
b.putFloat(haptic + 16, it.amplitude)
|
||||
b.putFloat(haptic + 20, it.frequency)
|
||||
}
|
||||
}
|
||||
out.orb?.let { orb ->
|
||||
val at = XrHostLayout.CONTROL_ORB
|
||||
b.putInt(at, 1)
|
||||
b.putFloat(at + 4, orb.progress); b.putFloat(at + 8, orb.burst); b.putFloat(at + 12, orb.radius)
|
||||
writePose(b, at + 16, Pose(position = orb.position))
|
||||
}
|
||||
out.layers.take(XrHostLayout.LAYERS).forEachIndexed { index, layer ->
|
||||
val at = XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE
|
||||
b.putInt(at, layer.id)
|
||||
b.putInt(at + 4, 1)
|
||||
b.putInt(at + 8, if (layer.alpha) XrHostLayout.LAYER_ALPHA else 0)
|
||||
b.putInt(at + 12, layer.order)
|
||||
writePose(b, at + 16, layer.pose)
|
||||
b.putFloat(at + 48, layer.width); b.putFloat(at + 52, layer.height)
|
||||
}
|
||||
for (index in out.layers.size until XrHostLayout.LAYERS) b.putInt(XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE, -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* [barButton]: the grab bar has a button at its left end; the menu has its own close button instead.
|
||||
* [tilt]: how far the panel leans back from upright, in radians, as a keyboard lies on a desk.
|
||||
*/
|
||||
internal enum class XrPanelKind(
|
||||
val key: String, val resizable: Boolean, val chrome: Boolean, val barButton: Boolean = false, val tilt: Float = 0f,
|
||||
) {
|
||||
MENU("menu", resizable = true, chrome = true),
|
||||
PET_HEAD("pet_head", resizable = false, chrome = false),
|
||||
PET_CHAT("pet_chat", resizable = true, chrome = true, barButton = true),
|
||||
KEYBOARD("keyboard_desk", resizable = true, chrome = true, barButton = true, tilt = (PI / 4).toFloat());
|
||||
|
||||
/** Turned towards [head] about the vertical axis, then leant back by [tilt]. */
|
||||
fun orient(position: Vec3, head: Vec3): Quat = facing(position, head) * Quat.pitch(-tilt)
|
||||
}
|
||||
|
||||
/** Where a panel is and how big, in metres; [pixelWidth] and [pixelHeight] are its surface's size. */
|
||||
internal class XrPanelState(val kind: XrPanelKind, var pose: Pose, var width: Float, var height: Float) {
|
||||
var pixelWidth = XrUnits.pixels(width)
|
||||
var pixelHeight = XrUnits.pixels(height)
|
||||
/** 0 while it opens or closes from [animationFrom], 1 when it is in place and takes input. */
|
||||
var scale = 1f
|
||||
var animationFrom: Vec3? = null
|
||||
|
||||
val shownPose: Pose get() = animationFrom?.let { Pose(pose.orientation, Vec3.lerp(it, pose.position, scale)) } ?: pose
|
||||
val interactive: Boolean get() = scale >= 1f
|
||||
|
||||
fun hit(ray: Pose): XrHit? = hitPlane(ray, bounded = true)
|
||||
|
||||
/** Where [ray] meets this panel's plane; [bounded] limits it to the panel itself. */
|
||||
fun hitPlane(ray: Pose, bounded: Boolean, plane: Pose = pose, w: Float = width, h: Float = height): XrHit? {
|
||||
val normal = plane.orientation.rotate(Vec3(0f, 0f, 1f))
|
||||
val direction = ray.forward
|
||||
val denominator = direction dot normal
|
||||
if (denominator > -1e-4f) return null
|
||||
val distance = ((plane.position - ray.position) dot normal) / denominator
|
||||
if (distance <= 0f) return null
|
||||
val local = plane.toLocal(ray.position + direction * distance)
|
||||
if (bounded && (abs(local.x) > w / 2f || abs(local.y) > h / 2f)) return null
|
||||
return XrHit(this, local.x, local.y, distance)
|
||||
}
|
||||
|
||||
fun u(localX: Float) = (localX / width + 0.5f).coerceIn(0f, 1f)
|
||||
fun v(localY: Float) = (0.5f - localY / height).coerceIn(0f, 1f)
|
||||
fun pixelX(localX: Float) = u(localX) * pixelWidth
|
||||
fun pixelY(localY: Float) = v(localY) * pixelHeight
|
||||
|
||||
/** The grab bar runs along the bottom, as under Quest's own windows, with its button at the left end. */
|
||||
fun inBar(hit: XrHit) = kind.chrome && hit.y + 0.5f * height <= XrUnits.BAR_METRES
|
||||
fun inBarButtons(hit: XrHit) = kind.barButton && inBar(hit) && hit.x + 0.5f * width <= XrUnits.BAR_BUTTONS_METRES
|
||||
fun inResizeGrip(hit: XrHit) = kind.resizable &&
|
||||
0.5f * width - hit.x <= XrUnits.GRIP_METRES && hit.y + 0.5f * height <= XrUnits.GRIP_METRES
|
||||
}
|
||||
|
||||
internal class XrHit(val panel: XrPanelState, val x: Float, val y: Float, val distance: Float)
|
||||
|
||||
internal object XrUnits {
|
||||
const val DP_PER_METRE = 900f
|
||||
const val DENSITY = 2f
|
||||
const val DPI = 320
|
||||
const val BAR_METRES = 52f / DP_PER_METRE
|
||||
const val BAR_BUTTONS_DP = 150f
|
||||
const val BAR_BUTTONS_METRES = BAR_BUTTONS_DP / DP_PER_METRE
|
||||
const val GRIP_METRES = 0.05f
|
||||
const val MIN_METRES = 0.3f
|
||||
const val MAX_METRES = 1.6f
|
||||
const val MIN_DISTANCE = 0.4f
|
||||
const val MAX_DISTANCE = 3f
|
||||
fun pixels(metres: Float) = (metres * DP_PER_METRE * DENSITY).toInt().coerceAtLeast(16)
|
||||
}
|
||||
|
||||
internal sealed class XrPointerEvent(val panel: XrPanelState) {
|
||||
class Down(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
|
||||
class Move(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
|
||||
class Up(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
|
||||
class Cancel(panel: XrPanelState, val hand: Int = 0) : XrPointerEvent(panel)
|
||||
class Scroll(panel: XrPanelState, val x: Float, val y: Float, val amount: Float) : XrPointerEvent(panel)
|
||||
class Back(panel: XrPanelState) : XrPointerEvent(panel)
|
||||
class Click(panel: XrPanelState) : XrPointerEvent(panel)
|
||||
class Resized(panel: XrPanelState) : XrPointerEvent(panel)
|
||||
class Moved(panel: XrPanelState) : XrPointerEvent(panel)
|
||||
}
|
||||
|
||||
internal class XrInteractionOut {
|
||||
val events = mutableListOf<XrPointerEvent>()
|
||||
val masks = BooleanArray(2)
|
||||
val lasers = FloatArray(2)
|
||||
val ticks = BooleanArray(2)
|
||||
/** Where each controller points on each panel, in its pixels, left hand first; panels with no entry show none. */
|
||||
val cursors = mutableMapOf<XrPanelState, MutableList<Pair<Float, Float>>>()
|
||||
|
||||
fun point(panel: XrPanelState, x: Float, y: Float) {
|
||||
cursors.getOrPut(panel) { mutableListOf() } += x to y
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the two controllers do to the panels each frame. A controller acts on a panel only while it
|
||||
* points at one, or while it holds one it picked up, pressed or is resizing; only then is its input
|
||||
* taken from the game.
|
||||
*/
|
||||
internal class XrInteraction {
|
||||
private sealed class Hold {
|
||||
object None : Hold()
|
||||
class Press(val panel: XrPanelState, var x: Float, var y: Float) : Hold()
|
||||
class Move(val panel: XrPanelState, var offset: Vec3, val byGrip: Boolean) : Hold()
|
||||
class Resize(val panel: XrPanelState, val plane: Pose, val width: Float, val height: Float, val startX: Float, val startY: Float) : Hold()
|
||||
class HeadPress(val panel: XrPanelState, val startX: Float, val startY: Float, val offset: Vec3) : Hold()
|
||||
}
|
||||
|
||||
private val holds = arrayOf<Hold>(Hold.None, Hold.None)
|
||||
private val trigger = BooleanArray(2)
|
||||
private val grip = BooleanArray(2)
|
||||
private val secondary = BooleanArray(2)
|
||||
|
||||
fun holding(panel: XrPanelState) = holds.any { held(it) === panel }
|
||||
|
||||
private fun held(hold: Hold): XrPanelState? = when (hold) {
|
||||
is Hold.Press -> hold.panel
|
||||
is Hold.Move -> hold.panel
|
||||
is Hold.Resize -> hold.panel
|
||||
is Hold.HeadPress -> hold.panel
|
||||
Hold.None -> null
|
||||
}
|
||||
|
||||
/** Lets go of everything, as when the immersive view goes. A button still held counts only once let go and pressed again. */
|
||||
fun reset() {
|
||||
holds.fill(Hold.None)
|
||||
trigger.fill(true)
|
||||
grip.fill(true)
|
||||
secondary.fill(true)
|
||||
}
|
||||
|
||||
/** Cancels a press and ends a move or resize where it is, as when the headset loses focus; then [reset]. */
|
||||
fun cancel(out: XrInteractionOut) {
|
||||
for ((hand, hold) in holds.withIndex()) when (hold) {
|
||||
is Hold.Press -> out.events += XrPointerEvent.Cancel(hold.panel, hand)
|
||||
is Hold.Move -> out.events += XrPointerEvent.Moved(hold.panel)
|
||||
is Hold.Resize -> out.events += XrPointerEvent.Resized(hold.panel)
|
||||
else -> Unit
|
||||
}
|
||||
reset()
|
||||
}
|
||||
|
||||
/** Lets go of [panel], as when it closes. */
|
||||
fun release(panel: XrPanelState, out: XrInteractionOut) {
|
||||
for (hand in 0..1) if (held(holds[hand]) === panel) {
|
||||
if (holds[hand] is Hold.Press) out.events += XrPointerEvent.Cancel(panel, hand)
|
||||
holds[hand] = Hold.None
|
||||
}
|
||||
}
|
||||
|
||||
fun update(head: Pose, hands: List<XrHand>, panels: List<XrPanelState>, dtSeconds: Float): XrInteractionOut {
|
||||
val out = XrInteractionOut()
|
||||
for (hand in 0..1) handFrame(hand, head, hands[hand], panels.filter { it.interactive }, dtSeconds, out)
|
||||
return out
|
||||
}
|
||||
|
||||
private fun handFrame(index: Int, head: Pose, hand: XrHand, panels: List<XrPanelState>, dt: Float, out: XrInteractionOut) {
|
||||
val wasTrigger = trigger[index]
|
||||
val wasGrip = grip[index]
|
||||
val wasSecondary = secondary[index]
|
||||
trigger[index] = if (wasTrigger) hand.trigger > 0.4f else hand.trigger > 0.6f
|
||||
grip[index] = if (wasGrip) hand.squeeze > 0.5f else hand.squeeze > 0.7f
|
||||
secondary[index] = hand.secondary
|
||||
val triggerDown = trigger[index] && !wasTrigger
|
||||
val triggerUp = !trigger[index] && wasTrigger
|
||||
val gripDown = grip[index] && !wasGrip
|
||||
val secondaryDown = secondary[index] && !wasSecondary
|
||||
val hold = holds[index]
|
||||
if (!hand.active) {
|
||||
if (hold is Hold.Press) out.events += XrPointerEvent.Cancel(hold.panel, index)
|
||||
if (hold is Hold.Move) out.events += XrPointerEvent.Moved(hold.panel)
|
||||
if (hold is Hold.Resize) out.events += XrPointerEvent.Resized(hold.panel)
|
||||
holds[index] = Hold.None
|
||||
return
|
||||
}
|
||||
val ray = hand.aim
|
||||
when (hold) {
|
||||
is Hold.Move -> {
|
||||
val panel = hold.panel
|
||||
if (abs(hand.stickY) > 0.2f) {
|
||||
val length = hold.offset.length
|
||||
val wanted = (length * (1f + hand.stickY * 1.2f * dt)).coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE)
|
||||
hold.offset = hold.offset.normalized() * wanted
|
||||
}
|
||||
val position = ray.toWorld(hold.offset)
|
||||
panel.pose = Pose(panel.kind.orient(position, head.position), position)
|
||||
out.masks[index] = true
|
||||
out.lasers[index] = hold.offset.length
|
||||
val released = if (hold.byGrip) !grip[index] else !trigger[index]
|
||||
if (released) {
|
||||
holds[index] = Hold.None
|
||||
out.events += XrPointerEvent.Moved(panel)
|
||||
}
|
||||
return
|
||||
}
|
||||
is Hold.Resize -> {
|
||||
val panel = hold.panel
|
||||
out.masks[index] = true
|
||||
hold.panel.hitPlane(ray, bounded = false, plane = hold.plane, w = hold.width, h = hold.height)?.let { hit ->
|
||||
val left = -hold.width / 2f
|
||||
val top = hold.height / 2f
|
||||
val width = (hold.width + hit.x - hold.startX).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES)
|
||||
val height = (hold.height + hold.startY - hit.y).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES)
|
||||
panel.width = width
|
||||
panel.height = height
|
||||
panel.pose = Pose(hold.plane.orientation, hold.plane.toWorld(Vec3(left + width / 2f, top - height / 2f, 0f)))
|
||||
out.lasers[index] = hit.distance
|
||||
}
|
||||
if (!trigger[index]) {
|
||||
holds[index] = Hold.None
|
||||
out.events += XrPointerEvent.Resized(panel)
|
||||
}
|
||||
return
|
||||
}
|
||||
is Hold.Press -> {
|
||||
val panel = hold.panel
|
||||
out.masks[index] = true
|
||||
val hit = panel.hitPlane(ray, bounded = false)
|
||||
if (hit != null) {
|
||||
val x = panel.pixelX(hit.x)
|
||||
val y = panel.pixelY(hit.y)
|
||||
if (x != hold.x || y != hold.y) out.events += XrPointerEvent.Move(panel, x, y, index)
|
||||
hold.x = x; hold.y = y
|
||||
out.lasers[index] = hit.distance
|
||||
out.point(panel, x, y)
|
||||
}
|
||||
if (secondaryDown) out.events += XrPointerEvent.Back(panel)
|
||||
if (triggerUp || !trigger[index]) {
|
||||
out.events += if (hit != null) XrPointerEvent.Up(panel, hold.x, hold.y, index) else XrPointerEvent.Cancel(panel, index)
|
||||
holds[index] = Hold.None
|
||||
}
|
||||
return
|
||||
}
|
||||
is Hold.HeadPress -> {
|
||||
val panel = hold.panel
|
||||
out.masks[index] = true
|
||||
val hit = panel.hitPlane(ray, bounded = false)
|
||||
if (hit != null) {
|
||||
out.lasers[index] = hit.distance
|
||||
val moved = Vec3(hit.x - hold.startX, hit.y - hold.startY, 0f).length
|
||||
if (moved > HEAD_DRAG_METRES) {
|
||||
holds[index] = Hold.Move(panel, hold.offset, byGrip = false)
|
||||
val position = ray.toWorld(hold.offset)
|
||||
panel.pose = Pose(panel.kind.orient(position, head.position), position)
|
||||
return
|
||||
}
|
||||
}
|
||||
if (!trigger[index]) {
|
||||
holds[index] = Hold.None
|
||||
if (panel.hit(ray) != null) out.events += XrPointerEvent.Click(panel)
|
||||
}
|
||||
return
|
||||
}
|
||||
Hold.None -> Unit
|
||||
}
|
||||
val hit = panels.mapNotNull { it.hit(ray) }.minByOrNull { it.distance } ?: return
|
||||
val panel = hit.panel
|
||||
out.masks[index] = true
|
||||
out.lasers[index] = hit.distance
|
||||
val x = panel.pixelX(hit.x)
|
||||
val y = panel.pixelY(hit.y)
|
||||
out.point(panel, x, y)
|
||||
val other = holds[1 - index]
|
||||
val heldByOther = held(other) === panel && other !is Hold.Press
|
||||
when {
|
||||
heldByOther -> Unit
|
||||
gripDown -> {
|
||||
holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = true)
|
||||
out.ticks[index] = true
|
||||
}
|
||||
triggerDown && panel.kind == XrPanelKind.PET_HEAD ->
|
||||
holds[index] = Hold.HeadPress(panel, hit.x, hit.y, ray.toLocal(panel.pose.position))
|
||||
triggerDown && panel.inResizeGrip(hit) -> {
|
||||
holds[index] = Hold.Resize(panel, panel.pose, panel.width, panel.height, hit.x, hit.y)
|
||||
out.ticks[index] = true
|
||||
}
|
||||
triggerDown && panel.inBar(hit) && !panel.inBarButtons(hit) -> {
|
||||
holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = false)
|
||||
out.ticks[index] = true
|
||||
}
|
||||
triggerDown -> {
|
||||
holds[index] = Hold.Press(panel, x, y)
|
||||
out.events += XrPointerEvent.Down(panel, x, y, index)
|
||||
}
|
||||
}
|
||||
if (holds[index] === Hold.None) {
|
||||
if (abs(hand.stickY) > 0.25f) out.events += XrPointerEvent.Scroll(panel, x, y, hand.stickY * SCROLL_PER_SECOND * dt)
|
||||
if (secondaryDown) out.events += XrPointerEvent.Back(panel)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val HEAD_DRAG_METRES = 0.02f
|
||||
const val SCROLL_PER_SECOND = 12f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.Backspace
|
||||
import androidx.compose.material.icons.automirrored.outlined.KeyboardReturn
|
||||
import androidx.compose.material.icons.outlined.KeyboardArrowUp
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
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.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.compositeOver
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.input.EditCommand
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.ImeOptions
|
||||
import androidx.compose.ui.text.input.PlatformTextInputService
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.input.PC_KEY_ROWS
|
||||
import kotlinx.coroutines.delay
|
||||
import com.droiddeck.launcher.ui.TypingRequest
|
||||
|
||||
/** Sends text fields in the floating panels to [XrKeyboard], since the system keyboard cannot show in the immersive view. */
|
||||
internal class XrTextInput : PlatformTextInputService {
|
||||
private var request: TypingRequest? = null
|
||||
|
||||
override fun startInput(
|
||||
value: TextFieldValue, imeOptions: ImeOptions,
|
||||
onEditCommand: (List<EditCommand>) -> Unit, onImeActionPerformed: (ImeAction) -> Unit,
|
||||
) {
|
||||
val next = TypingRequest(value, imeOptions, { onEditCommand(TypingRequest.editsFor(it)) }, onImeActionPerformed)
|
||||
request = next
|
||||
XrPanels.startTyping(next)
|
||||
}
|
||||
|
||||
override fun stopInput() {
|
||||
request?.let { XrPanels.stopTyping(it) }
|
||||
request = null
|
||||
}
|
||||
|
||||
override fun showSoftwareKeyboard() {
|
||||
request?.let { XrPanels.startTyping(it) }
|
||||
}
|
||||
|
||||
override fun hideSoftwareKeyboard() {
|
||||
request?.let { XrPanels.stopTyping(it) }
|
||||
}
|
||||
|
||||
override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) {
|
||||
request?.value = newValue
|
||||
}
|
||||
}
|
||||
|
||||
internal object XrKeys {
|
||||
private val letters = listOf("qwertyuiop", "asdfghjkl", "zxcvbnm")
|
||||
private val symbols = listOf("1234567890", "@#&*-+=()", "!?:;'\"/,")
|
||||
|
||||
fun rows(numbers: Boolean, shift: Boolean): List<String> =
|
||||
(if (numbers) symbols else letters).map { if (shift && !numbers) it.uppercase() else it }
|
||||
|
||||
fun insert(value: TextFieldValue, text: String): TextFieldValue {
|
||||
val start = minOf(value.selection.start, value.selection.end)
|
||||
val end = maxOf(value.selection.start, value.selection.end)
|
||||
val next = value.text.substring(0, start) + text + value.text.substring(end)
|
||||
return TextFieldValue(next, TextRange(start + text.length))
|
||||
}
|
||||
|
||||
fun backspace(value: TextFieldValue): TextFieldValue {
|
||||
val start = minOf(value.selection.start, value.selection.end)
|
||||
val end = maxOf(value.selection.start, value.selection.end)
|
||||
if (start != end) return TextFieldValue(value.text.substring(0, start) + value.text.substring(end), TextRange(start))
|
||||
if (start == 0) return value
|
||||
val cut = value.text.offsetByCodePoints(start, -1)
|
||||
return TextFieldValue(value.text.substring(0, cut) + value.text.substring(start), TextRange(cut))
|
||||
}
|
||||
|
||||
const val REPEAT_DELAY_MS = 450L
|
||||
const val REPEAT_MS = 50L
|
||||
|
||||
/** Return sends when the field asks for an action, and starts a new line otherwise. */
|
||||
fun returnSends(options: ImeOptions) = options.imeAction != ImeAction.Default && options.imeAction != ImeAction.None &&
|
||||
options.singleLine
|
||||
}
|
||||
|
||||
/** Where the laser keyboard's keys go: a text field in a panel, or the game. */
|
||||
internal interface XrKeyTarget {
|
||||
fun type(text: String)
|
||||
fun backspace()
|
||||
fun enter()
|
||||
}
|
||||
|
||||
internal class XrFieldTarget(private val request: TypingRequest) : XrKeyTarget {
|
||||
override fun type(text: String) = request.send(XrKeys.insert(request.value, text))
|
||||
override fun backspace() = request.send(XrKeys.backspace(request.value))
|
||||
override fun enter() = if (XrKeys.returnSends(request.imeOptions)) request.action() else type("\n")
|
||||
}
|
||||
|
||||
internal class XrGameTarget(private val host: XrMenuHost) : XrKeyTarget {
|
||||
override fun type(text: String) = host.xrTypeText(text)
|
||||
override fun backspace() = host.xrTapKey(KeyEvent.KEYCODE_DEL)
|
||||
override fun enter() = host.xrTapKey(KeyEvent.KEYCODE_ENTER)
|
||||
}
|
||||
|
||||
/**
|
||||
* DroidDeck's PC keyboard typing into a panel's text field: the keys that make a character type it,
|
||||
* Backspace, Enter and Space edit, and Shift and Caps Lock pick the case. The rest have nothing to do there.
|
||||
*/
|
||||
internal class XrPcText(private val target: XrKeyTarget, private val timer: XrTimer = XrTimer.Main) {
|
||||
private val keys = PC_KEY_ROWS.flatten()
|
||||
.filter { it.labelRes == 0 && it.label.length == 1 && it.code !in ARROWS }
|
||||
.associateBy { it.code }
|
||||
private val shifts = mutableSetOf<Int>()
|
||||
private var caps = false
|
||||
private var stopRepeat: (() -> Unit)? = null
|
||||
|
||||
fun key(code: Int, down: Boolean) {
|
||||
if (code == LEFT_SHIFT || code == RIGHT_SHIFT) {
|
||||
if (down) shifts += code else shifts -= code
|
||||
return
|
||||
}
|
||||
if (!down && code != BACKSPACE) return
|
||||
stopRepeat?.invoke()
|
||||
stopRepeat = null
|
||||
if (!down) return
|
||||
val shifted = shifts.isNotEmpty()
|
||||
when (code) {
|
||||
BACKSPACE -> {
|
||||
target.backspace()
|
||||
stopRepeat = timer.after(XrKeys.REPEAT_DELAY_MS, ::repeatBackspace)
|
||||
}
|
||||
ENTER -> target.enter()
|
||||
SPACE -> target.type(" ")
|
||||
CAPS -> caps = !caps
|
||||
else -> keys[code]?.let { key ->
|
||||
target.type(when {
|
||||
shifted && key.shifted != null -> key.shifted
|
||||
key.label[0].isLetter() && (shifted xor caps) -> key.label.uppercase()
|
||||
else -> key.label
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun repeatBackspace() {
|
||||
target.backspace()
|
||||
stopRepeat = timer.after(XrKeys.REPEAT_MS, ::repeatBackspace)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val LEFT_SHIFT = 42
|
||||
const val RIGHT_SHIFT = 54
|
||||
const val BACKSPACE = 14
|
||||
const val ENTER = 28
|
||||
const val SPACE = 57
|
||||
const val CAPS = 58
|
||||
val ARROWS = setOf(103, 105, 106, 108)
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs an action later on the main thread; the function it returns cancels it. */
|
||||
internal fun interface XrTimer {
|
||||
fun after(ms: Long, action: () -> Unit): () -> Unit
|
||||
|
||||
companion object {
|
||||
private val handler by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
|
||||
val Main = XrTimer { ms, action ->
|
||||
val runnable = Runnable(action)
|
||||
handler.postDelayed(runnable, ms)
|
||||
({ handler.removeCallbacks(runnable) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The Android-style text keyboard. */
|
||||
@Composable
|
||||
internal fun XrKeyboard(target: XrKeyTarget) {
|
||||
var shift by remember { mutableStateOf(false) }
|
||||
var numbers by remember { mutableStateOf(false) }
|
||||
fun type(text: String) {
|
||||
target.type(text)
|
||||
if (shift) shift = false
|
||||
}
|
||||
Column(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
XrKeys.rows(numbers, shift).forEachIndexed { index, row ->
|
||||
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (index == 2) KeyIcon(Icons.Outlined.KeyboardArrowUp, stringResource(R.string.pckb_key_shift), active = shift, weight = 1.5f) { shift = !shift }
|
||||
row.forEach { key -> Key(key.toString()) { type(key.toString()) } }
|
||||
if (index == 2) KeyIcon(Icons.AutoMirrored.Outlined.Backspace, stringResource(R.string.pckb_key_backspace), weight = 1.5f, repeats = true) { target.backspace() }
|
||||
}
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Key(if (numbers) "abc" else "?123", weight = 1.5f) { numbers = !numbers }
|
||||
Key(",") { type(",") }
|
||||
Key(" ", weight = 5f) { type(" ") }
|
||||
Key(".") { type(".") }
|
||||
KeyIcon(Icons.AutoMirrored.Outlined.KeyboardReturn, stringResource(R.string.pckb_key_enter), weight = 1.5f) { target.enter() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A key that lights while the laser is over it and dips while it is pressed; [repeats] keeps acting while held. */
|
||||
@Composable
|
||||
private fun RowScope.KeyBox(
|
||||
weight: Float, active: Boolean, onClick: () -> Unit, repeats: Boolean = false, content: @Composable (Color) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val (pointedAt, pointed) = rememberXrPointed()
|
||||
val hovered = pointed.value
|
||||
val pressed by source.collectIsPressedAsState()
|
||||
val action by rememberUpdatedState(onClick)
|
||||
var repeated by remember { mutableStateOf(false) }
|
||||
if (repeats) LaunchedEffect(pressed) {
|
||||
if (!pressed) return@LaunchedEffect
|
||||
repeated = false
|
||||
delay(XrKeys.REPEAT_DELAY_MS)
|
||||
repeated = true
|
||||
while (true) {
|
||||
action()
|
||||
delay(XrKeys.REPEAT_MS)
|
||||
}
|
||||
}
|
||||
val fill by animateColorAsState(
|
||||
when {
|
||||
pressed -> colors.primary
|
||||
active -> colors.primary.copy(alpha = 0.8f)
|
||||
hovered -> colors.onSurface.copy(alpha = 0.22f).compositeOver(colors.surfaceVariant)
|
||||
else -> colors.surfaceVariant
|
||||
}, tween(if (pressed) 40 else 140), label = "keyFill",
|
||||
)
|
||||
val scale by animateFloatAsState(if (pressed) 0.9f else if (hovered) 1.05f else 1f, tween(if (pressed) 40 else 140), label = "keyScale")
|
||||
Box(
|
||||
Modifier.weight(weight).fillMaxHeight()
|
||||
.then(pointedAt)
|
||||
.graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale }
|
||||
.clip(RoundedCornerShape(8.dp)).background(fill)
|
||||
.border(if (hovered) 2.dp else 0.dp, if (hovered) colors.primary else Color.Transparent, RoundedCornerShape(8.dp))
|
||||
.clickable(interactionSource = source, indication = null) { if (repeated) repeated = false else onClick() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) { content(if (pressed || active) colors.onPrimary else colors.onSurface) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RowScope.Key(label: String, weight: Float = 1f, onClick: () -> Unit) =
|
||||
KeyBox(weight, active = false, onClick) { tint -> Text(label, color = tint, fontSize = 22.sp, maxLines = 1) }
|
||||
|
||||
@Composable
|
||||
private fun RowScope.KeyIcon(icon: ImageVector, label: String, active: Boolean = false, weight: Float = 1f, repeats: Boolean = false, onClick: () -> Unit) =
|
||||
KeyBox(weight, active, onClick, repeats) { tint -> Icon(icon, label, tint = tint) }
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
internal data class Vec3(val x: Float, val y: Float, val z: Float) {
|
||||
operator fun plus(o: Vec3) = Vec3(x + o.x, y + o.y, z + o.z)
|
||||
operator fun minus(o: Vec3) = Vec3(x - o.x, y - o.y, z - o.z)
|
||||
operator fun times(s: Float) = Vec3(x * s, y * s, z * s)
|
||||
infix fun dot(o: Vec3) = x * o.x + y * o.y + z * o.z
|
||||
infix fun cross(o: Vec3) = Vec3(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x)
|
||||
val length: Float get() = sqrt(this dot this)
|
||||
fun normalized(): Vec3 = length.let { if (it > 1e-6f) this * (1f / it) else ZERO }
|
||||
|
||||
companion object {
|
||||
val ZERO = Vec3(0f, 0f, 0f)
|
||||
val FORWARD = Vec3(0f, 0f, -1f)
|
||||
val UP = Vec3(0f, 1f, 0f)
|
||||
fun lerp(a: Vec3, b: Vec3, t: Float) = a + (b - a) * t
|
||||
}
|
||||
}
|
||||
|
||||
internal data class Quat(val x: Float, val y: Float, val z: Float, val w: Float) {
|
||||
fun rotate(v: Vec3): Vec3 {
|
||||
val u = Vec3(x, y, z)
|
||||
return u * (2f * (u dot v)) + v * (w * w - (u dot u)) + (u cross v) * (2f * w)
|
||||
}
|
||||
|
||||
fun conjugate() = Quat(-x, -y, -z, w)
|
||||
|
||||
operator fun times(o: Quat) = Quat(
|
||||
w * o.x + x * o.w + y * o.z - z * o.y,
|
||||
w * o.y - x * o.z + y * o.w + z * o.x,
|
||||
w * o.z + x * o.y - y * o.x + z * o.w,
|
||||
w * o.w - x * o.x - y * o.y - z * o.z,
|
||||
)
|
||||
|
||||
companion object {
|
||||
val IDENTITY = Quat(0f, 0f, 0f, 1f)
|
||||
fun yaw(radians: Float) = Quat(0f, sin(radians / 2f), 0f, cos(radians / 2f))
|
||||
fun pitch(radians: Float) = Quat(sin(radians / 2f), 0f, 0f, cos(radians / 2f))
|
||||
}
|
||||
}
|
||||
|
||||
internal data class Pose(val orientation: Quat = Quat.IDENTITY, val position: Vec3 = Vec3.ZERO) {
|
||||
val forward: Vec3 get() = orientation.rotate(Vec3.FORWARD)
|
||||
fun toLocal(world: Vec3): Vec3 = orientation.conjugate().rotate(world - position)
|
||||
fun toWorld(local: Vec3): Vec3 = position + orientation.rotate(local)
|
||||
}
|
||||
|
||||
/** Yaw of a direction in the horizontal plane, 0 along -Z, matching [Quat.yaw] applied to -Z. */
|
||||
internal fun yawOf(direction: Vec3): Float = atan2(-direction.x, -direction.z)
|
||||
|
||||
/** An orientation that turns +Z, the side of a quad that shows, from [position] towards [target] about the vertical axis only. */
|
||||
internal fun facing(position: Vec3, target: Vec3): Quat {
|
||||
val d = target - position
|
||||
if (d.x * d.x + d.z * d.z < 1e-8f) return Quat.IDENTITY
|
||||
return Quat.yaw(atan2(d.x, d.z))
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Remove
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.State
|
||||
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.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.boundsInWindow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* The frame of a floating panel: the content, a bar under it to grab it by with up to two buttons at
|
||||
* its left end, a corner grip to resize it, and the dot where a controller points. Its sizes match [XrUnits].
|
||||
*/
|
||||
@Composable
|
||||
internal fun XrPanelChrome(
|
||||
cursor: State<List<Pair<Float, Float>>>,
|
||||
buttons: List<XrPanelButton>,
|
||||
resizable: Boolean,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
Box(Modifier.fillMaxSize().clip(shape).background(colors.background).border(1.dp, Color(0x33FFFFFF), shape)) {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Box(Modifier.weight(1f).fillMaxWidth().padding(start = 10.dp, top = 10.dp, end = 10.dp)) {
|
||||
CompositionLocalProvider(LocalXrPointers provides cursor) { content() }
|
||||
}
|
||||
Box(
|
||||
Modifier.fillMaxWidth().height(52.dp).background(colors.surfaceVariant.copy(alpha = 0.6f)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Box(Modifier.width(72.dp).height(6.dp).clip(CircleShape).background(colors.onSurface.copy(alpha = 0.35f)))
|
||||
if (buttons.isNotEmpty()) Row(
|
||||
Modifier.align(Alignment.CenterStart).width(XrUnits.BAR_BUTTONS_DP.dp).padding(start = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
buttons.take(2).forEach { button ->
|
||||
if (button.icon != null) IconButton(onClick = button.onClick, modifier = Modifier.size(44.dp)) {
|
||||
Icon(button.icon, button.label, tint = colors.onSurface)
|
||||
} else TextButton(onClick = button.onClick, modifier = Modifier.height(40.dp), contentPadding = PaddingValues(horizontal = 10.dp)) {
|
||||
Text(button.label, color = colors.onSurface, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (resizable) Canvas(Modifier.align(Alignment.BottomEnd).padding(6.dp).size(28.dp)) {
|
||||
val stroke = Stroke(width = 3.dp.toPx())
|
||||
for (step in 1..3) {
|
||||
val inset = size.width * step / 4f
|
||||
drawLine(Color(0x99FFFFFF), Offset(size.width, inset), Offset(inset, size.height), stroke.width)
|
||||
}
|
||||
}
|
||||
val density = LocalDensity.current
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val radius = with(density) { 7.dp.toPx() }
|
||||
for ((x, y) in cursor.value) {
|
||||
drawCircle(Color(0xCC1E9EFF), radius, Offset(x, y))
|
||||
drawCircle(Color.White, radius, Offset(x, y), style = Stroke(with(density) { 2.dp.toPx() }))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Where each laser meets the panel, in the panel's pixels; null off a floating panel. */
|
||||
internal val LocalXrPointers = staticCompositionLocalOf<State<List<Pair<Float, Float>>>?> { null }
|
||||
|
||||
/**
|
||||
* Whether a laser rests on the element the returned [Modifier] is put on, for both controllers at
|
||||
* once, where a mouse hover has room for one. False off a floating panel.
|
||||
*/
|
||||
@Composable
|
||||
internal fun rememberXrPointed(): Pair<Modifier, State<Boolean>> {
|
||||
val pointers = LocalXrPointers.current
|
||||
var bounds by remember { mutableStateOf(Rect.Zero) }
|
||||
val pointed = remember(pointers) {
|
||||
derivedStateOf { pointers != null && pointers.value.any { (x, y) -> bounds.contains(Offset(x, y)) } }
|
||||
}
|
||||
return Modifier.onGloballyPositioned { bounds = it.boundsInWindow() } to pointed
|
||||
}
|
||||
|
||||
/** With no [icon] the button shows [label] itself, for a short word such as a keyboard mode. */
|
||||
internal class XrPanelButton(val icon: ImageVector?, val label: String, val onClick: () -> Unit)
|
||||
|
||||
internal val XrCollapseIcon get() = Icons.Outlined.Remove
|
||||
@@ -0,0 +1,271 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import android.app.Presentation
|
||||
import android.content.Context
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.hardware.display.VirtualDisplay
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.view.InputDevice
|
||||
import android.view.MotionEvent
|
||||
import android.view.Surface
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowManager
|
||||
import android.view.inspector.WindowInspector
|
||||
import android.widget.FrameLayout
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.platform.LocalTextInputService
|
||||
import androidx.compose.ui.text.input.TextInputService
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
import androidx.activity.OnBackPressedDispatcher
|
||||
import androidx.activity.OnBackPressedDispatcherOwner
|
||||
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
|
||||
import androidx.lifecycle.ViewModelStore
|
||||
import androidx.lifecycle.ViewModelStoreOwner
|
||||
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||
import androidx.lifecycle.setViewTreeViewModelStoreOwner
|
||||
import androidx.savedstate.SavedStateRegistry
|
||||
import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import com.droiddeck.launcher.ui.LocalPresentationWindow
|
||||
|
||||
/** Keeps a panel's Compose content running while the activity that made it is stopped behind the XR view. */
|
||||
private class PanelOwner : LifecycleOwner, SavedStateRegistryOwner, ViewModelStoreOwner, OnBackPressedDispatcherOwner {
|
||||
private val registry = LifecycleRegistry(this)
|
||||
private val saved = SavedStateRegistryController.create(this)
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
|
||||
override val viewModelStore = ViewModelStore()
|
||||
override val onBackPressedDispatcher = OnBackPressedDispatcher()
|
||||
|
||||
fun own(view: View) {
|
||||
view.setViewTreeLifecycleOwner(this)
|
||||
view.setViewTreeSavedStateRegistryOwner(this)
|
||||
view.setViewTreeViewModelStoreOwner(this)
|
||||
view.setViewTreeOnBackPressedDispatcherOwner(this)
|
||||
}
|
||||
|
||||
init {
|
||||
saved.performRestore(null)
|
||||
registry.currentState = Lifecycle.State.RESUMED
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
registry.currentState = Lifecycle.State.DESTROYED
|
||||
viewModelStore.clear()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One floating panel's Android side: a private virtual display drawing into the panel's OpenXR
|
||||
* surface, and a presentation on it holding the Compose content. Main thread only.
|
||||
*/
|
||||
internal class XrPanelWindow(
|
||||
private val context: Context,
|
||||
private var surface: Surface,
|
||||
width: Int,
|
||||
height: Int,
|
||||
startPaused: Boolean,
|
||||
private val content: @Composable () -> Unit,
|
||||
) {
|
||||
private var paused = startPaused
|
||||
private val owner = PanelOwner()
|
||||
private val textInput = TextInputService(XrTextInput())
|
||||
private val display: VirtualDisplay = context.getSystemService(DisplayManager::class.java).createVirtualDisplay(
|
||||
"DroidDeck XR panel", width, height, XrUnits.DPI, surface.takeUnless { paused }, DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY,
|
||||
)
|
||||
private val presentation = PanelPresentation(context, display.display)
|
||||
private var downTime = 0L
|
||||
private var target: View? = null
|
||||
/** The controllers pressing the panel, by hand, as fingers of one touch. */
|
||||
private val touches = linkedMapOf<Int, Pair<Float, Float>>()
|
||||
private var hovering: View? = null
|
||||
private var hoverAt = 0f to 0f
|
||||
private var cursor: Pair<Float, Float>? = null
|
||||
|
||||
init {
|
||||
try {
|
||||
presentation.show()
|
||||
} catch (failure: RuntimeException) {
|
||||
release()
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
|
||||
val displayId: Int get() = display.display.displayId
|
||||
|
||||
fun resize(surface: Surface, width: Int, height: Int) {
|
||||
this.surface = surface
|
||||
if (!paused) display.surface = surface
|
||||
display.resize(width, height, XrUnits.DPI)
|
||||
}
|
||||
|
||||
/** Stops drawing into the panel's layer, or starts again. */
|
||||
fun pause(pause: Boolean) {
|
||||
if (pause == paused) return
|
||||
paused = pause
|
||||
display.surface = if (pause) null else surface
|
||||
}
|
||||
|
||||
fun release() {
|
||||
runCatching { presentation.dismiss() }
|
||||
owner.destroy()
|
||||
display.release()
|
||||
}
|
||||
|
||||
private inner class PanelPresentation(outer: Context, display: android.view.Display) : Presentation(outer, display) {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window?.setBackgroundDrawableResource(android.R.color.transparent)
|
||||
window?.addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED)
|
||||
val compose = ComposeView(context).apply {
|
||||
owner.own(this)
|
||||
setContent {
|
||||
CompositionLocalProvider(
|
||||
LocalPresentationWindow provides true,
|
||||
LocalTextInputService provides textInput,
|
||||
) { content() }
|
||||
}
|
||||
}
|
||||
val frame = FrameLayout(context).apply {
|
||||
addView(compose, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
setContentView(frame)
|
||||
window?.decorView?.let(owner::own)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The topmost window on this panel's display under the point, so popups and dialogs get the input.
|
||||
* A focusable popup or dialog on top takes a press outside it too, as on a touchscreen, where it
|
||||
* dismisses itself rather than letting the press act on what is behind it.
|
||||
*/
|
||||
private fun rootAt(x: Float, y: Float): View? {
|
||||
val roots = WindowInspector.getGlobalWindowViews().filter { it.isAttachedToWindow && it.display?.displayId == displayId && it.isShown }
|
||||
val location = IntArray(2)
|
||||
fun contains(root: View): Boolean {
|
||||
root.getLocationOnScreen(location)
|
||||
return x >= location[0] && y >= location[1] && x < location[0] + root.width && y < location[1] + root.height
|
||||
}
|
||||
val top = roots.lastOrNull() ?: return null
|
||||
val focusable = (top.layoutParams as? WindowManager.LayoutParams)
|
||||
?.let { it.flags and WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE == 0 } ?: false
|
||||
if (roots.size > 1 && focusable && !contains(top)) return top
|
||||
return roots.lastOrNull(::contains) ?: top
|
||||
}
|
||||
|
||||
/** Sends every finger in [touches] to [target]; [action] is already shifted by its pointer index where it needs one. */
|
||||
private fun sendTouches(action: Int, time: Long) {
|
||||
val view = target ?: return
|
||||
val location = IntArray(2)
|
||||
view.getLocationOnScreen(location)
|
||||
val properties = touches.keys.map { hand ->
|
||||
MotionEvent.PointerProperties().apply { id = hand; toolType = MotionEvent.TOOL_TYPE_FINGER }
|
||||
}.toTypedArray()
|
||||
val coords = touches.values.map { (x, y) ->
|
||||
MotionEvent.PointerCoords().apply { this.x = x - location[0]; this.y = y - location[1]; pressure = 1f; size = 1f }
|
||||
}.toTypedArray()
|
||||
val event = MotionEvent.obtain(downTime, time, action, touches.size, properties, coords, 0, 0, 1f, 1f, 0, 0,
|
||||
InputDevice.SOURCE_TOUCHSCREEN, 0)
|
||||
try {
|
||||
view.dispatchTouchEvent(event)
|
||||
} finally {
|
||||
event.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun indexed(action: Int, hand: Int) =
|
||||
action or (touches.keys.indexOf(hand) shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
|
||||
private fun send(view: View, action: Int, x: Float, y: Float, time: Long, generic: Boolean, scroll: Float = 0f): Boolean {
|
||||
val location = IntArray(2)
|
||||
view.getLocationOnScreen(location)
|
||||
val properties = arrayOf(MotionEvent.PointerProperties().apply {
|
||||
id = 0
|
||||
toolType = if (generic) MotionEvent.TOOL_TYPE_MOUSE else MotionEvent.TOOL_TYPE_FINGER
|
||||
})
|
||||
val coords = arrayOf(MotionEvent.PointerCoords().apply {
|
||||
this.x = x - location[0]
|
||||
this.y = y - location[1]
|
||||
pressure = 1f
|
||||
size = 1f
|
||||
if (scroll != 0f) setAxisValue(MotionEvent.AXIS_VSCROLL, scroll)
|
||||
})
|
||||
val source = if (generic) InputDevice.SOURCE_MOUSE else InputDevice.SOURCE_TOUCHSCREEN
|
||||
val event = MotionEvent.obtain(if (generic) time else downTime, time, action, 1, properties, coords, 0, 0, 1f, 1f, 0, 0, source, 0)
|
||||
return try {
|
||||
if (generic) view.dispatchGenericMotionEvent(event) else view.dispatchTouchEvent(event)
|
||||
} finally {
|
||||
event.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
/** The laser resting on the panel, as a mouse hovering, so keys and buttons light under it. Null: it left. */
|
||||
fun hover(at: Pair<Float, Float>?) {
|
||||
cursor = at
|
||||
if (target != null) return
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val root = at?.let { (x, y) -> rootAt(x, y) }
|
||||
if (root !== hovering) endHover(now)
|
||||
if (root == null || at == null) return
|
||||
if (hovering == null) send(root, MotionEvent.ACTION_HOVER_ENTER, at.first, at.second, now, generic = true)
|
||||
send(root, MotionEvent.ACTION_HOVER_MOVE, at.first, at.second, now, generic = true)
|
||||
hovering = root
|
||||
hoverAt = at
|
||||
}
|
||||
|
||||
private fun endHover(now: Long) {
|
||||
hovering?.let { send(it, MotionEvent.ACTION_HOVER_EXIT, hoverAt.first, hoverAt.second, now, generic = true) }
|
||||
hovering = null
|
||||
}
|
||||
|
||||
fun pointer(event: XrPointerEvent) {
|
||||
val now = SystemClock.uptimeMillis()
|
||||
when (event) {
|
||||
is XrPointerEvent.Down -> {
|
||||
if (event.hand in touches) return
|
||||
touches[event.hand] = event.x to event.y
|
||||
if (touches.size == 1) {
|
||||
endHover(now)
|
||||
downTime = now
|
||||
target = rootAt(event.x, event.y)
|
||||
sendTouches(MotionEvent.ACTION_DOWN, now)
|
||||
} else sendTouches(indexed(MotionEvent.ACTION_POINTER_DOWN, event.hand), now)
|
||||
}
|
||||
is XrPointerEvent.Move -> {
|
||||
if (event.hand !in touches) return
|
||||
touches[event.hand] = event.x to event.y
|
||||
sendTouches(MotionEvent.ACTION_MOVE, now)
|
||||
}
|
||||
is XrPointerEvent.Up -> {
|
||||
if (event.hand !in touches) return
|
||||
touches[event.hand] = event.x to event.y
|
||||
if (touches.size > 1) {
|
||||
sendTouches(indexed(MotionEvent.ACTION_POINTER_UP, event.hand), now)
|
||||
touches -= event.hand
|
||||
} else {
|
||||
sendTouches(MotionEvent.ACTION_UP, now)
|
||||
touches.clear()
|
||||
target = null
|
||||
hover(cursor)
|
||||
}
|
||||
}
|
||||
is XrPointerEvent.Cancel -> {
|
||||
if (event.hand !in touches) return
|
||||
sendTouches(MotionEvent.ACTION_CANCEL, now)
|
||||
touches.clear()
|
||||
target = null
|
||||
}
|
||||
is XrPointerEvent.Scroll -> rootAt(event.x, event.y)?.let {
|
||||
send(it, MotionEvent.ACTION_SCROLL, event.x, event.y, now, generic = true, scroll = event.amount)
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.KeyboardHide
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.agent.AgentHost
|
||||
import com.droiddeck.launcher.session.QuestExperimental
|
||||
import com.droiddeck.launcher.ui.AgentPage
|
||||
import com.droiddeck.launcher.ui.AgentPet
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.PcKeyboard
|
||||
import com.droiddeck.launcher.ui.PetFigure
|
||||
import com.droiddeck.launcher.ui.TypingRequest
|
||||
import com.droiddeck.launcher.ui.petStateNow
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.MainScope
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import java.lang.ref.WeakReference
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
import kotlin.math.PI
|
||||
|
||||
/** The 2D session window, which hands its menu to the immersive view while that is open. */
|
||||
internal interface XrMenuHost {
|
||||
@Composable
|
||||
fun XrMenuContent()
|
||||
fun xrSetMenuOpen(open: Boolean)
|
||||
fun xrMenuBack()
|
||||
/** A key of DroidDeck's PC keyboard, by Linux key code, to the game. */
|
||||
fun xrSendKey(code: Int, down: Boolean)
|
||||
/** Text from the laser keyboard to the game, as the Android keyboard sends it. */
|
||||
fun xrTypeText(text: String)
|
||||
fun xrTapKey(keyCode: Int)
|
||||
/** The immersive view opened or closed; Steam's screen, which SteamVR mirrors as its Steam window, sizes for it. */
|
||||
fun xrImmersiveChanged(active: Boolean)
|
||||
}
|
||||
|
||||
/** What the immersive view's native loop offers: surface-backed layers it composites in front of the game. */
|
||||
internal interface XrLayerSource {
|
||||
val context: Context
|
||||
fun createLayer(width: Int, height: Int): Int
|
||||
fun layerSurface(id: Int): Surface?
|
||||
fun destroyLayer(id: Int)
|
||||
fun setOrbImage(image: android.graphics.Bitmap)
|
||||
fun leave()
|
||||
}
|
||||
|
||||
/**
|
||||
* DroidDeck's own windows inside the immersive Quest view: the session menu, opened by holding the
|
||||
* controllers together, and the agent pet with its chat. Quest only. [frame] runs on the XR thread
|
||||
* each frame; the rest runs on the main thread.
|
||||
*/
|
||||
internal object XrPanels {
|
||||
private const val TAG = "XrPanels"
|
||||
private const val OPEN_MS = 350f
|
||||
private const val CLOSE_MS = 250f
|
||||
private const val BURST_MS = 400f
|
||||
|
||||
/** The immersive view is up, so the menu and pet belong in it. Always false off Quest. */
|
||||
@Volatile
|
||||
var immersiveActive = false
|
||||
|
||||
/** Counts attachments, so work posted from one immersive view is dropped once a later one, or none, is up. */
|
||||
@Volatile
|
||||
private var attachment = 0
|
||||
private set
|
||||
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
/** Whether the headset shows the session; panels draw into their layers only then. */
|
||||
@Volatile
|
||||
private var drawing = false
|
||||
private val lock = Any()
|
||||
private val ops = ConcurrentLinkedQueue<() -> Unit>()
|
||||
private var source: XrLayerSource? = null
|
||||
private var host: XrHost? = null
|
||||
private var menuHost: WeakReference<XrMenuHost>? = null
|
||||
private var scope: CoroutineScope? = null
|
||||
|
||||
private class Panel(val state: XrPanelState, val content: @Composable (State<List<Pair<Float, Float>>>) -> Unit) {
|
||||
val cursorState = mutableStateOf<List<Pair<Float, Float>>>(emptyList())
|
||||
var layerId = -1
|
||||
var window: XrPanelWindow? = null
|
||||
var openedMs = 0L
|
||||
var closingMs = 0L
|
||||
var resizing = false
|
||||
var cursor: List<Pair<Float, Float>> = emptyList()
|
||||
}
|
||||
|
||||
private val panels = mutableListOf<Panel>()
|
||||
private val gesture = XrGesture()
|
||||
private val interaction = XrInteraction()
|
||||
private var lastFrameMs = 0L
|
||||
private var orbImageSent = false
|
||||
private var lastHead = Pose()
|
||||
private var burstMs = 0L
|
||||
private var burstAt = Vec3.ZERO
|
||||
private var lastTick = 0
|
||||
private var menuFrom: Vec3? = null
|
||||
private val typing = mutableStateOf<TypingRequest?>(null)
|
||||
/** The keyboard was opened for the game, from the session menu; a panel's text field takes it over while it types. */
|
||||
private val gameKeyboard = mutableStateOf(false)
|
||||
private val pcKeyboard = mutableStateOf(false)
|
||||
|
||||
fun gateOpen(model: String, device: String, manufacturer: String, immersive: Boolean) =
|
||||
immersive && QuestExperimental.supported(model, device, manufacturer)
|
||||
|
||||
fun setMenuHost(menu: XrMenuHost?) {
|
||||
menuHost = menu?.let { WeakReference(it) }
|
||||
if (immersiveActive) menu?.xrImmersiveChanged(true)
|
||||
}
|
||||
|
||||
fun clearMenuHost(menu: XrMenuHost) {
|
||||
if (menuHost?.get() === menu) menuHost = null
|
||||
}
|
||||
|
||||
/** Main thread: the immersive view handed over its buffers. */
|
||||
fun attach(layers: XrLayerSource, state: ByteBuffer, control: ByteBuffer) {
|
||||
if (!QuestExperimental.isSupported()) return
|
||||
synchronized(lock) {
|
||||
source = layers
|
||||
host = XrHost(state, control)
|
||||
orbImageSent = false
|
||||
}
|
||||
attachment++
|
||||
immersiveActive = true
|
||||
menuHost?.get()?.xrImmersiveChanged(true)
|
||||
scope?.cancel()
|
||||
scope = MainScope().also { scope ->
|
||||
scope.launch {
|
||||
snapshotFlow { com.droiddeck.launcher.agent.AgentGuest.focusRevision }.collect {
|
||||
menuHost?.get()?.xrImmersiveChanged(true)
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
snapshotFlow { AgentPet.enabled && AgentHost.installed }.collect { on ->
|
||||
if (on) { if (!shown(XrPanelKind.PET_CHAT)) open(XrPanelKind.PET_HEAD) }
|
||||
else { close(XrPanelKind.PET_HEAD); close(XrPanelKind.PET_CHAT) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* XR thread, as the session becomes visible or stops being so. OpenXR allows writing into a surface
|
||||
* swapchain only while the session is visible or focused, and requires the writes to have stopped
|
||||
* before xrEndSession, so this returns once the panels have stopped or started drawing.
|
||||
*/
|
||||
fun setDrawing(visible: Boolean) {
|
||||
val done = java.util.concurrent.CountDownLatch(1)
|
||||
val apply = Runnable {
|
||||
try {
|
||||
drawing = visible
|
||||
synchronized(lock) { panels.mapNotNull { it.window } }.forEach { it.pause(!visible) }
|
||||
} finally {
|
||||
done.countDown()
|
||||
}
|
||||
}
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) apply.run()
|
||||
else if (main.post(apply) && !done.await(1, java.util.concurrent.TimeUnit.SECONDS))
|
||||
Log.w(TAG, "panels did not ${if (visible) "start" else "stop"} drawing within a second")
|
||||
}
|
||||
|
||||
/** Main thread: the immersive view is going; every panel goes with it. */
|
||||
fun detach() {
|
||||
if (!immersiveActive) return
|
||||
immersiveActive = false
|
||||
scope?.cancel()
|
||||
scope = null
|
||||
val windows = synchronized(lock) {
|
||||
source = null
|
||||
host = null
|
||||
ops.clear()
|
||||
interaction.reset()
|
||||
panels.mapNotNull { it.window }.also { panels.clear() }
|
||||
}
|
||||
windows.forEach { it.release() }
|
||||
typing.value = null
|
||||
gameKeyboard.value = false
|
||||
gesture.reset(release = false)
|
||||
menuHost?.get()?.xrSetMenuOpen(false)
|
||||
menuHost?.get()?.xrImmersiveChanged(false)
|
||||
}
|
||||
|
||||
/** Main thread, from the session window's menu state. */
|
||||
fun showMenu(): Boolean {
|
||||
if (!immersiveActive) return false
|
||||
open(XrPanelKind.MENU, menuFrom)
|
||||
menuFrom = null
|
||||
return true
|
||||
}
|
||||
|
||||
fun hideMenu() = close(XrPanelKind.MENU)
|
||||
|
||||
/** Main thread: closes the immersive view, as a stop chosen in its menu asks. */
|
||||
fun leaveImmersive() {
|
||||
synchronized(lock) { source }?.leave()
|
||||
}
|
||||
|
||||
/** Main thread: a text field in a panel wants typing, so the laser keyboard opens. */
|
||||
fun startTyping(request: TypingRequest) {
|
||||
if (!immersiveActive) return
|
||||
typing.value = request
|
||||
open(XrPanelKind.KEYBOARD)
|
||||
}
|
||||
|
||||
fun stopTyping(request: TypingRequest) {
|
||||
if (typing.value !== request) return
|
||||
typing.value = null
|
||||
if (!gameKeyboard.value) close(XrPanelKind.KEYBOARD)
|
||||
}
|
||||
|
||||
/**
|
||||
* Main thread: the session menu's keyboards. [pc] picks DroidDeck's PC keyboard over the Android-style one;
|
||||
* asking again for the one already open closes it. False off the immersive view, where the 2D keyboards stay.
|
||||
*/
|
||||
fun toggleGameKeyboard(pc: Boolean): Boolean {
|
||||
if (!immersiveActive) return false
|
||||
if (gameKeyboard.value && pcKeyboard.value == pc && shown(XrPanelKind.KEYBOARD)) hideKeyboard()
|
||||
else showGameKeyboard(pc)
|
||||
return true
|
||||
}
|
||||
|
||||
fun showGameKeyboard(pc: Boolean): Boolean {
|
||||
if (!immersiveActive) return false
|
||||
gameKeyboard.value = true
|
||||
pcKeyboard.value = pc
|
||||
open(XrPanelKind.KEYBOARD)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun hideKeyboard() {
|
||||
typing.value = null
|
||||
gameKeyboard.value = false
|
||||
close(XrPanelKind.KEYBOARD)
|
||||
}
|
||||
|
||||
private fun shown(kind: XrPanelKind) = synchronized(lock) { panels.any { it.state.kind == kind && it.closingMs == 0L } }
|
||||
|
||||
private fun open(kind: XrPanelKind, from: Vec3? = null) {
|
||||
ops += { create(kind, from) }
|
||||
}
|
||||
|
||||
private fun close(kind: XrPanelKind) {
|
||||
ops += {
|
||||
panels.filter { it.state.kind == kind && it.closingMs == 0L }.forEach { panel ->
|
||||
panel.closingMs = SystemClock.uptimeMillis()
|
||||
val out = XrInteractionOut()
|
||||
interaction.release(panel.state, out)
|
||||
dispatch(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** XR thread. */
|
||||
private fun create(kind: XrPanelKind, from: Vec3?) {
|
||||
val layers = source ?: return
|
||||
panels.firstOrNull { it.state.kind == kind }?.let { existing ->
|
||||
if (existing.closingMs != 0L) {
|
||||
existing.closingMs = 0L
|
||||
val elapsed = 1f - Math.cbrt((1.0 - existing.state.scale).coerceIn(0.0, 1.0)).toFloat()
|
||||
existing.openedMs = SystemClock.uptimeMillis() - (elapsed * OPEN_MS).toLong()
|
||||
}
|
||||
return
|
||||
}
|
||||
val placed = XrPlacement.load(layers.context, kind, lastHead)
|
||||
val state = XrPanelState(kind, placed.pose, placed.width, placed.height)
|
||||
state.scale = 0f
|
||||
state.animationFrom = from ?: placed.pose.position
|
||||
val id = layers.createLayer(state.pixelWidth, state.pixelHeight)
|
||||
val surface = if (id >= 0) layers.layerSurface(id) else null
|
||||
if (surface == null) {
|
||||
Log.w(TAG, "no layer for the ${kind.key} panel")
|
||||
if (id >= 0) layers.destroyLayer(id)
|
||||
if (kind == XrPanelKind.MENU) main.post { menuHost?.get()?.xrSetMenuOpen(false) }
|
||||
return
|
||||
}
|
||||
val panel = Panel(state, contentFor(kind))
|
||||
panel.layerId = id
|
||||
panel.openedMs = SystemClock.uptimeMillis()
|
||||
panels += panel
|
||||
val context = layers.context
|
||||
main.post {
|
||||
synchronized(lock) {
|
||||
if (panel !in panels) return@post
|
||||
panel.window = runCatching {
|
||||
XrPanelWindow(context, surface, state.pixelWidth, state.pixelHeight, startPaused = !drawing) {
|
||||
panel.content(panel.cursorState)
|
||||
}
|
||||
}.onFailure {
|
||||
Log.w(TAG, "could not show the ${kind.key} panel", it)
|
||||
panels -= panel
|
||||
ops += { if (source === layers) layers.destroyLayer(id) }
|
||||
if (kind == XrPanelKind.MENU) menuHost?.get()?.xrSetMenuOpen(false)
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun contentFor(kind: XrPanelKind): @Composable (State<List<Pair<Float, Float>>>) -> Unit = when (kind) {
|
||||
XrPanelKind.MENU -> { cursor ->
|
||||
DroidDeckTheme {
|
||||
XrPanelChrome(cursor, buttons = emptyList(), resizable = true) {
|
||||
menuHost?.get()?.XrMenuContent()
|
||||
}
|
||||
}
|
||||
}
|
||||
XrPanelKind.PET_HEAD -> { _ ->
|
||||
DroidDeckTheme { Box(Modifier.fillMaxSize()) { PetFigure(petStateNow(), Modifier.fillMaxSize()) } }
|
||||
}
|
||||
XrPanelKind.KEYBOARD -> { cursor ->
|
||||
DroidDeckTheme {
|
||||
val buttons = listOf(
|
||||
XrPanelButton(Icons.Outlined.KeyboardHide, stringResource(R.string.pckb_hide), ::hideKeyboard),
|
||||
XrPanelButton(null, if (pcKeyboard.value) "Android" else "PC") { pcKeyboard.value = !pcKeyboard.value },
|
||||
)
|
||||
XrPanelChrome(cursor, buttons, resizable = true) { KeyboardContent() }
|
||||
}
|
||||
}
|
||||
XrPanelKind.PET_CHAT -> { cursor ->
|
||||
DroidDeckTheme {
|
||||
XrPanelChrome(cursor, listOf(XrPanelButton(XrCollapseIcon, stringResource(R.string.bottom_chat_close), ::collapseChat)), resizable = true) {
|
||||
AgentPage(Modifier.fillMaxSize().padding(horizontal = 12.dp), visible = true, startTyping = false, hidesPet = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A panel's text field takes the keyboard while it types; otherwise its keys go to the game. */
|
||||
@Composable
|
||||
private fun KeyboardContent() {
|
||||
val request = typing.value
|
||||
val host = menuHost?.get()?.takeIf { gameKeyboard.value }
|
||||
val target = request?.let(::XrFieldTarget) ?: host?.let(::XrGameTarget) ?: return
|
||||
if (pcKeyboard.value) {
|
||||
val pcText = remember(request) { request?.let { XrPcText(XrFieldTarget(it)) } }
|
||||
PcKeyboard(
|
||||
sendKey = { code, down -> pcText?.key(code, down) ?: host?.xrSendKey(code, down) },
|
||||
onAndroidKeyboard = { pcKeyboard.value = false },
|
||||
onClose = ::hideKeyboard,
|
||||
heightFraction = 1f,
|
||||
showButtons = false,
|
||||
hoverFeedback = true,
|
||||
)
|
||||
} else XrKeyboard(target)
|
||||
}
|
||||
|
||||
private fun collapseChat() {
|
||||
close(XrPanelKind.PET_CHAT)
|
||||
open(XrPanelKind.PET_HEAD)
|
||||
}
|
||||
|
||||
private fun expandChat(from: Vec3) {
|
||||
close(XrPanelKind.PET_HEAD)
|
||||
open(XrPanelKind.PET_CHAT, from)
|
||||
}
|
||||
|
||||
/** XR thread, once per frame, from QuestXrActivity.onXrHostFrame. */
|
||||
fun frame() = synchronized(lock) {
|
||||
val host = host ?: return
|
||||
val layers = source ?: return
|
||||
val frame = host.read()
|
||||
lastHead = frame.head
|
||||
while (true) (ops.poll() ?: break).invoke()
|
||||
if (!orbImageSent) {
|
||||
orbImageSent = true
|
||||
runCatching {
|
||||
android.graphics.BitmapFactory.decodeResource(layers.context.resources, R.drawable.logo)
|
||||
}.getOrNull()?.let { layers.setOrbImage(it); it.recycle() }
|
||||
}
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val dt = if (lastFrameMs == 0L) 0f else ((now - lastFrameMs) / 1000f).coerceIn(0f, 0.1f)
|
||||
lastFrameMs = now
|
||||
val control = XrControlOut()
|
||||
animate(now, layers)
|
||||
val active = panels.filter { it.closingMs == 0L && it.window != null }
|
||||
if (frame.focused) {
|
||||
if (gesture.update(frame.hands[0], frame.hands[1], now)) {
|
||||
burstMs = now
|
||||
burstAt = gesture.midpoint
|
||||
lastTick = 0
|
||||
for (hand in 0..1) control.haptics[hand] = XrHaptic(60, 0.9f)
|
||||
val from = gesture.midpoint
|
||||
val posted = attachment
|
||||
main.post { if (immersiveActive && posted == attachment) toggleMenu(from) }
|
||||
} else if (gesture.phase == XrGesture.Phase.ARMING) {
|
||||
val step = (gesture.progress * 4).toInt()
|
||||
if (step > lastTick) for (hand in 0..1) control.haptics[hand] = XrHaptic(18, 0.2f + 0.15f * step)
|
||||
lastTick = step
|
||||
} else lastTick = 0
|
||||
val out = interaction.update(frame.head, frame.hands, active.map { it.state }, dt)
|
||||
for (hand in 0..1) {
|
||||
control.masks[hand] = out.masks[hand]
|
||||
control.lasers[hand] = out.lasers[hand]
|
||||
if (out.ticks[hand] && control.haptics[hand] == null) control.haptics[hand] = XrHaptic(12, 0.35f)
|
||||
}
|
||||
dispatch(out)
|
||||
} else {
|
||||
gesture.reset(release = false)
|
||||
val out = XrInteractionOut()
|
||||
interaction.cancel(out)
|
||||
dispatch(out)
|
||||
}
|
||||
control.orb = orb(now)
|
||||
panels.forEachIndexed { index, panel ->
|
||||
if (panel.layerId < 0 || panel.window == null) return@forEachIndexed
|
||||
val state = panel.state
|
||||
control.layers += XrLayerOut(panel.layerId, state.shownPose, state.width * state.scale, state.height * state.scale,
|
||||
order = if (state.kind == XrPanelKind.PET_HEAD) 100 else index)
|
||||
}
|
||||
host.write(control)
|
||||
}
|
||||
|
||||
private fun orb(now: Long): XrControlOut.Orb? {
|
||||
if (gesture.phase == XrGesture.Phase.ARMING)
|
||||
return XrControlOut.Orb(gesture.midpoint, 0.02f + 0.01f * gesture.progress, gesture.progress, 0f)
|
||||
val burst = (now - burstMs) / BURST_MS
|
||||
if (burstMs != 0L && burst < 1f) return XrControlOut.Orb(burstAt, 0.03f, 1f, burst.coerceAtLeast(0.01f))
|
||||
return null
|
||||
}
|
||||
|
||||
private fun animate(now: Long, layers: XrLayerSource) {
|
||||
val gone = mutableListOf<Panel>()
|
||||
for (panel in panels) {
|
||||
val state = panel.state
|
||||
if (panel.closingMs != 0L) {
|
||||
val t = ((now - panel.closingMs) / CLOSE_MS).coerceIn(0f, 1f)
|
||||
state.scale = minOf(state.scale, 1f - easeOut(t))
|
||||
if (state.animationFrom == null) state.animationFrom = state.pose.position
|
||||
if (t >= 1f) gone += panel
|
||||
} else if (state.scale < 1f) {
|
||||
state.scale = easeOut(((now - panel.openedMs) / OPEN_MS).coerceIn(0f, 1f))
|
||||
if (state.scale >= 1f) state.animationFrom = null
|
||||
}
|
||||
}
|
||||
for (panel in gone) {
|
||||
panels -= panel
|
||||
if (panel.layerId >= 0) layers.destroyLayer(panel.layerId)
|
||||
val window = panel.window
|
||||
val context = layers.context
|
||||
val state = panel.state
|
||||
val head = lastHead
|
||||
main.post {
|
||||
window?.release()
|
||||
XrPlacement.save(context, state.kind, head, state.pose, state.width, state.height)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun easeOut(t: Float) = 1f - (1f - t) * (1f - t) * (1f - t)
|
||||
|
||||
/** XR thread: hands each panel its input on the main thread and follows up on moves and resizes. */
|
||||
private fun dispatch(out: XrInteractionOut) {
|
||||
val layers = source ?: return
|
||||
for (panel in panels) {
|
||||
val cursor = out.cursors[panel.state]?.toList().orEmpty()
|
||||
if (cursor != panel.cursor) {
|
||||
panel.cursor = cursor
|
||||
val target = panel.cursorState
|
||||
val window = panel.window
|
||||
main.post {
|
||||
target.value = cursor
|
||||
window?.hover(cursor.firstOrNull())
|
||||
}
|
||||
}
|
||||
}
|
||||
for (event in out.events) {
|
||||
val panel = panels.firstOrNull { it.state === event.panel } ?: continue
|
||||
when (event) {
|
||||
is XrPointerEvent.Back -> main.post { back(panel.state.kind) }
|
||||
is XrPointerEvent.Click -> {
|
||||
val from = panel.state.pose.position
|
||||
main.post { expandChat(from) }
|
||||
}
|
||||
is XrPointerEvent.Resized -> {
|
||||
savePlacement(panel, layers)
|
||||
resize(panel, layers)
|
||||
}
|
||||
is XrPointerEvent.Moved -> savePlacement(panel, layers)
|
||||
else -> {
|
||||
val window = panel.window
|
||||
main.post { window?.pointer(event) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** XR thread: the place a move or resize ended at, read together now and saved on the main thread. */
|
||||
private fun savePlacement(panel: Panel, layers: XrLayerSource) {
|
||||
val state = panel.state
|
||||
val kind = state.kind
|
||||
val head = lastHead
|
||||
val pose = state.pose
|
||||
val width = state.width
|
||||
val height = state.height
|
||||
val context = layers.context
|
||||
main.post { XrPlacement.save(context, kind, head, pose, width, height) }
|
||||
}
|
||||
|
||||
/** XR thread: gives a resized panel a surface of its new size once its content has moved over to it. */
|
||||
private fun resize(panel: Panel, layers: XrLayerSource) {
|
||||
val state = panel.state
|
||||
val width = XrUnits.pixels(state.width)
|
||||
val height = XrUnits.pixels(state.height)
|
||||
if (width == state.pixelWidth && height == state.pixelHeight) return
|
||||
val id = layers.createLayer(width, height)
|
||||
val surface = if (id >= 0) layers.layerSurface(id) else null
|
||||
if (surface == null) {
|
||||
if (id >= 0) layers.destroyLayer(id)
|
||||
return
|
||||
}
|
||||
val window = panel.window
|
||||
main.post {
|
||||
window?.resize(surface, width, height)
|
||||
ops += {
|
||||
if (panel in panels) {
|
||||
val old = panel.layerId
|
||||
panel.layerId = id
|
||||
state.pixelWidth = width
|
||||
state.pixelHeight = height
|
||||
if (old >= 0) layers.destroyLayer(old)
|
||||
} else if (source === layers) layers.destroyLayer(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Main thread. */
|
||||
private fun toggleMenu(from: Vec3) {
|
||||
val menu = menuHost?.get() ?: return
|
||||
if (shown(XrPanelKind.MENU)) menu.xrSetMenuOpen(false)
|
||||
else {
|
||||
menuFrom = from
|
||||
menu.xrSetMenuOpen(true)
|
||||
}
|
||||
}
|
||||
|
||||
/** Main thread: B on a panel goes back a step, as Back does in the 2D window. */
|
||||
private fun back(kind: XrPanelKind) {
|
||||
when (kind) {
|
||||
XrPanelKind.MENU -> menuHost?.get()?.xrMenuBack()
|
||||
XrPanelKind.PET_CHAT -> collapseChat()
|
||||
XrPanelKind.PET_HEAD -> Unit
|
||||
XrPanelKind.KEYBOARD -> hideKeyboard()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Where each panel kind was left, relative to where the user faced, so it comes back there. */
|
||||
internal object XrPlacement {
|
||||
class Placed(val pose: Pose, val width: Float, val height: Float)
|
||||
|
||||
private class Default(val yaw: Float, val distance: Float, val dy: Float, val width: Float, val height: Float)
|
||||
|
||||
private val defaults = mapOf(
|
||||
XrPanelKind.MENU to Default(0f, 0.95f, -0.12f, 0.9f, 0.6f),
|
||||
XrPanelKind.PET_CHAT to Default(0.6f, 0.95f, -0.12f, 0.6f, 0.7f),
|
||||
XrPanelKind.PET_HEAD to Default(0.7f, 0.75f, -0.45f, 0.12f, 0.12f),
|
||||
XrPanelKind.KEYBOARD to Default(0f, 0.5f, -0.5f, 0.8f, 0.36f),
|
||||
)
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("quest_xr_panels", Context.MODE_PRIVATE)
|
||||
|
||||
fun place(kind: XrPanelKind, head: Pose, yaw: Float, distance: Float, dy: Float): Pose {
|
||||
val angle = yawOf(head.forward) + yaw
|
||||
val direction = Quat.yaw(angle).rotate(Vec3.FORWARD)
|
||||
val position = head.position + direction * distance + Vec3(0f, dy, 0f)
|
||||
return Pose(kind.orient(position, head.position), position)
|
||||
}
|
||||
|
||||
fun relative(head: Pose, position: Vec3): Triple<Float, Float, Float> {
|
||||
val offset = position - head.position
|
||||
val distance = Vec3(offset.x, 0f, offset.z).length
|
||||
var yaw = yawOf(offset) - yawOf(head.forward)
|
||||
while (yaw > PI) yaw -= (2 * PI).toFloat()
|
||||
while (yaw < -PI) yaw += (2 * PI).toFloat()
|
||||
return Triple(yaw, distance, offset.y)
|
||||
}
|
||||
|
||||
fun load(context: Context, kind: XrPanelKind, head: Pose): Placed {
|
||||
val fallback = defaults.getValue(kind)
|
||||
val saved = prefs(context).getString(kind.key, null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
|
||||
val values = saved?.takeIf { it.size == 5 } ?: listOf(fallback.yaw, fallback.distance, fallback.dy, fallback.width, fallback.height)
|
||||
val distance = values[1].coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE)
|
||||
val width = if (kind.resizable) values[3].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.width
|
||||
val height = if (kind.resizable) values[4].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.height
|
||||
return Placed(place(kind, head, values[0], distance, values[2].coerceIn(-1.5f, 1.5f)), width, height)
|
||||
}
|
||||
|
||||
fun save(context: Context, kind: XrPanelKind, head: Pose, pose: Pose, width: Float, height: Float) {
|
||||
val (yaw, distance, dy) = relative(head, pose.position)
|
||||
prefs(context).edit().putString(kind.key, listOf(yaw, distance, dy, width, height).joinToString(",")).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
/** Whether the guest's focus report shows Steam's own screen, with no game holding a window. */
|
||||
internal object XrSteamScreen {
|
||||
/** Steam's own UI and SteamVR, which have windows of their own but are not games. */
|
||||
private val STEAM_APPS = setOf(769L, 250820L)
|
||||
|
||||
/**
|
||||
* Gamescope lists Steam itself while its screen is up, so a report naming no app at all, as the guest
|
||||
* writes when it could not collect focus or gamescope has not published it, says nothing.
|
||||
*/
|
||||
fun shown(focusedApp: Long?, focusableApps: List<Long>?): Boolean {
|
||||
val apps = (listOfNotNull(focusedApp) + focusableApps.orEmpty()).filter { it > 0 }
|
||||
return apps.isNotEmpty() && apps.all { it in STEAM_APPS }
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -532,7 +532,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)
|
||||
@@ -1007,6 +1007,7 @@ private fun AttachButton() {
|
||||
val context = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
||||
AgentAttachments.picking = false
|
||||
if (uris.isEmpty()) return@rememberLauncherForActivityResult
|
||||
val chat = AgentHost.chat
|
||||
Thread({
|
||||
@@ -1017,7 +1018,8 @@ private fun AttachButton() {
|
||||
}, "agent-attach").start()
|
||||
}
|
||||
RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") {
|
||||
runCatching { picker.launch(arrayOf("*/*")) }
|
||||
AgentAttachments.picking = true
|
||||
if (runCatching { picker.launch(arrayOf("*/*")) }.isFailure) AgentAttachments.picking = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,7 +88,14 @@ internal object AgentPet {
|
||||
private set
|
||||
/** The floating windows could not be made, so the pet stays in DroidDeck's own windows instead. */
|
||||
private var floatFailed by mutableStateOf(false)
|
||||
val floating get() = enabled && allowed && !floatFailed
|
||||
val floating get() = enabled && allowed && !floatFailed && usesOverlayWindows(onQuest)
|
||||
/** Quest's shell turns overlay windows into system panels that take input from the VR view. */
|
||||
private val onQuest = com.droiddeck.launcher.session.QuestExperimental.isSupported()
|
||||
|
||||
internal fun usesOverlayWindows(quest: Boolean) = !quest
|
||||
|
||||
/** On Quest the chat opens as its own panel window, which Horizon moves, resizes and closes. */
|
||||
internal fun chatInOwnWindow(quest: Boolean = onQuest) = quest
|
||||
/** How to close the chat open inside each DroidDeck window that has one. */
|
||||
private val closeInWindow = java.util.WeakHashMap<AgentPetHost, () -> Unit>()
|
||||
|
||||
@@ -118,7 +125,7 @@ internal object AgentPet {
|
||||
AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
|
||||
if (on) {
|
||||
allowed = PetWindows.allowed(context)
|
||||
if (!allowed) requestFloating(context)
|
||||
if (!allowed && usesOverlayWindows(onQuest)) requestFloating(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,9 +258,12 @@ private fun PetLayer(host: AgentPetHost) {
|
||||
val density = LocalDensity.current
|
||||
val openLabel = androidx.compose.ui.res.stringResource(com.droiddeck.launcher.R.string.agent_pet_open)
|
||||
val openChat = {
|
||||
motion.dock()
|
||||
chatShown = true
|
||||
chatOpen = true
|
||||
if (AgentPet.chatInOwnWindow()) com.droiddeck.launcher.agent.AgentChatActivity.open(context)
|
||||
else {
|
||||
motion.dock()
|
||||
chatShown = true
|
||||
chatOpen = true
|
||||
}
|
||||
}
|
||||
val closeChat = {
|
||||
chatOpen = false
|
||||
|
||||
@@ -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,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,11 @@ class BottomDesktopPanel(
|
||||
private val status = ComposeView(context).apply {
|
||||
setContent { DroidDeckTheme { BottomDesktopStatus(state.value, ::startAgain) } }
|
||||
}
|
||||
private val keyboardHost = KeyboardHost(context) { event -> sendKey(event) }
|
||||
private val keyboardHost = KeyboardHost(
|
||||
context,
|
||||
sendKeyEvent = { event -> sendKey(event) },
|
||||
sendText = BottomDesktop::sendText,
|
||||
)
|
||||
private var directTouch = SessionPrefs.bottomDesktopDirectTouch(context)
|
||||
private val touchMode = mutableStateOf(directTouch)
|
||||
private val trackpad = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), TrackpadInput()).apply {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -7,13 +7,16 @@ import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.displayCutout
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
@@ -35,6 +38,7 @@ import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -90,6 +94,29 @@ internal fun DrawerEntryHint(steam: Boolean, inverted: Boolean, onOpen: () -> Un
|
||||
}
|
||||
}
|
||||
|
||||
/** A Quest has no system Back gesture, so a laser drag in from the right edge stands in for it. */
|
||||
@Composable
|
||||
internal fun DrawerEdgeSwipe(onBack: () -> Unit) {
|
||||
val density = LocalDensity.current
|
||||
val threshold = with(density) { 48.dp.toPx() }
|
||||
val strip = with(density) { 12.toDp() }
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
|
||||
Box(
|
||||
Modifier.fillMaxHeight().width(strip).testTag("drawer-edge")
|
||||
.pointerInput(Unit) {
|
||||
var travelled = 0f
|
||||
detectHorizontalDragGestures(
|
||||
onDragStart = { travelled = 0f },
|
||||
onDragEnd = { if (travelled <= -threshold) onBack() },
|
||||
) { change, amount ->
|
||||
change.consume()
|
||||
travelled += amount
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun DrawerCornerTap(onOpen: () -> Unit) {
|
||||
Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout), contentAlignment = Alignment.TopEnd) {
|
||||
|
||||
@@ -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,78 +41,175 @@ 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")
|
||||
|
||||
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
|
||||
if (!legacyButtons) OutlinedButton(
|
||||
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
|
||||
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().then(if (legacyButtons) Modifier else Modifier.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 (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)) }
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) {
|
||||
options.forEachIndexed { index, option ->
|
||||
val selected = mode == option ||
|
||||
(option.engine == FrameGen.ENGINE_OFF && selectedEngine == null)
|
||||
val enabled = option.engine != FrameGen.ENGINE_LSFG || lossless.ready || selected
|
||||
val pick = { onPick(option) }
|
||||
OutlinedButton(
|
||||
onClick = pick,
|
||||
enabled = enabled,
|
||||
modifier = (if (index == focusIndex) focusModifier else Modifier)
|
||||
.weight(1f).controllerConfirm(enabled = enabled, onClick = pick),
|
||||
modifier = (if (index == 0) focusModifier else Modifier).fillMaxWidth()
|
||||
.padding(top = if (index == 0) 0.dp else 6.dp)
|
||||
.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) }
|
||||
) { Text(FrameGen.label(context, option)) }
|
||||
}
|
||||
if (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
|
||||
OutlinedButton(
|
||||
onClick = resetGame,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
|
||||
.controllerConfirm(onClick = resetGame),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
|
||||
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)) },
|
||||
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) }
|
||||
|
||||
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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -106,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),
|
||||
@@ -121,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,
|
||||
@@ -134,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) },
|
||||
@@ -457,6 +456,15 @@ internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusR
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun holdFocus(held: () -> Boolean, target: () -> FocusRequester?) {
|
||||
val since = MainTabSteps.otherKeys
|
||||
repeat(RAIL_HOLD_FRAMES) { frame ->
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
if (MainTabSteps.otherKeys != since) return
|
||||
if (frame == 0 || !held()) runCatching { target()?.requestFocus() }
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun focusSoon(target: () -> FocusRequester) {
|
||||
repeat(30) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
@@ -786,10 +794,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
val stepScope = androidx.compose.runtime.rememberCoroutineScope()
|
||||
val pageKeyNow = androidx.compose.runtime.rememberUpdatedState(s.pageKey)
|
||||
var railHold by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
|
||||
val stepView = androidx.compose.ui.platform.LocalView.current
|
||||
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
|
||||
if (!processSettingsPageVisible) {
|
||||
val keys = navigationKeys(s)
|
||||
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
|
||||
releaseFocusedTextField(stepView)
|
||||
OpenMenus.leaveAll(withPage = true)
|
||||
PageSwipe.direction = step
|
||||
if (s.dualScreen) { onRailSelect(key); return@let }
|
||||
showRailPage(key, false)
|
||||
|
||||
@@ -711,7 +711,7 @@ internal fun SetupPanel(
|
||||
ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) {
|
||||
AgentPet.set(agentContext, it)
|
||||
}
|
||||
if (AgentPet.enabled && !AgentPet.allowed) ActionRow(
|
||||
if (AgentPet.enabled && !AgentPet.allowed && AgentPet.usesOverlayWindows(com.droiddeck.launcher.session.QuestExperimental.isSupported())) ActionRow(
|
||||
stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint),
|
||||
stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) },
|
||||
)
|
||||
@@ -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
|
||||
@@ -887,6 +887,33 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
val steamCard: (@Composable (Modifier) -> Unit)? = if (game != null && steamScope != null) { m ->
|
||||
Box(m) { GameSettingsCard(host, game, steamScope) }
|
||||
} else null
|
||||
val frameGenMenuContent: @Composable () -> Unit = {
|
||||
FrameGenMenu(
|
||||
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
|
||||
lossless = s.lossless,
|
||||
onPick = { mode ->
|
||||
val key = frameGenProfileKey
|
||||
if (key == null) {
|
||||
a.onFrameGenPick(mode)
|
||||
} else {
|
||||
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
|
||||
gameFrameGenMode = mode
|
||||
gameFrameGenOverride = true
|
||||
}
|
||||
},
|
||||
legacyButtons = true,
|
||||
gameProfileId = frameGenProfileKey,
|
||||
hasGameOverride = gameFrameGenOverride,
|
||||
onResetGame = {
|
||||
val key = frameGenProfileKey
|
||||
if (key != null) {
|
||||
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
|
||||
gameFrameGenMode = com.droiddeck.launcher.gpu.FrameGen.mode(context)
|
||||
gameFrameGenOverride = false
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
|
||||
add { m ->
|
||||
val back = stringResource(R.string.hop_from_games)
|
||||
@@ -908,33 +935,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
) {
|
||||
host.open = if (host.open == "fg") null else "fg"
|
||||
}
|
||||
if (host.open == "fg") FrameGenMenu(
|
||||
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
|
||||
lossless = s.lossless,
|
||||
onPick = { mode ->
|
||||
val key = frameGenProfileKey
|
||||
if (key == null) {
|
||||
a.onFrameGenPick(mode)
|
||||
} else {
|
||||
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
|
||||
gameFrameGenMode = mode
|
||||
gameFrameGenOverride = true
|
||||
}
|
||||
},
|
||||
onImportLossless = a.onImportLossless,
|
||||
legacyButtons = true,
|
||||
gameProfileId = frameGenProfileKey,
|
||||
hasGameOverride = gameFrameGenOverride,
|
||||
onResetGame = {
|
||||
val key = frameGenProfileKey
|
||||
if (key != null) {
|
||||
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
|
||||
gameFrameGenMode =
|
||||
com.droiddeck.launcher.gpu.FrameGen.mode(context)
|
||||
gameFrameGenOverride = false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
}
|
||||
}
|
||||
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
|
||||
@@ -966,6 +967,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||
}
|
||||
}
|
||||
if (host.open == "fg") {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 4.dp)) {
|
||||
frameGenMenuContent()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 307 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user