Compare commits

...
Author SHA1 Message Date
The412Banner e6370e1ff7 fix(bionic): start a program outside the prefix from a drive whose root Android lets Wine open 2026-12-03 14:22:50 +00:00
Kurt Himebauch f9eeef44ed Keep the last frame visible on manual pause (#3626)
Use the effective zero-copy profile to capture and restore presentation across manual pause and resume, without overriding a disabled preference.
2026-12-03 07:39:12 -05:00
danyi eeb10e02fd Restore Chinese input for Android and Steam keyboards (#1529)
Commit Android IME text through the focused renderer and submit only after delivery is confirmed. Restore Steam pinyin on Ubuntu rc7 and allow older runtimes to start normally without IBus.
2026-12-03 07:36:55 -05:00
Kurt Himebauch e935263ccb Include IBus in the Ubuntu runtime (#3624)
Ship the IBus daemon, client, and Python bindings required for Steam pinyin. Verify these dependencies during runtime assembly.
2026-12-03 07:36:49 -05:00
FryMcNugget 673675b45e feat(quest): DroidDeck's menu, agent pet and keyboards float in the immersive SteamVR view (#3596) 2026-12-03 07:28:05 -05:00
Tushar Gandhe 153c873898 fix(ui): LB, RB, LT and RT close the keyboard and menus of the page they leave (#3619) 2026-12-03 07:26:39 -05:00
MicroCool cec2e4ed70 Retry rate-limited Robolectric downloads with a Maven Central mirror (#3620) 2026-12-03 07:26:11 -05:00
MaxsTechReview affb0da37f fix(fex): keep the guest stack clear of the host stack's growth reserve (#3623) 2026-12-03 07:13:39 -05:00
FryMcNugget 8cf1e60cc2 fix(runtime): thermal zone binds no longer leak into the stand-in for PCI devices (#3595) 2026-12-02 22:22:52 -05:00
LunaDL e3faee459f Fix frame generation controls in Library and Steam settings (#3597)
Restore the frame generation controls and make the Steam menu focus its first enabled option for controller and keyboard navigation.
2026-12-02 20:54:39 -05:00
Kurt Himebauch 20df8b1858 fix(nativeguest): reap the zombies session processes adopt as subreapers and never wait for (#3610) 2026-12-02 20:31:58 -05:00
Kurt Himebauch 4ab9635ceb fix(desktop): run Plasma, its helpers and the apps it opens outside Android's child-process count (#3599) 2026-12-02 18:45:22 -05:00
112 changed files with 10587 additions and 252 deletions

No files matched your search

+21 -3
View File
@@ -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
+3
View File
@@ -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
}
}
+75
View File
@@ -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>
+1 -1
View File
@@ -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)
+325 -21
View File
@@ -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(); }
+91
View File
@@ -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");
+229
View File
@@ -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;
}
}
};
+30 -2
View File
@@ -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>
@@ -4582,11 +4583,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 +4633,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 +4790,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;
@@ -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);
@@ -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) {
@@ -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) {
@@ -2247,7 +2247,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 +2256,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
@@ -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)
@@ -348,6 +350,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 +553,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 +572,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)
@@ -850,6 +864,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() ||
@@ -988,7 +1003,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 +1208,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 +1287,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 +1492,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 +1547,70 @@ 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 {
com.droiddeck.launcher.input.KeyboardHost(this) { event ->
CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) &&
com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) }
}
}
@androidx.compose.runtime.Composable
private fun SessionMenu(
docked: Boolean,
@@ -1906,9 +1989,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 ->
@@ -2005,18 +2088,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 +2185,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 +2224,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 +2234,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()
}
@@ -3045,6 +3139,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 +3156,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
@@ -3680,16 +3807,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 +3903,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 +3986,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)
}
@@ -5149,27 +5280,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 +5301,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (text != null && stillOpen()) endGameField()
done(text)
}
selectGameField(KEY_C)
selectGameField(copy = true)
}
private fun cancelWowChat() {
@@ -6081,11 +6204,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 +6281,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 +6396,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldButtons.clear()
hidePrimaryKeyboard()
sessionClipboard.stop()
sessionTextInput.stop()
padMotion?.stop()
cursorVisible = false
closeSecondScreen(reset = false)
@@ -6283,7 +6412,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()
@@ -6354,6 +6483,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
contentResolver.unregisterContentObserver(refreshSettingObserver)
if (!screenIsOff()) closeSecondScreen(reset = false)
sessionTextInput.stop()
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
updateBottomGame()
@@ -6433,7 +6563,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)
@@ -7150,6 +7280,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 +7294,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 +7407,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"
@@ -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)
@@ -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'
}
}
@@ -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
}
}
@@ -224,6 +224,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 +314,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) {
@@ -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());
@@ -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) } })
}
@@ -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
@@ -1874,10 +1874,10 @@ object SessionPrefs {
prefs(context).edit().putBoolean(hdrKey(mode), on).apply()
}
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.$mode", true)
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
@@ -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 }
}
}
@@ -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
@@ -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 {
@@ -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) {
@@ -41,8 +41,73 @@ internal fun FrameGenMenu(
val colors = MaterialTheme.colorScheme
val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG")
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_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 == 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(FrameGen.label(context, option)) }
}
if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(
need.orEmpty(),
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 " ✓")
}
}
if (lossless.owned) {
val using = when (lossless.source) {
Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam)
Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import)
Lossless.Source.NONE -> null
}
OutlinedButton(
onClick = onImportLossless,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
.controllerConfirm(onClick = onImportLossless),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: ""))
}
}
}
return
}
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
if (!legacyButtons) OutlinedButton(
OutlinedButton(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
modifier = Modifier.fillMaxWidth().controllerConfirm(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
@@ -54,7 +119,7 @@ internal fun FrameGenMenu(
),
) { Text(offLabel) }
Row(Modifier.fillMaxWidth().then(if (legacyButtons) Modifier else Modifier.padding(top = 8.dp)), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
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
}
@@ -457,6 +457,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 +795,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) },
)
@@ -887,6 +887,34 @@ 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
}
},
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
}
},
)
}
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 +936,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 +968,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()
}
}
}
}
@@ -235,7 +235,7 @@ internal fun GameDetail(
steppedTo = null
return@LaunchedEffect
}
focusSoon { tabFocus.getValue(t) }
holdFocus({ onStrip }) { tabFocus.getValue(t) }
steppedTo = null
}
fun cycle(step: Int) {
@@ -243,7 +243,7 @@ internal fun GameDetail(
val at = tabs.indexOf(tab).coerceAtLeast(0)
val next = tabs[(at + step + tabs.size) % tabs.size]
picked = next
if (inPage) steppedTo = next
steppedTo = next
}
val art: Any? = game?.hero ?: item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover
val artModel: Any? = if (art is String) cardArtRequest(art, item?.tallImageUrl) else art
@@ -531,13 +531,11 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val grid = remember { LazyGridState() }
val detailScroll = rememberScrollState()
var cycled by remember { mutableIntStateOf(0) }
var gridFocused by remember { mutableStateOf(false) }
LaunchedEffect(source, sort) { grid.scrollToItem(0) }
LaunchedEffect(cycled) {
if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
focusWithinFrames({ gridFocused }) {
if (ff.firstTileAttached > 0) ff.firstTile else ff.items["libchip:$source"] ?: FocusRequester.Default
}
val chip = "libchip:$source"
holdFocus({ ff.last == chip }) { ff.items[chip] }
}
CardDetailHost(
open, detailScroll,
@@ -563,7 +561,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
else { focusManager.clearFocus(force = true); onSelect(it) }
},
searchCleared = open != null,
onFocus = { gridFocused = it },
onFocus = {},
soundMode = soundMode,
wallArt = { wallTiles(all.filterNot(concealed).mapNotNull { entryArt(it, tall = true) }) },
emptyText = when {
@@ -753,20 +751,23 @@ private fun LibraryGrid(
}
}
}
val manage = !soundMode && !s.shortcutPicker
LazyVerticalGrid(
columns = if (listMode) GridCells.Fixed(1) else remember(baseWidth, level) { LevelCells(baseWidth, level) }, state = grid,
modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup().bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }).onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level)
gridH = it.height
},
modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup()
.then(if (sourceChipsShown(sources, manage)) Modifier.bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }) else Modifier)
.onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level)
gridH = it.height
},
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
) {
val header: @Composable () -> Unit = {
LibraryHeader(s, a, if (soundMode) total else visible.size + hiddenUninstalled, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections, source = source)
}
val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage = !soundMode && !s.shortcutPicker) }
val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage) }
item(key = if (soundMode) "header" else "filters", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.onSizeChanged { chipsH = it.height }) { Rise(0) { if (soundMode) header() else filters() } }
}
@@ -908,10 +909,13 @@ private fun LibraryHeader(
if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() }
}
private fun sourceChipsShown(sources: List<String>, manage: Boolean): Boolean =
(manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit, manage: Boolean) {
val chips = (manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
val chips = sourceChipsShown(sources, manage)
if (!chips && !manage) return
val pal = LocalPalette.current
val keys = if (chips) listOf(LIBRARY_ALL) + sources else emptyList()
@@ -8,6 +8,9 @@ import com.droiddeck.launcher.input.PcKey
import androidx.compose.ui.res.stringResource
import android.view.KeyEvent
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
@@ -69,6 +72,9 @@ fun PcKeyboard(
sendKey: (Int, Boolean) -> Unit,
onAndroidKeyboard: () -> Unit,
onClose: () -> Unit,
heightFraction: Float? = null,
showButtons: Boolean = true,
hoverFeedback: Boolean = false,
) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
@@ -76,31 +82,40 @@ fun PcKeyboard(
var capsOn by remember { mutableStateOf(false) }
val firstKey = remember { FocusRequester() }
val shifted = (mods[42] ?: MOD_OFF) != MOD_OFF || (mods[54] ?: MOD_OFF) != MOD_OFF
// Keys go to wherever sendKey points now, but a held key is let go where it went down.
val currentSend by androidx.compose.runtime.rememberUpdatedState(sendKey)
val heldAt = remember { mutableMapOf<Int, (Int, Boolean) -> Unit>() }
fun down(code: Int) {
val send = currentSend
heldAt[code] = send
send(code, true)
}
fun up(code: Int) = (heldAt.remove(code) ?: currentSend)(code, false)
fun releaseOnceModifiers() {
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { sendKey(code, false); mods[code] = MOD_OFF }
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { up(code); mods[code] = MOD_OFF }
}
fun press(key: PcKey) {
if (key.code in PC_MODIFIERS) {
when (mods[key.code] ?: MOD_OFF) {
MOD_OFF -> { sendKey(key.code, true); mods[key.code] = MOD_ONCE }
MOD_OFF -> { down(key.code); mods[key.code] = MOD_ONCE }
MOD_ONCE -> mods[key.code] = MOD_LOCKED
else -> { sendKey(key.code, false); mods[key.code] = MOD_OFF }
else -> { up(key.code); mods[key.code] = MOD_OFF }
}
return
}
sendKey(key.code, true)
down(key.code)
}
fun release(key: PcKey) {
if (key.code in PC_MODIFIERS) return
sendKey(key.code, false)
up(key.code)
if (key.code == 58) capsOn = !capsOn
releaseOnceModifiers()
}
androidx.compose.runtime.DisposableEffect(Unit) {
onDispose { for ((code, state) in mods.toMap()) if (state != MOD_OFF) sendKey(code, false) }
onDispose { for (code in heldAt.keys.toList()) up(code) }
}
LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } }
LaunchedEffect(Unit) { if (!hoverFeedback) runCatching { firstKey.requestFocus() } }
val prefsContext = LocalContext.current
remember { PcKeyboardPrefs.load(prefsContext) }
@@ -108,7 +123,7 @@ fun PcKeyboard(
val rows = PC_KEY_ROWS.map { row -> row.filter { it.code !in hiddenCodes } }.filter { it.isNotEmpty() }
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
val rowHeight = ((maxHeight * (PcKeyboardPrefs.size / 100f) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
val rowHeight = ((maxHeight * (heightFraction ?: (PcKeyboardPrefs.size / 100f)) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
.coerceIn(20.dp, 56.dp)
Box(
Modifier.fillMaxWidth()
@@ -122,9 +137,11 @@ fun PcKeyboard(
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(24.dp)) {
Text(stringResource(R.string.drawer_pc_keyboard), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant)
Spacer(Modifier.weight(1f))
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
Spacer(Modifier.width(8.dp))
HeaderButton(stringResource(R.string.pckb_hide), onClose)
if (showButtons) {
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
Spacer(Modifier.width(8.dp))
HeaderButton(stringResource(R.string.pckb_hide), onClose)
}
}
rows.forEachIndexed { r, row ->
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) {
@@ -139,7 +156,7 @@ fun PcKeyboard(
}
key(key.code) {
KeyCap(
label, key.weight, lit, locked = state == MOD_LOCKED,
label, key.weight, lit, locked = state == MOD_LOCKED, hoverFeedback = hoverFeedback,
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
onDown = { press(key) }, onUp = { release(key) },
)
@@ -154,25 +171,35 @@ fun PcKeyboard(
@Composable
private fun RowScope.KeyCap(
label: String, weight: Float, lit: Boolean, locked: Boolean,
label: String, weight: Float, lit: Boolean, locked: Boolean, hoverFeedback: Boolean,
modifier: Modifier, onDown: () -> Unit, onUp: () -> Unit,
) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val focused by src.collectIsFocusedAsState()
val hovered by src.collectIsHoveredAsState()
val (pointedAt, laser) = com.droiddeck.launcher.session.xr.rememberXrPointed()
val pointed = hoverFeedback && (hovered || laser.value)
var down by remember { mutableStateOf(false) }
val fill by animateColorAsState(
when {
down -> pal.signal.copy(alpha = 0.55f)
lit -> pal.signal.copy(alpha = if (locked) 0.45f else 0.28f)
pointed -> Color.White.copy(alpha = 0.2f)
else -> Color.White.copy(alpha = 0.07f)
}, Motion.tw(160), label = "keyFill",
}, Motion.tw(if (down) 40 else 160), label = "keyFill",
)
val scale by animateFloatAsState(
if (!hoverFeedback) 1f else if (down) 0.9f else if (pointed) 1.06f else 1f, Motion.tw(if (down) 40 else 140), label = "keyScale",
)
Box(
contentAlignment = Alignment.Center,
modifier = modifier.weight(weight).fillMaxHeight()
.then(pointedAt)
.graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale }
.background(fill, RoundedCornerShape(7.dp))
.glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
.glideBorder(if (hoverFeedback) pointed || down else focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
.then(if (hoverFeedback) Modifier.hoverable(src) else Modifier)
.pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown().consume()
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.compose.foundation.gestures.awaitEachGesture
@@ -48,10 +49,18 @@ internal fun releaseTextField(field: EditText, origin: IntArray, x: Float, y: Fl
val insideX = x >= origin[0] - margin && x <= origin[0] + field.width + margin
val insideY = y >= origin[1] - margin && y <= origin[1] + field.height + margin
if (insideX && insideY) return
releaseTextField(field)
}
internal fun releaseTextField(field: EditText) {
field.clearFocus()
(field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(field.windowToken, 0)
}
internal fun releaseFocusedTextField(view: View) {
(view.rootView.findFocus() as? EditText)?.let(::releaseTextField)
}
/** A dialog's touches never reach the activity, so a dialog holding a search field counts its taps and releases the field itself. */
internal fun Modifier.releaseTextFieldOnTap(): Modifier = composed {
val view = LocalView.current
@@ -25,6 +25,7 @@ import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.wayland.WaylandCompositor
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.BottomDesktop
@@ -490,12 +491,19 @@ class SecondScreenPresentation(
}
private fun attachKeyboard() {
val host = KeyboardHost(context) { event ->
val handled = sessionActivity.dispatchKeyEvent(event)
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
(event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() }
handled
}
val host = KeyboardHost(
context,
sendKeyEvent = { event ->
val handled = sessionActivity.dispatchImeKeyEvent(event)
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
(event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() }
handled
},
sendText = { text ->
WaylandCompositor.textInputCommit(text)
if (fieldKeyboard && text == "\r") root.post { closeFieldKeyboard() }
},
)
host.onImeChanged = { visible -> if (!visible && keyboardShown.value) keyboardClosed() }
keyboardHost = host
root.addView(host, ViewGroup.LayoutParams(1, 1))
@@ -87,6 +87,7 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.node.currentValueOf
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
@@ -152,14 +153,43 @@ internal fun Modifier.blockTouches(): Modifier = pointerInput(Unit) { detectTapG
internal fun Modifier.tapOutside(onTap: () -> Unit): Modifier =
pointerInput(onTap) { detectTapGestures(onTap = { onTap() }) }
internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = onPreviewKeyEvent { event ->
val keyEvent = event.nativeKeyEvent
val previous = keyEvent.keyCode == KeyEvent.KEYCODE_BUTTON_L1
if (!previous && keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_R1) {
false
} else {
if (keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) { if (previous) onPrevious() else onNext() }
true
internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = this then BumpersElement(onPrevious, onNext)
private data class BumpersElement(val onPrevious: () -> Unit, val onNext: () -> Unit) :
androidx.compose.ui.node.ModifierNodeElement<BumpersNode>() {
override fun create() = BumpersNode(onPrevious, onNext)
override fun update(node: BumpersNode) {
node.onPrevious = onPrevious
node.onNext = onNext
}
}
internal class BumpersNode(var onPrevious: () -> Unit, var onNext: () -> Unit) :
Modifier.Node(), androidx.compose.ui.input.key.KeyInputModifierNode, androidx.compose.ui.node.CompositionLocalConsumerModifierNode {
override fun onAttach() { PageBumpers.attached += this }
override fun onDetach() { PageBumpers.attached -= this }
override fun onPreKeyEvent(event: androidx.compose.ui.input.key.KeyEvent): Boolean = PageBumpers.handle(event.nativeKeyEvent, this)
override fun onKeyEvent(event: androidx.compose.ui.input.key.KeyEvent): Boolean = false
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
fun step(previous: Boolean) {
releaseFocusedTextField(currentValueOf(androidx.compose.ui.platform.LocalView))
OpenMenus.leaveAll(withPage = false)
if (previous) onPrevious() else onNext()
// Android keeps touch mode through gamepad buttons, and the pages move the focus only outside it.
val input = currentValueOf(LocalInputModeManager)
if (input.inputMode != InputMode.Keyboard) input.requestInputMode(InputMode.Keyboard)
}
}
internal object PageBumpers {
val attached = ArrayList<BumpersNode>()
fun handle(event: KeyEvent, node: BumpersNode? = attached.lastOrNull()): Boolean {
val previous = event.keyCode == KeyEvent.KEYCODE_BUTTON_L1
if (node == null || (!previous && event.keyCode != KeyEvent.KEYCODE_BUTTON_R1)) return false
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) node.step(previous)
return true
}
}
@@ -267,6 +297,25 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
}
}
private val StepKeys = setOf(KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2)
private fun launcherOf(view: android.view.View) = view.context.findActivity() as? com.droiddeck.launcher.FrontEndActivity
// A popup is a window of its own, so controller input sent to it never reaches the launcher's.
private fun Modifier.passSteps(host: android.view.View): Modifier = onPreviewKeyEvent { event ->
event.nativeKeyEvent.keyCode in StepKeys && launcherOf(host) != null && host.rootView.dispatchKeyEvent(event.nativeKeyEvent)
}
@Composable
private fun PassTriggerMotion(host: android.view.View) {
val popup = androidx.compose.ui.platform.LocalView.current
androidx.compose.runtime.DisposableEffect(popup, host) {
val launcher = launcherOf(host)?.takeIf { it.window.decorView === host.rootView }
if (launcher != null) popup.setOnGenericMotionListener { _, event -> launcher.onMenuMotion(event); false }
onDispose { popup.setOnGenericMotionListener(null) }
}
}
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
fun AnchoredMenu(
@@ -277,6 +326,13 @@ fun AnchoredMenu(
val state = remember { MutableTransitionState(false) }
state.targetState = open
if (!state.currentState && !state.targetState && state.isIdle) return
val dismissNow = rememberUpdatedState(onDismiss)
if (open) androidx.compose.runtime.DisposableEffect(Unit) {
val leave = { _: Boolean -> dismissNow.value() }
OpenMenus.leave += leave
onDispose { OpenMenus.leave -= leave }
}
val hostView = androidx.compose.ui.platform.LocalView.current
val firstItemFocus = remember { FocusRequester() }
val inputMode = LocalInputModeManager.current.inputMode
LaunchedEffect(open, inputMode) {
@@ -294,6 +350,7 @@ fun AnchoredMenu(
val pal = LocalPalette.current
Popup(popupPositionProvider = provider, onDismissRequest = onDismiss, properties = PopupProperties(focusable = true)) {
TrackKeyWindow()
PassTriggerMotion(hostView)
val popupInput = LocalInputModeManager.current
LaunchedEffect(open, inputMode) {
if (!open || inputMode != InputMode.Keyboard) return@LaunchedEffect
@@ -323,6 +380,7 @@ fun AnchoredMenu(
.clip(RowShape)
.background(pal.surfaceVariant.copy(alpha = 0.95f))
.border(1.dp, pal.signal.copy(alpha = 0.22f), RowShape)
.passSteps(hostView)
.controllerBack(onDismiss)
.padding(6.dp),
) {
@@ -2,7 +2,10 @@ package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
@@ -12,8 +15,30 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) {
SettingsGroup(stringResource(R.string.frame_gen_title)) {
SettingsRow(stringResource(R.string.frame_gen_title), stringResource(R.string.frame_gen_hint), highlighted = host.open == "fg") {
Box {
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
if (host.open == "fg") FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless)
val open = host.open == "fg"
ValueChip(s.frameGenLabel, open) { host.open = if (open) null else "fg" }
AnchoredMenu(
open = open,
onDismiss = { if (host.open == "fg") host.open = null },
title = stringResource(R.string.frame_gen_title),
compact = true,
minWidth = 220.dp,
) { firstItemFocus ->
FrameGenMenu(
mode = s.frameGen,
lossless = s.lossless,
onPick = { mode ->
a.onFrameGenPick(mode)
host.open = null
},
onImportLossless = {
a.onImportLossless()
host.open = null
},
focusModifier = Modifier.focusRequester(firstItemFocus),
legacyButtons = true,
)
}
}
}
}
@@ -145,6 +145,12 @@ internal class StepOutScope(private val items: List<Animatable<Float, AnimationV
}
}
internal object OpenMenus {
val leave = ArrayList<(Boolean) -> Unit>()
fun leaveAll(withPage: Boolean) = leave.toList().forEach { it(withPage) }
}
private val OutPull = 6.dp
private val OutBoxCorner = 16.dp
private val OutFillet = 10.dp
@@ -194,13 +200,25 @@ private fun StepOutPanel(
val glide = LocalFocusGlide.current
val opener = remember { arrayOfNulls<GlideSource>(1) }
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
val dismissNow = androidx.compose.runtime.rememberUpdatedState(onDismiss)
val leavesWithPage = remember { booleanArrayOf(false) }
val presence = remember { Animatable(1f) }
if (open) androidx.compose.runtime.DisposableEffect(Unit) {
val leave = { withPage: Boolean ->
opener[0] = null
leavesWithPage[0] = withPage
dismissNow.value()
}
OpenMenus.leave += leave
onDispose { OpenMenus.leave -= leave }
}
var moving by remember { mutableStateOf(false) }
val placed = remember { arrayOfNulls<Any>(3) }
if (moving) VeilRing()
val pull = with(density) { OutPull.toPx() }
val corner = pillCorner?.let { with(density) { it.toPx() } } ?: minOf(pill.height, pill.width) / 2f
BoxWithConstraints(Modifier.fillMaxSize()) {
BoxWithConstraints(Modifier.fillMaxSize().graphicsLayer { alpha = presence.value }) {
val hostWidth = constraints.maxWidth.toFloat()
val hostHeight = constraints.maxHeight.toFloat()
val availableHeight = with(density) {
@@ -221,9 +239,11 @@ private fun StepOutPanel(
if (grown && flipped) edge.snapTo(if (open) out else rest)
val boxBottom = pill.bottom + pull + c.height
if (open) {
leavesWithPage[0] = false
presence.snapTo(1f)
if (!grown) {
opener[0] = glide?.current
edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f)
edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f); dim.snapTo(0f)
pieces.forEach { it.snapTo(0f) }
grown = true
}
@@ -241,7 +261,10 @@ private fun StepOutPanel(
} else {
opener[0]?.let { o -> if (inputMode.inputMode == InputMode.Keyboard) runCatching { o.requester.requestFocus() } }
opener[0] = null
coroutineScope {
if (leavesWithPage[0]) {
moving = true
presence.animateTo(0f, Motion.tw(160))
} else coroutineScope {
pieces.forEach { launch { it.animateTo(0f, Motion.tw(90)) } }
launch { delay(Motion.ms(60).toLong()); dim.animateTo(0f, Motion.tw(300)) }
moving = true
@@ -31,7 +31,7 @@ class BottomDesktopCompositorService : Service() {
MSG_RESIZE -> resize(msg.arg1, msg.arg2)
MSG_TOUCH -> WaylandCompositor.nativeSendTouch(msg.arg1 and 0xff, msg.arg1 shr 8,
msg.arg2 ushr 16, msg.arg2 and 0xffff)
MSG_KEY -> WaylandCompositor.nativeSendKey(msg.arg1, msg.arg2)
MSG_KEY -> WaylandCompositor.nativeSendKeyOrdered(msg.arg1, msg.arg2)
MSG_POINTER -> WaylandCompositor.nativeSendPointer(1, msg.arg1, msg.arg2)
MSG_SCENE -> WaylandCompositor.nativeSendSceneInput(msg.arg1, msg.arg2, msg.peekData()?.getInt(KEY_B) ?: 0)
MSG_CURSOR -> if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(msg.arg1 != 0)
@@ -202,6 +202,27 @@ public final class WaylandCompositor {
if (l != null) l.onTextInput(enabled, program, x, y, w, h);
}
public interface TextInputFallbackListener {
boolean onTextInputFallback(String text, int token);
}
private static volatile TextInputFallbackListener textInputFallbackListener;
public static void setTextInputFallbackListener(TextInputFallbackListener l) { textInputFallbackListener = l; }
public static boolean isTextInputFallbackListener(TextInputFallbackListener l) { return textInputFallbackListener == l; }
public static void clearTextInputFallbackListener(TextInputFallbackListener l) {
if (textInputFallbackListener == l) textInputFallbackListener = null;
}
@SuppressWarnings("unused")
static boolean onTextInputFallback(byte[] utf8, int token) {
TextInputFallbackListener l = textInputFallbackListener;
if (l == null || utf8 == null) return false;
return l.onTextInputFallback(new String(utf8, java.nio.charset.StandardCharsets.UTF_8), token);
}
private static byte[] utf8(String s) {
return s == null ? new byte[0] : s.getBytes(java.nio.charset.StandardCharsets.UTF_8);
}
@@ -210,14 +231,28 @@ public final class WaylandCompositor {
public static void textInputCommit(String text) { if (text != null && !text.isEmpty()) nativeTextInputCommit(utf8(text)); }
public static void textInputCommitAndSubmit(String text) {
if (text != null && !text.isEmpty()) nativeTextInputCommitAndSubmit(utf8(text));
}
public static void textInputPreedit(String text, int cursor) { nativeTextInputPreedit(utf8(text), cursor, cursor); }
public static void textInputDelete(int before, int after) { nativeTextInputDelete(before, after); }
public static final int TEXT_NOT_DELIVERED = 0;
public static final int TEXT_DELIVERED = 1;
public static final int TEXT_UNRESOLVED = 2;
public static void completeTextInputFallback(int token, int result) {
nativeCompleteTextInputFallback(token, result);
}
private static native void nativeSetClipboardText(byte[] utf8);
private static native void nativeTextInputCommit(byte[] utf8);
private static native void nativeTextInputCommitAndSubmit(byte[] utf8);
private static native void nativeTextInputPreedit(byte[] utf8, int cursorBegin, int cursorEnd);
private static native void nativeTextInputDelete(int before, int after);
private static native void nativeCompleteTextInputFallback(int token, int result);
public static native void nativeStart(String xdgRuntimeDir);
@@ -248,6 +283,10 @@ public final class WaylandCompositor {
public static native void nativeSendKey(int evdev, int state);
// Ordered delivery: key events share the host queue with text commits so keys cannot overtake pending text.
public static native void nativeSendKeyOrdered(int evdev, int state);
public static native void nativeSelectGameField(boolean copy);
public static native boolean nativeFocusTakesTouch();
public static native boolean nativeCursorInputPos(int[] out);
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.input
import org.junit.Assert.assertEquals
import org.junit.Test
class HeldInputTest {
@Test
fun normalRoutingUsesDefaultEmitter() {
val events = mutableListOf<Pair<Int, Boolean>>()
val input = HeldInput { code, down -> events.add(code to down) }
input.set(1, 30, true)
input.set(1, 30, false)
assertEquals(listOf(30 to true, 30 to false), events)
}
@Test
fun orderedSenderHandlesDownRepeatedDownSecondOwnerAndFinalRelease() {
val defaultEvents = mutableListOf<Pair<Int, Boolean>>()
val orderedEvents = mutableListOf<Pair<Int, Boolean>>()
val input = HeldInput { code, down -> defaultEvents.add(code to down) }
val ordered: (Int, Boolean) -> Unit = { code, down -> orderedEvents.add(code to down) }
input.set(1, 30, true, ordered)
input.set(1, 30, true, ordered)
input.set(2, 30, true, ordered)
input.set(1, 30, false)
input.set(2, 30, false)
assertEquals(listOf(30 to true, 30 to false), orderedEvents)
assertEquals(emptyList<Pair<Int, Boolean>>(), defaultEvents)
}
@Test
fun releaseChoosesMatchingRoute() {
val defaultEvents = mutableListOf<Pair<Int, Boolean>>()
val orderedEvents = mutableListOf<Pair<Int, Boolean>>()
val input = HeldInput { code, down -> defaultEvents.add(code to down) }
val ordered: (Int, Boolean) -> Unit = { code, down -> orderedEvents.add(code to down) }
input.set(1, 31, true, ordered)
input.set(2, 32, true)
input.release(2)
input.release(1)
assertEquals(listOf(31 to true, 31 to false), orderedEvents)
assertEquals(listOf(32 to true, 32 to false), defaultEvents)
}
@Test
fun clearChoosesMatchingRoute() {
val defaultEvents = mutableListOf<Pair<Int, Boolean>>()
val orderedEvents = mutableListOf<Pair<Int, Boolean>>()
val input = HeldInput { code, down -> defaultEvents.add(code to down) }
val ordered: (Int, Boolean) -> Unit = { code, down -> orderedEvents.add(code to down) }
input.set(1, 40, true, ordered)
input.set(2, 41, true)
input.clear()
assertEquals(listOf(40 to true, 40 to false), orderedEvents)
assertEquals(listOf(41 to true, 41 to false), defaultEvents)
}
}
@@ -3,9 +3,15 @@ package com.droiddeck.launcher.input
import android.app.Activity
import android.content.Context
import android.os.Looper
import android.text.InputType
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
@@ -20,11 +26,13 @@ import org.robolectric.annotation.Config
class KeyboardHostTest {
private lateinit var imm: InputMethodManager
private lateinit var host: KeyboardHost
private val keys = mutableListOf<KeyEvent>()
private val texts = mutableListOf<String>()
@Before fun setUp() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
host = KeyboardHost(activity)
host = KeyboardHost(activity, { keys += it; true }, { texts += it })
activity.setContentView(FrameLayout(activity).apply { addView(host) })
idle()
}
@@ -41,6 +49,36 @@ class KeyboardHostTest {
assertTrue(host.shown)
}
@Config(sdk = [33])
@Test fun shownEditorIsNotDescribedAsAPasswordField() {
host.show()
idle()
val attrs = EditorInfo()
val connection = host.onCreateInputConnection(attrs)
assertNotNull("shown host must expose an input connection", connection)
assertEquals(
"editor must be declared as a text field",
InputType.TYPE_CLASS_TEXT,
attrs.inputType and InputType.TYPE_MASK_CLASS,
)
val variation = attrs.inputType and InputType.TYPE_MASK_VARIATION
assertFalse(
"text field must not be a password field",
variation == InputType.TYPE_TEXT_VARIATION_PASSWORD,
)
assertFalse(
"text field must not be a visible password field",
variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD,
)
assertFalse(
"text field must not be a web password field",
variation == InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD,
)
}
@Config(sdk = [28])
@Test fun toggleHidesAKeyboardThatIsShowing() {
host.show()
@@ -51,5 +89,436 @@ class KeyboardHostTest {
assertFalse(host.shown)
}
@Config(sdk = [33])
@Test fun mixedScriptTextIsCommittedOnceWithoutKeyEvents() {
host.show()
idle()
val text = "中文ABC123,。é😀"
assertTrue(connection().commitText(text, 1))
idle()
assertEquals("the whole string must reach the guest once", listOf(text), texts)
assertTrue("non-ASCII text must not be turned into key events", keys.isEmpty())
}
@Config(sdk = [33])
@Test fun latestCompositionIsCommittedOnceWhenFinished() {
host.show()
idle()
val connection = connection()
connection.setComposingText("zhong", 1)
connection.setComposingText("中文", 1)
assertTrue(texts.isEmpty())
connection.finishComposingText()
connection.finishComposingText()
idle()
assertTrue(keys.isEmpty())
assertEquals(listOf("中文"), texts)
}
@Config(sdk = [33])
@Test fun finishedCandidateIsCommittedExactlyOnce() {
host.show()
idle()
val connection = connection()
connection.setComposingText("zhong", 1)
connection.deleteSurroundingText(1, 0)
connection.commitText("中文", 1)
connection.finishComposingText()
connection.setComposingText("ab", 1)
connection.deleteSurroundingText(1, 0)
connection.setComposingText("xy", 1)
connection.finishComposingText()
idle()
assertEquals(listOf("中文", "xy"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun emptyCompositionCancelsPendingText() {
host.show()
idle()
val connection = connection()
connection.setComposingText("zhong", 1)
connection.setComposingText("", 1)
connection.finishComposingText()
idle()
assertTrue(texts.isEmpty())
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun deleteWithinCompositionShortensPendingTextWithoutGuestBackspace() {
host.show()
idle()
val connection = connection()
connection.setComposingText("abc", 1)
connection.deleteSurroundingText(1, 0)
idle()
assertTrue(texts.isEmpty())
assertTrue(keys.isEmpty())
connection.finishComposingText()
idle()
assertEquals(listOf("ab"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun deleteBeyondCompositionForwardsOnlyResidualCountsWithoutResurrectingText() {
host.show()
idle()
val connection = connection()
connection.setComposingText("ab", 1)
connection.deleteSurroundingText(3, 1)
connection.finishComposingText()
connection.setComposingText("cd", 0)
connection.deleteSurroundingText(1, 3)
connection.finishComposingText()
idle()
assertEquals(listOf("\b\u007f", "\b\u007f"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun composingCursorAtStartConsumesForwardDeleteAndForwardsBackspace() {
host.show()
idle()
val connection = connection()
connection.setComposingText("abc", 0)
connection.deleteSurroundingText(1, 0)
assertEquals(listOf("\b"), texts)
connection.deleteSurroundingText(0, 1)
connection.finishComposingText()
idle()
assertEquals(listOf("\b", "bc"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun utf16DeleteOfTrailingEmojiInCompositionPreservesChineseText() {
host.show()
idle()
val connection = connection()
connection.setComposingText("中文😀", 1)
connection.deleteSurroundingText(2, 0)
connection.finishComposingText()
idle()
assertEquals(listOf("中文"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun chinesePendingTextFinishesBeforeEditorActionWithoutDuplication() {
host.show()
idle()
val connection = connection()
connection.setComposingText("中文", 1)
connection.performEditorAction(EditorInfo.IME_ACTION_SEND)
connection.finishComposingText()
idle()
assertEquals(listOf("中文", "\r"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun chinesePendingTextFinishesBeforePlainSoftEnterWithoutDuplication() {
host.show()
idle()
val connection = connection()
connection.setComposingText("中文", 1)
connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
connection.finishComposingText()
idle()
assertEquals(listOf("中文", "\r"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun unknownUtf16DeleteOfCommittedEmojiIsRejectedWithoutGuestEdit() {
host.show()
idle()
val connection = connection()
assertTrue(connection.commitText("A\uD83D\uDE00", 1))
idle()
texts.clear()
assertFalse("unknown committed UTF-16 deletion must be rejected",
connection.deleteSurroundingText(2, 0))
idle()
assertTrue("a rejected deletion must not edit the guest", texts.isEmpty())
assertTrue(connection.deleteSurroundingTextInCodePoints(1, 0))
idle()
assertEquals(listOf("\b"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun codePointDeleteAtEndOfComposingSurrogateSendsOnlyTextBeforeEmoji() {
host.show()
idle()
val connection = connection()
connection.setComposingText("A\uD83D\uDE00", 1)
assertFalse("half-surrogate UTF-16 deletion must be rejected",
connection.deleteSurroundingText(1, 0))
idle()
assertTrue("a rejected half-surrogate deletion must retain original text", texts.isEmpty())
assertTrue(connection.deleteSurroundingTextInCodePoints(1, 0))
connection.finishComposingText()
idle()
assertEquals(listOf("A"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun codePointDeleteBeyondCompositionForwardsBothResidualControls() {
host.show()
idle()
val connection = connection()
assertTrue(connection.commitText("abcd", 1))
idle()
texts.clear()
assertTrue(connection.deleteSurroundingTextInCodePoints(2, 2))
idle()
assertEquals(listOf("\b\b\u007f\u007f"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun asciiTextIsCommittedAsOneTextCallback() {
host.show()
idle()
assertTrue(connection().commitText("ab", 1))
idle()
assertEquals("ASCII must reach the guest as one whole commit", listOf("ab"), texts)
assertTrue("ASCII must not take the key event path", keys.isEmpty())
}
@Config(sdk = [33])
@Test fun adjacentCommitsKeepTheirOrder() {
host.show()
idle()
val connection = connection()
assertTrue(connection.commitText("中文", 1))
assertTrue(connection.commitText("中文", 1))
assertTrue(connection.commitText(" ", 1))
assertTrue(connection.commitText("abc", 1))
idle()
assertEquals("every commit must keep the order the IME sent it", listOf("中文", "中文", " ", "abc"), texts)
assertTrue("no commit may take the key event path", keys.isEmpty())
}
@Config(sdk = [33])
@Test fun backspaceAndEnterQueueOrderedControls() {
host.show()
idle()
val connection = connection()
connection.deleteSurroundingText(1, 0)
connection.performEditorAction(EditorInfo.IME_ACTION_SEND)
idle()
assertEquals(
"soft edits must ride the ordered text FIFO, not the key event route",
listOf("\b", "\r"), texts,
)
assertTrue("soft edits must not become key events", keys.isEmpty())
}
@Config(sdk = [33])
@Test fun deleteSurroundingTextQueuesBackspaceThenForwardDelete() {
host.show()
idle()
assertTrue(connection().deleteSurroundingText(1, 1))
idle()
assertEquals(listOf("\b\u007f"), texts)
assertTrue("deletions must not become key events", keys.isEmpty())
}
@Config(sdk = [33])
@Test fun commitThenDeleteThenEditorActionKeepTheirOrder() {
host.show()
idle()
val connection = connection()
assertTrue(connection.commitText("中文", 1))
assertTrue(connection.deleteSurroundingText(1, 0))
assertTrue(connection.performEditorAction(EditorInfo.IME_ACTION_SEND))
idle()
assertEquals("a Chinese commit must not be overtaken by the soft edits after it",
listOf("中文", "\b", "\r"), texts)
assertTrue(keys.isEmpty())
}
@Config(sdk = [33])
@Test fun softEditKeysQueueExactlyOneControlPerPress() {
host.show()
idle()
val connection = connection()
for ((keyCode, control) in listOf(
KeyEvent.KEYCODE_DEL to "\b",
KeyEvent.KEYCODE_FORWARD_DEL to "\u007f",
KeyEvent.KEYCODE_ENTER to "\r",
KeyEvent.KEYCODE_TAB to "\t",
)) {
texts.clear()
assertTrue(connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, keyCode)))
assertTrue(connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, keyCode)))
assertEquals("one down plus one up must queue exactly one control",
listOf(control), texts)
}
assertTrue("soft edit keys must not reach the key event route", keys.isEmpty())
}
@Config(sdk = [33])
@Test fun modifiedSoftKeysStillTravelAsKeyEvents() {
host.show()
idle()
val connection = connection()
assertTrue(connection.sendKeyEvent(
keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER,
KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON)))
idle()
assertEquals("a modifier shortcut must keep using key events",
listOf(KeyEvent.KEYCODE_ENTER), keys.map { it.keyCode })
assertTrue(texts.isEmpty())
}
@Config(sdk = [33])
@Test fun unmodifiedSoftDownStaysSoftWhenTheUpGainsAModifier() {
host.show()
idle()
val connection = connection()
assertTrue(connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)))
assertTrue(connection.sendKeyEvent(
keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, KeyEvent.META_CTRL_ON)))
idle()
assertEquals("a plain press must stay a soft edit for its whole press", listOf("\r"), texts)
assertTrue("the matching up must follow the route picked on down", keys.isEmpty())
}
@Config(sdk = [33])
@Test fun modifiedSoftDownStaysAKeyEventWhenTheUpLosesTheModifier() {
host.show()
idle()
val connection = connection()
connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, KeyEvent.META_SHIFT_ON))
connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
idle()
assertEquals("a shortcut press keeps both of its key events",
listOf(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_ENTER), keys.map { it.keyCode })
assertTrue("a shortcut press must not leak into the text channel", texts.isEmpty())
}
@Config(sdk = [33])
@Test fun repeatedSoftDownKeepsOneRouteAcrossModifierChanges() {
host.show()
idle()
val connection = connection()
connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
connection.sendKeyEvent(
keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL, KeyEvent.META_CTRL_ON, repeat = 2))
connection.sendKeyEvent(
keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL, KeyEvent.META_CTRL_ON))
idle()
assertEquals("autorepeat must stay on the soft control route", listOf("\b", "\b"), texts)
assertTrue("autorepeat must not turn into key events", keys.isEmpty())
}
@Config(sdk = [33])
@Test fun interleavedSoftKeysKeepTheirOwnRoutes() {
host.show()
idle()
val connection = connection()
connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, KeyEvent.META_CTRL_ON))
connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL, KeyEvent.META_CTRL_ON))
connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_TAB))
idle()
assertEquals("only the plain press is a soft edit", listOf("\b"), texts)
assertEquals("the shortcut press keeps both of its key events",
listOf(KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_TAB), keys.map { it.keyCode })
}
@Config(sdk = [33])
@Test fun typedChatTextAndSoftEditsStayOrdered() {
host.type("你好😀")
host.tap(KeyEvent.KEYCODE_DEL)
host.tap(KeyEvent.KEYCODE_ENTER)
idle()
assertEquals("text, delete and enter must keep their order",
listOf("你好😀", "\b", "\r"), texts)
assertTrue("chat text and edits must not become key events", keys.isEmpty())
}
@Config(sdk = [33])
@Test fun tappingEscapeStillSendsKeyEvents() {
host.tap(KeyEvent.KEYCODE_ESCAPE)
idle()
assertEquals("escape must keep its down/up pair",
listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP), keys.map { it.action })
assertEquals("escape must target the escape key",
listOf(KeyEvent.KEYCODE_ESCAPE, KeyEvent.KEYCODE_ESCAPE), keys.map { it.keyCode })
assertTrue("escape must not use the text channel", texts.isEmpty())
}
private fun keyEvent(action: Int, keyCode: Int, metaState: Int = 0, repeat: Int = 0) =
KeyEvent(0L, 0L, action, keyCode, repeat, metaState)
private fun connection(): InputConnection {
val connection = host.onCreateInputConnection(EditorInfo())
assertNotNull("shown host must expose an input connection", connection)
return connection!!
}
private fun idle() = shadowOf(Looper.getMainLooper()).idle()
}
@@ -46,6 +46,7 @@ class SessionInputPointerTest {
CompositorShadow.pointers.clear()
CompositorShadow.events.clear()
CompositorShadow.keys.clear()
CompositorShadow.ordered.clear()
WriterShadow.mouse.clear()
WriterShadow.beforeWheel = null
}
@@ -151,7 +152,8 @@ class SessionInputPointerTest {
fun hardwareCtrl(down: Boolean) = ReflectionHelpers.callInstanceMethod<Unit>(activity, "sendGuestKey",
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 97),
ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, down),
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 8))
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 8),
ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, false))
output.key(29, true)
hardwareCtrl(true)
hardwareCtrl(false)
@@ -249,10 +251,26 @@ class SessionInputPointerTest {
@Test fun wowFieldSelectionPreservesCtrlHeldByTheInputProfile() {
output.key(29, true)
ReflectionHelpers.callInstanceMethod<Unit>(activity, "selectGameField",
ReflectionHelpers.ClassParameter.from(IntArray::class.java, intArrayOf(46)))
assertEquals(listOf(29 to 1, 30 to 1, 30 to 0, 46 to 1, 46 to 0), CompositorShadow.keys)
ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true))
assertEquals(listOf("select:true"), CompositorShadow.ordered)
assertEquals(listOf(29 to 1), CompositorShadow.keys)
output.key(29, false)
assertEquals(29 to 0, CompositorShadow.keys.last())
assertEquals(listOf(29 to 1, 29 to 0), CompositorShadow.keys)
}
@Test fun wowChatQueuesCaretKeysBeforeAtomicTextAndSubmit() {
ReflectionHelpers.setField(activity, "keyboard",
KeyboardHost(activity, { false }, WaylandCompositor::textInputCommit))
fun send(replace: Boolean) = ReflectionHelpers.callInstanceMethod<Unit>(activity, "sendWowChat",
ReflectionHelpers.ClassParameter.from(String::class.java, "中文"),
ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType!!, replace))
send(true)
assertEquals(listOf("select:false", "submit:中文"),
CompositorShadow.ordered)
CompositorShadow.ordered.clear()
send(false)
assertEquals(listOf("key:107:1", "key:107:0", "submit:中文"), CompositorShadow.ordered)
assertEquals(emptyList<Pair<Int, Int>>(), CompositorShadow.keys)
}
@Test fun horizontalWheelFinishesBeforeRawMouseDestruction() {
@@ -311,10 +329,15 @@ class SessionInputPointerTest {
val pointers = mutableListOf<Triple<Int, Int, Int>>()
val events = mutableListOf<Triple<Int, Int, Int>>()
val keys = mutableListOf<Pair<Int, Int>>()
val ordered = mutableListOf<String>()
@JvmStatic @Implementation fun __staticInitializer__() {}
@JvmStatic @Implementation fun nativeSendPointer(action: Int, x: Int, y: Int) { pointers += Triple(action, x, y) }
@JvmStatic @Implementation fun nativeSendSceneInput(type: Int, code: Int, value: Int) { events += Triple(type, code, value) }
@JvmStatic @Implementation fun nativeSendKey(code: Int, value: Int) { keys += code to value }
@JvmStatic @Implementation fun nativeSendKeyOrdered(code: Int, value: Int) { ordered += "key:$code:$value" }
@JvmStatic @Implementation fun nativeSelectGameField(copy: Boolean) { ordered += "select:$copy" }
@JvmStatic @Implementation fun textInputCommit(text: String) { ordered += "text:$text" }
@JvmStatic @Implementation fun textInputCommitAndSubmit(text: String) { ordered += "submit:$text" }
}
}
@@ -0,0 +1,314 @@
package com.droiddeck.launcher.input
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.os.Looper
import android.system.Os
import android.system.OsConstants
import com.droiddeck.launcher.wayland.WaylandCompositor
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.annotation.LooperMode
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], shadows = [SessionTextInputTest.ShadowLocalSocket::class, SessionTextInputTest.ShadowWaylandCompositor::class])
@LooperMode(LooperMode.Mode.PAUSED)
class SessionTextInputTest {
@Before
fun setUp() {
ShadowLocalSocket.reset()
ShadowWaylandCompositor.reset()
shadowOf(Looper.getMainLooper()).idle()
}
@After
fun tearDown() {
shadowOf(Looper.getMainLooper()).idle()
}
@Test
fun retriesUntilGuestProvesReadyThenCompletes() {
val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true }
try {
input.start()
assertTrue(ShadowWaylandCompositor.submit(73))
shadowOf(Looper.getMainLooper()).idle()
val negative = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)
assertEquals(73 to WaylandCompositor.TEXT_UNRESOLVED, negative)
val firstAttempt = ShadowLocalSocket.attemptsQueue.poll(5, TimeUnit.SECONDS)
assertEquals(1, firstAttempt)
val retryAttempt = ShadowLocalSocket.attemptsQueue.poll(5, TimeUnit.SECONDS)
assertEquals(2, retryAttempt)
ShadowLocalSocket.proofAvailable.set(true)
shadowOf(Looper.getMainLooper()).idle()
val completion = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)
assertEquals(73 to WaylandCompositor.TEXT_NOT_DELIVERED, completion)
assertEquals(1, ShadowLocalSocket.frameCount.get())
assertNull(ShadowWaylandCompositor.completions.poll())
} finally {
input.stop()
}
}
@Test
fun stopCancelsPendingRetryAndNewGenerationCanSucceed() {
val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true }
try {
input.start()
assertTrue(ShadowWaylandCompositor.submit(74))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(1, ShadowLocalSocket.attemptsQueue.poll(5, TimeUnit.SECONDS))
val negative = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)
assertEquals(74 to WaylandCompositor.TEXT_UNRESOLVED, negative)
input.stop()
shadowOf(Looper.getMainLooper()).idle()
val extra = ShadowLocalSocket.attemptsQueue.poll(600, TimeUnit.MILLISECONDS)
assertNull(extra)
ShadowLocalSocket.proofAvailable.set(true)
input.start()
shadowOf(Looper.getMainLooper()).idle()
val completion = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)
assertEquals(74 to WaylandCompositor.TEXT_NOT_DELIVERED, completion)
assertEquals(1, ShadowLocalSocket.frameCount.get())
} finally {
input.stop()
}
}
@Test
fun replacementActivityRecoversPendingTokenAndKeepsItsListener() {
val app = RuntimeEnvironment.getApplication()
val first = SessionTextInput(app) { true }
val replacement = SessionTextInput(app) { true }
try {
first.start()
assertTrue(ShadowWaylandCompositor.submit(80))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(80 to WaylandCompositor.TEXT_UNRESOLVED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS))
first.stop()
replacement.start()
first.stop()
ShadowLocalSocket.proofAvailable.set(true)
assertEquals(80 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS))
assertEquals(1, ShadowLocalSocket.frameCount.get())
ShadowLocalSocket.frameAck.set(1)
assertTrue(ShadowWaylandCompositor.submit(81))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(81 to WaylandCompositor.TEXT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS))
assertEquals(2, ShadowLocalSocket.frameCount.get())
} finally {
replacement.stop()
first.stop()
}
}
@Test
fun guestRefusalCompletesWithoutProbeAndNextCommitIsDelivered() {
val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true }
try {
input.start()
ShadowLocalSocket.frameAck.set(0)
assertTrue(ShadowWaylandCompositor.submit(75))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(75 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS))
assertNull(ShadowLocalSocket.attemptsQueue.poll())
ShadowLocalSocket.frameAck.set(1)
assertTrue(ShadowWaylandCompositor.submit(76))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(76 to WaylandCompositor.TEXT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS))
assertNull(ShadowLocalSocket.attemptsQueue.poll())
} finally {
input.stop()
}
}
@Test
fun successfulProbeDoesNotConvertMissingCommitAckToDelivered() {
val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true }
try {
input.start()
ShadowLocalSocket.proofAvailable.set(true)
assertTrue(ShadowWaylandCompositor.submit(77))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(77 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS))
assertEquals(1, ShadowLocalSocket.attemptsQueue.poll())
assertNull(ShadowWaylandCompositor.completions.poll())
} finally {
input.stop()
}
}
@Test
fun nativeReadTimeoutCancelsThenHonorsDeliveredAck() {
val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true }
try {
input.start()
ShadowLocalSocket.frameReadError = IOException(Os.strerror(OsConstants.EAGAIN))
ShadowLocalSocket.frameAck.set(1)
assertTrue(ShadowWaylandCompositor.submit(82))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(82 to WaylandCompositor.TEXT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS))
assertEquals(1, ShadowLocalSocket.shutdowns.get())
assertNull(ShadowLocalSocket.attemptsQueue.poll())
} finally {
input.stop()
}
}
@Test
fun brokenSocketUsesRecoveryAfterFinalAckReadAlsoFails() {
val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true }
try {
input.start()
ShadowLocalSocket.frameReadError = IOException("Connection reset by peer")
ShadowLocalSocket.finalFrameReadError = IOException("Socket closed")
ShadowLocalSocket.proofAvailable.set(true)
assertTrue(ShadowWaylandCompositor.submit(83))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(83 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS))
assertEquals(1, ShadowLocalSocket.shutdowns.get())
assertEquals(1, ShadowLocalSocket.attemptsQueue.poll())
} finally {
input.stop()
}
}
@Implements(LocalSocket::class)
class ShadowLocalSocket {
private val written = ByteArrayOutputStream()
private var connected = false
@Implementation
fun connect(address: LocalSocketAddress) { connected = true }
@Implementation
fun setSoTimeout(timeout: Int) {
if (!connected) throw IOException("socket not created")
}
@Implementation
fun getOutputStream(): OutputStream = object : OutputStream() {
override fun write(b: Int) { written.write(b) }
override fun write(b: ByteArray, off: Int, len: Int) { written.write(b, off, len) }
}
@Implementation
fun getInputStream(): InputStream {
val bytes = written.toByteArray()
val isProbe = bytes.size == 4 && bytes.all { it == 0.toByte() }
return if (isProbe) {
probeCount.incrementAndGet()
val allowProof = proofAvailable.get()
attemptsQueue.offer(probeCount.get())
ByteArrayInputStream(byteArrayOf(if (allowProof) 0 else 42))
} else {
frameCount.incrementAndGet()
object : InputStream() {
private var attempts = 0
override fun read(): Int {
val error = if (attempts++ == 0) frameReadError else finalFrameReadError
if (error != null) throw error
return frameAck.get()
}
}
}
}
@Implementation
fun close() {}
@Implementation
fun shutdownOutput() { shutdowns.incrementAndGet() }
companion object {
private val probeCount = AtomicInteger(0)
val attemptsQueue = LinkedBlockingQueue<Int>()
val frameCount = AtomicInteger(0)
val frameAck = AtomicInteger(42)
val shutdowns = AtomicInteger(0)
@Volatile var frameReadError: IOException? = null
@Volatile var finalFrameReadError: IOException? = null
val proofAvailable = java.util.concurrent.atomic.AtomicBoolean(false)
fun reset() {
probeCount.set(0)
attemptsQueue.clear()
frameCount.set(0)
frameAck.set(42)
shutdowns.set(0)
frameReadError = null
finalFrameReadError = null
proofAvailable.set(false)
}
}
}
@Implements(WaylandCompositor::class, isInAndroidSdk = false)
class ShadowWaylandCompositor {
companion object {
val completions = LinkedBlockingQueue<Pair<Int, Int>>()
@Volatile private var listener: WaylandCompositor.TextInputFallbackListener? = null
fun reset() {
completions.clear()
listener = null
}
fun submit(token: Int): Boolean = listener!!.onTextInputFallback("abc", token)
@Implementation
@JvmStatic
fun __staticInitializer__() {}
@Implementation
@JvmStatic
fun completeTextInputFallback(token: Int, result: Int) {
completions.offer(token to result)
}
@Implementation
@JvmStatic
fun setTextInputFallbackListener(l: WaylandCompositor.TextInputFallbackListener?) {
listener = l
}
@Implementation
@JvmStatic
fun isTextInputFallbackListener(l: WaylandCompositor.TextInputFallbackListener?): Boolean =
listener != null && listener === l
@Implementation
@JvmStatic
fun clearTextInputFallbackListener(l: WaylandCompositor.TextInputFallbackListener?) {
if (listener === l) listener = null
}
}
}
}
@@ -35,6 +35,37 @@ class LegacyNamesTest {
assertEquals("droiddeck", link("etc/bannerlator"))
}
@Test fun theEmptyStandInIsEmptiedAndThermalZonesGetTheirOwn() {
write("etc/droiddeck/empty/thermal_zone26/temp", "")
LegacyNames.migrateEtc(root)
assertEquals(emptyList<String>(), File(root, "etc/droiddeck/empty").list()!!.toList())
assertTrue(File(root, LegacyNames.NO_THERMAL).isDirectory)
}
@Test fun clearingTheEmptyStandInRemovesLinksWithoutTouchingWhatTheyPointAt() {
write("home/keep/file", "kept")
val links = File(root, "etc/droiddeck/empty").apply { mkdirs() }
val made = runCatching {
Files.createSymbolicLink(File(links, "dir").toPath(), File(root, "home/keep").toPath())
Files.createSymbolicLink(File(links, "dangling").toPath(), File(root, "missing").toPath())
}.isSuccess
org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made)
LegacyNames.migrateEtc(root)
assertEquals(emptyList<String>(), links.list()!!.toList())
assertEquals("kept", File(root, "home/keep/file").readText())
}
@Test fun aLinkInPlaceOfTheEmptyStandInIsReplacedWithoutTouchingItsTarget() {
write("home/keep/file", "kept")
val empty = File(root, "etc/droiddeck/empty").also { it.parentFile!!.mkdirs() }
val made = runCatching { Files.createSymbolicLink(empty.toPath(), File(root, "home/keep").toPath()) }.isSuccess
org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made)
LegacyNames.migrateEtc(root)
assertFalse(Files.isSymbolicLink(empty.toPath()))
assertEquals(emptyList<String>(), empty.list()!!.toList())
assertEquals("kept", File(root, "home/keep/file").readText())
}
@Test fun aFreshRuntimeGetsNoOldNames() {
write("usr/local/bin/droiddeck-session", "new")
LegacyNames.migrateRootfs(root)
@@ -0,0 +1,94 @@
package com.droiddeck.launcher.session
import android.os.Handler
import android.os.Looper
import android.os.Messenger
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.wayland.BottomDesktopCompositorService
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = android.app.Application::class)
class BottomDesktopInputTest {
private data class Sent(val what: Int, val arg1: Int, val arg2: Int, val text: String?)
private val sent = ArrayList<Sent>()
private val key = BottomDesktopCompositorService.MSG_KEY
private val text = BottomDesktopCompositorService.MSG_TEXT
private val textKey = BottomDesktopCompositorService.KEY_TEXT
private lateinit var desktop: BottomDesktop
private var original: Messenger? = null
@Before
fun setUp() {
desktop = BottomDesktop
original = ReflectionHelpers.getField<Messenger>(desktop, "service")
sent.clear()
val recorder = Handler(Looper.getMainLooper(), Handler.Callback { msg ->
sent.add(Sent(msg.what, msg.arg1, msg.arg2, msg.data?.getString(textKey)))
true
})
ReflectionHelpers.setField(desktop, "service", Messenger(recorder))
}
@After
fun tearDown() {
shadowOf(Looper.getMainLooper()).idle()
ReflectionHelpers.setField(desktop, "service", original)
}
@Test
fun pureControlBatchSendsOneDownAndOneUpPerChar() {
BottomDesktop.sendText("\r\n\b\u007f\t")
shadowOf(Looper.getMainLooper()).idle()
assertEquals(
press(28) + press(28) + press(14) + press(111) + press(15),
sent
)
assertTrue(sent.none { it.what == text })
}
@Test
fun ordinaryTextIncludingSupplementaryAndNewlineIsOneTextMessage() {
val value = "中文😀\nline"
BottomDesktop.sendText(value)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(Sent(text, 0, 0, value)), sent)
}
@Test
fun keyboardHostOrderMatchesImeEditingSequence() {
val host = KeyboardHost(RuntimeEnvironment.getApplication(), { true }, { BottomDesktop.sendText(it) })
ReflectionHelpers.setField(host, "shown", true)
val connection = host.onCreateInputConnection(EditorInfo())!!
connection.commitText("中文", 1)
connection.performEditorAction(EditorInfo.IME_ACTION_NONE)
connection.deleteSurroundingText(1, 0)
connection.deleteSurroundingText(0, 1)
assertTrue(connection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB)))
assertTrue(connection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_TAB)))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(
listOf(Sent(text, 0, 0, "中文")) + press(28) + press(14) + press(111) + press(15),
sent
)
assertEquals(1, sent.count { it.what == key && it.arg1 == 15 && it.arg2 == 1 })
assertEquals(1, sent.count { it.what == key && it.arg1 == 15 && it.arg2 == 0 })
}
private fun press(evdev: Int) = listOf(Sent(key, evdev, 1, null), Sent(key, evdev, 0, null))
}
@@ -0,0 +1,36 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SessionPrefsZeroCopyTest {
private val app get() = RuntimeEnvironment.getApplication()
@Test fun standaloneGamesUseTheSteamPresentationSetting() {
SessionPrefs.setZeroCopy(app, SessionService.MODE_STEAM, false)
assertFalse(SessionPrefs.zeroCopy(app, SessionService.MODE_RUN))
assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_DESKTOP))
SessionPrefs.setZeroCopy(app, SessionService.MODE_RUN, true)
assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_STEAM))
assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_RUN))
}
@Test fun aRawRunKeyCannotDisagreeWithTheSteamSetting() {
app.getSharedPreferences("session", Context.MODE_PRIVATE)
.edit().putBoolean("zeroCopy.run", false).commit()
SessionPrefs.setZeroCopy(app, SessionService.MODE_STEAM, true)
assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_RUN))
}
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.session.xr
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class XrGestureTest {
private fun hand(x: Float, active: Boolean = true) =
XrHand(Pose(), Pose(Quat.IDENTITY, Vec3(x, 1.2f, -0.3f)), 0f, 0f, 0f, 0f, 0, active)
@Test
fun holdingTheControllersTogetherFiresAfterTheHold() {
val gesture = XrGesture()
assertFalse(gesture.update(hand(-0.03f), hand(0.03f), 0))
assertEquals(XrGesture.Phase.ARMING, gesture.phase)
assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS / 2))
assertEquals(0.5f, gesture.progress, 0.01f)
assertEquals(0f, gesture.midpoint.x, 1e-6f)
assertTrue(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS))
}
@Test
fun pullingApartCancels() {
val gesture = XrGesture()
gesture.update(hand(-0.03f), hand(0.03f), 0)
gesture.update(hand(-0.06f), hand(0.06f), 500)
assertEquals(XrGesture.Phase.ARMING, gesture.phase)
gesture.update(hand(-0.08f), hand(0.08f), 600)
assertEquals(XrGesture.Phase.IDLE, gesture.phase)
assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS + 600))
assertEquals(0f, gesture.progress, 0f)
}
@Test
fun itDoesNotFireAgainUntilTheControllersPart() {
val gesture = XrGesture()
gesture.update(hand(-0.03f), hand(0.03f), 0)
assertTrue(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS))
for (t in 1..5) assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS * (t + 1)))
gesture.update(hand(-0.2f), hand(0.2f), 20_000)
gesture.update(hand(-0.03f), hand(0.03f), 21_000)
assertTrue(gesture.update(hand(-0.03f), hand(0.03f), 21_000 + XrGesture.HOLD_MS))
}
@Test
fun aLostControllerStopsIt() {
val gesture = XrGesture()
gesture.update(hand(-0.03f), hand(0.03f), 0)
assertFalse(gesture.update(hand(-0.03f), hand(0.03f, active = false), XrGesture.HOLD_MS))
assertEquals(XrGesture.Phase.IDLE, gesture.phase)
}
}
@@ -0,0 +1,84 @@
package com.droiddeck.launcher.session.xr
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
class XrHostTest {
private fun buffer(size: Int) = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder())
@Test
fun readsHandsAtTheNativeOffsets() {
val state = buffer(XrHostLayout.STATE_SIZE)
state.putInt(8, XrHostLayout.FLAG_FOCUSED or XrHostLayout.FLAG_SURFACE_SWAPCHAIN)
state.putLong(16, 42L)
XrHost.writePose(state, XrHostLayout.STATE_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f)))
val right = XrHostLayout.STATE_HANDS + XrHostLayout.HAND_SIZE
XrHost.writePose(state, right + XrHostLayout.HAND_AIM, Pose(Quat.IDENTITY, Vec3(0.2f, 1.2f, -0.3f)))
state.putFloat(right + XrHostLayout.HAND_TRIGGER, 0.75f)
state.putFloat(right + XrHostLayout.HAND_STICK + 4, -0.5f)
state.putInt(right + XrHostLayout.HAND_BUTTONS, XrHostLayout.SECONDARY_CLICK)
state.putInt(right + XrHostLayout.HAND_ACTIVE, 1)
val frame = XrHost(state, buffer(XrHostLayout.CONTROL_SIZE)).read()
assertTrue(frame.focused)
assertTrue(frame.surfaces)
assertEquals(42L, frame.frame)
assertEquals(1.6f, frame.head.position.y, 0f)
assertFalse(frame.hands[0].active)
val hand = frame.hands[1]
assertTrue(hand.active)
assertTrue(hand.secondary)
assertEquals(0.75f, hand.trigger, 0f)
assertEquals(-0.5f, hand.stickY, 0f)
assertEquals(Vec3(0.2f, 1.2f, -0.3f), hand.aim.position)
}
@Test
fun writesControlAtTheNativeOffsets() {
val control = buffer(XrHostLayout.CONTROL_SIZE)
val host = XrHost(buffer(XrHostLayout.STATE_SIZE), control)
val out = XrControlOut().apply {
masks[1] = true
lasers[1] = 0.8f
haptics[0] = XrHaptic(20, 0.5f)
orb = XrControlOut.Orb(Vec3(0f, 1f, -0.5f), 0.04f, 0.25f, 0f)
layers += XrLayerOut(3, Pose(Quat.IDENTITY, Vec3(0f, 1.5f, -1f)), 0.9f, 0.6f, order = 2)
}
host.write(out)
assertEquals(XrHostLayout.VERSION, control.getInt(0))
val right = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_SIZE
assertEquals(XrHostLayout.MASK_INPUT, control.getInt(right))
assertEquals(0.8f, control.getFloat(right + XrHostLayout.HAND_CONTROL_LASER), 0f)
assertEquals(0, control.getInt(XrHostLayout.CONTROL_HANDS))
val haptic = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_HAPTIC
assertEquals(1L, control.getLong(haptic))
assertEquals(20_000_000L, control.getLong(haptic + 8))
assertEquals(1, control.getInt(XrHostLayout.CONTROL_ORB))
assertEquals(0.25f, control.getFloat(XrHostLayout.CONTROL_ORB + 4), 0f)
val layer = XrHostLayout.CONTROL_LAYERS
assertEquals(3, control.getInt(layer))
assertEquals(1, control.getInt(layer + 4))
assertEquals(2, control.getInt(layer + 12))
assertEquals(-1f, control.getFloat(layer + 16 + 24), 0f)
assertEquals(0.9f, control.getFloat(layer + 48), 0f)
assertEquals(-1, control.getInt(layer + XrHostLayout.LAYER_SIZE))
}
@Test
fun aHapticIsSentOnceAndTheNextGetsANewId() {
val control = buffer(XrHostLayout.CONTROL_SIZE)
val host = XrHost(buffer(XrHostLayout.STATE_SIZE), control)
val haptic = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_HAPTIC
host.write(XrControlOut().apply { haptics[0] = XrHaptic(10, 0.3f) })
host.write(XrControlOut())
assertEquals(1L, control.getLong(haptic))
host.write(XrControlOut().apply { haptics[0] = XrHaptic(10, 0.3f) })
assertEquals(2L, control.getLong(haptic))
}
}
@@ -0,0 +1,246 @@
package com.droiddeck.launcher.session.xr
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class XrInteractionTest {
private val head = Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f))
/** A panel 1 m ahead facing the user, 1 m wide and 0.6 m high. */
private fun panel(kind: XrPanelKind = XrPanelKind.MENU, z: Float = -1f) =
XrPanelState(kind, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, z)), 1f, 0.6f)
/** A controller at the head's height pointing straight ahead at ([x], [y]) on the panel's plane. */
private fun aim(x: Float = 0f, y: Float = 0f, trigger: Float = 0f, squeeze: Float = 0f, stickY: Float = 0f,
buttons: Int = 0, active: Boolean = true) =
XrHand(Pose(), Pose(Quat.IDENTITY, Vec3(x, 1.6f + y, 0f)), trigger, squeeze, 0f, stickY, buttons, active)
private val idle = XrHand.IDLE
@Test
fun aRayHitsThePanelInItsPixels() {
val panel = panel()
val hit = panel.hit(aim(0.25f, 0.15f).aim)
assertNotNull(hit)
assertEquals(1f, hit!!.distance, 1e-4f)
assertEquals(panel.pixelWidth * 0.75f, panel.pixelX(hit.x), 0.5f)
assertEquals(panel.pixelHeight * 0.25f, panel.pixelY(hit.y), 0.5f)
assertNull(panel.hit(aim(0.7f).aim))
}
@Test
fun aPanelBehindTheControllerOrSeenFromBehindIsMissed() {
assertNull(panel(z = 1f).hit(aim().aim))
val turned = XrPanelState(XrPanelKind.MENU, Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, -1f)), 1f, 0.6f)
assertNull(turned.hit(aim().aim))
}
@Test
fun theNearestPanelTakesTheRay() {
val far = panel(z = -2f)
val near = panel(z = -1f)
val out = XrInteraction().update(head, listOf(aim(trigger = 0f), idle), listOf(far, near), 0.014f)
assertTrue(out.cursors.containsKey(near))
assertFalse(out.cursors.containsKey(far))
}
@Test
fun onlyTheControllerPointingAtAPanelIsTakenFromTheGame() {
val panel = panel()
val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true)
val out = XrInteraction().update(head, listOf(away, aim()), listOf(panel), 0.014f)
assertFalse(out.masks[0])
assertEquals(0f, out.lasers[0], 0f)
assertTrue(out.masks[1])
assertEquals(1f, out.lasers[1], 1e-4f)
}
@Test
fun theTriggerPressesMovesAndReleases() {
val panel = panel()
val interaction = XrInteraction()
val down = interaction.update(head, listOf(aim(0f, 0f, trigger = 0.9f), idle), listOf(panel), 0.014f)
assertTrue(down.events.single() is XrPointerEvent.Down)
val moved = interaction.update(head, listOf(aim(0.1f, 0f, trigger = 0.5f), idle), listOf(panel), 0.014f)
assertTrue(moved.events.single() is XrPointerEvent.Move)
assertTrue(moved.masks[0])
val up = interaction.update(head, listOf(aim(0.1f, 0f, trigger = 0.1f), idle), listOf(panel), 0.014f)
val release = up.events.single() as XrPointerEvent.Up
assertEquals(panel.pixelWidth * 0.6f, release.x, 0.5f)
}
@Test
fun aHeldPressFollowsTheRayOffThePanelAndAlostControllerCancels() {
val panel = panel()
val interaction = XrInteraction()
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
val off = interaction.update(head, listOf(aim(0.9f, trigger = 0.9f), idle), listOf(panel), 0.014f)
assertTrue((off.events.single() as XrPointerEvent.Move).x >= panel.pixelWidth - 0.5f)
assertTrue(off.masks[0])
val lost = interaction.update(head, listOf(aim(active = false), idle), listOf(panel), 0.014f)
assertTrue(lost.events.single() is XrPointerEvent.Cancel)
}
@Test
fun theStickScrollsAndBGoesBack() {
val panel = panel()
val interaction = XrInteraction()
val scroll = interaction.update(head, listOf(aim(stickY = 1f), idle), listOf(panel), 0.1f)
assertTrue((scroll.events.single() as XrPointerEvent.Scroll).amount > 0f)
val back = interaction.update(head, listOf(aim(buttons = XrHostLayout.SECONDARY_CLICK), idle), listOf(panel), 0.014f)
assertTrue(back.events.single() is XrPointerEvent.Back)
val held = interaction.update(head, listOf(aim(buttons = XrHostLayout.SECONDARY_CLICK), idle), listOf(panel), 0.014f)
assertTrue(held.events.isEmpty())
}
@Test
fun gripCarriesThePanelAndTheStickPushesItAway() {
val panel = panel()
val interaction = XrInteraction()
interaction.update(head, listOf(aim(squeeze = 0.9f), idle), listOf(panel), 0.014f)
interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f), idle), listOf(panel), 0.014f)
assertEquals(0.3f, panel.pose.position.x, 1e-4f)
assertEquals(1.7f, panel.pose.position.y, 1e-4f)
val before = panel.pose.position.z
repeat(10) { interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f, stickY = 1f), idle), listOf(panel), 0.1f) }
assertTrue(panel.pose.position.z < before)
repeat(200) { interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f, stickY = 1f), idle), listOf(panel), 0.1f) }
assertTrue((panel.pose.position - Vec3(0.3f, 1.7f, 0f)).length <= XrUnits.MAX_DISTANCE + 1e-3f)
val dropped = interaction.update(head, listOf(aim(0.3f, 0.1f), idle), listOf(panel), 0.014f)
assertTrue(dropped.events.single() is XrPointerEvent.Moved)
val facingHead = panel.pose.orientation.rotate(Vec3(0f, 0f, 1f))
val toHead = (head.position - panel.pose.position).let { Vec3(it.x, 0f, it.z).normalized() }
assertEquals(1f, facingHead dot toHead, 1e-3f)
}
@Test
fun theBottomBarCarriesThePanelButItsButtonIsClicked() {
val panel = panel()
val interaction = XrInteraction()
val barY = -0.3f + XrUnits.BAR_METRES / 2f
val bar = interaction.update(head, listOf(aim(0.1f, barY, trigger = 0.9f), idle), listOf(panel), 0.014f)
assertTrue(bar.events.isEmpty())
interaction.update(head, listOf(aim(0.2f, barY, trigger = 0.9f), idle), listOf(panel), 0.014f)
assertEquals(0.1f, panel.pose.position.x, 1e-4f)
interaction.update(head, listOf(aim(0.2f, barY), idle), listOf(panel), 0.014f)
val chat = panel(XrPanelKind.PET_CHAT)
val button = XrInteraction().update(head, listOf(aim(-0.48f, barY, trigger = 0.9f), idle), listOf(chat), 0.014f)
assertTrue(button.events.single() is XrPointerEvent.Down)
val menu = panel()
val noButton = XrInteraction().update(head, listOf(aim(-0.48f, barY, trigger = 0.9f), idle), listOf(menu), 0.014f)
assertTrue(noButton.events.isEmpty())
}
@Test
fun theCornerResizesWithTheTopLeftCornerFixed() {
val panel = panel()
val interaction = XrInteraction()
interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), idle), listOf(panel), 0.014f)
assertEquals(1f, panel.width, 1e-4f)
assertEquals(0.6f, panel.height, 1e-4f)
interaction.update(head, listOf(aim(0.78f, -0.48f, trigger = 0.9f), idle), listOf(panel), 0.014f)
assertEquals(1.3f, panel.width, 1e-3f)
assertEquals(0.8f, panel.height, 1e-3f)
assertEquals(-0.5f, panel.pose.position.x - panel.width / 2f, 1e-3f)
assertEquals(1.9f, panel.pose.position.y + panel.height / 2f, 1e-3f)
interaction.update(head, listOf(aim(-2f, 2f, trigger = 0.9f), idle), listOf(panel), 0.014f)
assertEquals(XrUnits.MIN_METRES, panel.width, 1e-4f)
assertEquals(XrUnits.MIN_METRES, panel.height, 1e-4f)
val done = interaction.update(head, listOf(aim(-2f, 2f), idle), listOf(panel), 0.014f)
assertTrue(done.events.single() is XrPointerEvent.Resized)
}
@Test
fun thePetHeadClicksOrIsDragged() {
val head0 = XrPanelState(XrPanelKind.PET_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, -1f)), 0.12f, 0.12f)
val interaction = XrInteraction()
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(head0), 0.014f)
val click = interaction.update(head, listOf(aim(), idle), listOf(head0), 0.014f)
assertTrue(click.events.single() is XrPointerEvent.Click)
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(head0), 0.014f)
interaction.update(head, listOf(aim(0.05f, trigger = 0.9f), idle), listOf(head0), 0.014f)
interaction.update(head, listOf(aim(0.2f, trigger = 0.9f), idle), listOf(head0), 0.014f)
assertEquals(0.2f, head0.pose.position.x, 1e-3f)
val dropped = interaction.update(head, listOf(aim(0.2f), idle), listOf(head0), 0.014f)
assertTrue(dropped.events.single() is XrPointerEvent.Moved)
}
@Test
fun aClosingPanelLetsGo() {
val panel = panel()
val interaction = XrInteraction()
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
val out = XrInteractionOut()
interaction.release(panel, out)
assertTrue(out.events.single() is XrPointerEvent.Cancel)
assertFalse(interaction.holding(panel))
}
@Test
fun aReleaseAimedAwayFromThePanelCancels() {
val panel = panel()
val interaction = XrInteraction()
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true)
val out = interaction.update(head, listOf(away, idle), listOf(panel), 0.014f)
assertTrue(out.events.single() is XrPointerEvent.Cancel)
}
@Test
fun aPanelOneControllerHoldsCannotBeTakenByTheOther() {
val panel = panel()
val interaction = XrInteraction()
interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), idle), listOf(panel), 0.014f)
interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), aim(squeeze = 0.9f)), listOf(panel), 0.014f)
val out = interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), aim(0.3f, squeeze = 0.9f)), listOf(panel), 0.014f)
assertEquals(0f, panel.pose.position.x, 1e-3f)
assertTrue(out.events.isEmpty())
}
@Test
fun losingFocusCancelsAndAButtonStillHeldNeedsANewPress() {
val panel = panel()
val interaction = XrInteraction()
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
val out = XrInteractionOut()
interaction.cancel(out)
assertTrue(out.events.single() is XrPointerEvent.Cancel)
assertFalse(interaction.holding(panel))
val stillHeld = interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
assertTrue(stillHeld.events.isEmpty())
interaction.update(head, listOf(aim(), idle), listOf(panel), 0.014f)
val pressed = interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
assertTrue(pressed.events.single() is XrPointerEvent.Down)
}
@Test
fun bothControllersPressOnePanelAtOnce() {
val panel = panel()
val interaction = XrInteraction()
val first = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f)), listOf(panel), 0.014f)
assertEquals(2, first.cursors.getValue(panel).size)
assertEquals(0, (first.events.single() as XrPointerEvent.Down).hand)
val second = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f, trigger = 0.9f)), listOf(panel), 0.014f)
assertEquals(1, (second.events.single() as XrPointerEvent.Down).hand)
val up = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f)), listOf(panel), 0.014f)
assertEquals(1, (up.events.single() as XrPointerEvent.Up).hand)
}
@Test
fun lettingGoOfThePetHeadOffItIsNoClick() {
val pet = XrPanelState(XrPanelKind.PET_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, -1f)), 0.12f, 0.12f)
val interaction = XrInteraction()
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(pet), 0.014f)
val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true)
val out = interaction.update(head, listOf(away, idle), listOf(pet), 0.014f)
assertTrue(out.events.isEmpty())
assertFalse(interaction.holding(pet))
}
}
@@ -0,0 +1,113 @@
package com.droiddeck.launcher.session.xr
import android.content.Context
import android.view.Surface
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowBuild
import java.nio.ByteBuffer
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE)
class XrPanelsGateTest {
private val layers = object : XrLayerSource {
override val context: Context get() = RuntimeEnvironment.getApplication()
override fun createLayer(width: Int, height: Int) = -1
override fun layerSurface(id: Int): Surface? = null
override fun destroyLayer(id: Int) = Unit
override fun setOrbImage(image: android.graphics.Bitmap) = Unit
override fun leave() = Unit
}
private fun attach() = XrPanels.attach(
layers, ByteBuffer.allocateDirect(XrHostLayout.STATE_SIZE), ByteBuffer.allocateDirect(XrHostLayout.CONTROL_SIZE),
)
@After
fun detach() = XrPanels.detach()
@Test
fun onlyAQuestInTheImmersiveViewOpensTheGate() {
assertTrue(XrPanels.gateOpen("Quest 3", "eureka", "Oculus", immersive = true))
assertTrue(XrPanels.gateOpen("Quest 3S", "panther", "Oculus", immersive = true))
assertFalse(XrPanels.gateOpen("Quest 3", "eureka", "Oculus", immersive = false))
assertFalse(XrPanels.gateOpen("BKQ_N49", "BKQ", "HONOR", immersive = true))
assertFalse(XrPanels.gateOpen("Pixel 9", "tokay", "Google", immersive = true))
assertFalse(XrPanels.gateOpen("Rift", "rift", "Oculus", immersive = true))
}
@Test
fun offQuestTheMenuStaysInTheSessionWindow() {
ShadowBuild.setModel("BKQ_N49")
ShadowBuild.setDevice("BKQ")
ShadowBuild.setManufacturer("HONOR")
attach()
assertFalse(XrPanels.immersiveActive)
assertFalse(XrPanels.showMenu())
}
@Test
fun onQuestTheImmersiveViewTakesTheMenu() {
ShadowBuild.setModel("Quest 3")
ShadowBuild.setDevice("eureka")
ShadowBuild.setManufacturer("Oculus")
assertFalse(XrPanels.showMenu())
attach()
assertTrue(XrPanels.immersiveActive)
assertTrue(XrPanels.showMenu())
XrPanels.detach()
assertFalse(XrPanels.immersiveActive)
assertFalse(XrPanels.showMenu())
}
private class Host : XrMenuHost {
val immersive = mutableListOf<Boolean>()
@androidx.compose.runtime.Composable
override fun XrMenuContent() = Unit
override fun xrSetMenuOpen(open: Boolean) = Unit
override fun xrMenuBack() = Unit
override fun xrSendKey(code: Int, down: Boolean) = Unit
override fun xrTypeText(text: String) = Unit
override fun xrTapKey(keyCode: Int) = Unit
override fun xrImmersiveChanged(active: Boolean) { immersive += active }
}
@Test
fun aFocusChangeInTheImmersiveViewSizesSteamsScreenAgain() {
ShadowBuild.setModel("Quest 3")
ShadowBuild.setDevice("eureka")
ShadowBuild.setManufacturer("Oculus")
val host = Host()
XrPanels.setMenuHost(host)
try {
attach()
settle()
val opened = host.immersive.size
assertTrue(opened >= 1 && host.immersive.all { it })
com.droiddeck.launcher.agent.AgentGuest.focusRevision++
settle()
assertTrue(host.immersive.size > opened)
assertTrue(host.immersive.all { it })
XrPanels.detach()
val left = host.immersive.size
com.droiddeck.launcher.agent.AgentGuest.focusRevision++
settle()
assertEquals(false, host.immersive.last())
assertEquals(left, host.immersive.size)
} finally {
XrPanels.clearMenuHost(host)
}
}
private fun settle() {
androidx.compose.runtime.snapshots.Snapshot.sendApplyNotifications()
org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()
}
}
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.session.xr
import org.junit.Assert.assertEquals
import org.junit.Test
class XrPcTextTest {
private class Field : XrKeyTarget {
val text = StringBuilder()
var entered = 0
override fun type(text: String) { this.text.append(text) }
override fun backspace() { if (text.isNotEmpty()) text.setLength(text.length - 1) }
override fun enter() { entered++ }
}
private fun XrPcText.tap(code: Int) { key(code, true); key(code, false) }
@Test
fun pcKeysTypeIntoAPanelField() {
val field = Field()
val keys = XrPcText(field)
keys.key(42, true); keys.tap(35); keys.key(42, false)
keys.tap(18); keys.tap(57); keys.key(54, true); keys.tap(2); keys.key(54, false)
assertEquals("He !", field.text.toString())
keys.tap(58); keys.tap(30); keys.tap(58); keys.tap(30)
assertEquals("He !Aa", field.text.toString())
keys.tap(14); keys.tap(28)
assertEquals("He !A", field.text.toString())
assertEquals(1, field.entered)
}
private class FakeTimer : XrTimer {
var pending: (() -> Unit)? = null
override fun after(ms: Long, action: () -> Unit): () -> Unit {
pending = action
return { if (pending === action) pending = null }
}
fun fire() = pending!!.invoke()
}
@Test
fun holdingBackspaceKeepsDeletingUntilItIsLetGo() {
val field = Field().apply { text.append("hello") }
val timer = FakeTimer()
val keys = XrPcText(field, timer)
keys.key(14, true)
assertEquals("hell", field.text.toString())
timer.fire(); timer.fire()
assertEquals("he", field.text.toString())
keys.key(14, false)
assertEquals(null, timer.pending)
assertEquals("he", field.text.toString())
}
@Test
fun anotherKeyLetGoLeavesBackspaceRepeating() {
val field = Field().apply { text.append("hello") }
val timer = FakeTimer()
val keys = XrPcText(field, timer)
keys.key(14, true)
keys.key(30, false)
timer.fire()
assertEquals("hel", field.text.toString())
}
@Test
fun keysWithNoCharacterTypeNothing() {
val field = Field()
val keys = XrPcText(field)
for (code in listOf(1, 59, 29, 56, 103, 105, 15, 111)) keys.tap(code)
assertEquals("", field.text.toString())
}
}
@@ -0,0 +1,67 @@
package com.droiddeck.launcher.session.xr
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
class XrPlacementTest {
@Test
fun aPanelComesBackAtTheSamePlaceRelativeToWhereTheUserFaces() {
val head = Pose(Quat.yaw(0.4f), Vec3(0.5f, 1.6f, 0.2f))
val placed = XrPlacement.place(XrPanelKind.MENU, head, yaw = 0.3f, distance = 1.1f, dy = -0.2f)
val (yaw, distance, dy) = XrPlacement.relative(head, placed.position)
assertEquals(0.3f, yaw, 1e-4f)
assertEquals(1.1f, distance, 1e-4f)
assertEquals(-0.2f, dy, 1e-4f)
val turned = Pose(Quat.yaw(1.4f), Vec3(-1f, 1.5f, 3f))
val again = XrPlacement.place(XrPanelKind.MENU, turned, yaw, distance, dy)
val (yaw2, distance2, dy2) = XrPlacement.relative(turned, again.position)
assertEquals(yaw, yaw2, 1e-4f)
assertEquals(distance, distance2, 1e-4f)
assertEquals(dy, dy2, 1e-4f)
}
@Test
fun aPlacedPanelFacesTheHead() {
val head = Pose(Quat.yaw(-0.8f), Vec3(0f, 1.6f, 0f))
val placed = XrPlacement.place(XrPanelKind.MENU, head, yaw = 0.5f, distance = 0.9f, dy = 0f)
val front = placed.orientation.rotate(Vec3(0f, 0f, 1f))
val toHead = (head.position - placed.position).normalized()
assertEquals(1f, front dot toHead, 1e-4f)
}
@Test
fun straightAheadIsStraightAhead() {
val placed = XrPlacement.place(XrPanelKind.MENU, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f)), 0f, 1f, 0f)
assertEquals(0f, placed.position.x, 1e-5f)
assertEquals(-1f, placed.position.z, 1e-5f)
}
@Test
fun theKeyboardLeansBackLikeOneOnADeskAndStillTakesTheLaser() {
val head = Pose(Quat.yaw(0.6f), Vec3(0f, 1.6f, 0f))
val placed = XrPlacement.place(XrPanelKind.KEYBOARD, head, yaw = 0f, distance = 0.5f, dy = -0.5f)
val front = placed.orientation.rotate(Vec3(0f, 0f, 1f))
val level = (head.position - placed.position).let { Vec3(it.x, 0f, it.z).normalized() }
assertEquals(0.7071f, front.y, 1e-3f)
assertEquals(0.7071f, front dot level, 1e-3f)
val keyboard = XrPanelState(XrPanelKind.KEYBOARD, placed, 0.8f, 0.36f)
val hand = placed.position + Vec3(0f, 0.25f, 0f) + level * 0.15f
val down = (placed.position - hand).normalized()
val aim = Pose(rotationFromForward(down), hand)
val hit = keyboard.hit(aim)
assertNotNull(hit)
assertEquals(0f, hit!!.x, 1e-3f)
assertEquals(0f, hit.y, 1e-3f)
}
private fun rotationFromForward(direction: Vec3): Quat {
val axis = Vec3.FORWARD cross direction
val angle = kotlin.math.acos((Vec3.FORWARD dot direction).coerceIn(-1f, 1f))
val unit = axis.normalized()
val s = kotlin.math.sin(angle / 2f)
return Quat(unit.x * s, unit.y * s, unit.z * s, kotlin.math.cos(angle / 2f))
}
}
@@ -0,0 +1,23 @@
package com.droiddeck.launcher.session.xr
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class XrSteamScreenTest {
@Test fun steamAndSteamVrAloneAreSteamsScreen() {
assertTrue(XrSteamScreen.shown(250820L, listOf(769L, 250820L)))
assertTrue(XrSteamScreen.shown(0L, listOf(769L)))
}
@Test fun aRunningGameKeepsItFlatEvenWithSteamVrFocused() {
assertFalse(XrSteamScreen.shown(250820L, listOf(769L, 250820L, 1245620L)))
assertFalse(XrSteamScreen.shown(1245620L, null))
}
@Test fun aReportWithNoFocusIsUnknown() {
assertFalse(XrSteamScreen.shown(null, null))
assertFalse(XrSteamScreen.shown(null, emptyList()))
assertFalse(XrSteamScreen.shown(0L, emptyList()))
}
}
@@ -0,0 +1,24 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE)
class AgentPetQuestTest {
@Test
fun phonesKeepTheFloatingPetAndItsChat() {
assertTrue(AgentPet.usesOverlayWindows(quest = false))
assertFalse(AgentPet.chatInOwnWindow(quest = false))
}
@Test
fun questUsesNoOverlayWindowsAndOpensTheChatAsItsOwnPanel() {
assertFalse(AgentPet.usesOverlayWindows(quest = true))
assertTrue(AgentPet.chatInOwnWindow(quest = true))
}
}
@@ -0,0 +1,177 @@
package com.droiddeck.launcher.ui
import androidx.activity.ComponentActivity
import android.hardware.display.DisplayManager
import android.os.Looper
import android.view.Display
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.wayland.WaylandCompositor
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.android.controller.ActivityController
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w800dp-h600dp", shadows = [SecondScreenImeTest.CompositorShadow::class])
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class SecondScreenImeTest {
private var previousMode = ""
private var previousDeckPad = false
@Before fun setUp() {
previousMode = SessionState.mode
previousDeckPad = SessionState.deckPad
SessionState.deckPad = false
CompositorShadow.commits.clear()
}
@After fun tearDown() {
SessionState.mode = previousMode
SessionState.deckPad = previousDeckPad
}
@Test fun editorActionClosesFieldKeyboardAfterOneCommit() {
var closes = 0
val fixture = keyboard(forField = true) { closes++ }
try {
assertTrue(fixture.connection.performEditorAction(EditorInfo.IME_ACTION_SEND))
idle()
assertEquals(listOf("\r"), CompositorShadow.commits)
assertEquals(1, closes)
assertFalse(fixture.host.shown)
assertFalse(fixture.panel.fieldKeyboardOpen)
} finally {
fixture.close()
}
}
@Test fun unmodifiedEnterKeyClosesFieldKeyboard() {
var closes = 0
val fixture = keyboard(forField = true) { closes++ }
try {
assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN)))
assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP)))
idle()
assertEquals(listOf("\r"), CompositorShadow.commits)
assertEquals(1, closes)
assertFalse(fixture.host.shown)
assertFalse(fixture.panel.fieldKeyboardOpen)
} finally {
fixture.close()
}
}
@Test fun ordinaryTextAndNewlineLeaveFieldKeyboardOpen() {
var closes = 0
val fixture = keyboard(forField = true) { closes++ }
try {
assertTrue(fixture.connection.commitText("hello", 1))
assertTrue(fixture.connection.commitText("line\n", 1))
idle()
assertEquals(listOf("hello", "line\n"), CompositorShadow.commits)
assertEquals(0, closes)
assertTrue(fixture.host.shown)
assertTrue(fixture.panel.fieldKeyboardOpen)
} finally {
fixture.close()
}
}
@Test fun enterLeavesNonFieldKeyboardOpen() {
var closes = 0
val fixture = keyboard(forField = false) { closes++ }
try {
assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN)))
assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP)))
idle()
assertEquals(listOf("\r"), CompositorShadow.commits)
assertEquals(0, closes)
assertTrue(fixture.host.shown)
assertFalse(fixture.panel.fieldKeyboardOpen)
} finally {
fixture.close()
}
}
private fun keyboard(forField: Boolean, onClosed: () -> Unit): Fixture {
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val panel = SecondScreenPresentation(activity, display, {}, {}, {}, onKeyboardClosed = onClosed)
panel.show()
panel.showMode(SecondScreenMode.CUSTOM_CONTROLS)
panel.requestKeyboard(forField)
val host: KeyboardHost = ReflectionHelpers.getField(panel, "keyboardHost")
val root: View = ReflectionHelpers.getField(panel, "root")
val owner = Robolectric.buildActivity(ComponentActivity::class.java).setup()
try {
(root.parent as ViewGroup).removeView(root)
owner.get().setContentView(root)
host.show()
idle()
assertTrue("Presentation root is not attached to window after host.show()", root.isAttachedToWindow)
assertTrue(host.shown)
val connection = host.onCreateInputConnection(EditorInfo())
assertNotNull(connection)
return Fixture(panel, host, connection!!, owner)
} catch (t: Throwable) {
panel.closeControls()
owner.pause().stop().destroy()
throw t
}
}
private fun keyEvent(action: Int) = KeyEvent(0L, 0L, action, KeyEvent.KEYCODE_ENTER, 0)
private fun idle() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(50))
private data class Fixture(
val panel: SecondScreenPresentation,
val host: KeyboardHost,
val connection: InputConnection,
val owner: ActivityController<ComponentActivity>,
) {
fun close() {
panel.closeControls()
owner.pause().stop().destroy()
}
}
@Implements(WaylandCompositor::class, isInAndroidSdk = false)
class CompositorShadow {
companion object {
val commits = mutableListOf<String>()
@JvmStatic @Implementation fun __staticInitializer__() {}
@JvmStatic @Implementation fun textInputCommit(text: String) {
commits += text
}
}
}
}
@@ -0,0 +1,122 @@
package com.droiddeck.launcher.wayland
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.os.Looper
import android.os.Message
import android.os.Messenger
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = Application::class, shadows = [BottomDesktopCompositorInputTest.CompositorShadow::class])
class BottomDesktopCompositorInputTest {
@Before fun setUp() {
CompositorShadow.calls.clear()
}
@Test fun chineseTextThenEnterUsesTheOrderedHostQueue() {
withService { messenger ->
messenger.send(text("中文输入"))
messenger.send(key(KEY_ENTER, PRESSED))
messenger.send(key(KEY_ENTER, RELEASED))
idle()
assertEquals(listOf("text:中文输入", "key:28:1", "key:28:0"), CompositorShadow.calls)
assertTrue(CompositorShadow.calls.none { it.startsWith("unordered") })
}
}
@Test fun editingKeysAndTextShareOneOrderedQueue() {
withService { messenger ->
messenger.send(text("ab"))
messenger.send(key(KEY_BACKSPACE, PRESSED))
messenger.send(key(KEY_BACKSPACE, RELEASED))
messenger.send(key(KEY_DELETE, PRESSED))
messenger.send(key(KEY_DELETE, RELEASED))
messenger.send(key(KEY_TAB, PRESSED))
messenger.send(key(KEY_TAB, RELEASED))
messenger.send(text("cd"))
messenger.send(key(KEY_DOWN, PRESSED))
messenger.send(key(KEY_DOWN, RELEASED))
messenger.send(key(KEY_UP, PRESSED))
messenger.send(key(KEY_UP, RELEASED))
idle()
assertEquals(
listOf(
"text:ab",
"key:14:1", "key:14:0",
"key:111:1", "key:111:0",
"key:15:1", "key:15:0",
"text:cd",
"key:108:1", "key:108:0",
"key:103:1", "key:103:0",
),
CompositorShadow.calls,
)
assertTrue(CompositorShadow.calls.none { it.startsWith("unordered") })
}
}
private fun withService(block: (Messenger) -> Unit) {
val controller = Robolectric.buildService(BottomDesktopCompositorService::class.java).create()
try {
val messenger = Messenger(controller.get().onBind(Intent()))
block(messenger)
} finally {
controller.destroy()
}
}
private fun text(value: String) = Message.obtain(null, BottomDesktopCompositorService.MSG_TEXT).apply {
data = Bundle().apply { putString(BottomDesktopCompositorService.KEY_TEXT, value) }
}
private fun key(code: Int, state: Int) =
Message.obtain(null, BottomDesktopCompositorService.MSG_KEY, code, state)
private fun idle() = shadowOf(Looper.getMainLooper()).idle()
companion object {
private const val KEY_ENTER = 28
private const val KEY_BACKSPACE = 14
private const val KEY_DELETE = 111
private const val KEY_TAB = 15
private const val KEY_DOWN = 108
private const val KEY_UP = 103
private const val PRESSED = 1
private const val RELEASED = 0
}
@Implements(WaylandCompositor::class, isInAndroidSdk = false)
class CompositorShadow {
companion object {
val calls = mutableListOf<String>()
@JvmStatic @Implementation fun __staticInitializer__() {}
@JvmStatic @Implementation fun textInputCommit(text: String) {
calls += "text:$text"
}
@JvmStatic @Implementation fun nativeSendKey(evdev: Int, state: Int) {
calls += "unordered:$evdev:$state"
}
@JvmStatic @Implementation fun nativeSendKeyOrdered(evdev: Int, state: Int) {
calls += "key:$evdev:$state"
}
}
}
}
+10
View File
@@ -303,6 +303,16 @@ alone would then read as an installed client.
hook records the guest handler as it does for `sigaction()` and keeps its own installed, so a
program that sets a crash handler is no longer killed by the next blocked system call
(`tools/tests/test_native_hook_sigsys_mask.py`).
- `0020-guest-stack-clear-of-host-stack-reserve`: FEX places the guest's 128 MB stack range
with `MAP_FIXED_NOREPLACE`, scanning down from the top of the address space. With a 39-bit address
space the host stack sits in that top range in about one start in eight, and the guest stack then
landed directly below it, inside the space the kernel keeps free for the host stack to grow
(`RLIMIT_STACK`, at least 128 MB). A deep host call chain (the native userland's `execve` hook
and libc `syscall()` wrappers) then grew the host stack into the top of the guest stack, where
the guest's argument and environment strings live, and the next program started with a corrupted
environment (Proton failing with `KeyError: 'PWD'` or "No compat data path"). The guest stack is
now placed below that reserve. On a Retroid Pocket Duo, 100 nested Proton starts ran clean, 10 of
them with the host stack at the top; without the patch 3 of 25 were corrupted.
- **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from
this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container
with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release,
+53 -3
View File
@@ -172,7 +172,7 @@ there.
### B. Exec-in-place workers for long-lived processes
Declare a pool of `android:process` services (`:g0`…`:g95`). Each long-lived program runs as the
Declare a pool of `android:process` services (`:g0`…`:g127`). Each long-lived program runs as the
main process of one worker (Gap 2): full app privileges, direct GPU, normal signals and `/proc`
(same uid and SELinux domain), and the app hears its exit through binder death. Costs and limits:
@@ -262,8 +262,29 @@ vfork-safe (Python's subprocess execs under `vfork`). Details that mattered:
session (KDE Plasma, 17–19 counted at rest), a Konsole running 40 `sleep 600 &` jobs peaked at
61 counted and lost 27 processes to Android's limit (Konsole, D-Bus, the portal) before this, and
at 20 with no kills after. Still counted, and not handed off: a terminal's foreground jobs (a
`make -j` and its compilers), the D-Bus daemon's activation helpers (forks that never exec) and
the desktop's own programs started by KDE's launchers.
`make -j` and its compilers) and the D-Bus daemon's activation helpers (forks that never exec).
- **The desktop.** Plasma's own programs are listed (`startplasma-wayland`, `plasma_session`,
KWin, `kded6`, `ksmserver`, `plasmashell`, PowerDevil, KDE Connect, the KIO workers, the D-Bus
activated portal, dconf and activity manager) along with DroidDeck's desktop helpers. Discover's
update notifier, GeoClue's demo agent and the global-menu proxy are off in the user's Autostart.
A program a desktop launcher starts (`DD_HANDOFF_LAUNCHERS`: Plasma's shell, KRunner, Dolphin)
goes to a worker when it is a plain fork and exec: in the launcher's process group and session,
with no controlling terminal. Those launchers are Qt programs, which wait with `waitpid()` once
the hook has taken their pidfds away. A terminal's shell (its own session and terminal) stays.
Firefox runs with fission off, at most two web content processes and no crash helper. The
desktop and its apps use about 80 workers with Steam and a game running, hence 128.
Counted children on the Thor (main: the session as #3338 and #3594 left it):
| | main | this |
|---|---|---|
| desktop at rest | 30 | 0 |
| Dolphin, Konsole, Firefox, Kate and System Settings open | not measured (49 on a Pocket FIT without Firefox, the terminal running 40 jobs) | 7 |
| those, the desktop's Steam client and Bully running | not measured | 20 (30 with 64 workers: Wine's services were refused one) |
With Bully running, six scans forced with the stock limit of 32 killed nothing. What stays
counted then: Steam's client and launch chain (10), Firefox's helpers (6), Konsole's shell,
Proton's script and `wineserver`.
Default list: the portals, at-spi, `python3`, PipeWire, WirePlumber, Decky's PluginLoader, the log's
`gnudd`, `xprop -spy`, the web helper's renderers, `wine`, `wine-preloader`, `wineserver`.
@@ -510,6 +531,35 @@ the old behavior and the old requirement.
7. A (the isolated tier) only if B stops working on a future Android; it needs a file and socket
broker and keeps the GPU outside.
## Zombies
Every session process is a child subreaper (`tools/linuxfs/preload/subreaper.c`, so that a
double-forked Xwayland is not left to init, which some vendor kernels kill), and most programs
never wait for a child they did not fork. What they adopted stayed a zombie: the grandchildren of
Qt's `startDetached()` under Plasma's shell, KWin and kaccess, Wine's double-forked processes,
wlroots' Xwayland under gamescope. A parent that never waits at all (Plasma's shell, for what it
launches) also kept the forked child of each program it handed off. On the Thor, main had 4
zombies in Steam mode at rest and 19 in Bully, and the desktop gained one per app closed.
The hook now reaps them from SIGCHLD (`ddh_reap_unclaimed()`):
- **Adopted:** each process records, at its pid, the parent that started it and its own start
time, in one file for the session (`DD_PARENTS`). A fork's child does it at the fork, any other
program at its start. A zombie child whose record names another parent was adopted. An own child
(recorded with this parent, or with no record, such as a static program a `vfork()` started) is
left for its program's wait.
- **A handed-off program's forked child,** as a wait's look reaps it: the program's exit stays in
the table for the parent's wait.
The program's SIGCHLD action runs first, and `sigaction()` shows it as the program set it.
`SIG_IGN` and `SA_NOCLDWAIT` stay the kernel's. A program that leaves SIGCHLD alone gets the
handler only when `DD_REAP_ADOPTED` names it (Plasma's programs, D-Bus, gamescope, Wine's
launchers, Decky's loader): with a handler, `poll()`, `sleep()` and the like return `EINTR` when a
child exits. With these changes there are no zombies left in either mode, Bully included.
qemu-user has no `PR_SET_CHILD_SUBREAPER`, so the adoption tests skip under it (CI) and were run on
the Thor's kernel.
## Robustness
- Gap 1's path mismatch is a bug that could be fixed; the app-zygote skip is deliberate. Use app
+23
View File
@@ -0,0 +1,23 @@
# Chinese input
The app ships a pinyin input method payload with the session files; it needs no network at run time.
## Android keyboard
1. Select your Android input method (for example Sogou or Gboard) in the system settings, then start a DroidDeck session and open its Android keyboard.
2. Type pinyin, pick a candidate, and commit it; confirm mixed Chinese/Latin and emoji text such as `中文` and `😀` arrives in the focused field, and that a backspace or Enter sent after a commit stays after it.
## Steam on-screen keyboard
Steam pinyin requires a Linux runtime built with IBus. The APK installs the pinyin engine and its data, but does not replace an installed Linux runtime. A runtime without IBus can still start Steam and cannot offer pinyin until it is updated.
Start a Steam session, open Steam's on-screen keyboard on a text field, switch it to Simplified Chinese (pinyin), and confirm committing a candidate puts the characters in the field. Physical keys, shortcuts, and Latin input keep working as before.
## X11 text-input fallback
For clients without native Wayland text input, committed Android IME text is delivered to the focused X11 display.
- **One focused display.** Text goes only to the focused X11 display.
- **Mappings stay stable.** Each keysym keeps its keycode and mapping until the helper exits, because clients may decode key events after they arrive.
- **Capacity is finite.** Only originally empty, non-modifier, unheld keycodes 8..255 can be reserved (at most 248 per display, in practice fewer); a frame that needs more distinct symbols than remain is refused before anything is injected, so restart the session to reclaim the slots.
- **Scope of the limitation.** Steam's own built-in IBus pinyin keyboard and native Wayland text input do not use this fallback and are not subject to it.
+12
View File
@@ -8,6 +8,18 @@ pluginManagement {
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
def robolectricMirror = providers.gradleProperty('robolectricMavenMirror').orNull
if (robolectricMirror) {
exclusiveContent {
forRepository {
maven {
name = 'robolectricMirror'
url = uri(robolectricMirror)
}
}
filter { includeGroup 'org.robolectric' }
}
}
google()
mavenCentral()
maven { url 'https://jitpack.io' }
+7
View File
@@ -87,6 +87,11 @@ static const char *rewrite_path(const char *path, char *out, size_t size) {
return path;
}
// The native hook's SIGCHLD handling (hook/signals.c) is not part of this shim: its programs record their
// first parent for the session's subreapers, and reap nothing themselves.
static void ddnatv_manage_sigchld(void) {}
static void ddh_reap_unclaimed(void) __attribute__((unused));
#include "../nativeguest/hook/kept.c"
#include "../nativeguest/hook/handoff.c"
@@ -315,12 +320,14 @@ pid_t fork(void) {
}
ddh_prepare();
pid_t forker = (pid_t)syscall(SYS_gettid);
pid_t forking = (pid_t)syscall(SYS_getpid);
pid_t pid = orig_fork();
if (pid == 0) {
kept_forked();
kept_close_forked();
ddh_drop_worker_binder();
ddh_forked(forker);
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
} else if (pid > 0) {
ddh_child_created(pid, 1);
}
+27
View File
@@ -224,6 +224,32 @@ drive_z() {
rm -f "$z" && ln -s / "$z" && echo "$(date +%H:%M:%S) drive z: -> / (was ${old:-missing})"
}
program_drive() {
dev=$COMPAT/pfx/dosdevices
case "$EXE" in /*) ;; *) return 0 ;; esac
[ -d "$dev" ] || return 0
dir=${EXE%/*}
top=$dir
ls "$top" > /dev/null 2>&1 || return 0
while [ "$top" != / ]; do
up=${top%/*}; up=${up:-/}
ls "$up" > /dev/null 2>&1 || break
top=$up
done
[ "$top" = / ] && return 0
for l in "$dev"/[a-y]:; do
[ -L "$l" ] || continue
t=$(readlink "$l"); t=${t%/}
case "$t" in /?*) ;; *) continue ;; esac
case "$dir/" in "$t"/*) case "$t/" in "$top"/*) return 0 ;; esac ;; esac
done
for x in d e f g h i j k l m n o p q r t u v w x y; do
{ [ -e "$dev/$x:" ] || [ -L "$dev/$x:" ]; } && continue
ln -s "$top" "$dev/$x:" && echo "$(date +%H:%M:%S) drive $x: -> $top (Android does not let Wine open Z:'s root)"
return 0
done
}
prepare_prefix() {
P=$COMPAT/pfx
drive_z "$P"
@@ -344,6 +370,7 @@ if [ $dead -gt 0 ]; then
fi
prepare_prefix
program_drive
# FEX keeps translated code per program in the prefix (AppData/Local/fex-emu/DiskCache) and reuses it with whatever FEX
# runs the prefix next. Code cached by another FEX build (DroidDeck-Proton's, or a different FEX picked in the
+3 -1
View File
@@ -50,7 +50,7 @@ if ! command -v docker >/dev/null 2>&1; then
echo "Docker is required to cross-compile the glibc ARM64 preload libraries." >&2
exit 1
fi
for tool in curl tar zstd shasum unzip python3 go; do
for tool in curl tar zstd shasum unzip python3 go rpm2cpio cpio; do
if ! command -v "${tool}" >/dev/null 2>&1; then
echo "${tool} is required to build the CI-equivalent APK." >&2
exit 1
@@ -540,6 +540,8 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
fi
python3 tools/powervr/fetch.py
bash tools/packs/build.sh app/build/packs
mkdir -p "${cache_dir}/ime"
python3 "${repo_root}/tools/ime/prepare.py" --packages "${cache_dir}/ime" --download --output "${linuxfs_dir}"
python3 tools/release/runtime_inputs.py record
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
+8 -1
View File
@@ -15,6 +15,7 @@
"tools/msitools",
"tools/pipewire",
"tools/vr",
"tools/ime",
"tools/gpuload",
"app/src/main/cpp/waylandcomp/generated",
"app/src/main/cpp/waylandcomp/src/headpose_shm.h",
@@ -24,6 +25,10 @@
"outputs": [
"app/src/main/assets/linuxfs/usr/local/bin/gamescope",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/bin/linuxarm64/driver_droiddeck.so",
"app/src/main/assets/linuxfs/usr/local/share/droiddeck/ime-files.json",
"app/src/main/assets/linuxfs/usr/local/share/droiddeck/ibus.profile",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ime/ibus-engine-pinyin",
"app/src/main/assets/linuxfs/usr/share/pyzy/db/android.db",
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so"
],
"ndk": true,
@@ -32,7 +37,9 @@
"libc6-dev-arm64-cross",
"g++-aarch64-linux-gnu",
"libvulkan1",
"mesa-vulkan-drivers"
"mesa-vulkan-drivers",
"rpm2cpio",
"cpio"
]
},
"esync": {
+2
View File
@@ -12,6 +12,8 @@ done
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
[ -f "$f" ] && install -Dm644 "$f" "$D/${f#tools/linuxfs/overlay/}"
done
mkdir -p app/build/ime-packages
python3 tools/ime/prepare.py --packages app/build/ime-packages --download --output "$D"
if [ -f tools/gamescope/release.env ]; then
. tools/gamescope/release.env
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst"
+1 -1
View File
@@ -4,7 +4,7 @@ if [[ -z "${docker_platform}" ]]; then
fi
case "${docker_platform}" in linux/arm64|linux/arm64/*) docker_platform=linux/arm64 ;; esac
if [[ -z "${DROIDDECK_BUILD_IMAGE:-}" ]]; then
DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v4
DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v5
[[ "${docker_platform}" == linux/arm64 ]] && DROIDDECK_BUILD_IMAGE+=-arm64
fi
export DROIDDECK_DOCKER_PLATFORM=${docker_platform} DROIDDECK_BUILD_IMAGE
@@ -0,0 +1,45 @@
diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
index cebf1f5..b1a72d2 100644
--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h
+++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
@@ -32,6 +32,7 @@
#include <sys/personality.h>
#include <sys/prctl.h>
#include <sys/random.h>
+#include <sys/resource.h>
#define PAGE_START(x) ((x) & ~(uintptr_t)(4095))
#define PAGE_OFFSET(x) ((x) & 4095)
@@ -505,7 +506,12 @@ public:
auto PageSize = sysconf(_SC_PAGESIZE);
PageSize = PageSize > 0 ? PageSize : FEXCore::Utils::FEX_PAGE_SIZE;
+ const auto [HostStackLow, HostStackHigh] = HostStackReservation(PageSize);
+
do {
+ if (StackHint < HostStackHigh && StackHint + FULL_STACK_SIZE > HostStackLow && HostStackLow > FULL_STACK_SIZE) {
+ StackHint = (HostStackLow - FULL_STACK_SIZE) & ~static_cast<uint64_t>(PageSize - 1);
+ }
// Allocate the base of the full 128MB stack range.
StackPointerBase = Handler->GuestMmap(Thread, reinterpret_cast<void*>(StackHint), FULL_STACK_SIZE, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_GROWSDOWN | MAP_NORESERVE | MAP_FIXED_NOREPLACE, -1, 0);
@@ -793,6 +799,19 @@ public:
*AuxTabSize = sizeof(AuxType) * AuxVariables.size();
}
+ static std::pair<uint64_t, uint64_t> HostStackReservation(uint64_t PageSize) {
+ struct prctl_mm_map map {};
+ uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast<uint64_t>(__builtin_frame_address(0));
+ Top = (Top + PageSize - 1) & ~(PageSize - 1);
+
+ constexpr uint64_t MinGap = 128ULL * 1024 * 1024;
+ const uint64_t MaxGap = std::max(Top / 6 * 5, MinGap);
+ struct rlimit Limit {};
+ uint64_t Gap = getrlimit(RLIMIT_STACK, &Limit) == 0 ? static_cast<uint64_t>(Limit.rlim_cur) : MinGap;
+ Gap = std::clamp(Gap, MinGap, MaxGap) + 256 * PageSize;
+ return {Top > Gap ? Top - Gap : 0, Top};
+ }
+
// Get the current memory map from /proc/self/stat
static bool GetCurrentMap(struct prctl_mm_map& map) {
+27
View File
@@ -0,0 +1,27 @@
{
"version": 1,
"release": "Fedora 44 Everything aarch64",
"mirror": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/",
"packages": {
"ibus-pinyin": {
"filename": "ibus-pinyin-1.5.1-7.fc44.aarch64.rpm",
"url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/i/ibus-pinyin-1.5.1-7.fc44.aarch64.rpm",
"sha256": "fcae3a5f4263c005efa0751737bd653d4dca8ca53777362ad519f6bcbd99587c"
},
"pyzy": {
"filename": "pyzy-0.1.0-37.fc44.aarch64.rpm",
"url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/p/pyzy-0.1.0-37.fc44.aarch64.rpm",
"sha256": "aa41dfdaa052ac5432e2fd4c64ea706a7153b6e7b72f18bf1633006f7190b76f"
},
"pyzy-db-android": {
"filename": "pyzy-db-android-0.1.0-37.fc44.noarch.rpm",
"url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/p/pyzy-db-android-0.1.0-37.fc44.noarch.rpm",
"sha256": "bcaafe36fc93b892b1901607c887fd4efbc47eaa5b829bfe0347aa3137f41576"
},
"lua-libs": {
"filename": "lua-libs-5.4.8-5.fc44.aarch64.rpm",
"url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/l/lua-libs-5.4.8-5.fc44.aarch64.rpm",
"sha256": "d719e35a8c2f771084f0b0d135a3ac68c51b032fc2199507685fe3ea32cee8fc"
}
}
}
+230
View File
@@ -0,0 +1,230 @@
#!/usr/bin/env python3
"""Prepare the pinned pinyin engine and its runtime dependencies."""
import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import shutil
import subprocess
import tempfile
import urllib.request
import xml.etree.ElementTree as ElementTree
PACKAGES = Path(__file__).with_name('packages.json')
LIBRARY_DIR = 'usr/local/lib/droiddeck-ime'
ENGINE_NAME = 'ibus-engine-pinyin'
ENGINE_MEMBERS = ('usr/libexec/' + ENGINE_NAME, 'usr/bin/' + ENGINE_NAME)
COMPONENT = 'usr/share/ibus/component/pinyin.xml'
PROFILE = 'usr/local/share/droiddeck/ibus.profile'
MANIFEST = 'usr/local/share/droiddeck/ime-files.json'
LICENSES = 'usr/local/share/licenses/droiddeck-ime'
PROFILE_TEXT = 'user-db:user\nsystem-db:ibus\n'
# The engine links these by soname, so the dereferenced copies keep the RPM member names.
LIBRARIES = {'pyzy': ('usr/lib64/libpyzy-1.0.so.0',),
'lua-libs': ('usr/lib64/liblua-5.4.so', 'usr/lib64/liblua-5.4.so.0')}
DATA = {'ibus-pinyin': ('usr/share/ibus-pinyin/base.lua', 'usr/share/ibus-pinyin/phrases.txt',
'usr/share/ibus-pinyin/db/english.db'),
'pyzy': ('usr/share/pyzy/phrases.txt',),
'pyzy-db-android': ('usr/share/pyzy/db/android.db',)}
NOTICES = ('COPYING', 'LICENSE', 'COPYRIGHT', 'README', 'NOTICE')
def digest(path):
result = hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
result.update(block)
return result.hexdigest()
def specifications():
return json.loads(PACKAGES.read_text())['packages']
def fetch(directory, spec):
directory.mkdir(parents=True, exist_ok=True)
path = directory / spec['filename']
pending = path.with_name(path.name + '.pending')
with urllib.request.urlopen(spec['url'], timeout=60) as response, pending.open('wb') as stream:
shutil.copyfileobj(response, stream)
if digest(pending) != spec['sha256']:
pending.unlink()
raise ValueError('SHA256 mismatch for downloaded ' + spec['filename'])
pending.replace(path)
return path
def verified(directory, download=False):
sources = {}
for name, spec in specifications().items():
path = directory / spec['filename']
if download and not (path.is_file() and digest(path) == spec['sha256']):
path = fetch(directory, spec)
if not path.is_file():
raise ValueError('missing RPM ' + spec['filename'])
if digest(path) != spec['sha256']:
raise ValueError('SHA256 mismatch for ' + spec['filename'])
sources[name] = path
return sources
def extract(name, rpm, destination):
for tool in ('rpm2cpio', 'cpio'):
if shutil.which(tool) is None:
raise ValueError(tool + ' is required to unpack the RPM payload')
destination.mkdir(parents=True)
with tempfile.TemporaryFile(dir=destination.parent) as payload:
subprocess.run(['rpm2cpio', str(rpm)], stdout=payload, check=True)
payload.seek(0)
listing = subprocess.run(['cpio', '-it', '--quiet'], stdin=payload,
stdout=subprocess.PIPE, check=True)
payload.seek(0)
for line in listing.stdout.splitlines():
path = PurePosixPath(line.decode('utf-8', 'surrogateescape'))
if path.is_absolute() or '..' in path.parts:
raise ValueError(f'{name}: RPM payload contains unsafe path {path}')
subprocess.run(['cpio', '-idm', '--quiet'], stdin=payload,
cwd=destination, check=True)
def member(tree, name):
path = (tree / name).resolve()
if not path.is_relative_to(tree.resolve()) or not path.is_file():
raise ValueError(f'{tree.name}: RPM payload is missing {name}')
return path
def install(source, target, output, files, executable=False):
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
target.chmod(0o755 if executable else 0o644)
files.add(target.relative_to(output).as_posix())
def engine(tree):
for candidate in ENGINE_MEMBERS:
if (tree / candidate).is_file():
return candidate
raise ValueError('ibus-pinyin RPM has no ' + ENGINE_NAME + ' executable')
def component(tree):
root = ElementTree.parse(member(tree, COMPONENT)).getroot()
for element in list(root.iter()):
for child in list(element):
if child.tag == 'setup':
element.remove(child)
executable = root.find('exec')
if executable is None:
raise ValueError('pinyin.xml has no engine exec element')
executable.text = f'/{LIBRARY_DIR}/{ENGINE_NAME} --ibus'
engines = {node.findtext('name', '').strip() for node in root.iter('engine')}
if not {'pinyin', 'bopomofo'} <= engines:
raise ValueError('pinyin.xml no longer defines the pinyin and bopomofo engines')
return root
def icons(root, tree, output, files):
names = set()
for node in root.iter('icon'):
text = (node.text or '').strip()
if text:
names.add(Path(text).stem if '/' in text else text)
found = sorted(path for path in (tree / 'usr/share').rglob('*')
if path.is_file() and path.suffix in ('.svg', '.png') and path.stem in names)
if names and not found:
raise ValueError('pinyin.xml icons are not in the ibus-pinyin RPM: ' + ', '.join(sorted(names)))
for path in found:
install(path, output / path.relative_to(tree), output, files)
def notices(name, tree, output, files):
copied = []
for folder in ('usr/share/licenses/' + name, 'usr/share/doc/' + name):
base = tree / folder
if not base.is_dir():
continue
for path in sorted(base.rglob('*')):
if path.is_file() and path.name.upper().startswith(NOTICES):
target = output / LICENSES / name / path.relative_to(base)
install(path, target, output, files)
copied.append(target.relative_to(output / LICENSES).as_posix())
return copied
def prepare(directory, output, work=None, download=False):
specs = specifications()
sources = verified(directory, download)
output = output.resolve()
output.mkdir(parents=True, exist_ok=True)
created = work is None
work = Path(tempfile.mkdtemp(prefix='.droiddeck-ime-', dir=output.parent)) if created else Path(work)
work.mkdir(parents=True, exist_ok=True)
try:
trees = {}
for name, source in sources.items():
trees[name] = work / name
shutil.rmtree(trees[name], ignore_errors=True)
extract(name, source, trees[name])
files = set()
pinyin = trees['ibus-pinyin']
install(member(pinyin, engine(pinyin)), output / LIBRARY_DIR / ENGINE_NAME, output, files, executable=True)
for name, candidates in LIBRARIES.items():
installed = [candidate for candidate in candidates if (trees[name] / candidate).exists()]
if not installed:
raise ValueError(f'{name}: RPM has none of {list(candidates)}')
for candidate in installed:
install(member(trees[name], candidate), output / LIBRARY_DIR / Path(candidate).name, output, files)
for name, members in DATA.items():
for relative in members:
install(member(trees[name], relative), output / relative, output, files)
root = component(pinyin)
icons(root, pinyin, output, files)
target = output / COMPONENT
target.parent.mkdir(parents=True, exist_ok=True)
ElementTree.ElementTree(root).write(target, encoding='utf-8', xml_declaration=True)
files.add(COMPONENT)
profile = output / PROFILE
profile.parent.mkdir(parents=True, exist_ok=True)
profile.write_text(PROFILE_TEXT, newline='\n')
files.add(PROFILE)
packages = {}
for name, spec in specs.items():
license_files = notices(name, trees[name], output, files)
packages[name] = {'filename': spec['filename'], 'url': spec['url'], 'sha256': spec['sha256'],
'license_files': license_files}
if not license_files:
packages[name]['license_note'] = ('RPM bundles no separate license file; '
'the payload is unmodified Fedora package content')
manifest = {'version': 1, 'engine': 'pinyin', 'packages': packages,
'files': {path: {'sha256': digest(output / path),
'mode': f'{(output / path).stat().st_mode & 0o777:04o}'}
for path in sorted(files)}}
destination = output / MANIFEST
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(json.dumps(manifest, sort_keys=True, indent=2) + '\n', newline='\n')
return destination, len(files)
finally:
if created:
shutil.rmtree(work, ignore_errors=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--packages', type=Path, required=True, help='Directory with the exact pinned RPMs')
parser.add_argument('--output', type=Path, required=True,
help='Prepared linuxfs root, for example app/build/prepared-assets/linuxfs')
parser.add_argument('--work', type=Path, help='Kept extraction cache instead of a temporary directory')
parser.add_argument('--download', action='store_true',
help='Fetch missing or mismatched RPMs into --packages and verify their SHA256')
args = parser.parse_args()
try:
destination, count = prepare(args.packages, args.output, args.work, args.download)
except (OSError, ValueError, subprocess.CalledProcessError, ElementTree.ParseError) as error:
parser.exit(1, f'error: {error}\n')
print(f'Wrote {count} IME payload files; manifest {destination}')
if __name__ == '__main__':
main()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Check pinyin configuration and text commits over IBus."""
import os
import time
try:
import gi
gi.require_version('IBus', '1.0')
from gi.repository import GLib, IBus
except (ImportError, ValueError) as error:
raise SystemExit(f'error: PyGObject with the IBus 1.0 typelib is required: {error}')
CLIENT = 'droiddeck-ime-test'
ENGINE = 'pinyin'
SECTION = 'engine/Pinyin'
BOOLEAN_KEYS = ('DoublePinyin', 'InitPinyin', 'GBK')
KEYCODES = {'a': 38, 'h': 43, 'i': 31, 'n': 57, 'o': 32, 'space': 65, '1': 10}
def pump(seconds, condition):
deadline = time.monotonic() + seconds
while True:
GLib.MainContext.default().iteration(False)
if condition():
return True
if time.monotonic() >= deadline:
return False
time.sleep(0.02)
def press(context, name):
keyval = IBus.keyval_from_name(name)
keycode = KEYCODES[name]
context.process_key_event(keyval, keycode, 0)
context.process_key_event(keyval, keycode, IBus.ModifierType.RELEASE_MASK)
def boolean(config, key):
value = config.get_value(SECTION, key)
if value is None or value.get_type_string() != 'b':
return None
return value.get_boolean()
def unchanged(value, original):
if original is None:
return value is None
return value is not None and value.print_(True) == original.print_(True)
def configured(bus):
config = bus.get_config()
if config is None:
raise SystemExit('error: the bus exposes no configuration service')
saved = {key: config.get_value(SECTION, key) for key in BOOLEAN_KEYS}
probed = 0
try:
for key in BOOLEAN_KEYS:
original = saved[key]
current = original is not None and original.get_type_string() == 'b' \
and original.get_boolean()
wanted = not current
# The PyGObject override returns None on success, so verify writes by readback.
config.set_value(SECTION, key, GLib.Variant.new_boolean(wanted))
if not pump(3.0, lambda key=key, wanted=wanted: boolean(config, key) == wanted):
raise SystemExit(f'error: {SECTION}/{key} did not read back as written')
probed += 1
finally:
restore_failed = []
for key in BOOLEAN_KEYS:
original = saved[key]
try:
if original is None:
config.unset(SECTION, key)
else:
config.set_value(SECTION, key, original)
if not pump(3.0, lambda key=key, original=original:
unchanged(config.get_value(SECTION, key), original)):
restore_failed.append(key)
except GLib.Error:
restore_failed.append(key)
if restore_failed:
raise SystemExit('error: could not restore ' + SECTION + ' settings: '
+ ', '.join(restore_failed))
return probed
def main():
if not os.environ.get('IBUS_ADDRESS'):
raise SystemExit('error: IBUS_ADDRESS is not set; the smoke test needs the private ibus-daemon')
bus = IBus.Bus()
if not bus.is_connected():
raise SystemExit('error: cannot connect to the IBus bus from IBUS_ADDRESS')
engines = {engine.get_name() for engine in bus.list_engines() or []}
if ENGINE not in engines:
raise SystemExit('error: pinyin is not registered: ' + ', '.join(sorted(engines)))
print('IBus bus connected; pinyin engine registered')
keys = configured(bus)
print(f'engine/Pinyin config write/readback ok ({keys} boolean settings)')
if not bus.set_global_engine(ENGINE):
raise SystemExit('error: the bus rejected the pinyin global engine')
context = bus.create_input_context(CLIENT)
state = {'candidates': 0, 'commit': ''}
def lookup(_, table, visible):
if table is not None:
state['candidates'] = table.get_number_of_candidates()
def commit(_, text):
state['commit'] = text.get_text() or state['commit']
context.connect('update-lookup-table', lookup)
context.connect('commit-text', commit)
context.set_capabilities(IBus.Capabilite.PREEDIT_TEXT | IBus.Capabilite.LOOKUP_TABLE
| IBus.Capabilite.FOCUS)
context.focus_in()
pump(1.0, lambda: False)
context.set_engine(ENGINE)
pump(1.0, lambda: False)
for _ in range(3):
for name in 'nihao':
press(context, name)
if pump(3.0, lambda: state['candidates'] > 0):
break
else:
raise SystemExit('error: no pinyin candidates after typing the test syllable')
print('lookup table ok')
def chinese():
return any('\u4e00' <= character <= '\u9fff' for character in state['commit'])
for name in ('space', '1'):
press(context, name)
if pump(3.0, chinese):
break
if not chinese():
raise SystemExit('error: pinyin committed no Chinese text for the test syllable')
print('commit-text ok')
context.focus_out()
print('droiddeck IBus pinyin smoke test passed')
if __name__ == '__main__':
try:
main()
except GLib.Error as error:
raise SystemExit(f'error: IBus call failed: {error.message}')
+12 -4
View File
@@ -9,7 +9,7 @@ export MOZ_ENABLE_WAYLAND=1 MOZ_USE_XINPUT2=1
export SHELL=/bin/bash
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
export MOZ_SHM_NO_SEALS=1 MOZ_CRASHREPORTER_DISABLE=1
export QTWEBENGINE_DISABLE_SANDBOX=1
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
export KWIN_USE_OVERLAYS=0
@@ -142,11 +142,10 @@ Exec=konsole -e /usr/local/bin/droiddeck-steam-x64
Icon=steam
Categories=System;
ENTRY
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
python3 /usr/local/bin/droiddeck-pad-defaults --every 30 &
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) &
python3 /usr/local/bin/droiddeck-library-perms 2>&1 &
mkdir -p /usr/local/share/applications
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
[Desktop Entry]
@@ -175,6 +174,15 @@ fi
if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then
FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 &
fi
# Android counts the desktop's programs against an app's limit of 32. Off unless the user turns them
# back on in Autostart: Discover's update notifier (the packages follow DroidDeck's releases, and it
# keeps PackageKit running as root), GeoClue's demo agent (nothing asks for a location) and the
# global-menu proxy (the panel has no global menu).
mkdir -p "$HOME/.config/autostart"
for entry in org.kde.discover.notifier geoclue-demo-agent gmenudbusmenuproxy; do
[ -e "$HOME/.config/autostart/$entry.desktop" ] ||
printf '[Desktop Entry]\nType=Application\nName=%s\nHidden=true\n' "$entry" > "$HOME/.config/autostart/$entry.desktop"
done
skel_done=$HOME/.local/share/droiddeck/skel-copied
if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then
cp -rn /etc/skel/. "$HOME/" 2>/dev/null
@@ -9,3 +9,11 @@ pref("datareporting.policy.dataSubmissionEnabled", false);
pref("browser.aboutwelcome.enabled", false);
pref("browser.startup.homepage", "about:blank");
pref("layout.css.devPixelsPerPx", "1.25");
// Android counts each of Firefox's processes against the app's limit of 32: one web content process
// per two tabs' worth of sites rather than one per site, none started ahead, and extensions and
// about: pages in the processes that already exist.
pref("fission.autostart", false);
pref("dom.ipc.processCount", 2);
pref("dom.ipc.processPrelaunch.enabled", false);
pref("browser.tabs.remote.separatePrivilegedContentProcess", false);
pref("extensions.webextensions.remote", false);
@@ -1,7 +1,15 @@
#!/bin/bash
[ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -n "${DISPLAY:-}" ] || exit 0
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
child=$!
trap 'kill "$child" 2>/dev/null' EXIT
[ -n "${DISPLAY:-}" ] || exit 0
children=()
if [ -n "${DD_ANDROID_CLIPBOARD:-}" ]; then
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
children+=("$!")
fi
if [ -n "${DD_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-text-input ]; then
/usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" &
children+=("$!")
fi
[ "${#children[@]}" -gt 0 ] || exit 0
trap 'kill "${children[@]}" 2>/dev/null' EXIT
trap 'exit 0' TERM INT
wait "$child"
wait "${children[@]}"
@@ -1,6 +1,8 @@
#!/usr/bin/python3
import glob
import os
import sys
import time
HOME = os.environ.get("HOME", "/root")
CONFIG = os.environ.get("XDG_CONFIG_HOME", os.path.join(HOME, ".config"))
@@ -1048,8 +1050,19 @@ def switch_emulators():
print(f"droiddeck-pad-defaults: {name}: Player 1 on the controller ({cfg})")
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
try:
step()
except Exception as e:
print(f"droiddeck-pad-defaults: {step.__name__}: {e}")
def run_all():
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
try:
step()
except Exception as e:
print(f"droiddeck-pad-defaults: {step.__name__}: {e}", flush=True)
# --every SECONDS: again at that interval, for emulators set up while the desktop runs. One process
# for the whole desktop session rather than a shell loop starting a new one each time.
sys.stdout.reconfigure(line_buffering=True)
run_all()
if len(sys.argv) == 3 and sys.argv[1] == "--every":
while True:
time.sleep(float(sys.argv[2]))
run_all()
@@ -13,6 +13,12 @@ fi
export HOME=${HOME:-/root}
mode=${1:-desktop}
shift || true
# Steam and its helpers share one session bus per session; an existing desktop bus is inherited.
if [ "$mode" = steam ] && [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
exec dbus-run-session -- "$0" "$mode" "$@"
fi
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
# Starts a long-lived program in its own Android process, which Android does not count against
# the session's child processes (docs/phantom-processes.md); a normal background job otherwise.
@@ -63,9 +69,16 @@ dd_job() {
# window's app by walking its process's parents) or its utility processes (the client only accepts
# its transport from its own children).
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver}
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver:droiddeck-login1:droiddeck-snapd:droiddeck-polkitd:droiddeck-root+/usr/libexec/packagekitd:droiddeck-desktop-clipboard:droiddeck-ime:droiddeck-pad-defaults+--every:droiddeck-library-perms:droiddeck-clipboard:dbus-run-session:startplasma-wayland:plasma_session:kwin_wayland_wrapper:kwin_wayland:kded6:ksmserver:kglobalacceld:plasmashell:krunner:org_kde_powerdevil:xembedsniproxy:kaccess:xsettingsd:kdeconnectd:kunifiedpush-distributor:kactivitymanagerd:xdg-desktop-portal-kde:dconf-service:polkit-kde-authentication-agent-1:plasma-welcome:kioworker}
# The programs these start for the user (an app from the panel, a file opened in Dolphin)
export DD_HANDOFF_LAUNCHERS=${DD_HANDOFF_LAUNCHERS-plasmashell:krunner:dolphin}
# Each process's first parent, so that a process can reap the zombies it adopts as a subreaper, and
# the programs that reap them even while they leave SIGCHLD alone (hook/signals.c)
rm -f /run/droiddeck-parents.* 2>/dev/null
export DD_PARENTS=/run/droiddeck-parents.$$
export DD_REAP_ADOPTED=${DD_REAP_ADOPTED-plasmashell:plasma_session:kwin_wayland:kwin_wayland_wrapper:kaccess:ksmserver:kded6:krunner:dolphin:dbus-daemon:startplasma-wayland:gamescope:wine:wine64:wine-preloader:wine64-preloader:wineserver:PluginLoader:PluginLoader.real}
else
unset DD_HANDOFF
unset DD_HANDOFF DD_HANDOFF_LAUNCHERS DD_PARENTS DD_REAP_ADOPTED
fi
steam_setup_failed() {
echo "== steam: the Steam client could not be set up (status $1)"
@@ -705,6 +718,13 @@ if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr
dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD"
fi
ime_text_pid=
if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DISPLAY:-}" ] && [ -n "${DD_LAUNCH_DIR:-}" ] \
&& [ -x /usr/local/bin/droiddeck-text-input ]; then
/usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" &
ime_text_pid=$!
fi
[ "${DD_DESKTOP:-}" = 1 ] || start_agent
case $mode in
@@ -1971,6 +1991,46 @@ case $mode in
fi
fi
rm -f "$HOME/.dd-restart-game" "$HOME/.dd-restarted-for"
unset IBUS_ADDRESS
ime_ibus_pid=
ime_ibus_socket=
stop_steam_ime() {
if [ -n "$ime_ibus_pid" ]; then
kill "$ime_ibus_pid" 2>/dev/null || true
wait "$ime_ibus_pid" 2>/dev/null || true
ime_ibus_pid=
fi
[ -S "$ime_ibus_socket" ] && rm -f "$ime_ibus_socket"
ime_ibus_socket=
unset IBUS_ADDRESS
}
if [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ] \
&& [ -x /usr/bin/ibus-daemon ] && [ -x /usr/bin/ibus ]; then
ime_ibus_socket="${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-ibus-$$.sock"
export IBUS_ADDRESS="unix:path=$ime_ibus_socket"
/usr/local/bin/droiddeck-steam-ime &
ime_ibus_pid=$!
ime_ready=0
_ime_deadline=$((SECONDS + 5))
while [ "$SECONDS" -lt "$_ime_deadline" ]; do
if env -u LD_LIBRARY_PATH -u LD_PRELOAD -u GSETTINGS_SCHEMA_DIR -u DCONF_PROFILE \
timeout 1 /usr/bin/ibus list-engine --name-only 2>/dev/null | grep -qx 'pinyin'; then
ime_ready=1
break
fi
kill -0 "$ime_ibus_pid" 2>/dev/null || break
nap 0.1
done
unset _ime_deadline
if [ "$ime_ready" = 1 ]; then
echo "== ime: pinyin engine ready at $IBUS_ADDRESS"
else
echo "== ime: the pinyin engine did not start at $IBUS_ADDRESS; Steam starts without Chinese input"
stop_steam_ime
fi
elif [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ]; then
echo "== ime: the installed Linux runtime does not include IBus; Steam starts without pinyin"
fi
while :; do
rm -f "$HOME/.dd-restart-once" "$HOME/.dd-restart-lost"
if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then
@@ -2086,6 +2146,12 @@ case $mode in
kill "$games_watcher" 2>/dev/null || true
wait "$games_watcher" 2>/dev/null || true
fi
stop_steam_ime
if [ -n "${ime_text_pid:-}" ]; then
kill "$ime_text_pid" 2>/dev/null || true
wait "$ime_text_pid" 2>/dev/null || true
ime_text_pid=
fi
if [ -n "${DD_DESKTOP:-}" ]; then
if [ -n "${decky_supervisor:-}" ]; then
kill "$decky_supervisor" 2>/dev/null || true
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
[ -n "${IBUS_ADDRESS:-}" ] || exit 0
unset LD_PRELOAD LD_LIBRARY_PATH GSETTINGS_SCHEMA_DIR
export LD_LIBRARY_PATH=/usr/local/lib/droiddeck-ime
export DCONF_PROFILE=/usr/local/share/droiddeck/ibus.profile
exec /usr/bin/ibus-daemon --address "$IBUS_ADDRESS" --panel disable --config default \
--emoji-extension disable --cache none
+510
View File
@@ -0,0 +1,510 @@
#!/usr/bin/python3
"""Deliver committed Android IME text to the focused X11 client."""
import ctypes
import ctypes.util
import errno
import os
import select
import signal
import socket
import stat
import struct
import sys
MAX_TEXT = 65536
CANCELLABLE = 1 << 31
CLIENT_TIMEOUT = 2.0
PROBE_TIMEOUT = 0.5
FOCUS_PROPERTY = b'GAMESCOPE_KEYBOARD_FOCUS_DISPLAY'
ANY_PROPERTY_TYPE = 0
PROPERTY_WORDS = 1024
PR_SET_PDEATHSIG = 1
UNICODE_KEYSYM_FLAG = 0x01000000
X11_SPECIAL_KEYSYMS = {
'\r': 0xff0d, # XK_Return
'\n': 0xff0d, # XK_Return
'\b': 0xff08, # XK_BackSpace
'\u007f': 0xffff, # XK_Delete
'\t': 0xff09, # XK_Tab
}
_STOP = False
class XModifierKeymap(ctypes.Structure):
_fields_ = [('max_keypermod', ctypes.c_int),
('modifiermap', ctypes.POINTER(ctypes.c_ubyte))]
class _DisplayState:
"""Keep mappings stable until shutdown because clients may decode key events later."""
__slots__ = ('handle', 'codes', 'owned')
def __init__(self, handle):
self.handle = handle
self.codes = {} # keysym -> keycode, stable for the session
self.owned = {} # keycode -> (width, original row) for shutdown restore
class XBridge:
def __init__(self):
self.lib = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6')
self.xtst = ctypes.CDLL(ctypes.util.find_library('Xtst') or 'libXtst.so.6')
self._open_displays = {}
self._declare()
def _declare(self):
lib = self.lib
lib.XOpenDisplay.argtypes = [ctypes.c_char_p]
lib.XOpenDisplay.restype = ctypes.c_void_p
lib.XCloseDisplay.argtypes = [ctypes.c_void_p]
lib.XCloseDisplay.restype = ctypes.c_int
lib.XDefaultRootWindow.argtypes = [ctypes.c_void_p]
lib.XDefaultRootWindow.restype = ctypes.c_ulong
lib.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]
lib.XInternAtom.restype = ctypes.c_ulong
lib.XGetWindowProperty.argtypes = [
ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_long, ctypes.c_long,
ctypes.c_int, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_void_p)]
lib.XGetWindowProperty.restype = ctypes.c_int
lib.XFree.argtypes = [ctypes.c_void_p]
lib.XFree.restype = ctypes.c_int
lib.XDisplayKeycodes.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
lib.XDisplayKeycodes.restype = ctypes.c_int
lib.XGetKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_int,
ctypes.POINTER(ctypes.c_int)]
lib.XGetKeyboardMapping.restype = ctypes.POINTER(ctypes.c_ulong)
lib.XChangeKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.POINTER(ctypes.c_ulong), ctypes.c_int]
lib.XChangeKeyboardMapping.restype = ctypes.c_int
lib.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int]
lib.XSync.restype = ctypes.c_int
lib.XQueryKeymap.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
lib.XQueryKeymap.restype = ctypes.c_int
lib.XGetModifierMapping.argtypes = [ctypes.c_void_p]
lib.XGetModifierMapping.restype = ctypes.POINTER(XModifierKeymap)
lib.XFreeModifiermap.argtypes = [ctypes.POINTER(XModifierKeymap)]
lib.XFreeModifiermap.restype = ctypes.c_int
self.xtst.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int,
ctypes.c_ulong]
self.xtst.XTestFakeKeyEvent.restype = ctypes.c_int
def state(self, name):
existing = self._open_displays.get(name)
if existing is not None:
return existing
handle = self.lib.XOpenDisplay(name.encode())
if not handle:
return None
state = _DisplayState(handle)
self._open_displays[name] = state
return state
def display(self, name):
state = self.state(name)
return state.handle if state else None
def close(self):
for state in self._open_displays.values():
for keycode, (width, original) in state.owned.items():
row = (ctypes.c_ulong * width)(*original)
self.lib.XChangeKeyboardMapping(state.handle, keycode, width, row, 1)
self.lib.XSync(state.handle, 0)
self.lib.XCloseDisplay(state.handle)
self._open_displays.clear()
def target_display(self):
main = os.environ.get('DISPLAY', '').strip()
if not main:
return None
game = os.environ.get('STEAM_GAME_DISPLAY_0', '').strip()
if not game or game == main:
return main
main_display = self.display(main)
if not main_display:
return None
focused = self._focused_display(main_display)
if focused == game:
return game
if focused == main:
return main
return None
def _focused_display(self, display):
root = self.lib.XDefaultRootWindow(display)
atom = self.lib.XInternAtom(display, FOCUS_PROPERTY, 0)
if not atom:
return None
actual_type = ctypes.c_ulong(0)
actual_format = ctypes.c_int(0)
items = ctypes.c_ulong(0)
remaining = ctypes.c_ulong(0)
data = ctypes.c_void_p()
status = self.lib.XGetWindowProperty(
display, root, atom, 0, PROPERTY_WORDS, 0, ANY_PROPERTY_TYPE,
ctypes.byref(actual_type), ctypes.byref(actual_format), ctypes.byref(items),
ctypes.byref(remaining), ctypes.byref(data))
if status != 0 or not data or not items.value:
if data:
self.lib.XFree(data)
return None
try:
raw = _property_bytes(data, actual_format.value, items.value)
finally:
self.lib.XFree(data)
if raw is None:
return None
raw = raw.split(b'\0', 1)[0]
if not raw:
return None
try:
return raw.decode('ascii')
except UnicodeDecodeError:
return None
def keymap(self, display):
lowest = ctypes.c_int(0)
highest = ctypes.c_int(0)
self.lib.XDisplayKeycodes(display, ctypes.byref(lowest), ctypes.byref(highest))
if lowest.value < 0 or highest.value < lowest.value:
return None
count = highest.value - lowest.value + 1
width = ctypes.c_int(0)
symbols = self.lib.XGetKeyboardMapping(display, lowest.value, count, ctypes.byref(width))
if not symbols:
return None
if width.value <= 0:
self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p))
return None
rows = [[symbols[index * width.value + level] for level in range(width.value)]
for index in range(count)]
self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p))
return lowest.value, width.value, rows
def held_keys(self, display):
state = ctypes.create_string_buffer(32)
if not self.lib.XQueryKeymap(display, ctypes.cast(state, ctypes.c_void_p)):
return set()
raw = state.raw
return {keycode for keycode in range(len(raw) * 8)
if raw[keycode >> 3] >> (keycode & 7) & 1}
def modifier_keys(self, display):
mapping = self.lib.XGetModifierMapping(display)
if not mapping:
return set()
try:
width = mapping.contents.max_keypermod
keys = mapping.contents.modifiermap
return {keys[index] for index in range(8 * width) if keys[index]}
finally:
self.lib.XFreeModifiermap(mapping)
def empty_rows(self, display, reserved):
keymap = self.keymap(display)
if keymap is None:
return []
lowest, width, rows = keymap
held = self.held_keys(display)
modifiers = self.modifier_keys(display)
available = []
for index in range(len(rows) - 1, -1, -1):
keycode = lowest + index
if keycode < 8 or keycode > 255 or keycode in held or keycode in modifiers:
continue
if keycode in reserved:
continue
row = rows[index]
if any(row):
continue
available.append((keycode, width, tuple(row)))
return available
def type_text(self, state, text, cancelled=None):
"""Reserve all required mappings before injecting any part of a frame."""
handle = state.handle
needed = []
seen = set()
for character in text:
keysym = _character_keysym(character)
if keysym not in seen:
seen.add(keysym)
needed.append(keysym)
missing = [keysym for keysym in needed if keysym not in state.codes]
if missing:
available = self.empty_rows(handle, set(state.codes.values()))
if len(available) < len(missing):
_log_capacity_exhausted()
return False
for keysym, (keycode, width, original) in zip(missing, available):
row = (ctypes.c_ulong * width)(*[keysym] * width)
# XChangeKeyboardMapping queues the request and returns 0.
self.lib.XChangeKeyboardMapping(handle, keycode, width, row, 1)
state.codes[keysym] = keycode
state.owned[keycode] = (width, original)
self.lib.XSync(handle, 0)
for character in text:
if _STOP:
return False
if cancelled is not None and cancelled():
return False
keycode = state.codes[_character_keysym(character)]
if not self._tap(handle, keycode):
return False
return True
def _tap(self, handle, keycode):
pressed = False
try:
if not self.xtst.XTestFakeKeyEvent(handle, keycode, 1, 0):
return False
pressed = True
self.lib.XSync(handle, 0)
if not self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0):
return False
pressed = False
self.lib.XSync(handle, 0)
finally:
if pressed:
self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0)
self.lib.XSync(handle, 0)
return True
def _character_keysym(character):
keysym = X11_SPECIAL_KEYSYMS.get(character)
if keysym is not None:
return keysym
codepoint = ord(character)
return codepoint if codepoint < 256 else UNICODE_KEYSYM_FLAG | codepoint
def _log_capacity_exhausted():
try:
sys.stderr.write('droiddeck-text-input: not enough empty keycodes for this frame\n')
sys.stderr.flush()
except OSError:
pass
def _property_bytes(data, actual_format, items):
if actual_format == 8:
return ctypes.string_at(data, items)
if actual_format == 32:
# Xlib exposes format-32 property items as native longs, including on 64-bit systems.
words = ctypes.cast(data, ctypes.POINTER(ctypes.c_ulong))
return b''.join(struct.pack('<I', words[index] & 0xffffffff)
for index in range(items))
return None
def _recv_exact(connection, count):
chunks = []
remaining = count
while remaining > 0:
try:
chunk = connection.recv(remaining)
except OSError:
return None
if not chunk:
return None
chunks.append(chunk)
remaining -= len(chunk)
return b''.join(chunks)
def read_request(connection):
header = _recv_exact(connection, 4)
if header is None:
return None
raw = struct.unpack('>I', header)[0]
cancellable = bool(raw & CANCELLABLE)
length = raw & ~CANCELLABLE
if length < 1 or length > MAX_TEXT:
return None
body = _recv_exact(connection, length)
if body is None:
return None
if b'\0' in body:
return None
try:
return body.decode('utf-8'), cancellable
except UnicodeDecodeError:
return None
def answer(connection, accepted):
try:
connection.sendall(b'\x01' if accepted else b'\x00')
connection.shutdown(socket.SHUT_WR)
except OSError:
return
# Drain unread bytes so close() does not reset the connection after the ACK.
try:
connection.settimeout(0.2)
while connection.recv(4096):
pass
except OSError:
pass
def _cancellation_probe(connection):
"""Return a predicate that is true once the peer has cancelled a flagged frame.
After the full frame has been read, any readable event (POLLIN/POLLHUP/POLLERR)
means extra data, half-close or reset - all of which are cancellation for a
cancellable client.
"""
poller = select.poll()
poller.register(connection, select.POLLIN)
return lambda: bool(poller.poll(0))
def deliver(bridge, text, cancelled=None):
if cancelled is not None and cancelled():
return False
target = bridge.target_display()
if target is None:
return False
state = bridge.state(target)
if state is None:
return False
return bridge.type_text(state, text, cancelled)
def serve_connection(connection, bridge):
connection.settimeout(CLIENT_TIMEOUT)
request = read_request(connection)
accepted = False
if request is not None:
text, cancellable = request
cancelled = _cancellation_probe(connection) if cancellable else None
try:
accepted = deliver(bridge, text, cancelled)
except Exception:
accepted = False
answer(connection, accepted)
def _identity(path):
try:
info = os.stat(path)
except OSError:
return None
return info.st_dev, info.st_ino
def _release(path, owned):
if owned is None:
return
try:
info = os.lstat(path)
except OSError:
return
if stat.S_ISSOCK(info.st_mode) and (info.st_dev, info.st_ino) == owned:
try:
os.unlink(path)
except OSError:
pass
def serve(path, bridge):
if not _remove_stale(path):
print("droiddeck-text-input: refusing to replace %s" % path, file=sys.stderr)
return 1
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
owned = None
try:
server.bind(path)
os.chmod(path, 0o600)
server.listen(8)
server.setblocking(False)
owned = _identity(path)
while not _STOP:
try:
ready, _, _ = select.select([server], [], [], 0.25)
except OSError:
break
if not ready:
continue
try:
connection, _ = server.accept()
except OSError:
if _STOP:
break
continue
try:
serve_connection(connection, bridge)
finally:
connection.close()
finally:
server.close()
_release(path, owned)
return 0
def _remove_stale(path):
try:
info = os.lstat(path)
except FileNotFoundError:
return True
except OSError:
return False
if not stat.S_ISSOCK(info.st_mode):
return False
probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
probe.settimeout(PROBE_TIMEOUT)
probe.connect(path)
except OSError as error:
if error.errno == errno.ENOENT:
return True
if error.errno != errno.ECONNREFUSED:
return False
else:
return False
finally:
probe.close()
_release(path, (info.st_dev, info.st_ino))
return True
def _stop(signum, frame):
global _STOP
_STOP = True
def _adopt_parent_death():
parent = os.getppid()
try:
libc = ctypes.CDLL(None, use_errno=True)
libc.prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong,
ctypes.c_ulong]
libc.prctl.restype = ctypes.c_int
libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0)
except (OSError, AttributeError):
return True
return os.getppid() == parent and parent > 1
def main(argv):
if len(argv) != 2 or not argv[1]:
return 2
if not _adopt_parent_death():
return 0
os.umask(0o077)
for name in ('SIGTERM', 'SIGINT', 'SIGHUP'):
signal.signal(getattr(signal, name), _stop)
bridge = XBridge()
try:
return serve(argv[1], bridge)
finally:
bridge.close()
if __name__ == '__main__':
sys.exit(main(sys.argv))
+1 -1
View File
@@ -3,7 +3,7 @@ FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get install -y binutils gcc g++ libvulkan-dev python3 zstd unzip \
&& apt-get install -y binutils gcc g++ libvulkan-dev python3 zstd unzip rpm2cpio cpio \
&& if [ "$(uname -m)" = aarch64 ]; then \
for tool in gcc g++ strip readelf objdump ar; do ln -s "$(command -v $tool)" /usr/local/bin/aarch64-linux-gnu-$tool; done; \
else \
+2
View File
@@ -661,12 +661,14 @@ pid_t fork(void) {
}
ddh_prepare();
pid_t forker = (pid_t)syscall(SYS_gettid);
pid_t forking = (pid_t)syscall(SYS_getpid);
pid_t pid = orig_fork();
if (pid == 0) {
kept_forked();
kept_close_forked();
ddh_drop_worker_binder();
ddh_forked(forker);
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
} else if (pid > 0) {
ddh_child_created(pid, 1);
}
+189 -2
View File
@@ -878,6 +878,9 @@ static void ddh_apply_inherited(void) {
}
}
static void ddh_open_parents(void);
static void ddh_record_own_parent(void);
__attribute__((constructor)) static void ddh_init(void) {
ddh_apply_inherited();
ddh_find_worker_binder();
@@ -885,6 +888,9 @@ __attribute__((constructor)) static void ddh_init(void) {
ddh_find_parent_table();
// tests only: as when the table could not be made here, and the first fork makes it
if (!getenv("DDH_TEST_LATE_TABLE")) ddh_prepare();
ddh_open_parents();
ddh_record_own_parent();
ddnatv_manage_sigchld();
}
static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) {
@@ -1274,6 +1280,30 @@ static int ddh_job_control_job(void) {
return ddh_waiter(parent) && (pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent);
}
// Whether this is a program a desktop launcher starts for the user (DD_HANDOFF_LAUNCHERS names the
// launchers: Plasma's shell, KRunner, Dolphin): a plain fork and exec, still in the launcher's process
// group and session, with no controlling terminal. Those launchers are Qt programs, which wait with
// waitpid() once they have no pidfds (privileged.c), so the program's exit reaches them. A child the
// launcher set up as a terminal's (a session and a terminal of its own) stays its own child.
static int ddh_launched(const char *filename, char *const argv[], char *const envp[]) {
const char *list = ddh_env(envp, "DD_HANDOFF_LAUNCHERS");
if (!list || !*list || ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv)) return 0;
pid_t parent = (pid_t)syscall(SYS_getppid);
char path[48], name[32];
snprintf(path, sizeof(path), "/proc/%d/comm", (int)parent);
if (ddh_read_proc(path, name, sizeof(name)) <= 0) return 0;
name[strcspn(name, "\n")] = 0;
if (!ddh_listed(list, name, NULL)) return 0;
if ((pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent) ||
(pid_t)syscall(SYS_getsid, 0) != (pid_t)syscall(SYS_getsid, parent))
return 0;
// /dev/tty opens only for a process with a controlling terminal
int tty = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/dev/tty",
O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC, 0, 0, 0);
if (tty >= 0) syscall(SYS_close, tty);
return tty < 0;
}
static int ddh_pressed(const char *filename, char *const argv[], char *const envp[]) {
if (ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv) || !ddh_waiter((pid_t)syscall(SYS_getppid))) return 0;
// Not a job in the foreground of its controlling terminal: a handed-off program has none (the
@@ -1302,7 +1332,11 @@ static void ddh_debug(char *const envp[], const char *what, const char *filename
struct ddh_buf b = {line, 0, sizeof(line) - 1};
ddh_puts(&b, "ddnatv handoff: ");
ddh_putint(&b, getpid());
ddh_puts(&b, " ");
ddh_puts(&b, " (parent ");
ddh_putint(&b, (long)syscall(SYS_getppid));
ddh_puts(&b, ", session ");
ddh_putint(&b, (long)syscall(SYS_getsid, 0));
ddh_puts(&b, ") ");
ddh_puts(&b, what);
ddh_puts(&b, " ");
ddh_puts(&b, filename ? filename : "?");
@@ -1364,7 +1398,8 @@ static void ddh_try_as(const char *filename, char *const argv[], char *const env
ddh_debug(envp, "a job-control job:", filename);
return;
}
if (!ddh_program_listed(list, match_file, match_argv) && !ddh_pressed(match_file, match_argv, envp)) {
if (!ddh_program_listed(list, match_file, match_argv) && !ddh_launched(match_file, match_argv, envp) &&
!ddh_pressed(match_file, match_argv, envp)) {
ddh_debug(envp, "not listed:", filename);
return;
}
@@ -1644,6 +1679,158 @@ static int32_t ddh_gen_of(const struct ddh_entry *e, pid_t child) {
return (st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->child == child ? gen : 0;
}
// ---- children no wait will come for ------------------------------------------------------------
//
// Every session process is a child subreaper (tools/linuxfs/preload/subreaper.c): a process whose
// parent exits goes to its nearest ancestor in the session, not to init, which some vendor kernels
// kill. Most programs never wait for a child they did not fork, so what they adopt stays a zombie (the
// grandchildren of Qt's startDetached() under Plasma's shell, KWin and kaccess). Each process records
// here, at its pid, the parent that started it and its own start time (DD_PARENTS, one file for the
// session): a zombie whose record names another parent was adopted.
static uint64_t *g_ddh_parents;
static void ddh_open_parents(void) {
const char *name = getenv("DD_PARENTS");
if (!name || !*name || __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE)) return;
char path[PATH_MAX];
const char *real = rewrite_path(name, path, sizeof(path));
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real,
O_RDWR | O_CREAT | O_CLOEXEC, 0600, 0, 0);
if (fd < 0) return;
size_t size = (size_t)DDH_FORKS * sizeof(uint64_t);
struct stat st;
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size < size)
call_orig_syscall(SYS_ftruncate, (unsigned long)fd, size, 0, 0, 0, 0);
// past the file's end a page would fault (SIGBUS): mapped only once the file has its size
void *map = MAP_FAILED;
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size >= size)
map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
syscall(SYS_close, fd);
if (map == MAP_FAILED) return;
uint64_t *none = NULL;
if (!__atomic_compare_exchange_n(&g_ddh_parents, &none, (uint64_t *)map, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE))
munmap(map, size);
}
static uint64_t ddh_parent_record(pid_t parent, long start) { return (uint64_t)(uint32_t)parent << 32 | (uint32_t)start; }
static void ddh_record_parent(pid_t me, pid_t parent) {
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
if (!map || me <= 0) return;
int saved = errno;
long start = ddh_start_time(me);
errno = saved;
if (start > 0) __atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record(parent, start), __ATOMIC_RELEASE);
}
// At a program's start, unless its fork recorded it: the child of a vfork(), of glibc's own
// posix_spawn() (popen(), system()) or of a raw clone() records the parent it has now, which is
// still the one that started it (a vfork()'s waits for the exec).
static void ddh_record_own_parent(void) {
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
if (!map) return;
pid_t me = (pid_t)syscall(SYS_getpid);
int saved = errno;
long start = ddh_start_time(me);
errno = saved;
if (start <= 0) return;
uint64_t r = __atomic_load_n(&map[(uint32_t)me % DDH_FORKS], __ATOMIC_ACQUIRE);
if ((uint32_t)r == (uint32_t)start && r >> 32) return;
__atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record((pid_t)syscall(SYS_getppid), start), __ATOMIC_RELEASE);
}
// /proc/PID/stat's state and start time, from a signal handler: 0 when it cannot be read.
static int ddh_proc_state(pid_t pid, char *state, long *start, pid_t *ppid) {
char path[48] = "/proc/", digits[16], stat[512];
int n = 0, len = 6;
for (unsigned int v = (unsigned int)pid; v || !n; v /= 10) digits[n++] = (char)('0' + v % 10);
while (n) path[len++] = digits[--n];
memcpy(path + len, "/stat", 6);
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0);
if (fd < 0) return 0;
long got = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)stat, sizeof(stat) - 1, 0, 0, 0);
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
if (got <= 0) return 0;
stat[got] = 0;
char *p = strrchr(stat, ')');
if (!p || p[1] != ' ' || !p[2]) return 0;
*state = p[2];
// ") S PPID": field 4; starttime is field 22
long parent = 0;
for (const char *q = p + 4; *q >= '0' && *q <= '9'; q++) parent = parent * 10 + (*q - '0');
*ppid = (pid_t)parent;
for (int field = 2; p && field < 22; field++) p = strchr(p + 1, ' ');
long t = 0;
for (const char *q = p ? p + 1 : ""; *q >= '0' && *q <= '9'; q++) t = t * 10 + (*q - '0');
*start = t;
return 1;
}
// Reaps child if no wait will come for it: the forked child of a handed-off program (its program's
// exit stays in the table for the program's own waits, as when a wait reaps it), or a child this
// process adopted. 1 when it did.
static int ddh_reap_unwaited(pid_t me, pid_t child) {
char state = 0;
long start = 0;
pid_t ppid = 0;
if (!ddh_proc_state(child, &state, &start, &ppid) || state != 'Z' || ppid != me) return 0;
struct ddh_entry *e = ddh_find(child);
int32_t gen = e ? ddh_gen_of(e, child) : 0;
if (gen) {
if (ddh_reaped(e) || call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) != child) return 0;
ddh_mark_reaped(e, gen);
return 1;
}
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
uint64_t r = map ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0;
if (!r || (uint32_t)r != (uint32_t)start || (pid_t)(r >> 32) == me || !(r >> 32)) return 0;
return call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) == child;
}
// From the SIGCHLD handler (signals.c): the zombies among this process's children that no wait will
// come for. The kernel names one zombie at a time; past one the program will reap itself, /proc.
static void ddh_reap_unclaimed(void) {
if (!__atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE) && !__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return;
int saved = errno;
pid_t me = (pid_t)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0);
// past 64 reaped this way, the rest from /proc too
int scan = 1;
for (int i = 0; i < 64; i++) {
siginfo_t si;
memset(&si, 0, sizeof(si));
if (call_orig_syscall(SYS_waitid, P_ALL, 0, (unsigned long)&si, WEXITED | WNOHANG | WNOWAIT, 0, 0) != 0 || si.si_pid <= 0) {
scan = 0;
break;
}
if (!ddh_reap_unwaited(me, si.si_pid)) {
break;
}
}
int dir = scan ? (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc",
O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0) : -1;
char buf[2048];
while (dir >= 0) {
long n = call_orig_syscall(SYS_getdents64, (unsigned long)dir, (unsigned long)buf, sizeof(buf), 0, 0, 0);
if (n <= 0) break;
for (long off = 0; off < n;) {
struct ddh_reap_dirent {
uint64_t ino;
int64_t off;
unsigned short reclen;
unsigned char type;
char name[];
} *d = (struct ddh_reap_dirent *)(buf + off);
off += d->reclen;
long pid = 0;
const char *c = d->name;
for (; *c >= '0' && *c <= '9'; c++) pid = pid * 10 + (*c - '0');
if (!*c && pid > 0 && pid != me) ddh_reap_unwaited(me, (pid_t)pid);
}
}
if (dir >= 0) call_orig_syscall(SYS_close, (unsigned long)dir, 0, 0, 0, 0, 0);
errno = saved;
}
// Takes e's exit for one waiter (EXITED to TAKEN): 0 when another waiter has it.
static int ddh_take(struct ddh_entry *e) {
int expected = DDH_EXITED;
+84
View File
@@ -174,10 +174,83 @@ __attribute__((constructor(101))) static void install_sigsys_handler(void) {
real_sig(SIGSYS, &sa, NULL);
}
// SIGCHLD in a session with a parents file (handoff.c, DD_PARENTS): the program's action as it set it
// runs from ddnatv_sigchld_handler(), which then reaps the children no wait will come for
// (ddh_reap_unclaimed()). sigaction() shows the program its own action. A program that leaves SIGCHLD
// alone gets the handler only when DD_REAP_ADOPTED names it: with a handler, poll(), sleep() and the
// like return EINTR when a child exits, which a program that never had one may not expect.
static struct sigaction g_app_sigchld;
static int g_sigchld_managed;
static int g_sigchld_on_default;
static void ddh_reap_unclaimed(void);
static int ddh_listed(const char *list, const char *name, char *const argv[]);
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *));
static void ddnatv_sigchld_handler(int sig, siginfo_t *info, void *ctx) {
struct sigaction app = g_app_sigchld;
if (app.sa_handler != SIG_DFL && app.sa_handler != SIG_IGN) {
if (app.sa_flags & SA_RESETHAND) {
// as the kernel would: the default from now on, with the handler only for a named program
g_app_sigchld.sa_handler = SIG_DFL;
g_app_sigchld.sa_flags &= ~(SA_SIGINFO | SA_RESETHAND);
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
int saved = errno;
if (real_sig) ddnatv_apply_sigchld(real_sig);
errno = saved;
}
if (app.sa_flags & SA_SIGINFO) app.sa_sigaction(sig, info, ctx);
else app.sa_handler(sig);
}
ddh_reap_unclaimed();
}
// Puts g_app_sigchld into effect: as it is where the kernel reaps every child itself (SIG_IGN,
// SA_NOCLDWAIT) or the program wants no handler and is not named, else through the handler above.
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *)) {
const struct sigaction *app = &g_app_sigchld;
int handler = app->sa_handler != SIG_DFL && app->sa_handler != SIG_IGN;
if (app->sa_handler == SIG_IGN || (app->sa_flags & SA_NOCLDWAIT) || (!handler && !g_sigchld_on_default))
return real_sig(SIGCHLD, app, NULL);
struct sigaction k;
memset(&k, 0, sizeof(k));
k.sa_sigaction = ddnatv_sigchld_handler;
k.sa_mask = app->sa_mask;
k.sa_flags = SA_SIGINFO | (handler ? (app->sa_flags & ~(SA_SIGINFO | SA_RESETHAND)) : (SA_RESTART | SA_NOCLDSTOP));
return real_sig(SIGCHLD, &k, NULL);
}
static int ddnatv_sigchld_action(int (*real_sig)(int, const struct sigaction *, struct sigaction *),
const struct sigaction *act, struct sigaction *oldact) {
struct sigaction prev = g_app_sigchld;
if (act) {
g_app_sigchld = *act;
if (ddnatv_apply_sigchld(real_sig) != 0) {
int err = errno;
g_app_sigchld = prev;
errno = err;
return -1;
}
}
if (oldact) *oldact = prev;
return 0;
}
// From the hook's start (handoff.c), once the parents file is open
static void ddnatv_manage_sigchld(void) {
if (!getenv("DD_PARENTS")) return;
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (!real_sig || real_sig(SIGCHLD, NULL, &g_app_sigchld) != 0) return;
const char *named = getenv("DD_REAP_ADOPTED");
g_sigchld_on_default = named && ddh_listed(named, program_invocation_short_name, NULL);
if (ddnatv_apply_sigchld(real_sig) == 0) g_sigchld_managed = 1;
}
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) {
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (!real_sig) return -1;
if (signum == SIGCHLD && g_sigchld_managed) return ddnatv_sigchld_action(real_sig, act, oldact);
if (signum == SIGSYS) {
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
return real_sig(signum, act, oldact);
@@ -192,6 +265,7 @@ int rt_sigaction(int signum, const struct sigaction *act, struct sigaction *olda
static int (*orig_rt_sigaction)(int, const struct sigaction *, struct sigaction *, size_t) = NULL;
if (!orig_rt_sigaction) orig_rt_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *, size_t))dlsym(RTLD_NEXT, "rt_sigaction");
if (signum == SIGCHLD && g_sigchld_managed) return sigaction(signum, act, oldact);
if (signum == SIGSYS) {
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
return orig_rt_sigaction ? orig_rt_sigaction(signum, act, oldact, sigsetsize) : 0;
@@ -210,6 +284,16 @@ typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler) {
static sighandler_t (*orig_signal)(int, sighandler_t) = NULL;
if (!orig_signal) orig_signal = (sighandler_t (*)(int, sighandler_t))dlsym(RTLD_NEXT, "signal");
if (signum == SIGCHLD && g_sigchld_managed) {
// glibc's signal(): BSD semantics
struct sigaction act, old;
memset(&act, 0, sizeof(act));
act.sa_handler = handler;
act.sa_flags = SA_RESTART;
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask, SIGCHLD);
return sigaction(SIGCHLD, &act, &old) == 0 ? old.sa_handler : SIG_ERR;
}
if (signum == SIGSYS) {
struct sigaction act, old;
memset(&act, 0, sizeof(act));
+110 -6
View File
@@ -10,6 +10,7 @@ import argparse
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import struct
@@ -49,8 +50,14 @@ LOCAL_ANDROID_SOURCES = {'app/src/main/cpp/CMakeLists.txt',
'app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c',
'app/src/main/cpp/waylandcomp/src/spatialpose.c',
'app/src/main/cpp/waylandcomp/CMakeLists.txt'}
LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr'}
LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-session',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input'}
IME_SOURCES = {'tools/ime/packages.json', 'tools/ime/prepare.py', 'tools/ime/smoke.py'}
IME_MANIFEST = 'usr/local/share/droiddeck/ime-files.json'
IME_PACKAGES = 'build/windows-setup/ime-packages'
VR_PREFIX = 'assets/linuxfs/usr/local/lib/droiddeck-vr/'
CHECK_PATHS = list(dict.fromkeys(runtime.SOURCE_PATHS + [
'app/src/main/cpp', 'app/src/main/jniLibs', 'app/src/main/rust/stores', 'tools/vr']))
@@ -82,20 +89,23 @@ def check_sources():
if git('merge-tree', '--write-tree', DONOR_PR_SOURCE, DONOR_MAIN_SOURCE).decode().splitlines()[0] != DONOR_TREE:
raise ValueError('The donor CI merge does not match the audited source tree')
helper_sources = {path.relative_to(ROOT).as_posix() for path in source_assets()}
reviewed = LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | (LOCAL_SESSION_HELPERS & helper_sources)
reviewed = (LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | IME_SOURCES |
(LOCAL_SESSION_HELPERS & helper_sources))
unexpected = {p for p in changed(AUDITED_SOURCE, 'HEAD') - reviewed if not vr_build.is_source(p)}
if unexpected:
raise ValueError('Sources changed since the component audit:\n' + '\n'.join(sorted(unexpected)))
local = changed('HEAD')
untracked = set(filter(None, git('ls-files', '--others', '--exclude-standard', '-z',
'--', *CHECK_PATHS).decode().split('\0')))
unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES)
unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES - IME_SOURCES)
if not vr_build.is_source(p)}
if unexpected:
raise ValueError('Unreviewed runtime/native/Rust changes:\n' + '\n'.join(sorted(unexpected)))
classifications = {}
for path in sorted(changed(DONOR_TREE, 'HEAD') | local | untracked):
if vr_build.is_source(path):
if path in IME_SOURCES:
action = 'regenerated from checksum-pinned RPMs; never reused from donor'
elif vr_build.is_source(path):
action = 'VR component rebuilt from current source and verified; never imported from donor'
elif path in LOCAL_ANDROID_SOURCES:
action = 'Android native source compiled by Gradle; not imported from donor'
@@ -161,6 +171,92 @@ def read_gamescope(path):
return files, pins
def find_docker():
docker = shutil.which('docker')
if docker:
return docker
desktop = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Docker/Docker/resources/bin/docker.exe'
if desktop.is_file():
return str(desktop)
raise ValueError('Docker is required to prepare IME files on Windows; install Docker Desktop or add docker to PATH')
def prepare_ime(image):
workspace = ROOT / 'build/windows-setup'
workspace.mkdir(parents=True, exist_ok=True)
packages = ROOT / IME_PACKAGES
packages.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='droiddeck-ime-', dir=workspace) as folder:
temporary = Path(folder)
linuxfs = temporary / 'linuxfs'
linuxfs.mkdir()
script = ROOT / 'tools/ime/prepare.py'
if sys.platform == 'win32':
docker = find_docker()
inspect_cmd = [docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image]
inspected = subprocess.run(inspect_cmd, capture_output=True, text=True, check=False)
fields = inspected.stdout.strip().split() if inspected.returncode == 0 else []
image_id = fields[0] if len(fields) == 2 and fields[0] and fields[1] == 'linux/amd64' else ''
if not image_id and image == vr_build.IMAGE:
dockerfile = (ROOT / 'tools/local-cross.Dockerfile').read_bytes().replace(b'\r\n', b'\n')
try:
subprocess.run([docker, 'build', '--platform', 'linux/amd64', '--tag', image,
'--file', '-', str(temporary)], input=dockerfile, check=True)
except subprocess.CalledProcessError as error:
raise ValueError('IME preparation failed to build default compiler Docker image ' + image +
'; inspect the Docker build output above, resolve the build error, and rerun preparation') from error
inspected = subprocess.run(inspect_cmd, capture_output=True, text=True, check=False)
fields = inspected.stdout.strip().split() if inspected.returncode == 0 else []
image_id = fields[0] if len(fields) == 2 and fields[0] and fields[1] == 'linux/amd64' else ''
if not image_id:
detail = inspected.stdout.strip() if inspected.returncode == 0 else inspected.stderr.strip()
detail = detail or 'no image id or platform returned'
raise ValueError('IME preparation requires the existing Docker image ' + image +
' for linux/amd64; build or load it first (inspect result: ' + detail + ')')
snapshot = temporary / 'src'
(snapshot / 'tools/ime').mkdir(parents=True)
shutil.copy2(script, snapshot / 'tools/ime/prepare.py')
shutil.copy2(ROOT / 'tools/ime/packages.json', snapshot / 'tools/ime/packages.json')
command = [docker, 'run', '--rm', '--platform', 'linux/amd64',
'-v', str(snapshot) + ':/src:ro',
'-v', str(packages) + ':/cache',
'-v', str(linuxfs) + ':/out',
image_id, 'sh', '-c',
'for tool in rpm2cpio cpio; do command -v "$tool" >/dev/null 2>&1 || { '
'echo "missing $tool; rebuild compiler image using tools/local-cross.Dockerfile" >&2; exit 1; }; done; '
'exec python3 /src/tools/ime/prepare.py --packages /cache --download --output /out']
else:
command = [sys.executable, str(script), '--packages', str(packages), '--download',
'--output', str(linuxfs)]
try:
subprocess.run(command, check=True)
except subprocess.CalledProcessError as error:
if sys.platform == 'win32':
raise ValueError('IME preparation failed; ensure Docker is running and image ' + image +
' is available') from error
raise
manifest_path = linuxfs / IME_MANIFEST
if not manifest_path.is_file():
raise ValueError('IME preparation did not produce ' + IME_MANIFEST)
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
if manifest.get('version') != 1 or not isinstance(manifest.get('files'), dict):
raise ValueError('Unexpected IME manifest format')
files = {}
for relative, entry in sorted(manifest['files'].items()):
if not isinstance(entry, dict):
raise ValueError('Unexpected IME manifest entry: ' + str(relative))
validate_relative(relative)
path = linuxfs / relative
if not path.is_file():
raise ValueError('IME manifest references a missing file: ' + relative)
data = path.read_bytes()
if hashlib.sha256(data).hexdigest() != entry.get('sha256'):
raise ValueError('IME file checksum mismatch: ' + relative)
files[relative] = data
files[IME_MANIFEST] = manifest_path.read_bytes()
return files, manifest
def validate_rebuilt(path, machine):
data = path.read_bytes()
if len(data) < 20 or data[:4] != b'\x7fELF' or data[5] != 1 or struct.unpack('<H', data[18:20])[0] != machine:
@@ -212,6 +308,7 @@ def prepare(apk, rebuilt_dir, gamescope, llvm_strip=None, rebuilt_vr=None, vk_in
vr_files, vr_manifest = vr_build.build(ROOT / 'build/windows-setup/vr', vk_include, root=ROOT, image=vr_image)
else:
vr_files, vr_manifest = vr_build.validate(rebuilt_vr, vk_include, root=ROOT)
ime_files, ime_manifest = prepare_ime(vr_image)
helpers = source_assets()
helper_assets = set(helpers.values())
plan = {}
@@ -257,6 +354,11 @@ def prepare(apk, rebuilt_dir, gamescope, llvm_strip=None, rebuilt_vr=None, vk_in
checked_output(target)
plan[target] = data
origins[target] = 'VR rebuilt from current source; source and output checksums verified'
for name, data in ime_files.items():
target = 'app/src/main/assets/linuxfs/' + name
checked_output(target)
plan[target] = data
origins[target] = 'regenerated from checksum-pinned RPMs; never reused from donor'
expected = set(plan) | {'app/src/main/' + name for name in helper_assets}
for tree in ('linuxfs', 'directaudio', 'droiddeck-esync'):
base = ROOT / 'app/src/main/assets' / tree
@@ -293,6 +395,7 @@ def prepare(apk, rebuilt_dir, gamescope, llvm_strip=None, rebuilt_vr=None, vk_in
'archive_sha256': pins['GAMESCOPE_SHA256']},
'tracked_files_verified': tracked,
'vr_build': vr_manifest,
'ime_build': ime_manifest,
'outputs': {name: {'origin': origins[name], 'sha256': hashlib.sha256(data).hexdigest()}
for name, data in sorted(plan.items())},
'preload_sources': {path.relative_to(ROOT).as_posix(): runtime.digest(path)
@@ -318,7 +421,8 @@ def main():
'AppData/Local/Android/Sdk/ndk/27.3.13750724/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-strip.exe')
parser.add_argument('--rebuilt-vr', type=Path, help='Reuse a VR build with vr-build.json; default rebuilds in Docker')
parser.add_argument('--vk-include', type=Path, help='NDK Vulkan headers; defaults to the sysroot beside --llvm-strip')
parser.add_argument('--vr-image', default=vr_build.IMAGE, help='Docker compiler image for a fresh VR build')
parser.add_argument('--vr-image', default=vr_build.IMAGE,
help='Docker compiler image for VR/IME preparation; default is built if missing')
parser.add_argument('--check-sources', action='store_true', help='Audit source differences without extracting files')
args = parser.parse_args()
zstd = ROOT / 'build/windows-setup/tools/zstd/zstd.exe'
+5 -1
View File
@@ -27,7 +27,7 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
'tools/ime', 'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
'tools/gpuload', 'app/src/main/resources/rockstar/legacy-cipher.bin',
@@ -130,6 +130,10 @@ def required():
['xodus-cli', 'xodus-service', 'version', 'backend.lock.json', 'runtime.lock.json', 'LICENSE.xodus', 'LICENSE.nexus', 'LICENSE.LGPL-2.1', 'LICENSE.nghttp2',
'windows/xgameruntime.dll', 'windows/winhttp.dll', 'windows/windows.web.dll', 'windows/twinapi.appcore.dll', 'windows/libnghttp2.dll',
'compat/PlayFabGameSave.dll', 'LICENSE.runtime-compat']]
paths += ['assets/linuxfs/' + name for name in
['usr/local/share/droiddeck/ime-files.json', 'usr/local/share/droiddeck/ibus.profile',
'usr/local/lib/droiddeck-ime/ibus-engine-pinyin', 'usr/local/lib/droiddeck-ime/libpyzy-1.0.so.0',
'usr/local/lib/droiddeck-ime/liblua-5.4.so', 'usr/share/pyzy/db/android.db']]
for driver in ['linux-wine11', 'linux-wine11-systhread']:
paths += ['assets/directaudio/' + driver + '/' + name for name in
['aarch64-unix/winedirectaudio.so', 'aarch64-windows/winedirectaudio.drv',
+1 -1
View File
@@ -28,7 +28,7 @@ else
python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \
"$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \
"$P.pairingguide=$pkg.pairingguide" "$P.devicecode=$pkg.devicecode" "$P.pin=$pkg.pin" \
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" "$P.agentchat=$pkg.agentchat" \
"$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" "$P.keeptop=$pkg.keeptop" \
"$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
fi
+66
View File
@@ -191,6 +191,72 @@ class PrefixFromProton(unittest.TestCase):
self.assertIn('export WINE_NEW_NDIS=${WINE_NEW_NDIS:-1}', LAUNCH.read_text())
class ProgramDrive(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
base = Path(self.tmp.name)
self.compat = base / 'compatdata/2489251740'
self.drives = self.compat / 'pfx/dosdevices'
self.drives.mkdir(parents=True)
os.symlink('../drive_c', self.drives / 'c:')
os.symlink('/', self.drives / 'z:')
self.storage = base / 'storage/emulated/0'
self.game = self.storage / 'Windows Games/PG Scene Viewer'
self.game.mkdir(parents=True)
self.bin = base / 'bin'
self.bin.mkdir()
ls = self.bin / 'ls'
ls.write_text('#!/bin/sh\nfor a; do case "$a" in -*) continue ;; esac\n'
' case "$a/" in "$OPENS"/*) ;; *) exit 1 ;; esac; done\nexec %s "$@"\n' % shutil.which('ls'))
ls.chmod(0o755)
def run_drive(self, exe, opens):
text = LAUNCH.read_text()
function = text[text.index('program_drive() {'):text.index('\nprepare_prefix() {')]
env = dict(os.environ, COMPAT=str(self.compat), EXE=str(exe), OPENS=str(opens),
PATH='%s:%s' % (self.bin, os.environ['PATH']))
return subprocess.run(['sh', '-c', function + '\nprogram_drive'], env=env,
capture_output=True, text=True, check=True).stdout
def links(self):
return {p.name: os.readlink(p) for p in self.drives.iterdir()}
def test_a_program_under_folders_android_refuses_gets_a_drive_of_its_own(self):
exe = self.game / 'Party Games.exe'
out = self.run_drive(exe, self.storage)
self.assertIn('drive d: -> %s' % self.storage, out)
self.assertEqual({'c:': '../drive_c', 'z:': '/', 'd:': str(self.storage)}, self.links())
self.assertEqual('', self.run_drive(exe, self.storage))
self.assertEqual(3, len(self.links()))
def test_taken_letters_and_the_steam_drive_are_skipped(self):
for name in ('d:', 'e:', 'f:', 'g:', 'h:', 'i:', 'j:', 'k:', 'l:', 'm:', 'n:', 'o:', 'p:', 'q:', 'r:'):
os.symlink('/nonexistent/' + name[0], self.drives / name)
self.run_drive(self.game / 'Party Games.exe', self.storage)
self.assertNotIn('s:', self.links())
self.assertEqual(str(self.storage), self.links()['t:'])
def test_a_drive_that_already_holds_the_program_is_kept(self):
os.symlink(str(self.storage / 'Windows Games'), self.drives / 's:')
self.assertEqual('', self.run_drive(self.game / 'Party Games.exe', self.storage))
self.assertEqual({'c:', 'z:', 's:'}, set(self.links()))
def test_a_drive_above_the_openable_folders_does_not_count(self):
os.symlink(str(self.storage.parent), self.drives / 'e:')
self.run_drive(self.game / 'Party Games.exe', self.storage)
self.assertEqual(str(self.storage), self.links()['d:'])
def test_windows_paths_bare_names_and_an_open_root_add_no_drive(self):
self.assertEqual('', self.run_drive('D:\\Games\\game.exe', self.storage))
self.assertEqual('', self.run_drive('cmd.exe', self.storage))
self.assertEqual('', self.run_drive(self.game / 'Party Games.exe', ''))
self.assertEqual({'c:', 'z:'}, set(self.links()))
def test_the_launch_adds_it_after_the_prefix_is_ready(self):
self.assertIn('\nprepare_prefix\nprogram_drive\n', LAUNCH.read_text())
class StorePaths(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
+79
View File
@@ -75,6 +75,85 @@ class CiChecksTest(unittest.TestCase):
self.assertIn("outputs.doNotCacheIf('CI executes the test suite on every run') { true }", gradle)
self.assertIn('outputs.upToDateWhen { false }', gradle)
def test_unit_tests_switch_mirrors_only_for_robolectric_rate_limits(self):
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
script = next(step['run'] for step in steps if step.get('id') == 'unit-tests')
central = 'https://repo.maven.apache.org/maven2/'
native = f'{central}org/robolectric/nativeruntime-dist-compat/1.0.18/nativeruntime-dist-compat-1.0.18.jar'
sdk = 'https://repo1.maven.org/maven2/org/robolectric/android-all-instrumented/sdk.jar.sha512'
gradle_error = 'org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException'
get_error = f"Could not GET '{native}'. Received status code 429 from server: Too Many Requests"
mirror = '-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2'
# These two resolvers report the status and URL in opposite orders.
cases = [
('ok', 0, 0, 0, 1),
(f'Could not GET {native}. Received status code 429', 1, 0, 0, 2),
(f'Server returned HTTP response code: 429 for URL: {sdk}', 1, 9, 9, 2),
(f' Caused by: {gradle_error}: {get_error}', 1, 0, 0, 2),
(f' Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: {sdk}', 1, 0, 0, 2),
(f'Failed to get resource: GET. [HTTP HTTP/1.1 429 Too Many Requests: {native})]\n'
'java.lang.AssertionError: expected a visible window', 7, 0, 7, 1),
('AssertionError: expected 429', 7, 0, 7, 1),
(f'AssertionError: expected status code 429 for URL: {sdk}', 7, 0, 7, 1),
(f'Caused by: java.lang.AssertionError: {get_error}', 7, 0, 7, 1),
(f'Could not GET {central}other/group/lib.jar. Received status code 429', 8, 0, 8, 1),
]
for message, first, retry, expected, attempts in cases:
with self.subTest(message=message), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
gradle = root / 'gradlew'
gradle.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> calls\n'
'case "$*" in *-ProbolectricMavenMirror=*) exit "$RETRY";; esac\n'
'echo "$MESSAGE"\nexit "$FIRST"\n')
gradle.chmod(0o755)
sleep = root / 'sleep'
sleep.write_text('#!/bin/sh\necho "sleep $*" >> calls\n')
sleep.chmod(0o755)
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
NDK_VERSION='test', MESSAGE=message, FIRST=str(first), RETRY=str(retry))
result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env, capture_output=True, timeout=15)
self.assertEqual(result.returncode, expected, result.stdout)
calls = (root / 'calls').read_text().splitlines()
self.assertEqual(len(calls), attempts)
self.assertNotIn(mirror, calls[0])
if attempts == 2:
self.assertEqual(calls[1].split(), [*calls[0].split(), mirror])
def test_unit_tests_back_off_on_maven_central_rate_limits(self):
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
script = next(step['run'] for step in steps if step.get('id') == 'unit-tests')
rate_limit = (
"Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: "
"Could not GET 'https://repo.maven.apache.org/maven2/junit/junit/4.13.2/junit-4.13.2.jar'. "
"Received status code 429 from server: Too Many Requests"
)
for exit_codes, expected_status, expected_events in (
([7, 0], 0, ['gradle', 'sleep 60', 'gradle']),
([7, 9, 23, 0], 23, ['gradle', 'sleep 60', 'gradle', 'sleep 180', 'gradle']),
):
with self.subTest(exit_codes=exit_codes), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'statuses').write_text(''.join(f'{code}\n' for code in exit_codes))
gradle = root / 'gradlew'
gradle.write_text('#!/bin/sh\n'
'echo gradle >> events\n'
'echo "$*" >> gradle-args\n'
'attempt=$(wc -l < gradle-args)\n'
'status=$(sed -n "${attempt}p" statuses)\n'
'if [ "$status" != 0 ]; then echo "$MAVEN_ERROR"; fi\n'
'exit "${status:-99}"\n')
gradle.chmod(0o755)
sleep = root / 'sleep'
sleep.write_text('#!/bin/sh\necho "sleep $*" >> events\n')
sleep.chmod(0o755)
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
NDK_VERSION='test', MAVEN_ERROR=rate_limit)
result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env,
capture_output=True, text=True, timeout=15)
self.assertEqual(result.returncode, expected_status, result.stdout + result.stderr)
self.assertEqual((root / 'events').read_text().splitlines(), expected_events)
self.assertNotIn('-ProbolectricMavenMirror=', (root / 'gradle-args').read_text())
def test_unit_tests_do_not_hold_up_the_apk(self):
build = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())
for step in build['jobs']['build']['steps']:
@@ -0,0 +1,73 @@
import re
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch"
LOADER = "Source/Tools/FEXInterpreter/ELFCodeLoader.h"
MIN_GAP = 128 * 1024 * 1024
STACK = 128 * 1024 * 1024
PAGE = 4096
def lines(sign):
return [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith(sign) and not line.startswith(sign * 3)]
def reservation(top, rlimit):
top = (top + PAGE - 1) & ~(PAGE - 1)
gap = min(max(rlimit, MIN_GAP), max(top // 6 * 5, MIN_GAP)) + 256 * PAGE
return (top - gap if top > gap else 0, top)
def place(hint, low, high):
if hint < high and hint + STACK > low and low > STACK:
hint = (low - STACK) & ~(PAGE - 1)
return hint
class FexGuestStackReserveTest(unittest.TestCase):
def test_only_the_elf_loader_changes(self):
self.assertEqual([LOADER], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
def test_nothing_is_removed(self):
self.assertEqual([], lines("-"))
def test_the_reserve_starts_at_the_end_of_the_host_environment(self):
added = lines("+")
self.assertIn("uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast<uint64_t>(__builtin_frame_address(0));", added)
self.assertIn("uint64_t Gap = getrlimit(RLIMIT_STACK, &Limit) == 0 ? static_cast<uint64_t>(Limit.rlim_cur) : MinGap;", added)
self.assertIn("Gap = std::clamp(Gap, MinGap, MaxGap) + 256 * PageSize;", added)
def test_every_stack_hint_is_checked_against_the_reserve(self):
text = PATCH.read_text()
self.assertLess(text.index("HostStackReservation(PageSize);"), text.index("do {"))
self.assertLess(text.index("do {"), text.index("StackHint = (HostStackLow - FULL_STACK_SIZE)"))
self.assertLess(text.index("StackHint = (HostStackLow - FULL_STACK_SIZE)"), text.index("// Allocate the base of the full 128MB stack range."))
def test_a_guest_stack_overlapping_the_reserve_moves_below_it(self):
host_env_end = 0x7FFC391000
low, high = reservation(host_env_end, 8 * 1024 * 1024)
hint = place((1 << 39) - STACK, low, high)
self.assertLessEqual(hint + STACK, low)
self.assertGreaterEqual(host_env_end - (hint + STACK), MIN_GAP)
def test_a_guest_stack_clear_of_the_reserve_stays_put(self):
low, high = reservation(0x7FC491C000, 8 * 1024 * 1024)
hint = (1 << 39) - STACK
self.assertEqual(hint, place(hint, low, high))
def test_a_larger_stack_limit_widens_the_reserve(self):
low, _ = reservation(0x7FFC391000, 512 * 1024 * 1024)
self.assertEqual(0x7FFC391000 - 512 * 1024 * 1024 - 256 * PAGE, low)
def test_an_unlimited_stack_limit_keeps_room_for_the_guest(self):
low, _ = reservation(0x7FFC391000, (1 << 64) - 1)
self.assertGreater(low, STACK)
def test_no_comments_are_added(self):
self.assertFalse([line for line in lines("+") if line.startswith(("//", "/*"))])
if __name__ == "__main__":
unittest.main()
+134
View File
@@ -0,0 +1,134 @@
'''Regression tests for tools/ime/prepare.py RPM extraction.'''
import contextlib
import importlib.util
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import tempfile
import unittest
from unittest import mock
MODULE_PATH = Path(__file__).resolve().parents[1] / 'ime' / 'prepare.py'
SPEC = importlib.util.spec_from_file_location('ime_prepare', MODULE_PATH)
PREPARE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(PREPARE)
NUL = bytes(1)
def _newc(files):
archive = bytearray()
for inode, (name, data) in enumerate(files.items(), start=1):
encoded = name.encode('utf-8')
name_size = len(encoded) + 1
header = '070701' + ''.join(f'{value:08x}' for value in (
inode, 0o100644, 0, 0, 1, 0, len(data), 0, 0, 0, 0, name_size, 0))
archive += header.encode('ascii')
archive += encoded + NUL
archive += NUL * (-(110 + name_size) % 4)
archive += data
archive += NUL * (-len(data) % 4)
trailer = b'TRAILER!!!' + NUL
header = '070701' + ''.join(f'{value:08x}' for value in (
0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, len(trailer), 0))
archive += header.encode('ascii')
archive += trailer
archive += NUL * (-(110 + len(trailer)) % 4)
return bytes(archive)
class ExtractTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
def _write_executable(self, path, text):
path.write_text(text, encoding='utf-8')
path.chmod(0o755)
def _tools(self, base, cpio, payload=None, exit_code=1):
tools = base / 'bin'
tools.mkdir(parents=True)
fixture = base / 'payload.cpio'
if payload is None:
script = f'''#!/bin/sh
echo rpm2cpio failed >&2
exit {exit_code}
'''
else:
fixture.write_bytes(payload)
script = f'''#!/bin/sh
exec cat {shlex.quote(str(fixture))}
'''
self._write_executable(tools / 'rpm2cpio', script)
self._write_executable(tools / 'cpio', f'''#!/bin/sh
exec {shlex.quote(str(cpio))} "$@"
''')
return tools
@contextlib.contextmanager
def _path(self, tools):
with mock.patch.dict(os.environ,
{'PATH': str(tools) + os.pathsep + os.environ.get('PATH', '')}):
yield
def _cpio_candidates(self):
candidates = []
for command in ('cpio', 'bsdcpio'):
path = shutil.which(command)
if path:
candidates.append((command, Path(path)))
return candidates
def test_extract_normal_payload_with_available_cpio(self):
candidates = self._cpio_candidates()
if not candidates:
self.skipTest('no cpio implementation is available')
payload = _newc({'usr/share/demo.txt': b'hello'})
for command, cpio in candidates:
with self.subTest(cpio=command):
base = self.root / ('normal-' + command)
base.mkdir()
tools = self._tools(base, cpio, payload)
destination = base / 'destination'
with self._path(tools):
PREPARE.extract('demo', base / 'demo.rpm', destination)
self.assertEqual((destination / 'usr/share/demo.txt').read_bytes(), b'hello')
def test_extract_rejects_unsafe_paths_before_writing(self):
candidates = self._cpio_candidates()
if not candidates:
self.skipTest('no cpio implementation is available')
cpio = candidates[0][1]
for label in ('absolute', 'parent'):
with self.subTest(case=label):
base = self.root / ('unsafe-' + label)
base.mkdir()
outside = base / (label + '-escaped.txt')
name = str(outside) if label == 'absolute' else '../' + outside.name
tools = self._tools(base, cpio, _newc({'payload/safe.txt': b'safe', name: b'bad'}))
destination = base / 'destination'
with self._path(tools), self.assertRaises(ValueError) as caught:
PREPARE.extract('unsafe', base / 'unsafe.rpm', destination)
self.assertIn('unsafe path', str(caught.exception))
self.assertFalse((destination / 'payload/safe.txt').exists())
self.assertFalse(outside.exists())
def test_extract_propagates_rpm2cpio_failure(self):
candidates = self._cpio_candidates()
if not candidates:
self.skipTest('no cpio implementation is available')
base = self.root / 'failed'
base.mkdir()
tools = self._tools(base, candidates[0][1], exit_code=7)
with self._path(tools), self.assertRaises(subprocess.CalledProcessError) as caught:
PREPARE.extract('broken', base / 'broken.rpm', base / 'destination')
self.assertEqual(caught.exception.returncode, 7)
if __name__ == '__main__':
unittest.main()
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more